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