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