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