]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/amd64/amd64/pmap.c
Copy head to stable/8 as part of 8.0 Release cycle.
[FreeBSD/stable/8.git] / sys / amd64 / amd64 / pmap.c
1 /*-
2  * Copyright (c) 1991 Regents of the University of California.
3  * All rights reserved.
4  * Copyright (c) 1994 John S. Dyson
5  * All rights reserved.
6  * Copyright (c) 1994 David Greenman
7  * All rights reserved.
8  * Copyright (c) 2003 Peter Wemm
9  * All rights reserved.
10  * Copyright (c) 2005-2008 Alan L. Cox <alc@cs.rice.edu>
11  * All rights reserved.
12  *
13  * This code is derived from software contributed to Berkeley by
14  * the Systems Programming Group of the University of Utah Computer
15  * Science Department and William Jolitz of UUNET Technologies Inc.
16  *
17  * Redistribution and use in source and binary forms, with or without
18  * modification, are permitted provided that the following conditions
19  * are met:
20  * 1. Redistributions of source code must retain the above copyright
21  *    notice, this list of conditions and the following disclaimer.
22  * 2. Redistributions in binary form must reproduce the above copyright
23  *    notice, this list of conditions and the following disclaimer in the
24  *    documentation and/or other materials provided with the distribution.
25  * 3. All advertising materials mentioning features or use of this software
26  *    must display the following acknowledgement:
27  *      This product includes software developed by the University of
28  *      California, Berkeley and its contributors.
29  * 4. Neither the name of the University nor the names of its contributors
30  *    may be used to endorse or promote products derived from this software
31  *    without specific prior written permission.
32  *
33  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
34  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
35  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
36  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
37  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
38  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
39  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
40  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
41  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
42  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
43  * SUCH DAMAGE.
44  *
45  *      from:   @(#)pmap.c      7.7 (Berkeley)  5/12/91
46  */
47 /*-
48  * Copyright (c) 2003 Networks Associates Technology, Inc.
49  * All rights reserved.
50  *
51  * This software was developed for the FreeBSD Project by Jake Burkholder,
52  * Safeport Network Services, and Network Associates Laboratories, the
53  * Security Research Division of Network Associates, Inc. under
54  * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA
55  * CHATS research program.
56  *
57  * Redistribution and use in source and binary forms, with or without
58  * modification, are permitted provided that the following conditions
59  * are met:
60  * 1. Redistributions of source code must retain the above copyright
61  *    notice, this list of conditions and the following disclaimer.
62  * 2. Redistributions in binary form must reproduce the above copyright
63  *    notice, this list of conditions and the following disclaimer in the
64  *    documentation and/or other materials provided with the distribution.
65  *
66  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
67  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
68  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
69  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
70  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
71  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
72  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
73  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
74  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
75  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
76  * SUCH DAMAGE.
77  */
78
79 #include <sys/cdefs.h>
80 __FBSDID("$FreeBSD$");
81
82 /*
83  *      Manages physical address maps.
84  *
85  *      In addition to hardware address maps, this
86  *      module is called upon to provide software-use-only
87  *      maps which may or may not be stored in the same
88  *      form as hardware maps.  These pseudo-maps are
89  *      used to store intermediate results from copy
90  *      operations to and from address spaces.
91  *
92  *      Since the information managed by this module is
93  *      also stored by the logical address mapping module,
94  *      this module may throw away valid virtual-to-physical
95  *      mappings at almost any time.  However, invalidations
96  *      of virtual-to-physical mappings must be done as
97  *      requested.
98  *
99  *      In order to cope with hardware architectures which
100  *      make virtual-to-physical map invalidates expensive,
101  *      this module may delay invalidate or reduced protection
102  *      operations until such time as they are actually
103  *      necessary.  This module is given full information as
104  *      to which processors are currently using which maps,
105  *      and to when physical maps must be made correct.
106  */
107
108 #include "opt_msgbuf.h"
109 #include "opt_pmap.h"
110 #include "opt_vm.h"
111
112 #include <sys/param.h>
113 #include <sys/systm.h>
114 #include <sys/kernel.h>
115 #include <sys/ktr.h>
116 #include <sys/lock.h>
117 #include <sys/malloc.h>
118 #include <sys/mman.h>
119 #include <sys/msgbuf.h>
120 #include <sys/mutex.h>
121 #include <sys/proc.h>
122 #include <sys/sx.h>
123 #include <sys/vmmeter.h>
124 #include <sys/sched.h>
125 #include <sys/sysctl.h>
126 #ifdef SMP
127 #include <sys/smp.h>
128 #endif
129
130 #include <vm/vm.h>
131 #include <vm/vm_param.h>
132 #include <vm/vm_kern.h>
133 #include <vm/vm_page.h>
134 #include <vm/vm_map.h>
135 #include <vm/vm_object.h>
136 #include <vm/vm_extern.h>
137 #include <vm/vm_pageout.h>
138 #include <vm/vm_pager.h>
139 #include <vm/vm_reserv.h>
140 #include <vm/uma.h>
141
142 #include <machine/cpu.h>
143 #include <machine/cputypes.h>
144 #include <machine/md_var.h>
145 #include <machine/pcb.h>
146 #include <machine/specialreg.h>
147 #ifdef SMP
148 #include <machine/smp.h>
149 #endif
150
151 #ifndef PMAP_SHPGPERPROC
152 #define PMAP_SHPGPERPROC 200
153 #endif
154
155 #if !defined(DIAGNOSTIC)
156 #define PMAP_INLINE     __gnu89_inline
157 #else
158 #define PMAP_INLINE
159 #endif
160
161 #define PV_STATS
162 #ifdef PV_STATS
163 #define PV_STAT(x)      do { x ; } while (0)
164 #else
165 #define PV_STAT(x)      do { } while (0)
166 #endif
167
168 #define pa_index(pa)    ((pa) >> PDRSHIFT)
169 #define pa_to_pvh(pa)   (&pv_table[pa_index(pa)])
170
171 struct pmap kernel_pmap_store;
172
173 vm_offset_t virtual_avail;      /* VA of first avail page (after kernel bss) */
174 vm_offset_t virtual_end;        /* VA of last avail page (end of kernel AS) */
175
176 static int ndmpdp;
177 static vm_paddr_t dmaplimit;
178 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
179 pt_entry_t pg_nx;
180
181 SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD, 0, "VM/pmap parameters");
182
183 static int pg_ps_enabled = 1;
184 SYSCTL_INT(_vm_pmap, OID_AUTO, pg_ps_enabled, CTLFLAG_RD, &pg_ps_enabled, 0,
185     "Are large page mappings enabled?");
186
187 static u_int64_t        KPTphys;        /* phys addr of kernel level 1 */
188 static u_int64_t        KPDphys;        /* phys addr of kernel level 2 */
189 u_int64_t               KPDPphys;       /* phys addr of kernel level 3 */
190 u_int64_t               KPML4phys;      /* phys addr of kernel level 4 */
191
192 static u_int64_t        DMPDphys;       /* phys addr of direct mapped level 2 */
193 static u_int64_t        DMPDPphys;      /* phys addr of direct mapped level 3 */
194
195 /*
196  * Data for the pv entry allocation mechanism
197  */
198 static int pv_entry_count = 0, pv_entry_max = 0, pv_entry_high_water = 0;
199 static struct md_page *pv_table;
200 static int shpgperproc = PMAP_SHPGPERPROC;
201
202 /*
203  * All those kernel PT submaps that BSD is so fond of
204  */
205 pt_entry_t *CMAP1 = 0;
206 caddr_t CADDR1 = 0;
207 struct msgbuf *msgbufp = 0;
208
209 /*
210  * Crashdump maps.
211  */
212 static caddr_t crashdumpmap;
213
214 static void     free_pv_entry(pmap_t pmap, pv_entry_t pv);
215 static pv_entry_t get_pv_entry(pmap_t locked_pmap, int try);
216 static void     pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa);
217 static boolean_t pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa);
218 static void     pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa);
219 static void     pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
220 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
221                     vm_offset_t va);
222 static int      pmap_pvh_wired_mappings(struct md_page *pvh, int count);
223
224 static int pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode);
225 static boolean_t pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
226 static boolean_t pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe,
227     vm_offset_t va);
228 static boolean_t pmap_enter_pde(pmap_t pmap, vm_offset_t va, vm_page_t m,
229     vm_prot_t prot);
230 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
231     vm_page_t m, vm_prot_t prot, vm_page_t mpte);
232 static void pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte);
233 static void pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte);
234 static void pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva);
235 static boolean_t pmap_is_modified_pvh(struct md_page *pvh);
236 static void pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode);
237 static vm_page_t pmap_lookup_pt_page(pmap_t pmap, vm_offset_t va);
238 static void pmap_pde_attr(pd_entry_t *pde, int cache_bits);
239 static void pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
240 static boolean_t pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva,
241     vm_prot_t prot);
242 static void pmap_pte_attr(pt_entry_t *pte, int cache_bits);
243 static int pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
244                 vm_page_t *free);
245 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq,
246                 vm_offset_t sva, pd_entry_t ptepde, vm_page_t *free);
247 static void pmap_remove_pt_page(pmap_t pmap, vm_page_t mpte);
248 static void pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
249     vm_page_t *free);
250 static void pmap_remove_entry(struct pmap *pmap, vm_page_t m,
251                 vm_offset_t va);
252 static void pmap_insert_entry(pmap_t pmap, vm_offset_t va, vm_page_t m);
253 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
254     vm_page_t m);
255
256 static vm_page_t pmap_allocpde(pmap_t pmap, vm_offset_t va, int flags);
257 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va, int flags);
258
259 static vm_page_t _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, int flags);
260 static int _pmap_unwire_pte_hold(pmap_t pmap, vm_offset_t va, vm_page_t m,
261                 vm_page_t* free);
262 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, vm_page_t *);
263 static vm_offset_t pmap_kmem_choose(vm_offset_t addr);
264
265 CTASSERT(1 << PDESHIFT == sizeof(pd_entry_t));
266 CTASSERT(1 << PTESHIFT == sizeof(pt_entry_t));
267
268 /*
269  * Move the kernel virtual free pointer to the next
270  * 2MB.  This is used to help improve performance
271  * by using a large (2MB) page for much of the kernel
272  * (.text, .data, .bss)
273  */
274 static vm_offset_t
275 pmap_kmem_choose(vm_offset_t addr)
276 {
277         vm_offset_t newaddr = addr;
278
279         newaddr = (addr + (NBPDR - 1)) & ~(NBPDR - 1);
280         return newaddr;
281 }
282
283 /********************/
284 /* Inline functions */
285 /********************/
286
287 /* Return a non-clipped PD index for a given VA */
288 static __inline vm_pindex_t
289 pmap_pde_pindex(vm_offset_t va)
290 {
291         return va >> PDRSHIFT;
292 }
293
294
295 /* Return various clipped indexes for a given VA */
296 static __inline vm_pindex_t
297 pmap_pte_index(vm_offset_t va)
298 {
299
300         return ((va >> PAGE_SHIFT) & ((1ul << NPTEPGSHIFT) - 1));
301 }
302
303 static __inline vm_pindex_t
304 pmap_pde_index(vm_offset_t va)
305 {
306
307         return ((va >> PDRSHIFT) & ((1ul << NPDEPGSHIFT) - 1));
308 }
309
310 static __inline vm_pindex_t
311 pmap_pdpe_index(vm_offset_t va)
312 {
313
314         return ((va >> PDPSHIFT) & ((1ul << NPDPEPGSHIFT) - 1));
315 }
316
317 static __inline vm_pindex_t
318 pmap_pml4e_index(vm_offset_t va)
319 {
320
321         return ((va >> PML4SHIFT) & ((1ul << NPML4EPGSHIFT) - 1));
322 }
323
324 /* Return a pointer to the PML4 slot that corresponds to a VA */
325 static __inline pml4_entry_t *
326 pmap_pml4e(pmap_t pmap, vm_offset_t va)
327 {
328
329         return (&pmap->pm_pml4[pmap_pml4e_index(va)]);
330 }
331
332 /* Return a pointer to the PDP slot that corresponds to a VA */
333 static __inline pdp_entry_t *
334 pmap_pml4e_to_pdpe(pml4_entry_t *pml4e, vm_offset_t va)
335 {
336         pdp_entry_t *pdpe;
337
338         pdpe = (pdp_entry_t *)PHYS_TO_DMAP(*pml4e & PG_FRAME);
339         return (&pdpe[pmap_pdpe_index(va)]);
340 }
341
342 /* Return a pointer to the PDP slot that corresponds to a VA */
343 static __inline pdp_entry_t *
344 pmap_pdpe(pmap_t pmap, vm_offset_t va)
345 {
346         pml4_entry_t *pml4e;
347
348         pml4e = pmap_pml4e(pmap, va);
349         if ((*pml4e & PG_V) == 0)
350                 return NULL;
351         return (pmap_pml4e_to_pdpe(pml4e, va));
352 }
353
354 /* Return a pointer to the PD slot that corresponds to a VA */
355 static __inline pd_entry_t *
356 pmap_pdpe_to_pde(pdp_entry_t *pdpe, vm_offset_t va)
357 {
358         pd_entry_t *pde;
359
360         pde = (pd_entry_t *)PHYS_TO_DMAP(*pdpe & PG_FRAME);
361         return (&pde[pmap_pde_index(va)]);
362 }
363
364 /* Return a pointer to the PD slot that corresponds to a VA */
365 static __inline pd_entry_t *
366 pmap_pde(pmap_t pmap, vm_offset_t va)
367 {
368         pdp_entry_t *pdpe;
369
370         pdpe = pmap_pdpe(pmap, va);
371         if (pdpe == NULL || (*pdpe & PG_V) == 0)
372                  return NULL;
373         return (pmap_pdpe_to_pde(pdpe, va));
374 }
375
376 /* Return a pointer to the PT slot that corresponds to a VA */
377 static __inline pt_entry_t *
378 pmap_pde_to_pte(pd_entry_t *pde, vm_offset_t va)
379 {
380         pt_entry_t *pte;
381
382         pte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
383         return (&pte[pmap_pte_index(va)]);
384 }
385
386 /* Return a pointer to the PT slot that corresponds to a VA */
387 static __inline pt_entry_t *
388 pmap_pte(pmap_t pmap, vm_offset_t va)
389 {
390         pd_entry_t *pde;
391
392         pde = pmap_pde(pmap, va);
393         if (pde == NULL || (*pde & PG_V) == 0)
394                 return NULL;
395         if ((*pde & PG_PS) != 0)        /* compat with i386 pmap_pte() */
396                 return ((pt_entry_t *)pde);
397         return (pmap_pde_to_pte(pde, va));
398 }
399
400
401 PMAP_INLINE pt_entry_t *
402 vtopte(vm_offset_t va)
403 {
404         u_int64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
405
406         return (PTmap + ((va >> PAGE_SHIFT) & mask));
407 }
408
409 static __inline pd_entry_t *
410 vtopde(vm_offset_t va)
411 {
412         u_int64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
413
414         return (PDmap + ((va >> PDRSHIFT) & mask));
415 }
416
417 static u_int64_t
418 allocpages(vm_paddr_t *firstaddr, int n)
419 {
420         u_int64_t ret;
421
422         ret = *firstaddr;
423         bzero((void *)ret, n * PAGE_SIZE);
424         *firstaddr += n * PAGE_SIZE;
425         return (ret);
426 }
427
428 static void
429 create_pagetables(vm_paddr_t *firstaddr)
430 {
431         int i;
432
433         /* Allocate pages */
434         KPTphys = allocpages(firstaddr, NKPT);
435         KPML4phys = allocpages(firstaddr, 1);
436         KPDPphys = allocpages(firstaddr, NKPML4E);
437         KPDphys = allocpages(firstaddr, NKPDPE);
438
439         ndmpdp = (ptoa(Maxmem) + NBPDP - 1) >> PDPSHIFT;
440         if (ndmpdp < 4)         /* Minimum 4GB of dirmap */
441                 ndmpdp = 4;
442         DMPDPphys = allocpages(firstaddr, NDMPML4E);
443         if ((amd_feature & AMDID_PAGE1GB) == 0)
444                 DMPDphys = allocpages(firstaddr, ndmpdp);
445         dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
446
447         /* Fill in the underlying page table pages */
448         /* Read-only from zero to physfree */
449         /* XXX not fully used, underneath 2M pages */
450         for (i = 0; (i << PAGE_SHIFT) < *firstaddr; i++) {
451                 ((pt_entry_t *)KPTphys)[i] = i << PAGE_SHIFT;
452                 ((pt_entry_t *)KPTphys)[i] |= PG_RW | PG_V | PG_G;
453         }
454
455         /* Now map the page tables at their location within PTmap */
456         for (i = 0; i < NKPT; i++) {
457                 ((pd_entry_t *)KPDphys)[i] = KPTphys + (i << PAGE_SHIFT);
458                 ((pd_entry_t *)KPDphys)[i] |= PG_RW | PG_V;
459         }
460
461         /* Map from zero to end of allocations under 2M pages */
462         /* This replaces some of the KPTphys entries above */
463         for (i = 0; (i << PDRSHIFT) < *firstaddr; i++) {
464                 ((pd_entry_t *)KPDphys)[i] = i << PDRSHIFT;
465                 ((pd_entry_t *)KPDphys)[i] |= PG_RW | PG_V | PG_PS | PG_G;
466         }
467
468         /* And connect up the PD to the PDP */
469         for (i = 0; i < NKPDPE; i++) {
470                 ((pdp_entry_t *)KPDPphys)[i + KPDPI] = KPDphys +
471                     (i << PAGE_SHIFT);
472                 ((pdp_entry_t *)KPDPphys)[i + KPDPI] |= PG_RW | PG_V | PG_U;
473         }
474
475         /* Now set up the direct map space using either 2MB or 1GB pages */
476         /* Preset PG_M and PG_A because demotion expects it */
477         if ((amd_feature & AMDID_PAGE1GB) == 0) {
478                 for (i = 0; i < NPDEPG * ndmpdp; i++) {
479                         ((pd_entry_t *)DMPDphys)[i] = (vm_paddr_t)i << PDRSHIFT;
480                         ((pd_entry_t *)DMPDphys)[i] |= PG_RW | PG_V | PG_PS |
481                             PG_G | PG_M | PG_A;
482                 }
483                 /* And the direct map space's PDP */
484                 for (i = 0; i < ndmpdp; i++) {
485                         ((pdp_entry_t *)DMPDPphys)[i] = DMPDphys +
486                             (i << PAGE_SHIFT);
487                         ((pdp_entry_t *)DMPDPphys)[i] |= PG_RW | PG_V | PG_U;
488                 }
489         } else {
490                 for (i = 0; i < ndmpdp; i++) {
491                         ((pdp_entry_t *)DMPDPphys)[i] =
492                             (vm_paddr_t)i << PDPSHIFT;
493                         ((pdp_entry_t *)DMPDPphys)[i] |= PG_RW | PG_V | PG_PS |
494                             PG_G | PG_M | PG_A;
495                 }
496         }
497
498         /* And recursively map PML4 to itself in order to get PTmap */
499         ((pdp_entry_t *)KPML4phys)[PML4PML4I] = KPML4phys;
500         ((pdp_entry_t *)KPML4phys)[PML4PML4I] |= PG_RW | PG_V | PG_U;
501
502         /* Connect the Direct Map slot up to the PML4 */
503         ((pdp_entry_t *)KPML4phys)[DMPML4I] = DMPDPphys;
504         ((pdp_entry_t *)KPML4phys)[DMPML4I] |= PG_RW | PG_V | PG_U;
505
506         /* Connect the KVA slot up to the PML4 */
507         ((pdp_entry_t *)KPML4phys)[KPML4I] = KPDPphys;
508         ((pdp_entry_t *)KPML4phys)[KPML4I] |= PG_RW | PG_V | PG_U;
509 }
510
511 /*
512  *      Bootstrap the system enough to run with virtual memory.
513  *
514  *      On amd64 this is called after mapping has already been enabled
515  *      and just syncs the pmap module with what has already been done.
516  *      [We can't call it easily with mapping off since the kernel is not
517  *      mapped with PA == VA, hence we would have to relocate every address
518  *      from the linked base (virtual) address "KERNBASE" to the actual
519  *      (physical) address starting relative to 0]
520  */
521 void
522 pmap_bootstrap(vm_paddr_t *firstaddr)
523 {
524         vm_offset_t va;
525         pt_entry_t *pte, *unused;
526
527         /*
528          * Create an initial set of page tables to run the kernel in.
529          */
530         create_pagetables(firstaddr);
531
532         virtual_avail = (vm_offset_t) KERNBASE + *firstaddr;
533         virtual_avail = pmap_kmem_choose(virtual_avail);
534
535         virtual_end = VM_MAX_KERNEL_ADDRESS;
536
537
538         /* XXX do %cr0 as well */
539         load_cr4(rcr4() | CR4_PGE | CR4_PSE);
540         load_cr3(KPML4phys);
541
542         /*
543          * Initialize the kernel pmap (which is statically allocated).
544          */
545         PMAP_LOCK_INIT(kernel_pmap);
546         kernel_pmap->pm_pml4 = (pdp_entry_t *)PHYS_TO_DMAP(KPML4phys);
547         kernel_pmap->pm_root = NULL;
548         kernel_pmap->pm_active = -1;    /* don't allow deactivation */
549         TAILQ_INIT(&kernel_pmap->pm_pvchunk);
550
551         /*
552          * Reserve some special page table entries/VA space for temporary
553          * mapping of pages.
554          */
555 #define SYSMAP(c, p, v, n)      \
556         v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
557
558         va = virtual_avail;
559         pte = vtopte(va);
560
561         /*
562          * CMAP1 is only used for the memory test.
563          */
564         SYSMAP(caddr_t, CMAP1, CADDR1, 1)
565
566         /*
567          * Crashdump maps.
568          */
569         SYSMAP(caddr_t, unused, crashdumpmap, MAXDUMPPGS)
570
571         /*
572          * msgbufp is used to map the system message buffer.
573          */
574         SYSMAP(struct msgbuf *, unused, msgbufp, atop(round_page(MSGBUF_SIZE)))
575
576         virtual_avail = va;
577
578         *CMAP1 = 0;
579
580         invltlb();
581
582         /* Initialize the PAT MSR. */
583         pmap_init_pat();
584 }
585
586 /*
587  * Setup the PAT MSR.
588  */
589 void
590 pmap_init_pat(void)
591 {
592         uint64_t pat_msr;
593
594         /* Bail if this CPU doesn't implement PAT. */
595         if (!(cpu_feature & CPUID_PAT))
596                 panic("no PAT??");
597
598         /*
599          * Leave the indices 0-3 at the default of WB, WT, UC, and UC-.
600          * Program 4 and 5 as WP and WC.
601          * Leave 6 and 7 as UC and UC-.
602          */
603         pat_msr = rdmsr(MSR_PAT);
604         pat_msr &= ~(PAT_MASK(4) | PAT_MASK(5));
605         pat_msr |= PAT_VALUE(4, PAT_WRITE_PROTECTED) |
606             PAT_VALUE(5, PAT_WRITE_COMBINING);
607         wrmsr(MSR_PAT, pat_msr);
608 }
609
610 /*
611  *      Initialize a vm_page's machine-dependent fields.
612  */
613 void
614 pmap_page_init(vm_page_t m)
615 {
616
617         TAILQ_INIT(&m->md.pv_list);
618         m->md.pat_mode = PAT_WRITE_BACK;
619 }
620
621 /*
622  *      Initialize the pmap module.
623  *      Called by vm_init, to initialize any structures that the pmap
624  *      system needs to map virtual memory.
625  */
626 void
627 pmap_init(void)
628 {
629         pd_entry_t *pd;
630         vm_page_t mpte;
631         vm_size_t s;
632         int i, pv_npg;
633
634         /*
635          * Initialize the vm page array entries for the kernel pmap's
636          * page table pages.
637          */ 
638         pd = pmap_pde(kernel_pmap, KERNBASE);
639         for (i = 0; i < NKPT; i++) {
640                 if ((pd[i] & (PG_PS | PG_V)) == (PG_PS | PG_V))
641                         continue;
642                 KASSERT((pd[i] & PG_V) != 0,
643                     ("pmap_init: page table page is missing"));
644                 mpte = PHYS_TO_VM_PAGE(pd[i] & PG_FRAME);
645                 KASSERT(mpte >= vm_page_array &&
646                     mpte < &vm_page_array[vm_page_array_size],
647                     ("pmap_init: page table page is out of range"));
648                 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
649                 mpte->phys_addr = pd[i] & PG_FRAME;
650         }
651
652         /*
653          * Initialize the address space (zone) for the pv entries.  Set a
654          * high water mark so that the system can recover from excessive
655          * numbers of pv entries.
656          */
657         TUNABLE_INT_FETCH("vm.pmap.shpgperproc", &shpgperproc);
658         pv_entry_max = shpgperproc * maxproc + cnt.v_page_count;
659         TUNABLE_INT_FETCH("vm.pmap.pv_entries", &pv_entry_max);
660         pv_entry_high_water = 9 * (pv_entry_max / 10);
661
662         /*
663          * Are large page mappings enabled?
664          */
665         TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
666
667         /*
668          * Calculate the size of the pv head table for superpages.
669          */
670         for (i = 0; phys_avail[i + 1]; i += 2);
671         pv_npg = round_2mpage(phys_avail[(i - 2) + 1]) / NBPDR;
672
673         /*
674          * Allocate memory for the pv head table for superpages.
675          */
676         s = (vm_size_t)(pv_npg * sizeof(struct md_page));
677         s = round_page(s);
678         pv_table = (struct md_page *)kmem_alloc(kernel_map, s);
679         for (i = 0; i < pv_npg; i++)
680                 TAILQ_INIT(&pv_table[i].pv_list);
681 }
682
683 static int
684 pmap_pventry_proc(SYSCTL_HANDLER_ARGS)
685 {
686         int error;
687
688         error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
689         if (error == 0 && req->newptr) {
690                 shpgperproc = (pv_entry_max - cnt.v_page_count) / maxproc;
691                 pv_entry_high_water = 9 * (pv_entry_max / 10);
692         }
693         return (error);
694 }
695 SYSCTL_PROC(_vm_pmap, OID_AUTO, pv_entry_max, CTLTYPE_INT|CTLFLAG_RW, 
696     &pv_entry_max, 0, pmap_pventry_proc, "IU", "Max number of PV entries");
697
698 static int
699 pmap_shpgperproc_proc(SYSCTL_HANDLER_ARGS)
700 {
701         int error;
702
703         error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
704         if (error == 0 && req->newptr) {
705                 pv_entry_max = shpgperproc * maxproc + cnt.v_page_count;
706                 pv_entry_high_water = 9 * (pv_entry_max / 10);
707         }
708         return (error);
709 }
710 SYSCTL_PROC(_vm_pmap, OID_AUTO, shpgperproc, CTLTYPE_INT|CTLFLAG_RW, 
711     &shpgperproc, 0, pmap_shpgperproc_proc, "IU", "Page share factor per proc");
712
713 SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD, 0,
714     "2MB page mapping counters");
715
716 static u_long pmap_pde_demotions;
717 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, demotions, CTLFLAG_RD,
718     &pmap_pde_demotions, 0, "2MB page demotions");
719
720 static u_long pmap_pde_mappings;
721 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
722     &pmap_pde_mappings, 0, "2MB page mappings");
723
724 static u_long pmap_pde_p_failures;
725 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
726     &pmap_pde_p_failures, 0, "2MB page promotion failures");
727
728 static u_long pmap_pde_promotions;
729 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
730     &pmap_pde_promotions, 0, "2MB page promotions");
731
732 SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD, 0,
733     "1GB page mapping counters");
734
735 static u_long pmap_pdpe_demotions;
736 SYSCTL_ULONG(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
737     &pmap_pdpe_demotions, 0, "1GB page demotions");
738
739
740 /***************************************************
741  * Low level helper routines.....
742  ***************************************************/
743
744 /*
745  * Determine the appropriate bits to set in a PTE or PDE for a specified
746  * caching mode.
747  */
748 static int
749 pmap_cache_bits(int mode, boolean_t is_pde)
750 {
751         int pat_flag, pat_index, cache_bits;
752
753         /* The PAT bit is different for PTE's and PDE's. */
754         pat_flag = is_pde ? PG_PDE_PAT : PG_PTE_PAT;
755
756         /* Map the caching mode to a PAT index. */
757         switch (mode) {
758         case PAT_UNCACHEABLE:
759                 pat_index = 3;
760                 break;
761         case PAT_WRITE_THROUGH:
762                 pat_index = 1;
763                 break;
764         case PAT_WRITE_BACK:
765                 pat_index = 0;
766                 break;
767         case PAT_UNCACHED:
768                 pat_index = 2;
769                 break;
770         case PAT_WRITE_COMBINING:
771                 pat_index = 5;
772                 break;
773         case PAT_WRITE_PROTECTED:
774                 pat_index = 4;
775                 break;
776         default:
777                 panic("Unknown caching mode %d\n", mode);
778         }
779
780         /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
781         cache_bits = 0;
782         if (pat_index & 0x4)
783                 cache_bits |= pat_flag;
784         if (pat_index & 0x2)
785                 cache_bits |= PG_NC_PCD;
786         if (pat_index & 0x1)
787                 cache_bits |= PG_NC_PWT;
788         return (cache_bits);
789 }
790 #ifdef SMP
791 /*
792  * For SMP, these functions have to use the IPI mechanism for coherence.
793  *
794  * N.B.: Before calling any of the following TLB invalidation functions,
795  * the calling processor must ensure that all stores updating a non-
796  * kernel page table are globally performed.  Otherwise, another
797  * processor could cache an old, pre-update entry without being
798  * invalidated.  This can happen one of two ways: (1) The pmap becomes
799  * active on another processor after its pm_active field is checked by
800  * one of the following functions but before a store updating the page
801  * table is globally performed. (2) The pmap becomes active on another
802  * processor before its pm_active field is checked but due to
803  * speculative loads one of the following functions stills reads the
804  * pmap as inactive on the other processor.
805  * 
806  * The kernel page table is exempt because its pm_active field is
807  * immutable.  The kernel page table is always active on every
808  * processor.
809  */
810 void
811 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
812 {
813         u_int cpumask;
814         u_int other_cpus;
815
816         sched_pin();
817         if (pmap == kernel_pmap || pmap->pm_active == all_cpus) {
818                 invlpg(va);
819                 smp_invlpg(va);
820         } else {
821                 cpumask = PCPU_GET(cpumask);
822                 other_cpus = PCPU_GET(other_cpus);
823                 if (pmap->pm_active & cpumask)
824                         invlpg(va);
825                 if (pmap->pm_active & other_cpus)
826                         smp_masked_invlpg(pmap->pm_active & other_cpus, va);
827         }
828         sched_unpin();
829 }
830
831 void
832 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
833 {
834         u_int cpumask;
835         u_int other_cpus;
836         vm_offset_t addr;
837
838         sched_pin();
839         if (pmap == kernel_pmap || pmap->pm_active == all_cpus) {
840                 for (addr = sva; addr < eva; addr += PAGE_SIZE)
841                         invlpg(addr);
842                 smp_invlpg_range(sva, eva);
843         } else {
844                 cpumask = PCPU_GET(cpumask);
845                 other_cpus = PCPU_GET(other_cpus);
846                 if (pmap->pm_active & cpumask)
847                         for (addr = sva; addr < eva; addr += PAGE_SIZE)
848                                 invlpg(addr);
849                 if (pmap->pm_active & other_cpus)
850                         smp_masked_invlpg_range(pmap->pm_active & other_cpus,
851                             sva, eva);
852         }
853         sched_unpin();
854 }
855
856 void
857 pmap_invalidate_all(pmap_t pmap)
858 {
859         u_int cpumask;
860         u_int other_cpus;
861
862         sched_pin();
863         if (pmap == kernel_pmap || pmap->pm_active == all_cpus) {
864                 invltlb();
865                 smp_invltlb();
866         } else {
867                 cpumask = PCPU_GET(cpumask);
868                 other_cpus = PCPU_GET(other_cpus);
869                 if (pmap->pm_active & cpumask)
870                         invltlb();
871                 if (pmap->pm_active & other_cpus)
872                         smp_masked_invltlb(pmap->pm_active & other_cpus);
873         }
874         sched_unpin();
875 }
876
877 void
878 pmap_invalidate_cache(void)
879 {
880
881         sched_pin();
882         wbinvd();
883         smp_cache_flush();
884         sched_unpin();
885 }
886 #else /* !SMP */
887 /*
888  * Normal, non-SMP, invalidation functions.
889  * We inline these within pmap.c for speed.
890  */
891 PMAP_INLINE void
892 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
893 {
894
895         if (pmap == kernel_pmap || pmap->pm_active)
896                 invlpg(va);
897 }
898
899 PMAP_INLINE void
900 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
901 {
902         vm_offset_t addr;
903
904         if (pmap == kernel_pmap || pmap->pm_active)
905                 for (addr = sva; addr < eva; addr += PAGE_SIZE)
906                         invlpg(addr);
907 }
908
909 PMAP_INLINE void
910 pmap_invalidate_all(pmap_t pmap)
911 {
912
913         if (pmap == kernel_pmap || pmap->pm_active)
914                 invltlb();
915 }
916
917 PMAP_INLINE void
918 pmap_invalidate_cache(void)
919 {
920
921         wbinvd();
922 }
923 #endif /* !SMP */
924
925 static void
926 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva)
927 {
928
929         KASSERT((sva & PAGE_MASK) == 0,
930             ("pmap_invalidate_cache_range: sva not page-aligned"));
931         KASSERT((eva & PAGE_MASK) == 0,
932             ("pmap_invalidate_cache_range: eva not page-aligned"));
933
934         if (cpu_feature & CPUID_SS)
935                 ; /* If "Self Snoop" is supported, do nothing. */
936         else if (cpu_feature & CPUID_CLFSH) {
937
938                 /*
939                  * Otherwise, do per-cache line flush.  Use the mfence
940                  * instruction to insure that previous stores are
941                  * included in the write-back.  The processor
942                  * propagates flush to other processors in the cache
943                  * coherence domain.
944                  */
945                 mfence();
946                 for (; eva < sva; eva += cpu_clflush_line_size)
947                         clflush(eva);
948                 mfence();
949         } else {
950
951                 /*
952                  * No targeted cache flush methods are supported by CPU,
953                  * globally invalidate cache as a last resort.
954                  */
955                 pmap_invalidate_cache();
956         }
957 }
958
959 /*
960  * Are we current address space or kernel?
961  */
962 static __inline int
963 pmap_is_current(pmap_t pmap)
964 {
965         return (pmap == kernel_pmap ||
966             (pmap->pm_pml4[PML4PML4I] & PG_FRAME) == (PML4pml4e[0] & PG_FRAME));
967 }
968
969 /*
970  *      Routine:        pmap_extract
971  *      Function:
972  *              Extract the physical page address associated
973  *              with the given map/virtual_address pair.
974  */
975 vm_paddr_t 
976 pmap_extract(pmap_t pmap, vm_offset_t va)
977 {
978         vm_paddr_t rtval;
979         pt_entry_t *pte;
980         pd_entry_t pde, *pdep;
981
982         rtval = 0;
983         PMAP_LOCK(pmap);
984         pdep = pmap_pde(pmap, va);
985         if (pdep != NULL) {
986                 pde = *pdep;
987                 if (pde) {
988                         if ((pde & PG_PS) != 0)
989                                 rtval = (pde & PG_PS_FRAME) | (va & PDRMASK);
990                         else {
991                                 pte = pmap_pde_to_pte(pdep, va);
992                                 rtval = (*pte & PG_FRAME) | (va & PAGE_MASK);
993                         }
994                 }
995         }
996         PMAP_UNLOCK(pmap);
997         return (rtval);
998 }
999
1000 /*
1001  *      Routine:        pmap_extract_and_hold
1002  *      Function:
1003  *              Atomically extract and hold the physical page
1004  *              with the given pmap and virtual address pair
1005  *              if that mapping permits the given protection.
1006  */
1007 vm_page_t
1008 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
1009 {
1010         pd_entry_t pde, *pdep;
1011         pt_entry_t pte;
1012         vm_page_t m;
1013
1014         m = NULL;
1015         vm_page_lock_queues();
1016         PMAP_LOCK(pmap);
1017         pdep = pmap_pde(pmap, va);
1018         if (pdep != NULL && (pde = *pdep)) {
1019                 if (pde & PG_PS) {
1020                         if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0) {
1021                                 m = PHYS_TO_VM_PAGE((pde & PG_PS_FRAME) |
1022                                     (va & PDRMASK));
1023                                 vm_page_hold(m);
1024                         }
1025                 } else {
1026                         pte = *pmap_pde_to_pte(pdep, va);
1027                         if ((pte & PG_V) &&
1028                             ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
1029                                 m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
1030                                 vm_page_hold(m);
1031                         }
1032                 }
1033         }
1034         vm_page_unlock_queues();
1035         PMAP_UNLOCK(pmap);
1036         return (m);
1037 }
1038
1039 vm_paddr_t
1040 pmap_kextract(vm_offset_t va)
1041 {
1042         pd_entry_t pde;
1043         vm_paddr_t pa;
1044
1045         if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
1046                 pa = DMAP_TO_PHYS(va);
1047         } else {
1048                 pde = *vtopde(va);
1049                 if (pde & PG_PS) {
1050                         pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
1051                 } else {
1052                         /*
1053                          * Beware of a concurrent promotion that changes the
1054                          * PDE at this point!  For example, vtopte() must not
1055                          * be used to access the PTE because it would use the
1056                          * new PDE.  It is, however, safe to use the old PDE
1057                          * because the page table page is preserved by the
1058                          * promotion.
1059                          */
1060                         pa = *pmap_pde_to_pte(&pde, va);
1061                         pa = (pa & PG_FRAME) | (va & PAGE_MASK);
1062                 }
1063         }
1064         return pa;
1065 }
1066
1067 /***************************************************
1068  * Low level mapping routines.....
1069  ***************************************************/
1070
1071 /*
1072  * Add a wired page to the kva.
1073  * Note: not SMP coherent.
1074  */
1075 PMAP_INLINE void 
1076 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
1077 {
1078         pt_entry_t *pte;
1079
1080         pte = vtopte(va);
1081         pte_store(pte, pa | PG_RW | PG_V | PG_G);
1082 }
1083
1084 static __inline void
1085 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
1086 {
1087         pt_entry_t *pte;
1088
1089         pte = vtopte(va);
1090         pte_store(pte, pa | PG_RW | PG_V | PG_G | pmap_cache_bits(mode, 0));
1091 }
1092
1093 /*
1094  * Remove a page from the kernel pagetables.
1095  * Note: not SMP coherent.
1096  */
1097 PMAP_INLINE void
1098 pmap_kremove(vm_offset_t va)
1099 {
1100         pt_entry_t *pte;
1101
1102         pte = vtopte(va);
1103         pte_clear(pte);
1104 }
1105
1106 /*
1107  *      Used to map a range of physical addresses into kernel
1108  *      virtual address space.
1109  *
1110  *      The value passed in '*virt' is a suggested virtual address for
1111  *      the mapping. Architectures which can support a direct-mapped
1112  *      physical to virtual region can return the appropriate address
1113  *      within that region, leaving '*virt' unchanged. Other
1114  *      architectures should map the pages starting at '*virt' and
1115  *      update '*virt' with the first usable address after the mapped
1116  *      region.
1117  */
1118 vm_offset_t
1119 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
1120 {
1121         return PHYS_TO_DMAP(start);
1122 }
1123
1124
1125 /*
1126  * Add a list of wired pages to the kva
1127  * this routine is only used for temporary
1128  * kernel mappings that do not need to have
1129  * page modification or references recorded.
1130  * Note that old mappings are simply written
1131  * over.  The page *must* be wired.
1132  * Note: SMP coherent.  Uses a ranged shootdown IPI.
1133  */
1134 void
1135 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
1136 {
1137         pt_entry_t *endpte, oldpte, *pte;
1138
1139         oldpte = 0;
1140         pte = vtopte(sva);
1141         endpte = pte + count;
1142         while (pte < endpte) {
1143                 oldpte |= *pte;
1144                 pte_store(pte, VM_PAGE_TO_PHYS(*ma) | PG_G |
1145                     pmap_cache_bits((*ma)->md.pat_mode, 0) | PG_RW | PG_V);
1146                 pte++;
1147                 ma++;
1148         }
1149         if ((oldpte & PG_V) != 0)
1150                 pmap_invalidate_range(kernel_pmap, sva, sva + count *
1151                     PAGE_SIZE);
1152 }
1153
1154 /*
1155  * This routine tears out page mappings from the
1156  * kernel -- it is meant only for temporary mappings.
1157  * Note: SMP coherent.  Uses a ranged shootdown IPI.
1158  */
1159 void
1160 pmap_qremove(vm_offset_t sva, int count)
1161 {
1162         vm_offset_t va;
1163
1164         va = sva;
1165         while (count-- > 0) {
1166                 pmap_kremove(va);
1167                 va += PAGE_SIZE;
1168         }
1169         pmap_invalidate_range(kernel_pmap, sva, va);
1170 }
1171
1172 /***************************************************
1173  * Page table page management routines.....
1174  ***************************************************/
1175 static __inline void
1176 pmap_free_zero_pages(vm_page_t free)
1177 {
1178         vm_page_t m;
1179
1180         while (free != NULL) {
1181                 m = free;
1182                 free = m->right;
1183                 /* Preserve the page's PG_ZERO setting. */
1184                 vm_page_free_toq(m);
1185         }
1186 }
1187
1188 /*
1189  * Schedule the specified unused page table page to be freed.  Specifically,
1190  * add the page to the specified list of pages that will be released to the
1191  * physical memory manager after the TLB has been updated.
1192  */
1193 static __inline void
1194 pmap_add_delayed_free_list(vm_page_t m, vm_page_t *free, boolean_t set_PG_ZERO)
1195 {
1196
1197         if (set_PG_ZERO)
1198                 m->flags |= PG_ZERO;
1199         else
1200                 m->flags &= ~PG_ZERO;
1201         m->right = *free;
1202         *free = m;
1203 }
1204         
1205 /*
1206  * Inserts the specified page table page into the specified pmap's collection
1207  * of idle page table pages.  Each of a pmap's page table pages is responsible
1208  * for mapping a distinct range of virtual addresses.  The pmap's collection is
1209  * ordered by this virtual address range.
1210  */
1211 static void
1212 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte)
1213 {
1214         vm_page_t root;
1215
1216         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1217         root = pmap->pm_root;
1218         if (root == NULL) {
1219                 mpte->left = NULL;
1220                 mpte->right = NULL;
1221         } else {
1222                 root = vm_page_splay(mpte->pindex, root);
1223                 if (mpte->pindex < root->pindex) {
1224                         mpte->left = root->left;
1225                         mpte->right = root;
1226                         root->left = NULL;
1227                 } else if (mpte->pindex == root->pindex)
1228                         panic("pmap_insert_pt_page: pindex already inserted");
1229                 else {
1230                         mpte->right = root->right;
1231                         mpte->left = root;
1232                         root->right = NULL;
1233                 }
1234         }
1235         pmap->pm_root = mpte;
1236 }
1237
1238 /*
1239  * Looks for a page table page mapping the specified virtual address in the
1240  * specified pmap's collection of idle page table pages.  Returns NULL if there
1241  * is no page table page corresponding to the specified virtual address.
1242  */
1243 static vm_page_t
1244 pmap_lookup_pt_page(pmap_t pmap, vm_offset_t va)
1245 {
1246         vm_page_t mpte;
1247         vm_pindex_t pindex = pmap_pde_pindex(va);
1248
1249         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1250         if ((mpte = pmap->pm_root) != NULL && mpte->pindex != pindex) {
1251                 mpte = vm_page_splay(pindex, mpte);
1252                 if ((pmap->pm_root = mpte)->pindex != pindex)
1253                         mpte = NULL;
1254         }
1255         return (mpte);
1256 }
1257
1258 /*
1259  * Removes the specified page table page from the specified pmap's collection
1260  * of idle page table pages.  The specified page table page must be a member of
1261  * the pmap's collection.
1262  */
1263 static void
1264 pmap_remove_pt_page(pmap_t pmap, vm_page_t mpte)
1265 {
1266         vm_page_t root;
1267
1268         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1269         if (mpte != pmap->pm_root) {
1270                 root = vm_page_splay(mpte->pindex, pmap->pm_root);
1271                 KASSERT(mpte == root,
1272                     ("pmap_remove_pt_page: mpte %p is missing from pmap %p",
1273                     mpte, pmap));
1274         }
1275         if (mpte->left == NULL)
1276                 root = mpte->right;
1277         else {
1278                 root = vm_page_splay(mpte->pindex, mpte->left);
1279                 root->right = mpte->right;
1280         }
1281         pmap->pm_root = root;
1282 }
1283
1284 /*
1285  * This routine unholds page table pages, and if the hold count
1286  * drops to zero, then it decrements the wire count.
1287  */
1288 static __inline int
1289 pmap_unwire_pte_hold(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_page_t *free)
1290 {
1291
1292         --m->wire_count;
1293         if (m->wire_count == 0)
1294                 return _pmap_unwire_pte_hold(pmap, va, m, free);
1295         else
1296                 return 0;
1297 }
1298
1299 static int 
1300 _pmap_unwire_pte_hold(pmap_t pmap, vm_offset_t va, vm_page_t m, 
1301     vm_page_t *free)
1302 {
1303
1304         /*
1305          * unmap the page table page
1306          */
1307         if (m->pindex >= (NUPDE + NUPDPE)) {
1308                 /* PDP page */
1309                 pml4_entry_t *pml4;
1310                 pml4 = pmap_pml4e(pmap, va);
1311                 *pml4 = 0;
1312         } else if (m->pindex >= NUPDE) {
1313                 /* PD page */
1314                 pdp_entry_t *pdp;
1315                 pdp = pmap_pdpe(pmap, va);
1316                 *pdp = 0;
1317         } else {
1318                 /* PTE page */
1319                 pd_entry_t *pd;
1320                 pd = pmap_pde(pmap, va);
1321                 *pd = 0;
1322         }
1323         --pmap->pm_stats.resident_count;
1324         if (m->pindex < NUPDE) {
1325                 /* We just released a PT, unhold the matching PD */
1326                 vm_page_t pdpg;
1327
1328                 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
1329                 pmap_unwire_pte_hold(pmap, va, pdpg, free);
1330         }
1331         if (m->pindex >= NUPDE && m->pindex < (NUPDE + NUPDPE)) {
1332                 /* We just released a PD, unhold the matching PDP */
1333                 vm_page_t pdppg;
1334
1335                 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
1336                 pmap_unwire_pte_hold(pmap, va, pdppg, free);
1337         }
1338
1339         /*
1340          * This is a release store so that the ordinary store unmapping
1341          * the page table page is globally performed before TLB shoot-
1342          * down is begun.
1343          */
1344         atomic_subtract_rel_int(&cnt.v_wire_count, 1);
1345
1346         /* 
1347          * Put page on a list so that it is released after
1348          * *ALL* TLB shootdown is done
1349          */
1350         pmap_add_delayed_free_list(m, free, TRUE);
1351         
1352         return 1;
1353 }
1354
1355 /*
1356  * After removing a page table entry, this routine is used to
1357  * conditionally free the page, and manage the hold/wire counts.
1358  */
1359 static int
1360 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde, vm_page_t *free)
1361 {
1362         vm_page_t mpte;
1363
1364         if (va >= VM_MAXUSER_ADDRESS)
1365                 return 0;
1366         KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
1367         mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
1368         return pmap_unwire_pte_hold(pmap, va, mpte, free);
1369 }
1370
1371 void
1372 pmap_pinit0(pmap_t pmap)
1373 {
1374
1375         PMAP_LOCK_INIT(pmap);
1376         pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
1377         pmap->pm_root = NULL;
1378         pmap->pm_active = 0;
1379         TAILQ_INIT(&pmap->pm_pvchunk);
1380         bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
1381 }
1382
1383 /*
1384  * Initialize a preallocated and zeroed pmap structure,
1385  * such as one in a vmspace structure.
1386  */
1387 int
1388 pmap_pinit(pmap_t pmap)
1389 {
1390         vm_page_t pml4pg;
1391         static vm_pindex_t color;
1392
1393         PMAP_LOCK_INIT(pmap);
1394
1395         /*
1396          * allocate the page directory page
1397          */
1398         while ((pml4pg = vm_page_alloc(NULL, color++, VM_ALLOC_NOOBJ |
1399             VM_ALLOC_NORMAL | VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL)
1400                 VM_WAIT;
1401
1402         pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
1403
1404         if ((pml4pg->flags & PG_ZERO) == 0)
1405                 pagezero(pmap->pm_pml4);
1406
1407         /* Wire in kernel global address entries. */
1408         pmap->pm_pml4[KPML4I] = KPDPphys | PG_RW | PG_V | PG_U;
1409         pmap->pm_pml4[DMPML4I] = DMPDPphys | PG_RW | PG_V | PG_U;
1410
1411         /* install self-referential address mapping entry(s) */
1412         pmap->pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) | PG_V | PG_RW | PG_A | PG_M;
1413
1414         pmap->pm_root = NULL;
1415         pmap->pm_active = 0;
1416         TAILQ_INIT(&pmap->pm_pvchunk);
1417         bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
1418
1419         return (1);
1420 }
1421
1422 /*
1423  * this routine is called if the page table page is not
1424  * mapped correctly.
1425  *
1426  * Note: If a page allocation fails at page table level two or three,
1427  * one or two pages may be held during the wait, only to be released
1428  * afterwards.  This conservative approach is easily argued to avoid
1429  * race conditions.
1430  */
1431 static vm_page_t
1432 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, int flags)
1433 {
1434         vm_page_t m, pdppg, pdpg;
1435
1436         KASSERT((flags & (M_NOWAIT | M_WAITOK)) == M_NOWAIT ||
1437             (flags & (M_NOWAIT | M_WAITOK)) == M_WAITOK,
1438             ("_pmap_allocpte: flags is neither M_NOWAIT nor M_WAITOK"));
1439
1440         /*
1441          * Allocate a page table page.
1442          */
1443         if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
1444             VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
1445                 if (flags & M_WAITOK) {
1446                         PMAP_UNLOCK(pmap);
1447                         vm_page_unlock_queues();
1448                         VM_WAIT;
1449                         vm_page_lock_queues();
1450                         PMAP_LOCK(pmap);
1451                 }
1452
1453                 /*
1454                  * Indicate the need to retry.  While waiting, the page table
1455                  * page may have been allocated.
1456                  */
1457                 return (NULL);
1458         }
1459         if ((m->flags & PG_ZERO) == 0)
1460                 pmap_zero_page(m);
1461
1462         /*
1463          * Map the pagetable page into the process address space, if
1464          * it isn't already there.
1465          */
1466
1467         if (ptepindex >= (NUPDE + NUPDPE)) {
1468                 pml4_entry_t *pml4;
1469                 vm_pindex_t pml4index;
1470
1471                 /* Wire up a new PDPE page */
1472                 pml4index = ptepindex - (NUPDE + NUPDPE);
1473                 pml4 = &pmap->pm_pml4[pml4index];
1474                 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
1475
1476         } else if (ptepindex >= NUPDE) {
1477                 vm_pindex_t pml4index;
1478                 vm_pindex_t pdpindex;
1479                 pml4_entry_t *pml4;
1480                 pdp_entry_t *pdp;
1481
1482                 /* Wire up a new PDE page */
1483                 pdpindex = ptepindex - NUPDE;
1484                 pml4index = pdpindex >> NPML4EPGSHIFT;
1485
1486                 pml4 = &pmap->pm_pml4[pml4index];
1487                 if ((*pml4 & PG_V) == 0) {
1488                         /* Have to allocate a new pdp, recurse */
1489                         if (_pmap_allocpte(pmap, NUPDE + NUPDPE + pml4index,
1490                             flags) == NULL) {
1491                                 --m->wire_count;
1492                                 atomic_subtract_int(&cnt.v_wire_count, 1);
1493                                 vm_page_free_zero(m);
1494                                 return (NULL);
1495                         }
1496                 } else {
1497                         /* Add reference to pdp page */
1498                         pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
1499                         pdppg->wire_count++;
1500                 }
1501                 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
1502
1503                 /* Now find the pdp page */
1504                 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
1505                 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
1506
1507         } else {
1508                 vm_pindex_t pml4index;
1509                 vm_pindex_t pdpindex;
1510                 pml4_entry_t *pml4;
1511                 pdp_entry_t *pdp;
1512                 pd_entry_t *pd;
1513
1514                 /* Wire up a new PTE page */
1515                 pdpindex = ptepindex >> NPDPEPGSHIFT;
1516                 pml4index = pdpindex >> NPML4EPGSHIFT;
1517
1518                 /* First, find the pdp and check that its valid. */
1519                 pml4 = &pmap->pm_pml4[pml4index];
1520                 if ((*pml4 & PG_V) == 0) {
1521                         /* Have to allocate a new pd, recurse */
1522                         if (_pmap_allocpte(pmap, NUPDE + pdpindex,
1523                             flags) == NULL) {
1524                                 --m->wire_count;
1525                                 atomic_subtract_int(&cnt.v_wire_count, 1);
1526                                 vm_page_free_zero(m);
1527                                 return (NULL);
1528                         }
1529                         pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
1530                         pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
1531                 } else {
1532                         pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
1533                         pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
1534                         if ((*pdp & PG_V) == 0) {
1535                                 /* Have to allocate a new pd, recurse */
1536                                 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
1537                                     flags) == NULL) {
1538                                         --m->wire_count;
1539                                         atomic_subtract_int(&cnt.v_wire_count,
1540                                             1);
1541                                         vm_page_free_zero(m);
1542                                         return (NULL);
1543                                 }
1544                         } else {
1545                                 /* Add reference to the pd page */
1546                                 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
1547                                 pdpg->wire_count++;
1548                         }
1549                 }
1550                 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
1551
1552                 /* Now we know where the page directory page is */
1553                 pd = &pd[ptepindex & ((1ul << NPDEPGSHIFT) - 1)];
1554                 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
1555         }
1556
1557         pmap->pm_stats.resident_count++;
1558
1559         return m;
1560 }
1561
1562 static vm_page_t
1563 pmap_allocpde(pmap_t pmap, vm_offset_t va, int flags)
1564 {
1565         vm_pindex_t pdpindex, ptepindex;
1566         pdp_entry_t *pdpe;
1567         vm_page_t pdpg;
1568
1569         KASSERT((flags & (M_NOWAIT | M_WAITOK)) == M_NOWAIT ||
1570             (flags & (M_NOWAIT | M_WAITOK)) == M_WAITOK,
1571             ("pmap_allocpde: flags is neither M_NOWAIT nor M_WAITOK"));
1572 retry:
1573         pdpe = pmap_pdpe(pmap, va);
1574         if (pdpe != NULL && (*pdpe & PG_V) != 0) {
1575                 /* Add a reference to the pd page. */
1576                 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
1577                 pdpg->wire_count++;
1578         } else {
1579                 /* Allocate a pd page. */
1580                 ptepindex = pmap_pde_pindex(va);
1581                 pdpindex = ptepindex >> NPDPEPGSHIFT;
1582                 pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex, flags);
1583                 if (pdpg == NULL && (flags & M_WAITOK))
1584                         goto retry;
1585         }
1586         return (pdpg);
1587 }
1588
1589 static vm_page_t
1590 pmap_allocpte(pmap_t pmap, vm_offset_t va, int flags)
1591 {
1592         vm_pindex_t ptepindex;
1593         pd_entry_t *pd;
1594         vm_page_t m;
1595
1596         KASSERT((flags & (M_NOWAIT | M_WAITOK)) == M_NOWAIT ||
1597             (flags & (M_NOWAIT | M_WAITOK)) == M_WAITOK,
1598             ("pmap_allocpte: flags is neither M_NOWAIT nor M_WAITOK"));
1599
1600         /*
1601          * Calculate pagetable page index
1602          */
1603         ptepindex = pmap_pde_pindex(va);
1604 retry:
1605         /*
1606          * Get the page directory entry
1607          */
1608         pd = pmap_pde(pmap, va);
1609
1610         /*
1611          * This supports switching from a 2MB page to a
1612          * normal 4K page.
1613          */
1614         if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
1615                 if (!pmap_demote_pde(pmap, pd, va)) {
1616                         /*
1617                          * Invalidation of the 2MB page mapping may have caused
1618                          * the deallocation of the underlying PD page.
1619                          */
1620                         pd = NULL;
1621                 }
1622         }
1623
1624         /*
1625          * If the page table page is mapped, we just increment the
1626          * hold count, and activate it.
1627          */
1628         if (pd != NULL && (*pd & PG_V) != 0) {
1629                 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
1630                 m->wire_count++;
1631         } else {
1632                 /*
1633                  * Here if the pte page isn't mapped, or if it has been
1634                  * deallocated.
1635                  */
1636                 m = _pmap_allocpte(pmap, ptepindex, flags);
1637                 if (m == NULL && (flags & M_WAITOK))
1638                         goto retry;
1639         }
1640         return (m);
1641 }
1642
1643
1644 /***************************************************
1645  * Pmap allocation/deallocation routines.
1646  ***************************************************/
1647
1648 /*
1649  * Release any resources held by the given physical map.
1650  * Called when a pmap initialized by pmap_pinit is being released.
1651  * Should only be called if the map contains no valid mappings.
1652  */
1653 void
1654 pmap_release(pmap_t pmap)
1655 {
1656         vm_page_t m;
1657
1658         KASSERT(pmap->pm_stats.resident_count == 0,
1659             ("pmap_release: pmap resident count %ld != 0",
1660             pmap->pm_stats.resident_count));
1661         KASSERT(pmap->pm_root == NULL,
1662             ("pmap_release: pmap has reserved page table page(s)"));
1663
1664         m = PHYS_TO_VM_PAGE(pmap->pm_pml4[PML4PML4I] & PG_FRAME);
1665
1666         pmap->pm_pml4[KPML4I] = 0;      /* KVA */
1667         pmap->pm_pml4[DMPML4I] = 0;     /* Direct Map */
1668         pmap->pm_pml4[PML4PML4I] = 0;   /* Recursive Mapping */
1669
1670         m->wire_count--;
1671         atomic_subtract_int(&cnt.v_wire_count, 1);
1672         vm_page_free_zero(m);
1673         PMAP_LOCK_DESTROY(pmap);
1674 }
1675 \f
1676 static int
1677 kvm_size(SYSCTL_HANDLER_ARGS)
1678 {
1679         unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
1680
1681         return sysctl_handle_long(oidp, &ksize, 0, req);
1682 }
1683 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD, 
1684     0, 0, kvm_size, "LU", "Size of KVM");
1685
1686 static int
1687 kvm_free(SYSCTL_HANDLER_ARGS)
1688 {
1689         unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
1690
1691         return sysctl_handle_long(oidp, &kfree, 0, req);
1692 }
1693 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD, 
1694     0, 0, kvm_free, "LU", "Amount of KVM free");
1695
1696 /*
1697  * grow the number of kernel page table entries, if needed
1698  */
1699 void
1700 pmap_growkernel(vm_offset_t addr)
1701 {
1702         vm_paddr_t paddr;
1703         vm_page_t nkpg;
1704         pd_entry_t *pde, newpdir;
1705         pdp_entry_t *pdpe;
1706
1707         mtx_assert(&kernel_map->system_mtx, MA_OWNED);
1708
1709         /*
1710          * Return if "addr" is within the range of kernel page table pages
1711          * that were preallocated during pmap bootstrap.  Moreover, leave
1712          * "kernel_vm_end" and the kernel page table as they were.
1713          *
1714          * The correctness of this action is based on the following
1715          * argument: vm_map_findspace() allocates contiguous ranges of the
1716          * kernel virtual address space.  It calls this function if a range
1717          * ends after "kernel_vm_end".  If the kernel is mapped between
1718          * "kernel_vm_end" and "addr", then the range cannot begin at
1719          * "kernel_vm_end".  In fact, its beginning address cannot be less
1720          * than the kernel.  Thus, there is no immediate need to allocate
1721          * any new kernel page table pages between "kernel_vm_end" and
1722          * "KERNBASE".
1723          */
1724         if (KERNBASE < addr && addr <= KERNBASE + NKPT * NBPDR)
1725                 return;
1726
1727         addr = roundup2(addr, NBPDR);
1728         if (addr - 1 >= kernel_map->max_offset)
1729                 addr = kernel_map->max_offset;
1730         while (kernel_vm_end < addr) {
1731                 pdpe = pmap_pdpe(kernel_pmap, kernel_vm_end);
1732                 if ((*pdpe & PG_V) == 0) {
1733                         /* We need a new PDP entry */
1734                         nkpg = vm_page_alloc(NULL, kernel_vm_end >> PDPSHIFT,
1735                             VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ |
1736                             VM_ALLOC_WIRED | VM_ALLOC_ZERO);
1737                         if (nkpg == NULL)
1738                                 panic("pmap_growkernel: no memory to grow kernel");
1739                         if ((nkpg->flags & PG_ZERO) == 0)
1740                                 pmap_zero_page(nkpg);
1741                         paddr = VM_PAGE_TO_PHYS(nkpg);
1742                         *pdpe = (pdp_entry_t)
1743                                 (paddr | PG_V | PG_RW | PG_A | PG_M);
1744                         continue; /* try again */
1745                 }
1746                 pde = pmap_pdpe_to_pde(pdpe, kernel_vm_end);
1747                 if ((*pde & PG_V) != 0) {
1748                         kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
1749                         if (kernel_vm_end - 1 >= kernel_map->max_offset) {
1750                                 kernel_vm_end = kernel_map->max_offset;
1751                                 break;                       
1752                         }
1753                         continue;
1754                 }
1755
1756                 nkpg = vm_page_alloc(NULL, pmap_pde_pindex(kernel_vm_end),
1757                     VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
1758                     VM_ALLOC_ZERO);
1759                 if (nkpg == NULL)
1760                         panic("pmap_growkernel: no memory to grow kernel");
1761                 if ((nkpg->flags & PG_ZERO) == 0)
1762                         pmap_zero_page(nkpg);
1763                 paddr = VM_PAGE_TO_PHYS(nkpg);
1764                 newpdir = (pd_entry_t) (paddr | PG_V | PG_RW | PG_A | PG_M);
1765                 pde_store(pde, newpdir);
1766
1767                 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
1768                 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
1769                         kernel_vm_end = kernel_map->max_offset;
1770                         break;                       
1771                 }
1772         }
1773 }
1774
1775
1776 /***************************************************
1777  * page management routines.
1778  ***************************************************/
1779
1780 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
1781 CTASSERT(_NPCM == 3);
1782 CTASSERT(_NPCPV == 168);
1783
1784 static __inline struct pv_chunk *
1785 pv_to_chunk(pv_entry_t pv)
1786 {
1787
1788         return (struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK);
1789 }
1790
1791 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
1792
1793 #define PC_FREE0        0xfffffffffffffffful
1794 #define PC_FREE1        0xfffffffffffffffful
1795 #define PC_FREE2        0x000000fffffffffful
1796
1797 static uint64_t pc_freemask[_NPCM] = { PC_FREE0, PC_FREE1, PC_FREE2 };
1798
1799 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
1800         "Current number of pv entries");
1801
1802 #ifdef PV_STATS
1803 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
1804
1805 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
1806         "Current number of pv entry chunks");
1807 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
1808         "Current number of pv entry chunks allocated");
1809 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
1810         "Current number of pv entry chunks frees");
1811 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
1812         "Number of times tried to get a chunk page but failed.");
1813
1814 static long pv_entry_frees, pv_entry_allocs;
1815 static int pv_entry_spare;
1816
1817 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
1818         "Current number of pv entry frees");
1819 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
1820         "Current number of pv entry allocs");
1821 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
1822         "Current number of spare pv entries");
1823
1824 static int pmap_collect_inactive, pmap_collect_active;
1825
1826 SYSCTL_INT(_vm_pmap, OID_AUTO, pmap_collect_inactive, CTLFLAG_RD, &pmap_collect_inactive, 0,
1827         "Current number times pmap_collect called on inactive queue");
1828 SYSCTL_INT(_vm_pmap, OID_AUTO, pmap_collect_active, CTLFLAG_RD, &pmap_collect_active, 0,
1829         "Current number times pmap_collect called on active queue");
1830 #endif
1831
1832 /*
1833  * We are in a serious low memory condition.  Resort to
1834  * drastic measures to free some pages so we can allocate
1835  * another pv entry chunk.  This is normally called to
1836  * unmap inactive pages, and if necessary, active pages.
1837  *
1838  * We do not, however, unmap 2mpages because subsequent accesses will
1839  * allocate per-page pv entries until repromotion occurs, thereby
1840  * exacerbating the shortage of free pv entries.
1841  */
1842 static void
1843 pmap_collect(pmap_t locked_pmap, struct vpgqueues *vpq)
1844 {
1845         struct md_page *pvh;
1846         pd_entry_t *pde;
1847         pmap_t pmap;
1848         pt_entry_t *pte, tpte;
1849         pv_entry_t next_pv, pv;
1850         vm_offset_t va;
1851         vm_page_t m, free;
1852
1853         TAILQ_FOREACH(m, &vpq->pl, pageq) {
1854                 if (m->hold_count || m->busy)
1855                         continue;
1856                 TAILQ_FOREACH_SAFE(pv, &m->md.pv_list, pv_list, next_pv) {
1857                         va = pv->pv_va;
1858                         pmap = PV_PMAP(pv);
1859                         /* Avoid deadlock and lock recursion. */
1860                         if (pmap > locked_pmap)
1861                                 PMAP_LOCK(pmap);
1862                         else if (pmap != locked_pmap && !PMAP_TRYLOCK(pmap))
1863                                 continue;
1864                         pmap->pm_stats.resident_count--;
1865                         pde = pmap_pde(pmap, va);
1866                         KASSERT((*pde & PG_PS) == 0, ("pmap_collect: found"
1867                             " a 2mpage in page %p's pv list", m));
1868                         pte = pmap_pde_to_pte(pde, va);
1869                         tpte = pte_load_clear(pte);
1870                         KASSERT((tpte & PG_W) == 0,
1871                             ("pmap_collect: wired pte %#lx", tpte));
1872                         if (tpte & PG_A)
1873                                 vm_page_flag_set(m, PG_REFERENCED);
1874                         if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
1875                                 vm_page_dirty(m);
1876                         free = NULL;
1877                         pmap_unuse_pt(pmap, va, *pde, &free);
1878                         pmap_invalidate_page(pmap, va);
1879                         pmap_free_zero_pages(free);
1880                         TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
1881                         if (TAILQ_EMPTY(&m->md.pv_list)) {
1882                                 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
1883                                 if (TAILQ_EMPTY(&pvh->pv_list))
1884                                         vm_page_flag_clear(m, PG_WRITEABLE);
1885                         }
1886                         free_pv_entry(pmap, pv);
1887                         if (pmap != locked_pmap)
1888                                 PMAP_UNLOCK(pmap);
1889                 }
1890         }
1891 }
1892
1893
1894 /*
1895  * free the pv_entry back to the free list
1896  */
1897 static void
1898 free_pv_entry(pmap_t pmap, pv_entry_t pv)
1899 {
1900         vm_page_t m;
1901         struct pv_chunk *pc;
1902         int idx, field, bit;
1903
1904         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1905         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1906         PV_STAT(pv_entry_frees++);
1907         PV_STAT(pv_entry_spare++);
1908         pv_entry_count--;
1909         pc = pv_to_chunk(pv);
1910         idx = pv - &pc->pc_pventry[0];
1911         field = idx / 64;
1912         bit = idx % 64;
1913         pc->pc_map[field] |= 1ul << bit;
1914         /* move to head of list */
1915         TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
1916         if (pc->pc_map[0] != PC_FREE0 || pc->pc_map[1] != PC_FREE1 ||
1917             pc->pc_map[2] != PC_FREE2) {
1918                 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
1919                 return;
1920         }
1921         PV_STAT(pv_entry_spare -= _NPCPV);
1922         PV_STAT(pc_chunk_count--);
1923         PV_STAT(pc_chunk_frees++);
1924         /* entire chunk is free, return it */
1925         m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
1926         dump_drop_page(m->phys_addr);
1927         vm_page_unwire(m, 0);
1928         vm_page_free(m);
1929 }
1930
1931 /*
1932  * get a new pv_entry, allocating a block from the system
1933  * when needed.
1934  */
1935 static pv_entry_t
1936 get_pv_entry(pmap_t pmap, int try)
1937 {
1938         static const struct timeval printinterval = { 60, 0 };
1939         static struct timeval lastprint;
1940         static vm_pindex_t colour;
1941         struct vpgqueues *pq;
1942         int bit, field;
1943         pv_entry_t pv;
1944         struct pv_chunk *pc;
1945         vm_page_t m;
1946
1947         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1948         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1949         PV_STAT(pv_entry_allocs++);
1950         pv_entry_count++;
1951         if (pv_entry_count > pv_entry_high_water)
1952                 if (ratecheck(&lastprint, &printinterval))
1953                         printf("Approaching the limit on PV entries, consider "
1954                             "increasing either the vm.pmap.shpgperproc or the "
1955                             "vm.pmap.pv_entry_max sysctl.\n");
1956         pq = NULL;
1957 retry:
1958         pc = TAILQ_FIRST(&pmap->pm_pvchunk);
1959         if (pc != NULL) {
1960                 for (field = 0; field < _NPCM; field++) {
1961                         if (pc->pc_map[field]) {
1962                                 bit = bsfq(pc->pc_map[field]);
1963                                 break;
1964                         }
1965                 }
1966                 if (field < _NPCM) {
1967                         pv = &pc->pc_pventry[field * 64 + bit];
1968                         pc->pc_map[field] &= ~(1ul << bit);
1969                         /* If this was the last item, move it to tail */
1970                         if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
1971                             pc->pc_map[2] == 0) {
1972                                 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
1973                                 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
1974                         }
1975                         PV_STAT(pv_entry_spare--);
1976                         return (pv);
1977                 }
1978         }
1979         /* No free items, allocate another chunk */
1980         m = vm_page_alloc(NULL, colour, (pq == &vm_page_queues[PQ_ACTIVE] ?
1981             VM_ALLOC_SYSTEM : VM_ALLOC_NORMAL) | VM_ALLOC_NOOBJ |
1982             VM_ALLOC_WIRED);
1983         if (m == NULL) {
1984                 if (try) {
1985                         pv_entry_count--;
1986                         PV_STAT(pc_chunk_tryfail++);
1987                         return (NULL);
1988                 }
1989                 /*
1990                  * Reclaim pv entries: At first, destroy mappings to inactive
1991                  * pages.  After that, if a pv chunk entry is still needed,
1992                  * destroy mappings to active pages.
1993                  */
1994                 if (pq == NULL) {
1995                         PV_STAT(pmap_collect_inactive++);
1996                         pq = &vm_page_queues[PQ_INACTIVE];
1997                 } else if (pq == &vm_page_queues[PQ_INACTIVE]) {
1998                         PV_STAT(pmap_collect_active++);
1999                         pq = &vm_page_queues[PQ_ACTIVE];
2000                 } else
2001                         panic("get_pv_entry: increase vm.pmap.shpgperproc");
2002                 pmap_collect(pmap, pq);
2003                 goto retry;
2004         }
2005         PV_STAT(pc_chunk_count++);
2006         PV_STAT(pc_chunk_allocs++);
2007         colour++;
2008         dump_add_page(m->phys_addr);
2009         pc = (void *)PHYS_TO_DMAP(m->phys_addr);
2010         pc->pc_pmap = pmap;
2011         pc->pc_map[0] = PC_FREE0 & ~1ul;        /* preallocated bit 0 */
2012         pc->pc_map[1] = PC_FREE1;
2013         pc->pc_map[2] = PC_FREE2;
2014         pv = &pc->pc_pventry[0];
2015         TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
2016         PV_STAT(pv_entry_spare += _NPCPV - 1);
2017         return (pv);
2018 }
2019
2020 /*
2021  * First find and then remove the pv entry for the specified pmap and virtual
2022  * address from the specified pv list.  Returns the pv entry if found and NULL
2023  * otherwise.  This operation can be performed on pv lists for either 4KB or
2024  * 2MB page mappings.
2025  */
2026 static __inline pv_entry_t
2027 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
2028 {
2029         pv_entry_t pv;
2030
2031         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2032         TAILQ_FOREACH(pv, &pvh->pv_list, pv_list) {
2033                 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
2034                         TAILQ_REMOVE(&pvh->pv_list, pv, pv_list);
2035                         break;
2036                 }
2037         }
2038         return (pv);
2039 }
2040
2041 /*
2042  * After demotion from a 2MB page mapping to 512 4KB page mappings,
2043  * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
2044  * entries for each of the 4KB page mappings.
2045  */
2046 static void
2047 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa)
2048 {
2049         struct md_page *pvh;
2050         pv_entry_t pv;
2051         vm_offset_t va_last;
2052         vm_page_t m;
2053
2054         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2055         KASSERT((pa & PDRMASK) == 0,
2056             ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
2057
2058         /*
2059          * Transfer the 2mpage's pv entry for this mapping to the first
2060          * page's pv list.
2061          */
2062         pvh = pa_to_pvh(pa);
2063         va = trunc_2mpage(va);
2064         pv = pmap_pvh_remove(pvh, pmap, va);
2065         KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
2066         m = PHYS_TO_VM_PAGE(pa);
2067         TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
2068         /* Instantiate the remaining NPTEPG - 1 pv entries. */
2069         va_last = va + NBPDR - PAGE_SIZE;
2070         do {
2071                 m++;
2072                 KASSERT((m->flags & (PG_FICTITIOUS | PG_UNMANAGED)) == 0,
2073                     ("pmap_pv_demote_pde: page %p is not managed", m));
2074                 va += PAGE_SIZE;
2075                 pmap_insert_entry(pmap, va, m);
2076         } while (va < va_last);
2077 }
2078
2079 /*
2080  * After promotion from 512 4KB page mappings to a single 2MB page mapping,
2081  * replace the many pv entries for the 4KB page mappings by a single pv entry
2082  * for the 2MB page mapping.
2083  */
2084 static void
2085 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa)
2086 {
2087         struct md_page *pvh;
2088         pv_entry_t pv;
2089         vm_offset_t va_last;
2090         vm_page_t m;
2091
2092         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2093         KASSERT((pa & PDRMASK) == 0,
2094             ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
2095
2096         /*
2097          * Transfer the first page's pv entry for this mapping to the
2098          * 2mpage's pv list.  Aside from avoiding the cost of a call
2099          * to get_pv_entry(), a transfer avoids the possibility that
2100          * get_pv_entry() calls pmap_collect() and that pmap_collect()
2101          * removes one of the mappings that is being promoted.
2102          */
2103         m = PHYS_TO_VM_PAGE(pa);
2104         va = trunc_2mpage(va);
2105         pv = pmap_pvh_remove(&m->md, pmap, va);
2106         KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
2107         pvh = pa_to_pvh(pa);
2108         TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_list);
2109         /* Free the remaining NPTEPG - 1 pv entries. */
2110         va_last = va + NBPDR - PAGE_SIZE;
2111         do {
2112                 m++;
2113                 va += PAGE_SIZE;
2114                 pmap_pvh_free(&m->md, pmap, va);
2115         } while (va < va_last);
2116 }
2117
2118 /*
2119  * First find and then destroy the pv entry for the specified pmap and virtual
2120  * address.  This operation can be performed on pv lists for either 4KB or 2MB
2121  * page mappings.
2122  */
2123 static void
2124 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
2125 {
2126         pv_entry_t pv;
2127
2128         pv = pmap_pvh_remove(pvh, pmap, va);
2129         KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
2130         free_pv_entry(pmap, pv);
2131 }
2132
2133 static void
2134 pmap_remove_entry(pmap_t pmap, vm_page_t m, vm_offset_t va)
2135 {
2136         struct md_page *pvh;
2137
2138         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2139         pmap_pvh_free(&m->md, pmap, va);
2140         if (TAILQ_EMPTY(&m->md.pv_list)) {
2141                 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
2142                 if (TAILQ_EMPTY(&pvh->pv_list))
2143                         vm_page_flag_clear(m, PG_WRITEABLE);
2144         }
2145 }
2146
2147 /*
2148  * Create a pv entry for page at pa for
2149  * (pmap, va).
2150  */
2151 static void
2152 pmap_insert_entry(pmap_t pmap, vm_offset_t va, vm_page_t m)
2153 {
2154         pv_entry_t pv;
2155
2156         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2157         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2158         pv = get_pv_entry(pmap, FALSE);
2159         pv->pv_va = va;
2160         TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
2161 }
2162
2163 /*
2164  * Conditionally create a pv entry.
2165  */
2166 static boolean_t
2167 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m)
2168 {
2169         pv_entry_t pv;
2170
2171         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2172         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2173         if (pv_entry_count < pv_entry_high_water && 
2174             (pv = get_pv_entry(pmap, TRUE)) != NULL) {
2175                 pv->pv_va = va;
2176                 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
2177                 return (TRUE);
2178         } else
2179                 return (FALSE);
2180 }
2181
2182 /*
2183  * Create the pv entry for a 2MB page mapping.
2184  */
2185 static boolean_t
2186 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa)
2187 {
2188         struct md_page *pvh;
2189         pv_entry_t pv;
2190
2191         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2192         if (pv_entry_count < pv_entry_high_water && 
2193             (pv = get_pv_entry(pmap, TRUE)) != NULL) {
2194                 pv->pv_va = va;
2195                 pvh = pa_to_pvh(pa);
2196                 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_list);
2197                 return (TRUE);
2198         } else
2199                 return (FALSE);
2200 }
2201
2202 /*
2203  * Fills a page table page with mappings to consecutive physical pages.
2204  */
2205 static void
2206 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
2207 {
2208         pt_entry_t *pte;
2209
2210         for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
2211                 *pte = newpte;
2212                 newpte += PAGE_SIZE;
2213         }
2214 }
2215
2216 /*
2217  * Tries to demote a 2MB page mapping.  If demotion fails, the 2MB page
2218  * mapping is invalidated.
2219  */
2220 static boolean_t
2221 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
2222 {
2223         pd_entry_t newpde, oldpde;
2224         pt_entry_t *firstpte, newpte;
2225         vm_paddr_t mptepa;
2226         vm_page_t free, mpte;
2227
2228         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2229         oldpde = *pde;
2230         KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
2231             ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
2232         mpte = pmap_lookup_pt_page(pmap, va);
2233         if (mpte != NULL)
2234                 pmap_remove_pt_page(pmap, mpte);
2235         else {
2236                 KASSERT((oldpde & PG_W) == 0,
2237                     ("pmap_demote_pde: page table page for a wired mapping"
2238                     " is missing"));
2239
2240                 /*
2241                  * Invalidate the 2MB page mapping and return "failure" if the
2242                  * mapping was never accessed or the allocation of the new
2243                  * page table page fails.  If the 2MB page mapping belongs to
2244                  * the direct map region of the kernel's address space, then
2245                  * the page allocation request specifies the highest possible
2246                  * priority (VM_ALLOC_INTERRUPT).  Otherwise, the priority is
2247                  * normal.  Page table pages are preallocated for every other
2248                  * part of the kernel address space, so the direct map region
2249                  * is the only part of the kernel address space that must be
2250                  * handled here.
2251                  */
2252                 if ((oldpde & PG_A) == 0 || (mpte = vm_page_alloc(NULL,
2253                     pmap_pde_pindex(va), (va >= DMAP_MIN_ADDRESS && va <
2254                     DMAP_MAX_ADDRESS ? VM_ALLOC_INTERRUPT : VM_ALLOC_NORMAL) |
2255                     VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
2256                         free = NULL;
2257                         pmap_remove_pde(pmap, pde, trunc_2mpage(va), &free);
2258                         pmap_invalidate_page(pmap, trunc_2mpage(va));
2259                         pmap_free_zero_pages(free);
2260                         CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx"
2261                             " in pmap %p", va, pmap);
2262                         return (FALSE);
2263                 }
2264         }
2265         mptepa = VM_PAGE_TO_PHYS(mpte);
2266         firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
2267         newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
2268         KASSERT((oldpde & PG_A) != 0,
2269             ("pmap_demote_pde: oldpde is missing PG_A"));
2270         KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
2271             ("pmap_demote_pde: oldpde is missing PG_M"));
2272         newpte = oldpde & ~PG_PS;
2273         if ((newpte & PG_PDE_PAT) != 0)
2274                 newpte ^= PG_PDE_PAT | PG_PTE_PAT;
2275
2276         /*
2277          * If the page table page is new, initialize it.
2278          */
2279         if (mpte->wire_count == 1) {
2280                 mpte->wire_count = NPTEPG;
2281                 pmap_fill_ptp(firstpte, newpte);
2282         }
2283         KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
2284             ("pmap_demote_pde: firstpte and newpte map different physical"
2285             " addresses"));
2286
2287         /*
2288          * If the mapping has changed attributes, update the page table
2289          * entries.
2290          */
2291         if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
2292                 pmap_fill_ptp(firstpte, newpte);
2293
2294         /*
2295          * Demote the mapping.  This pmap is locked.  The old PDE has
2296          * PG_A set.  If the old PDE has PG_RW set, it also has PG_M
2297          * set.  Thus, there is no danger of a race with another
2298          * processor changing the setting of PG_A and/or PG_M between
2299          * the read above and the store below. 
2300          */
2301         pde_store(pde, newpde); 
2302
2303         /*
2304          * Invalidate a stale recursive mapping of the page table page.
2305          */
2306         if (va >= VM_MAXUSER_ADDRESS)
2307                 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
2308
2309         /*
2310          * Demote the pv entry.  This depends on the earlier demotion
2311          * of the mapping.  Specifically, the (re)creation of a per-
2312          * page pv entry might trigger the execution of pmap_collect(),
2313          * which might reclaim a newly (re)created per-page pv entry
2314          * and destroy the associated mapping.  In order to destroy
2315          * the mapping, the PDE must have already changed from mapping
2316          * the 2mpage to referencing the page table page.
2317          */
2318         if ((oldpde & PG_MANAGED) != 0)
2319                 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME);
2320
2321         pmap_pde_demotions++;
2322         CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx"
2323             " in pmap %p", va, pmap);
2324         return (TRUE);
2325 }
2326
2327 /*
2328  * pmap_remove_pde: do the things to unmap a superpage in a process
2329  */
2330 static int
2331 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
2332     vm_page_t *free)
2333 {
2334         struct md_page *pvh;
2335         pd_entry_t oldpde;
2336         vm_offset_t eva, va;
2337         vm_page_t m, mpte;
2338
2339         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2340         KASSERT((sva & PDRMASK) == 0,
2341             ("pmap_remove_pde: sva is not 2mpage aligned"));
2342         oldpde = pte_load_clear(pdq);
2343         if (oldpde & PG_W)
2344                 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
2345
2346         /*
2347          * Machines that don't support invlpg, also don't support
2348          * PG_G.
2349          */
2350         if (oldpde & PG_G)
2351                 pmap_invalidate_page(kernel_pmap, sva);
2352         pmap->pm_stats.resident_count -= NBPDR / PAGE_SIZE;
2353         if (oldpde & PG_MANAGED) {
2354                 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
2355                 pmap_pvh_free(pvh, pmap, sva);
2356                 eva = sva + NBPDR;
2357                 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
2358                     va < eva; va += PAGE_SIZE, m++) {
2359                         if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
2360                                 vm_page_dirty(m);
2361                         if (oldpde & PG_A)
2362                                 vm_page_flag_set(m, PG_REFERENCED);
2363                         if (TAILQ_EMPTY(&m->md.pv_list) &&
2364                             TAILQ_EMPTY(&pvh->pv_list))
2365                                 vm_page_flag_clear(m, PG_WRITEABLE);
2366                 }
2367         }
2368         if (pmap == kernel_pmap) {
2369                 if (!pmap_demote_pde(pmap, pdq, sva))
2370                         panic("pmap_remove_pde: failed demotion");
2371         } else {
2372                 mpte = pmap_lookup_pt_page(pmap, sva);
2373                 if (mpte != NULL) {
2374                         pmap_remove_pt_page(pmap, mpte);
2375                         pmap->pm_stats.resident_count--;
2376                         KASSERT(mpte->wire_count == NPTEPG,
2377                             ("pmap_remove_pde: pte page wire count error"));
2378                         mpte->wire_count = 0;
2379                         pmap_add_delayed_free_list(mpte, free, FALSE);
2380                         atomic_subtract_int(&cnt.v_wire_count, 1);
2381                 }
2382         }
2383         return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
2384 }
2385
2386 /*
2387  * pmap_remove_pte: do the things to unmap a page in a process
2388  */
2389 static int
2390 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va, 
2391     pd_entry_t ptepde, vm_page_t *free)
2392 {
2393         pt_entry_t oldpte;
2394         vm_page_t m;
2395
2396         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2397         oldpte = pte_load_clear(ptq);
2398         if (oldpte & PG_W)
2399                 pmap->pm_stats.wired_count -= 1;
2400         /*
2401          * Machines that don't support invlpg, also don't support
2402          * PG_G.
2403          */
2404         if (oldpte & PG_G)
2405                 pmap_invalidate_page(kernel_pmap, va);
2406         pmap->pm_stats.resident_count -= 1;
2407         if (oldpte & PG_MANAGED) {
2408                 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
2409                 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
2410                         vm_page_dirty(m);
2411                 if (oldpte & PG_A)
2412                         vm_page_flag_set(m, PG_REFERENCED);
2413                 pmap_remove_entry(pmap, m, va);
2414         }
2415         return (pmap_unuse_pt(pmap, va, ptepde, free));
2416 }
2417
2418 /*
2419  * Remove a single page from a process address space
2420  */
2421 static void
2422 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, vm_page_t *free)
2423 {
2424         pt_entry_t *pte;
2425
2426         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2427         if ((*pde & PG_V) == 0)
2428                 return;
2429         pte = pmap_pde_to_pte(pde, va);
2430         if ((*pte & PG_V) == 0)
2431                 return;
2432         pmap_remove_pte(pmap, pte, va, *pde, free);
2433         pmap_invalidate_page(pmap, va);
2434 }
2435
2436 /*
2437  *      Remove the given range of addresses from the specified map.
2438  *
2439  *      It is assumed that the start and end are properly
2440  *      rounded to the page size.
2441  */
2442 void
2443 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
2444 {
2445         vm_offset_t va_next;
2446         pml4_entry_t *pml4e;
2447         pdp_entry_t *pdpe;
2448         pd_entry_t ptpaddr, *pde;
2449         pt_entry_t *pte;
2450         vm_page_t free = NULL;
2451         int anyvalid;
2452
2453         /*
2454          * Perform an unsynchronized read.  This is, however, safe.
2455          */
2456         if (pmap->pm_stats.resident_count == 0)
2457                 return;
2458
2459         anyvalid = 0;
2460
2461         vm_page_lock_queues();
2462         PMAP_LOCK(pmap);
2463
2464         /*
2465          * special handling of removing one page.  a very
2466          * common operation and easy to short circuit some
2467          * code.
2468          */
2469         if (sva + PAGE_SIZE == eva) {
2470                 pde = pmap_pde(pmap, sva);
2471                 if (pde && (*pde & PG_PS) == 0) {
2472                         pmap_remove_page(pmap, sva, pde, &free);
2473                         goto out;
2474                 }
2475         }
2476
2477         for (; sva < eva; sva = va_next) {
2478
2479                 if (pmap->pm_stats.resident_count == 0)
2480                         break;
2481
2482                 pml4e = pmap_pml4e(pmap, sva);
2483                 if ((*pml4e & PG_V) == 0) {
2484                         va_next = (sva + NBPML4) & ~PML4MASK;
2485                         if (va_next < sva)
2486                                 va_next = eva;
2487                         continue;
2488                 }
2489
2490                 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
2491                 if ((*pdpe & PG_V) == 0) {
2492                         va_next = (sva + NBPDP) & ~PDPMASK;
2493                         if (va_next < sva)
2494                                 va_next = eva;
2495                         continue;
2496                 }
2497
2498                 /*
2499                  * Calculate index for next page table.
2500                  */
2501                 va_next = (sva + NBPDR) & ~PDRMASK;
2502                 if (va_next < sva)
2503                         va_next = eva;
2504
2505                 pde = pmap_pdpe_to_pde(pdpe, sva);
2506                 ptpaddr = *pde;
2507
2508                 /*
2509                  * Weed out invalid mappings.
2510                  */
2511                 if (ptpaddr == 0)
2512                         continue;
2513
2514                 /*
2515                  * Check for large page.
2516                  */
2517                 if ((ptpaddr & PG_PS) != 0) {
2518                         /*
2519                          * Are we removing the entire large page?  If not,
2520                          * demote the mapping and fall through.
2521                          */
2522                         if (sva + NBPDR == va_next && eva >= va_next) {
2523                                 /*
2524                                  * The TLB entry for a PG_G mapping is
2525                                  * invalidated by pmap_remove_pde().
2526                                  */
2527                                 if ((ptpaddr & PG_G) == 0)
2528                                         anyvalid = 1;
2529                                 pmap_remove_pde(pmap, pde, sva, &free);
2530                                 continue;
2531                         } else if (!pmap_demote_pde(pmap, pde, sva)) {
2532                                 /* The large page mapping was destroyed. */
2533                                 continue;
2534                         } else
2535                                 ptpaddr = *pde;
2536                 }
2537
2538                 /*
2539                  * Limit our scan to either the end of the va represented
2540                  * by the current page table page, or to the end of the
2541                  * range being removed.
2542                  */
2543                 if (va_next > eva)
2544                         va_next = eva;
2545
2546                 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
2547                     sva += PAGE_SIZE) {
2548                         if (*pte == 0)
2549                                 continue;
2550
2551                         /*
2552                          * The TLB entry for a PG_G mapping is invalidated
2553                          * by pmap_remove_pte().
2554                          */
2555                         if ((*pte & PG_G) == 0)
2556                                 anyvalid = 1;
2557                         if (pmap_remove_pte(pmap, pte, sva, ptpaddr, &free))
2558                                 break;
2559                 }
2560         }
2561 out:
2562         if (anyvalid)
2563                 pmap_invalidate_all(pmap);
2564         vm_page_unlock_queues();        
2565         PMAP_UNLOCK(pmap);
2566         pmap_free_zero_pages(free);
2567 }
2568
2569 /*
2570  *      Routine:        pmap_remove_all
2571  *      Function:
2572  *              Removes this physical page from
2573  *              all physical maps in which it resides.
2574  *              Reflects back modify bits to the pager.
2575  *
2576  *      Notes:
2577  *              Original versions of this routine were very
2578  *              inefficient because they iteratively called
2579  *              pmap_remove (slow...)
2580  */
2581
2582 void
2583 pmap_remove_all(vm_page_t m)
2584 {
2585         struct md_page *pvh;
2586         pv_entry_t pv;
2587         pmap_t pmap;
2588         pt_entry_t *pte, tpte;
2589         pd_entry_t *pde;
2590         vm_offset_t va;
2591         vm_page_t free;
2592
2593         KASSERT((m->flags & PG_FICTITIOUS) == 0,
2594             ("pmap_remove_all: page %p is fictitious", m));
2595         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2596         pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
2597         while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
2598                 va = pv->pv_va;
2599                 pmap = PV_PMAP(pv);
2600                 PMAP_LOCK(pmap);
2601                 pde = pmap_pde(pmap, va);
2602                 (void)pmap_demote_pde(pmap, pde, va);
2603                 PMAP_UNLOCK(pmap);
2604         }
2605         while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
2606                 pmap = PV_PMAP(pv);
2607                 PMAP_LOCK(pmap);
2608                 pmap->pm_stats.resident_count--;
2609                 pde = pmap_pde(pmap, pv->pv_va);
2610                 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
2611                     " a 2mpage in page %p's pv list", m));
2612                 pte = pmap_pde_to_pte(pde, pv->pv_va);
2613                 tpte = pte_load_clear(pte);
2614                 if (tpte & PG_W)
2615                         pmap->pm_stats.wired_count--;
2616                 if (tpte & PG_A)
2617                         vm_page_flag_set(m, PG_REFERENCED);
2618
2619                 /*
2620                  * Update the vm_page_t clean and reference bits.
2621                  */
2622                 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
2623                         vm_page_dirty(m);
2624                 free = NULL;
2625                 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
2626                 pmap_invalidate_page(pmap, pv->pv_va);
2627                 pmap_free_zero_pages(free);
2628                 TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
2629                 free_pv_entry(pmap, pv);
2630                 PMAP_UNLOCK(pmap);
2631         }
2632         vm_page_flag_clear(m, PG_WRITEABLE);
2633 }
2634
2635 /*
2636  * pmap_protect_pde: do the things to protect a 2mpage in a process
2637  */
2638 static boolean_t
2639 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
2640 {
2641         pd_entry_t newpde, oldpde;
2642         vm_offset_t eva, va;
2643         vm_page_t m;
2644         boolean_t anychanged;
2645
2646         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2647         KASSERT((sva & PDRMASK) == 0,
2648             ("pmap_protect_pde: sva is not 2mpage aligned"));
2649         anychanged = FALSE;
2650 retry:
2651         oldpde = newpde = *pde;
2652         if (oldpde & PG_MANAGED) {
2653                 eva = sva + NBPDR;
2654                 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
2655                     va < eva; va += PAGE_SIZE, m++) {
2656                         /*
2657                          * In contrast to the analogous operation on a 4KB page
2658                          * mapping, the mapping's PG_A flag is not cleared and
2659                          * the page's PG_REFERENCED flag is not set.  The
2660                          * reason is that pmap_demote_pde() expects that a 2MB
2661                          * page mapping with a stored page table page has PG_A
2662                          * set.
2663                          */
2664                         if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
2665                                 vm_page_dirty(m);
2666                 }
2667         }
2668         if ((prot & VM_PROT_WRITE) == 0)
2669                 newpde &= ~(PG_RW | PG_M);
2670         if ((prot & VM_PROT_EXECUTE) == 0)
2671                 newpde |= pg_nx;
2672         if (newpde != oldpde) {
2673                 if (!atomic_cmpset_long(pde, oldpde, newpde))
2674                         goto retry;
2675                 if (oldpde & PG_G)
2676                         pmap_invalidate_page(pmap, sva);
2677                 else
2678                         anychanged = TRUE;
2679         }
2680         return (anychanged);
2681 }
2682
2683 /*
2684  *      Set the physical protection on the
2685  *      specified range of this map as requested.
2686  */
2687 void
2688 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
2689 {
2690         vm_offset_t va_next;
2691         pml4_entry_t *pml4e;
2692         pdp_entry_t *pdpe;
2693         pd_entry_t ptpaddr, *pde;
2694         pt_entry_t *pte;
2695         int anychanged;
2696
2697         if ((prot & VM_PROT_READ) == VM_PROT_NONE) {
2698                 pmap_remove(pmap, sva, eva);
2699                 return;
2700         }
2701
2702         if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
2703             (VM_PROT_WRITE|VM_PROT_EXECUTE))
2704                 return;
2705
2706         anychanged = 0;
2707
2708         vm_page_lock_queues();
2709         PMAP_LOCK(pmap);
2710         for (; sva < eva; sva = va_next) {
2711
2712                 pml4e = pmap_pml4e(pmap, sva);
2713                 if ((*pml4e & PG_V) == 0) {
2714                         va_next = (sva + NBPML4) & ~PML4MASK;
2715                         if (va_next < sva)
2716                                 va_next = eva;
2717                         continue;
2718                 }
2719
2720                 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
2721                 if ((*pdpe & PG_V) == 0) {
2722                         va_next = (sva + NBPDP) & ~PDPMASK;
2723                         if (va_next < sva)
2724                                 va_next = eva;
2725                         continue;
2726                 }
2727
2728                 va_next = (sva + NBPDR) & ~PDRMASK;
2729                 if (va_next < sva)
2730                         va_next = eva;
2731
2732                 pde = pmap_pdpe_to_pde(pdpe, sva);
2733                 ptpaddr = *pde;
2734
2735                 /*
2736                  * Weed out invalid mappings.
2737                  */
2738                 if (ptpaddr == 0)
2739                         continue;
2740
2741                 /*
2742                  * Check for large page.
2743                  */
2744                 if ((ptpaddr & PG_PS) != 0) {
2745                         /*
2746                          * Are we protecting the entire large page?  If not,
2747                          * demote the mapping and fall through.
2748                          */
2749                         if (sva + NBPDR == va_next && eva >= va_next) {
2750                                 /*
2751                                  * The TLB entry for a PG_G mapping is
2752                                  * invalidated by pmap_protect_pde().
2753                                  */
2754                                 if (pmap_protect_pde(pmap, pde, sva, prot))
2755                                         anychanged = 1;
2756                                 continue;
2757                         } else if (!pmap_demote_pde(pmap, pde, sva)) {
2758                                 /* The large page mapping was destroyed. */
2759                                 continue;
2760                         }
2761                 }
2762
2763                 if (va_next > eva)
2764                         va_next = eva;
2765
2766                 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
2767                     sva += PAGE_SIZE) {
2768                         pt_entry_t obits, pbits;
2769                         vm_page_t m;
2770
2771 retry:
2772                         obits = pbits = *pte;
2773                         if ((pbits & PG_V) == 0)
2774                                 continue;
2775                         if (pbits & PG_MANAGED) {
2776                                 m = NULL;
2777                                 if (pbits & PG_A) {
2778                                         m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
2779                                         vm_page_flag_set(m, PG_REFERENCED);
2780                                         pbits &= ~PG_A;
2781                                 }
2782                                 if ((pbits & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
2783                                         if (m == NULL)
2784                                                 m = PHYS_TO_VM_PAGE(pbits &
2785                                                     PG_FRAME);
2786                                         vm_page_dirty(m);
2787                                 }
2788                         }
2789
2790                         if ((prot & VM_PROT_WRITE) == 0)
2791                                 pbits &= ~(PG_RW | PG_M);
2792                         if ((prot & VM_PROT_EXECUTE) == 0)
2793                                 pbits |= pg_nx;
2794
2795                         if (pbits != obits) {
2796                                 if (!atomic_cmpset_long(pte, obits, pbits))
2797                                         goto retry;
2798                                 if (obits & PG_G)
2799                                         pmap_invalidate_page(pmap, sva);
2800                                 else
2801                                         anychanged = 1;
2802                         }
2803                 }
2804         }
2805         if (anychanged)
2806                 pmap_invalidate_all(pmap);
2807         vm_page_unlock_queues();
2808         PMAP_UNLOCK(pmap);
2809 }
2810
2811 /*
2812  * Tries to promote the 512, contiguous 4KB page mappings that are within a
2813  * single page table page (PTP) to a single 2MB page mapping.  For promotion
2814  * to occur, two conditions must be met: (1) the 4KB page mappings must map
2815  * aligned, contiguous physical memory and (2) the 4KB page mappings must have
2816  * identical characteristics. 
2817  */
2818 static void
2819 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
2820 {
2821         pd_entry_t newpde;
2822         pt_entry_t *firstpte, oldpte, pa, *pte;
2823         vm_offset_t oldpteva;
2824         vm_page_t mpte;
2825
2826         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2827
2828         /*
2829          * Examine the first PTE in the specified PTP.  Abort if this PTE is
2830          * either invalid, unused, or does not map the first 4KB physical page
2831          * within a 2MB page. 
2832          */
2833         firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
2834 setpde:
2835         newpde = *firstpte;
2836         if ((newpde & ((PG_FRAME & PDRMASK) | PG_A | PG_V)) != (PG_A | PG_V)) {
2837                 pmap_pde_p_failures++;
2838                 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
2839                     " in pmap %p", va, pmap);
2840                 return;
2841         }
2842         if ((newpde & (PG_M | PG_RW)) == PG_RW) {
2843                 /*
2844                  * When PG_M is already clear, PG_RW can be cleared without
2845                  * a TLB invalidation.
2846                  */
2847                 if (!atomic_cmpset_long(firstpte, newpde, newpde & ~PG_RW))
2848                         goto setpde;
2849                 newpde &= ~PG_RW;
2850         }
2851
2852         /*
2853          * Examine each of the other PTEs in the specified PTP.  Abort if this
2854          * PTE maps an unexpected 4KB physical page or does not have identical
2855          * characteristics to the first PTE.
2856          */
2857         pa = (newpde & (PG_PS_FRAME | PG_A | PG_V)) + NBPDR - PAGE_SIZE;
2858         for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
2859 setpte:
2860                 oldpte = *pte;
2861                 if ((oldpte & (PG_FRAME | PG_A | PG_V)) != pa) {
2862                         pmap_pde_p_failures++;
2863                         CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
2864                             " in pmap %p", va, pmap);
2865                         return;
2866                 }
2867                 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
2868                         /*
2869                          * When PG_M is already clear, PG_RW can be cleared
2870                          * without a TLB invalidation.
2871                          */
2872                         if (!atomic_cmpset_long(pte, oldpte, oldpte & ~PG_RW))
2873                                 goto setpte;
2874                         oldpte &= ~PG_RW;
2875                         oldpteva = (oldpte & PG_FRAME & PDRMASK) |
2876                             (va & ~PDRMASK);
2877                         CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
2878                             " in pmap %p", oldpteva, pmap);
2879                 }
2880                 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
2881                         pmap_pde_p_failures++;
2882                         CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
2883                             " in pmap %p", va, pmap);
2884                         return;
2885                 }
2886                 pa -= PAGE_SIZE;
2887         }
2888
2889         /*
2890          * Save the page table page in its current state until the PDE
2891          * mapping the superpage is demoted by pmap_demote_pde() or
2892          * destroyed by pmap_remove_pde(). 
2893          */
2894         mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
2895         KASSERT(mpte >= vm_page_array &&
2896             mpte < &vm_page_array[vm_page_array_size],
2897             ("pmap_promote_pde: page table page is out of range"));
2898         KASSERT(mpte->pindex == pmap_pde_pindex(va),
2899             ("pmap_promote_pde: page table page's pindex is wrong"));
2900         pmap_insert_pt_page(pmap, mpte);
2901
2902         /*
2903          * Promote the pv entries.
2904          */
2905         if ((newpde & PG_MANAGED) != 0)
2906                 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME);
2907
2908         /*
2909          * Propagate the PAT index to its proper position.
2910          */
2911         if ((newpde & PG_PTE_PAT) != 0)
2912                 newpde ^= PG_PDE_PAT | PG_PTE_PAT;
2913
2914         /*
2915          * Map the superpage.
2916          */
2917         pde_store(pde, PG_PS | newpde);
2918
2919         pmap_pde_promotions++;
2920         CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
2921             " in pmap %p", va, pmap);
2922 }
2923
2924 /*
2925  *      Insert the given physical page (p) at
2926  *      the specified virtual address (v) in the
2927  *      target physical map with the protection requested.
2928  *
2929  *      If specified, the page will be wired down, meaning
2930  *      that the related pte can not be reclaimed.
2931  *
2932  *      NB:  This is the only routine which MAY NOT lazy-evaluate
2933  *      or lose information.  That is, this routine must actually
2934  *      insert this page into the given map NOW.
2935  */
2936 void
2937 pmap_enter(pmap_t pmap, vm_offset_t va, vm_prot_t access, vm_page_t m,
2938     vm_prot_t prot, boolean_t wired)
2939 {
2940         vm_paddr_t pa;
2941         pd_entry_t *pde;
2942         pt_entry_t *pte;
2943         vm_paddr_t opa;
2944         pt_entry_t origpte, newpte;
2945         vm_page_t mpte, om;
2946         boolean_t invlva;
2947
2948         va = trunc_page(va);
2949         KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
2950         KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
2951             ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)", va));
2952
2953         mpte = NULL;
2954
2955         vm_page_lock_queues();
2956         PMAP_LOCK(pmap);
2957
2958         /*
2959          * In the case that a page table page is not
2960          * resident, we are creating it here.
2961          */
2962         if (va < VM_MAXUSER_ADDRESS) {
2963                 mpte = pmap_allocpte(pmap, va, M_WAITOK);
2964         }
2965
2966         pde = pmap_pde(pmap, va);
2967         if (pde != NULL && (*pde & PG_V) != 0) {
2968                 if ((*pde & PG_PS) != 0)
2969                         panic("pmap_enter: attempted pmap_enter on 2MB page");
2970                 pte = pmap_pde_to_pte(pde, va);
2971         } else
2972                 panic("pmap_enter: invalid page directory va=%#lx", va);
2973
2974         pa = VM_PAGE_TO_PHYS(m);
2975         om = NULL;
2976         origpte = *pte;
2977         opa = origpte & PG_FRAME;
2978
2979         /*
2980          * Mapping has not changed, must be protection or wiring change.
2981          */
2982         if (origpte && (opa == pa)) {
2983                 /*
2984                  * Wiring change, just update stats. We don't worry about
2985                  * wiring PT pages as they remain resident as long as there
2986                  * are valid mappings in them. Hence, if a user page is wired,
2987                  * the PT page will be also.
2988                  */
2989                 if (wired && ((origpte & PG_W) == 0))
2990                         pmap->pm_stats.wired_count++;
2991                 else if (!wired && (origpte & PG_W))
2992                         pmap->pm_stats.wired_count--;
2993
2994                 /*
2995                  * Remove extra pte reference
2996                  */
2997                 if (mpte)
2998                         mpte->wire_count--;
2999
3000                 /*
3001                  * We might be turning off write access to the page,
3002                  * so we go ahead and sense modify status.
3003                  */
3004                 if (origpte & PG_MANAGED) {
3005                         om = m;
3006                         pa |= PG_MANAGED;
3007                 }
3008                 goto validate;
3009         } 
3010         /*
3011          * Mapping has changed, invalidate old range and fall through to
3012          * handle validating new mapping.
3013          */
3014         if (opa) {
3015                 if (origpte & PG_W)
3016                         pmap->pm_stats.wired_count--;
3017                 if (origpte & PG_MANAGED) {
3018                         om = PHYS_TO_VM_PAGE(opa);
3019                         pmap_remove_entry(pmap, om, va);
3020                 }
3021                 if (mpte != NULL) {
3022                         mpte->wire_count--;
3023                         KASSERT(mpte->wire_count > 0,
3024                             ("pmap_enter: missing reference to page table page,"
3025                              " va: 0x%lx", va));
3026                 }
3027         } else
3028                 pmap->pm_stats.resident_count++;
3029
3030         /*
3031          * Enter on the PV list if part of our managed memory.
3032          */
3033         if ((m->flags & (PG_FICTITIOUS | PG_UNMANAGED)) == 0) {
3034                 KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva,
3035                     ("pmap_enter: managed mapping within the clean submap"));
3036                 pmap_insert_entry(pmap, va, m);
3037                 pa |= PG_MANAGED;
3038         }
3039
3040         /*
3041          * Increment counters
3042          */
3043         if (wired)
3044                 pmap->pm_stats.wired_count++;
3045
3046 validate:
3047         /*
3048          * Now validate mapping with desired protection/wiring.
3049          */
3050         newpte = (pt_entry_t)(pa | pmap_cache_bits(m->md.pat_mode, 0) | PG_V);
3051         if ((prot & VM_PROT_WRITE) != 0) {
3052                 newpte |= PG_RW;
3053                 vm_page_flag_set(m, PG_WRITEABLE);
3054         }
3055         if ((prot & VM_PROT_EXECUTE) == 0)
3056                 newpte |= pg_nx;
3057         if (wired)
3058                 newpte |= PG_W;
3059         if (va < VM_MAXUSER_ADDRESS)
3060                 newpte |= PG_U;
3061         if (pmap == kernel_pmap)
3062                 newpte |= PG_G;
3063
3064         /*
3065          * if the mapping or permission bits are different, we need
3066          * to update the pte.
3067          */
3068         if ((origpte & ~(PG_M|PG_A)) != newpte) {
3069                 newpte |= PG_A;
3070                 if ((access & VM_PROT_WRITE) != 0)
3071                         newpte |= PG_M;
3072                 if (origpte & PG_V) {
3073                         invlva = FALSE;
3074                         origpte = pte_load_store(pte, newpte);
3075                         if (origpte & PG_A) {
3076                                 if (origpte & PG_MANAGED)
3077                                         vm_page_flag_set(om, PG_REFERENCED);
3078                                 if (opa != VM_PAGE_TO_PHYS(m) || ((origpte &
3079                                     PG_NX) == 0 && (newpte & PG_NX)))
3080                                         invlva = TRUE;
3081                         }
3082                         if ((origpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
3083                                 if ((origpte & PG_MANAGED) != 0)
3084                                         vm_page_dirty(om);
3085                                 if ((newpte & PG_RW) == 0)
3086                                         invlva = TRUE;
3087                         }
3088                         if (invlva)
3089                                 pmap_invalidate_page(pmap, va);
3090                 } else
3091                         pte_store(pte, newpte);
3092         }
3093
3094         /*
3095          * If both the page table page and the reservation are fully
3096          * populated, then attempt promotion.
3097          */
3098         if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
3099             pg_ps_enabled && vm_reserv_level_iffullpop(m) == 0)
3100                 pmap_promote_pde(pmap, pde, va);
3101
3102         vm_page_unlock_queues();
3103         PMAP_UNLOCK(pmap);
3104 }
3105
3106 /*
3107  * Tries to create a 2MB page mapping.  Returns TRUE if successful and FALSE
3108  * otherwise.  Fails if (1) a page table page cannot be allocated without
3109  * blocking, (2) a mapping already exists at the specified virtual address, or
3110  * (3) a pv entry cannot be allocated without reclaiming another pv entry. 
3111  */
3112 static boolean_t
3113 pmap_enter_pde(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
3114 {
3115         pd_entry_t *pde, newpde;
3116         vm_page_t free, mpde;
3117
3118         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
3119         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3120         if ((mpde = pmap_allocpde(pmap, va, M_NOWAIT)) == NULL) {
3121                 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
3122                     " in pmap %p", va, pmap);
3123                 return (FALSE);
3124         }
3125         pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpde));
3126         pde = &pde[pmap_pde_index(va)];
3127         if ((*pde & PG_V) != 0) {
3128                 KASSERT(mpde->wire_count > 1,
3129                     ("pmap_enter_pde: mpde's wire count is too low"));
3130                 mpde->wire_count--;
3131                 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
3132                     " in pmap %p", va, pmap);
3133                 return (FALSE);
3134         }
3135         newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(m->md.pat_mode, 1) |
3136             PG_PS | PG_V;
3137         if ((m->flags & (PG_FICTITIOUS | PG_UNMANAGED)) == 0) {
3138                 newpde |= PG_MANAGED;
3139
3140                 /*
3141                  * Abort this mapping if its PV entry could not be created.
3142                  */
3143                 if (!pmap_pv_insert_pde(pmap, va, VM_PAGE_TO_PHYS(m))) {
3144                         free = NULL;
3145                         if (pmap_unwire_pte_hold(pmap, va, mpde, &free)) {
3146                                 pmap_invalidate_page(pmap, va);
3147                                 pmap_free_zero_pages(free);
3148                         }
3149                         CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
3150                             " in pmap %p", va, pmap);
3151                         return (FALSE);
3152                 }
3153         }
3154         if ((prot & VM_PROT_EXECUTE) == 0)
3155                 newpde |= pg_nx;
3156         if (va < VM_MAXUSER_ADDRESS)
3157                 newpde |= PG_U;
3158
3159         /*
3160          * Increment counters.
3161          */
3162         pmap->pm_stats.resident_count += NBPDR / PAGE_SIZE;
3163
3164         /*
3165          * Map the superpage.
3166          */
3167         pde_store(pde, newpde);
3168
3169         pmap_pde_mappings++;
3170         CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx"
3171             " in pmap %p", va, pmap);
3172         return (TRUE);
3173 }
3174
3175 /*
3176  * Maps a sequence of resident pages belonging to the same object.
3177  * The sequence begins with the given page m_start.  This page is
3178  * mapped at the given virtual address start.  Each subsequent page is
3179  * mapped at a virtual address that is offset from start by the same
3180  * amount as the page is offset from m_start within the object.  The
3181  * last page in the sequence is the page with the largest offset from
3182  * m_start that can be mapped at a virtual address less than the given
3183  * virtual address end.  Not every virtual page between start and end
3184  * is mapped; only those for which a resident page exists with the
3185  * corresponding offset from m_start are mapped.
3186  */
3187 void
3188 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
3189     vm_page_t m_start, vm_prot_t prot)
3190 {
3191         vm_offset_t va;
3192         vm_page_t m, mpte;
3193         vm_pindex_t diff, psize;
3194
3195         VM_OBJECT_LOCK_ASSERT(m_start->object, MA_OWNED);
3196         psize = atop(end - start);
3197         mpte = NULL;
3198         m = m_start;
3199         PMAP_LOCK(pmap);
3200         while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
3201                 va = start + ptoa(diff);
3202                 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
3203                     (VM_PAGE_TO_PHYS(m) & PDRMASK) == 0 &&
3204                     pg_ps_enabled && vm_reserv_level_iffullpop(m) == 0 &&
3205                     pmap_enter_pde(pmap, va, m, prot))
3206                         m = &m[NBPDR / PAGE_SIZE - 1];
3207                 else
3208                         mpte = pmap_enter_quick_locked(pmap, va, m, prot,
3209                             mpte);
3210                 m = TAILQ_NEXT(m, listq);
3211         }
3212         PMAP_UNLOCK(pmap);
3213 }
3214
3215 /*
3216  * this code makes some *MAJOR* assumptions:
3217  * 1. Current pmap & pmap exists.
3218  * 2. Not wired.
3219  * 3. Read access.
3220  * 4. No page table pages.
3221  * but is *MUCH* faster than pmap_enter...
3222  */
3223
3224 void
3225 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
3226 {
3227
3228         PMAP_LOCK(pmap);
3229         (void) pmap_enter_quick_locked(pmap, va, m, prot, NULL);
3230         PMAP_UNLOCK(pmap);
3231 }
3232
3233 static vm_page_t
3234 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
3235     vm_prot_t prot, vm_page_t mpte)
3236 {
3237         vm_page_t free;
3238         pt_entry_t *pte;
3239         vm_paddr_t pa;
3240
3241         KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
3242             (m->flags & (PG_FICTITIOUS | PG_UNMANAGED)) != 0,
3243             ("pmap_enter_quick_locked: managed mapping within the clean submap"));
3244         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
3245         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3246
3247         /*
3248          * In the case that a page table page is not
3249          * resident, we are creating it here.
3250          */
3251         if (va < VM_MAXUSER_ADDRESS) {
3252                 vm_pindex_t ptepindex;
3253                 pd_entry_t *ptepa;
3254
3255                 /*
3256                  * Calculate pagetable page index
3257                  */
3258                 ptepindex = pmap_pde_pindex(va);
3259                 if (mpte && (mpte->pindex == ptepindex)) {
3260                         mpte->wire_count++;
3261                 } else {
3262                         /*
3263                          * Get the page directory entry
3264                          */
3265                         ptepa = pmap_pde(pmap, va);
3266
3267                         /*
3268                          * If the page table page is mapped, we just increment
3269                          * the hold count, and activate it.
3270                          */
3271                         if (ptepa && (*ptepa & PG_V) != 0) {
3272                                 if (*ptepa & PG_PS)
3273                                         return (NULL);
3274                                 mpte = PHYS_TO_VM_PAGE(*ptepa & PG_FRAME);
3275                                 mpte->wire_count++;
3276                         } else {
3277                                 mpte = _pmap_allocpte(pmap, ptepindex,
3278                                     M_NOWAIT);
3279                                 if (mpte == NULL)
3280                                         return (mpte);
3281                         }
3282                 }
3283                 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
3284                 pte = &pte[pmap_pte_index(va)];
3285         } else {
3286                 mpte = NULL;
3287                 pte = vtopte(va);
3288         }
3289         if (*pte) {
3290                 if (mpte != NULL) {
3291                         mpte->wire_count--;
3292                         mpte = NULL;
3293                 }
3294                 return (mpte);
3295         }
3296
3297         /*
3298          * Enter on the PV list if part of our managed memory.
3299          */
3300         if ((m->flags & (PG_FICTITIOUS | PG_UNMANAGED)) == 0 &&
3301             !pmap_try_insert_pv_entry(pmap, va, m)) {
3302                 if (mpte != NULL) {
3303                         free = NULL;
3304                         if (pmap_unwire_pte_hold(pmap, va, mpte, &free)) {
3305                                 pmap_invalidate_page(pmap, va);
3306                                 pmap_free_zero_pages(free);
3307                         }
3308                         mpte = NULL;
3309                 }
3310                 return (mpte);
3311         }
3312
3313         /*
3314          * Increment counters
3315          */
3316         pmap->pm_stats.resident_count++;
3317
3318         pa = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(m->md.pat_mode, 0);
3319         if ((prot & VM_PROT_EXECUTE) == 0)
3320                 pa |= pg_nx;
3321
3322         /*
3323          * Now validate mapping with RO protection
3324          */
3325         if (m->flags & (PG_FICTITIOUS|PG_UNMANAGED))
3326                 pte_store(pte, pa | PG_V | PG_U);
3327         else
3328                 pte_store(pte, pa | PG_V | PG_U | PG_MANAGED);
3329         return mpte;
3330 }
3331
3332 /*
3333  * Make a temporary mapping for a physical address.  This is only intended
3334  * to be used for panic dumps.
3335  */
3336 void *
3337 pmap_kenter_temporary(vm_paddr_t pa, int i)
3338 {
3339         vm_offset_t va;
3340
3341         va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
3342         pmap_kenter(va, pa);
3343         invlpg(va);
3344         return ((void *)crashdumpmap);
3345 }
3346
3347 /*
3348  * This code maps large physical mmap regions into the
3349  * processor address space.  Note that some shortcuts
3350  * are taken, but the code works.
3351  */
3352 void
3353 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
3354     vm_pindex_t pindex, vm_size_t size)
3355 {
3356         pd_entry_t *pde;
3357         vm_paddr_t pa, ptepa;
3358         vm_page_t p, pdpg;
3359         int pat_mode;
3360
3361         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
3362         KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
3363             ("pmap_object_init_pt: non-device object"));
3364         if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
3365                 if (!vm_object_populate(object, pindex, pindex + atop(size)))
3366                         return;
3367                 p = vm_page_lookup(object, pindex);
3368                 KASSERT(p->valid == VM_PAGE_BITS_ALL,
3369                     ("pmap_object_init_pt: invalid page %p", p));
3370                 pat_mode = p->md.pat_mode;
3371
3372                 /*
3373                  * Abort the mapping if the first page is not physically
3374                  * aligned to a 2MB page boundary.
3375                  */
3376                 ptepa = VM_PAGE_TO_PHYS(p);
3377                 if (ptepa & (NBPDR - 1))
3378                         return;
3379
3380                 /*
3381                  * Skip the first page.  Abort the mapping if the rest of
3382                  * the pages are not physically contiguous or have differing
3383                  * memory attributes.
3384                  */
3385                 p = TAILQ_NEXT(p, listq);
3386                 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
3387                     pa += PAGE_SIZE) {
3388                         KASSERT(p->valid == VM_PAGE_BITS_ALL,
3389                             ("pmap_object_init_pt: invalid page %p", p));
3390                         if (pa != VM_PAGE_TO_PHYS(p) ||
3391                             pat_mode != p->md.pat_mode)
3392                                 return;
3393                         p = TAILQ_NEXT(p, listq);
3394                 }
3395
3396                 /*
3397                  * Map using 2MB pages.  Since "ptepa" is 2M aligned and
3398                  * "size" is a multiple of 2M, adding the PAT setting to "pa"
3399                  * will not affect the termination of this loop.
3400                  */ 
3401                 PMAP_LOCK(pmap);
3402                 for (pa = ptepa | pmap_cache_bits(pat_mode, 1); pa < ptepa +
3403                     size; pa += NBPDR) {
3404                         pdpg = pmap_allocpde(pmap, addr, M_NOWAIT);
3405                         if (pdpg == NULL) {
3406                                 /*
3407                                  * The creation of mappings below is only an
3408                                  * optimization.  If a page directory page
3409                                  * cannot be allocated without blocking,
3410                                  * continue on to the next mapping rather than
3411                                  * blocking.
3412                                  */
3413                                 addr += NBPDR;
3414                                 continue;
3415                         }
3416                         pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
3417                         pde = &pde[pmap_pde_index(addr)];
3418                         if ((*pde & PG_V) == 0) {
3419                                 pde_store(pde, pa | PG_PS | PG_M | PG_A |
3420                                     PG_U | PG_RW | PG_V);
3421                                 pmap->pm_stats.resident_count += NBPDR /
3422                                     PAGE_SIZE;
3423                                 pmap_pde_mappings++;
3424                         } else {
3425                                 /* Continue on if the PDE is already valid. */
3426                                 pdpg->wire_count--;
3427                                 KASSERT(pdpg->wire_count > 0,
3428                                     ("pmap_object_init_pt: missing reference "
3429                                     "to page directory page, va: 0x%lx", addr));
3430                         }
3431                         addr += NBPDR;
3432                 }
3433                 PMAP_UNLOCK(pmap);
3434         }
3435 }
3436
3437 /*
3438  *      Routine:        pmap_change_wiring
3439  *      Function:       Change the wiring attribute for a map/virtual-address
3440  *                      pair.
3441  *      In/out conditions:
3442  *                      The mapping must already exist in the pmap.
3443  */
3444 void
3445 pmap_change_wiring(pmap_t pmap, vm_offset_t va, boolean_t wired)
3446 {
3447         pd_entry_t *pde;
3448         pt_entry_t *pte;
3449         boolean_t are_queues_locked;
3450
3451         are_queues_locked = FALSE;
3452
3453         /*
3454          * Wiring is not a hardware characteristic so there is no need to
3455          * invalidate TLB.
3456          */
3457 retry:
3458         PMAP_LOCK(pmap);
3459         pde = pmap_pde(pmap, va);
3460         if ((*pde & PG_PS) != 0) {
3461                 if (!wired != ((*pde & PG_W) == 0)) {
3462                         if (!are_queues_locked) {
3463                                 are_queues_locked = TRUE;
3464                                 if (!mtx_trylock(&vm_page_queue_mtx)) {
3465                                         PMAP_UNLOCK(pmap);
3466                                         vm_page_lock_queues();
3467                                         goto retry;
3468                                 }
3469                         }
3470                         if (!pmap_demote_pde(pmap, pde, va))
3471                                 panic("pmap_change_wiring: demotion failed");
3472                 } else
3473                         goto out;
3474         }
3475         pte = pmap_pde_to_pte(pde, va);
3476         if (wired && (*pte & PG_W) == 0) {
3477                 pmap->pm_stats.wired_count++;
3478                 atomic_set_long(pte, PG_W);
3479         } else if (!wired && (*pte & PG_W) != 0) {
3480                 pmap->pm_stats.wired_count--;
3481                 atomic_clear_long(pte, PG_W);
3482         }
3483 out:
3484         if (are_queues_locked)
3485                 vm_page_unlock_queues();
3486         PMAP_UNLOCK(pmap);
3487 }
3488
3489
3490
3491 /*
3492  *      Copy the range specified by src_addr/len
3493  *      from the source map to the range dst_addr/len
3494  *      in the destination map.
3495  *
3496  *      This routine is only advisory and need not do anything.
3497  */
3498
3499 void
3500 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
3501     vm_offset_t src_addr)
3502 {
3503         vm_page_t   free;
3504         vm_offset_t addr;
3505         vm_offset_t end_addr = src_addr + len;
3506         vm_offset_t va_next;
3507
3508         if (dst_addr != src_addr)
3509                 return;
3510
3511         vm_page_lock_queues();
3512         if (dst_pmap < src_pmap) {
3513                 PMAP_LOCK(dst_pmap);
3514                 PMAP_LOCK(src_pmap);
3515         } else {
3516                 PMAP_LOCK(src_pmap);
3517                 PMAP_LOCK(dst_pmap);
3518         }
3519         for (addr = src_addr; addr < end_addr; addr = va_next) {
3520                 pt_entry_t *src_pte, *dst_pte;
3521                 vm_page_t dstmpde, dstmpte, srcmpte;
3522                 pml4_entry_t *pml4e;
3523                 pdp_entry_t *pdpe;
3524                 pd_entry_t srcptepaddr, *pde;
3525
3526                 KASSERT(addr < UPT_MIN_ADDRESS,
3527                     ("pmap_copy: invalid to pmap_copy page tables"));
3528
3529                 pml4e = pmap_pml4e(src_pmap, addr);
3530                 if ((*pml4e & PG_V) == 0) {
3531                         va_next = (addr + NBPML4) & ~PML4MASK;
3532                         if (va_next < addr)
3533                                 va_next = end_addr;
3534                         continue;
3535                 }
3536
3537                 pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
3538                 if ((*pdpe & PG_V) == 0) {
3539                         va_next = (addr + NBPDP) & ~PDPMASK;
3540                         if (va_next < addr)
3541                                 va_next = end_addr;
3542                         continue;
3543                 }
3544
3545                 va_next = (addr + NBPDR) & ~PDRMASK;
3546                 if (va_next < addr)
3547                         va_next = end_addr;
3548
3549                 pde = pmap_pdpe_to_pde(pdpe, addr);
3550                 srcptepaddr = *pde;
3551                 if (srcptepaddr == 0)
3552                         continue;
3553                         
3554                 if (srcptepaddr & PG_PS) {
3555                         dstmpde = pmap_allocpde(dst_pmap, addr, M_NOWAIT);
3556                         if (dstmpde == NULL)
3557                                 break;
3558                         pde = (pd_entry_t *)
3559                             PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpde));
3560                         pde = &pde[pmap_pde_index(addr)];
3561                         if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
3562                             pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr &
3563                             PG_PS_FRAME))) {
3564                                 *pde = srcptepaddr & ~PG_W;
3565                                 dst_pmap->pm_stats.resident_count +=
3566                                     NBPDR / PAGE_SIZE;
3567                         } else
3568                                 dstmpde->wire_count--;
3569                         continue;
3570                 }
3571
3572                 srcptepaddr &= PG_FRAME;
3573                 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
3574                 KASSERT(srcmpte->wire_count > 0,
3575                     ("pmap_copy: source page table page is unused"));
3576
3577                 if (va_next > end_addr)
3578                         va_next = end_addr;
3579
3580                 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
3581                 src_pte = &src_pte[pmap_pte_index(addr)];
3582                 dstmpte = NULL;
3583                 while (addr < va_next) {
3584                         pt_entry_t ptetemp;
3585                         ptetemp = *src_pte;
3586                         /*
3587                          * we only virtual copy managed pages
3588                          */
3589                         if ((ptetemp & PG_MANAGED) != 0) {
3590                                 if (dstmpte != NULL &&
3591                                     dstmpte->pindex == pmap_pde_pindex(addr))
3592                                         dstmpte->wire_count++;
3593                                 else if ((dstmpte = pmap_allocpte(dst_pmap,
3594                                     addr, M_NOWAIT)) == NULL)
3595                                         goto out;
3596                                 dst_pte = (pt_entry_t *)
3597                                     PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
3598                                 dst_pte = &dst_pte[pmap_pte_index(addr)];
3599                                 if (*dst_pte == 0 &&
3600                                     pmap_try_insert_pv_entry(dst_pmap, addr,
3601                                     PHYS_TO_VM_PAGE(ptetemp & PG_FRAME))) {
3602                                         /*
3603                                          * Clear the wired, modified, and
3604                                          * accessed (referenced) bits
3605                                          * during the copy.
3606                                          */
3607                                         *dst_pte = ptetemp & ~(PG_W | PG_M |
3608                                             PG_A);
3609                                         dst_pmap->pm_stats.resident_count++;
3610                                 } else {
3611                                         free = NULL;
3612                                         if (pmap_unwire_pte_hold(dst_pmap,
3613                                             addr, dstmpte, &free)) {
3614                                                 pmap_invalidate_page(dst_pmap,
3615                                                     addr);
3616                                                 pmap_free_zero_pages(free);
3617                                         }
3618                                         goto out;
3619                                 }
3620                                 if (dstmpte->wire_count >= srcmpte->wire_count)
3621                                         break;
3622                         }
3623                         addr += PAGE_SIZE;
3624                         src_pte++;
3625                 }
3626         }
3627 out:
3628         vm_page_unlock_queues();
3629         PMAP_UNLOCK(src_pmap);
3630         PMAP_UNLOCK(dst_pmap);
3631 }       
3632
3633 /*
3634  *      pmap_zero_page zeros the specified hardware page by mapping 
3635  *      the page into KVM and using bzero to clear its contents.
3636  */
3637 void
3638 pmap_zero_page(vm_page_t m)
3639 {
3640         vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
3641
3642         pagezero((void *)va);
3643 }
3644
3645 /*
3646  *      pmap_zero_page_area zeros the specified hardware page by mapping 
3647  *      the page into KVM and using bzero to clear its contents.
3648  *
3649  *      off and size may not cover an area beyond a single hardware page.
3650  */
3651 void
3652 pmap_zero_page_area(vm_page_t m, int off, int size)
3653 {
3654         vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
3655
3656         if (off == 0 && size == PAGE_SIZE)
3657                 pagezero((void *)va);
3658         else
3659                 bzero((char *)va + off, size);
3660 }
3661
3662 /*
3663  *      pmap_zero_page_idle zeros the specified hardware page by mapping 
3664  *      the page into KVM and using bzero to clear its contents.  This
3665  *      is intended to be called from the vm_pagezero process only and
3666  *      outside of Giant.
3667  */
3668 void
3669 pmap_zero_page_idle(vm_page_t m)
3670 {
3671         vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
3672
3673         pagezero((void *)va);
3674 }
3675
3676 /*
3677  *      pmap_copy_page copies the specified (machine independent)
3678  *      page by mapping the page into virtual memory and using
3679  *      bcopy to copy the page, one machine dependent page at a
3680  *      time.
3681  */
3682 void
3683 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
3684 {
3685         vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
3686         vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
3687
3688         pagecopy((void *)src, (void *)dst);
3689 }
3690
3691 /*
3692  * Returns true if the pmap's pv is one of the first
3693  * 16 pvs linked to from this page.  This count may
3694  * be changed upwards or downwards in the future; it
3695  * is only necessary that true be returned for a small
3696  * subset of pmaps for proper page aging.
3697  */
3698 boolean_t
3699 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
3700 {
3701         struct md_page *pvh;
3702         pv_entry_t pv;
3703         int loops = 0;
3704
3705         if (m->flags & PG_FICTITIOUS)
3706                 return FALSE;
3707
3708         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
3709         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
3710                 if (PV_PMAP(pv) == pmap) {
3711                         return TRUE;
3712                 }
3713                 loops++;
3714                 if (loops >= 16)
3715                         break;
3716         }
3717         if (loops < 16) {
3718                 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3719                 TAILQ_FOREACH(pv, &pvh->pv_list, pv_list) {
3720                         if (PV_PMAP(pv) == pmap)
3721                                 return (TRUE);
3722                         loops++;
3723                         if (loops >= 16)
3724                                 break;
3725                 }
3726         }
3727         return (FALSE);
3728 }
3729
3730 /*
3731  *      pmap_page_wired_mappings:
3732  *
3733  *      Return the number of managed mappings to the given physical page
3734  *      that are wired.
3735  */
3736 int
3737 pmap_page_wired_mappings(vm_page_t m)
3738 {
3739         int count;
3740
3741         count = 0;
3742         if ((m->flags & PG_FICTITIOUS) != 0)
3743                 return (count);
3744         count = pmap_pvh_wired_mappings(&m->md, count);
3745         return (pmap_pvh_wired_mappings(pa_to_pvh(VM_PAGE_TO_PHYS(m)), count));
3746 }
3747
3748 /*
3749  *      pmap_pvh_wired_mappings:
3750  *
3751  *      Return the updated number "count" of managed mappings that are wired.
3752  */
3753 static int
3754 pmap_pvh_wired_mappings(struct md_page *pvh, int count)
3755 {
3756         pmap_t pmap;
3757         pt_entry_t *pte;
3758         pv_entry_t pv;
3759
3760         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
3761         TAILQ_FOREACH(pv, &pvh->pv_list, pv_list) {
3762                 pmap = PV_PMAP(pv);
3763                 PMAP_LOCK(pmap);
3764                 pte = pmap_pte(pmap, pv->pv_va);
3765                 if ((*pte & PG_W) != 0)
3766                         count++;
3767                 PMAP_UNLOCK(pmap);
3768         }
3769         return (count);
3770 }
3771
3772 /*
3773  * Returns TRUE if the given page is mapped individually or as part of
3774  * a 2mpage.  Otherwise, returns FALSE.
3775  */
3776 boolean_t
3777 pmap_page_is_mapped(vm_page_t m)
3778 {
3779         struct md_page *pvh;
3780
3781         if ((m->flags & (PG_FICTITIOUS | PG_UNMANAGED)) != 0)
3782                 return (FALSE);
3783         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
3784         if (TAILQ_EMPTY(&m->md.pv_list)) {
3785                 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3786                 return (!TAILQ_EMPTY(&pvh->pv_list));
3787         } else
3788                 return (TRUE);
3789 }
3790
3791 /*
3792  * Remove all pages from specified address space
3793  * this aids process exit speeds.  Also, this code
3794  * is special cased for current process only, but
3795  * can have the more generic (and slightly slower)
3796  * mode enabled.  This is much faster than pmap_remove
3797  * in the case of running down an entire address space.
3798  */
3799 void
3800 pmap_remove_pages(pmap_t pmap)
3801 {
3802         pd_entry_t ptepde;
3803         pt_entry_t *pte, tpte;
3804         vm_page_t free = NULL;
3805         vm_page_t m, mpte, mt;
3806         pv_entry_t pv;
3807         struct md_page *pvh;
3808         struct pv_chunk *pc, *npc;
3809         int field, idx;
3810         int64_t bit;
3811         uint64_t inuse, bitmask;
3812         int allfree;
3813
3814         if (pmap != vmspace_pmap(curthread->td_proc->p_vmspace)) {
3815                 printf("warning: pmap_remove_pages called with non-current pmap\n");
3816                 return;
3817         }
3818         vm_page_lock_queues();
3819         PMAP_LOCK(pmap);
3820         TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
3821                 allfree = 1;
3822                 for (field = 0; field < _NPCM; field++) {
3823                         inuse = (~(pc->pc_map[field])) & pc_freemask[field];
3824                         while (inuse != 0) {
3825                                 bit = bsfq(inuse);
3826                                 bitmask = 1UL << bit;
3827                                 idx = field * 64 + bit;
3828                                 pv = &pc->pc_pventry[idx];
3829                                 inuse &= ~bitmask;
3830
3831                                 pte = pmap_pdpe(pmap, pv->pv_va);
3832                                 ptepde = *pte;
3833                                 pte = pmap_pdpe_to_pde(pte, pv->pv_va);
3834                                 tpte = *pte;
3835                                 if ((tpte & (PG_PS | PG_V)) == PG_V) {
3836                                         ptepde = tpte;
3837                                         pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
3838                                             PG_FRAME);
3839                                         pte = &pte[pmap_pte_index(pv->pv_va)];
3840                                         tpte = *pte & ~PG_PTE_PAT;
3841                                 }
3842                                 if ((tpte & PG_V) == 0)
3843                                         panic("bad pte");
3844
3845 /*
3846  * We cannot remove wired pages from a process' mapping at this time
3847  */
3848                                 if (tpte & PG_W) {
3849                                         allfree = 0;
3850                                         continue;
3851                                 }
3852
3853                                 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
3854                                 KASSERT(m->phys_addr == (tpte & PG_FRAME),
3855                                     ("vm_page_t %p phys_addr mismatch %016jx %016jx",
3856                                     m, (uintmax_t)m->phys_addr,
3857                                     (uintmax_t)tpte));
3858
3859                                 KASSERT(m < &vm_page_array[vm_page_array_size],
3860                                         ("pmap_remove_pages: bad tpte %#jx",
3861                                         (uintmax_t)tpte));
3862
3863                                 pte_clear(pte);
3864
3865                                 /*
3866                                  * Update the vm_page_t clean/reference bits.
3867                                  */
3868                                 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
3869                                         if ((tpte & PG_PS) != 0) {
3870                                                 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
3871                                                         vm_page_dirty(mt);
3872                                         } else
3873                                                 vm_page_dirty(m);
3874                                 }
3875
3876                                 /* Mark free */
3877                                 PV_STAT(pv_entry_frees++);
3878                                 PV_STAT(pv_entry_spare++);
3879                                 pv_entry_count--;
3880                                 pc->pc_map[field] |= bitmask;
3881                                 if ((tpte & PG_PS) != 0) {
3882                                         pmap->pm_stats.resident_count -= NBPDR / PAGE_SIZE;
3883                                         pvh = pa_to_pvh(tpte & PG_PS_FRAME);
3884                                         TAILQ_REMOVE(&pvh->pv_list, pv, pv_list);
3885                                         if (TAILQ_EMPTY(&pvh->pv_list)) {
3886                                                 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
3887                                                         if (TAILQ_EMPTY(&mt->md.pv_list))
3888                                                                 vm_page_flag_clear(mt, PG_WRITEABLE);
3889                                         }
3890                                         mpte = pmap_lookup_pt_page(pmap, pv->pv_va);
3891                                         if (mpte != NULL) {
3892                                                 pmap_remove_pt_page(pmap, mpte);
3893                                                 pmap->pm_stats.resident_count--;
3894                                                 KASSERT(mpte->wire_count == NPTEPG,
3895                                                     ("pmap_remove_pages: pte page wire count error"));
3896                                                 mpte->wire_count = 0;
3897                                                 pmap_add_delayed_free_list(mpte, &free, FALSE);
3898                                                 atomic_subtract_int(&cnt.v_wire_count, 1);
3899                                         }
3900                                 } else {
3901                                         pmap->pm_stats.resident_count--;
3902                                         TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
3903                                         if (TAILQ_EMPTY(&m->md.pv_list)) {
3904                                                 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3905                                                 if (TAILQ_EMPTY(&pvh->pv_list))
3906                                                         vm_page_flag_clear(m, PG_WRITEABLE);
3907                                         }
3908                                 }
3909                                 pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
3910                         }
3911                 }
3912                 if (allfree) {
3913                         PV_STAT(pv_entry_spare -= _NPCPV);
3914                         PV_STAT(pc_chunk_count--);
3915                         PV_STAT(pc_chunk_frees++);
3916                         TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3917                         m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3918                         dump_drop_page(m->phys_addr);
3919                         vm_page_unwire(m, 0);
3920                         vm_page_free(m);
3921                 }
3922         }
3923         pmap_invalidate_all(pmap);
3924         vm_page_unlock_queues();
3925         PMAP_UNLOCK(pmap);
3926         pmap_free_zero_pages(free);
3927 }
3928
3929 /*
3930  *      pmap_is_modified:
3931  *
3932  *      Return whether or not the specified physical page was modified
3933  *      in any physical maps.
3934  */
3935 boolean_t
3936 pmap_is_modified(vm_page_t m)
3937 {
3938
3939         if (m->flags & PG_FICTITIOUS)
3940                 return (FALSE);
3941         if (pmap_is_modified_pvh(&m->md))
3942                 return (TRUE);
3943         return (pmap_is_modified_pvh(pa_to_pvh(VM_PAGE_TO_PHYS(m))));
3944 }
3945
3946 /*
3947  * Returns TRUE if any of the given mappings were used to modify
3948  * physical memory.  Otherwise, returns FALSE.  Both page and 2mpage
3949  * mappings are supported.
3950  */
3951 static boolean_t
3952 pmap_is_modified_pvh(struct md_page *pvh)
3953 {
3954         pv_entry_t pv;
3955         pt_entry_t *pte;
3956         pmap_t pmap;
3957         boolean_t rv;
3958
3959         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
3960         rv = FALSE;
3961         TAILQ_FOREACH(pv, &pvh->pv_list, pv_list) {
3962                 pmap = PV_PMAP(pv);
3963                 PMAP_LOCK(pmap);
3964                 pte = pmap_pte(pmap, pv->pv_va);
3965                 rv = (*pte & (PG_M | PG_RW)) == (PG_M | PG_RW);
3966                 PMAP_UNLOCK(pmap);
3967                 if (rv)
3968                         break;
3969         }
3970         return (rv);
3971 }
3972
3973 /*
3974  *      pmap_is_prefaultable:
3975  *
3976  *      Return whether or not the specified virtual address is elgible
3977  *      for prefault.
3978  */
3979 boolean_t
3980 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
3981 {
3982         pd_entry_t *pde;
3983         pt_entry_t *pte;
3984         boolean_t rv;
3985
3986         rv = FALSE;
3987         PMAP_LOCK(pmap);
3988         pde = pmap_pde(pmap, addr);
3989         if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
3990                 pte = pmap_pde_to_pte(pde, addr);
3991                 rv = (*pte & PG_V) == 0;
3992         }
3993         PMAP_UNLOCK(pmap);
3994         return (rv);
3995 }
3996
3997 /*
3998  * Clear the write and modified bits in each of the given page's mappings.
3999  */
4000 void
4001 pmap_remove_write(vm_page_t m)
4002 {
4003         struct md_page *pvh;
4004         pmap_t pmap;
4005         pv_entry_t next_pv, pv;
4006         pd_entry_t *pde;
4007         pt_entry_t oldpte, *pte;
4008         vm_offset_t va;
4009
4010         if ((m->flags & PG_FICTITIOUS) != 0 ||
4011             (m->flags & PG_WRITEABLE) == 0)
4012                 return;
4013         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
4014         pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
4015         TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_list, next_pv) {
4016                 va = pv->pv_va;
4017                 pmap = PV_PMAP(pv);
4018                 PMAP_LOCK(pmap);
4019                 pde = pmap_pde(pmap, va);
4020                 if ((*pde & PG_RW) != 0)
4021                         (void)pmap_demote_pde(pmap, pde, va);
4022                 PMAP_UNLOCK(pmap);
4023         }
4024         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
4025                 pmap = PV_PMAP(pv);
4026                 PMAP_LOCK(pmap);
4027                 pde = pmap_pde(pmap, pv->pv_va);
4028                 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_write: found"
4029                     " a 2mpage in page %p's pv list", m));
4030                 pte = pmap_pde_to_pte(pde, pv->pv_va);
4031 retry:
4032                 oldpte = *pte;
4033                 if (oldpte & PG_RW) {
4034                         if (!atomic_cmpset_long(pte, oldpte, oldpte &
4035                             ~(PG_RW | PG_M)))
4036                                 goto retry;
4037                         if ((oldpte & PG_M) != 0)
4038                                 vm_page_dirty(m);
4039                         pmap_invalidate_page(pmap, pv->pv_va);
4040                 }
4041                 PMAP_UNLOCK(pmap);
4042         }
4043         vm_page_flag_clear(m, PG_WRITEABLE);
4044 }
4045
4046 /*
4047  *      pmap_ts_referenced:
4048  *
4049  *      Return a count of reference bits for a page, clearing those bits.
4050  *      It is not necessary for every reference bit to be cleared, but it
4051  *      is necessary that 0 only be returned when there are truly no
4052  *      reference bits set.
4053  *
4054  *      XXX: The exact number of bits to check and clear is a matter that
4055  *      should be tested and standardized at some point in the future for
4056  *      optimal aging of shared pages.
4057  */
4058 int
4059 pmap_ts_referenced(vm_page_t m)
4060 {
4061         struct md_page *pvh;
4062         pv_entry_t pv, pvf, pvn;
4063         pmap_t pmap;
4064         pd_entry_t oldpde, *pde;
4065         pt_entry_t *pte;
4066         vm_offset_t va;
4067         int rtval = 0;
4068
4069         if (m->flags & PG_FICTITIOUS)
4070                 return (rtval);
4071         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
4072         pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
4073         TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_list, pvn) {
4074                 va = pv->pv_va;
4075                 pmap = PV_PMAP(pv);
4076                 PMAP_LOCK(pmap);
4077                 pde = pmap_pde(pmap, va);
4078                 oldpde = *pde;
4079                 if ((oldpde & PG_A) != 0) {
4080                         if (pmap_demote_pde(pmap, pde, va)) {
4081                                 if ((oldpde & PG_W) == 0) {
4082                                         /*
4083                                          * Remove the mapping to a single page
4084                                          * so that a subsequent access may
4085                                          * repromote.  Since the underlying
4086                                          * page table page is fully populated,
4087                                          * this removal never frees a page
4088                                          * table page.
4089                                          */
4090                                         va += VM_PAGE_TO_PHYS(m) - (oldpde &
4091                                             PG_PS_FRAME);
4092                                         pmap_remove_page(pmap, va, pde, NULL);
4093                                         rtval++;
4094                                         if (rtval > 4) {
4095                                                 PMAP_UNLOCK(pmap);
4096                                                 return (rtval);
4097                                         }
4098                                 }
4099                         }
4100                 }
4101                 PMAP_UNLOCK(pmap);
4102         }
4103         if ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
4104                 pvf = pv;
4105                 do {
4106                         pvn = TAILQ_NEXT(pv, pv_list);
4107                         TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
4108                         TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
4109                         pmap = PV_PMAP(pv);
4110                         PMAP_LOCK(pmap);
4111                         pde = pmap_pde(pmap, pv->pv_va);
4112                         KASSERT((*pde & PG_PS) == 0, ("pmap_ts_referenced:"
4113                             " found a 2mpage in page %p's pv list", m));
4114                         pte = pmap_pde_to_pte(pde, pv->pv_va);
4115                         if ((*pte & PG_A) != 0) {
4116                                 atomic_clear_long(pte, PG_A);
4117                                 pmap_invalidate_page(pmap, pv->pv_va);
4118                                 rtval++;
4119                                 if (rtval > 4)
4120                                         pvn = NULL;
4121                         }
4122                         PMAP_UNLOCK(pmap);
4123                 } while ((pv = pvn) != NULL && pv != pvf);
4124         }
4125         return (rtval);
4126 }
4127
4128 /*
4129  *      Clear the modify bits on the specified physical page.
4130  */
4131 void
4132 pmap_clear_modify(vm_page_t m)
4133 {
4134         struct md_page *pvh;
4135         pmap_t pmap;
4136         pv_entry_t next_pv, pv;
4137         pd_entry_t oldpde, *pde;
4138         pt_entry_t oldpte, *pte;
4139         vm_offset_t va;
4140
4141         if ((m->flags & PG_FICTITIOUS) != 0)
4142                 return;
4143         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
4144         pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
4145         TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_list, next_pv) {
4146                 va = pv->pv_va;
4147                 pmap = PV_PMAP(pv);
4148                 PMAP_LOCK(pmap);
4149                 pde = pmap_pde(pmap, va);
4150                 oldpde = *pde;
4151                 if ((oldpde & PG_RW) != 0) {
4152                         if (pmap_demote_pde(pmap, pde, va)) {
4153                                 if ((oldpde & PG_W) == 0) {
4154                                         /*
4155                                          * Write protect the mapping to a
4156                                          * single page so that a subsequent
4157                                          * write access may repromote.
4158                                          */
4159                                         va += VM_PAGE_TO_PHYS(m) - (oldpde &
4160                                             PG_PS_FRAME);
4161                                         pte = pmap_pde_to_pte(pde, va);
4162                                         oldpte = *pte;
4163                                         if ((oldpte & PG_V) != 0) {
4164                                                 while (!atomic_cmpset_long(pte,
4165                                                     oldpte,
4166                                                     oldpte & ~(PG_M | PG_RW)))
4167                                                         oldpte = *pte;
4168                                                 vm_page_dirty(m);
4169                                                 pmap_invalidate_page(pmap, va);
4170                                         }
4171                                 }
4172                         }
4173                 }
4174                 PMAP_UNLOCK(pmap);
4175         }
4176         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
4177                 pmap = PV_PMAP(pv);
4178                 PMAP_LOCK(pmap);
4179                 pde = pmap_pde(pmap, pv->pv_va);
4180                 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
4181                     " a 2mpage in page %p's pv list", m));
4182                 pte = pmap_pde_to_pte(pde, pv->pv_va);
4183                 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
4184                         atomic_clear_long(pte, PG_M);
4185                         pmap_invalidate_page(pmap, pv->pv_va);
4186                 }
4187                 PMAP_UNLOCK(pmap);
4188         }
4189 }
4190
4191 /*
4192  *      pmap_clear_reference:
4193  *
4194  *      Clear the reference bit on the specified physical page.
4195  */
4196 void
4197 pmap_clear_reference(vm_page_t m)
4198 {
4199         struct md_page *pvh;
4200         pmap_t pmap;
4201         pv_entry_t next_pv, pv;
4202         pd_entry_t oldpde, *pde;
4203         pt_entry_t *pte;
4204         vm_offset_t va;
4205
4206         if ((m->flags & PG_FICTITIOUS) != 0)
4207                 return;
4208         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
4209         pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
4210         TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_list, next_pv) {
4211                 va = pv->pv_va;
4212                 pmap = PV_PMAP(pv);
4213                 PMAP_LOCK(pmap);
4214                 pde = pmap_pde(pmap, va);
4215                 oldpde = *pde;
4216                 if ((oldpde & PG_A) != 0) {
4217                         if (pmap_demote_pde(pmap, pde, va)) {
4218                                 /*
4219                                  * Remove the mapping to a single page so
4220                                  * that a subsequent access may repromote.
4221                                  * Since the underlying page table page is
4222                                  * fully populated, this removal never frees
4223                                  * a page table page.
4224                                  */
4225                                 va += VM_PAGE_TO_PHYS(m) - (oldpde &
4226                                     PG_PS_FRAME);
4227                                 pmap_remove_page(pmap, va, pde, NULL);
4228                         }
4229                 }
4230                 PMAP_UNLOCK(pmap);
4231         }
4232         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
4233                 pmap = PV_PMAP(pv);
4234                 PMAP_LOCK(pmap);
4235                 pde = pmap_pde(pmap, pv->pv_va);
4236                 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_reference: found"
4237                     " a 2mpage in page %p's pv list", m));
4238                 pte = pmap_pde_to_pte(pde, pv->pv_va);
4239                 if (*pte & PG_A) {
4240                         atomic_clear_long(pte, PG_A);
4241                         pmap_invalidate_page(pmap, pv->pv_va);
4242                 }
4243                 PMAP_UNLOCK(pmap);
4244         }
4245 }
4246
4247 /*
4248  * Miscellaneous support routines follow
4249  */
4250
4251 /* Adjust the cache mode for a 4KB page mapped via a PTE. */
4252 static __inline void
4253 pmap_pte_attr(pt_entry_t *pte, int cache_bits)
4254 {
4255         u_int opte, npte;
4256
4257         /*
4258          * The cache mode bits are all in the low 32-bits of the
4259          * PTE, so we can just spin on updating the low 32-bits.
4260          */
4261         do {
4262                 opte = *(u_int *)pte;
4263                 npte = opte & ~PG_PTE_CACHE;
4264                 npte |= cache_bits;
4265         } while (npte != opte && !atomic_cmpset_int((u_int *)pte, opte, npte));
4266 }
4267
4268 /* Adjust the cache mode for a 2MB page mapped via a PDE. */
4269 static __inline void
4270 pmap_pde_attr(pd_entry_t *pde, int cache_bits)
4271 {
4272         u_int opde, npde;
4273
4274         /*
4275          * The cache mode bits are all in the low 32-bits of the
4276          * PDE, so we can just spin on updating the low 32-bits.
4277          */
4278         do {
4279                 opde = *(u_int *)pde;
4280                 npde = opde & ~PG_PDE_CACHE;
4281                 npde |= cache_bits;
4282         } while (npde != opde && !atomic_cmpset_int((u_int *)pde, opde, npde));
4283 }
4284
4285 /*
4286  * Map a set of physical memory pages into the kernel virtual
4287  * address space. Return a pointer to where it is mapped. This
4288  * routine is intended to be used for mapping device memory,
4289  * NOT real memory.
4290  */
4291 void *
4292 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
4293 {
4294         vm_offset_t va, offset;
4295         vm_size_t tmpsize;
4296
4297         /*
4298          * If the specified range of physical addresses fits within the direct
4299          * map window, use the direct map. 
4300          */
4301         if (pa < dmaplimit && pa + size < dmaplimit) {
4302                 va = PHYS_TO_DMAP(pa);
4303                 if (!pmap_change_attr(va, size, mode))
4304                         return ((void *)va);
4305         }
4306         offset = pa & PAGE_MASK;
4307         size = roundup(offset + size, PAGE_SIZE);
4308         va = kmem_alloc_nofault(kernel_map, size);
4309         if (!va)
4310                 panic("pmap_mapdev: Couldn't alloc kernel virtual memory");
4311         pa = trunc_page(pa);
4312         for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
4313                 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
4314         pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
4315         pmap_invalidate_cache_range(va, va + tmpsize);
4316         return ((void *)(va + offset));
4317 }
4318
4319 void *
4320 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
4321 {
4322
4323         return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
4324 }
4325
4326 void *
4327 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
4328 {
4329
4330         return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
4331 }
4332
4333 void
4334 pmap_unmapdev(vm_offset_t va, vm_size_t size)
4335 {
4336         vm_offset_t base, offset, tmpva;
4337
4338         /* If we gave a direct map region in pmap_mapdev, do nothing */
4339         if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
4340                 return;
4341         base = trunc_page(va);
4342         offset = va & PAGE_MASK;
4343         size = roundup(offset + size, PAGE_SIZE);
4344         for (tmpva = base; tmpva < (base + size); tmpva += PAGE_SIZE)
4345                 pmap_kremove(tmpva);
4346         pmap_invalidate_range(kernel_pmap, va, tmpva);
4347         kmem_free(kernel_map, base, size);
4348 }
4349
4350 /*
4351  * Tries to demote a 1GB page mapping.
4352  */
4353 static boolean_t
4354 pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe, vm_offset_t va)
4355 {
4356         pdp_entry_t newpdpe, oldpdpe;
4357         pd_entry_t *firstpde, newpde, *pde;
4358         vm_paddr_t mpdepa;
4359         vm_page_t mpde;
4360
4361         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4362         oldpdpe = *pdpe;
4363         KASSERT((oldpdpe & (PG_PS | PG_V)) == (PG_PS | PG_V),
4364             ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
4365         if ((mpde = vm_page_alloc(NULL, va >> PDPSHIFT, VM_ALLOC_INTERRUPT |
4366             VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
4367                 CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
4368                     " in pmap %p", va, pmap);
4369                 return (FALSE);
4370         }
4371         mpdepa = VM_PAGE_TO_PHYS(mpde);
4372         firstpde = (pd_entry_t *)PHYS_TO_DMAP(mpdepa);
4373         newpdpe = mpdepa | PG_M | PG_A | (oldpdpe & PG_U) | PG_RW | PG_V;
4374         KASSERT((oldpdpe & PG_A) != 0,
4375             ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
4376         KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
4377             ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
4378         newpde = oldpdpe;
4379
4380         /*
4381          * Initialize the page directory page.
4382          */
4383         for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
4384                 *pde = newpde;
4385                 newpde += NBPDR;
4386         }
4387
4388         /*
4389          * Demote the mapping.
4390          */
4391         *pdpe = newpdpe;
4392
4393         /*
4394          * Invalidate a stale recursive mapping of the page directory page.
4395          */
4396         pmap_invalidate_page(pmap, (vm_offset_t)vtopde(va));
4397
4398         pmap_pdpe_demotions++;
4399         CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
4400             " in pmap %p", va, pmap);
4401         return (TRUE);
4402 }
4403
4404 /*
4405  * Sets the memory attribute for the specified page.
4406  */
4407 void
4408 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
4409 {
4410
4411         m->md.pat_mode = ma;
4412
4413         /*
4414          * If "m" is a normal page, update its direct mapping.  This update
4415          * can be relied upon to perform any cache operations that are
4416          * required for data coherence.
4417          */
4418         if ((m->flags & PG_FICTITIOUS) == 0 &&
4419             pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
4420             m->md.pat_mode))
4421                 panic("memory attribute change on the direct map failed");
4422 }
4423
4424 /*
4425  * Changes the specified virtual address range's memory type to that given by
4426  * the parameter "mode".  The specified virtual address range must be
4427  * completely contained within either the direct map or the kernel map.  If
4428  * the virtual address range is contained within the kernel map, then the
4429  * memory type for each of the corresponding ranges of the direct map is also
4430  * changed.  (The corresponding ranges of the direct map are those ranges that
4431  * map the same physical pages as the specified virtual address range.)  These
4432  * changes to the direct map are necessary because Intel describes the
4433  * behavior of their processors as "undefined" if two or more mappings to the
4434  * same physical page have different memory types.
4435  *
4436  * Returns zero if the change completed successfully, and either EINVAL or
4437  * ENOMEM if the change failed.  Specifically, EINVAL is returned if some part
4438  * of the virtual address range was not mapped, and ENOMEM is returned if
4439  * there was insufficient memory available to complete the change.  In the
4440  * latter case, the memory type may have been changed on some part of the
4441  * virtual address range or the direct map.
4442  */
4443 int
4444 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
4445 {
4446         int error;
4447
4448         PMAP_LOCK(kernel_pmap);
4449         error = pmap_change_attr_locked(va, size, mode);
4450         PMAP_UNLOCK(kernel_pmap);
4451         return (error);
4452 }
4453
4454 static int
4455 pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode)
4456 {
4457         vm_offset_t base, offset, tmpva;
4458         vm_paddr_t pa_start, pa_end;
4459         pdp_entry_t *pdpe;
4460         pd_entry_t *pde;
4461         pt_entry_t *pte;
4462         int cache_bits_pte, cache_bits_pde, error;
4463         boolean_t changed;
4464
4465         PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
4466         base = trunc_page(va);
4467         offset = va & PAGE_MASK;
4468         size = roundup(offset + size, PAGE_SIZE);
4469
4470         /*
4471          * Only supported on kernel virtual addresses, including the direct
4472          * map but excluding the recursive map.
4473          */
4474         if (base < DMAP_MIN_ADDRESS)
4475                 return (EINVAL);
4476
4477         cache_bits_pde = cache_bits_pte = -1;
4478         changed = FALSE;
4479
4480         /*
4481          * Pages that aren't mapped aren't supported.  Also break down 2MB pages
4482          * into 4KB pages if required.
4483          */
4484         for (tmpva = base; tmpva < base + size; ) {
4485                 pdpe = pmap_pdpe(kernel_pmap, tmpva);
4486                 if (*pdpe == 0)
4487                         return (EINVAL);
4488                 if (*pdpe & PG_PS) {
4489                         /*
4490                          * If the current 1GB page already has the required
4491                          * memory type, then we need not demote this page. Just
4492                          * increment tmpva to the next 1GB page frame.
4493                          */
4494                         if (cache_bits_pde < 0)
4495                                 cache_bits_pde = pmap_cache_bits(mode, 1);
4496                         if ((*pdpe & PG_PDE_CACHE) == cache_bits_pde) {
4497                                 tmpva = trunc_1gpage(tmpva) + NBPDP;
4498                                 continue;
4499                         }
4500
4501                         /*
4502                          * If the current offset aligns with a 1GB page frame
4503                          * and there is at least 1GB left within the range, then
4504                          * we need not break down this page into 2MB pages.
4505                          */
4506                         if ((tmpva & PDPMASK) == 0 &&
4507                             tmpva + PDPMASK < base + size) {
4508                                 tmpva += NBPDP;
4509                                 continue;
4510                         }
4511                         if (!pmap_demote_pdpe(kernel_pmap, pdpe, tmpva))
4512                                 return (ENOMEM);
4513                 }
4514                 pde = pmap_pdpe_to_pde(pdpe, tmpva);
4515                 if (*pde == 0)
4516                         return (EINVAL);
4517                 if (*pde & PG_PS) {
4518                         /*
4519                          * If the current 2MB page already has the required
4520                          * memory type, then we need not demote this page. Just
4521                          * increment tmpva to the next 2MB page frame.
4522                          */
4523                         if (cache_bits_pde < 0)
4524                                 cache_bits_pde = pmap_cache_bits(mode, 1);
4525                         if ((*pde & PG_PDE_CACHE) == cache_bits_pde) {
4526                                 tmpva = trunc_2mpage(tmpva) + NBPDR;
4527                                 continue;
4528                         }
4529
4530                         /*
4531                          * If the current offset aligns with a 2MB page frame
4532                          * and there is at least 2MB left within the range, then
4533                          * we need not break down this page into 4KB pages.
4534                          */
4535                         if ((tmpva & PDRMASK) == 0 &&
4536                             tmpva + PDRMASK < base + size) {
4537                                 tmpva += NBPDR;
4538                                 continue;
4539                         }
4540                         if (!pmap_demote_pde(kernel_pmap, pde, tmpva))
4541                                 return (ENOMEM);
4542                 }
4543                 pte = pmap_pde_to_pte(pde, tmpva);
4544                 if (*pte == 0)
4545                         return (EINVAL);
4546                 tmpva += PAGE_SIZE;
4547         }
4548         error = 0;
4549
4550         /*
4551          * Ok, all the pages exist, so run through them updating their
4552          * cache mode if required.
4553          */
4554         pa_start = pa_end = 0;
4555         for (tmpva = base; tmpva < base + size; ) {
4556                 pdpe = pmap_pdpe(kernel_pmap, tmpva);
4557                 if (*pdpe & PG_PS) {
4558                         if (cache_bits_pde < 0)
4559                                 cache_bits_pde = pmap_cache_bits(mode, 1);
4560                         if ((*pdpe & PG_PDE_CACHE) != cache_bits_pde) {
4561                                 pmap_pde_attr(pdpe, cache_bits_pde);
4562                                 if (!changed)
4563                                         changed = TRUE;
4564                         }
4565                         if (tmpva >= VM_MIN_KERNEL_ADDRESS) {
4566                                 if (pa_start == pa_end) {
4567                                         /* Start physical address run. */
4568                                         pa_start = *pdpe & PG_PS_FRAME;
4569                                         pa_end = pa_start + NBPDP;
4570                                 } else if (pa_end == (*pdpe & PG_PS_FRAME))
4571                                         pa_end += NBPDP;
4572                                 else {
4573                                         /* Run ended, update direct map. */
4574                                         error = pmap_change_attr_locked(
4575                                             PHYS_TO_DMAP(pa_start),
4576                                             pa_end - pa_start, mode);
4577                                         if (error != 0)
4578                                                 break;
4579                                         /* Start physical address run. */
4580                                         pa_start = *pdpe & PG_PS_FRAME;
4581                                         pa_end = pa_start + NBPDP;
4582                                 }
4583                         }
4584                         tmpva = trunc_1gpage(tmpva) + NBPDP;
4585                         continue;
4586                 }
4587                 pde = pmap_pdpe_to_pde(pdpe, tmpva);
4588                 if (*pde & PG_PS) {
4589                         if (cache_bits_pde < 0)
4590                                 cache_bits_pde = pmap_cache_bits(mode, 1);
4591                         if ((*pde & PG_PDE_CACHE) != cache_bits_pde) {
4592                                 pmap_pde_attr(pde, cache_bits_pde);
4593                                 if (!changed)
4594                                         changed = TRUE;
4595                         }
4596                         if (tmpva >= VM_MIN_KERNEL_ADDRESS) {
4597                                 if (pa_start == pa_end) {
4598                                         /* Start physical address run. */
4599                                         pa_start = *pde & PG_PS_FRAME;
4600                                         pa_end = pa_start + NBPDR;
4601                                 } else if (pa_end == (*pde & PG_PS_FRAME))
4602                                         pa_end += NBPDR;
4603                                 else {
4604                                         /* Run ended, update direct map. */
4605                                         error = pmap_change_attr_locked(
4606                                             PHYS_TO_DMAP(pa_start),
4607                                             pa_end - pa_start, mode);
4608                                         if (error != 0)
4609                                                 break;
4610                                         /* Start physical address run. */
4611                                         pa_start = *pde & PG_PS_FRAME;
4612                                         pa_end = pa_start + NBPDR;
4613                                 }
4614                         }
4615                         tmpva = trunc_2mpage(tmpva) + NBPDR;
4616                 } else {
4617                         if (cache_bits_pte < 0)
4618                                 cache_bits_pte = pmap_cache_bits(mode, 0);
4619                         pte = pmap_pde_to_pte(pde, tmpva);
4620                         if ((*pte & PG_PTE_CACHE) != cache_bits_pte) {
4621                                 pmap_pte_attr(pte, cache_bits_pte);
4622                                 if (!changed)
4623                                         changed = TRUE;
4624                         }
4625                         if (tmpva >= VM_MIN_KERNEL_ADDRESS) {
4626                                 if (pa_start == pa_end) {
4627                                         /* Start physical address run. */
4628                                         pa_start = *pte & PG_FRAME;
4629                                         pa_end = pa_start + PAGE_SIZE;
4630                                 } else if (pa_end == (*pte & PG_FRAME))
4631                                         pa_end += PAGE_SIZE;
4632                                 else {
4633                                         /* Run ended, update direct map. */
4634                                         error = pmap_change_attr_locked(
4635                                             PHYS_TO_DMAP(pa_start),
4636                                             pa_end - pa_start, mode);
4637                                         if (error != 0)
4638                                                 break;
4639                                         /* Start physical address run. */
4640                                         pa_start = *pte & PG_FRAME;
4641                                         pa_end = pa_start + PAGE_SIZE;
4642                                 }
4643                         }
4644                         tmpva += PAGE_SIZE;
4645                 }
4646         }
4647         if (error == 0 && pa_start != pa_end)
4648                 error = pmap_change_attr_locked(PHYS_TO_DMAP(pa_start),
4649                     pa_end - pa_start, mode);
4650
4651         /*
4652          * Flush CPU caches if required to make sure any data isn't cached that
4653          * shouldn't be, etc.
4654          */
4655         if (changed) {
4656                 pmap_invalidate_range(kernel_pmap, base, tmpva);
4657                 pmap_invalidate_cache_range(base, tmpva);
4658         }
4659         return (error);
4660 }
4661
4662 /*
4663  * perform the pmap work for mincore
4664  */
4665 int
4666 pmap_mincore(pmap_t pmap, vm_offset_t addr)
4667 {
4668         pd_entry_t *pdep;
4669         pt_entry_t pte;
4670         vm_paddr_t pa;
4671         vm_page_t m;
4672         int val = 0;
4673         
4674         PMAP_LOCK(pmap);
4675         pdep = pmap_pde(pmap, addr);
4676         if (pdep != NULL && (*pdep & PG_V)) {
4677                 if (*pdep & PG_PS) {
4678                         pte = *pdep;
4679                         val = MINCORE_SUPER;
4680                         /* Compute the physical address of the 4KB page. */
4681                         pa = ((*pdep & PG_PS_FRAME) | (addr & PDRMASK)) &
4682                             PG_FRAME;
4683                 } else {
4684                         pte = *pmap_pde_to_pte(pdep, addr);
4685                         pa = pte & PG_FRAME;
4686                 }
4687         } else {
4688                 pte = 0;
4689                 pa = 0;
4690         }
4691         PMAP_UNLOCK(pmap);
4692
4693         if (pte != 0) {
4694                 val |= MINCORE_INCORE;
4695                 if ((pte & PG_MANAGED) == 0)
4696                         return val;
4697
4698                 m = PHYS_TO_VM_PAGE(pa);
4699
4700                 /*
4701                  * Modified by us
4702                  */
4703                 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4704                         val |= MINCORE_MODIFIED|MINCORE_MODIFIED_OTHER;
4705                 else {
4706                         /*
4707                          * Modified by someone else
4708                          */
4709                         vm_page_lock_queues();
4710                         if (m->dirty || pmap_is_modified(m))
4711                                 val |= MINCORE_MODIFIED_OTHER;
4712                         vm_page_unlock_queues();
4713                 }
4714                 /*
4715                  * Referenced by us
4716                  */
4717                 if (pte & PG_A)
4718                         val |= MINCORE_REFERENCED|MINCORE_REFERENCED_OTHER;
4719                 else {
4720                         /*
4721                          * Referenced by someone else
4722                          */
4723                         vm_page_lock_queues();
4724                         if ((m->flags & PG_REFERENCED) ||
4725                             pmap_ts_referenced(m)) {
4726                                 val |= MINCORE_REFERENCED_OTHER;
4727                                 vm_page_flag_set(m, PG_REFERENCED);
4728                         }
4729                         vm_page_unlock_queues();
4730                 }
4731         } 
4732         return val;
4733 }
4734
4735 void
4736 pmap_activate(struct thread *td)
4737 {
4738         pmap_t  pmap, oldpmap;
4739         u_int64_t  cr3;
4740
4741         critical_enter();
4742         pmap = vmspace_pmap(td->td_proc->p_vmspace);
4743         oldpmap = PCPU_GET(curpmap);
4744 #ifdef SMP
4745 if (oldpmap)    /* XXX FIXME */
4746         atomic_clear_int(&oldpmap->pm_active, PCPU_GET(cpumask));
4747         atomic_set_int(&pmap->pm_active, PCPU_GET(cpumask));
4748 #else
4749 if (oldpmap)    /* XXX FIXME */
4750         oldpmap->pm_active &= ~PCPU_GET(cpumask);
4751         pmap->pm_active |= PCPU_GET(cpumask);
4752 #endif
4753         cr3 = DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4);
4754         td->td_pcb->pcb_cr3 = cr3;
4755         load_cr3(cr3);
4756         critical_exit();
4757 }
4758
4759 /*
4760  *      Increase the starting virtual address of the given mapping if a
4761  *      different alignment might result in more superpage mappings.
4762  */
4763 void
4764 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
4765     vm_offset_t *addr, vm_size_t size)
4766 {
4767         vm_offset_t superpage_offset;
4768
4769         if (size < NBPDR)
4770                 return;
4771         if (object != NULL && (object->flags & OBJ_COLORED) != 0)
4772                 offset += ptoa(object->pg_color);
4773         superpage_offset = offset & PDRMASK;
4774         if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
4775             (*addr & PDRMASK) == superpage_offset)
4776                 return;
4777         if ((*addr & PDRMASK) < superpage_offset)
4778                 *addr = (*addr & ~PDRMASK) + superpage_offset;
4779         else
4780                 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
4781 }