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