583a7a1ce0f50ccd11dbf136ef7465cb9e340ff4
[dragonfly.git] / sys / platform / pc64 / x86_64 / pmap.c
1 /*
2  * Copyright (c) 1991 Regents of the University of California.
3  * Copyright (c) 1994 John S. Dyson
4  * Copyright (c) 1994 David Greenman
5  * Copyright (c) 2003 Peter Wemm
6  * Copyright (c) 2005-2008 Alan L. Cox <alc@cs.rice.edu>
7  * Copyright (c) 2008, 2009 The DragonFly Project.
8  * Copyright (c) 2008, 2009 Jordan Gordeev.
9  * All rights reserved.
10  *
11  * This code is derived from software contributed to Berkeley by
12  * the Systems Programming Group of the University of Utah Computer
13  * Science Department and William Jolitz of UUNET Technologies Inc.
14  *
15  * Redistribution and use in source and binary forms, with or without
16  * modification, are permitted provided that the following conditions
17  * are met:
18  * 1. Redistributions of source code must retain the above copyright
19  *    notice, this list of conditions and the following disclaimer.
20  * 2. Redistributions in binary form must reproduce the above copyright
21  *    notice, this list of conditions and the following disclaimer in the
22  *    documentation and/or other materials provided with the distribution.
23  * 3. All advertising materials mentioning features or use of this software
24  *    must display the following acknowledgement:
25  *      This product includes software developed by the University of
26  *      California, Berkeley and its contributors.
27  * 4. Neither the name of the University nor the names of its contributors
28  *    may be used to endorse or promote products derived from this software
29  *    without specific prior written permission.
30  *
31  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
32  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
33  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
34  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
35  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
36  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
37  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
38  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
39  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
40  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
41  * SUCH DAMAGE.
42  *
43  *      from:   @(#)pmap.c      7.7 (Berkeley)  5/12/91
44  * $FreeBSD: src/sys/i386/i386/pmap.c,v 1.250.2.18 2002/03/06 22:48:53 silby Exp $
45  */
46
47 /*
48  *      Manages physical address maps.
49  *
50  *      In addition to hardware address maps, this
51  *      module is called upon to provide software-use-only
52  *      maps which may or may not be stored in the same
53  *      form as hardware maps.  These pseudo-maps are
54  *      used to store intermediate results from copy
55  *      operations to and from address spaces.
56  *
57  *      Since the information managed by this module is
58  *      also stored by the logical address mapping module,
59  *      this module may throw away valid virtual-to-physical
60  *      mappings at almost any time.  However, invalidations
61  *      of virtual-to-physical mappings must be done as
62  *      requested.
63  *
64  *      In order to cope with hardware architectures which
65  *      make virtual-to-physical map invalidates expensive,
66  *      this module may delay invalidate or reduced protection
67  *      operations until such time as they are actually
68  *      necessary.  This module is given full information as
69  *      to which processors are currently using which maps,
70  *      and to when physical maps must be made correct.
71  */
72
73 #if JG
74 #include "opt_disable_pse.h"
75 #include "opt_pmap.h"
76 #endif
77 #include "opt_msgbuf.h"
78
79 #include <sys/param.h>
80 #include <sys/systm.h>
81 #include <sys/kernel.h>
82 #include <sys/proc.h>
83 #include <sys/msgbuf.h>
84 #include <sys/vmmeter.h>
85 #include <sys/mman.h>
86
87 #include <vm/vm.h>
88 #include <vm/vm_param.h>
89 #include <sys/sysctl.h>
90 #include <sys/lock.h>
91 #include <vm/vm_kern.h>
92 #include <vm/vm_page.h>
93 #include <vm/vm_map.h>
94 #include <vm/vm_object.h>
95 #include <vm/vm_extern.h>
96 #include <vm/vm_pageout.h>
97 #include <vm/vm_pager.h>
98 #include <vm/vm_zone.h>
99
100 #include <sys/user.h>
101 #include <sys/thread2.h>
102 #include <sys/sysref2.h>
103
104 #include <machine/cputypes.h>
105 #include <machine/md_var.h>
106 #include <machine/specialreg.h>
107 #include <machine/smp.h>
108 #include <machine_base/apic/apicreg.h>
109 #include <machine/globaldata.h>
110 #include <machine/pmap.h>
111 #include <machine/pmap_inval.h>
112
113 #include <ddb/ddb.h>
114
115 #define PMAP_KEEP_PDIRS
116 #ifndef PMAP_SHPGPERPROC
117 #define PMAP_SHPGPERPROC 200
118 #endif
119
120 #if defined(DIAGNOSTIC)
121 #define PMAP_DIAGNOSTIC
122 #endif
123
124 #define MINPV 2048
125
126 /*
127  * Get PDEs and PTEs for user/kernel address space
128  */
129 static pd_entry_t *pmap_pde(pmap_t pmap, vm_offset_t va);
130 #define pdir_pde(m, v) (m[(vm_offset_t)(v) >> PDRSHIFT])
131
132 #define pmap_pde_v(pte)         ((*(pd_entry_t *)pte & PG_V) != 0)
133 #define pmap_pte_w(pte)         ((*(pt_entry_t *)pte & PG_W) != 0)
134 #define pmap_pte_m(pte)         ((*(pt_entry_t *)pte & PG_M) != 0)
135 #define pmap_pte_u(pte)         ((*(pt_entry_t *)pte & PG_A) != 0)
136 #define pmap_pte_v(pte)         ((*(pt_entry_t *)pte & PG_V) != 0)
137
138
139 /*
140  * Given a map and a machine independent protection code,
141  * convert to a vax protection code.
142  */
143 #define pte_prot(m, p)          \
144         (protection_codes[p & (VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE)])
145 static int protection_codes[8];
146
147 struct pmap kernel_pmap;
148 static TAILQ_HEAD(,pmap)        pmap_list = TAILQ_HEAD_INITIALIZER(pmap_list);
149
150 vm_paddr_t avail_start;         /* PA of first available physical page */
151 vm_paddr_t avail_end;           /* PA of last available physical page */
152 vm_offset_t virtual2_start;     /* cutout free area prior to kernel start */
153 vm_offset_t virtual2_end;
154 vm_offset_t virtual_start;      /* VA of first avail page (after kernel bss) */
155 vm_offset_t virtual_end;        /* VA of last avail page (end of kernel AS) */
156 vm_offset_t KvaStart;           /* VA start of KVA space */
157 vm_offset_t KvaEnd;             /* VA end of KVA space (non-inclusive) */
158 vm_offset_t KvaSize;            /* max size of kernel virtual address space */
159 static boolean_t pmap_initialized = FALSE;      /* Has pmap_init completed? */
160 static int pgeflag;             /* PG_G or-in */
161 static int pseflag;             /* PG_PS or-in */
162
163 static vm_object_t kptobj;
164
165 static int ndmpdp;
166 static vm_paddr_t dmaplimit;
167 static int nkpt;
168 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
169
170 static uint64_t KPTbase;
171 static uint64_t KPTphys;
172 static uint64_t KPDphys;        /* phys addr of kernel level 2 */
173 static uint64_t KPDbase;        /* phys addr of kernel level 2 @ KERNBASE */
174 uint64_t KPDPphys;      /* phys addr of kernel level 3 */
175 uint64_t KPML4phys;     /* phys addr of kernel level 4 */
176
177 static uint64_t DMPDphys;       /* phys addr of direct mapped level 2 */
178 static uint64_t DMPDPphys;      /* phys addr of direct mapped level 3 */
179
180 /*
181  * Data for the pv entry allocation mechanism
182  */
183 static vm_zone_t pvzone;
184 static struct vm_zone pvzone_store;
185 static struct vm_object pvzone_obj;
186 static int pv_entry_count=0, pv_entry_max=0, pv_entry_high_water=0;
187 static int pmap_pagedaemon_waken = 0;
188 static struct pv_entry *pvinit;
189
190 /*
191  * All those kernel PT submaps that BSD is so fond of
192  */
193 pt_entry_t *CMAP1 = 0, *ptmmap;
194 caddr_t CADDR1 = 0, ptvmmap = 0;
195 static pt_entry_t *msgbufmap;
196 struct msgbuf *msgbufp=0;
197
198 /*
199  * Crashdump maps.
200  */
201 static pt_entry_t *pt_crashdumpmap;
202 static caddr_t crashdumpmap;
203
204 extern pt_entry_t *SMPpt;
205 extern uint64_t SMPptpa;
206
207 #define DISABLE_PSE
208
209 static pv_entry_t get_pv_entry (void);
210 static void i386_protection_init (void);
211 static void create_pagetables(vm_paddr_t *firstaddr);
212 static void pmap_remove_all (vm_page_t m);
213 static int  pmap_remove_pte (struct pmap *pmap, pt_entry_t *ptq,
214                                 vm_offset_t sva, pmap_inval_info_t info);
215 static void pmap_remove_page (struct pmap *pmap, 
216                                 vm_offset_t va, pmap_inval_info_t info);
217 static int  pmap_remove_entry (struct pmap *pmap, vm_page_t m,
218                                 vm_offset_t va, pmap_inval_info_t info);
219 static boolean_t pmap_testbit (vm_page_t m, int bit);
220 static void pmap_insert_entry (pmap_t pmap, vm_offset_t va,
221                                 vm_page_t mpte, vm_page_t m);
222
223 static vm_page_t pmap_allocpte (pmap_t pmap, vm_offset_t va);
224
225 static int pmap_release_free_page (pmap_t pmap, vm_page_t p);
226 static vm_page_t _pmap_allocpte (pmap_t pmap, vm_pindex_t ptepindex);
227 static pt_entry_t * pmap_pte_quick (pmap_t pmap, vm_offset_t va);
228 static vm_page_t pmap_page_lookup (vm_object_t object, vm_pindex_t pindex);
229 static int _pmap_unwire_pte_hold(pmap_t pmap, vm_offset_t va, vm_page_t m,
230                                 pmap_inval_info_t info);
231 static int pmap_unuse_pt (pmap_t, vm_offset_t, vm_page_t, pmap_inval_info_t);
232 static vm_offset_t pmap_kmem_choose(vm_offset_t addr);
233
234 static unsigned pdir4mb;
235
236 /*
237  * Move the kernel virtual free pointer to the next
238  * 2MB.  This is used to help improve performance
239  * by using a large (2MB) page for much of the kernel
240  * (.text, .data, .bss)
241  */
242 static
243 vm_offset_t
244 pmap_kmem_choose(vm_offset_t addr)
245 {
246         vm_offset_t newaddr = addr;
247
248         newaddr = (addr + (NBPDR - 1)) & ~(NBPDR - 1);
249         return newaddr;
250 }
251
252 /*
253  * pmap_pte_quick:
254  *
255  *      Super fast pmap_pte routine best used when scanning the pv lists.
256  *      This eliminates many course-grained invltlb calls.  Note that many of
257  *      the pv list scans are across different pmaps and it is very wasteful
258  *      to do an entire invltlb when checking a single mapping.
259  *
260  *      Should only be called while in a critical section.
261  */
262 static __inline pt_entry_t *pmap_pte(pmap_t pmap, vm_offset_t va);
263
264 static
265 pt_entry_t *
266 pmap_pte_quick(pmap_t pmap, vm_offset_t va)
267 {
268         return pmap_pte(pmap, va);
269 }
270
271 /* Return a non-clipped PD index for a given VA */
272 static __inline
273 vm_pindex_t
274 pmap_pde_pindex(vm_offset_t va)
275 {
276         return va >> PDRSHIFT;
277 }
278
279 /* Return various clipped indexes for a given VA */
280 static __inline
281 vm_pindex_t
282 pmap_pte_index(vm_offset_t va)
283 {
284
285         return ((va >> PAGE_SHIFT) & ((1ul << NPTEPGSHIFT) - 1));
286 }
287
288 static __inline
289 vm_pindex_t
290 pmap_pde_index(vm_offset_t va)
291 {
292
293         return ((va >> PDRSHIFT) & ((1ul << NPDEPGSHIFT) - 1));
294 }
295
296 static __inline
297 vm_pindex_t
298 pmap_pdpe_index(vm_offset_t va)
299 {
300
301         return ((va >> PDPSHIFT) & ((1ul << NPDPEPGSHIFT) - 1));
302 }
303
304 static __inline
305 vm_pindex_t
306 pmap_pml4e_index(vm_offset_t va)
307 {
308
309         return ((va >> PML4SHIFT) & ((1ul << NPML4EPGSHIFT) - 1));
310 }
311
312 /* Return a pointer to the PML4 slot that corresponds to a VA */
313 static __inline
314 pml4_entry_t *
315 pmap_pml4e(pmap_t pmap, vm_offset_t va)
316 {
317
318         return (&pmap->pm_pml4[pmap_pml4e_index(va)]);
319 }
320
321 /* Return a pointer to the PDP slot that corresponds to a VA */
322 static __inline
323 pdp_entry_t *
324 pmap_pml4e_to_pdpe(pml4_entry_t *pml4e, vm_offset_t va)
325 {
326         pdp_entry_t *pdpe;
327
328         pdpe = (pdp_entry_t *)PHYS_TO_DMAP(*pml4e & PG_FRAME);
329         return (&pdpe[pmap_pdpe_index(va)]);
330 }
331
332 /* Return a pointer to the PDP slot that corresponds to a VA */
333 static __inline
334 pdp_entry_t *
335 pmap_pdpe(pmap_t pmap, vm_offset_t va)
336 {
337         pml4_entry_t *pml4e;
338
339         pml4e = pmap_pml4e(pmap, va);
340         if ((*pml4e & PG_V) == 0)
341                 return NULL;
342         return (pmap_pml4e_to_pdpe(pml4e, va));
343 }
344
345 /* Return a pointer to the PD slot that corresponds to a VA */
346 static __inline
347 pd_entry_t *
348 pmap_pdpe_to_pde(pdp_entry_t *pdpe, vm_offset_t va)
349 {
350         pd_entry_t *pde;
351
352         pde = (pd_entry_t *)PHYS_TO_DMAP(*pdpe & PG_FRAME);
353         return (&pde[pmap_pde_index(va)]);
354 }
355
356 /* Return a pointer to the PD slot that corresponds to a VA */
357 static __inline
358 pd_entry_t *
359 pmap_pde(pmap_t pmap, vm_offset_t va)
360 {
361         pdp_entry_t *pdpe;
362
363         pdpe = pmap_pdpe(pmap, va);
364         if (pdpe == NULL || (*pdpe & PG_V) == 0)
365                  return NULL;
366         return (pmap_pdpe_to_pde(pdpe, va));
367 }
368
369 /* Return a pointer to the PT slot that corresponds to a VA */
370 static __inline
371 pt_entry_t *
372 pmap_pde_to_pte(pd_entry_t *pde, vm_offset_t va)
373 {
374         pt_entry_t *pte;
375
376         pte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
377         return (&pte[pmap_pte_index(va)]);
378 }
379
380 /* Return a pointer to the PT slot that corresponds to a VA */
381 static __inline
382 pt_entry_t *
383 pmap_pte(pmap_t pmap, vm_offset_t va)
384 {
385         pd_entry_t *pde;
386
387         pde = pmap_pde(pmap, va);
388         if (pde == NULL || (*pde & PG_V) == 0)
389                 return NULL;
390         if ((*pde & PG_PS) != 0)        /* compat with i386 pmap_pte() */
391                 return ((pt_entry_t *)pde);
392         return (pmap_pde_to_pte(pde, va));
393 }
394
395 static __inline
396 pt_entry_t *
397 vtopte(vm_offset_t va)
398 {
399         uint64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
400
401         return (PTmap + ((va >> PAGE_SHIFT) & mask));
402 }
403
404 static __inline
405 pd_entry_t *
406 vtopde(vm_offset_t va)
407 {
408         uint64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
409
410         return (PDmap + ((va >> PDRSHIFT) & mask));
411 }
412
413 static uint64_t
414 allocpages(vm_paddr_t *firstaddr, int n)
415 {
416         uint64_t ret;
417
418         ret = *firstaddr;
419         bzero((void *)ret, n * PAGE_SIZE);
420         *firstaddr += n * PAGE_SIZE;
421         return (ret);
422 }
423
424 static
425 void
426 create_pagetables(vm_paddr_t *firstaddr)
427 {
428         int i;
429
430         /* we are running (mostly) V=P at this point */
431
432         /* Allocate pages */
433         KPTbase = allocpages(firstaddr, NKPT);
434         KPTphys = allocpages(firstaddr, NKPT);
435         KPML4phys = allocpages(firstaddr, 1);
436         KPDPphys = allocpages(firstaddr, NKPML4E);
437
438         /*
439          * Calculate the page directory base for KERNBASE,
440          * that is where we start populating the page table pages.
441          * Basically this is the end - 2.
442          */
443         KPDphys = allocpages(firstaddr, NKPDPE);
444         KPDbase = KPDphys + ((NKPDPE - (NPDPEPG - KPDPI)) << PAGE_SHIFT);
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         /*
455          * Fill in the underlying page table pages for the area around
456          * KERNBASE.  This remaps low physical memory to KERNBASE.
457          *
458          * Read-only from zero to physfree
459          * XXX not fully used, underneath 2M pages
460          */
461         for (i = 0; (i << PAGE_SHIFT) < *firstaddr; i++) {
462                 ((pt_entry_t *)KPTbase)[i] = i << PAGE_SHIFT;
463                 ((pt_entry_t *)KPTbase)[i] |= PG_RW | PG_V | PG_G;
464         }
465
466         /*
467          * Now map the initial kernel page tables.  One block of page
468          * tables is placed at the beginning of kernel virtual memory,
469          * and another block is placed at KERNBASE to map the kernel binary,
470          * data, bss, and initial pre-allocations.
471          */
472         for (i = 0; i < NKPT; i++) {
473                 ((pd_entry_t *)KPDbase)[i] = KPTbase + (i << PAGE_SHIFT);
474                 ((pd_entry_t *)KPDbase)[i] |= PG_RW | PG_V;
475         }
476         for (i = 0; i < NKPT; i++) {
477                 ((pd_entry_t *)KPDphys)[i] = KPTphys + (i << PAGE_SHIFT);
478                 ((pd_entry_t *)KPDphys)[i] |= PG_RW | PG_V;
479         }
480
481         /*
482          * Map from zero to end of allocations using 2M pages as an
483          * optimization.  This will bypass some of the KPTBase pages
484          * above in the KERNBASE area.
485          */
486         for (i = 0; (i << PDRSHIFT) < *firstaddr; i++) {
487                 ((pd_entry_t *)KPDbase)[i] = i << PDRSHIFT;
488                 ((pd_entry_t *)KPDbase)[i] |= PG_RW | PG_V | PG_PS | PG_G;
489         }
490
491         /*
492          * And connect up the PD to the PDP.  The kernel pmap is expected
493          * to pre-populate all of its PDs.  See NKPDPE in vmparam.h.
494          */
495         for (i = 0; i < NKPDPE; i++) {
496                 ((pdp_entry_t *)KPDPphys)[NPDPEPG - NKPDPE + i] =
497                                 KPDphys + (i << PAGE_SHIFT);
498                 ((pdp_entry_t *)KPDPphys)[NPDPEPG - NKPDPE + i] |=
499                                 PG_RW | PG_V | PG_U;
500         }
501
502         /* Now set up the direct map space using either 2MB or 1GB pages */
503         /* Preset PG_M and PG_A because demotion expects it */
504         if ((amd_feature & AMDID_PAGE1GB) == 0) {
505                 for (i = 0; i < NPDEPG * ndmpdp; i++) {
506                         ((pd_entry_t *)DMPDphys)[i] = (vm_paddr_t)i << PDRSHIFT;
507                         ((pd_entry_t *)DMPDphys)[i] |= PG_RW | PG_V | PG_PS |
508                             PG_G | PG_M | PG_A;
509                 }
510                 /* And the direct map space's PDP */
511                 for (i = 0; i < ndmpdp; i++) {
512                         ((pdp_entry_t *)DMPDPphys)[i] = DMPDphys +
513                             (i << PAGE_SHIFT);
514                         ((pdp_entry_t *)DMPDPphys)[i] |= PG_RW | PG_V | PG_U;
515                 }
516         } else {
517                 for (i = 0; i < ndmpdp; i++) {
518                         ((pdp_entry_t *)DMPDPphys)[i] =
519                             (vm_paddr_t)i << PDPSHIFT;
520                         ((pdp_entry_t *)DMPDPphys)[i] |= PG_RW | PG_V | PG_PS |
521                             PG_G | PG_M | PG_A;
522                 }
523         }
524
525         /* And recursively map PML4 to itself in order to get PTmap */
526         ((pdp_entry_t *)KPML4phys)[PML4PML4I] = KPML4phys;
527         ((pdp_entry_t *)KPML4phys)[PML4PML4I] |= PG_RW | PG_V | PG_U;
528
529         /* Connect the Direct Map slot up to the PML4 */
530         ((pdp_entry_t *)KPML4phys)[DMPML4I] = DMPDPphys;
531         ((pdp_entry_t *)KPML4phys)[DMPML4I] |= PG_RW | PG_V | PG_U;
532
533         /* Connect the KVA slot up to the PML4 */
534         ((pdp_entry_t *)KPML4phys)[KPML4I] = KPDPphys;
535         ((pdp_entry_t *)KPML4phys)[KPML4I] |= PG_RW | PG_V | PG_U;
536 }
537
538 void
539 init_paging(vm_paddr_t *firstaddr)
540 {
541         create_pagetables(firstaddr);
542 }
543
544 /*
545  *      Bootstrap the system enough to run with virtual memory.
546  *
547  *      On the i386 this is called after mapping has already been enabled
548  *      and just syncs the pmap module with what has already been done.
549  *      [We can't call it easily with mapping off since the kernel is not
550  *      mapped with PA == VA, hence we would have to relocate every address
551  *      from the linked base (virtual) address "KERNBASE" to the actual
552  *      (physical) address starting relative to 0]
553  */
554 void
555 pmap_bootstrap(vm_paddr_t *firstaddr)
556 {
557         vm_offset_t va;
558         pt_entry_t *pte;
559         struct mdglobaldata *gd;
560         int pg;
561
562         KvaStart = VM_MIN_KERNEL_ADDRESS;
563         KvaEnd = VM_MAX_KERNEL_ADDRESS;
564         KvaSize = KvaEnd - KvaStart;
565
566         avail_start = *firstaddr;
567
568         /*
569          * Create an initial set of page tables to run the kernel in.
570          */
571         create_pagetables(firstaddr);
572
573         virtual2_start = KvaStart;
574         virtual2_end = PTOV_OFFSET;
575
576         virtual_start = (vm_offset_t) PTOV_OFFSET + *firstaddr;
577         virtual_start = pmap_kmem_choose(virtual_start);
578
579         virtual_end = VM_MAX_KERNEL_ADDRESS;
580
581         /* XXX do %cr0 as well */
582         load_cr4(rcr4() | CR4_PGE | CR4_PSE);
583         load_cr3(KPML4phys);
584
585         /*
586          * Initialize protection array.
587          */
588         i386_protection_init();
589
590         /*
591          * The kernel's pmap is statically allocated so we don't have to use
592          * pmap_create, which is unlikely to work correctly at this part of
593          * the boot sequence (XXX and which no longer exists).
594          */
595         kernel_pmap.pm_pml4 = (pdp_entry_t *) (PTOV_OFFSET + KPML4phys);
596         kernel_pmap.pm_count = 1;
597         kernel_pmap.pm_active = (cpumask_t)-1;  /* don't allow deactivation */
598         TAILQ_INIT(&kernel_pmap.pm_pvlist);
599         nkpt = NKPT;
600
601         /*
602          * Reserve some special page table entries/VA space for temporary
603          * mapping of pages.
604          */
605 #define SYSMAP(c, p, v, n)      \
606         v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
607
608         va = virtual_start;
609 #ifdef JG
610         pte = (pt_entry_t *) pmap_pte(&kernel_pmap, va);
611 #else
612         pte = vtopte(va);
613 #endif
614
615         /*
616          * CMAP1/CMAP2 are used for zeroing and copying pages.
617          */
618         SYSMAP(caddr_t, CMAP1, CADDR1, 1)
619
620         /*
621          * Crashdump maps.
622          */
623         SYSMAP(caddr_t, pt_crashdumpmap, crashdumpmap, MAXDUMPPGS);
624
625         /*
626          * ptvmmap is used for reading arbitrary physical pages via
627          * /dev/mem.
628          */
629         SYSMAP(caddr_t, ptmmap, ptvmmap, 1)
630
631         /*
632          * msgbufp is used to map the system message buffer.
633          * XXX msgbufmap is not used.
634          */
635         SYSMAP(struct msgbuf *, msgbufmap, msgbufp,
636                atop(round_page(MSGBUF_SIZE)))
637
638         virtual_start = va;
639
640         *CMAP1 = 0;
641
642         /*
643          * PG_G is terribly broken on SMP because we IPI invltlb's in some
644          * cases rather then invl1pg.  Actually, I don't even know why it
645          * works under UP because self-referential page table mappings
646          */
647 #ifdef SMP
648         pgeflag = 0;
649 #else
650         if (cpu_feature & CPUID_PGE)
651                 pgeflag = PG_G;
652 #endif
653         
654 /*
655  * Initialize the 4MB page size flag
656  */
657         pseflag = 0;
658 /*
659  * The 4MB page version of the initial
660  * kernel page mapping.
661  */
662         pdir4mb = 0;
663
664 #if !defined(DISABLE_PSE)
665         if (cpu_feature & CPUID_PSE) {
666                 pt_entry_t ptditmp;
667                 /*
668                  * Note that we have enabled PSE mode
669                  */
670                 pseflag = PG_PS;
671                 ptditmp = *(PTmap + x86_64_btop(KERNBASE));
672                 ptditmp &= ~(NBPDR - 1);
673                 ptditmp |= PG_V | PG_RW | PG_PS | PG_U | pgeflag;
674                 pdir4mb = ptditmp;
675
676 #ifndef SMP
677                 /*
678                  * Enable the PSE mode.  If we are SMP we can't do this
679                  * now because the APs will not be able to use it when
680                  * they boot up.
681                  */
682                 load_cr4(rcr4() | CR4_PSE);
683
684                 /*
685                  * We can do the mapping here for the single processor
686                  * case.  We simply ignore the old page table page from
687                  * now on.
688                  */
689                 /*
690                  * For SMP, we still need 4K pages to bootstrap APs,
691                  * PSE will be enabled as soon as all APs are up.
692                  */
693                 PTD[KPTDI] = (pd_entry_t)ptditmp;
694                 cpu_invltlb();
695 #endif
696         }
697 #endif
698 #ifdef SMP
699         if (cpu_apic_address == 0)
700                 panic("pmap_bootstrap: no local apic!");
701 #endif
702
703         /*
704          * We need to finish setting up the globaldata page for the BSP.
705          * locore has already populated the page table for the mdglobaldata
706          * portion.
707          */
708         pg = MDGLOBALDATA_BASEALLOC_PAGES;
709         gd = &CPU_prvspace[0].mdglobaldata;
710         gd->gd_CMAP1 = &SMPpt[pg + 0];
711         gd->gd_CMAP2 = &SMPpt[pg + 1];
712         gd->gd_CMAP3 = &SMPpt[pg + 2];
713         gd->gd_PMAP1 = &SMPpt[pg + 3];
714         gd->gd_CADDR1 = CPU_prvspace[0].CPAGE1;
715         gd->gd_CADDR2 = CPU_prvspace[0].CPAGE2;
716         gd->gd_CADDR3 = CPU_prvspace[0].CPAGE3;
717         gd->gd_PADDR1 = (pt_entry_t *)CPU_prvspace[0].PPAGE1;
718
719         cpu_invltlb();
720 }
721
722 #ifdef SMP
723 /*
724  * Set 4mb pdir for mp startup
725  */
726 void
727 pmap_set_opt(void)
728 {
729         if (pseflag && (cpu_feature & CPUID_PSE)) {
730                 load_cr4(rcr4() | CR4_PSE);
731                 if (pdir4mb && mycpu->gd_cpuid == 0) {  /* only on BSP */
732                         cpu_invltlb();
733                 }
734         }
735 }
736 #endif
737
738 /*
739  *      Initialize the pmap module.
740  *      Called by vm_init, to initialize any structures that the pmap
741  *      system needs to map virtual memory.
742  *      pmap_init has been enhanced to support in a fairly consistant
743  *      way, discontiguous physical memory.
744  */
745 void
746 pmap_init(void)
747 {
748         int i;
749         int initial_pvs;
750
751         /*
752          * object for kernel page table pages
753          */
754         /* JG I think the number can be arbitrary */
755         kptobj = vm_object_allocate(OBJT_DEFAULT, 5);
756
757         /*
758          * Allocate memory for random pmap data structures.  Includes the
759          * pv_head_table.
760          */
761
762         for(i = 0; i < vm_page_array_size; i++) {
763                 vm_page_t m;
764
765                 m = &vm_page_array[i];
766                 TAILQ_INIT(&m->md.pv_list);
767                 m->md.pv_list_count = 0;
768         }
769
770         /*
771          * init the pv free list
772          */
773         initial_pvs = vm_page_array_size;
774         if (initial_pvs < MINPV)
775                 initial_pvs = MINPV;
776         pvzone = &pvzone_store;
777         pvinit = (struct pv_entry *) kmem_alloc(&kernel_map,
778                 initial_pvs * sizeof (struct pv_entry));
779         zbootinit(pvzone, "PV ENTRY", sizeof (struct pv_entry), pvinit,
780                 initial_pvs);
781
782         /*
783          * Now it is safe to enable pv_table recording.
784          */
785         pmap_initialized = TRUE;
786 #ifdef SMP
787         lapic = pmap_mapdev_uncacheable(cpu_apic_address, sizeof(struct LAPIC));
788 #endif
789 }
790
791 /*
792  * Initialize the address space (zone) for the pv_entries.  Set a
793  * high water mark so that the system can recover from excessive
794  * numbers of pv entries.
795  */
796 void
797 pmap_init2(void)
798 {
799         int shpgperproc = PMAP_SHPGPERPROC;
800
801         TUNABLE_INT_FETCH("vm.pmap.shpgperproc", &shpgperproc);
802         pv_entry_max = shpgperproc * maxproc + vm_page_array_size;
803         TUNABLE_INT_FETCH("vm.pmap.pv_entries", &pv_entry_max);
804         pv_entry_high_water = 9 * (pv_entry_max / 10);
805         zinitna(pvzone, &pvzone_obj, NULL, 0, pv_entry_max, ZONE_INTERRUPT, 1);
806 }
807
808
809 /***************************************************
810  * Low level helper routines.....
811  ***************************************************/
812
813 #if defined(PMAP_DIAGNOSTIC)
814
815 /*
816  * This code checks for non-writeable/modified pages.
817  * This should be an invalid condition.
818  */
819 static
820 int
821 pmap_nw_modified(pt_entry_t pte)
822 {
823         if ((pte & (PG_M|PG_RW)) == PG_M)
824                 return 1;
825         else
826                 return 0;
827 }
828 #endif
829
830
831 /*
832  * this routine defines the region(s) of memory that should
833  * not be tested for the modified bit.
834  */
835 static __inline
836 int
837 pmap_track_modified(vm_offset_t va)
838 {
839         if ((va < clean_sva) || (va >= clean_eva)) 
840                 return 1;
841         else
842                 return 0;
843 }
844
845 /*
846  * pmap_extract:
847  *
848  *      Extract the physical page address associated with the map/VA pair.
849  *
850  *      This function may not be called from an interrupt if the pmap is
851  *      not kernel_pmap.
852  */
853 vm_paddr_t 
854 pmap_extract(pmap_t pmap, vm_offset_t va)
855 {
856         vm_paddr_t rtval;
857         pt_entry_t *pte;
858         pd_entry_t pde, *pdep;
859
860         rtval = 0;
861         pdep = pmap_pde(pmap, va);
862         if (pdep != NULL) {
863                 pde = *pdep;
864                 if (pde) {
865                         if ((pde & PG_PS) != 0) {
866                                 rtval = (pde & PG_PS_FRAME) | (va & PDRMASK);
867                         } else {
868                                 pte = pmap_pde_to_pte(pdep, va);
869                                 rtval = (*pte & PG_FRAME) | (va & PAGE_MASK);
870                         }
871                 }
872         }
873         return rtval;
874 }
875
876 /*
877  *      Routine:        pmap_kextract
878  *      Function:
879  *              Extract the physical page address associated
880  *              kernel virtual address.
881  */
882 vm_paddr_t
883 pmap_kextract(vm_offset_t va)
884 {
885         pd_entry_t pde;
886         vm_paddr_t pa;
887
888         if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
889                 pa = DMAP_TO_PHYS(va);
890         } else {
891                 pde = *vtopde(va);
892                 if (pde & PG_PS) {
893                         pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
894                 } else {
895                         /*
896                          * Beware of a concurrent promotion that changes the
897                          * PDE at this point!  For example, vtopte() must not
898                          * be used to access the PTE because it would use the
899                          * new PDE.  It is, however, safe to use the old PDE
900                          * because the page table page is preserved by the
901                          * promotion.
902                          */
903                         pa = *pmap_pde_to_pte(&pde, va);
904                         pa = (pa & PG_FRAME) | (va & PAGE_MASK);
905                 }
906         }
907         return pa;
908 }
909
910 /***************************************************
911  * Low level mapping routines.....
912  ***************************************************/
913
914 /*
915  * Routine: pmap_kenter
916  * Function:
917  *      Add a wired page to the KVA
918  *      NOTE! note that in order for the mapping to take effect -- you
919  *      should do an invltlb after doing the pmap_kenter().
920  */
921 void 
922 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
923 {
924         pt_entry_t *pte;
925         pt_entry_t npte;
926         pmap_inval_info info;
927
928         pmap_inval_init(&info);
929         npte = pa | PG_RW | PG_V | pgeflag;
930         pte = vtopte(va);
931         pmap_inval_add(&info, &kernel_pmap, va);
932         *pte = npte;
933         pmap_inval_flush(&info);
934 }
935
936 /*
937  * Routine: pmap_kenter_quick
938  * Function:
939  *      Similar to pmap_kenter(), except we only invalidate the
940  *      mapping on the current CPU.
941  */
942 void
943 pmap_kenter_quick(vm_offset_t va, vm_paddr_t pa)
944 {
945         pt_entry_t *pte;
946         pt_entry_t npte;
947
948         npte = pa | PG_RW | PG_V | pgeflag;
949         pte = vtopte(va);
950         *pte = npte;
951         cpu_invlpg((void *)va);
952 }
953
954 void
955 pmap_kenter_sync(vm_offset_t va)
956 {
957         pmap_inval_info info;
958
959         pmap_inval_init(&info);
960         pmap_inval_add(&info, &kernel_pmap, va);
961         pmap_inval_flush(&info);
962 }
963
964 void
965 pmap_kenter_sync_quick(vm_offset_t va)
966 {
967         cpu_invlpg((void *)va);
968 }
969
970 /*
971  * remove a page from the kernel pagetables
972  */
973 void
974 pmap_kremove(vm_offset_t va)
975 {
976         pt_entry_t *pte;
977         pmap_inval_info info;
978
979         pmap_inval_init(&info);
980         pte = vtopte(va);
981         pmap_inval_add(&info, &kernel_pmap, va);
982         *pte = 0;
983         pmap_inval_flush(&info);
984 }
985
986 void
987 pmap_kremove_quick(vm_offset_t va)
988 {
989         pt_entry_t *pte;
990         pte = vtopte(va);
991         *pte = 0;
992         cpu_invlpg((void *)va);
993 }
994
995 /*
996  * XXX these need to be recoded.  They are not used in any critical path.
997  */
998 void
999 pmap_kmodify_rw(vm_offset_t va)
1000 {
1001         *vtopte(va) |= PG_RW;
1002         cpu_invlpg((void *)va);
1003 }
1004
1005 void
1006 pmap_kmodify_nc(vm_offset_t va)
1007 {
1008         *vtopte(va) |= PG_N;
1009         cpu_invlpg((void *)va);
1010 }
1011
1012 /*
1013  *      Used to map a range of physical addresses into kernel
1014  *      virtual address space.
1015  *
1016  *      For now, VM is already on, we only need to map the
1017  *      specified memory.
1018  */
1019 vm_offset_t
1020 pmap_map(vm_offset_t *virtp, vm_paddr_t start, vm_paddr_t end, int prot)
1021 {
1022         return PHYS_TO_DMAP(start);
1023 }
1024
1025
1026 /*
1027  * Add a list of wired pages to the kva
1028  * this routine is only used for temporary
1029  * kernel mappings that do not need to have
1030  * page modification or references recorded.
1031  * Note that old mappings are simply written
1032  * over.  The page *must* be wired.
1033  */
1034 void
1035 pmap_qenter(vm_offset_t va, vm_page_t *m, int count)
1036 {
1037         vm_offset_t end_va;
1038
1039         end_va = va + count * PAGE_SIZE;
1040                 
1041         while (va < end_va) {
1042                 pt_entry_t *pte;
1043
1044                 pte = vtopte(va);
1045                 *pte = VM_PAGE_TO_PHYS(*m) | PG_RW | PG_V | pgeflag;
1046                 cpu_invlpg((void *)va);
1047                 va += PAGE_SIZE;
1048                 m++;
1049         }
1050 #ifdef SMP
1051         smp_invltlb();  /* XXX */
1052 #endif
1053 }
1054
1055 void
1056 pmap_qenter2(vm_offset_t va, vm_page_t *m, int count, cpumask_t *mask)
1057 {
1058         vm_offset_t end_va;
1059         cpumask_t cmask = mycpu->gd_cpumask;
1060
1061         end_va = va + count * PAGE_SIZE;
1062
1063         while (va < end_va) {
1064                 pt_entry_t *pte;
1065                 pt_entry_t pteval;
1066
1067                 /*
1068                  * Install the new PTE.  If the pte changed from the prior
1069                  * mapping we must reset the cpu mask and invalidate the page.
1070                  * If the pte is the same but we have not seen it on the
1071                  * current cpu, invlpg the existing mapping.  Otherwise the
1072                  * entry is optimal and no invalidation is required.
1073                  */
1074                 pte = vtopte(va);
1075                 pteval = VM_PAGE_TO_PHYS(*m) | PG_A | PG_RW | PG_V | pgeflag;
1076                 if (*pte != pteval) {
1077                         *mask = 0;
1078                         *pte = pteval;
1079                         cpu_invlpg((void *)va);
1080                 } else if ((*mask & cmask) == 0) {
1081                         cpu_invlpg((void *)va);
1082                 }
1083                 va += PAGE_SIZE;
1084                 m++;
1085         }
1086         *mask |= cmask;
1087 }
1088
1089 /*
1090  * This routine jerks page mappings from the
1091  * kernel -- it is meant only for temporary mappings.
1092  *
1093  * MPSAFE, INTERRUPT SAFE (cluster callback)
1094  */
1095 void
1096 pmap_qremove(vm_offset_t va, int count)
1097 {
1098         vm_offset_t end_va;
1099
1100         end_va = va + count * PAGE_SIZE;
1101
1102         while (va < end_va) {
1103                 pt_entry_t *pte;
1104
1105                 pte = vtopte(va);
1106                 *pte = 0;
1107                 cpu_invlpg((void *)va);
1108                 va += PAGE_SIZE;
1109         }
1110 #ifdef SMP
1111         smp_invltlb();
1112 #endif
1113 }
1114
1115 /*
1116  * This routine works like vm_page_lookup() but also blocks as long as the
1117  * page is busy.  This routine does not busy the page it returns.
1118  *
1119  * Unless the caller is managing objects whos pages are in a known state,
1120  * the call should be made with a critical section held so the page's object
1121  * association remains valid on return.
1122  */
1123 static
1124 vm_page_t
1125 pmap_page_lookup(vm_object_t object, vm_pindex_t pindex)
1126 {
1127         vm_page_t m;
1128
1129         do {
1130                 m = vm_page_lookup(object, pindex);
1131         } while (m && vm_page_sleep_busy(m, FALSE, "pplookp"));
1132
1133         return(m);
1134 }
1135
1136 /*
1137  * Create a new thread and optionally associate it with a (new) process.
1138  * NOTE! the new thread's cpu may not equal the current cpu.
1139  */
1140 void
1141 pmap_init_thread(thread_t td)
1142 {
1143         /* enforce pcb placement */
1144         td->td_pcb = (struct pcb *)(td->td_kstack + td->td_kstack_size) - 1;
1145         td->td_savefpu = &td->td_pcb->pcb_save;
1146         td->td_sp = (char *)td->td_pcb - 16; /* JG is -16 needed on x86_64? */
1147 }
1148
1149 /*
1150  * This routine directly affects the fork perf for a process.
1151  */
1152 void
1153 pmap_init_proc(struct proc *p)
1154 {
1155 }
1156
1157 /*
1158  * Dispose the UPAGES for a process that has exited.
1159  * This routine directly impacts the exit perf of a process.
1160  */
1161 void
1162 pmap_dispose_proc(struct proc *p)
1163 {
1164         KASSERT(p->p_lock == 0, ("attempt to dispose referenced proc! %p", p));
1165 }
1166
1167 /***************************************************
1168  * Page table page management routines.....
1169  ***************************************************/
1170
1171 /*
1172  * This routine unholds page table pages, and if the hold count
1173  * drops to zero, then it decrements the wire count.
1174  */
1175 static __inline
1176 int
1177 pmap_unwire_pte_hold(pmap_t pmap, vm_offset_t va, vm_page_t m,
1178                      pmap_inval_info_t info)
1179 {
1180         KKASSERT(m->hold_count > 0);
1181         if (m->hold_count > 1) {
1182                 vm_page_unhold(m);
1183                 return 0;
1184         } else {
1185                 return _pmap_unwire_pte_hold(pmap, va, m, info);
1186         }
1187 }
1188
1189 static
1190 int
1191 _pmap_unwire_pte_hold(pmap_t pmap, vm_offset_t va, vm_page_t m,
1192                       pmap_inval_info_t info)
1193 {
1194         /* 
1195          * Wait until we can busy the page ourselves.  We cannot have
1196          * any active flushes if we block.  We own one hold count on the
1197          * page so it cannot be freed out from under us.
1198          */
1199         if (m->flags & PG_BUSY) {
1200                 pmap_inval_flush(info);
1201                 while (vm_page_sleep_busy(m, FALSE, "pmuwpt"))
1202                         ;
1203         }
1204         KASSERT(m->queue == PQ_NONE,
1205                 ("_pmap_unwire_pte_hold: %p->queue != PQ_NONE", m));
1206
1207         /*
1208          * This case can occur if new references were acquired while
1209          * we were blocked.
1210          */
1211         if (m->hold_count > 1) {
1212                 KKASSERT(m->hold_count > 1);
1213                 vm_page_unhold(m);
1214                 return 0;
1215         }
1216
1217         /*
1218          * Unmap the page table page
1219          */
1220         KKASSERT(m->hold_count == 1);
1221         vm_page_busy(m);
1222         pmap_inval_add(info, pmap, -1);
1223
1224         if (m->pindex >= (NUPDE + NUPDPE)) {
1225                 /* PDP page */
1226                 pml4_entry_t *pml4;
1227                 pml4 = pmap_pml4e(pmap, va);
1228                 *pml4 = 0;
1229         } else if (m->pindex >= NUPDE) {
1230                 /* PD page */
1231                 pdp_entry_t *pdp;
1232                 pdp = pmap_pdpe(pmap, va);
1233                 *pdp = 0;
1234         } else {
1235                 /* PT page */
1236                 pd_entry_t *pd;
1237                 pd = pmap_pde(pmap, va);
1238                 *pd = 0;
1239         }
1240
1241         KKASSERT(pmap->pm_stats.resident_count > 0);
1242         --pmap->pm_stats.resident_count;
1243
1244         if (pmap->pm_ptphint == m)
1245                 pmap->pm_ptphint = NULL;
1246
1247         if (m->pindex < NUPDE) {
1248                 /* We just released a PT, unhold the matching PD */
1249                 vm_page_t pdpg;
1250
1251                 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
1252                 pmap_unwire_pte_hold(pmap, va, pdpg, info);
1253         }
1254         if (m->pindex >= NUPDE && m->pindex < (NUPDE + NUPDPE)) {
1255                 /* We just released a PD, unhold the matching PDP */
1256                 vm_page_t pdppg;
1257
1258                 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
1259                 pmap_unwire_pte_hold(pmap, va, pdppg, info);
1260         }
1261
1262         /*
1263          * This was our last hold, the page had better be unwired
1264          * after we decrement wire_count.
1265          *
1266          * FUTURE NOTE: shared page directory page could result in
1267          * multiple wire counts.
1268          */
1269         vm_page_unhold(m);
1270         --m->wire_count;
1271         KKASSERT(m->wire_count == 0);
1272         --vmstats.v_wire_count;
1273         vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
1274         vm_page_flash(m);
1275         vm_page_free_zero(m);
1276
1277         return 1;
1278 }
1279
1280 /*
1281  * After removing a page table entry, this routine is used to
1282  * conditionally free the page, and manage the hold/wire counts.
1283  */
1284 static
1285 int
1286 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, vm_page_t mpte,
1287                 pmap_inval_info_t info)
1288 {
1289         vm_pindex_t ptepindex;
1290
1291         if (va >= VM_MAX_USER_ADDRESS)
1292                 return 0;
1293
1294         if (mpte == NULL) {
1295                 ptepindex = pmap_pde_pindex(va);
1296 #if JGHINT
1297                 if (pmap->pm_ptphint &&
1298                         (pmap->pm_ptphint->pindex == ptepindex)) {
1299                         mpte = pmap->pm_ptphint;
1300                 } else {
1301 #endif
1302                         pmap_inval_flush(info);
1303                         mpte = pmap_page_lookup(pmap->pm_pteobj, ptepindex);
1304                         pmap->pm_ptphint = mpte;
1305 #if JGHINT
1306                 }
1307 #endif
1308         }
1309         return pmap_unwire_pte_hold(pmap, va, mpte, info);
1310 }
1311
1312 /*
1313  * Initialize pmap0/vmspace0.  This pmap is not added to pmap_list because
1314  * it, and IdlePTD, represents the template used to update all other pmaps.
1315  *
1316  * On architectures where the kernel pmap is not integrated into the user
1317  * process pmap, this pmap represents the process pmap, not the kernel pmap.
1318  * kernel_pmap should be used to directly access the kernel_pmap.
1319  */
1320 void
1321 pmap_pinit0(struct pmap *pmap)
1322 {
1323         pmap->pm_pml4 = (pml4_entry_t *)(PTOV_OFFSET + KPML4phys);
1324         pmap->pm_count = 1;
1325         pmap->pm_active = 0;
1326         pmap->pm_ptphint = NULL;
1327         TAILQ_INIT(&pmap->pm_pvlist);
1328         bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
1329 }
1330
1331 /*
1332  * Initialize a preallocated and zeroed pmap structure,
1333  * such as one in a vmspace structure.
1334  */
1335 void
1336 pmap_pinit(struct pmap *pmap)
1337 {
1338         vm_page_t ptdpg;
1339
1340         /*
1341          * No need to allocate page table space yet but we do need a valid
1342          * page directory table.
1343          */
1344         if (pmap->pm_pml4 == NULL) {
1345                 pmap->pm_pml4 =
1346                     (pml4_entry_t *)kmem_alloc_pageable(&kernel_map, PAGE_SIZE);
1347         }
1348
1349         /*
1350          * Allocate an object for the ptes
1351          */
1352         if (pmap->pm_pteobj == NULL)
1353                 pmap->pm_pteobj = vm_object_allocate(OBJT_DEFAULT, NUPDE + NUPDPE + PML4PML4I + 1);
1354
1355         /*
1356          * Allocate the page directory page, unless we already have
1357          * one cached.  If we used the cached page the wire_count will
1358          * already be set appropriately.
1359          */
1360         if ((ptdpg = pmap->pm_pdirm) == NULL) {
1361                 ptdpg = vm_page_grab(pmap->pm_pteobj, NUPDE + NUPDPE + PML4PML4I,
1362                                      VM_ALLOC_NORMAL | VM_ALLOC_RETRY);
1363                 pmap->pm_pdirm = ptdpg;
1364                 vm_page_flag_clear(ptdpg, PG_MAPPED | PG_BUSY);
1365                 ptdpg->valid = VM_PAGE_BITS_ALL;
1366                 if (ptdpg->wire_count == 0)
1367                         ++vmstats.v_wire_count;
1368                 ptdpg->wire_count = 1;
1369                 pmap_kenter((vm_offset_t)pmap->pm_pml4, VM_PAGE_TO_PHYS(ptdpg));
1370         }
1371         if ((ptdpg->flags & PG_ZERO) == 0)
1372                 bzero(pmap->pm_pml4, PAGE_SIZE);
1373
1374         pmap->pm_pml4[KPML4I] = KPDPphys | PG_RW | PG_V | PG_U;
1375         pmap->pm_pml4[DMPML4I] = DMPDPphys | PG_RW | PG_V | PG_U;
1376
1377         /* install self-referential address mapping entry */
1378         pmap->pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(ptdpg) | PG_V | PG_RW | PG_A | PG_M;
1379
1380         pmap->pm_count = 1;
1381         pmap->pm_active = 0;
1382         pmap->pm_ptphint = NULL;
1383         TAILQ_INIT(&pmap->pm_pvlist);
1384         bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
1385         pmap->pm_stats.resident_count = 1;
1386 }
1387
1388 /*
1389  * Clean up a pmap structure so it can be physically freed.  This routine
1390  * is called by the vmspace dtor function.  A great deal of pmap data is
1391  * left passively mapped to improve vmspace management so we have a bit
1392  * of cleanup work to do here.
1393  */
1394 void
1395 pmap_puninit(pmap_t pmap)
1396 {
1397         vm_page_t p;
1398
1399         KKASSERT(pmap->pm_active == 0);
1400         if ((p = pmap->pm_pdirm) != NULL) {
1401                 KKASSERT(pmap->pm_pml4 != NULL);
1402                 KKASSERT(pmap->pm_pml4 != (void *)(PTOV_OFFSET + KPML4phys));
1403                 pmap_kremove((vm_offset_t)pmap->pm_pml4);
1404                 p->wire_count--;
1405                 vmstats.v_wire_count--;
1406                 KKASSERT((p->flags & PG_BUSY) == 0);
1407                 vm_page_busy(p);
1408                 vm_page_free_zero(p);
1409                 pmap->pm_pdirm = NULL;
1410         }
1411         if (pmap->pm_pml4) {
1412                 KKASSERT(pmap->pm_pml4 != (void *)(PTOV_OFFSET + KPML4phys));
1413                 kmem_free(&kernel_map, (vm_offset_t)pmap->pm_pml4, PAGE_SIZE);
1414                 pmap->pm_pml4 = NULL;
1415         }
1416         if (pmap->pm_pteobj) {
1417                 vm_object_deallocate(pmap->pm_pteobj);
1418                 pmap->pm_pteobj = NULL;
1419         }
1420 }
1421
1422 /*
1423  * Wire in kernel global address entries.  To avoid a race condition
1424  * between pmap initialization and pmap_growkernel, this procedure
1425  * adds the pmap to the master list (which growkernel scans to update),
1426  * then copies the template.
1427  */
1428 void
1429 pmap_pinit2(struct pmap *pmap)
1430 {
1431         crit_enter();
1432         TAILQ_INSERT_TAIL(&pmap_list, pmap, pm_pmnode);
1433         /* XXX copies current process, does not fill in MPPTDI */
1434         crit_exit();
1435 }
1436
1437 /*
1438  * Attempt to release and free a vm_page in a pmap.  Returns 1 on success,
1439  * 0 on failure (if the procedure had to sleep).
1440  *
1441  * When asked to remove the page directory page itself, we actually just
1442  * leave it cached so we do not have to incur the SMP inval overhead of
1443  * removing the kernel mapping.  pmap_puninit() will take care of it.
1444  */
1445 static
1446 int
1447 pmap_release_free_page(struct pmap *pmap, vm_page_t p)
1448 {
1449         /*
1450          * This code optimizes the case of freeing non-busy
1451          * page-table pages.  Those pages are zero now, and
1452          * might as well be placed directly into the zero queue.
1453          */
1454         if (vm_page_sleep_busy(p, FALSE, "pmaprl"))
1455                 return 0;
1456
1457         vm_page_busy(p);
1458
1459         /*
1460          * Remove the page table page from the processes address space.
1461          */
1462         if (p->pindex == NUPDE + NUPDPE + PML4PML4I) {
1463                 /*
1464                  * We are the pml4 table itself.
1465                  */
1466                 /* XXX anything to do here? */
1467         } else if (p->pindex >= (NUPDE + NUPDPE)) {
1468                 /*
1469                  * Remove a PDP page from the PML4.  We do not maintain
1470                  * hold counts on the PML4 page.
1471                  */
1472                 pml4_entry_t *pml4;
1473                 vm_page_t m4;
1474                 int idx;
1475
1476                 m4 = vm_page_lookup(pmap->pm_pteobj, NUPDE + NUPDPE + PML4PML4I);
1477                 KKASSERT(m4 != NULL);
1478                 pml4 = (void *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m4));
1479                 idx = (p->pindex - (NUPDE + NUPDPE)) % NPML4EPG;
1480                 KKASSERT(pml4[idx] != 0);
1481                 pml4[idx] = 0;
1482         } else if (p->pindex >= NUPDE) {
1483                 /*
1484                  * Remove a PD page from the PDP and drop the hold count
1485                  * on the PDP.  The PDP is left cached in the pmap if
1486                  * the hold count drops to 0 so the wire count remains
1487                  * intact.
1488                  */
1489                 vm_page_t m3;
1490                 pdp_entry_t *pdp;
1491                 int idx;
1492
1493                 m3 = vm_page_lookup(pmap->pm_pteobj,
1494                                 NUPDE + NUPDPE + (p->pindex - NUPDE) / NPDPEPG);
1495                 KKASSERT(m3 != NULL);
1496                 pdp = (void *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m3));
1497                 idx = (p->pindex - NUPDE) % NPDPEPG;
1498                 KKASSERT(pdp[idx] != 0);
1499                 pdp[idx] = 0;
1500                 m3->hold_count--;
1501         } else {
1502                 /*
1503                  * Remove a PT page from the PD and drop the hold count
1504                  * on the PD.  The PD is left cached in the pmap if
1505                  * the hold count drops to 0 so the wire count remains
1506                  * intact.
1507                  */
1508                 vm_page_t m2;
1509                 pd_entry_t *pd;
1510                 int idx;
1511
1512                 m2 = vm_page_lookup(pmap->pm_pteobj,
1513                                     NUPDE + p->pindex / NPDEPG);
1514                 KKASSERT(m2 != NULL);
1515                 pd = (void *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m2));
1516                 idx = p->pindex % NPDEPG;
1517                 pd[idx] = 0;
1518                 m2->hold_count--;
1519         }
1520
1521         /*
1522          * One fewer mappings in the pmap.  p's hold count had better
1523          * be zero.
1524          */
1525         KKASSERT(pmap->pm_stats.resident_count > 0);
1526         --pmap->pm_stats.resident_count;
1527         if (p->hold_count)
1528                 panic("pmap_release: freeing held page table page");
1529         if (pmap->pm_ptphint && (pmap->pm_ptphint->pindex == p->pindex))
1530                 pmap->pm_ptphint = NULL;
1531
1532         /*
1533          * We leave the top-level page table page cached, wired, and mapped in
1534          * the pmap until the dtor function (pmap_puninit()) gets called.
1535          * However, still clean it up so we can set PG_ZERO.
1536          */
1537         if (p->pindex == NUPDE + NUPDPE + PML4PML4I) {
1538                 bzero(pmap->pm_pml4, PAGE_SIZE);
1539                 vm_page_flag_set(p, PG_ZERO);
1540                 vm_page_wakeup(p);
1541         } else {
1542                 p->wire_count--;
1543                 KKASSERT(p->wire_count == 0);
1544                 vmstats.v_wire_count--;
1545                 /* JG eventually revert to using vm_page_free_zero() */
1546                 vm_page_free(p);
1547         }
1548         return 1;
1549 }
1550
1551 /*
1552  * This routine is called when various levels in the page table need to
1553  * be populated.  This routine cannot fail.
1554  */
1555 static
1556 vm_page_t
1557 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex)
1558 {
1559         vm_page_t m;
1560
1561         /*
1562          * Find or fabricate a new pagetable page.  This will busy the page.
1563          */
1564         m = vm_page_grab(pmap->pm_pteobj, ptepindex,
1565                          VM_ALLOC_NORMAL | VM_ALLOC_ZERO | VM_ALLOC_RETRY);
1566         if ((m->flags & PG_ZERO) == 0) {
1567                 pmap_zero_page(VM_PAGE_TO_PHYS(m));
1568         }
1569
1570         KASSERT(m->queue == PQ_NONE,
1571                 ("_pmap_allocpte: %p->queue != PQ_NONE", m));
1572
1573         /*
1574          * Increment the hold count for the page we will be returning to
1575          * the caller.
1576          */
1577         m->hold_count++;
1578         if (m->wire_count++ == 0)
1579                 vmstats.v_wire_count++;
1580
1581         /*
1582          * Map the pagetable page into the process address space, if
1583          * it isn't already there.
1584          *
1585          * It is possible that someone else got in and mapped the page
1586          * directory page while we were blocked, if so just unbusy and
1587          * return the held page.
1588          */
1589         if (ptepindex >= (NUPDE + NUPDPE)) {
1590                 /*
1591                  * Wire up a new PDP page in the PML4
1592                  */
1593                 vm_pindex_t pml4index;
1594                 pml4_entry_t *pml4;
1595
1596                 pml4index = ptepindex - (NUPDE + NUPDPE);
1597                 pml4 = &pmap->pm_pml4[pml4index];
1598                 if (*pml4 & PG_V) {
1599                         if (--m->wire_count == 0)
1600                                 --vmstats.v_wire_count;
1601                         vm_page_wakeup(m);
1602                         return(m);
1603                 }
1604                 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
1605         } else if (ptepindex >= NUPDE) {
1606                 /*
1607                  * Wire up a new PD page in the PDP
1608                  */
1609                 vm_pindex_t pml4index;
1610                 vm_pindex_t pdpindex;
1611                 vm_page_t pdppg;
1612                 pml4_entry_t *pml4;
1613                 pdp_entry_t *pdp;
1614
1615                 pdpindex = ptepindex - NUPDE;
1616                 pml4index = pdpindex >> NPML4EPGSHIFT;
1617
1618                 pml4 = &pmap->pm_pml4[pml4index];
1619                 if ((*pml4 & PG_V) == 0) {
1620                         /*
1621                          * Have to allocate a new PDP page, recurse.
1622                          * This always succeeds.  Returned page will
1623                          * be held.
1624                          */
1625                         pdppg = _pmap_allocpte(pmap,
1626                                                NUPDE + NUPDPE + pml4index);
1627                 } else {
1628                         /*
1629                          * Add a held reference to the PDP page.
1630                          */
1631                         pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
1632                         pdppg->hold_count++;
1633                 }
1634
1635                 /*
1636                  * Now find the pdp_entry and map the PDP.  If the PDP
1637                  * has already been mapped unwind and return the
1638                  * already-mapped PDP held.
1639                  *
1640                  * pdppg is left held (hold_count is incremented for
1641                  * each PD in the PDP).
1642                  */
1643                 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
1644                 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
1645                 if (*pdp & PG_V) {
1646                         vm_page_unhold(pdppg);
1647                         if (--m->wire_count == 0)
1648                                 --vmstats.v_wire_count;
1649                         vm_page_wakeup(m);
1650                         return(m);
1651                 }
1652                 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
1653         } else {
1654                 /*
1655                  * Wire up the new PT page in the PD
1656                  */
1657                 vm_pindex_t pml4index;
1658                 vm_pindex_t pdpindex;
1659                 pml4_entry_t *pml4;
1660                 pdp_entry_t *pdp;
1661                 pd_entry_t *pd;
1662                 vm_page_t pdpg;
1663
1664                 pdpindex = ptepindex >> NPDPEPGSHIFT;
1665                 pml4index = pdpindex >> NPML4EPGSHIFT;
1666
1667                 /*
1668                  * Locate the PDP page in the PML4, then the PD page in
1669                  * the PDP.  If either does not exist we simply recurse
1670                  * to allocate them.
1671                  *
1672                  * We can just recurse on the PD page as it will recurse
1673                  * on the PDP if necessary.
1674                  */
1675                 pml4 = &pmap->pm_pml4[pml4index];
1676                 if ((*pml4 & PG_V) == 0) {
1677                         pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex);
1678                         pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
1679                         pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
1680                 } else {
1681                         pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
1682                         pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
1683                         if ((*pdp & PG_V) == 0) {
1684                                 pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex);
1685                         } else {
1686                                 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
1687                                 pdpg->hold_count++;
1688                         }
1689                 }
1690
1691                 /*
1692                  * Now fill in the pte in the PD.  If the pte already exists
1693                  * (again, if we raced the grab), unhold pdpg and unwire
1694                  * m, returning a held m.
1695                  *
1696                  * pdpg is left held (hold_count is incremented for
1697                  * each PT in the PD).
1698                  */
1699                 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
1700                 pd = &pd[ptepindex & ((1ul << NPDEPGSHIFT) - 1)];
1701                 if (*pd != 0) {
1702                         vm_page_unhold(pdpg);
1703                         if (--m->wire_count == 0)
1704                                 --vmstats.v_wire_count;
1705                         vm_page_wakeup(m);
1706                         return(m);
1707                 }
1708                 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
1709         }
1710
1711         /*
1712          * We successfully loaded a PDP, PD, or PTE.  Set the page table hint,
1713          * valid bits, mapped flag, unbusy, and we're done.
1714          */
1715         pmap->pm_ptphint = m;
1716         ++pmap->pm_stats.resident_count;
1717
1718         m->valid = VM_PAGE_BITS_ALL;
1719         vm_page_flag_clear(m, PG_ZERO);
1720         vm_page_flag_set(m, PG_MAPPED);
1721         vm_page_wakeup(m);
1722
1723         return (m);
1724 }
1725
1726 static
1727 vm_page_t
1728 pmap_allocpte(pmap_t pmap, vm_offset_t va)
1729 {
1730         vm_pindex_t ptepindex;
1731         pd_entry_t *pd;
1732         vm_page_t m;
1733
1734         /*
1735          * Calculate pagetable page index
1736          */
1737         ptepindex = pmap_pde_pindex(va);
1738
1739         /*
1740          * Get the page directory entry
1741          */
1742         pd = pmap_pde(pmap, va);
1743
1744         /*
1745          * This supports switching from a 2MB page to a
1746          * normal 4K page.
1747          */
1748         if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
1749                 panic("no promotion/demotion yet");
1750                 *pd = 0;
1751                 pd = NULL;
1752                 cpu_invltlb();
1753                 smp_invltlb();
1754         }
1755
1756         /*
1757          * If the page table page is mapped, we just increment the
1758          * hold count, and activate it.
1759          */
1760         if (pd != NULL && (*pd & PG_V) != 0) {
1761                 /* YYY hint is used here on i386 */
1762                 m = pmap_page_lookup( pmap->pm_pteobj, ptepindex);
1763                 pmap->pm_ptphint = m;
1764                 m->hold_count++;
1765                 return m;
1766         }
1767         /*
1768          * Here if the pte page isn't mapped, or if it has been deallocated.
1769          */
1770         return _pmap_allocpte(pmap, ptepindex);
1771 }
1772
1773
1774 /***************************************************
1775  * Pmap allocation/deallocation routines.
1776  ***************************************************/
1777
1778 /*
1779  * Release any resources held by the given physical map.
1780  * Called when a pmap initialized by pmap_pinit is being released.
1781  * Should only be called if the map contains no valid mappings.
1782  */
1783 static int pmap_release_callback(struct vm_page *p, void *data);
1784
1785 void
1786 pmap_release(struct pmap *pmap)
1787 {
1788         vm_object_t object = pmap->pm_pteobj;
1789         struct rb_vm_page_scan_info info;
1790
1791         KASSERT(pmap->pm_active == 0, ("pmap still active! %08x", pmap->pm_active));
1792 #if defined(DIAGNOSTIC)
1793         if (object->ref_count != 1)
1794                 panic("pmap_release: pteobj reference count != 1");
1795 #endif
1796         
1797         info.pmap = pmap;
1798         info.object = object;
1799         crit_enter();
1800         TAILQ_REMOVE(&pmap_list, pmap, pm_pmnode);
1801         crit_exit();
1802
1803         do {
1804                 crit_enter();
1805                 info.error = 0;
1806                 info.mpte = NULL;
1807                 info.limit = object->generation;
1808
1809                 vm_page_rb_tree_RB_SCAN(&object->rb_memq, NULL, 
1810                                         pmap_release_callback, &info);
1811                 if (info.error == 0 && info.mpte) {
1812                         if (!pmap_release_free_page(pmap, info.mpte))
1813                                 info.error = 1;
1814                 }
1815                 crit_exit();
1816         } while (info.error);
1817 }
1818
1819 static
1820 int
1821 pmap_release_callback(struct vm_page *p, void *data)
1822 {
1823         struct rb_vm_page_scan_info *info = data;
1824
1825         if (p->pindex == NUPDE + NUPDPE + PML4PML4I) {
1826                 info->mpte = p;
1827                 return(0);
1828         }
1829         if (!pmap_release_free_page(info->pmap, p)) {
1830                 info->error = 1;
1831                 return(-1);
1832         }
1833         if (info->object->generation != info->limit) {
1834                 info->error = 1;
1835                 return(-1);
1836         }
1837         return(0);
1838 }
1839
1840 /*
1841  * Grow the number of kernel page table entries, if needed.
1842  */
1843 void
1844 pmap_growkernel(vm_offset_t addr)
1845 {
1846         vm_paddr_t paddr;
1847         vm_offset_t ptppaddr;
1848         vm_page_t nkpg;
1849         pd_entry_t *pde, newpdir;
1850         pdp_entry_t newpdp;
1851
1852         crit_enter();
1853         if (kernel_vm_end == 0) {
1854                 kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
1855                 nkpt = 0;
1856                 while ((*pmap_pde(&kernel_pmap, kernel_vm_end) & PG_V) != 0) {
1857                         kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) & ~(PAGE_SIZE * NPTEPG - 1);
1858                         nkpt++;
1859                         if (kernel_vm_end - 1 >= kernel_map.max_offset) {
1860                                 kernel_vm_end = kernel_map.max_offset;
1861                                 break;                       
1862                         }
1863                 }
1864         }
1865         addr = roundup2(addr, PAGE_SIZE * NPTEPG);
1866         if (addr - 1 >= kernel_map.max_offset)
1867                 addr = kernel_map.max_offset;
1868         while (kernel_vm_end < addr) {
1869                 pde = pmap_pde(&kernel_pmap, kernel_vm_end);
1870                 if (pde == NULL) {
1871                         /* We need a new PDP entry */
1872                         nkpg = vm_page_alloc(kptobj, nkpt,
1873                                              VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM
1874                                              | VM_ALLOC_INTERRUPT);
1875                         if (nkpg == NULL)
1876                                 panic("pmap_growkernel: no memory to grow kernel");
1877                         paddr = VM_PAGE_TO_PHYS(nkpg);
1878                         if ((nkpg->flags & PG_ZERO) == 0)
1879                                 pmap_zero_page(paddr);
1880                         vm_page_flag_clear(nkpg, PG_ZERO);
1881                         newpdp = (pdp_entry_t)
1882                                 (paddr | PG_V | PG_RW | PG_A | PG_M);
1883                         *pmap_pdpe(&kernel_pmap, kernel_vm_end) = newpdp;
1884                         nkpt++;
1885                         continue; /* try again */
1886                 }
1887                 if ((*pde & PG_V) != 0) {
1888                         kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) & ~(PAGE_SIZE * NPTEPG - 1);
1889                         if (kernel_vm_end - 1 >= kernel_map.max_offset) {
1890                                 kernel_vm_end = kernel_map.max_offset;
1891                                 break;                       
1892                         }
1893                         continue;
1894                 }
1895
1896                 /*
1897                  * This index is bogus, but out of the way
1898                  */
1899                 nkpg = vm_page_alloc(kptobj, nkpt,
1900                         VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM | VM_ALLOC_INTERRUPT);
1901                 if (nkpg == NULL)
1902                         panic("pmap_growkernel: no memory to grow kernel");
1903
1904                 vm_page_wire(nkpg);
1905                 ptppaddr = VM_PAGE_TO_PHYS(nkpg);
1906                 pmap_zero_page(ptppaddr);
1907                 vm_page_flag_clear(nkpg, PG_ZERO);
1908                 newpdir = (pd_entry_t) (ptppaddr | PG_V | PG_RW | PG_A | PG_M);
1909                 *pmap_pde(&kernel_pmap, kernel_vm_end) = newpdir;
1910                 nkpt++;
1911
1912                 kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) & ~(PAGE_SIZE * NPTEPG - 1);
1913                 if (kernel_vm_end - 1 >= kernel_map.max_offset) {
1914                         kernel_vm_end = kernel_map.max_offset;
1915                         break;                       
1916                 }
1917         }
1918         crit_exit();
1919 }
1920
1921 /*
1922  *      Retire the given physical map from service.
1923  *      Should only be called if the map contains
1924  *      no valid mappings.
1925  */
1926 void
1927 pmap_destroy(pmap_t pmap)
1928 {
1929         int count;
1930
1931         if (pmap == NULL)
1932                 return;
1933
1934         count = --pmap->pm_count;
1935         if (count == 0) {
1936                 pmap_release(pmap);
1937                 panic("destroying a pmap is not yet implemented");
1938         }
1939 }
1940
1941 /*
1942  *      Add a reference to the specified pmap.
1943  */
1944 void
1945 pmap_reference(pmap_t pmap)
1946 {
1947         if (pmap != NULL) {
1948                 pmap->pm_count++;
1949         }
1950 }
1951
1952 /***************************************************
1953 * page management routines.
1954  ***************************************************/
1955
1956 /*
1957  * free the pv_entry back to the free list.  This function may be
1958  * called from an interrupt.
1959  */
1960 static __inline
1961 void
1962 free_pv_entry(pv_entry_t pv)
1963 {
1964         pv_entry_count--;
1965         KKASSERT(pv_entry_count >= 0);
1966         zfree(pvzone, pv);
1967 }
1968
1969 /*
1970  * get a new pv_entry, allocating a block from the system
1971  * when needed.  This function may be called from an interrupt.
1972  */
1973 static
1974 pv_entry_t
1975 get_pv_entry(void)
1976 {
1977         pv_entry_count++;
1978         if (pv_entry_high_water &&
1979                 (pv_entry_count > pv_entry_high_water) &&
1980                 (pmap_pagedaemon_waken == 0)) {
1981                 pmap_pagedaemon_waken = 1;
1982                 wakeup(&vm_pages_needed);
1983         }
1984         return zalloc(pvzone);
1985 }
1986
1987 /*
1988  * This routine is very drastic, but can save the system
1989  * in a pinch.
1990  */
1991 void
1992 pmap_collect(void)
1993 {
1994         int i;
1995         vm_page_t m;
1996         static int warningdone=0;
1997
1998         if (pmap_pagedaemon_waken == 0)
1999                 return;
2000
2001         if (warningdone < 5) {
2002                 kprintf("pmap_collect: collecting pv entries -- suggest increasing PMAP_SHPGPERPROC\n");
2003                 warningdone++;
2004         }
2005
2006         for(i = 0; i < vm_page_array_size; i++) {
2007                 m = &vm_page_array[i];
2008                 if (m->wire_count || m->hold_count || m->busy ||
2009                     (m->flags & PG_BUSY))
2010                         continue;
2011                 pmap_remove_all(m);
2012         }
2013         pmap_pagedaemon_waken = 0;
2014 }
2015         
2016
2017 /*
2018  * If it is the first entry on the list, it is actually
2019  * in the header and we must copy the following entry up
2020  * to the header.  Otherwise we must search the list for
2021  * the entry.  In either case we free the now unused entry.
2022  */
2023 static
2024 int
2025 pmap_remove_entry(struct pmap *pmap, vm_page_t m, 
2026                         vm_offset_t va, pmap_inval_info_t info)
2027 {
2028         pv_entry_t pv;
2029         int rtval;
2030
2031         crit_enter();
2032         if (m->md.pv_list_count < pmap->pm_stats.resident_count) {
2033                 TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
2034                         if (pmap == pv->pv_pmap && va == pv->pv_va) 
2035                                 break;
2036                 }
2037         } else {
2038                 TAILQ_FOREACH(pv, &pmap->pm_pvlist, pv_plist) {
2039                         if (va == pv->pv_va) 
2040                                 break;
2041                 }
2042         }
2043
2044         rtval = 0;
2045         KKASSERT(pv);
2046
2047         TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
2048         m->md.pv_list_count--;
2049         KKASSERT(m->md.pv_list_count >= 0);
2050         if (TAILQ_EMPTY(&m->md.pv_list))
2051                 vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
2052         TAILQ_REMOVE(&pmap->pm_pvlist, pv, pv_plist);
2053         ++pmap->pm_generation;
2054         rtval = pmap_unuse_pt(pmap, va, pv->pv_ptem, info);
2055         free_pv_entry(pv);
2056
2057         crit_exit();
2058         return rtval;
2059 }
2060
2061 /*
2062  * Create a pv entry for page at pa for
2063  * (pmap, va).
2064  */
2065 static
2066 void
2067 pmap_insert_entry(pmap_t pmap, vm_offset_t va, vm_page_t mpte, vm_page_t m)
2068 {
2069         pv_entry_t pv;
2070
2071         crit_enter();
2072         pv = get_pv_entry();
2073         pv->pv_va = va;
2074         pv->pv_pmap = pmap;
2075         pv->pv_ptem = mpte;
2076
2077         TAILQ_INSERT_TAIL(&pmap->pm_pvlist, pv, pv_plist);
2078         TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
2079         ++pmap->pm_generation;
2080         m->md.pv_list_count++;
2081
2082         crit_exit();
2083 }
2084
2085 /*
2086  * pmap_remove_pte: do the things to unmap a page in a process
2087  */
2088 static
2089 int
2090 pmap_remove_pte(struct pmap *pmap, pt_entry_t *ptq, vm_offset_t va,
2091         pmap_inval_info_t info)
2092 {
2093         pt_entry_t oldpte;
2094         vm_page_t m;
2095
2096         pmap_inval_add(info, pmap, va);
2097         oldpte = pte_load_clear(ptq);
2098         if (oldpte & PG_W)
2099                 pmap->pm_stats.wired_count -= 1;
2100         /*
2101          * Machines that don't support invlpg, also don't support
2102          * PG_G.  XXX PG_G is disabled for SMP so don't worry about
2103          * the SMP case.
2104          */
2105         if (oldpte & PG_G)
2106                 cpu_invlpg((void *)va);
2107         KKASSERT(pmap->pm_stats.resident_count > 0);
2108         --pmap->pm_stats.resident_count;
2109         if (oldpte & PG_MANAGED) {
2110                 m = PHYS_TO_VM_PAGE(oldpte);
2111                 if (oldpte & PG_M) {
2112 #if defined(PMAP_DIAGNOSTIC)
2113                         if (pmap_nw_modified((pt_entry_t) oldpte)) {
2114                                 kprintf(
2115         "pmap_remove: modified page not writable: va: 0x%lx, pte: 0x%lx\n",
2116                                     va, oldpte);
2117                         }
2118 #endif
2119                         if (pmap_track_modified(va))
2120                                 vm_page_dirty(m);
2121                 }
2122                 if (oldpte & PG_A)
2123                         vm_page_flag_set(m, PG_REFERENCED);
2124                 return pmap_remove_entry(pmap, m, va, info);
2125         } else {
2126                 return pmap_unuse_pt(pmap, va, NULL, info);
2127         }
2128
2129         return 0;
2130 }
2131
2132 /*
2133  * pmap_remove_page:
2134  *
2135  *      Remove a single page from a process address space.
2136  *
2137  *      This function may not be called from an interrupt if the pmap is
2138  *      not kernel_pmap.
2139  */
2140 static
2141 void
2142 pmap_remove_page(struct pmap *pmap, vm_offset_t va, pmap_inval_info_t info)
2143 {
2144         pt_entry_t *pte;
2145
2146         pte = pmap_pte(pmap, va);
2147         if (pte == NULL)
2148                 return;
2149         if ((*pte & PG_V) == 0)
2150                 return;
2151         pmap_remove_pte(pmap, pte, va, info);
2152 }
2153
2154 /*
2155  * pmap_remove:
2156  *
2157  *      Remove the given range of addresses from the specified map.
2158  *
2159  *      It is assumed that the start and end are properly
2160  *      rounded to the page size.
2161  *
2162  *      This function may not be called from an interrupt if the pmap is
2163  *      not kernel_pmap.
2164  */
2165 void
2166 pmap_remove(struct pmap *pmap, vm_offset_t sva, vm_offset_t eva)
2167 {
2168         vm_offset_t va_next;
2169         pml4_entry_t *pml4e;
2170         pdp_entry_t *pdpe;
2171         pd_entry_t ptpaddr, *pde;
2172         pt_entry_t *pte;
2173         struct pmap_inval_info info;
2174
2175         if (pmap == NULL)
2176                 return;
2177
2178         if (pmap->pm_stats.resident_count == 0)
2179                 return;
2180
2181         pmap_inval_init(&info);
2182
2183         /*
2184          * special handling of removing one page.  a very
2185          * common operation and easy to short circuit some
2186          * code.
2187          */
2188         if (sva + PAGE_SIZE == eva) {
2189                 pde = pmap_pde(pmap, sva);
2190                 if (pde && (*pde & PG_PS) == 0) {
2191                         pmap_remove_page(pmap, sva, &info);
2192                         pmap_inval_flush(&info);
2193                         return;
2194                 }
2195         }
2196
2197         for (; sva < eva; sva = va_next) {
2198                 pml4e = pmap_pml4e(pmap, sva);
2199                 if ((*pml4e & PG_V) == 0) {
2200                         va_next = (sva + NBPML4) & ~PML4MASK;
2201                         if (va_next < sva)
2202                                 va_next = eva;
2203                         continue;
2204                 }
2205
2206                 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
2207                 if ((*pdpe & PG_V) == 0) {
2208                         va_next = (sva + NBPDP) & ~PDPMASK;
2209                         if (va_next < sva)
2210                                 va_next = eva;
2211                         continue;
2212                 }
2213
2214                 /*
2215                  * Calculate index for next page table.
2216                  */
2217                 va_next = (sva + NBPDR) & ~PDRMASK;
2218                 if (va_next < sva)
2219                         va_next = eva;
2220
2221                 pde = pmap_pdpe_to_pde(pdpe, sva);
2222                 ptpaddr = *pde;
2223
2224                 /*
2225                  * Weed out invalid mappings.
2226                  */
2227                 if (ptpaddr == 0)
2228                         continue;
2229
2230                 /*
2231                  * Check for large page.
2232                  */
2233                 if ((ptpaddr & PG_PS) != 0) {
2234                         /* JG FreeBSD has more complex treatment here */
2235                         pmap_inval_add(&info, pmap, -1);
2236                         *pde = 0;
2237                         pmap->pm_stats.resident_count -= NBPDR / PAGE_SIZE;
2238                         continue;
2239                 }
2240
2241                 /*
2242                  * Limit our scan to either the end of the va represented
2243                  * by the current page table page, or to the end of the
2244                  * range being removed.
2245                  */
2246                 if (va_next > eva)
2247                         va_next = eva;
2248
2249                 /*
2250                  * NOTE: pmap_remove_pte() can block.
2251                  */
2252                 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
2253                     sva += PAGE_SIZE) {
2254                         if (*pte == 0)
2255                                 continue;
2256                         if (pmap_remove_pte(pmap, pte, sva, &info))
2257                                 break;
2258                 }
2259         }
2260         pmap_inval_flush(&info);
2261 }
2262
2263 /*
2264  * pmap_remove_all:
2265  *
2266  *      Removes this physical page from all physical maps in which it resides.
2267  *      Reflects back modify bits to the pager.
2268  *
2269  *      This routine may not be called from an interrupt.
2270  */
2271
2272 static
2273 void
2274 pmap_remove_all(vm_page_t m)
2275 {
2276         struct pmap_inval_info info;
2277         pt_entry_t *pte, tpte;
2278         pv_entry_t pv;
2279
2280         if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
2281                 return;
2282
2283         pmap_inval_init(&info);
2284         crit_enter();
2285         while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
2286                 KKASSERT(pv->pv_pmap->pm_stats.resident_count > 0);
2287                 --pv->pv_pmap->pm_stats.resident_count;
2288
2289                 pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
2290                 pmap_inval_add(&info, pv->pv_pmap, pv->pv_va);
2291                 tpte = pte_load_clear(pte);
2292
2293                 if (tpte & PG_W)
2294                         pv->pv_pmap->pm_stats.wired_count--;
2295
2296                 if (tpte & PG_A)
2297                         vm_page_flag_set(m, PG_REFERENCED);
2298
2299                 /*
2300                  * Update the vm_page_t clean and reference bits.
2301                  */
2302                 if (tpte & PG_M) {
2303 #if defined(PMAP_DIAGNOSTIC)
2304                         if (pmap_nw_modified(tpte)) {
2305                                 kprintf(
2306         "pmap_remove_all: modified page not writable: va: 0x%lx, pte: 0x%lx\n",
2307                                     pv->pv_va, tpte);
2308                         }
2309 #endif
2310                         if (pmap_track_modified(pv->pv_va))
2311                                 vm_page_dirty(m);
2312                 }
2313                 TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
2314                 TAILQ_REMOVE(&pv->pv_pmap->pm_pvlist, pv, pv_plist);
2315                 ++pv->pv_pmap->pm_generation;
2316                 m->md.pv_list_count--;
2317                 KKASSERT(m->md.pv_list_count >= 0);
2318                 if (TAILQ_EMPTY(&m->md.pv_list))
2319                         vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
2320                 pmap_unuse_pt(pv->pv_pmap, pv->pv_va, pv->pv_ptem, &info);
2321                 free_pv_entry(pv);
2322         }
2323         crit_exit();
2324         KKASSERT((m->flags & (PG_MAPPED|PG_WRITEABLE)) == 0);
2325         pmap_inval_flush(&info);
2326 }
2327
2328 /*
2329  * pmap_protect:
2330  *
2331  *      Set the physical protection on the specified range of this map
2332  *      as requested.
2333  *
2334  *      This function may not be called from an interrupt if the map is
2335  *      not the kernel_pmap.
2336  */
2337 void
2338 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
2339 {
2340         vm_offset_t va_next;
2341         pml4_entry_t *pml4e;
2342         pdp_entry_t *pdpe;
2343         pd_entry_t ptpaddr, *pde;
2344         pt_entry_t *pte;
2345         pmap_inval_info info;
2346
2347         /* JG review for NX */
2348
2349         if (pmap == NULL)
2350                 return;
2351
2352         if ((prot & VM_PROT_READ) == VM_PROT_NONE) {
2353                 pmap_remove(pmap, sva, eva);
2354                 return;
2355         }
2356
2357         if (prot & VM_PROT_WRITE)
2358                 return;
2359
2360         pmap_inval_init(&info);
2361
2362         for (; sva < eva; sva = va_next) {
2363
2364                 pml4e = pmap_pml4e(pmap, sva);
2365                 if ((*pml4e & PG_V) == 0) {
2366                         va_next = (sva + NBPML4) & ~PML4MASK;
2367                         if (va_next < sva)
2368                                 va_next = eva;
2369                         continue;
2370                 }
2371
2372                 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
2373                 if ((*pdpe & PG_V) == 0) {
2374                         va_next = (sva + NBPDP) & ~PDPMASK;
2375                         if (va_next < sva)
2376                                 va_next = eva;
2377                         continue;
2378                 }
2379
2380                 va_next = (sva + NBPDR) & ~PDRMASK;
2381                 if (va_next < sva)
2382                         va_next = eva;
2383
2384                 pde = pmap_pdpe_to_pde(pdpe, sva);
2385                 ptpaddr = *pde;
2386
2387                 /*
2388                  * Check for large page.
2389                  */
2390                 if ((ptpaddr & PG_PS) != 0) {
2391                         pmap_inval_add(&info, pmap, -1);
2392                         *pde &= ~(PG_M|PG_RW);
2393                         pmap->pm_stats.resident_count -= NBPDR / PAGE_SIZE;
2394                         continue;
2395                 }
2396
2397                 /*
2398                  * Weed out invalid mappings. Note: we assume that the page
2399                  * directory table is always allocated, and in kernel virtual.
2400                  */
2401                 if (ptpaddr == 0)
2402                         continue;
2403
2404                 if (va_next > eva)
2405                         va_next = eva;
2406
2407                 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
2408                     sva += PAGE_SIZE) {
2409                         pt_entry_t obits, pbits;
2410                         vm_page_t m;
2411
2412                         /*
2413                          * XXX non-optimal.  Note also that there can be
2414                          * no pmap_inval_flush() calls until after we modify
2415                          * ptbase[sindex] (or otherwise we have to do another
2416                          * pmap_inval_add() call).
2417                          */
2418                         pmap_inval_add(&info, pmap, sva);
2419                         obits = pbits = *pte;
2420                         if ((pbits & PG_V) == 0)
2421                                 continue;
2422                         if (pbits & PG_MANAGED) {
2423                                 m = NULL;
2424                                 if (pbits & PG_A) {
2425                                         m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
2426                                         vm_page_flag_set(m, PG_REFERENCED);
2427                                         pbits &= ~PG_A;
2428                                 }
2429                                 if (pbits & PG_M) {
2430                                         if (pmap_track_modified(sva)) {
2431                                                 if (m == NULL)
2432                                                         m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
2433                                                 vm_page_dirty(m);
2434                                                 pbits &= ~PG_M;
2435                                         }
2436                                 }
2437                         }
2438
2439                         pbits &= ~PG_RW;
2440
2441                         if (pbits != obits) {
2442                                 *pte = pbits;
2443                         }
2444                 }
2445         }
2446         pmap_inval_flush(&info);
2447 }
2448
2449 /*
2450  *      Insert the given physical page (p) at
2451  *      the specified virtual address (v) in the
2452  *      target physical map with the protection requested.
2453  *
2454  *      If specified, the page will be wired down, meaning
2455  *      that the related pte can not be reclaimed.
2456  *
2457  *      NB:  This is the only routine which MAY NOT lazy-evaluate
2458  *      or lose information.  That is, this routine must actually
2459  *      insert this page into the given map NOW.
2460  */
2461 void
2462 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
2463            boolean_t wired)
2464 {
2465         vm_paddr_t pa;
2466         pd_entry_t *pde;
2467         pt_entry_t *pte;
2468         vm_paddr_t opa;
2469         pt_entry_t origpte, newpte;
2470         vm_page_t mpte;
2471         pmap_inval_info info;
2472
2473         if (pmap == NULL)
2474                 return;
2475
2476         va = trunc_page(va);
2477 #ifdef PMAP_DIAGNOSTIC
2478         if (va >= KvaEnd)
2479                 panic("pmap_enter: toobig");
2480         if ((va >= UPT_MIN_ADDRESS) && (va < UPT_MAX_ADDRESS))
2481                 panic("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)", va);
2482 #endif
2483         if (va < UPT_MAX_ADDRESS && pmap == &kernel_pmap) {
2484                 kprintf("Warning: pmap_enter called on UVA with kernel_pmap\n");
2485 #ifdef DDB
2486                 db_print_backtrace();
2487 #endif
2488         }
2489         if (va >= UPT_MAX_ADDRESS && pmap != &kernel_pmap) {
2490                 kprintf("Warning: pmap_enter called on KVA without kernel_pmap\n");
2491 #ifdef DDB
2492                 db_print_backtrace();
2493 #endif
2494         }
2495
2496         /*
2497          * In the case that a page table page is not
2498          * resident, we are creating it here.
2499          */
2500         if (va < VM_MAX_USER_ADDRESS)
2501                 mpte = pmap_allocpte(pmap, va);
2502         else
2503                 mpte = NULL;
2504
2505         pmap_inval_init(&info);
2506         pde = pmap_pde(pmap, va);
2507         if (pde != NULL && (*pde & PG_V) != 0) {
2508                 if ((*pde & PG_PS) != 0)
2509                         panic("pmap_enter: attempted pmap_enter on 2MB page");
2510                 pte = pmap_pde_to_pte(pde, va);
2511         } else
2512                 panic("pmap_enter: invalid page directory va=%#lx", va);
2513
2514         KKASSERT(pte != NULL);
2515         pa = VM_PAGE_TO_PHYS(m);
2516         origpte = *pte;
2517         opa = origpte & PG_FRAME;
2518
2519         /*
2520          * Mapping has not changed, must be protection or wiring change.
2521          */
2522         if (origpte && (opa == pa)) {
2523                 /*
2524                  * Wiring change, just update stats. We don't worry about
2525                  * wiring PT pages as they remain resident as long as there
2526                  * are valid mappings in them. Hence, if a user page is wired,
2527                  * the PT page will be also.
2528                  */
2529                 if (wired && ((origpte & PG_W) == 0))
2530                         pmap->pm_stats.wired_count++;
2531                 else if (!wired && (origpte & PG_W))
2532                         pmap->pm_stats.wired_count--;
2533
2534 #if defined(PMAP_DIAGNOSTIC)
2535                 if (pmap_nw_modified(origpte)) {
2536                         kprintf(
2537         "pmap_enter: modified page not writable: va: 0x%lx, pte: 0x%lx\n",
2538                             va, origpte);
2539                 }
2540 #endif
2541
2542                 /*
2543                  * Remove the extra pte reference.  Note that we cannot
2544                  * optimize the RO->RW case because we have adjusted the
2545                  * wiring count above and may need to adjust the wiring
2546                  * bits below.
2547                  */
2548                 if (mpte)
2549                         mpte->hold_count--;
2550
2551                 /*
2552                  * We might be turning off write access to the page,
2553                  * so we go ahead and sense modify status.
2554                  */
2555                 if (origpte & PG_MANAGED) {
2556                         if ((origpte & PG_M) && pmap_track_modified(va)) {
2557                                 vm_page_t om;
2558                                 om = PHYS_TO_VM_PAGE(opa);
2559                                 vm_page_dirty(om);
2560                         }
2561                         pa |= PG_MANAGED;
2562                         KKASSERT(m->flags & PG_MAPPED);
2563                 }
2564                 goto validate;
2565         } 
2566         /*
2567          * Mapping has changed, invalidate old range and fall through to
2568          * handle validating new mapping.
2569          */
2570         while (opa) {
2571                 int err;
2572                 err = pmap_remove_pte(pmap, pte, va, &info);
2573                 if (err)
2574                         panic("pmap_enter: pte vanished, va: 0x%lx", va);
2575                 origpte = *pte;
2576                 opa = origpte & PG_FRAME;
2577                 if (opa) {
2578                         kprintf("pmap_enter: Warning, raced pmap %p va %p\n",
2579                                 pmap, (void *)va);
2580                 }
2581         }
2582
2583         /*
2584          * Enter on the PV list if part of our managed memory. Note that we
2585          * raise IPL while manipulating pv_table since pmap_enter can be
2586          * called at interrupt time.
2587          */
2588         if (pmap_initialized && 
2589             (m->flags & (PG_FICTITIOUS|PG_UNMANAGED)) == 0) {
2590                 pmap_insert_entry(pmap, va, mpte, m);
2591                 pa |= PG_MANAGED;
2592                 vm_page_flag_set(m, PG_MAPPED);
2593         }
2594
2595         /*
2596          * Increment counters
2597          */
2598         ++pmap->pm_stats.resident_count;
2599         if (wired)
2600                 pmap->pm_stats.wired_count++;
2601
2602 validate:
2603         /*
2604          * Now validate mapping with desired protection/wiring.
2605          */
2606         newpte = (pt_entry_t) (pa | pte_prot(pmap, prot) | PG_V);
2607
2608         if (wired)
2609                 newpte |= PG_W;
2610         if (va < VM_MAX_USER_ADDRESS)
2611                 newpte |= PG_U;
2612         if (pmap == &kernel_pmap)
2613                 newpte |= pgeflag;
2614
2615         /*
2616          * if the mapping or permission bits are different, we need
2617          * to update the pte.
2618          */
2619         if ((origpte & ~(PG_M|PG_A)) != newpte) {
2620                 pmap_inval_add(&info, pmap, va);
2621                 *pte = newpte | PG_A;
2622                 if (newpte & PG_RW)
2623                         vm_page_flag_set(m, PG_WRITEABLE);
2624         }
2625         KKASSERT((newpte & PG_MANAGED) == 0 || (m->flags & PG_MAPPED));
2626         pmap_inval_flush(&info);
2627 }
2628
2629 /*
2630  * This code works like pmap_enter() but assumes VM_PROT_READ and not-wired.
2631  * This code also assumes that the pmap has no pre-existing entry for this
2632  * VA.
2633  *
2634  * This code currently may only be used on user pmaps, not kernel_pmap.
2635  */
2636 void
2637 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m)
2638 {
2639         pt_entry_t *pte;
2640         vm_paddr_t pa;
2641         vm_page_t mpte;
2642         vm_pindex_t ptepindex;
2643         pd_entry_t *ptepa;
2644         pmap_inval_info info;
2645
2646         pmap_inval_init(&info);
2647
2648         if (va < UPT_MAX_ADDRESS && pmap == &kernel_pmap) {
2649                 kprintf("Warning: pmap_enter_quick called on UVA with kernel_pmap\n");
2650 #ifdef DDB
2651                 db_print_backtrace();
2652 #endif
2653         }
2654         if (va >= UPT_MAX_ADDRESS && pmap != &kernel_pmap) {
2655                 kprintf("Warning: pmap_enter_quick called on KVA without kernel_pmap\n");
2656 #ifdef DDB
2657                 db_print_backtrace();
2658 #endif
2659         }
2660
2661         KKASSERT(va < UPT_MIN_ADDRESS); /* assert used on user pmaps only */
2662
2663         /*
2664          * Calculate the page table page (mpte), allocating it if necessary.
2665          *
2666          * A held page table page (mpte), or NULL, is passed onto the
2667          * section following.
2668          */
2669         if (va < VM_MAX_USER_ADDRESS) {
2670                 /*
2671                  * Calculate pagetable page index
2672                  */
2673                 ptepindex = pmap_pde_pindex(va);
2674
2675                 do {
2676                         /*
2677                          * Get the page directory entry
2678                          */
2679                         ptepa = pmap_pde(pmap, va);
2680
2681                         /*
2682                          * If the page table page is mapped, we just increment
2683                          * the hold count, and activate it.
2684                          */
2685                         if (ptepa && (*ptepa & PG_V) != 0) {
2686                                 if (*ptepa & PG_PS)
2687                                         panic("pmap_enter_quick: unexpected mapping into 2MB page");
2688 //                              if (pmap->pm_ptphint &&
2689 //                                  (pmap->pm_ptphint->pindex == ptepindex)) {
2690 //                                      mpte = pmap->pm_ptphint;
2691 //                              } else {
2692                                         mpte = pmap_page_lookup( pmap->pm_pteobj, ptepindex);
2693                                         pmap->pm_ptphint = mpte;
2694 //                              }
2695                                 if (mpte)
2696                                         mpte->hold_count++;
2697                         } else {
2698                                 mpte = _pmap_allocpte(pmap, ptepindex);
2699                         }
2700                 } while (mpte == NULL);
2701         } else {
2702                 mpte = NULL;
2703                 /* this code path is not yet used */
2704         }
2705
2706         /*
2707          * With a valid (and held) page directory page, we can just use
2708          * vtopte() to get to the pte.  If the pte is already present
2709          * we do not disturb it.
2710          */
2711         pte = vtopte(va);
2712         if (*pte & PG_V) {
2713                 if (mpte)
2714                         pmap_unwire_pte_hold(pmap, va, mpte, &info);
2715                 pa = VM_PAGE_TO_PHYS(m);
2716                 KKASSERT(((*pte ^ pa) & PG_FRAME) == 0);
2717                 return;
2718         }
2719
2720         /*
2721          * Enter on the PV list if part of our managed memory
2722          */
2723         if ((m->flags & (PG_FICTITIOUS|PG_UNMANAGED)) == 0) {
2724                 pmap_insert_entry(pmap, va, mpte, m);
2725                 vm_page_flag_set(m, PG_MAPPED);
2726         }
2727
2728         /*
2729          * Increment counters
2730          */
2731         ++pmap->pm_stats.resident_count;
2732
2733         pa = VM_PAGE_TO_PHYS(m);
2734
2735         /*
2736          * Now validate mapping with RO protection
2737          */
2738         if (m->flags & (PG_FICTITIOUS|PG_UNMANAGED))
2739                 *pte = pa | PG_V | PG_U;
2740         else
2741                 *pte = pa | PG_V | PG_U | PG_MANAGED;
2742 /*      pmap_inval_add(&info, pmap, va); shouldn't be needed inval->valid */
2743         pmap_inval_flush(&info);
2744 }
2745
2746 /*
2747  * Make a temporary mapping for a physical address.  This is only intended
2748  * to be used for panic dumps.
2749  */
2750 /* JG Needed on x86_64? */
2751 void *
2752 pmap_kenter_temporary(vm_paddr_t pa, int i)
2753 {
2754         pmap_kenter((vm_offset_t)crashdumpmap + (i * PAGE_SIZE), pa);
2755         return ((void *)crashdumpmap);
2756 }
2757
2758 #define MAX_INIT_PT (96)
2759
2760 /*
2761  * This routine preloads the ptes for a given object into the specified pmap.
2762  * This eliminates the blast of soft faults on process startup and
2763  * immediately after an mmap.
2764  */
2765 static int pmap_object_init_pt_callback(vm_page_t p, void *data);
2766
2767 void
2768 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_prot_t prot,
2769                     vm_object_t object, vm_pindex_t pindex, 
2770                     vm_size_t size, int limit)
2771 {
2772         struct rb_vm_page_scan_info info;
2773         struct lwp *lp;
2774         vm_size_t psize;
2775
2776         /*
2777          * We can't preinit if read access isn't set or there is no pmap
2778          * or object.
2779          */
2780         if ((prot & VM_PROT_READ) == 0 || pmap == NULL || object == NULL)
2781                 return;
2782
2783         /*
2784          * We can't preinit if the pmap is not the current pmap
2785          */
2786         lp = curthread->td_lwp;
2787         if (lp == NULL || pmap != vmspace_pmap(lp->lwp_vmspace))
2788                 return;
2789
2790         psize = x86_64_btop(size);
2791
2792         if ((object->type != OBJT_VNODE) ||
2793                 ((limit & MAP_PREFAULT_PARTIAL) && (psize > MAX_INIT_PT) &&
2794                         (object->resident_page_count > MAX_INIT_PT))) {
2795                 return;
2796         }
2797
2798         if (psize + pindex > object->size) {
2799                 if (object->size < pindex)
2800                         return;           
2801                 psize = object->size - pindex;
2802         }
2803
2804         if (psize == 0)
2805                 return;
2806
2807         /*
2808          * Use a red-black scan to traverse the requested range and load
2809          * any valid pages found into the pmap.
2810          *
2811          * We cannot safely scan the object's memq unless we are in a
2812          * critical section since interrupts can remove pages from objects.
2813          */
2814         info.start_pindex = pindex;
2815         info.end_pindex = pindex + psize - 1;
2816         info.limit = limit;
2817         info.mpte = NULL;
2818         info.addr = addr;
2819         info.pmap = pmap;
2820
2821         crit_enter();
2822         vm_page_rb_tree_RB_SCAN(&object->rb_memq, rb_vm_page_scancmp,
2823                                 pmap_object_init_pt_callback, &info);
2824         crit_exit();
2825 }
2826
2827 static
2828 int
2829 pmap_object_init_pt_callback(vm_page_t p, void *data)
2830 {
2831         struct rb_vm_page_scan_info *info = data;
2832         vm_pindex_t rel_index;
2833         /*
2834          * don't allow an madvise to blow away our really
2835          * free pages allocating pv entries.
2836          */
2837         if ((info->limit & MAP_PREFAULT_MADVISE) &&
2838                 vmstats.v_free_count < vmstats.v_free_reserved) {
2839                     return(-1);
2840         }
2841         if (((p->valid & VM_PAGE_BITS_ALL) == VM_PAGE_BITS_ALL) &&
2842             (p->busy == 0) && (p->flags & (PG_BUSY | PG_FICTITIOUS)) == 0) {
2843                 if ((p->queue - p->pc) == PQ_CACHE)
2844                         vm_page_deactivate(p);
2845                 vm_page_busy(p);
2846                 rel_index = p->pindex - info->start_pindex;
2847                 pmap_enter_quick(info->pmap,
2848                                  info->addr + x86_64_ptob(rel_index), p);
2849                 vm_page_wakeup(p);
2850         }
2851         return(0);
2852 }
2853
2854 /*
2855  * Return TRUE if the pmap is in shape to trivially
2856  * pre-fault the specified address.
2857  *
2858  * Returns FALSE if it would be non-trivial or if a
2859  * pte is already loaded into the slot.
2860  */
2861 int
2862 pmap_prefault_ok(pmap_t pmap, vm_offset_t addr)
2863 {
2864         pt_entry_t *pte;
2865         pd_entry_t *pde;
2866
2867         pde = pmap_pde(pmap, addr);
2868         if (pde == NULL || *pde == 0)
2869                 return(0);
2870
2871         pte = vtopte(addr);
2872         if (*pte)
2873                 return(0);
2874
2875         return(1);
2876 }
2877
2878 /*
2879  *      Routine:        pmap_change_wiring
2880  *      Function:       Change the wiring attribute for a map/virtual-address
2881  *                      pair.
2882  *      In/out conditions:
2883  *                      The mapping must already exist in the pmap.
2884  */
2885 void
2886 pmap_change_wiring(pmap_t pmap, vm_offset_t va, boolean_t wired)
2887 {
2888         pt_entry_t *pte;
2889
2890         if (pmap == NULL)
2891                 return;
2892
2893         pte = pmap_pte(pmap, va);
2894
2895         if (wired && !pmap_pte_w(pte))
2896                 pmap->pm_stats.wired_count++;
2897         else if (!wired && pmap_pte_w(pte))
2898                 pmap->pm_stats.wired_count--;
2899
2900         /*
2901          * Wiring is not a hardware characteristic so there is no need to
2902          * invalidate TLB.  However, in an SMP environment we must use
2903          * a locked bus cycle to update the pte (if we are not using 
2904          * the pmap_inval_*() API that is)... it's ok to do this for simple
2905          * wiring changes.
2906          */
2907 #ifdef SMP
2908         if (wired)
2909                 atomic_set_long(pte, PG_W);
2910         else
2911                 atomic_clear_long(pte, PG_W);
2912 #else
2913         if (wired)
2914                 atomic_set_long_nonlocked(pte, PG_W);
2915         else
2916                 atomic_clear_long_nonlocked(pte, PG_W);
2917 #endif
2918 }
2919
2920
2921
2922 /*
2923  *      Copy the range specified by src_addr/len
2924  *      from the source map to the range dst_addr/len
2925  *      in the destination map.
2926  *
2927  *      This routine is only advisory and need not do anything.
2928  */
2929 void
2930 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, 
2931           vm_size_t len, vm_offset_t src_addr)
2932 {
2933         return;
2934 #if 0
2935         pmap_inval_info info;
2936         vm_offset_t addr;
2937         vm_offset_t end_addr = src_addr + len;
2938         vm_offset_t pdnxt;
2939         pd_entry_t src_frame, dst_frame;
2940         vm_page_t m;
2941
2942         if (dst_addr != src_addr)
2943                 return;
2944 #if JGPMAP32
2945         src_frame = src_pmap->pm_pdir[PTDPTDI] & PG_FRAME;
2946         if (src_frame != (PTDpde & PG_FRAME)) {
2947                 return;
2948         }
2949
2950         dst_frame = dst_pmap->pm_pdir[PTDPTDI] & PG_FRAME;
2951         if (dst_frame != (APTDpde & PG_FRAME)) {
2952                 APTDpde = (pd_entry_t) (dst_frame | PG_RW | PG_V);
2953                 /* The page directory is not shared between CPUs */
2954                 cpu_invltlb();
2955         }
2956 #endif
2957         pmap_inval_init(&info);
2958         pmap_inval_add(&info, dst_pmap, -1);
2959         pmap_inval_add(&info, src_pmap, -1);
2960
2961         /*
2962          * critical section protection is required to maintain the page/object
2963          * association, interrupts can free pages and remove them from 
2964          * their objects.
2965          */
2966         crit_enter();
2967         for (addr = src_addr; addr < end_addr; addr = pdnxt) {
2968                 pt_entry_t *src_pte, *dst_pte;
2969                 vm_page_t dstmpte, srcmpte;
2970                 vm_offset_t srcptepaddr;
2971                 vm_pindex_t ptepindex;
2972
2973                 if (addr >= UPT_MIN_ADDRESS)
2974                         panic("pmap_copy: invalid to pmap_copy page tables\n");
2975
2976                 /*
2977                  * Don't let optional prefaulting of pages make us go
2978                  * way below the low water mark of free pages or way
2979                  * above high water mark of used pv entries.
2980                  */
2981                 if (vmstats.v_free_count < vmstats.v_free_reserved ||
2982                     pv_entry_count > pv_entry_high_water)
2983                         break;
2984                 
2985                 pdnxt = ((addr + PAGE_SIZE*NPTEPG) & ~(PAGE_SIZE*NPTEPG - 1));
2986                 ptepindex = addr >> PDRSHIFT;
2987
2988 #if JGPMAP32
2989                 srcptepaddr = (vm_offset_t) src_pmap->pm_pdir[ptepindex];
2990 #endif
2991                 if (srcptepaddr == 0)
2992                         continue;
2993                         
2994                 if (srcptepaddr & PG_PS) {
2995 #if JGPMAP32
2996                         if (dst_pmap->pm_pdir[ptepindex] == 0) {
2997                                 dst_pmap->pm_pdir[ptepindex] = (pd_entry_t) srcptepaddr;
2998                                 dst_pmap->pm_stats.resident_count += NBPDR / PAGE_SIZE;
2999                         }
3000 #endif
3001                         continue;
3002                 }
3003
3004                 srcmpte = vm_page_lookup(src_pmap->pm_pteobj, ptepindex);
3005                 if ((srcmpte == NULL) || (srcmpte->hold_count == 0) ||
3006                     (srcmpte->flags & PG_BUSY)) {
3007                         continue;
3008                 }
3009
3010                 if (pdnxt > end_addr)
3011                         pdnxt = end_addr;
3012
3013                 src_pte = vtopte(addr);
3014 #if JGPMAP32
3015                 dst_pte = avtopte(addr);
3016 #endif
3017                 while (addr < pdnxt) {
3018                         pt_entry_t ptetemp;
3019
3020                         ptetemp = *src_pte;
3021                         /*
3022                          * we only virtual copy managed pages
3023                          */
3024                         if ((ptetemp & PG_MANAGED) != 0) {
3025                                 /*
3026                                  * We have to check after allocpte for the
3027                                  * pte still being around...  allocpte can
3028                                  * block.
3029                                  *
3030                                  * pmap_allocpte() can block.  If we lose
3031                                  * our page directory mappings we stop.
3032                                  */
3033                                 dstmpte = pmap_allocpte(dst_pmap, addr);
3034
3035 #if JGPMAP32
3036                                 if (src_frame != (PTDpde & PG_FRAME) ||
3037                                     dst_frame != (APTDpde & PG_FRAME)
3038                                 ) {
3039                                         kprintf("WARNING: pmap_copy: detected and corrected race\n");
3040                                         pmap_unwire_pte_hold(dst_pmap, dstmpte, &info);
3041                                         goto failed;
3042                                 } else if ((*dst_pte == 0) &&
3043                                            (ptetemp = *src_pte) != 0 &&
3044                                            (ptetemp & PG_MANAGED)) {
3045                                         /*
3046                                          * Clear the modified and
3047                                          * accessed (referenced) bits
3048                                          * during the copy.
3049                                          */
3050                                         m = PHYS_TO_VM_PAGE(ptetemp);
3051                                         *dst_pte = ptetemp & ~(PG_M | PG_A);
3052                                         ++dst_pmap->pm_stats.resident_count;
3053                                         pmap_insert_entry(dst_pmap, addr,
3054                                                 dstmpte, m);
3055                                         KKASSERT(m->flags & PG_MAPPED);
3056                                 } else {
3057                                         kprintf("WARNING: pmap_copy: dst_pte race detected and corrected\n");
3058                                         pmap_unwire_pte_hold(dst_pmap, dstmpte, &info);
3059                                         goto failed;
3060                                 }
3061 #endif
3062                                 if (dstmpte->hold_count >= srcmpte->hold_count)
3063                                         break;
3064                         }
3065                         addr += PAGE_SIZE;
3066                         src_pte++;
3067                         dst_pte++;
3068                 }
3069         }
3070 failed:
3071         crit_exit();
3072         pmap_inval_flush(&info);
3073 #endif
3074 }       
3075
3076 /*
3077  * pmap_zero_page:
3078  *
3079  *      Zero the specified physical page.
3080  *
3081  *      This function may be called from an interrupt and no locking is
3082  *      required.
3083  */
3084 void
3085 pmap_zero_page(vm_paddr_t phys)
3086 {
3087         vm_offset_t va = PHYS_TO_DMAP(phys);
3088
3089         pagezero((void *)va);
3090 }
3091
3092 /*
3093  * pmap_page_assertzero:
3094  *
3095  *      Assert that a page is empty, panic if it isn't.
3096  */
3097 void
3098 pmap_page_assertzero(vm_paddr_t phys)
3099 {
3100         vm_offset_t virt = PHYS_TO_DMAP(phys);
3101         int i;
3102
3103         for (i = 0; i < PAGE_SIZE; i += sizeof(long)) {
3104             if (*(long *)((char *)virt + i) != 0) {
3105                 panic("pmap_page_assertzero() @ %p not zero!\n", (void *)virt);
3106             }
3107         }
3108 }
3109
3110 /*
3111  * pmap_zero_page:
3112  *
3113  *      Zero part of a physical page by mapping it into memory and clearing
3114  *      its contents with bzero.
3115  *
3116  *      off and size may not cover an area beyond a single hardware page.
3117  */
3118 void
3119 pmap_zero_page_area(vm_paddr_t phys, int off, int size)
3120 {
3121         vm_offset_t virt = PHYS_TO_DMAP(phys);
3122
3123         bzero((char *)virt + off, size);
3124 }
3125
3126 /*
3127  * pmap_copy_page:
3128  *
3129  *      Copy the physical page from the source PA to the target PA.
3130  *      This function may be called from an interrupt.  No locking
3131  *      is required.
3132  */
3133 void
3134 pmap_copy_page(vm_paddr_t src, vm_paddr_t dst)
3135 {
3136         vm_offset_t src_virt, dst_virt;
3137
3138         src_virt = PHYS_TO_DMAP(src);
3139         dst_virt = PHYS_TO_DMAP(dst);
3140         bcopy((void *)src_virt, (void *)dst_virt, PAGE_SIZE);
3141 }
3142
3143 /*
3144  * pmap_copy_page_frag:
3145  *
3146  *      Copy the physical page from the source PA to the target PA.
3147  *      This function may be called from an interrupt.  No locking
3148  *      is required.
3149  */
3150 void
3151 pmap_copy_page_frag(vm_paddr_t src, vm_paddr_t dst, size_t bytes)
3152 {
3153         vm_offset_t src_virt, dst_virt;
3154
3155         src_virt = PHYS_TO_DMAP(src);
3156         dst_virt = PHYS_TO_DMAP(dst);
3157
3158         bcopy((char *)src_virt + (src & PAGE_MASK),
3159               (char *)dst_virt + (dst & PAGE_MASK),
3160               bytes);
3161 }
3162
3163 /*
3164  * Returns true if the pmap's pv is one of the first
3165  * 16 pvs linked to from this page.  This count may
3166  * be changed upwards or downwards in the future; it
3167  * is only necessary that true be returned for a small
3168  * subset of pmaps for proper page aging.
3169  */
3170 boolean_t
3171 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
3172 {
3173         pv_entry_t pv;
3174         int loops = 0;
3175
3176         if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
3177                 return FALSE;
3178
3179         crit_enter();
3180
3181         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
3182                 if (pv->pv_pmap == pmap) {
3183                         crit_exit();
3184                         return TRUE;
3185                 }
3186                 loops++;
3187                 if (loops >= 16)
3188                         break;
3189         }
3190         crit_exit();
3191         return (FALSE);
3192 }
3193
3194 /*
3195  * Remove all pages from specified address space
3196  * this aids process exit speeds.  Also, this code
3197  * is special cased for current process only, but
3198  * can have the more generic (and slightly slower)
3199  * mode enabled.  This is much faster than pmap_remove
3200  * in the case of running down an entire address space.
3201  */
3202 void
3203 pmap_remove_pages(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3204 {
3205         struct lwp *lp;
3206         pt_entry_t *pte, tpte;
3207         pv_entry_t pv, npv;
3208         vm_page_t m;
3209         pmap_inval_info info;
3210         int iscurrentpmap;
3211         int save_generation;
3212
3213         lp = curthread->td_lwp;
3214         if (lp && pmap == vmspace_pmap(lp->lwp_vmspace))
3215                 iscurrentpmap = 1;
3216         else
3217                 iscurrentpmap = 0;
3218
3219         pmap_inval_init(&info);
3220         crit_enter();
3221         for (pv = TAILQ_FIRST(&pmap->pm_pvlist); pv; pv = npv) {
3222                 if (pv->pv_va >= eva || pv->pv_va < sva) {
3223                         npv = TAILQ_NEXT(pv, pv_plist);
3224                         continue;
3225                 }
3226
3227                 KKASSERT(pmap == pv->pv_pmap);
3228
3229                 if (iscurrentpmap)
3230                         pte = vtopte(pv->pv_va);
3231                 else
3232                         pte = pmap_pte_quick(pmap, pv->pv_va);
3233                 if (pmap->pm_active)
3234                         pmap_inval_add(&info, pmap, pv->pv_va);
3235
3236                 /*
3237                  * We cannot remove wired pages from a process' mapping
3238                  * at this time
3239                  */
3240                 if (*pte & PG_W) {
3241                         npv = TAILQ_NEXT(pv, pv_plist);
3242                         continue;
3243                 }
3244                 tpte = pte_load_clear(pte);
3245
3246                 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
3247
3248                 KASSERT(m < &vm_page_array[vm_page_array_size],
3249                         ("pmap_remove_pages: bad tpte %lx", tpte));
3250
3251                 KKASSERT(pmap->pm_stats.resident_count > 0);
3252                 --pmap->pm_stats.resident_count;
3253
3254                 /*
3255                  * Update the vm_page_t clean and reference bits.
3256                  */
3257                 if (tpte & PG_M) {
3258                         vm_page_dirty(m);
3259                 }
3260
3261                 npv = TAILQ_NEXT(pv, pv_plist);
3262                 TAILQ_REMOVE(&pmap->pm_pvlist, pv, pv_plist);
3263                 save_generation = ++pmap->pm_generation;
3264
3265                 m->md.pv_list_count--;
3266                 TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
3267                 if (TAILQ_EMPTY(&m->md.pv_list))
3268                         vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
3269
3270                 pmap_unuse_pt(pmap, pv->pv_va, pv->pv_ptem, &info);
3271                 free_pv_entry(pv);
3272
3273                 /*
3274                  * Restart the scan if we blocked during the unuse or free
3275                  * calls and other removals were made.
3276                  */
3277                 if (save_generation != pmap->pm_generation) {
3278                         kprintf("Warning: pmap_remove_pages race-A avoided\n");
3279                         npv = TAILQ_FIRST(&pmap->pm_pvlist);
3280                 }
3281         }
3282         pmap_inval_flush(&info);
3283         crit_exit();
3284 }
3285
3286 /*
3287  * pmap_testbit tests bits in pte's
3288  * note that the testbit/clearbit routines are inline,
3289  * and a lot of things compile-time evaluate.
3290  */
3291 static
3292 boolean_t
3293 pmap_testbit(vm_page_t m, int bit)
3294 {
3295         pv_entry_t pv;
3296         pt_entry_t *pte;
3297
3298         if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
3299                 return FALSE;
3300
3301         if (TAILQ_FIRST(&m->md.pv_list) == NULL)
3302                 return FALSE;
3303
3304         crit_enter();
3305
3306         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
3307                 /*
3308                  * if the bit being tested is the modified bit, then
3309                  * mark clean_map and ptes as never
3310                  * modified.
3311                  */
3312                 if (bit & (PG_A|PG_M)) {
3313                         if (!pmap_track_modified(pv->pv_va))
3314                                 continue;
3315                 }
3316
3317 #if defined(PMAP_DIAGNOSTIC)
3318                 if (pv->pv_pmap == NULL) {
3319                         kprintf("Null pmap (tb) at va: 0x%lx\n", pv->pv_va);
3320                         continue;
3321                 }
3322 #endif
3323                 pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
3324                 if (*pte & bit) {
3325                         crit_exit();
3326                         return TRUE;
3327                 }
3328         }
3329         crit_exit();
3330         return (FALSE);
3331 }
3332
3333 /*
3334  * this routine is used to modify bits in ptes
3335  */
3336 static __inline
3337 void
3338 pmap_clearbit(vm_page_t m, int bit)
3339 {
3340         struct pmap_inval_info info;
3341         pv_entry_t pv;
3342         pt_entry_t *pte;
3343         pt_entry_t pbits;
3344
3345         if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
3346                 return;
3347
3348         pmap_inval_init(&info);
3349         crit_enter();
3350
3351         /*
3352          * Loop over all current mappings setting/clearing as appropos If
3353          * setting RO do we need to clear the VAC?
3354          */
3355         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
3356                 /*
3357                  * don't write protect pager mappings
3358                  */
3359                 if (bit == PG_RW) {
3360                         if (!pmap_track_modified(pv->pv_va))
3361                                 continue;
3362                 }
3363
3364 #if defined(PMAP_DIAGNOSTIC)
3365                 if (pv->pv_pmap == NULL) {
3366                         kprintf("Null pmap (cb) at va: 0x%lx\n", pv->pv_va);
3367                         continue;
3368                 }
3369 #endif
3370
3371                 /*
3372                  * Careful here.  We can use a locked bus instruction to
3373                  * clear PG_A or PG_M safely but we need to synchronize
3374                  * with the target cpus when we mess with PG_RW.
3375                  *
3376                  * We do not have to force synchronization when clearing
3377                  * PG_M even for PTEs generated via virtual memory maps,
3378                  * because the virtual kernel will invalidate the pmap
3379                  * entry when/if it needs to resynchronize the Modify bit.
3380                  */
3381                 if (bit & PG_RW)
3382                         pmap_inval_add(&info, pv->pv_pmap, pv->pv_va);
3383                 pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
3384 again:
3385                 pbits = *pte;
3386                 if (pbits & bit) {
3387                         if (bit == PG_RW) {
3388                                 if (pbits & PG_M) {
3389                                         vm_page_dirty(m);
3390                                         atomic_clear_long(pte, PG_M|PG_RW);
3391                                 } else {
3392                                         /*
3393                                          * The cpu may be trying to set PG_M
3394                                          * simultaniously with our clearing
3395                                          * of PG_RW.
3396                                          */
3397                                         if (!atomic_cmpset_long(pte, pbits,
3398                                                                pbits & ~PG_RW))
3399                                                 goto again;
3400                                 }
3401                         } else if (bit == PG_M) {
3402                                 /*
3403                                  * We could also clear PG_RW here to force
3404                                  * a fault on write to redetect PG_M for
3405                                  * virtual kernels, but it isn't necessary
3406                                  * since virtual kernels invalidate the pte 
3407                                  * when they clear the VPTE_M bit in their
3408                                  * virtual page tables.
3409                                  */
3410                                 atomic_clear_long(pte, PG_M);
3411                         } else {
3412                                 atomic_clear_long(pte, bit);
3413                         }
3414                 }
3415         }
3416         pmap_inval_flush(&info);
3417         crit_exit();
3418 }
3419
3420 /*
3421  *      pmap_page_protect:
3422  *
3423  *      Lower the permission for all mappings to a given page.
3424  */
3425 void
3426 pmap_page_protect(vm_page_t m, vm_prot_t prot)
3427 {
3428         /* JG NX support? */
3429         if ((prot & VM_PROT_WRITE) == 0) {
3430                 if (prot & (VM_PROT_READ | VM_PROT_EXECUTE)) {
3431                         pmap_clearbit(m, PG_RW);
3432                         vm_page_flag_clear(m, PG_WRITEABLE);
3433                 } else {
3434                         pmap_remove_all(m);
3435                 }
3436         }
3437 }
3438
3439 vm_paddr_t
3440 pmap_phys_address(vm_pindex_t ppn)
3441 {
3442         return (x86_64_ptob(ppn));
3443 }
3444
3445 /*
3446  *      pmap_ts_referenced:
3447  *
3448  *      Return a count of reference bits for a page, clearing those bits.
3449  *      It is not necessary for every reference bit to be cleared, but it
3450  *      is necessary that 0 only be returned when there are truly no
3451  *      reference bits set.
3452  *
3453  *      XXX: The exact number of bits to check and clear is a matter that
3454  *      should be tested and standardized at some point in the future for
3455  *      optimal aging of shared pages.
3456  */
3457 int
3458 pmap_ts_referenced(vm_page_t m)
3459 {
3460         pv_entry_t pv, pvf, pvn;
3461         pt_entry_t *pte;
3462         int rtval = 0;
3463
3464         if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
3465                 return (rtval);
3466
3467         crit_enter();
3468
3469         if ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
3470
3471                 pvf = pv;
3472
3473                 do {
3474                         pvn = TAILQ_NEXT(pv, pv_list);
3475
3476                         crit_enter();
3477                         TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
3478                         TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
3479                         crit_exit();
3480
3481                         if (!pmap_track_modified(pv->pv_va))
3482                                 continue;
3483
3484                         pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
3485
3486                         if (pte && (*pte & PG_A)) {
3487 #ifdef SMP
3488                                 atomic_clear_long(pte, PG_A);
3489 #else
3490                                 atomic_clear_long_nonlocked(pte, PG_A);
3491 #endif
3492                                 rtval++;
3493                                 if (rtval > 4) {
3494                                         break;
3495                                 }
3496                         }
3497                 } while ((pv = pvn) != NULL && pv != pvf);
3498         }
3499         crit_exit();
3500
3501         return (rtval);
3502 }
3503
3504 /*
3505  *      pmap_is_modified:
3506  *
3507  *      Return whether or not the specified physical page was modified
3508  *      in any physical maps.
3509  */
3510 boolean_t
3511 pmap_is_modified(vm_page_t m)
3512 {
3513         return pmap_testbit(m, PG_M);
3514 }
3515
3516 /*
3517  *      Clear the modify bits on the specified physical page.
3518  */
3519 void
3520 pmap_clear_modify(vm_page_t m)
3521 {
3522         pmap_clearbit(m, PG_M);
3523 }
3524
3525 /*
3526  *      pmap_clear_reference:
3527  *
3528  *      Clear the reference bit on the specified physical page.
3529  */
3530 void
3531 pmap_clear_reference(vm_page_t m)
3532 {
3533         pmap_clearbit(m, PG_A);
3534 }
3535
3536 /*
3537  * Miscellaneous support routines follow
3538  */
3539
3540 static
3541 void
3542 i386_protection_init(void)
3543 {
3544         int *kp, prot;
3545
3546         /* JG NX support may go here; No VM_PROT_EXECUTE ==> set NX bit  */
3547         kp = protection_codes;
3548         for (prot = 0; prot < 8; prot++) {
3549                 switch (prot) {
3550                 case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_NONE:
3551                         /*
3552                          * Read access is also 0. There isn't any execute bit,
3553                          * so just make it readable.
3554                          */
3555                 case VM_PROT_READ | VM_PROT_NONE | VM_PROT_NONE:
3556                 case VM_PROT_READ | VM_PROT_NONE | VM_PROT_EXECUTE:
3557                 case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_EXECUTE:
3558                         *kp++ = 0;
3559                         break;
3560                 case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_NONE:
3561                 case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_EXECUTE:
3562                 case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_NONE:
3563                 case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE:
3564                         *kp++ = PG_RW;
3565                         break;
3566                 }
3567         }
3568 }
3569
3570 /*
3571  * Map a set of physical memory pages into the kernel virtual
3572  * address space. Return a pointer to where it is mapped. This
3573  * routine is intended to be used for mapping device memory,
3574  * NOT real memory.
3575  *
3576  * NOTE: we can't use pgeflag unless we invalidate the pages one at
3577  * a time.
3578  */
3579 void *
3580 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
3581 {
3582         vm_offset_t va, tmpva, offset;
3583         pt_entry_t *pte;
3584
3585         offset = pa & PAGE_MASK;
3586         size = roundup(offset + size, PAGE_SIZE);
3587
3588         va = kmem_alloc_nofault(&kernel_map, size);
3589         if (va == 0)
3590                 panic("pmap_mapdev: Couldn't alloc kernel virtual memory");
3591
3592         pa = pa & ~PAGE_MASK;
3593         for (tmpva = va; size > 0;) {
3594                 pte = vtopte(tmpva);
3595                 *pte = pa | PG_RW | PG_V; /* | pgeflag; */
3596                 size -= PAGE_SIZE;
3597                 tmpva += PAGE_SIZE;
3598                 pa += PAGE_SIZE;
3599         }
3600         cpu_invltlb();
3601         smp_invltlb();
3602
3603         return ((void *)(va + offset));
3604 }
3605
3606 void *
3607 pmap_mapdev_uncacheable(vm_paddr_t pa, vm_size_t size)
3608 {
3609         vm_offset_t va, tmpva, offset;
3610         pt_entry_t *pte;
3611
3612         offset = pa & PAGE_MASK;
3613         size = roundup(offset + size, PAGE_SIZE);
3614
3615         va = kmem_alloc_nofault(&kernel_map, size);
3616         if (va == 0)
3617                 panic("pmap_mapdev: Couldn't alloc kernel virtual memory");
3618
3619         pa = pa & ~PAGE_MASK;
3620         for (tmpva = va; size > 0;) {
3621                 pte = vtopte(tmpva);
3622                 *pte = pa | PG_RW | PG_V | PG_N; /* | pgeflag; */
3623                 size -= PAGE_SIZE;
3624                 tmpva += PAGE_SIZE;
3625                 pa += PAGE_SIZE;
3626         }
3627         cpu_invltlb();
3628         smp_invltlb();
3629
3630         return ((void *)(va + offset));
3631 }
3632
3633 void
3634 pmap_unmapdev(vm_offset_t va, vm_size_t size)
3635 {
3636         vm_offset_t base, offset;
3637
3638         base = va & ~PAGE_MASK;
3639         offset = va & PAGE_MASK;
3640         size = roundup(offset + size, PAGE_SIZE);
3641         pmap_qremove(va, size >> PAGE_SHIFT);
3642         kmem_free(&kernel_map, base, size);
3643 }
3644
3645 /*
3646  * perform the pmap work for mincore
3647  */
3648 int
3649 pmap_mincore(pmap_t pmap, vm_offset_t addr)
3650 {
3651         pt_entry_t *ptep, pte;
3652         vm_page_t m;
3653         int val = 0;
3654         
3655         ptep = pmap_pte(pmap, addr);
3656         if (ptep == 0) {
3657                 return 0;
3658         }
3659
3660         if ((pte = *ptep) != 0) {
3661                 vm_offset_t pa;
3662
3663                 val = MINCORE_INCORE;
3664                 if ((pte & PG_MANAGED) == 0)
3665                         return val;
3666
3667                 pa = pte & PG_FRAME;
3668
3669                 m = PHYS_TO_VM_PAGE(pa);
3670
3671                 /*
3672                  * Modified by us
3673                  */
3674                 if (pte & PG_M)
3675                         val |= MINCORE_MODIFIED|MINCORE_MODIFIED_OTHER;
3676                 /*
3677                  * Modified by someone
3678                  */
3679                 else if (m->dirty || pmap_is_modified(m))
3680                         val |= MINCORE_MODIFIED_OTHER;
3681                 /*
3682                  * Referenced by us
3683                  */
3684                 if (pte & PG_A)
3685                         val |= MINCORE_REFERENCED|MINCORE_REFERENCED_OTHER;
3686
3687                 /*
3688                  * Referenced by someone
3689                  */
3690                 else if ((m->flags & PG_REFERENCED) || pmap_ts_referenced(m)) {
3691                         val |= MINCORE_REFERENCED_OTHER;
3692                         vm_page_flag_set(m, PG_REFERENCED);
3693                 }
3694         } 
3695         return val;
3696 }
3697
3698 /*
3699  * Replace p->p_vmspace with a new one.  If adjrefs is non-zero the new
3700  * vmspace will be ref'd and the old one will be deref'd.
3701  *
3702  * The vmspace for all lwps associated with the process will be adjusted
3703  * and cr3 will be reloaded if any lwp is the current lwp.
3704  */
3705 void
3706 pmap_replacevm(struct proc *p, struct vmspace *newvm, int adjrefs)
3707 {
3708         struct vmspace *oldvm;
3709         struct lwp *lp;
3710
3711         crit_enter();
3712         oldvm = p->p_vmspace;
3713         if (oldvm != newvm) {
3714                 p->p_vmspace = newvm;
3715                 KKASSERT(p->p_nthreads == 1);
3716                 lp = RB_ROOT(&p->p_lwp_tree);
3717                 pmap_setlwpvm(lp, newvm);
3718                 if (adjrefs) {
3719                         sysref_get(&newvm->vm_sysref);
3720                         sysref_put(&oldvm->vm_sysref);
3721                 }
3722         }
3723         crit_exit();
3724 }
3725
3726 /*
3727  * Set the vmspace for a LWP.  The vmspace is almost universally set the
3728  * same as the process vmspace, but virtual kernels need to swap out contexts
3729  * on a per-lwp basis.
3730  */
3731 void
3732 pmap_setlwpvm(struct lwp *lp, struct vmspace *newvm)
3733 {
3734         struct vmspace *oldvm;
3735         struct pmap *pmap;
3736
3737         crit_enter();
3738         oldvm = lp->lwp_vmspace;
3739
3740         if (oldvm != newvm) {
3741                 lp->lwp_vmspace = newvm;
3742                 if (curthread->td_lwp == lp) {
3743                         pmap = vmspace_pmap(newvm);
3744 #if defined(SMP)
3745                         atomic_set_int(&pmap->pm_active, 1 << mycpu->gd_cpuid);
3746 #else
3747                         pmap->pm_active |= 1;
3748 #endif
3749 #if defined(SWTCH_OPTIM_STATS)
3750                         tlb_flush_count++;
3751 #endif
3752                         curthread->td_pcb->pcb_cr3 = vtophys(pmap->pm_pml4);
3753                         load_cr3(curthread->td_pcb->pcb_cr3);
3754                         pmap = vmspace_pmap(oldvm);
3755 #if defined(SMP)
3756                         atomic_clear_int(&pmap->pm_active,
3757                                           1 << mycpu->gd_cpuid);
3758 #else
3759                         pmap->pm_active &= ~1;
3760 #endif
3761                 }
3762         }
3763         crit_exit();
3764 }
3765
3766 vm_offset_t
3767 pmap_addr_hint(vm_object_t obj, vm_offset_t addr, vm_size_t size)
3768 {
3769
3770         if ((obj == NULL) || (size < NBPDR) || (obj->type != OBJT_DEVICE)) {
3771                 return addr;
3772         }
3773
3774         addr = (addr + (NBPDR - 1)) & ~(NBPDR - 1);
3775         return addr;
3776 }
3777
3778
3779 #if defined(DEBUG)
3780
3781 static void     pads (pmap_t pm);
3782 void            pmap_pvdump (vm_paddr_t pa);
3783
3784 /* print address space of pmap*/
3785 static
3786 void
3787 pads(pmap_t pm)
3788 {
3789         vm_offset_t va;
3790         unsigned i, j;
3791         pt_entry_t *ptep;
3792
3793         if (pm == &kernel_pmap)
3794                 return;
3795         crit_enter();
3796         for (i = 0; i < NPDEPG; i++) {
3797                 ;
3798         }
3799         crit_exit();
3800
3801 }
3802
3803 void
3804 pmap_pvdump(vm_paddr_t pa)
3805 {
3806         pv_entry_t pv;
3807         vm_page_t m;
3808
3809         kprintf("pa %08llx", (long long)pa);
3810         m = PHYS_TO_VM_PAGE(pa);
3811         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
3812 #ifdef used_to_be
3813                 kprintf(" -> pmap %p, va %x, flags %x",
3814                     (void *)pv->pv_pmap, pv->pv_va, pv->pv_flags);
3815 #endif
3816                 kprintf(" -> pmap %p, va %x", (void *)pv->pv_pmap, pv->pv_va);
3817                 pads(pv->pv_pmap);
3818         }
3819         kprintf(" ");
3820 }
3821 #endif