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