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-2010 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 * Since the information managed by this module is
84 * also stored by the logical address mapping module,
85 * this module may throw away valid virtual-to-physical
86 * mappings at almost any time. However, invalidations
87 * of virtual-to-physical mappings must be done as
90 * In order to cope with hardware architectures which
91 * make virtual-to-physical map invalidates expensive,
92 * this module may delay invalidate or reduced protection
93 * operations until such time as they are actually
94 * necessary. This module is given full information as
95 * to which processors are currently using which maps,
96 * and to when physical maps must be made correct.
101 #include "opt_pmap.h"
103 #include "opt_xbox.h"
105 #include <sys/param.h>
106 #include <sys/systm.h>
107 #include <sys/kernel.h>
109 #include <sys/lock.h>
110 #include <sys/malloc.h>
111 #include <sys/mman.h>
112 #include <sys/msgbuf.h>
113 #include <sys/mutex.h>
114 #include <sys/proc.h>
115 #include <sys/rwlock.h>
116 #include <sys/sf_buf.h>
118 #include <sys/vmmeter.h>
119 #include <sys/sched.h>
120 #include <sys/sysctl.h>
124 #include <sys/cpuset.h>
128 #include <vm/vm_param.h>
129 #include <vm/vm_kern.h>
130 #include <vm/vm_page.h>
131 #include <vm/vm_map.h>
132 #include <vm/vm_object.h>
133 #include <vm/vm_extern.h>
134 #include <vm/vm_pageout.h>
135 #include <vm/vm_pager.h>
136 #include <vm/vm_radix.h>
137 #include <vm/vm_reserv.h>
142 #include <machine/intr_machdep.h>
143 #include <machine/apicvar.h>
145 #include <machine/cpu.h>
146 #include <machine/cputypes.h>
147 #include <machine/md_var.h>
148 #include <machine/pcb.h>
149 #include <machine/specialreg.h>
151 #include <machine/smp.h>
155 #include <machine/xbox.h>
158 #if !defined(CPU_DISABLE_SSE) && defined(I686_CPU)
159 #define CPU_ENABLE_SSE
162 #ifndef PMAP_SHPGPERPROC
163 #define PMAP_SHPGPERPROC 200
166 #if !defined(DIAGNOSTIC)
167 #ifdef __GNUC_GNU_INLINE__
168 #define PMAP_INLINE __attribute__((__gnu_inline__)) inline
170 #define PMAP_INLINE extern inline
177 #define PV_STAT(x) do { x ; } while (0)
179 #define PV_STAT(x) do { } while (0)
182 #define pa_index(pa) ((pa) >> PDRSHIFT)
183 #define pa_to_pvh(pa) (&pv_table[pa_index(pa)])
186 * Get PDEs and PTEs for user/kernel address space
188 #define pmap_pde(m, v) (&((m)->pm_pdir[(vm_offset_t)(v) >> PDRSHIFT]))
189 #define pdir_pde(m, v) (m[(vm_offset_t)(v) >> PDRSHIFT])
191 #define pmap_pde_v(pte) ((*(int *)pte & PG_V) != 0)
192 #define pmap_pte_w(pte) ((*(int *)pte & PG_W) != 0)
193 #define pmap_pte_m(pte) ((*(int *)pte & PG_M) != 0)
194 #define pmap_pte_u(pte) ((*(int *)pte & PG_A) != 0)
195 #define pmap_pte_v(pte) ((*(int *)pte & PG_V) != 0)
197 #define pmap_pte_set_w(pte, v) ((v) ? atomic_set_int((u_int *)(pte), PG_W) : \
198 atomic_clear_int((u_int *)(pte), PG_W))
199 #define pmap_pte_set_prot(pte, v) ((*(int *)pte &= ~PG_PROT), (*(int *)pte |= (v)))
201 struct pmap kernel_pmap_store;
202 LIST_HEAD(pmaplist, pmap);
203 static struct pmaplist allpmaps;
204 static struct mtx allpmaps_lock;
206 vm_offset_t virtual_avail; /* VA of first avail page (after kernel bss) */
207 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
208 int pgeflag = 0; /* PG_G or-in */
209 int pseflag = 0; /* PG_PS or-in */
211 static int nkpt = NKPT;
212 vm_offset_t kernel_vm_end = KERNBASE + NKPT * NBPDR;
213 extern u_int32_t KERNend;
214 extern u_int32_t KPTphys;
218 static uma_zone_t pdptzone;
221 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD, 0, "VM/pmap parameters");
223 static int pat_works = 1;
224 SYSCTL_INT(_vm_pmap, OID_AUTO, pat_works, CTLFLAG_RD, &pat_works, 1,
225 "Is page attribute table fully functional?");
227 static int pg_ps_enabled = 1;
228 SYSCTL_INT(_vm_pmap, OID_AUTO, pg_ps_enabled, CTLFLAG_RDTUN, &pg_ps_enabled, 0,
229 "Are large page mappings enabled?");
231 #define PAT_INDEX_SIZE 8
232 static int pat_index[PAT_INDEX_SIZE]; /* cache mode to PAT index conversion */
234 static struct rwlock_padalign pvh_global_lock;
237 * Data for the pv entry allocation mechanism
239 static TAILQ_HEAD(pch, pv_chunk) pv_chunks = TAILQ_HEAD_INITIALIZER(pv_chunks);
240 static int pv_entry_count = 0, pv_entry_max = 0, pv_entry_high_water = 0;
241 static struct md_page *pv_table;
242 static int shpgperproc = PMAP_SHPGPERPROC;
244 struct pv_chunk *pv_chunkbase; /* KVA block for pv_chunks */
245 int pv_maxchunks; /* How many chunks we have KVA for */
246 vm_offset_t pv_vafree; /* freelist stored in the PTE */
249 * All those kernel PT submaps that BSD is so fond of
258 static struct sysmaps sysmaps_pcpu[MAXCPU];
260 static pd_entry_t *KPTD;
263 struct msgbuf *msgbufp = 0;
268 static caddr_t crashdumpmap;
270 static pt_entry_t *PMAP1 = 0, *PMAP2;
271 static pt_entry_t *PADDR1 = 0, *PADDR2;
274 static int PMAP1changedcpu;
275 SYSCTL_INT(_debug, OID_AUTO, PMAP1changedcpu, CTLFLAG_RD,
277 "Number of times pmap_pte_quick changed CPU with same PMAP1");
279 static int PMAP1changed;
280 SYSCTL_INT(_debug, OID_AUTO, PMAP1changed, CTLFLAG_RD,
282 "Number of times pmap_pte_quick changed PMAP1");
283 static int PMAP1unchanged;
284 SYSCTL_INT(_debug, OID_AUTO, PMAP1unchanged, CTLFLAG_RD,
286 "Number of times pmap_pte_quick didn't change PMAP1");
287 static struct mtx PMAP2mutex;
289 static void free_pv_chunk(struct pv_chunk *pc);
290 static void free_pv_entry(pmap_t pmap, pv_entry_t pv);
291 static pv_entry_t get_pv_entry(pmap_t pmap, boolean_t try);
292 static void pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa);
293 static boolean_t pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa);
294 static void pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa);
295 static void pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
296 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
298 static int pmap_pvh_wired_mappings(struct md_page *pvh, int count);
300 static boolean_t pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
301 static boolean_t pmap_enter_pde(pmap_t pmap, vm_offset_t va, vm_page_t m,
303 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
304 vm_page_t m, vm_prot_t prot, vm_page_t mpte);
305 static void pmap_flush_page(vm_page_t m);
306 static int pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte);
307 static void pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte);
308 static boolean_t pmap_is_modified_pvh(struct md_page *pvh);
309 static boolean_t pmap_is_referenced_pvh(struct md_page *pvh);
310 static void pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode);
311 static void pmap_kenter_pde(vm_offset_t va, pd_entry_t newpde);
312 static vm_page_t pmap_lookup_pt_page(pmap_t pmap, vm_offset_t va);
313 static void pmap_pde_attr(pd_entry_t *pde, int cache_bits);
314 static void pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
315 static boolean_t pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva,
317 static void pmap_pte_attr(pt_entry_t *pte, int cache_bits);
318 static void pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
319 struct spglist *free);
320 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva,
321 struct spglist *free);
322 static void pmap_remove_pt_page(pmap_t pmap, vm_page_t mpte);
323 static void pmap_remove_page(struct pmap *pmap, vm_offset_t va,
324 struct spglist *free);
325 static void pmap_remove_entry(struct pmap *pmap, vm_page_t m,
327 static void pmap_insert_entry(pmap_t pmap, vm_offset_t va, vm_page_t m);
328 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
330 static void pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
332 static void pmap_update_pde_invalidate(vm_offset_t va, pd_entry_t newpde);
334 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va, u_int flags);
336 static vm_page_t _pmap_allocpte(pmap_t pmap, u_int ptepindex, u_int flags);
337 static void _pmap_unwire_ptp(pmap_t pmap, vm_page_t m, struct spglist *free);
338 static pt_entry_t *pmap_pte_quick(pmap_t pmap, vm_offset_t va);
339 static void pmap_pte_release(pt_entry_t *pte);
340 static int pmap_unuse_pt(pmap_t, vm_offset_t, struct spglist *);
342 static void *pmap_pdpt_allocf(uma_zone_t zone, int bytes, u_int8_t *flags, int wait);
344 static void pmap_set_pg(void);
346 static __inline void pagezero(void *page);
348 CTASSERT(1 << PDESHIFT == sizeof(pd_entry_t));
349 CTASSERT(1 << PTESHIFT == sizeof(pt_entry_t));
352 * If you get an error here, then you set KVA_PAGES wrong! See the
353 * description of KVA_PAGES in sys/i386/include/pmap.h. It must be
354 * multiple of 4 for a normal kernel, or a multiple of 8 for a PAE.
356 CTASSERT(KERNBASE % (1 << 24) == 0);
359 * Bootstrap the system enough to run with virtual memory.
361 * On the i386 this is called after mapping has already been enabled
362 * and just syncs the pmap module with what has already been done.
363 * [We can't call it easily with mapping off since the kernel is not
364 * mapped with PA == VA, hence we would have to relocate every address
365 * from the linked base (virtual) address "KERNBASE" to the actual
366 * (physical) address starting relative to 0]
369 pmap_bootstrap(vm_paddr_t firstaddr)
372 pt_entry_t *pte, *unused;
373 struct sysmaps *sysmaps;
377 * Initialize the first available kernel virtual address. However,
378 * using "firstaddr" may waste a few pages of the kernel virtual
379 * address space, because locore may not have mapped every physical
380 * page that it allocated. Preferably, locore would provide a first
381 * unused virtual address in addition to "firstaddr".
383 virtual_avail = (vm_offset_t) KERNBASE + firstaddr;
385 virtual_end = VM_MAX_KERNEL_ADDRESS;
388 * Initialize the kernel pmap (which is statically allocated).
390 PMAP_LOCK_INIT(kernel_pmap);
391 kernel_pmap->pm_pdir = (pd_entry_t *) (KERNBASE + (u_int)IdlePTD);
393 kernel_pmap->pm_pdpt = (pdpt_entry_t *) (KERNBASE + (u_int)IdlePDPT);
395 CPU_FILL(&kernel_pmap->pm_active); /* don't allow deactivation */
396 TAILQ_INIT(&kernel_pmap->pm_pvchunk);
399 * Initialize the global pv list lock.
401 rw_init(&pvh_global_lock, "pmap pv global");
403 LIST_INIT(&allpmaps);
406 * Request a spin mutex so that changes to allpmaps cannot be
407 * preempted by smp_rendezvous_cpus(). Otherwise,
408 * pmap_update_pde_kernel() could access allpmaps while it is
411 mtx_init(&allpmaps_lock, "allpmaps", NULL, MTX_SPIN);
412 mtx_lock_spin(&allpmaps_lock);
413 LIST_INSERT_HEAD(&allpmaps, kernel_pmap, pm_list);
414 mtx_unlock_spin(&allpmaps_lock);
417 * Reserve some special page table entries/VA space for temporary
420 #define SYSMAP(c, p, v, n) \
421 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
427 * CMAP1/CMAP2 are used for zeroing and copying pages.
428 * CMAP3 is used for the idle process page zeroing.
430 for (i = 0; i < MAXCPU; i++) {
431 sysmaps = &sysmaps_pcpu[i];
432 mtx_init(&sysmaps->lock, "SYSMAPS", NULL, MTX_DEF);
433 SYSMAP(caddr_t, sysmaps->CMAP1, sysmaps->CADDR1, 1)
434 SYSMAP(caddr_t, sysmaps->CMAP2, sysmaps->CADDR2, 1)
436 SYSMAP(caddr_t, CMAP3, CADDR3, 1)
441 SYSMAP(caddr_t, unused, crashdumpmap, MAXDUMPPGS)
444 * ptvmmap is used for reading arbitrary physical pages via /dev/mem.
446 SYSMAP(caddr_t, unused, ptvmmap, 1)
449 * msgbufp is used to map the system message buffer.
451 SYSMAP(struct msgbuf *, unused, msgbufp, atop(round_page(msgbufsize)))
454 * KPTmap is used by pmap_kextract().
456 * KPTmap is first initialized by locore. However, that initial
457 * KPTmap can only support NKPT page table pages. Here, a larger
458 * KPTmap is created that can support KVA_PAGES page table pages.
460 SYSMAP(pt_entry_t *, KPTD, KPTmap, KVA_PAGES)
462 for (i = 0; i < NKPT; i++)
463 KPTD[i] = (KPTphys + (i << PAGE_SHIFT)) | pgeflag | PG_RW | PG_V;
466 * Adjust the start of the KPTD and KPTmap so that the implementation
467 * of pmap_kextract() and pmap_growkernel() can be made simpler.
470 KPTmap -= i386_btop(KPTDI << PDRSHIFT);
473 * PADDR1 and PADDR2 are used by pmap_pte_quick() and pmap_pte(),
476 SYSMAP(pt_entry_t *, PMAP1, PADDR1, 1)
477 SYSMAP(pt_entry_t *, PMAP2, PADDR2, 1)
479 mtx_init(&PMAP2mutex, "PMAP2", NULL, MTX_DEF);
484 * Leave in place an identity mapping (virt == phys) for the low 1 MB
485 * physical memory region that is used by the ACPI wakeup code. This
486 * mapping must not have PG_G set.
489 /* FIXME: This is gross, but needed for the XBOX. Since we are in such
490 * an early stadium, we cannot yet neatly map video memory ... :-(
491 * Better fixes are very welcome! */
492 if (!arch_i386_is_xbox)
494 for (i = 1; i < NKPT; i++)
497 /* Initialize the PAT MSR if present. */
500 /* Turn on PG_G on kernel page(s) */
510 int pat_table[PAT_INDEX_SIZE];
515 /* Set default PAT index table. */
516 for (i = 0; i < PAT_INDEX_SIZE; i++)
518 pat_table[PAT_WRITE_BACK] = 0;
519 pat_table[PAT_WRITE_THROUGH] = 1;
520 pat_table[PAT_UNCACHEABLE] = 3;
521 pat_table[PAT_WRITE_COMBINING] = 3;
522 pat_table[PAT_WRITE_PROTECTED] = 3;
523 pat_table[PAT_UNCACHED] = 3;
525 /* Bail if this CPU doesn't implement PAT. */
526 if ((cpu_feature & CPUID_PAT) == 0) {
527 for (i = 0; i < PAT_INDEX_SIZE; i++)
528 pat_index[i] = pat_table[i];
534 * Due to some Intel errata, we can only safely use the lower 4
537 * Intel Pentium III Processor Specification Update
538 * Errata E.27 (Upper Four PAT Entries Not Usable With Mode B
541 * Intel Pentium IV Processor Specification Update
542 * Errata N46 (PAT Index MSB May Be Calculated Incorrectly)
544 if (cpu_vendor_id == CPU_VENDOR_INTEL &&
545 !(CPUID_TO_FAMILY(cpu_id) == 6 && CPUID_TO_MODEL(cpu_id) >= 0xe))
548 /* Initialize default PAT entries. */
549 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
550 PAT_VALUE(1, PAT_WRITE_THROUGH) |
551 PAT_VALUE(2, PAT_UNCACHED) |
552 PAT_VALUE(3, PAT_UNCACHEABLE) |
553 PAT_VALUE(4, PAT_WRITE_BACK) |
554 PAT_VALUE(5, PAT_WRITE_THROUGH) |
555 PAT_VALUE(6, PAT_UNCACHED) |
556 PAT_VALUE(7, PAT_UNCACHEABLE);
560 * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
561 * Program 5 and 6 as WP and WC.
562 * Leave 4 and 7 as WB and UC.
564 pat_msr &= ~(PAT_MASK(5) | PAT_MASK(6));
565 pat_msr |= PAT_VALUE(5, PAT_WRITE_PROTECTED) |
566 PAT_VALUE(6, PAT_WRITE_COMBINING);
567 pat_table[PAT_UNCACHED] = 2;
568 pat_table[PAT_WRITE_PROTECTED] = 5;
569 pat_table[PAT_WRITE_COMBINING] = 6;
572 * Just replace PAT Index 2 with WC instead of UC-.
574 pat_msr &= ~PAT_MASK(2);
575 pat_msr |= PAT_VALUE(2, PAT_WRITE_COMBINING);
576 pat_table[PAT_WRITE_COMBINING] = 2;
581 load_cr4(cr4 & ~CR4_PGE);
583 /* Disable caches (CD = 1, NW = 0). */
585 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
587 /* Flushes caches and TLBs. */
591 /* Update PAT and index table. */
592 wrmsr(MSR_PAT, pat_msr);
593 for (i = 0; i < PAT_INDEX_SIZE; i++)
594 pat_index[i] = pat_table[i];
596 /* Flush caches and TLBs again. */
600 /* Restore caches and PGE. */
606 * Set PG_G on kernel pages. Only the BSP calls this when SMP is turned on.
612 vm_offset_t va, endva;
617 endva = KERNBASE + KERNend;
620 va = KERNBASE + KERNLOAD;
622 pdir_pde(PTD, va) |= pgeflag;
623 invltlb(); /* Play it safe, invltlb() every time */
627 va = (vm_offset_t)btext;
632 invltlb(); /* Play it safe, invltlb() every time */
639 * Initialize a vm_page's machine-dependent fields.
642 pmap_page_init(vm_page_t m)
645 TAILQ_INIT(&m->md.pv_list);
646 m->md.pat_mode = PAT_WRITE_BACK;
651 pmap_pdpt_allocf(uma_zone_t zone, int bytes, u_int8_t *flags, int wait)
654 /* Inform UMA that this allocator uses kernel_map/object. */
655 *flags = UMA_SLAB_KERNEL;
656 return ((void *)kmem_alloc_contig(kernel_arena, bytes, wait, 0x0ULL,
657 0xffffffffULL, 1, 0, VM_MEMATTR_DEFAULT));
662 * ABuse the pte nodes for unmapped kva to thread a kva freelist through.
664 * - Must deal with pages in order to ensure that none of the PG_* bits
665 * are ever set, PG_V in particular.
666 * - Assumes we can write to ptes without pte_store() atomic ops, even
667 * on PAE systems. This should be ok.
668 * - Assumes nothing will ever test these addresses for 0 to indicate
669 * no mapping instead of correctly checking PG_V.
670 * - Assumes a vm_offset_t will fit in a pte (true for i386).
671 * Because PG_V is never set, there can be no mappings to invalidate.
674 pmap_ptelist_alloc(vm_offset_t *head)
681 panic("pmap_ptelist_alloc: exhausted ptelist KVA");
685 panic("pmap_ptelist_alloc: va with PG_V set!");
691 pmap_ptelist_free(vm_offset_t *head, vm_offset_t va)
696 panic("pmap_ptelist_free: freeing va with PG_V set!");
698 *pte = *head; /* virtual! PG_V is 0 though */
703 pmap_ptelist_init(vm_offset_t *head, void *base, int npages)
709 for (i = npages - 1; i >= 0; i--) {
710 va = (vm_offset_t)base + i * PAGE_SIZE;
711 pmap_ptelist_free(head, va);
717 * Initialize the pmap module.
718 * Called by vm_init, to initialize any structures that the pmap
719 * system needs to map virtual memory.
729 * Initialize the vm page array entries for the kernel pmap's
732 for (i = 0; i < NKPT; i++) {
733 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
734 KASSERT(mpte >= vm_page_array &&
735 mpte < &vm_page_array[vm_page_array_size],
736 ("pmap_init: page table page is out of range"));
737 mpte->pindex = i + KPTDI;
738 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
742 * Initialize the address space (zone) for the pv entries. Set a
743 * high water mark so that the system can recover from excessive
744 * numbers of pv entries.
746 TUNABLE_INT_FETCH("vm.pmap.shpgperproc", &shpgperproc);
747 pv_entry_max = shpgperproc * maxproc + cnt.v_page_count;
748 TUNABLE_INT_FETCH("vm.pmap.pv_entries", &pv_entry_max);
749 pv_entry_max = roundup(pv_entry_max, _NPCPV);
750 pv_entry_high_water = 9 * (pv_entry_max / 10);
753 * If the kernel is running on a virtual machine, then it must assume
754 * that MCA is enabled by the hypervisor. Moreover, the kernel must
755 * be prepared for the hypervisor changing the vendor and family that
756 * are reported by CPUID. Consequently, the workaround for AMD Family
757 * 10h Erratum 383 is enabled if the processor's feature set does not
758 * include at least one feature that is only supported by older Intel
759 * or newer AMD processors.
761 if (vm_guest == VM_GUEST_VM && (cpu_feature & CPUID_SS) == 0 &&
762 (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
763 CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
765 workaround_erratum383 = 1;
768 * Are large page mappings supported and enabled?
770 TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
773 else if (pg_ps_enabled) {
774 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
775 ("pmap_init: can't assign to pagesizes[1]"));
776 pagesizes[1] = NBPDR;
780 * Calculate the size of the pv head table for superpages.
782 for (i = 0; phys_avail[i + 1]; i += 2);
783 pv_npg = round_4mpage(phys_avail[(i - 2) + 1]) / NBPDR;
786 * Allocate memory for the pv head table for superpages.
788 s = (vm_size_t)(pv_npg * sizeof(struct md_page));
790 pv_table = (struct md_page *)kmem_malloc(kernel_arena, s,
792 for (i = 0; i < pv_npg; i++)
793 TAILQ_INIT(&pv_table[i].pv_list);
795 pv_maxchunks = MAX(pv_entry_max / _NPCPV, maxproc);
796 pv_chunkbase = (struct pv_chunk *)kva_alloc(PAGE_SIZE * pv_maxchunks);
797 if (pv_chunkbase == NULL)
798 panic("pmap_init: not enough kvm for pv chunks");
799 pmap_ptelist_init(&pv_vafree, pv_chunkbase, pv_maxchunks);
801 pdptzone = uma_zcreate("PDPT", NPGPTD * sizeof(pdpt_entry_t), NULL,
802 NULL, NULL, NULL, (NPGPTD * sizeof(pdpt_entry_t)) - 1,
803 UMA_ZONE_VM | UMA_ZONE_NOFREE);
804 uma_zone_set_allocf(pdptzone, pmap_pdpt_allocf);
809 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_max, CTLFLAG_RD, &pv_entry_max, 0,
810 "Max number of PV entries");
811 SYSCTL_INT(_vm_pmap, OID_AUTO, shpgperproc, CTLFLAG_RD, &shpgperproc, 0,
812 "Page share factor per proc");
814 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD, 0,
815 "2/4MB page mapping counters");
817 static u_long pmap_pde_demotions;
818 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, demotions, CTLFLAG_RD,
819 &pmap_pde_demotions, 0, "2/4MB page demotions");
821 static u_long pmap_pde_mappings;
822 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
823 &pmap_pde_mappings, 0, "2/4MB page mappings");
825 static u_long pmap_pde_p_failures;
826 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
827 &pmap_pde_p_failures, 0, "2/4MB page promotion failures");
829 static u_long pmap_pde_promotions;
830 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
831 &pmap_pde_promotions, 0, "2/4MB page promotions");
833 /***************************************************
834 * Low level helper routines.....
835 ***************************************************/
838 * Determine the appropriate bits to set in a PTE or PDE for a specified
842 pmap_cache_bits(int mode, boolean_t is_pde)
844 int cache_bits, pat_flag, pat_idx;
846 if (mode < 0 || mode >= PAT_INDEX_SIZE || pat_index[mode] < 0)
847 panic("Unknown caching mode %d\n", mode);
849 /* The PAT bit is different for PTE's and PDE's. */
850 pat_flag = is_pde ? PG_PDE_PAT : PG_PTE_PAT;
852 /* Map the caching mode to a PAT index. */
853 pat_idx = pat_index[mode];
855 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
858 cache_bits |= pat_flag;
860 cache_bits |= PG_NC_PCD;
862 cache_bits |= PG_NC_PWT;
867 * The caller is responsible for maintaining TLB consistency.
870 pmap_kenter_pde(vm_offset_t va, pd_entry_t newpde)
874 boolean_t PTD_updated;
877 mtx_lock_spin(&allpmaps_lock);
878 LIST_FOREACH(pmap, &allpmaps, pm_list) {
879 if ((pmap->pm_pdir[PTDPTDI] & PG_FRAME) == (PTDpde[0] &
882 pde = pmap_pde(pmap, va);
883 pde_store(pde, newpde);
885 mtx_unlock_spin(&allpmaps_lock);
887 ("pmap_kenter_pde: current page table is not in allpmaps"));
891 * After changing the page size for the specified virtual address in the page
892 * table, flush the corresponding entries from the processor's TLB. Only the
893 * calling processor's TLB is affected.
895 * The calling thread must be pinned to a processor.
898 pmap_update_pde_invalidate(vm_offset_t va, pd_entry_t newpde)
902 if ((newpde & PG_PS) == 0)
903 /* Demotion: flush a specific 2MB page mapping. */
905 else if ((newpde & PG_G) == 0)
907 * Promotion: flush every 4KB page mapping from the TLB
908 * because there are too many to flush individually.
913 * Promotion: flush every 4KB page mapping from the TLB,
914 * including any global (PG_G) mappings.
917 load_cr4(cr4 & ~CR4_PGE);
919 * Although preemption at this point could be detrimental to
920 * performance, it would not lead to an error. PG_G is simply
921 * ignored if CR4.PGE is clear. Moreover, in case this block
922 * is re-entered, the load_cr4() either above or below will
923 * modify CR4.PGE flushing the TLB.
925 load_cr4(cr4 | CR4_PGE);
930 * For SMP, these functions have to use the IPI mechanism for coherence.
932 * N.B.: Before calling any of the following TLB invalidation functions,
933 * the calling processor must ensure that all stores updating a non-
934 * kernel page table are globally performed. Otherwise, another
935 * processor could cache an old, pre-update entry without being
936 * invalidated. This can happen one of two ways: (1) The pmap becomes
937 * active on another processor after its pm_active field is checked by
938 * one of the following functions but before a store updating the page
939 * table is globally performed. (2) The pmap becomes active on another
940 * processor before its pm_active field is checked but due to
941 * speculative loads one of the following functions stills reads the
942 * pmap as inactive on the other processor.
944 * The kernel page table is exempt because its pm_active field is
945 * immutable. The kernel page table is always active on every
949 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
955 if (pmap == kernel_pmap || !CPU_CMP(&pmap->pm_active, &all_cpus)) {
959 cpuid = PCPU_GET(cpuid);
960 other_cpus = all_cpus;
961 CPU_CLR(cpuid, &other_cpus);
962 if (CPU_ISSET(cpuid, &pmap->pm_active))
964 CPU_AND(&other_cpus, &pmap->pm_active);
965 if (!CPU_EMPTY(&other_cpus))
966 smp_masked_invlpg(other_cpus, va);
972 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
979 if (pmap == kernel_pmap || !CPU_CMP(&pmap->pm_active, &all_cpus)) {
980 for (addr = sva; addr < eva; addr += PAGE_SIZE)
982 smp_invlpg_range(sva, eva);
984 cpuid = PCPU_GET(cpuid);
985 other_cpus = all_cpus;
986 CPU_CLR(cpuid, &other_cpus);
987 if (CPU_ISSET(cpuid, &pmap->pm_active))
988 for (addr = sva; addr < eva; addr += PAGE_SIZE)
990 CPU_AND(&other_cpus, &pmap->pm_active);
991 if (!CPU_EMPTY(&other_cpus))
992 smp_masked_invlpg_range(other_cpus, sva, eva);
998 pmap_invalidate_all(pmap_t pmap)
1000 cpuset_t other_cpus;
1004 if (pmap == kernel_pmap || !CPU_CMP(&pmap->pm_active, &all_cpus)) {
1008 cpuid = PCPU_GET(cpuid);
1009 other_cpus = all_cpus;
1010 CPU_CLR(cpuid, &other_cpus);
1011 if (CPU_ISSET(cpuid, &pmap->pm_active))
1013 CPU_AND(&other_cpus, &pmap->pm_active);
1014 if (!CPU_EMPTY(&other_cpus))
1015 smp_masked_invltlb(other_cpus);
1021 pmap_invalidate_cache(void)
1031 cpuset_t invalidate; /* processors that invalidate their TLB */
1035 u_int store; /* processor that updates the PDE */
1039 pmap_update_pde_kernel(void *arg)
1041 struct pde_action *act = arg;
1045 if (act->store == PCPU_GET(cpuid)) {
1048 * Elsewhere, this operation requires allpmaps_lock for
1049 * synchronization. Here, it does not because it is being
1050 * performed in the context of an all_cpus rendezvous.
1052 LIST_FOREACH(pmap, &allpmaps, pm_list) {
1053 pde = pmap_pde(pmap, act->va);
1054 pde_store(pde, act->newpde);
1060 pmap_update_pde_user(void *arg)
1062 struct pde_action *act = arg;
1064 if (act->store == PCPU_GET(cpuid))
1065 pde_store(act->pde, act->newpde);
1069 pmap_update_pde_teardown(void *arg)
1071 struct pde_action *act = arg;
1073 if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
1074 pmap_update_pde_invalidate(act->va, act->newpde);
1078 * Change the page size for the specified virtual address in a way that
1079 * prevents any possibility of the TLB ever having two entries that map the
1080 * same virtual address using different page sizes. This is the recommended
1081 * workaround for Erratum 383 on AMD Family 10h processors. It prevents a
1082 * machine check exception for a TLB state that is improperly diagnosed as a
1086 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1088 struct pde_action act;
1089 cpuset_t active, other_cpus;
1093 cpuid = PCPU_GET(cpuid);
1094 other_cpus = all_cpus;
1095 CPU_CLR(cpuid, &other_cpus);
1096 if (pmap == kernel_pmap)
1099 active = pmap->pm_active;
1100 if (CPU_OVERLAP(&active, &other_cpus)) {
1102 act.invalidate = active;
1105 act.newpde = newpde;
1106 CPU_SET(cpuid, &active);
1107 smp_rendezvous_cpus(active,
1108 smp_no_rendevous_barrier, pmap == kernel_pmap ?
1109 pmap_update_pde_kernel : pmap_update_pde_user,
1110 pmap_update_pde_teardown, &act);
1112 if (pmap == kernel_pmap)
1113 pmap_kenter_pde(va, newpde);
1115 pde_store(pde, newpde);
1116 if (CPU_ISSET(cpuid, &active))
1117 pmap_update_pde_invalidate(va, newpde);
1123 * Normal, non-SMP, 486+ invalidation functions.
1124 * We inline these within pmap.c for speed.
1127 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1130 if (pmap == kernel_pmap || !CPU_EMPTY(&pmap->pm_active))
1135 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1139 if (pmap == kernel_pmap || !CPU_EMPTY(&pmap->pm_active))
1140 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1145 pmap_invalidate_all(pmap_t pmap)
1148 if (pmap == kernel_pmap || !CPU_EMPTY(&pmap->pm_active))
1153 pmap_invalidate_cache(void)
1160 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1163 if (pmap == kernel_pmap)
1164 pmap_kenter_pde(va, newpde);
1166 pde_store(pde, newpde);
1167 if (pmap == kernel_pmap || !CPU_EMPTY(&pmap->pm_active))
1168 pmap_update_pde_invalidate(va, newpde);
1172 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
1175 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva)
1178 KASSERT((sva & PAGE_MASK) == 0,
1179 ("pmap_invalidate_cache_range: sva not page-aligned"));
1180 KASSERT((eva & PAGE_MASK) == 0,
1181 ("pmap_invalidate_cache_range: eva not page-aligned"));
1183 if (cpu_feature & CPUID_SS)
1184 ; /* If "Self Snoop" is supported, do nothing. */
1185 else if ((cpu_feature & CPUID_CLFSH) != 0 &&
1186 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
1190 * XXX: Some CPUs fault, hang, or trash the local APIC
1191 * registers if we use CLFLUSH on the local APIC
1192 * range. The local APIC is always uncached, so we
1193 * don't need to flush for that range anyway.
1195 if (pmap_kextract(sva) == lapic_paddr)
1199 * Otherwise, do per-cache line flush. Use the mfence
1200 * instruction to insure that previous stores are
1201 * included in the write-back. The processor
1202 * propagates flush to other processors in the cache
1206 for (; sva < eva; sva += cpu_clflush_line_size)
1212 * No targeted cache flush methods are supported by CPU,
1213 * or the supplied range is bigger than 2MB.
1214 * Globally invalidate cache.
1216 pmap_invalidate_cache();
1221 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
1225 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
1226 (cpu_feature & CPUID_CLFSH) == 0) {
1227 pmap_invalidate_cache();
1229 for (i = 0; i < count; i++)
1230 pmap_flush_page(pages[i]);
1235 * Are we current address space or kernel? N.B. We return FALSE when
1236 * a pmap's page table is in use because a kernel thread is borrowing
1237 * it. The borrowed page table can change spontaneously, making any
1238 * dependence on its continued use subject to a race condition.
1241 pmap_is_current(pmap_t pmap)
1244 return (pmap == kernel_pmap ||
1245 (pmap == vmspace_pmap(curthread->td_proc->p_vmspace) &&
1246 (pmap->pm_pdir[PTDPTDI] & PG_FRAME) == (PTDpde[0] & PG_FRAME)));
1250 * If the given pmap is not the current or kernel pmap, the returned pte must
1251 * be released by passing it to pmap_pte_release().
1254 pmap_pte(pmap_t pmap, vm_offset_t va)
1259 pde = pmap_pde(pmap, va);
1263 /* are we current address space or kernel? */
1264 if (pmap_is_current(pmap))
1265 return (vtopte(va));
1266 mtx_lock(&PMAP2mutex);
1267 newpf = *pde & PG_FRAME;
1268 if ((*PMAP2 & PG_FRAME) != newpf) {
1269 *PMAP2 = newpf | PG_RW | PG_V | PG_A | PG_M;
1270 pmap_invalidate_page(kernel_pmap, (vm_offset_t)PADDR2);
1272 return (PADDR2 + (i386_btop(va) & (NPTEPG - 1)));
1278 * Releases a pte that was obtained from pmap_pte(). Be prepared for the pte
1281 static __inline void
1282 pmap_pte_release(pt_entry_t *pte)
1285 if ((pt_entry_t *)((vm_offset_t)pte & ~PAGE_MASK) == PADDR2)
1286 mtx_unlock(&PMAP2mutex);
1290 * NB: The sequence of updating a page table followed by accesses to the
1291 * corresponding pages is subject to the situation described in the "AMD64
1292 * Architecture Programmer's Manual Volume 2: System Programming" rev. 3.23,
1293 * "7.3.1 Special Coherency Considerations". Therefore, issuing the INVLPG
1294 * right after modifying the PTE bits is crucial.
1296 static __inline void
1297 invlcaddr(void *caddr)
1300 invlpg((u_int)caddr);
1304 * Super fast pmap_pte routine best used when scanning
1305 * the pv lists. This eliminates many coarse-grained
1306 * invltlb calls. Note that many of the pv list
1307 * scans are across different pmaps. It is very wasteful
1308 * to do an entire invltlb for checking a single mapping.
1310 * If the given pmap is not the current pmap, pvh_global_lock
1311 * must be held and curthread pinned to a CPU.
1314 pmap_pte_quick(pmap_t pmap, vm_offset_t va)
1319 pde = pmap_pde(pmap, va);
1323 /* are we current address space or kernel? */
1324 if (pmap_is_current(pmap))
1325 return (vtopte(va));
1326 rw_assert(&pvh_global_lock, RA_WLOCKED);
1327 KASSERT(curthread->td_pinned > 0, ("curthread not pinned"));
1328 newpf = *pde & PG_FRAME;
1329 if ((*PMAP1 & PG_FRAME) != newpf) {
1330 *PMAP1 = newpf | PG_RW | PG_V | PG_A | PG_M;
1332 PMAP1cpu = PCPU_GET(cpuid);
1338 if (PMAP1cpu != PCPU_GET(cpuid)) {
1339 PMAP1cpu = PCPU_GET(cpuid);
1345 return (PADDR1 + (i386_btop(va) & (NPTEPG - 1)));
1351 * Routine: pmap_extract
1353 * Extract the physical page address associated
1354 * with the given map/virtual_address pair.
1357 pmap_extract(pmap_t pmap, vm_offset_t va)
1365 pde = pmap->pm_pdir[va >> PDRSHIFT];
1367 if ((pde & PG_PS) != 0)
1368 rtval = (pde & PG_PS_FRAME) | (va & PDRMASK);
1370 pte = pmap_pte(pmap, va);
1371 rtval = (*pte & PG_FRAME) | (va & PAGE_MASK);
1372 pmap_pte_release(pte);
1380 * Routine: pmap_extract_and_hold
1382 * Atomically extract and hold the physical page
1383 * with the given pmap and virtual address pair
1384 * if that mapping permits the given protection.
1387 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
1390 pt_entry_t pte, *ptep;
1398 pde = *pmap_pde(pmap, va);
1401 if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0) {
1402 if (vm_page_pa_tryrelock(pmap, (pde &
1403 PG_PS_FRAME) | (va & PDRMASK), &pa))
1405 m = PHYS_TO_VM_PAGE((pde & PG_PS_FRAME) |
1410 ptep = pmap_pte(pmap, va);
1412 pmap_pte_release(ptep);
1414 ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
1415 if (vm_page_pa_tryrelock(pmap, pte & PG_FRAME,
1418 m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
1428 /***************************************************
1429 * Low level mapping routines.....
1430 ***************************************************/
1433 * Add a wired page to the kva.
1434 * Note: not SMP coherent.
1436 * This function may be used before pmap_bootstrap() is called.
1439 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
1444 pte_store(pte, pa | PG_RW | PG_V | pgeflag);
1447 static __inline void
1448 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
1453 pte_store(pte, pa | PG_RW | PG_V | pgeflag | pmap_cache_bits(mode, 0));
1457 * Remove a page from the kernel pagetables.
1458 * Note: not SMP coherent.
1460 * This function may be used before pmap_bootstrap() is called.
1463 pmap_kremove(vm_offset_t va)
1472 * Used to map a range of physical addresses into kernel
1473 * virtual address space.
1475 * The value passed in '*virt' is a suggested virtual address for
1476 * the mapping. Architectures which can support a direct-mapped
1477 * physical to virtual region can return the appropriate address
1478 * within that region, leaving '*virt' unchanged. Other
1479 * architectures should map the pages starting at '*virt' and
1480 * update '*virt' with the first usable address after the mapped
1484 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
1486 vm_offset_t va, sva;
1487 vm_paddr_t superpage_offset;
1492 * Does the physical address range's size and alignment permit at
1493 * least one superpage mapping to be created?
1495 superpage_offset = start & PDRMASK;
1496 if ((end - start) - ((NBPDR - superpage_offset) & PDRMASK) >= NBPDR) {
1498 * Increase the starting virtual address so that its alignment
1499 * does not preclude the use of superpage mappings.
1501 if ((va & PDRMASK) < superpage_offset)
1502 va = (va & ~PDRMASK) + superpage_offset;
1503 else if ((va & PDRMASK) > superpage_offset)
1504 va = ((va + PDRMASK) & ~PDRMASK) + superpage_offset;
1507 while (start < end) {
1508 if ((start & PDRMASK) == 0 && end - start >= NBPDR &&
1510 KASSERT((va & PDRMASK) == 0,
1511 ("pmap_map: misaligned va %#x", va));
1512 newpde = start | PG_PS | pgeflag | PG_RW | PG_V;
1513 pmap_kenter_pde(va, newpde);
1517 pmap_kenter(va, start);
1522 pmap_invalidate_range(kernel_pmap, sva, va);
1529 * Add a list of wired pages to the kva
1530 * this routine is only used for temporary
1531 * kernel mappings that do not need to have
1532 * page modification or references recorded.
1533 * Note that old mappings are simply written
1534 * over. The page *must* be wired.
1535 * Note: SMP coherent. Uses a ranged shootdown IPI.
1538 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
1540 pt_entry_t *endpte, oldpte, pa, *pte;
1545 endpte = pte + count;
1546 while (pte < endpte) {
1548 pa = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(m->md.pat_mode, 0);
1549 if ((*pte & (PG_FRAME | PG_PTE_CACHE)) != pa) {
1551 pte_store(pte, pa | pgeflag | PG_RW | PG_V);
1555 if (__predict_false((oldpte & PG_V) != 0))
1556 pmap_invalidate_range(kernel_pmap, sva, sva + count *
1561 * This routine tears out page mappings from the
1562 * kernel -- it is meant only for temporary mappings.
1563 * Note: SMP coherent. Uses a ranged shootdown IPI.
1566 pmap_qremove(vm_offset_t sva, int count)
1571 while (count-- > 0) {
1575 pmap_invalidate_range(kernel_pmap, sva, va);
1578 /***************************************************
1579 * Page table page management routines.....
1580 ***************************************************/
1581 static __inline void
1582 pmap_free_zero_pages(struct spglist *free)
1586 while ((m = SLIST_FIRST(free)) != NULL) {
1587 SLIST_REMOVE_HEAD(free, plinks.s.ss);
1588 /* Preserve the page's PG_ZERO setting. */
1589 vm_page_free_toq(m);
1594 * Schedule the specified unused page table page to be freed. Specifically,
1595 * add the page to the specified list of pages that will be released to the
1596 * physical memory manager after the TLB has been updated.
1598 static __inline void
1599 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
1600 boolean_t set_PG_ZERO)
1604 m->flags |= PG_ZERO;
1606 m->flags &= ~PG_ZERO;
1607 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
1611 * Inserts the specified page table page into the specified pmap's collection
1612 * of idle page table pages. Each of a pmap's page table pages is responsible
1613 * for mapping a distinct range of virtual addresses. The pmap's collection is
1614 * ordered by this virtual address range.
1617 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte)
1620 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1621 return (vm_radix_insert(&pmap->pm_root, mpte));
1625 * Looks for a page table page mapping the specified virtual address in the
1626 * specified pmap's collection of idle page table pages. Returns NULL if there
1627 * is no page table page corresponding to the specified virtual address.
1629 static __inline vm_page_t
1630 pmap_lookup_pt_page(pmap_t pmap, vm_offset_t va)
1633 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1634 return (vm_radix_lookup(&pmap->pm_root, va >> PDRSHIFT));
1638 * Removes the specified page table page from the specified pmap's collection
1639 * of idle page table pages. The specified page table page must be a member of
1640 * the pmap's collection.
1642 static __inline void
1643 pmap_remove_pt_page(pmap_t pmap, vm_page_t mpte)
1646 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1647 vm_radix_remove(&pmap->pm_root, mpte->pindex);
1651 * Decrements a page table page's wire count, which is used to record the
1652 * number of valid page table entries within the page. If the wire count
1653 * drops to zero, then the page table page is unmapped. Returns TRUE if the
1654 * page table page was unmapped and FALSE otherwise.
1656 static inline boolean_t
1657 pmap_unwire_ptp(pmap_t pmap, vm_page_t m, struct spglist *free)
1661 if (m->wire_count == 0) {
1662 _pmap_unwire_ptp(pmap, m, free);
1669 _pmap_unwire_ptp(pmap_t pmap, vm_page_t m, struct spglist *free)
1674 * unmap the page table page
1676 pmap->pm_pdir[m->pindex] = 0;
1677 --pmap->pm_stats.resident_count;
1680 * This is a release store so that the ordinary store unmapping
1681 * the page table page is globally performed before TLB shoot-
1684 atomic_subtract_rel_int(&cnt.v_wire_count, 1);
1687 * Do an invltlb to make the invalidated mapping
1688 * take effect immediately.
1690 pteva = VM_MAXUSER_ADDRESS + i386_ptob(m->pindex);
1691 pmap_invalidate_page(pmap, pteva);
1694 * Put page on a list so that it is released after
1695 * *ALL* TLB shootdown is done
1697 pmap_add_delayed_free_list(m, free, TRUE);
1701 * After removing a page table entry, this routine is used to
1702 * conditionally free the page, and manage the hold/wire counts.
1705 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, struct spglist *free)
1710 if (va >= VM_MAXUSER_ADDRESS)
1712 ptepde = *pmap_pde(pmap, va);
1713 mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
1714 return (pmap_unwire_ptp(pmap, mpte, free));
1718 * Initialize the pmap for the swapper process.
1721 pmap_pinit0(pmap_t pmap)
1724 PMAP_LOCK_INIT(pmap);
1726 * Since the page table directory is shared with the kernel pmap,
1727 * which is already included in the list "allpmaps", this pmap does
1728 * not need to be inserted into that list.
1730 pmap->pm_pdir = (pd_entry_t *)(KERNBASE + (vm_offset_t)IdlePTD);
1732 pmap->pm_pdpt = (pdpt_entry_t *)(KERNBASE + (vm_offset_t)IdlePDPT);
1734 pmap->pm_root.rt_root = 0;
1735 CPU_ZERO(&pmap->pm_active);
1736 PCPU_SET(curpmap, pmap);
1737 TAILQ_INIT(&pmap->pm_pvchunk);
1738 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
1742 * Initialize a preallocated and zeroed pmap structure,
1743 * such as one in a vmspace structure.
1746 pmap_pinit(pmap_t pmap)
1748 vm_page_t m, ptdpg[NPGPTD];
1753 * No need to allocate page table space yet but we do need a valid
1754 * page directory table.
1756 if (pmap->pm_pdir == NULL) {
1757 pmap->pm_pdir = (pd_entry_t *)kva_alloc(NBPTD);
1758 if (pmap->pm_pdir == NULL)
1761 pmap->pm_pdpt = uma_zalloc(pdptzone, M_WAITOK | M_ZERO);
1762 KASSERT(((vm_offset_t)pmap->pm_pdpt &
1763 ((NPGPTD * sizeof(pdpt_entry_t)) - 1)) == 0,
1764 ("pmap_pinit: pdpt misaligned"));
1765 KASSERT(pmap_kextract((vm_offset_t)pmap->pm_pdpt) < (4ULL<<30),
1766 ("pmap_pinit: pdpt above 4g"));
1768 pmap->pm_root.rt_root = 0;
1770 KASSERT(vm_radix_is_empty(&pmap->pm_root),
1771 ("pmap_pinit: pmap has reserved page table page(s)"));
1774 * allocate the page directory page(s)
1776 for (i = 0; i < NPGPTD;) {
1777 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
1778 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
1786 pmap_qenter((vm_offset_t)pmap->pm_pdir, ptdpg, NPGPTD);
1788 for (i = 0; i < NPGPTD; i++)
1789 if ((ptdpg[i]->flags & PG_ZERO) == 0)
1790 pagezero(pmap->pm_pdir + (i * NPDEPG));
1792 mtx_lock_spin(&allpmaps_lock);
1793 LIST_INSERT_HEAD(&allpmaps, pmap, pm_list);
1794 /* Copy the kernel page table directory entries. */
1795 bcopy(PTD + KPTDI, pmap->pm_pdir + KPTDI, nkpt * sizeof(pd_entry_t));
1796 mtx_unlock_spin(&allpmaps_lock);
1798 /* install self-referential address mapping entry(s) */
1799 for (i = 0; i < NPGPTD; i++) {
1800 pa = VM_PAGE_TO_PHYS(ptdpg[i]);
1801 pmap->pm_pdir[PTDPTDI + i] = pa | PG_V | PG_RW | PG_A | PG_M;
1803 pmap->pm_pdpt[i] = pa | PG_V;
1807 CPU_ZERO(&pmap->pm_active);
1808 TAILQ_INIT(&pmap->pm_pvchunk);
1809 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
1815 * this routine is called if the page table page is not
1819 _pmap_allocpte(pmap_t pmap, u_int ptepindex, u_int flags)
1825 * Allocate a page table page.
1827 if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
1828 VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
1829 if ((flags & PMAP_ENTER_NOSLEEP) == 0) {
1831 rw_wunlock(&pvh_global_lock);
1833 rw_wlock(&pvh_global_lock);
1838 * Indicate the need to retry. While waiting, the page table
1839 * page may have been allocated.
1843 if ((m->flags & PG_ZERO) == 0)
1847 * Map the pagetable page into the process address space, if
1848 * it isn't already there.
1851 pmap->pm_stats.resident_count++;
1853 ptepa = VM_PAGE_TO_PHYS(m);
1854 pmap->pm_pdir[ptepindex] =
1855 (pd_entry_t) (ptepa | PG_U | PG_RW | PG_V | PG_A | PG_M);
1861 pmap_allocpte(pmap_t pmap, vm_offset_t va, u_int flags)
1868 * Calculate pagetable page index
1870 ptepindex = va >> PDRSHIFT;
1873 * Get the page directory entry
1875 ptepa = pmap->pm_pdir[ptepindex];
1878 * This supports switching from a 4MB page to a
1881 if (ptepa & PG_PS) {
1882 (void)pmap_demote_pde(pmap, &pmap->pm_pdir[ptepindex], va);
1883 ptepa = pmap->pm_pdir[ptepindex];
1887 * If the page table page is mapped, we just increment the
1888 * hold count, and activate it.
1891 m = PHYS_TO_VM_PAGE(ptepa & PG_FRAME);
1895 * Here if the pte page isn't mapped, or if it has
1898 m = _pmap_allocpte(pmap, ptepindex, flags);
1899 if (m == NULL && (flags & PMAP_ENTER_NOSLEEP) == 0)
1906 /***************************************************
1907 * Pmap allocation/deallocation routines.
1908 ***************************************************/
1912 * Deal with a SMP shootdown of other users of the pmap that we are
1913 * trying to dispose of. This can be a bit hairy.
1915 static cpuset_t *lazymask;
1916 static u_int lazyptd;
1917 static volatile u_int lazywait;
1919 void pmap_lazyfix_action(void);
1922 pmap_lazyfix_action(void)
1926 (*ipi_lazypmap_counts[PCPU_GET(cpuid)])++;
1928 if (rcr3() == lazyptd)
1929 load_cr3(curpcb->pcb_cr3);
1930 CPU_CLR_ATOMIC(PCPU_GET(cpuid), lazymask);
1931 atomic_store_rel_int(&lazywait, 1);
1935 pmap_lazyfix_self(u_int cpuid)
1938 if (rcr3() == lazyptd)
1939 load_cr3(curpcb->pcb_cr3);
1940 CPU_CLR_ATOMIC(cpuid, lazymask);
1945 pmap_lazyfix(pmap_t pmap)
1947 cpuset_t mymask, mask;
1951 mask = pmap->pm_active;
1952 while (!CPU_EMPTY(&mask)) {
1955 /* Find least significant set bit. */
1956 lsb = CPU_FFS(&mask);
1959 CPU_SETOF(lsb, &mask);
1960 mtx_lock_spin(&smp_ipi_mtx);
1962 lazyptd = vtophys(pmap->pm_pdpt);
1964 lazyptd = vtophys(pmap->pm_pdir);
1966 cpuid = PCPU_GET(cpuid);
1968 /* Use a cpuset just for having an easy check. */
1969 CPU_SETOF(cpuid, &mymask);
1970 if (!CPU_CMP(&mask, &mymask)) {
1971 lazymask = &pmap->pm_active;
1972 pmap_lazyfix_self(cpuid);
1974 atomic_store_rel_int((u_int *)&lazymask,
1975 (u_int)&pmap->pm_active);
1976 atomic_store_rel_int(&lazywait, 0);
1977 ipi_selected(mask, IPI_LAZYPMAP);
1978 while (lazywait == 0) {
1984 mtx_unlock_spin(&smp_ipi_mtx);
1986 printf("pmap_lazyfix: spun for 50000000\n");
1987 mask = pmap->pm_active;
1994 * Cleaning up on uniprocessor is easy. For various reasons, we're
1995 * unlikely to have to even execute this code, including the fact
1996 * that the cleanup is deferred until the parent does a wait(2), which
1997 * means that another userland process has run.
2000 pmap_lazyfix(pmap_t pmap)
2004 cr3 = vtophys(pmap->pm_pdir);
2005 if (cr3 == rcr3()) {
2006 load_cr3(curpcb->pcb_cr3);
2007 CPU_CLR(PCPU_GET(cpuid), &pmap->pm_active);
2013 * Release any resources held by the given physical map.
2014 * Called when a pmap initialized by pmap_pinit is being released.
2015 * Should only be called if the map contains no valid mappings.
2018 pmap_release(pmap_t pmap)
2020 vm_page_t m, ptdpg[NPGPTD];
2023 KASSERT(pmap->pm_stats.resident_count == 0,
2024 ("pmap_release: pmap resident count %ld != 0",
2025 pmap->pm_stats.resident_count));
2026 KASSERT(vm_radix_is_empty(&pmap->pm_root),
2027 ("pmap_release: pmap has reserved page table page(s)"));
2030 mtx_lock_spin(&allpmaps_lock);
2031 LIST_REMOVE(pmap, pm_list);
2032 mtx_unlock_spin(&allpmaps_lock);
2034 for (i = 0; i < NPGPTD; i++)
2035 ptdpg[i] = PHYS_TO_VM_PAGE(pmap->pm_pdir[PTDPTDI + i] &
2038 bzero(pmap->pm_pdir + PTDPTDI, (nkpt + NPGPTD) *
2039 sizeof(*pmap->pm_pdir));
2041 pmap_qremove((vm_offset_t)pmap->pm_pdir, NPGPTD);
2043 for (i = 0; i < NPGPTD; i++) {
2046 KASSERT(VM_PAGE_TO_PHYS(m) == (pmap->pm_pdpt[i] & PG_FRAME),
2047 ("pmap_release: got wrong ptd page"));
2050 atomic_subtract_int(&cnt.v_wire_count, 1);
2051 vm_page_free_zero(m);
2056 kvm_size(SYSCTL_HANDLER_ARGS)
2058 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - KERNBASE;
2060 return (sysctl_handle_long(oidp, &ksize, 0, req));
2062 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD,
2063 0, 0, kvm_size, "IU", "Size of KVM");
2066 kvm_free(SYSCTL_HANDLER_ARGS)
2068 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
2070 return (sysctl_handle_long(oidp, &kfree, 0, req));
2072 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD,
2073 0, 0, kvm_free, "IU", "Amount of KVM free");
2076 * grow the number of kernel page table entries, if needed
2079 pmap_growkernel(vm_offset_t addr)
2081 vm_paddr_t ptppaddr;
2085 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
2086 addr = roundup2(addr, NBPDR);
2087 if (addr - 1 >= kernel_map->max_offset)
2088 addr = kernel_map->max_offset;
2089 while (kernel_vm_end < addr) {
2090 if (pdir_pde(PTD, kernel_vm_end)) {
2091 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
2092 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
2093 kernel_vm_end = kernel_map->max_offset;
2099 nkpg = vm_page_alloc(NULL, kernel_vm_end >> PDRSHIFT,
2100 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
2103 panic("pmap_growkernel: no memory to grow kernel");
2107 if ((nkpg->flags & PG_ZERO) == 0)
2108 pmap_zero_page(nkpg);
2109 ptppaddr = VM_PAGE_TO_PHYS(nkpg);
2110 newpdir = (pd_entry_t) (ptppaddr | PG_V | PG_RW | PG_A | PG_M);
2111 pdir_pde(KPTD, kernel_vm_end) = pgeflag | newpdir;
2113 pmap_kenter_pde(kernel_vm_end, newpdir);
2114 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
2115 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
2116 kernel_vm_end = kernel_map->max_offset;
2123 /***************************************************
2124 * page management routines.
2125 ***************************************************/
2127 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
2128 CTASSERT(_NPCM == 11);
2129 CTASSERT(_NPCPV == 336);
2131 static __inline struct pv_chunk *
2132 pv_to_chunk(pv_entry_t pv)
2135 return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
2138 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
2140 #define PC_FREE0_9 0xfffffffful /* Free values for index 0 through 9 */
2141 #define PC_FREE10 0x0000fffful /* Free values for index 10 */
2143 static const uint32_t pc_freemask[_NPCM] = {
2144 PC_FREE0_9, PC_FREE0_9, PC_FREE0_9,
2145 PC_FREE0_9, PC_FREE0_9, PC_FREE0_9,
2146 PC_FREE0_9, PC_FREE0_9, PC_FREE0_9,
2147 PC_FREE0_9, PC_FREE10
2150 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
2151 "Current number of pv entries");
2154 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
2156 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
2157 "Current number of pv entry chunks");
2158 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
2159 "Current number of pv entry chunks allocated");
2160 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
2161 "Current number of pv entry chunks frees");
2162 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
2163 "Number of times tried to get a chunk page but failed.");
2165 static long pv_entry_frees, pv_entry_allocs;
2166 static int pv_entry_spare;
2168 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
2169 "Current number of pv entry frees");
2170 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
2171 "Current number of pv entry allocs");
2172 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
2173 "Current number of spare pv entries");
2177 * We are in a serious low memory condition. Resort to
2178 * drastic measures to free some pages so we can allocate
2179 * another pv entry chunk.
2182 pmap_pv_reclaim(pmap_t locked_pmap)
2185 struct pv_chunk *pc;
2186 struct md_page *pvh;
2189 pt_entry_t *pte, tpte;
2193 struct spglist free;
2195 int bit, field, freed;
2197 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
2201 TAILQ_INIT(&newtail);
2202 while ((pc = TAILQ_FIRST(&pv_chunks)) != NULL && (pv_vafree == 0 ||
2203 SLIST_EMPTY(&free))) {
2204 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
2205 if (pmap != pc->pc_pmap) {
2207 pmap_invalidate_all(pmap);
2208 if (pmap != locked_pmap)
2212 /* Avoid deadlock and lock recursion. */
2213 if (pmap > locked_pmap)
2215 else if (pmap != locked_pmap && !PMAP_TRYLOCK(pmap)) {
2217 TAILQ_INSERT_TAIL(&newtail, pc, pc_lru);
2223 * Destroy every non-wired, 4 KB page mapping in the chunk.
2226 for (field = 0; field < _NPCM; field++) {
2227 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
2228 inuse != 0; inuse &= ~(1UL << bit)) {
2230 pv = &pc->pc_pventry[field * 32 + bit];
2232 pde = pmap_pde(pmap, va);
2233 if ((*pde & PG_PS) != 0)
2235 pte = pmap_pte(pmap, va);
2237 if ((tpte & PG_W) == 0)
2238 tpte = pte_load_clear(pte);
2239 pmap_pte_release(pte);
2240 if ((tpte & PG_W) != 0)
2243 ("pmap_pv_reclaim: pmap %p va %x zero pte",
2245 if ((tpte & PG_G) != 0)
2246 pmap_invalidate_page(pmap, va);
2247 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
2248 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
2250 if ((tpte & PG_A) != 0)
2251 vm_page_aflag_set(m, PGA_REFERENCED);
2252 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
2253 if (TAILQ_EMPTY(&m->md.pv_list) &&
2254 (m->flags & PG_FICTITIOUS) == 0) {
2255 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
2256 if (TAILQ_EMPTY(&pvh->pv_list)) {
2257 vm_page_aflag_clear(m,
2261 pc->pc_map[field] |= 1UL << bit;
2262 pmap_unuse_pt(pmap, va, &free);
2267 TAILQ_INSERT_TAIL(&newtail, pc, pc_lru);
2270 /* Every freed mapping is for a 4 KB page. */
2271 pmap->pm_stats.resident_count -= freed;
2272 PV_STAT(pv_entry_frees += freed);
2273 PV_STAT(pv_entry_spare += freed);
2274 pv_entry_count -= freed;
2275 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2276 for (field = 0; field < _NPCM; field++)
2277 if (pc->pc_map[field] != pc_freemask[field]) {
2278 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc,
2280 TAILQ_INSERT_TAIL(&newtail, pc, pc_lru);
2283 * One freed pv entry in locked_pmap is
2286 if (pmap == locked_pmap)
2290 if (field == _NPCM) {
2291 PV_STAT(pv_entry_spare -= _NPCPV);
2292 PV_STAT(pc_chunk_count--);
2293 PV_STAT(pc_chunk_frees++);
2294 /* Entire chunk is free; return it. */
2295 m_pc = PHYS_TO_VM_PAGE(pmap_kextract((vm_offset_t)pc));
2296 pmap_qremove((vm_offset_t)pc, 1);
2297 pmap_ptelist_free(&pv_vafree, (vm_offset_t)pc);
2302 TAILQ_CONCAT(&pv_chunks, &newtail, pc_lru);
2304 pmap_invalidate_all(pmap);
2305 if (pmap != locked_pmap)
2308 if (m_pc == NULL && pv_vafree != 0 && SLIST_EMPTY(&free)) {
2309 m_pc = SLIST_FIRST(&free);
2310 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2311 /* Recycle a freed page table page. */
2312 m_pc->wire_count = 1;
2313 atomic_add_int(&cnt.v_wire_count, 1);
2315 pmap_free_zero_pages(&free);
2320 * free the pv_entry back to the free list
2323 free_pv_entry(pmap_t pmap, pv_entry_t pv)
2325 struct pv_chunk *pc;
2326 int idx, field, bit;
2328 rw_assert(&pvh_global_lock, RA_WLOCKED);
2329 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2330 PV_STAT(pv_entry_frees++);
2331 PV_STAT(pv_entry_spare++);
2333 pc = pv_to_chunk(pv);
2334 idx = pv - &pc->pc_pventry[0];
2337 pc->pc_map[field] |= 1ul << bit;
2338 for (idx = 0; idx < _NPCM; idx++)
2339 if (pc->pc_map[idx] != pc_freemask[idx]) {
2341 * 98% of the time, pc is already at the head of the
2342 * list. If it isn't already, move it to the head.
2344 if (__predict_false(TAILQ_FIRST(&pmap->pm_pvchunk) !=
2346 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2347 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc,
2352 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2357 free_pv_chunk(struct pv_chunk *pc)
2361 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
2362 PV_STAT(pv_entry_spare -= _NPCPV);
2363 PV_STAT(pc_chunk_count--);
2364 PV_STAT(pc_chunk_frees++);
2365 /* entire chunk is free, return it */
2366 m = PHYS_TO_VM_PAGE(pmap_kextract((vm_offset_t)pc));
2367 pmap_qremove((vm_offset_t)pc, 1);
2368 vm_page_unwire(m, 0);
2370 pmap_ptelist_free(&pv_vafree, (vm_offset_t)pc);
2374 * get a new pv_entry, allocating a block from the system
2378 get_pv_entry(pmap_t pmap, boolean_t try)
2380 static const struct timeval printinterval = { 60, 0 };
2381 static struct timeval lastprint;
2384 struct pv_chunk *pc;
2387 rw_assert(&pvh_global_lock, RA_WLOCKED);
2388 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2389 PV_STAT(pv_entry_allocs++);
2391 if (pv_entry_count > pv_entry_high_water)
2392 if (ratecheck(&lastprint, &printinterval))
2393 printf("Approaching the limit on PV entries, consider "
2394 "increasing either the vm.pmap.shpgperproc or the "
2395 "vm.pmap.pv_entry_max tunable.\n");
2397 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
2399 for (field = 0; field < _NPCM; field++) {
2400 if (pc->pc_map[field]) {
2401 bit = bsfl(pc->pc_map[field]);
2405 if (field < _NPCM) {
2406 pv = &pc->pc_pventry[field * 32 + bit];
2407 pc->pc_map[field] &= ~(1ul << bit);
2408 /* If this was the last item, move it to tail */
2409 for (field = 0; field < _NPCM; field++)
2410 if (pc->pc_map[field] != 0) {
2411 PV_STAT(pv_entry_spare--);
2412 return (pv); /* not full, return */
2414 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2415 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
2416 PV_STAT(pv_entry_spare--);
2421 * Access to the ptelist "pv_vafree" is synchronized by the pvh
2422 * global lock. If "pv_vafree" is currently non-empty, it will
2423 * remain non-empty until pmap_ptelist_alloc() completes.
2425 if (pv_vafree == 0 || (m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
2426 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
2429 PV_STAT(pc_chunk_tryfail++);
2432 m = pmap_pv_reclaim(pmap);
2436 PV_STAT(pc_chunk_count++);
2437 PV_STAT(pc_chunk_allocs++);
2438 pc = (struct pv_chunk *)pmap_ptelist_alloc(&pv_vafree);
2439 pmap_qenter((vm_offset_t)pc, &m, 1);
2441 pc->pc_map[0] = pc_freemask[0] & ~1ul; /* preallocated bit 0 */
2442 for (field = 1; field < _NPCM; field++)
2443 pc->pc_map[field] = pc_freemask[field];
2444 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
2445 pv = &pc->pc_pventry[0];
2446 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
2447 PV_STAT(pv_entry_spare += _NPCPV - 1);
2451 static __inline pv_entry_t
2452 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
2456 rw_assert(&pvh_global_lock, RA_WLOCKED);
2457 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
2458 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
2459 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
2467 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa)
2469 struct md_page *pvh;
2471 vm_offset_t va_last;
2474 rw_assert(&pvh_global_lock, RA_WLOCKED);
2475 KASSERT((pa & PDRMASK) == 0,
2476 ("pmap_pv_demote_pde: pa is not 4mpage aligned"));
2479 * Transfer the 4mpage's pv entry for this mapping to the first
2482 pvh = pa_to_pvh(pa);
2483 va = trunc_4mpage(va);
2484 pv = pmap_pvh_remove(pvh, pmap, va);
2485 KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
2486 m = PHYS_TO_VM_PAGE(pa);
2487 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
2488 /* Instantiate the remaining NPTEPG - 1 pv entries. */
2489 va_last = va + NBPDR - PAGE_SIZE;
2492 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
2493 ("pmap_pv_demote_pde: page %p is not managed", m));
2495 pmap_insert_entry(pmap, va, m);
2496 } while (va < va_last);
2500 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa)
2502 struct md_page *pvh;
2504 vm_offset_t va_last;
2507 rw_assert(&pvh_global_lock, RA_WLOCKED);
2508 KASSERT((pa & PDRMASK) == 0,
2509 ("pmap_pv_promote_pde: pa is not 4mpage aligned"));
2512 * Transfer the first page's pv entry for this mapping to the
2513 * 4mpage's pv list. Aside from avoiding the cost of a call
2514 * to get_pv_entry(), a transfer avoids the possibility that
2515 * get_pv_entry() calls pmap_collect() and that pmap_collect()
2516 * removes one of the mappings that is being promoted.
2518 m = PHYS_TO_VM_PAGE(pa);
2519 va = trunc_4mpage(va);
2520 pv = pmap_pvh_remove(&m->md, pmap, va);
2521 KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
2522 pvh = pa_to_pvh(pa);
2523 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
2524 /* Free the remaining NPTEPG - 1 pv entries. */
2525 va_last = va + NBPDR - PAGE_SIZE;
2529 pmap_pvh_free(&m->md, pmap, va);
2530 } while (va < va_last);
2534 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
2538 pv = pmap_pvh_remove(pvh, pmap, va);
2539 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
2540 free_pv_entry(pmap, pv);
2544 pmap_remove_entry(pmap_t pmap, vm_page_t m, vm_offset_t va)
2546 struct md_page *pvh;
2548 rw_assert(&pvh_global_lock, RA_WLOCKED);
2549 pmap_pvh_free(&m->md, pmap, va);
2550 if (TAILQ_EMPTY(&m->md.pv_list) && (m->flags & PG_FICTITIOUS) == 0) {
2551 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
2552 if (TAILQ_EMPTY(&pvh->pv_list))
2553 vm_page_aflag_clear(m, PGA_WRITEABLE);
2558 * Create a pv entry for page at pa for
2562 pmap_insert_entry(pmap_t pmap, vm_offset_t va, vm_page_t m)
2566 rw_assert(&pvh_global_lock, RA_WLOCKED);
2567 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2568 pv = get_pv_entry(pmap, FALSE);
2570 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
2574 * Conditionally create a pv entry.
2577 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m)
2581 rw_assert(&pvh_global_lock, RA_WLOCKED);
2582 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2583 if (pv_entry_count < pv_entry_high_water &&
2584 (pv = get_pv_entry(pmap, TRUE)) != NULL) {
2586 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
2593 * Create the pv entries for each of the pages within a superpage.
2596 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa)
2598 struct md_page *pvh;
2601 rw_assert(&pvh_global_lock, RA_WLOCKED);
2602 if (pv_entry_count < pv_entry_high_water &&
2603 (pv = get_pv_entry(pmap, TRUE)) != NULL) {
2605 pvh = pa_to_pvh(pa);
2606 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
2613 * Fills a page table page with mappings to consecutive physical pages.
2616 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
2620 for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
2622 newpte += PAGE_SIZE;
2627 * Tries to demote a 2- or 4MB page mapping. If demotion fails, the
2628 * 2- or 4MB page mapping is invalidated.
2631 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
2633 pd_entry_t newpde, oldpde;
2634 pt_entry_t *firstpte, newpte;
2637 struct spglist free;
2639 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2641 KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
2642 ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
2643 if ((oldpde & PG_A) != 0 && (mpte = pmap_lookup_pt_page(pmap, va)) !=
2645 pmap_remove_pt_page(pmap, mpte);
2647 KASSERT((oldpde & PG_W) == 0,
2648 ("pmap_demote_pde: page table page for a wired mapping"
2652 * Invalidate the 2- or 4MB page mapping and return
2653 * "failure" if the mapping was never accessed or the
2654 * allocation of the new page table page fails.
2656 if ((oldpde & PG_A) == 0 || (mpte = vm_page_alloc(NULL,
2657 va >> PDRSHIFT, VM_ALLOC_NOOBJ | VM_ALLOC_NORMAL |
2658 VM_ALLOC_WIRED)) == NULL) {
2660 pmap_remove_pde(pmap, pde, trunc_4mpage(va), &free);
2661 pmap_invalidate_page(pmap, trunc_4mpage(va));
2662 pmap_free_zero_pages(&free);
2663 CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#x"
2664 " in pmap %p", va, pmap);
2667 if (va < VM_MAXUSER_ADDRESS)
2668 pmap->pm_stats.resident_count++;
2670 mptepa = VM_PAGE_TO_PHYS(mpte);
2673 * If the page mapping is in the kernel's address space, then the
2674 * KPTmap can provide access to the page table page. Otherwise,
2675 * temporarily map the page table page (mpte) into the kernel's
2676 * address space at either PADDR1 or PADDR2.
2679 firstpte = &KPTmap[i386_btop(trunc_4mpage(va))];
2680 else if (curthread->td_pinned > 0 && rw_wowned(&pvh_global_lock)) {
2681 if ((*PMAP1 & PG_FRAME) != mptepa) {
2682 *PMAP1 = mptepa | PG_RW | PG_V | PG_A | PG_M;
2684 PMAP1cpu = PCPU_GET(cpuid);
2690 if (PMAP1cpu != PCPU_GET(cpuid)) {
2691 PMAP1cpu = PCPU_GET(cpuid);
2699 mtx_lock(&PMAP2mutex);
2700 if ((*PMAP2 & PG_FRAME) != mptepa) {
2701 *PMAP2 = mptepa | PG_RW | PG_V | PG_A | PG_M;
2702 pmap_invalidate_page(kernel_pmap, (vm_offset_t)PADDR2);
2706 newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
2707 KASSERT((oldpde & PG_A) != 0,
2708 ("pmap_demote_pde: oldpde is missing PG_A"));
2709 KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
2710 ("pmap_demote_pde: oldpde is missing PG_M"));
2711 newpte = oldpde & ~PG_PS;
2712 if ((newpte & PG_PDE_PAT) != 0)
2713 newpte ^= PG_PDE_PAT | PG_PTE_PAT;
2716 * If the page table page is new, initialize it.
2718 if (mpte->wire_count == 1) {
2719 mpte->wire_count = NPTEPG;
2720 pmap_fill_ptp(firstpte, newpte);
2722 KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
2723 ("pmap_demote_pde: firstpte and newpte map different physical"
2727 * If the mapping has changed attributes, update the page table
2730 if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
2731 pmap_fill_ptp(firstpte, newpte);
2734 * Demote the mapping. This pmap is locked. The old PDE has
2735 * PG_A set. If the old PDE has PG_RW set, it also has PG_M
2736 * set. Thus, there is no danger of a race with another
2737 * processor changing the setting of PG_A and/or PG_M between
2738 * the read above and the store below.
2740 if (workaround_erratum383)
2741 pmap_update_pde(pmap, va, pde, newpde);
2742 else if (pmap == kernel_pmap)
2743 pmap_kenter_pde(va, newpde);
2745 pde_store(pde, newpde);
2746 if (firstpte == PADDR2)
2747 mtx_unlock(&PMAP2mutex);
2750 * Invalidate the recursive mapping of the page table page.
2752 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
2755 * Demote the pv entry. This depends on the earlier demotion
2756 * of the mapping. Specifically, the (re)creation of a per-
2757 * page pv entry might trigger the execution of pmap_collect(),
2758 * which might reclaim a newly (re)created per-page pv entry
2759 * and destroy the associated mapping. In order to destroy
2760 * the mapping, the PDE must have already changed from mapping
2761 * the 2mpage to referencing the page table page.
2763 if ((oldpde & PG_MANAGED) != 0)
2764 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME);
2766 pmap_pde_demotions++;
2767 CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#x"
2768 " in pmap %p", va, pmap);
2773 * Removes a 2- or 4MB page mapping from the kernel pmap.
2776 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
2782 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2783 mpte = pmap_lookup_pt_page(pmap, va);
2785 panic("pmap_remove_kernel_pde: Missing pt page.");
2787 pmap_remove_pt_page(pmap, mpte);
2788 mptepa = VM_PAGE_TO_PHYS(mpte);
2789 newpde = mptepa | PG_M | PG_A | PG_RW | PG_V;
2792 * Initialize the page table page.
2794 pagezero((void *)&KPTmap[i386_btop(trunc_4mpage(va))]);
2797 * Remove the mapping.
2799 if (workaround_erratum383)
2800 pmap_update_pde(pmap, va, pde, newpde);
2802 pmap_kenter_pde(va, newpde);
2805 * Invalidate the recursive mapping of the page table page.
2807 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
2811 * pmap_remove_pde: do the things to unmap a superpage in a process
2814 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
2815 struct spglist *free)
2817 struct md_page *pvh;
2819 vm_offset_t eva, va;
2822 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2823 KASSERT((sva & PDRMASK) == 0,
2824 ("pmap_remove_pde: sva is not 4mpage aligned"));
2825 oldpde = pte_load_clear(pdq);
2827 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
2830 * Machines that don't support invlpg, also don't support
2834 pmap_invalidate_page(kernel_pmap, sva);
2835 pmap->pm_stats.resident_count -= NBPDR / PAGE_SIZE;
2836 if (oldpde & PG_MANAGED) {
2837 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
2838 pmap_pvh_free(pvh, pmap, sva);
2840 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
2841 va < eva; va += PAGE_SIZE, m++) {
2842 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
2845 vm_page_aflag_set(m, PGA_REFERENCED);
2846 if (TAILQ_EMPTY(&m->md.pv_list) &&
2847 TAILQ_EMPTY(&pvh->pv_list))
2848 vm_page_aflag_clear(m, PGA_WRITEABLE);
2851 if (pmap == kernel_pmap) {
2852 pmap_remove_kernel_pde(pmap, pdq, sva);
2854 mpte = pmap_lookup_pt_page(pmap, sva);
2856 pmap_remove_pt_page(pmap, mpte);
2857 pmap->pm_stats.resident_count--;
2858 KASSERT(mpte->wire_count == NPTEPG,
2859 ("pmap_remove_pde: pte page wire count error"));
2860 mpte->wire_count = 0;
2861 pmap_add_delayed_free_list(mpte, free, FALSE);
2862 atomic_subtract_int(&cnt.v_wire_count, 1);
2868 * pmap_remove_pte: do the things to unmap a page in a process
2871 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
2872 struct spglist *free)
2877 rw_assert(&pvh_global_lock, RA_WLOCKED);
2878 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2879 oldpte = pte_load_clear(ptq);
2880 KASSERT(oldpte != 0,
2881 ("pmap_remove_pte: pmap %p va %x zero pte", pmap, va));
2883 pmap->pm_stats.wired_count -= 1;
2885 * Machines that don't support invlpg, also don't support
2889 pmap_invalidate_page(kernel_pmap, va);
2890 pmap->pm_stats.resident_count -= 1;
2891 if (oldpte & PG_MANAGED) {
2892 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
2893 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
2896 vm_page_aflag_set(m, PGA_REFERENCED);
2897 pmap_remove_entry(pmap, m, va);
2899 return (pmap_unuse_pt(pmap, va, free));
2903 * Remove a single page from a process address space
2906 pmap_remove_page(pmap_t pmap, vm_offset_t va, struct spglist *free)
2910 rw_assert(&pvh_global_lock, RA_WLOCKED);
2911 KASSERT(curthread->td_pinned > 0, ("curthread not pinned"));
2912 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2913 if ((pte = pmap_pte_quick(pmap, va)) == NULL || *pte == 0)
2915 pmap_remove_pte(pmap, pte, va, free);
2916 pmap_invalidate_page(pmap, va);
2920 * Remove the given range of addresses from the specified map.
2922 * It is assumed that the start and end are properly
2923 * rounded to the page size.
2926 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
2931 struct spglist free;
2935 * Perform an unsynchronized read. This is, however, safe.
2937 if (pmap->pm_stats.resident_count == 0)
2943 rw_wlock(&pvh_global_lock);
2948 * special handling of removing one page. a very
2949 * common operation and easy to short circuit some
2952 if ((sva + PAGE_SIZE == eva) &&
2953 ((pmap->pm_pdir[(sva >> PDRSHIFT)] & PG_PS) == 0)) {
2954 pmap_remove_page(pmap, sva, &free);
2958 for (; sva < eva; sva = pdnxt) {
2962 * Calculate index for next page table.
2964 pdnxt = (sva + NBPDR) & ~PDRMASK;
2967 if (pmap->pm_stats.resident_count == 0)
2970 pdirindex = sva >> PDRSHIFT;
2971 ptpaddr = pmap->pm_pdir[pdirindex];
2974 * Weed out invalid mappings. Note: we assume that the page
2975 * directory table is always allocated, and in kernel virtual.
2981 * Check for large page.
2983 if ((ptpaddr & PG_PS) != 0) {
2985 * Are we removing the entire large page? If not,
2986 * demote the mapping and fall through.
2988 if (sva + NBPDR == pdnxt && eva >= pdnxt) {
2990 * The TLB entry for a PG_G mapping is
2991 * invalidated by pmap_remove_pde().
2993 if ((ptpaddr & PG_G) == 0)
2995 pmap_remove_pde(pmap,
2996 &pmap->pm_pdir[pdirindex], sva, &free);
2998 } else if (!pmap_demote_pde(pmap,
2999 &pmap->pm_pdir[pdirindex], sva)) {
3000 /* The large page mapping was destroyed. */
3006 * Limit our scan to either the end of the va represented
3007 * by the current page table page, or to the end of the
3008 * range being removed.
3013 for (pte = pmap_pte_quick(pmap, sva); sva != pdnxt; pte++,
3019 * The TLB entry for a PG_G mapping is invalidated
3020 * by pmap_remove_pte().
3022 if ((*pte & PG_G) == 0)
3024 if (pmap_remove_pte(pmap, pte, sva, &free))
3031 pmap_invalidate_all(pmap);
3032 rw_wunlock(&pvh_global_lock);
3034 pmap_free_zero_pages(&free);
3038 * Routine: pmap_remove_all
3040 * Removes this physical page from
3041 * all physical maps in which it resides.
3042 * Reflects back modify bits to the pager.
3045 * Original versions of this routine were very
3046 * inefficient because they iteratively called
3047 * pmap_remove (slow...)
3051 pmap_remove_all(vm_page_t m)
3053 struct md_page *pvh;
3056 pt_entry_t *pte, tpte;
3059 struct spglist free;
3061 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3062 ("pmap_remove_all: page %p is not managed", m));
3064 rw_wlock(&pvh_global_lock);
3066 if ((m->flags & PG_FICTITIOUS) != 0)
3067 goto small_mappings;
3068 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3069 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
3073 pde = pmap_pde(pmap, va);
3074 (void)pmap_demote_pde(pmap, pde, va);
3078 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
3081 pmap->pm_stats.resident_count--;
3082 pde = pmap_pde(pmap, pv->pv_va);
3083 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
3084 " a 4mpage in page %p's pv list", m));
3085 pte = pmap_pte_quick(pmap, pv->pv_va);
3086 tpte = pte_load_clear(pte);
3087 KASSERT(tpte != 0, ("pmap_remove_all: pmap %p va %x zero pte",
3090 pmap->pm_stats.wired_count--;
3092 vm_page_aflag_set(m, PGA_REFERENCED);
3095 * Update the vm_page_t clean and reference bits.
3097 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3099 pmap_unuse_pt(pmap, pv->pv_va, &free);
3100 pmap_invalidate_page(pmap, pv->pv_va);
3101 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
3102 free_pv_entry(pmap, pv);
3105 vm_page_aflag_clear(m, PGA_WRITEABLE);
3107 rw_wunlock(&pvh_global_lock);
3108 pmap_free_zero_pages(&free);
3112 * pmap_protect_pde: do the things to protect a 4mpage in a process
3115 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
3117 pd_entry_t newpde, oldpde;
3118 vm_offset_t eva, va;
3120 boolean_t anychanged;
3122 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3123 KASSERT((sva & PDRMASK) == 0,
3124 ("pmap_protect_pde: sva is not 4mpage aligned"));
3127 oldpde = newpde = *pde;
3128 if (oldpde & PG_MANAGED) {
3130 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
3131 va < eva; va += PAGE_SIZE, m++)
3132 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
3135 if ((prot & VM_PROT_WRITE) == 0)
3136 newpde &= ~(PG_RW | PG_M);
3138 if ((prot & VM_PROT_EXECUTE) == 0)
3141 if (newpde != oldpde) {
3142 if (!pde_cmpset(pde, oldpde, newpde))
3145 pmap_invalidate_page(pmap, sva);
3149 return (anychanged);
3153 * Set the physical protection on the
3154 * specified range of this map as requested.
3157 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
3162 boolean_t anychanged, pv_lists_locked;
3164 if ((prot & VM_PROT_READ) == VM_PROT_NONE) {
3165 pmap_remove(pmap, sva, eva);
3170 if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
3171 (VM_PROT_WRITE|VM_PROT_EXECUTE))
3174 if (prot & VM_PROT_WRITE)
3178 if (pmap_is_current(pmap))
3179 pv_lists_locked = FALSE;
3181 pv_lists_locked = TRUE;
3183 rw_wlock(&pvh_global_lock);
3189 for (; sva < eva; sva = pdnxt) {
3190 pt_entry_t obits, pbits;
3193 pdnxt = (sva + NBPDR) & ~PDRMASK;
3197 pdirindex = sva >> PDRSHIFT;
3198 ptpaddr = pmap->pm_pdir[pdirindex];
3201 * Weed out invalid mappings. Note: we assume that the page
3202 * directory table is always allocated, and in kernel virtual.
3208 * Check for large page.
3210 if ((ptpaddr & PG_PS) != 0) {
3212 * Are we protecting the entire large page? If not,
3213 * demote the mapping and fall through.
3215 if (sva + NBPDR == pdnxt && eva >= pdnxt) {
3217 * The TLB entry for a PG_G mapping is
3218 * invalidated by pmap_protect_pde().
3220 if (pmap_protect_pde(pmap,
3221 &pmap->pm_pdir[pdirindex], sva, prot))
3225 if (!pv_lists_locked) {
3226 pv_lists_locked = TRUE;
3227 if (!rw_try_wlock(&pvh_global_lock)) {
3229 pmap_invalidate_all(
3236 if (!pmap_demote_pde(pmap,
3237 &pmap->pm_pdir[pdirindex], sva)) {
3239 * The large page mapping was
3250 for (pte = pmap_pte_quick(pmap, sva); sva != pdnxt; pte++,
3256 * Regardless of whether a pte is 32 or 64 bits in
3257 * size, PG_RW, PG_A, and PG_M are among the least
3258 * significant 32 bits.
3260 obits = pbits = *pte;
3261 if ((pbits & PG_V) == 0)
3264 if ((prot & VM_PROT_WRITE) == 0) {
3265 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
3266 (PG_MANAGED | PG_M | PG_RW)) {
3267 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
3270 pbits &= ~(PG_RW | PG_M);
3273 if ((prot & VM_PROT_EXECUTE) == 0)
3277 if (pbits != obits) {
3279 if (!atomic_cmpset_64(pte, obits, pbits))
3282 if (!atomic_cmpset_int((u_int *)pte, obits,
3287 pmap_invalidate_page(pmap, sva);
3294 pmap_invalidate_all(pmap);
3295 if (pv_lists_locked) {
3297 rw_wunlock(&pvh_global_lock);
3303 * Tries to promote the 512 or 1024, contiguous 4KB page mappings that are
3304 * within a single page table page (PTP) to a single 2- or 4MB page mapping.
3305 * For promotion to occur, two conditions must be met: (1) the 4KB page
3306 * mappings must map aligned, contiguous physical memory and (2) the 4KB page
3307 * mappings must have identical characteristics.
3309 * Managed (PG_MANAGED) mappings within the kernel address space are not
3310 * promoted. The reason is that kernel PDEs are replicated in each pmap but
3311 * pmap_clear_ptes() and pmap_ts_referenced() only read the PDE from the kernel
3315 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3318 pt_entry_t *firstpte, oldpte, pa, *pte;
3319 vm_offset_t oldpteva;
3322 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3325 * Examine the first PTE in the specified PTP. Abort if this PTE is
3326 * either invalid, unused, or does not map the first 4KB physical page
3327 * within a 2- or 4MB page.
3329 firstpte = pmap_pte_quick(pmap, trunc_4mpage(va));
3332 if ((newpde & ((PG_FRAME & PDRMASK) | PG_A | PG_V)) != (PG_A | PG_V)) {
3333 pmap_pde_p_failures++;
3334 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#x"
3335 " in pmap %p", va, pmap);
3338 if ((*firstpte & PG_MANAGED) != 0 && pmap == kernel_pmap) {
3339 pmap_pde_p_failures++;
3340 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#x"
3341 " in pmap %p", va, pmap);
3344 if ((newpde & (PG_M | PG_RW)) == PG_RW) {
3346 * When PG_M is already clear, PG_RW can be cleared without
3347 * a TLB invalidation.
3349 if (!atomic_cmpset_int((u_int *)firstpte, newpde, newpde &
3356 * Examine each of the other PTEs in the specified PTP. Abort if this
3357 * PTE maps an unexpected 4KB physical page or does not have identical
3358 * characteristics to the first PTE.
3360 pa = (newpde & (PG_PS_FRAME | PG_A | PG_V)) + NBPDR - PAGE_SIZE;
3361 for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
3364 if ((oldpte & (PG_FRAME | PG_A | PG_V)) != pa) {
3365 pmap_pde_p_failures++;
3366 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#x"
3367 " in pmap %p", va, pmap);
3370 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
3372 * When PG_M is already clear, PG_RW can be cleared
3373 * without a TLB invalidation.
3375 if (!atomic_cmpset_int((u_int *)pte, oldpte,
3379 oldpteva = (oldpte & PG_FRAME & PDRMASK) |
3381 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#x"
3382 " in pmap %p", oldpteva, pmap);
3384 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
3385 pmap_pde_p_failures++;
3386 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#x"
3387 " in pmap %p", va, pmap);
3394 * Save the page table page in its current state until the PDE
3395 * mapping the superpage is demoted by pmap_demote_pde() or
3396 * destroyed by pmap_remove_pde().
3398 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
3399 KASSERT(mpte >= vm_page_array &&
3400 mpte < &vm_page_array[vm_page_array_size],
3401 ("pmap_promote_pde: page table page is out of range"));
3402 KASSERT(mpte->pindex == va >> PDRSHIFT,
3403 ("pmap_promote_pde: page table page's pindex is wrong"));
3404 if (pmap_insert_pt_page(pmap, mpte)) {
3405 pmap_pde_p_failures++;
3407 "pmap_promote_pde: failure for va %#x in pmap %p", va,
3413 * Promote the pv entries.
3415 if ((newpde & PG_MANAGED) != 0)
3416 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME);
3419 * Propagate the PAT index to its proper position.
3421 if ((newpde & PG_PTE_PAT) != 0)
3422 newpde ^= PG_PDE_PAT | PG_PTE_PAT;
3425 * Map the superpage.
3427 if (workaround_erratum383)
3428 pmap_update_pde(pmap, va, pde, PG_PS | newpde);
3429 else if (pmap == kernel_pmap)
3430 pmap_kenter_pde(va, PG_PS | newpde);
3432 pde_store(pde, PG_PS | newpde);
3434 pmap_pde_promotions++;
3435 CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#x"
3436 " in pmap %p", va, pmap);
3440 * Insert the given physical page (p) at
3441 * the specified virtual address (v) in the
3442 * target physical map with the protection requested.
3444 * If specified, the page will be wired down, meaning
3445 * that the related pte can not be reclaimed.
3447 * NB: This is the only routine which MAY NOT lazy-evaluate
3448 * or lose information. That is, this routine must actually
3449 * insert this page into the given map NOW.
3452 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
3453 u_int flags, int8_t psind)
3457 pt_entry_t newpte, origpte;
3461 boolean_t invlva, wired;
3463 va = trunc_page(va);
3465 wired = (flags & PMAP_ENTER_WIRED) != 0;
3467 KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
3468 KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
3469 ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%x)",
3471 if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_xbusied(m))
3472 VM_OBJECT_ASSERT_LOCKED(m->object);
3474 rw_wlock(&pvh_global_lock);
3479 * In the case that a page table page is not
3480 * resident, we are creating it here.
3482 if (va < VM_MAXUSER_ADDRESS) {
3483 mpte = pmap_allocpte(pmap, va, flags);
3485 KASSERT((flags & PMAP_ENTER_NOSLEEP) != 0,
3486 ("pmap_allocpte failed with sleep allowed"));
3488 rw_wunlock(&pvh_global_lock);
3490 return (KERN_RESOURCE_SHORTAGE);
3494 pde = pmap_pde(pmap, va);
3495 if ((*pde & PG_PS) != 0)
3496 panic("pmap_enter: attempted pmap_enter on 4MB page");
3497 pte = pmap_pte_quick(pmap, va);
3500 * Page Directory table entry not valid, we need a new PT page
3503 panic("pmap_enter: invalid page directory pdir=%#jx, va=%#x",
3504 (uintmax_t)pmap->pm_pdir[PTDPTDI], va);
3507 pa = VM_PAGE_TO_PHYS(m);
3510 opa = origpte & PG_FRAME;
3513 * Mapping has not changed, must be protection or wiring change.
3515 if (origpte && (opa == pa)) {
3517 * Wiring change, just update stats. We don't worry about
3518 * wiring PT pages as they remain resident as long as there
3519 * are valid mappings in them. Hence, if a user page is wired,
3520 * the PT page will be also.
3522 if (wired && ((origpte & PG_W) == 0))
3523 pmap->pm_stats.wired_count++;
3524 else if (!wired && (origpte & PG_W))
3525 pmap->pm_stats.wired_count--;
3528 * Remove extra pte reference
3533 if (origpte & PG_MANAGED) {
3543 * Mapping has changed, invalidate old range and fall through to
3544 * handle validating new mapping.
3548 pmap->pm_stats.wired_count--;
3549 if (origpte & PG_MANAGED) {
3550 om = PHYS_TO_VM_PAGE(opa);
3551 pv = pmap_pvh_remove(&om->md, pmap, va);
3555 KASSERT(mpte->wire_count > 0,
3556 ("pmap_enter: missing reference to page table page,"
3560 pmap->pm_stats.resident_count++;
3563 * Enter on the PV list if part of our managed memory.
3565 if ((m->oflags & VPO_UNMANAGED) == 0) {
3566 KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva,
3567 ("pmap_enter: managed mapping within the clean submap"));
3569 pv = get_pv_entry(pmap, FALSE);
3571 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3573 } else if (pv != NULL)
3574 free_pv_entry(pmap, pv);
3577 * Increment counters
3580 pmap->pm_stats.wired_count++;
3584 * Now validate mapping with desired protection/wiring.
3586 newpte = (pt_entry_t)(pa | pmap_cache_bits(m->md.pat_mode, 0) | PG_V);
3587 if ((prot & VM_PROT_WRITE) != 0) {
3589 if ((newpte & PG_MANAGED) != 0)
3590 vm_page_aflag_set(m, PGA_WRITEABLE);
3593 if ((prot & VM_PROT_EXECUTE) == 0)
3598 if (va < VM_MAXUSER_ADDRESS)
3600 if (pmap == kernel_pmap)
3604 * if the mapping or permission bits are different, we need
3605 * to update the pte.
3607 if ((origpte & ~(PG_M|PG_A)) != newpte) {
3609 if ((flags & VM_PROT_WRITE) != 0)
3611 if (origpte & PG_V) {
3613 origpte = pte_load_store(pte, newpte);
3614 if (origpte & PG_A) {
3615 if (origpte & PG_MANAGED)
3616 vm_page_aflag_set(om, PGA_REFERENCED);
3617 if (opa != VM_PAGE_TO_PHYS(m))
3620 if ((origpte & PG_NX) == 0 &&
3621 (newpte & PG_NX) != 0)
3625 if ((origpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
3626 if ((origpte & PG_MANAGED) != 0)
3628 if ((prot & VM_PROT_WRITE) == 0)
3631 if ((origpte & PG_MANAGED) != 0 &&
3632 TAILQ_EMPTY(&om->md.pv_list) &&
3633 ((om->flags & PG_FICTITIOUS) != 0 ||
3634 TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
3635 vm_page_aflag_clear(om, PGA_WRITEABLE);
3637 pmap_invalidate_page(pmap, va);
3639 pte_store(pte, newpte);
3643 * If both the page table page and the reservation are fully
3644 * populated, then attempt promotion.
3646 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
3647 pg_ps_enabled && (m->flags & PG_FICTITIOUS) == 0 &&
3648 vm_reserv_level_iffullpop(m) == 0)
3649 pmap_promote_pde(pmap, pde, va);
3652 rw_wunlock(&pvh_global_lock);
3654 return (KERN_SUCCESS);
3658 * Tries to create a 2- or 4MB page mapping. Returns TRUE if successful and
3659 * FALSE otherwise. Fails if (1) a page table page cannot be allocated without
3660 * blocking, (2) a mapping already exists at the specified virtual address, or
3661 * (3) a pv entry cannot be allocated without reclaiming another pv entry.
3664 pmap_enter_pde(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
3666 pd_entry_t *pde, newpde;
3668 rw_assert(&pvh_global_lock, RA_WLOCKED);
3669 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3670 pde = pmap_pde(pmap, va);
3672 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
3673 " in pmap %p", va, pmap);
3676 newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(m->md.pat_mode, 1) |
3678 if ((m->oflags & VPO_UNMANAGED) == 0) {
3679 newpde |= PG_MANAGED;
3682 * Abort this mapping if its PV entry could not be created.
3684 if (!pmap_pv_insert_pde(pmap, va, VM_PAGE_TO_PHYS(m))) {
3685 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
3686 " in pmap %p", va, pmap);
3691 if ((prot & VM_PROT_EXECUTE) == 0)
3694 if (va < VM_MAXUSER_ADDRESS)
3698 * Increment counters.
3700 pmap->pm_stats.resident_count += NBPDR / PAGE_SIZE;
3703 * Map the superpage.
3705 pde_store(pde, newpde);
3707 pmap_pde_mappings++;
3708 CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx"
3709 " in pmap %p", va, pmap);
3714 * Maps a sequence of resident pages belonging to the same object.
3715 * The sequence begins with the given page m_start. This page is
3716 * mapped at the given virtual address start. Each subsequent page is
3717 * mapped at a virtual address that is offset from start by the same
3718 * amount as the page is offset from m_start within the object. The
3719 * last page in the sequence is the page with the largest offset from
3720 * m_start that can be mapped at a virtual address less than the given
3721 * virtual address end. Not every virtual page between start and end
3722 * is mapped; only those for which a resident page exists with the
3723 * corresponding offset from m_start are mapped.
3726 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
3727 vm_page_t m_start, vm_prot_t prot)
3731 vm_pindex_t diff, psize;
3733 VM_OBJECT_ASSERT_LOCKED(m_start->object);
3735 psize = atop(end - start);
3738 rw_wlock(&pvh_global_lock);
3740 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
3741 va = start + ptoa(diff);
3742 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
3743 m->psind == 1 && pg_ps_enabled &&
3744 pmap_enter_pde(pmap, va, m, prot))
3745 m = &m[NBPDR / PAGE_SIZE - 1];
3747 mpte = pmap_enter_quick_locked(pmap, va, m, prot,
3749 m = TAILQ_NEXT(m, listq);
3751 rw_wunlock(&pvh_global_lock);
3756 * this code makes some *MAJOR* assumptions:
3757 * 1. Current pmap & pmap exists.
3760 * 4. No page table pages.
3761 * but is *MUCH* faster than pmap_enter...
3765 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
3768 rw_wlock(&pvh_global_lock);
3770 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL);
3771 rw_wunlock(&pvh_global_lock);
3776 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
3777 vm_prot_t prot, vm_page_t mpte)
3781 struct spglist free;
3783 KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
3784 (m->oflags & VPO_UNMANAGED) != 0,
3785 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
3786 rw_assert(&pvh_global_lock, RA_WLOCKED);
3787 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3790 * In the case that a page table page is not
3791 * resident, we are creating it here.
3793 if (va < VM_MAXUSER_ADDRESS) {
3798 * Calculate pagetable page index
3800 ptepindex = va >> PDRSHIFT;
3801 if (mpte && (mpte->pindex == ptepindex)) {
3805 * Get the page directory entry
3807 ptepa = pmap->pm_pdir[ptepindex];
3810 * If the page table page is mapped, we just increment
3811 * the hold count, and activate it.
3816 mpte = PHYS_TO_VM_PAGE(ptepa & PG_FRAME);
3819 mpte = _pmap_allocpte(pmap, ptepindex,
3820 PMAP_ENTER_NOSLEEP);
3830 * This call to vtopte makes the assumption that we are
3831 * entering the page into the current pmap. In order to support
3832 * quick entry into any pmap, one would likely use pmap_pte_quick.
3833 * But that isn't as quick as vtopte.
3845 * Enter on the PV list if part of our managed memory.
3847 if ((m->oflags & VPO_UNMANAGED) == 0 &&
3848 !pmap_try_insert_pv_entry(pmap, va, m)) {
3851 if (pmap_unwire_ptp(pmap, mpte, &free)) {
3852 pmap_invalidate_page(pmap, va);
3853 pmap_free_zero_pages(&free);
3862 * Increment counters
3864 pmap->pm_stats.resident_count++;
3866 pa = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(m->md.pat_mode, 0);
3868 if ((prot & VM_PROT_EXECUTE) == 0)
3873 * Now validate mapping with RO protection
3875 if ((m->oflags & VPO_UNMANAGED) != 0)
3876 pte_store(pte, pa | PG_V | PG_U);
3878 pte_store(pte, pa | PG_V | PG_U | PG_MANAGED);
3883 * Make a temporary mapping for a physical address. This is only intended
3884 * to be used for panic dumps.
3887 pmap_kenter_temporary(vm_paddr_t pa, int i)
3891 va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
3892 pmap_kenter(va, pa);
3894 return ((void *)crashdumpmap);
3898 * This code maps large physical mmap regions into the
3899 * processor address space. Note that some shortcuts
3900 * are taken, but the code works.
3903 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
3904 vm_pindex_t pindex, vm_size_t size)
3907 vm_paddr_t pa, ptepa;
3911 VM_OBJECT_ASSERT_WLOCKED(object);
3912 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
3913 ("pmap_object_init_pt: non-device object"));
3915 (addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
3916 if (!vm_object_populate(object, pindex, pindex + atop(size)))
3918 p = vm_page_lookup(object, pindex);
3919 KASSERT(p->valid == VM_PAGE_BITS_ALL,
3920 ("pmap_object_init_pt: invalid page %p", p));
3921 pat_mode = p->md.pat_mode;
3924 * Abort the mapping if the first page is not physically
3925 * aligned to a 2/4MB page boundary.
3927 ptepa = VM_PAGE_TO_PHYS(p);
3928 if (ptepa & (NBPDR - 1))
3932 * Skip the first page. Abort the mapping if the rest of
3933 * the pages are not physically contiguous or have differing
3934 * memory attributes.
3936 p = TAILQ_NEXT(p, listq);
3937 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
3939 KASSERT(p->valid == VM_PAGE_BITS_ALL,
3940 ("pmap_object_init_pt: invalid page %p", p));
3941 if (pa != VM_PAGE_TO_PHYS(p) ||
3942 pat_mode != p->md.pat_mode)
3944 p = TAILQ_NEXT(p, listq);
3948 * Map using 2/4MB pages. Since "ptepa" is 2/4M aligned and
3949 * "size" is a multiple of 2/4M, adding the PAT setting to
3950 * "pa" will not affect the termination of this loop.
3953 for (pa = ptepa | pmap_cache_bits(pat_mode, 1); pa < ptepa +
3954 size; pa += NBPDR) {
3955 pde = pmap_pde(pmap, addr);
3957 pde_store(pde, pa | PG_PS | PG_M | PG_A |
3958 PG_U | PG_RW | PG_V);
3959 pmap->pm_stats.resident_count += NBPDR /
3961 pmap_pde_mappings++;
3963 /* Else continue on if the PDE is already valid. */
3971 * Routine: pmap_change_wiring
3972 * Function: Change the wiring attribute for a map/virtual-address
3974 * In/out conditions:
3975 * The mapping must already exist in the pmap.
3978 pmap_change_wiring(pmap_t pmap, vm_offset_t va, boolean_t wired)
3982 boolean_t are_queues_locked;
3984 are_queues_locked = FALSE;
3987 pde = pmap_pde(pmap, va);
3988 if ((*pde & PG_PS) != 0) {
3989 if (!wired != ((*pde & PG_W) == 0)) {
3990 if (!are_queues_locked) {
3991 are_queues_locked = TRUE;
3992 if (!rw_try_wlock(&pvh_global_lock)) {
3994 rw_wlock(&pvh_global_lock);
3998 if (!pmap_demote_pde(pmap, pde, va))
3999 panic("pmap_change_wiring: demotion failed");
4003 pte = pmap_pte(pmap, va);
4005 if (wired && !pmap_pte_w(pte))
4006 pmap->pm_stats.wired_count++;
4007 else if (!wired && pmap_pte_w(pte))
4008 pmap->pm_stats.wired_count--;
4011 * Wiring is not a hardware characteristic so there is no need to
4014 pmap_pte_set_w(pte, wired);
4015 pmap_pte_release(pte);
4017 if (are_queues_locked)
4018 rw_wunlock(&pvh_global_lock);
4025 * Copy the range specified by src_addr/len
4026 * from the source map to the range dst_addr/len
4027 * in the destination map.
4029 * This routine is only advisory and need not do anything.
4033 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
4034 vm_offset_t src_addr)
4036 struct spglist free;
4038 vm_offset_t end_addr = src_addr + len;
4041 if (dst_addr != src_addr)
4044 if (!pmap_is_current(src_pmap))
4047 rw_wlock(&pvh_global_lock);
4048 if (dst_pmap < src_pmap) {
4049 PMAP_LOCK(dst_pmap);
4050 PMAP_LOCK(src_pmap);
4052 PMAP_LOCK(src_pmap);
4053 PMAP_LOCK(dst_pmap);
4056 for (addr = src_addr; addr < end_addr; addr = pdnxt) {
4057 pt_entry_t *src_pte, *dst_pte;
4058 vm_page_t dstmpte, srcmpte;
4059 pd_entry_t srcptepaddr;
4062 KASSERT(addr < UPT_MIN_ADDRESS,
4063 ("pmap_copy: invalid to pmap_copy page tables"));
4065 pdnxt = (addr + NBPDR) & ~PDRMASK;
4068 ptepindex = addr >> PDRSHIFT;
4070 srcptepaddr = src_pmap->pm_pdir[ptepindex];
4071 if (srcptepaddr == 0)
4074 if (srcptepaddr & PG_PS) {
4075 if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
4077 if (dst_pmap->pm_pdir[ptepindex] == 0 &&
4078 ((srcptepaddr & PG_MANAGED) == 0 ||
4079 pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr &
4081 dst_pmap->pm_pdir[ptepindex] = srcptepaddr &
4083 dst_pmap->pm_stats.resident_count +=
4089 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr & PG_FRAME);
4090 KASSERT(srcmpte->wire_count > 0,
4091 ("pmap_copy: source page table page is unused"));
4093 if (pdnxt > end_addr)
4096 src_pte = vtopte(addr);
4097 while (addr < pdnxt) {
4101 * we only virtual copy managed pages
4103 if ((ptetemp & PG_MANAGED) != 0) {
4104 dstmpte = pmap_allocpte(dst_pmap, addr,
4105 PMAP_ENTER_NOSLEEP);
4106 if (dstmpte == NULL)
4108 dst_pte = pmap_pte_quick(dst_pmap, addr);
4109 if (*dst_pte == 0 &&
4110 pmap_try_insert_pv_entry(dst_pmap, addr,
4111 PHYS_TO_VM_PAGE(ptetemp & PG_FRAME))) {
4113 * Clear the wired, modified, and
4114 * accessed (referenced) bits
4117 *dst_pte = ptetemp & ~(PG_W | PG_M |
4119 dst_pmap->pm_stats.resident_count++;
4122 if (pmap_unwire_ptp(dst_pmap, dstmpte,
4124 pmap_invalidate_page(dst_pmap,
4126 pmap_free_zero_pages(&free);
4130 if (dstmpte->wire_count >= srcmpte->wire_count)
4139 rw_wunlock(&pvh_global_lock);
4140 PMAP_UNLOCK(src_pmap);
4141 PMAP_UNLOCK(dst_pmap);
4144 static __inline void
4145 pagezero(void *page)
4147 #if defined(I686_CPU)
4148 if (cpu_class == CPUCLASS_686) {
4149 #if defined(CPU_ENABLE_SSE)
4150 if (cpu_feature & CPUID_SSE2)
4151 sse2_pagezero(page);
4154 i686_pagezero(page);
4157 bzero(page, PAGE_SIZE);
4161 * pmap_zero_page zeros the specified hardware page by mapping
4162 * the page into KVM and using bzero to clear its contents.
4165 pmap_zero_page(vm_page_t m)
4167 struct sysmaps *sysmaps;
4169 sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
4170 mtx_lock(&sysmaps->lock);
4171 if (*sysmaps->CMAP2)
4172 panic("pmap_zero_page: CMAP2 busy");
4174 *sysmaps->CMAP2 = PG_V | PG_RW | VM_PAGE_TO_PHYS(m) | PG_A | PG_M |
4175 pmap_cache_bits(m->md.pat_mode, 0);
4176 invlcaddr(sysmaps->CADDR2);
4177 pagezero(sysmaps->CADDR2);
4178 *sysmaps->CMAP2 = 0;
4180 mtx_unlock(&sysmaps->lock);
4184 * pmap_zero_page_area zeros the specified hardware page by mapping
4185 * the page into KVM and using bzero to clear its contents.
4187 * off and size may not cover an area beyond a single hardware page.
4190 pmap_zero_page_area(vm_page_t m, int off, int size)
4192 struct sysmaps *sysmaps;
4194 sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
4195 mtx_lock(&sysmaps->lock);
4196 if (*sysmaps->CMAP2)
4197 panic("pmap_zero_page_area: CMAP2 busy");
4199 *sysmaps->CMAP2 = PG_V | PG_RW | VM_PAGE_TO_PHYS(m) | PG_A | PG_M |
4200 pmap_cache_bits(m->md.pat_mode, 0);
4201 invlcaddr(sysmaps->CADDR2);
4202 if (off == 0 && size == PAGE_SIZE)
4203 pagezero(sysmaps->CADDR2);
4205 bzero((char *)sysmaps->CADDR2 + off, size);
4206 *sysmaps->CMAP2 = 0;
4208 mtx_unlock(&sysmaps->lock);
4212 * pmap_zero_page_idle zeros the specified hardware page by mapping
4213 * the page into KVM and using bzero to clear its contents. This
4214 * is intended to be called from the vm_pagezero process only and
4218 pmap_zero_page_idle(vm_page_t m)
4222 panic("pmap_zero_page_idle: CMAP3 busy");
4224 *CMAP3 = PG_V | PG_RW | VM_PAGE_TO_PHYS(m) | PG_A | PG_M |
4225 pmap_cache_bits(m->md.pat_mode, 0);
4233 * pmap_copy_page copies the specified (machine independent)
4234 * page by mapping the page into virtual memory and using
4235 * bcopy to copy the page, one machine dependent page at a
4239 pmap_copy_page(vm_page_t src, vm_page_t dst)
4241 struct sysmaps *sysmaps;
4243 sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
4244 mtx_lock(&sysmaps->lock);
4245 if (*sysmaps->CMAP1)
4246 panic("pmap_copy_page: CMAP1 busy");
4247 if (*sysmaps->CMAP2)
4248 panic("pmap_copy_page: CMAP2 busy");
4250 *sysmaps->CMAP1 = PG_V | VM_PAGE_TO_PHYS(src) | PG_A |
4251 pmap_cache_bits(src->md.pat_mode, 0);
4252 invlcaddr(sysmaps->CADDR1);
4253 *sysmaps->CMAP2 = PG_V | PG_RW | VM_PAGE_TO_PHYS(dst) | PG_A | PG_M |
4254 pmap_cache_bits(dst->md.pat_mode, 0);
4255 invlcaddr(sysmaps->CADDR2);
4256 bcopy(sysmaps->CADDR1, sysmaps->CADDR2, PAGE_SIZE);
4257 *sysmaps->CMAP1 = 0;
4258 *sysmaps->CMAP2 = 0;
4260 mtx_unlock(&sysmaps->lock);
4263 int unmapped_buf_allowed = 1;
4266 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
4267 vm_offset_t b_offset, int xfersize)
4269 struct sysmaps *sysmaps;
4270 vm_page_t a_pg, b_pg;
4272 vm_offset_t a_pg_offset, b_pg_offset;
4275 sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
4276 mtx_lock(&sysmaps->lock);
4277 if (*sysmaps->CMAP1 != 0)
4278 panic("pmap_copy_pages: CMAP1 busy");
4279 if (*sysmaps->CMAP2 != 0)
4280 panic("pmap_copy_pages: CMAP2 busy");
4282 while (xfersize > 0) {
4283 a_pg = ma[a_offset >> PAGE_SHIFT];
4284 a_pg_offset = a_offset & PAGE_MASK;
4285 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
4286 b_pg = mb[b_offset >> PAGE_SHIFT];
4287 b_pg_offset = b_offset & PAGE_MASK;
4288 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
4289 *sysmaps->CMAP1 = PG_V | VM_PAGE_TO_PHYS(a_pg) | PG_A |
4290 pmap_cache_bits(a_pg->md.pat_mode, 0);
4291 invlcaddr(sysmaps->CADDR1);
4292 *sysmaps->CMAP2 = PG_V | PG_RW | VM_PAGE_TO_PHYS(b_pg) | PG_A |
4293 PG_M | pmap_cache_bits(b_pg->md.pat_mode, 0);
4294 invlcaddr(sysmaps->CADDR2);
4295 a_cp = sysmaps->CADDR1 + a_pg_offset;
4296 b_cp = sysmaps->CADDR2 + b_pg_offset;
4297 bcopy(a_cp, b_cp, cnt);
4302 *sysmaps->CMAP1 = 0;
4303 *sysmaps->CMAP2 = 0;
4305 mtx_unlock(&sysmaps->lock);
4309 * Returns true if the pmap's pv is one of the first
4310 * 16 pvs linked to from this page. This count may
4311 * be changed upwards or downwards in the future; it
4312 * is only necessary that true be returned for a small
4313 * subset of pmaps for proper page aging.
4316 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
4318 struct md_page *pvh;
4323 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4324 ("pmap_page_exists_quick: page %p is not managed", m));
4326 rw_wlock(&pvh_global_lock);
4327 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
4328 if (PV_PMAP(pv) == pmap) {
4336 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
4337 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
4338 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
4339 if (PV_PMAP(pv) == pmap) {
4348 rw_wunlock(&pvh_global_lock);
4353 * pmap_page_wired_mappings:
4355 * Return the number of managed mappings to the given physical page
4359 pmap_page_wired_mappings(vm_page_t m)
4364 if ((m->oflags & VPO_UNMANAGED) != 0)
4366 rw_wlock(&pvh_global_lock);
4367 count = pmap_pvh_wired_mappings(&m->md, count);
4368 if ((m->flags & PG_FICTITIOUS) == 0) {
4369 count = pmap_pvh_wired_mappings(pa_to_pvh(VM_PAGE_TO_PHYS(m)),
4372 rw_wunlock(&pvh_global_lock);
4377 * pmap_pvh_wired_mappings:
4379 * Return the updated number "count" of managed mappings that are wired.
4382 pmap_pvh_wired_mappings(struct md_page *pvh, int count)
4388 rw_assert(&pvh_global_lock, RA_WLOCKED);
4390 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
4393 pte = pmap_pte_quick(pmap, pv->pv_va);
4394 if ((*pte & PG_W) != 0)
4403 * Returns TRUE if the given page is mapped individually or as part of
4404 * a 4mpage. Otherwise, returns FALSE.
4407 pmap_page_is_mapped(vm_page_t m)
4411 if ((m->oflags & VPO_UNMANAGED) != 0)
4413 rw_wlock(&pvh_global_lock);
4414 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
4415 ((m->flags & PG_FICTITIOUS) == 0 &&
4416 !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
4417 rw_wunlock(&pvh_global_lock);
4422 * Remove all pages from specified address space
4423 * this aids process exit speeds. Also, this code
4424 * is special cased for current process only, but
4425 * can have the more generic (and slightly slower)
4426 * mode enabled. This is much faster than pmap_remove
4427 * in the case of running down an entire address space.
4430 pmap_remove_pages(pmap_t pmap)
4432 pt_entry_t *pte, tpte;
4433 vm_page_t m, mpte, mt;
4435 struct md_page *pvh;
4436 struct pv_chunk *pc, *npc;
4437 struct spglist free;
4440 uint32_t inuse, bitmask;
4443 if (pmap != PCPU_GET(curpmap)) {
4444 printf("warning: pmap_remove_pages called with non-current pmap\n");
4448 rw_wlock(&pvh_global_lock);
4451 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
4452 KASSERT(pc->pc_pmap == pmap, ("Wrong pmap %p %p", pmap,
4455 for (field = 0; field < _NPCM; field++) {
4456 inuse = ~pc->pc_map[field] & pc_freemask[field];
4457 while (inuse != 0) {
4459 bitmask = 1UL << bit;
4460 idx = field * 32 + bit;
4461 pv = &pc->pc_pventry[idx];
4464 pte = pmap_pde(pmap, pv->pv_va);
4466 if ((tpte & PG_PS) == 0) {
4467 pte = vtopte(pv->pv_va);
4468 tpte = *pte & ~PG_PTE_PAT;
4473 "TPTE at %p IS ZERO @ VA %08x\n",
4479 * We cannot remove wired pages from a process' mapping at this time
4486 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
4487 KASSERT(m->phys_addr == (tpte & PG_FRAME),
4488 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
4489 m, (uintmax_t)m->phys_addr,
4492 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
4493 m < &vm_page_array[vm_page_array_size],
4494 ("pmap_remove_pages: bad tpte %#jx",
4500 * Update the vm_page_t clean/reference bits.
4502 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
4503 if ((tpte & PG_PS) != 0) {
4504 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
4511 PV_STAT(pv_entry_frees++);
4512 PV_STAT(pv_entry_spare++);
4514 pc->pc_map[field] |= bitmask;
4515 if ((tpte & PG_PS) != 0) {
4516 pmap->pm_stats.resident_count -= NBPDR / PAGE_SIZE;
4517 pvh = pa_to_pvh(tpte & PG_PS_FRAME);
4518 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
4519 if (TAILQ_EMPTY(&pvh->pv_list)) {
4520 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
4521 if (TAILQ_EMPTY(&mt->md.pv_list))
4522 vm_page_aflag_clear(mt, PGA_WRITEABLE);
4524 mpte = pmap_lookup_pt_page(pmap, pv->pv_va);
4526 pmap_remove_pt_page(pmap, mpte);
4527 pmap->pm_stats.resident_count--;
4528 KASSERT(mpte->wire_count == NPTEPG,
4529 ("pmap_remove_pages: pte page wire count error"));
4530 mpte->wire_count = 0;
4531 pmap_add_delayed_free_list(mpte, &free, FALSE);
4532 atomic_subtract_int(&cnt.v_wire_count, 1);
4535 pmap->pm_stats.resident_count--;
4536 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
4537 if (TAILQ_EMPTY(&m->md.pv_list) &&
4538 (m->flags & PG_FICTITIOUS) == 0) {
4539 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
4540 if (TAILQ_EMPTY(&pvh->pv_list))
4541 vm_page_aflag_clear(m, PGA_WRITEABLE);
4543 pmap_unuse_pt(pmap, pv->pv_va, &free);
4548 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
4553 pmap_invalidate_all(pmap);
4554 rw_wunlock(&pvh_global_lock);
4556 pmap_free_zero_pages(&free);
4562 * Return whether or not the specified physical page was modified
4563 * in any physical maps.
4566 pmap_is_modified(vm_page_t m)
4570 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4571 ("pmap_is_modified: page %p is not managed", m));
4574 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
4575 * concurrently set while the object is locked. Thus, if PGA_WRITEABLE
4576 * is clear, no PTEs can have PG_M set.
4578 VM_OBJECT_ASSERT_WLOCKED(m->object);
4579 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
4581 rw_wlock(&pvh_global_lock);
4582 rv = pmap_is_modified_pvh(&m->md) ||
4583 ((m->flags & PG_FICTITIOUS) == 0 &&
4584 pmap_is_modified_pvh(pa_to_pvh(VM_PAGE_TO_PHYS(m))));
4585 rw_wunlock(&pvh_global_lock);
4590 * Returns TRUE if any of the given mappings were used to modify
4591 * physical memory. Otherwise, returns FALSE. Both page and 2mpage
4592 * mappings are supported.
4595 pmap_is_modified_pvh(struct md_page *pvh)
4602 rw_assert(&pvh_global_lock, RA_WLOCKED);
4605 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
4608 pte = pmap_pte_quick(pmap, pv->pv_va);
4609 rv = (*pte & (PG_M | PG_RW)) == (PG_M | PG_RW);
4619 * pmap_is_prefaultable:
4621 * Return whether or not the specified virtual address is elgible
4625 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
4633 pde = pmap_pde(pmap, addr);
4634 if (*pde != 0 && (*pde & PG_PS) == 0) {
4643 * pmap_is_referenced:
4645 * Return whether or not the specified physical page was referenced
4646 * in any physical maps.
4649 pmap_is_referenced(vm_page_t m)
4653 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4654 ("pmap_is_referenced: page %p is not managed", m));
4655 rw_wlock(&pvh_global_lock);
4656 rv = pmap_is_referenced_pvh(&m->md) ||
4657 ((m->flags & PG_FICTITIOUS) == 0 &&
4658 pmap_is_referenced_pvh(pa_to_pvh(VM_PAGE_TO_PHYS(m))));
4659 rw_wunlock(&pvh_global_lock);
4664 * Returns TRUE if any of the given mappings were referenced and FALSE
4665 * otherwise. Both page and 4mpage mappings are supported.
4668 pmap_is_referenced_pvh(struct md_page *pvh)
4675 rw_assert(&pvh_global_lock, RA_WLOCKED);
4678 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
4681 pte = pmap_pte_quick(pmap, pv->pv_va);
4682 rv = (*pte & (PG_A | PG_V)) == (PG_A | PG_V);
4692 * Clear the write and modified bits in each of the given page's mappings.
4695 pmap_remove_write(vm_page_t m)
4697 struct md_page *pvh;
4698 pv_entry_t next_pv, pv;
4701 pt_entry_t oldpte, *pte;
4704 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4705 ("pmap_remove_write: page %p is not managed", m));
4708 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
4709 * set by another thread while the object is locked. Thus,
4710 * if PGA_WRITEABLE is clear, no page table entries need updating.
4712 VM_OBJECT_ASSERT_WLOCKED(m->object);
4713 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
4715 rw_wlock(&pvh_global_lock);
4717 if ((m->flags & PG_FICTITIOUS) != 0)
4718 goto small_mappings;
4719 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
4720 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
4724 pde = pmap_pde(pmap, va);
4725 if ((*pde & PG_RW) != 0)
4726 (void)pmap_demote_pde(pmap, pde, va);
4730 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
4733 pde = pmap_pde(pmap, pv->pv_va);
4734 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_write: found"
4735 " a 4mpage in page %p's pv list", m));
4736 pte = pmap_pte_quick(pmap, pv->pv_va);
4739 if ((oldpte & PG_RW) != 0) {
4741 * Regardless of whether a pte is 32 or 64 bits
4742 * in size, PG_RW and PG_M are among the least
4743 * significant 32 bits.
4745 if (!atomic_cmpset_int((u_int *)pte, oldpte,
4746 oldpte & ~(PG_RW | PG_M)))
4748 if ((oldpte & PG_M) != 0)
4750 pmap_invalidate_page(pmap, pv->pv_va);
4754 vm_page_aflag_clear(m, PGA_WRITEABLE);
4756 rw_wunlock(&pvh_global_lock);
4759 #define PMAP_TS_REFERENCED_MAX 5
4762 * pmap_ts_referenced:
4764 * Return a count of reference bits for a page, clearing those bits.
4765 * It is not necessary for every reference bit to be cleared, but it
4766 * is necessary that 0 only be returned when there are truly no
4767 * reference bits set.
4769 * XXX: The exact number of bits to check and clear is a matter that
4770 * should be tested and standardized at some point in the future for
4771 * optimal aging of shared pages.
4774 pmap_ts_referenced(vm_page_t m)
4776 struct md_page *pvh;
4784 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4785 ("pmap_ts_referenced: page %p is not managed", m));
4786 pa = VM_PAGE_TO_PHYS(m);
4787 pvh = pa_to_pvh(pa);
4788 rw_wlock(&pvh_global_lock);
4790 if ((m->flags & PG_FICTITIOUS) != 0 ||
4791 (pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
4792 goto small_mappings;
4797 pde = pmap_pde(pmap, pv->pv_va);
4798 if ((*pde & PG_A) != 0) {
4800 * Since this reference bit is shared by either 1024
4801 * or 512 4KB pages, it should not be cleared every
4802 * time it is tested. Apply a simple "hash" function
4803 * on the physical page number, the virtual superpage
4804 * number, and the pmap address to select one 4KB page
4805 * out of the 1024 or 512 on which testing the
4806 * reference bit will result in clearing that bit.
4807 * This function is designed to avoid the selection of
4808 * the same 4KB page for every 2- or 4MB page mapping.
4810 * On demotion, a mapping that hasn't been referenced
4811 * is simply destroyed. To avoid the possibility of a
4812 * subsequent page fault on a demoted wired mapping,
4813 * always leave its reference bit set. Moreover,
4814 * since the superpage is wired, the current state of
4815 * its reference bit won't affect page replacement.
4817 if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
4818 (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
4819 (*pde & PG_W) == 0) {
4820 atomic_clear_int((u_int *)pde, PG_A);
4821 pmap_invalidate_page(pmap, pv->pv_va);
4826 /* Rotate the PV list if it has more than one entry. */
4827 if (TAILQ_NEXT(pv, pv_next) != NULL) {
4828 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
4829 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
4831 if (rtval >= PMAP_TS_REFERENCED_MAX)
4833 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
4835 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
4841 pde = pmap_pde(pmap, pv->pv_va);
4842 KASSERT((*pde & PG_PS) == 0,
4843 ("pmap_ts_referenced: found a 4mpage in page %p's pv list",
4845 pte = pmap_pte_quick(pmap, pv->pv_va);
4846 if ((*pte & PG_A) != 0) {
4847 atomic_clear_int((u_int *)pte, PG_A);
4848 pmap_invalidate_page(pmap, pv->pv_va);
4852 /* Rotate the PV list if it has more than one entry. */
4853 if (TAILQ_NEXT(pv, pv_next) != NULL) {
4854 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
4855 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4857 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && rtval <
4858 PMAP_TS_REFERENCED_MAX);
4861 rw_wunlock(&pvh_global_lock);
4866 * Apply the given advice to the specified range of addresses within the
4867 * given pmap. Depending on the advice, clear the referenced and/or
4868 * modified flags in each mapping and set the mapped page's dirty field.
4871 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
4873 pd_entry_t oldpde, *pde;
4877 boolean_t anychanged, pv_lists_locked;
4879 if (advice != MADV_DONTNEED && advice != MADV_FREE)
4881 if (pmap_is_current(pmap))
4882 pv_lists_locked = FALSE;
4884 pv_lists_locked = TRUE;
4886 rw_wlock(&pvh_global_lock);
4891 for (; sva < eva; sva = pdnxt) {
4892 pdnxt = (sva + NBPDR) & ~PDRMASK;
4895 pde = pmap_pde(pmap, sva);
4897 if ((oldpde & PG_V) == 0)
4899 else if ((oldpde & PG_PS) != 0) {
4900 if ((oldpde & PG_MANAGED) == 0)
4902 if (!pv_lists_locked) {
4903 pv_lists_locked = TRUE;
4904 if (!rw_try_wlock(&pvh_global_lock)) {
4906 pmap_invalidate_all(pmap);
4912 if (!pmap_demote_pde(pmap, pde, sva)) {
4914 * The large page mapping was destroyed.
4920 * Unless the page mappings are wired, remove the
4921 * mapping to a single page so that a subsequent
4922 * access may repromote. Since the underlying page
4923 * table page is fully populated, this removal never
4924 * frees a page table page.
4926 if ((oldpde & PG_W) == 0) {
4927 pte = pmap_pte_quick(pmap, sva);
4928 KASSERT((*pte & PG_V) != 0,
4929 ("pmap_advise: invalid PTE"));
4930 pmap_remove_pte(pmap, pte, sva, NULL);
4936 for (pte = pmap_pte_quick(pmap, sva); sva != pdnxt; pte++,
4938 if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED |
4941 else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
4942 if (advice == MADV_DONTNEED) {
4944 * Future calls to pmap_is_modified()
4945 * can be avoided by making the page
4948 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
4951 atomic_clear_int((u_int *)pte, PG_M | PG_A);
4952 } else if ((*pte & PG_A) != 0)
4953 atomic_clear_int((u_int *)pte, PG_A);
4956 if ((*pte & PG_G) != 0)
4957 pmap_invalidate_page(pmap, sva);
4963 pmap_invalidate_all(pmap);
4964 if (pv_lists_locked) {
4966 rw_wunlock(&pvh_global_lock);
4972 * Clear the modify bits on the specified physical page.
4975 pmap_clear_modify(vm_page_t m)
4977 struct md_page *pvh;
4978 pv_entry_t next_pv, pv;
4980 pd_entry_t oldpde, *pde;
4981 pt_entry_t oldpte, *pte;
4984 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4985 ("pmap_clear_modify: page %p is not managed", m));
4986 VM_OBJECT_ASSERT_WLOCKED(m->object);
4987 KASSERT(!vm_page_xbusied(m),
4988 ("pmap_clear_modify: page %p is exclusive busied", m));
4991 * If the page is not PGA_WRITEABLE, then no PTEs can have PG_M set.
4992 * If the object containing the page is locked and the page is not
4993 * exclusive busied, then PGA_WRITEABLE cannot be concurrently set.
4995 if ((m->aflags & PGA_WRITEABLE) == 0)
4997 rw_wlock(&pvh_global_lock);
4999 if ((m->flags & PG_FICTITIOUS) != 0)
5000 goto small_mappings;
5001 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5002 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
5006 pde = pmap_pde(pmap, va);
5008 if ((oldpde & PG_RW) != 0) {
5009 if (pmap_demote_pde(pmap, pde, va)) {
5010 if ((oldpde & PG_W) == 0) {
5012 * Write protect the mapping to a
5013 * single page so that a subsequent
5014 * write access may repromote.
5016 va += VM_PAGE_TO_PHYS(m) - (oldpde &
5018 pte = pmap_pte_quick(pmap, va);
5020 if ((oldpte & PG_V) != 0) {
5022 * Regardless of whether a pte is 32 or 64 bits
5023 * in size, PG_RW and PG_M are among the least
5024 * significant 32 bits.
5026 while (!atomic_cmpset_int((u_int *)pte,
5028 oldpte & ~(PG_M | PG_RW)))
5031 pmap_invalidate_page(pmap, va);
5039 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5042 pde = pmap_pde(pmap, pv->pv_va);
5043 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
5044 " a 4mpage in page %p's pv list", m));
5045 pte = pmap_pte_quick(pmap, pv->pv_va);
5046 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
5048 * Regardless of whether a pte is 32 or 64 bits
5049 * in size, PG_M is among the least significant
5052 atomic_clear_int((u_int *)pte, PG_M);
5053 pmap_invalidate_page(pmap, pv->pv_va);
5058 rw_wunlock(&pvh_global_lock);
5062 * Miscellaneous support routines follow
5065 /* Adjust the cache mode for a 4KB page mapped via a PTE. */
5066 static __inline void
5067 pmap_pte_attr(pt_entry_t *pte, int cache_bits)
5072 * The cache mode bits are all in the low 32-bits of the
5073 * PTE, so we can just spin on updating the low 32-bits.
5076 opte = *(u_int *)pte;
5077 npte = opte & ~PG_PTE_CACHE;
5079 } while (npte != opte && !atomic_cmpset_int((u_int *)pte, opte, npte));
5082 /* Adjust the cache mode for a 2/4MB page mapped via a PDE. */
5083 static __inline void
5084 pmap_pde_attr(pd_entry_t *pde, int cache_bits)
5089 * The cache mode bits are all in the low 32-bits of the
5090 * PDE, so we can just spin on updating the low 32-bits.
5093 opde = *(u_int *)pde;
5094 npde = opde & ~PG_PDE_CACHE;
5096 } while (npde != opde && !atomic_cmpset_int((u_int *)pde, opde, npde));
5100 * Map a set of physical memory pages into the kernel virtual
5101 * address space. Return a pointer to where it is mapped. This
5102 * routine is intended to be used for mapping device memory,
5106 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
5108 vm_offset_t va, offset;
5111 offset = pa & PAGE_MASK;
5112 size = round_page(offset + size);
5115 if (pa < KERNLOAD && pa + size <= KERNLOAD)
5118 va = kva_alloc(size);
5120 panic("pmap_mapdev: Couldn't alloc kernel virtual memory");
5122 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
5123 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
5124 pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
5125 pmap_invalidate_cache_range(va, va + size);
5126 return ((void *)(va + offset));
5130 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
5133 return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
5137 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
5140 return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
5144 pmap_unmapdev(vm_offset_t va, vm_size_t size)
5146 vm_offset_t base, offset;
5148 if (va >= KERNBASE && va + size <= KERNBASE + KERNLOAD)
5150 base = trunc_page(va);
5151 offset = va & PAGE_MASK;
5152 size = round_page(offset + size);
5153 kva_free(base, size);
5157 * Sets the memory attribute for the specified page.
5160 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
5163 m->md.pat_mode = ma;
5164 if ((m->flags & PG_FICTITIOUS) != 0)
5168 * If "m" is a normal page, flush it from the cache.
5169 * See pmap_invalidate_cache_range().
5171 * First, try to find an existing mapping of the page by sf
5172 * buffer. sf_buf_invalidate_cache() modifies mapping and
5173 * flushes the cache.
5175 if (sf_buf_invalidate_cache(m))
5179 * If page is not mapped by sf buffer, but CPU does not
5180 * support self snoop, map the page transient and do
5181 * invalidation. In the worst case, whole cache is flushed by
5182 * pmap_invalidate_cache_range().
5184 if ((cpu_feature & CPUID_SS) == 0)
5189 pmap_flush_page(vm_page_t m)
5191 struct sysmaps *sysmaps;
5192 vm_offset_t sva, eva;
5194 if ((cpu_feature & CPUID_CLFSH) != 0) {
5195 sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
5196 mtx_lock(&sysmaps->lock);
5197 if (*sysmaps->CMAP2)
5198 panic("pmap_flush_page: CMAP2 busy");
5200 *sysmaps->CMAP2 = PG_V | PG_RW | VM_PAGE_TO_PHYS(m) |
5201 PG_A | PG_M | pmap_cache_bits(m->md.pat_mode, 0);
5202 invlcaddr(sysmaps->CADDR2);
5203 sva = (vm_offset_t)sysmaps->CADDR2;
5204 eva = sva + PAGE_SIZE;
5207 * Use mfence despite the ordering implied by
5208 * mtx_{un,}lock() because clflush is not guaranteed
5209 * to be ordered by any other instruction.
5212 for (; sva < eva; sva += cpu_clflush_line_size)
5215 *sysmaps->CMAP2 = 0;
5217 mtx_unlock(&sysmaps->lock);
5219 pmap_invalidate_cache();
5223 * Changes the specified virtual address range's memory type to that given by
5224 * the parameter "mode". The specified virtual address range must be
5225 * completely contained within either the kernel map.
5227 * Returns zero if the change completed successfully, and either EINVAL or
5228 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
5229 * of the virtual address range was not mapped, and ENOMEM is returned if
5230 * there was insufficient memory available to complete the change.
5233 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
5235 vm_offset_t base, offset, tmpva;
5238 int cache_bits_pte, cache_bits_pde;
5241 base = trunc_page(va);
5242 offset = va & PAGE_MASK;
5243 size = round_page(offset + size);
5246 * Only supported on kernel virtual addresses above the recursive map.
5248 if (base < VM_MIN_KERNEL_ADDRESS)
5251 cache_bits_pde = pmap_cache_bits(mode, 1);
5252 cache_bits_pte = pmap_cache_bits(mode, 0);
5256 * Pages that aren't mapped aren't supported. Also break down
5257 * 2/4MB pages into 4KB pages if required.
5259 PMAP_LOCK(kernel_pmap);
5260 for (tmpva = base; tmpva < base + size; ) {
5261 pde = pmap_pde(kernel_pmap, tmpva);
5263 PMAP_UNLOCK(kernel_pmap);
5268 * If the current 2/4MB page already has
5269 * the required memory type, then we need not
5270 * demote this page. Just increment tmpva to
5271 * the next 2/4MB page frame.
5273 if ((*pde & PG_PDE_CACHE) == cache_bits_pde) {
5274 tmpva = trunc_4mpage(tmpva) + NBPDR;
5279 * If the current offset aligns with a 2/4MB
5280 * page frame and there is at least 2/4MB left
5281 * within the range, then we need not break
5282 * down this page into 4KB pages.
5284 if ((tmpva & PDRMASK) == 0 &&
5285 tmpva + PDRMASK < base + size) {
5289 if (!pmap_demote_pde(kernel_pmap, pde, tmpva)) {
5290 PMAP_UNLOCK(kernel_pmap);
5294 pte = vtopte(tmpva);
5296 PMAP_UNLOCK(kernel_pmap);
5301 PMAP_UNLOCK(kernel_pmap);
5304 * Ok, all the pages exist, so run through them updating their
5305 * cache mode if required.
5307 for (tmpva = base; tmpva < base + size; ) {
5308 pde = pmap_pde(kernel_pmap, tmpva);
5310 if ((*pde & PG_PDE_CACHE) != cache_bits_pde) {
5311 pmap_pde_attr(pde, cache_bits_pde);
5314 tmpva = trunc_4mpage(tmpva) + NBPDR;
5316 pte = vtopte(tmpva);
5317 if ((*pte & PG_PTE_CACHE) != cache_bits_pte) {
5318 pmap_pte_attr(pte, cache_bits_pte);
5326 * Flush CPU caches to make sure any data isn't cached that
5327 * shouldn't be, etc.
5330 pmap_invalidate_range(kernel_pmap, base, tmpva);
5331 pmap_invalidate_cache_range(base, tmpva);
5337 * perform the pmap work for mincore
5340 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *locked_pa)
5343 pt_entry_t *ptep, pte;
5349 pdep = pmap_pde(pmap, addr);
5351 if (*pdep & PG_PS) {
5353 /* Compute the physical address of the 4KB page. */
5354 pa = ((*pdep & PG_PS_FRAME) | (addr & PDRMASK)) &
5356 val = MINCORE_SUPER;
5358 ptep = pmap_pte(pmap, addr);
5360 pmap_pte_release(ptep);
5361 pa = pte & PG_FRAME;
5369 if ((pte & PG_V) != 0) {
5370 val |= MINCORE_INCORE;
5371 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
5372 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
5373 if ((pte & PG_A) != 0)
5374 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
5376 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
5377 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
5378 (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
5379 /* Ensure that "PHYS_TO_VM_PAGE(pa)->object" doesn't change. */
5380 if (vm_page_pa_tryrelock(pmap, pa, locked_pa))
5383 PA_UNLOCK_COND(*locked_pa);
5389 pmap_activate(struct thread *td)
5391 pmap_t pmap, oldpmap;
5396 pmap = vmspace_pmap(td->td_proc->p_vmspace);
5397 oldpmap = PCPU_GET(curpmap);
5398 cpuid = PCPU_GET(cpuid);
5400 CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
5401 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
5403 CPU_CLR(cpuid, &oldpmap->pm_active);
5404 CPU_SET(cpuid, &pmap->pm_active);
5407 cr3 = vtophys(pmap->pm_pdpt);
5409 cr3 = vtophys(pmap->pm_pdir);
5412 * pmap_activate is for the current thread on the current cpu
5414 td->td_pcb->pcb_cr3 = cr3;
5416 PCPU_SET(curpmap, pmap);
5421 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
5426 * Increase the starting virtual address of the given mapping if a
5427 * different alignment might result in more superpage mappings.
5430 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
5431 vm_offset_t *addr, vm_size_t size)
5433 vm_offset_t superpage_offset;
5437 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
5438 offset += ptoa(object->pg_color);
5439 superpage_offset = offset & PDRMASK;
5440 if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
5441 (*addr & PDRMASK) == superpage_offset)
5443 if ((*addr & PDRMASK) < superpage_offset)
5444 *addr = (*addr & ~PDRMASK) + superpage_offset;
5446 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
5450 #if defined(PMAP_DEBUG)
5451 pmap_pid_dump(int pid)
5458 sx_slock(&allproc_lock);
5459 FOREACH_PROC_IN_SYSTEM(p) {
5460 if (p->p_pid != pid)
5466 pmap = vmspace_pmap(p->p_vmspace);
5467 for (i = 0; i < NPDEPTD; i++) {
5470 vm_offset_t base = i << PDRSHIFT;
5472 pde = &pmap->pm_pdir[i];
5473 if (pde && pmap_pde_v(pde)) {
5474 for (j = 0; j < NPTEPG; j++) {
5475 vm_offset_t va = base + (j << PAGE_SHIFT);
5476 if (va >= (vm_offset_t) VM_MIN_KERNEL_ADDRESS) {
5481 sx_sunlock(&allproc_lock);
5484 pte = pmap_pte(pmap, va);
5485 if (pte && pmap_pte_v(pte)) {
5489 m = PHYS_TO_VM_PAGE(pa & PG_FRAME);
5490 printf("va: 0x%x, pt: 0x%x, h: %d, w: %d, f: 0x%x",
5491 va, pa, m->hold_count, m->wire_count, m->flags);
5506 sx_sunlock(&allproc_lock);
5513 static void pads(pmap_t pm);
5514 void pmap_pvdump(vm_paddr_t pa);
5516 /* print address space of pmap*/
5524 if (pm == kernel_pmap)
5526 for (i = 0; i < NPDEPTD; i++)
5528 for (j = 0; j < NPTEPG; j++) {
5529 va = (i << PDRSHIFT) + (j << PAGE_SHIFT);
5530 if (pm == kernel_pmap && va < KERNBASE)
5532 if (pm != kernel_pmap && va > UPT_MAX_ADDRESS)
5534 ptep = pmap_pte(pm, va);
5535 if (pmap_pte_v(ptep))
5536 printf("%x:%x ", va, *ptep);
5542 pmap_pvdump(vm_paddr_t pa)
5548 printf("pa %x", pa);
5549 m = PHYS_TO_VM_PAGE(pa);
5550 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5552 printf(" -> pmap %p, va %x", (void *)pmap, pv->pv_va);