]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/arm/arm/pmap-v6.c
ARM: After removal of old pmap-v6 code, rename pmap-v6-new.c to pmap-v6.c.
[FreeBSD/FreeBSD.git] / sys / arm / arm / pmap-v6.c
1 /*-
2  * Copyright (c) 1991 Regents of the University of California.
3  * Copyright (c) 1994 John S. Dyson
4  * Copyright (c) 1994 David Greenman
5  * Copyright (c) 2005-2010 Alan L. Cox <alc@cs.rice.edu>
6  * Copyright (c) 2014 Svatopluk Kraus <onwahe@gmail.com>
7  * Copyright (c) 2014 Michal Meloun <meloun@miracle.cz>
8  * All rights reserved.
9  *
10  * This code is derived from software contributed to Berkeley by
11  * the Systems Programming Group of the University of Utah Computer
12  * Science Department and William Jolitz of UUNET Technologies Inc.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  * 3. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *      from:   @(#)pmap.c      7.7 (Berkeley)  5/12/91
39  */
40 /*-
41  * Copyright (c) 2003 Networks Associates Technology, Inc.
42  * All rights reserved.
43  *
44  * This software was developed for the FreeBSD Project by Jake Burkholder,
45  * Safeport Network Services, and Network Associates Laboratories, the
46  * Security Research Division of Network Associates, Inc. under
47  * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA
48  * CHATS research program.
49  *
50  * Redistribution and use in source and binary forms, with or without
51  * modification, are permitted provided that the following conditions
52  * are met:
53  * 1. Redistributions of source code must retain the above copyright
54  *    notice, this list of conditions and the following disclaimer.
55  * 2. Redistributions in binary form must reproduce the above copyright
56  *    notice, this list of conditions and the following disclaimer in the
57  *    documentation and/or other materials provided with the distribution.
58  *
59  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
60  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
63  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69  * SUCH DAMAGE.
70  */
71
72 #include <sys/cdefs.h>
73 __FBSDID("$FreeBSD$");
74
75 /*
76  *      Manages physical address maps.
77  *
78  *      Since the information managed by this module is
79  *      also stored by the logical address mapping module,
80  *      this module may throw away valid virtual-to-physical
81  *      mappings at almost any time.  However, invalidations
82  *      of virtual-to-physical mappings must be done as
83  *      requested.
84  *
85  *      In order to cope with hardware architectures which
86  *      make virtual-to-physical map invalidates expensive,
87  *      this module may delay invalidate or reduced protection
88  *      operations until such time as they are actually
89  *      necessary.  This module is given full information as
90  *      to which processors are currently using which maps,
91  *      and to when physical maps must be made correct.
92  */
93
94 #include "opt_vm.h"
95 #include "opt_pmap.h"
96 #include "opt_ddb.h"
97
98 #include <sys/param.h>
99 #include <sys/systm.h>
100 #include <sys/kernel.h>
101 #include <sys/ktr.h>
102 #include <sys/lock.h>
103 #include <sys/proc.h>
104 #include <sys/rwlock.h>
105 #include <sys/malloc.h>
106 #include <sys/vmmeter.h>
107 #include <sys/malloc.h>
108 #include <sys/mman.h>
109 #include <sys/sf_buf.h>
110 #include <sys/smp.h>
111 #include <sys/sched.h>
112 #include <sys/sysctl.h>
113 #ifdef SMP
114 #include <sys/smp.h>
115 #else
116 #include <sys/cpuset.h>
117 #endif
118
119 #ifdef DDB
120 #include <ddb/ddb.h>
121 #endif
122
123 #include <machine/physmem.h>
124 #include <machine/vmparam.h>
125
126 #include <vm/vm.h>
127 #include <vm/uma.h>
128 #include <vm/pmap.h>
129 #include <vm/vm_param.h>
130 #include <vm/vm_kern.h>
131 #include <vm/vm_object.h>
132 #include <vm/vm_map.h>
133 #include <vm/vm_page.h>
134 #include <vm/vm_pageout.h>
135 #include <vm/vm_phys.h>
136 #include <vm/vm_extern.h>
137 #include <vm/vm_reserv.h>
138 #include <sys/lock.h>
139 #include <sys/mutex.h>
140
141 #include <machine/md_var.h>
142 #include <machine/pmap_var.h>
143 #include <machine/cpu.h>
144 #include <machine/cpu-v6.h>
145 #include <machine/pcb.h>
146 #include <machine/sf_buf.h>
147 #ifdef SMP
148 #include <machine/smp.h>
149 #endif
150
151 #ifndef PMAP_SHPGPERPROC
152 #define PMAP_SHPGPERPROC 200
153 #endif
154
155 #ifndef DIAGNOSTIC
156 #define PMAP_INLINE     __inline
157 #else
158 #define PMAP_INLINE
159 #endif
160
161 #ifdef PMAP_DEBUG
162 static void pmap_zero_page_check(vm_page_t m);
163 void pmap_debug(int level);
164 int pmap_pid_dump(int pid);
165
166 #define PDEBUG(_lev_,_stat_) \
167         if (pmap_debug_level >= (_lev_)) \
168                 ((_stat_))
169 #define dprintf printf
170 int pmap_debug_level = 1;
171 #else   /* PMAP_DEBUG */
172 #define PDEBUG(_lev_,_stat_) /* Nothing */
173 #define dprintf(x, arg...)
174 #endif  /* PMAP_DEBUG */
175
176 /*
177  *  Level 2 page tables map definion ('max' is excluded).
178  */
179
180 #define PT2V_MIN_ADDRESS        ((vm_offset_t)PT2MAP)
181 #define PT2V_MAX_ADDRESS        ((vm_offset_t)PT2MAP + PT2MAP_SIZE)
182
183 #define UPT2V_MIN_ADDRESS       ((vm_offset_t)PT2MAP)
184 #define UPT2V_MAX_ADDRESS \
185     ((vm_offset_t)(PT2MAP + (KERNBASE >> PT2MAP_SHIFT)))
186
187 /*
188  *  Promotion to a 1MB (PTE1) page mapping requires that the corresponding
189  *  4KB (PTE2) page mappings have identical settings for the following fields:
190  */
191 #define PTE2_PROMOTE    (PTE2_V | PTE2_A | PTE2_NM | PTE2_S | PTE2_NG | \
192                          PTE2_NX | PTE2_RO | PTE2_U | PTE2_W |          \
193                          PTE2_ATTR_MASK)
194
195 #define PTE1_PROMOTE    (PTE1_V | PTE1_A | PTE1_NM | PTE1_S | PTE1_NG | \
196                          PTE1_NX | PTE1_RO | PTE1_U | PTE1_W |          \
197                          PTE1_ATTR_MASK)
198
199 #define ATTR_TO_L1(l2_attr)     ((((l2_attr) & L2_TEX0) ? L1_S_TEX0 : 0) | \
200                                  (((l2_attr) & L2_C)    ? L1_S_C    : 0) | \
201                                  (((l2_attr) & L2_B)    ? L1_S_B    : 0) | \
202                                  (((l2_attr) & PTE2_A)  ? PTE1_A    : 0) | \
203                                  (((l2_attr) & PTE2_NM) ? PTE1_NM   : 0) | \
204                                  (((l2_attr) & PTE2_S)  ? PTE1_S    : 0) | \
205                                  (((l2_attr) & PTE2_NG) ? PTE1_NG   : 0) | \
206                                  (((l2_attr) & PTE2_NX) ? PTE1_NX   : 0) | \
207                                  (((l2_attr) & PTE2_RO) ? PTE1_RO   : 0) | \
208                                  (((l2_attr) & PTE2_U)  ? PTE1_U    : 0) | \
209                                  (((l2_attr) & PTE2_W)  ? PTE1_W    : 0))
210
211 #define ATTR_TO_L2(l1_attr)     ((((l1_attr) & L1_S_TEX0) ? L2_TEX0 : 0) | \
212                                  (((l1_attr) & L1_S_C)    ? L2_C    : 0) | \
213                                  (((l1_attr) & L1_S_B)    ? L2_B    : 0) | \
214                                  (((l1_attr) & PTE1_A)    ? PTE2_A  : 0) | \
215                                  (((l1_attr) & PTE1_NM)   ? PTE2_NM : 0) | \
216                                  (((l1_attr) & PTE1_S)    ? PTE2_S  : 0) | \
217                                  (((l1_attr) & PTE1_NG)   ? PTE2_NG : 0) | \
218                                  (((l1_attr) & PTE1_NX)   ? PTE2_NX : 0) | \
219                                  (((l1_attr) & PTE1_RO)   ? PTE2_RO : 0) | \
220                                  (((l1_attr) & PTE1_U)    ? PTE2_U  : 0) | \
221                                  (((l1_attr) & PTE1_W)    ? PTE2_W  : 0))
222
223 /*
224  *  PTE2 descriptors creation macros.
225  */
226 #define PTE2_KPT(pa)    PTE2_KERN(pa, PTE2_AP_KRW, pt_memattr)
227 #define PTE2_KPT_NG(pa) PTE2_KERN_NG(pa, PTE2_AP_KRW, pt_memattr)
228
229 #define PTE2_KRW(pa)    PTE2_KERN(pa, PTE2_AP_KRW, PTE2_ATTR_NORMAL)
230 #define PTE2_KRO(pa)    PTE2_KERN(pa, PTE2_AP_KR,  PTE2_ATTR_NORMAL)
231
232 #define PV_STATS
233 #ifdef PV_STATS
234 #define PV_STAT(x)      do { x ; } while (0)
235 #else
236 #define PV_STAT(x)      do { } while (0)
237 #endif
238
239 /*
240  *  The boot_pt1 is used temporary in very early boot stage as L1 page table.
241  *  We can init many things with no memory allocation thanks to its static
242  *  allocation and this brings two main advantages:
243  *  (1) other cores can be started very simply,
244  *  (2) various boot loaders can be supported as its arguments can be processed
245  *      in virtual address space and can be moved to safe location before
246  *      first allocation happened.
247  *  Only disadvantage is that boot_pt1 is used only in very early boot stage.
248  *  However, the table is uninitialized and so lays in bss. Therefore kernel
249  *  image size is not influenced.
250  *
251  *  QQQ: In the future, maybe, boot_pt1 can be used for soft reset and
252  *       CPU suspend/resume game.
253  */
254 extern pt1_entry_t boot_pt1[];
255
256 vm_paddr_t base_pt1;
257 pt1_entry_t *kern_pt1;
258 pt2_entry_t *kern_pt2tab;
259 pt2_entry_t *PT2MAP;
260
261 static uint32_t ttb_flags;
262 static vm_memattr_t pt_memattr;
263 ttb_entry_t pmap_kern_ttb;
264
265 /* XXX use converion function*/
266 #define PTE2_ATTR_NORMAL        VM_MEMATTR_DEFAULT
267 #define PTE1_ATTR_NORMAL        ATTR_TO_L1(PTE2_ATTR_NORMAL)
268
269 struct pmap kernel_pmap_store;
270 LIST_HEAD(pmaplist, pmap);
271 static struct pmaplist allpmaps;
272 static struct mtx allpmaps_lock;
273
274 vm_offset_t virtual_avail;      /* VA of first avail page (after kernel bss) */
275 vm_offset_t virtual_end;        /* VA of last avail page (end of kernel AS) */
276
277 static vm_offset_t kernel_vm_end_new;
278 vm_offset_t kernel_vm_end = KERNBASE + NKPT2PG * NPT2_IN_PG * PTE1_SIZE;
279 vm_offset_t vm_max_kernel_address;
280 vm_paddr_t kernel_l1pa;
281
282 static struct rwlock __aligned(CACHE_LINE_SIZE) pvh_global_lock;
283
284 /*
285  *  Data for the pv entry allocation mechanism
286  */
287 static TAILQ_HEAD(pch, pv_chunk) pv_chunks = TAILQ_HEAD_INITIALIZER(pv_chunks);
288 static int pv_entry_count = 0, pv_entry_max = 0, pv_entry_high_water = 0;
289 static struct md_page *pv_table; /* XXX: Is it used only the list in md_page? */
290 static int shpgperproc = PMAP_SHPGPERPROC;
291
292 struct pv_chunk *pv_chunkbase;          /* KVA block for pv_chunks */
293 int pv_maxchunks;                       /* How many chunks we have KVA for */
294 vm_offset_t pv_vafree;                  /* freelist stored in the PTE */
295
296 vm_paddr_t first_managed_pa;
297 #define pa_to_pvh(pa)   (&pv_table[pte1_index(pa - first_managed_pa)])
298
299 /*
300  *  All those kernel PT submaps that BSD is so fond of
301  */
302 struct sysmaps {
303         struct  mtx lock;
304         pt2_entry_t *CMAP1;
305         pt2_entry_t *CMAP2;
306         pt2_entry_t *CMAP3;
307         caddr_t CADDR1;
308         caddr_t CADDR2;
309         caddr_t CADDR3;
310 };
311 static struct sysmaps sysmaps_pcpu[MAXCPU];
312 static pt2_entry_t *CMAP3;
313 static caddr_t CADDR3;
314 caddr_t _tmppt = 0;
315
316 struct msgbuf *msgbufp = 0; /* XXX move it to machdep.c */
317
318 /*
319  *  Crashdump maps.
320  */
321 static caddr_t crashdumpmap;
322
323 static pt2_entry_t *PMAP1 = 0, *PMAP2;
324 static pt2_entry_t *PADDR1 = 0, *PADDR2;
325 #ifdef DDB
326 static pt2_entry_t *PMAP3;
327 static pt2_entry_t *PADDR3;
328 static int PMAP3cpu __unused; /* for SMP only */
329 #endif
330 #ifdef SMP
331 static int PMAP1cpu;
332 static int PMAP1changedcpu;
333 SYSCTL_INT(_debug, OID_AUTO, PMAP1changedcpu, CTLFLAG_RD,
334     &PMAP1changedcpu, 0,
335     "Number of times pmap_pte2_quick changed CPU with same PMAP1");
336 #endif
337 static int PMAP1changed;
338 SYSCTL_INT(_debug, OID_AUTO, PMAP1changed, CTLFLAG_RD,
339     &PMAP1changed, 0,
340     "Number of times pmap_pte2_quick changed PMAP1");
341 static int PMAP1unchanged;
342 SYSCTL_INT(_debug, OID_AUTO, PMAP1unchanged, CTLFLAG_RD,
343     &PMAP1unchanged, 0,
344     "Number of times pmap_pte2_quick didn't change PMAP1");
345 static struct mtx PMAP2mutex;
346
347 static __inline void pt2_wirecount_init(vm_page_t m);
348 static boolean_t pmap_demote_pte1(pmap_t pmap, pt1_entry_t *pte1p,
349     vm_offset_t va);
350 void cache_icache_sync_fresh(vm_offset_t va, vm_paddr_t pa, vm_size_t size);
351
352 /*
353  *  Function to set the debug level of the pmap code.
354  */
355 #ifdef PMAP_DEBUG
356 void
357 pmap_debug(int level)
358 {
359
360         pmap_debug_level = level;
361         dprintf("pmap_debug: level=%d\n", pmap_debug_level);
362 }
363 #endif /* PMAP_DEBUG */
364
365 /*
366  *  This table must corespond with memory attribute configuration in vm.h.
367  *  First entry is used for normal system mapping.
368  *
369  *  Device memory is always marked as shared.
370  *  Normal memory is shared only in SMP .
371  *  Not outer shareable bits are not used yet.
372  *  Class 6 cannot be used on ARM11.
373  */
374 #define TEXDEF_TYPE_SHIFT       0
375 #define TEXDEF_TYPE_MASK        0x3
376 #define TEXDEF_INNER_SHIFT      2
377 #define TEXDEF_INNER_MASK       0x3
378 #define TEXDEF_OUTER_SHIFT      4
379 #define TEXDEF_OUTER_MASK       0x3
380 #define TEXDEF_NOS_SHIFT        6
381 #define TEXDEF_NOS_MASK         0x1
382
383 #define TEX(t, i, o, s)                         \
384                 ((t) << TEXDEF_TYPE_SHIFT) |    \
385                 ((i) << TEXDEF_INNER_SHIFT) |   \
386                 ((o) << TEXDEF_OUTER_SHIFT |    \
387                 ((s) << TEXDEF_NOS_SHIFT))
388
389 static uint32_t tex_class[8] = {
390 /*          type      inner cache outer cache */
391         TEX(PRRR_MEM, NMRR_WB_WA, NMRR_WB_WA, 0),  /* 0 - ATTR_WB_WA    */
392         TEX(PRRR_MEM, NMRR_NC,    NMRR_NC,    0),  /* 1 - ATTR_NOCACHE  */
393         TEX(PRRR_DEV, NMRR_NC,    NMRR_NC,    0),  /* 2 - ATTR_DEVICE   */
394         TEX(PRRR_SO,  NMRR_NC,    NMRR_NC,    0),  /* 3 - ATTR_SO       */
395         TEX(PRRR_MEM, NMRR_WT,    NMRR_WT,    0),  /* 4 - ATTR_WT       */
396         TEX(PRRR_MEM, NMRR_NC,    NMRR_NC,    0),  /* 5 - NOT USED YET  */
397         TEX(PRRR_MEM, NMRR_NC,    NMRR_NC,    0),  /* 6 - NOT USED YET  */
398         TEX(PRRR_MEM, NMRR_NC,    NMRR_NC,    0),  /* 7 - NOT USED YET  */
399 };
400 #undef TEX
401
402 /*
403  * Convert TEX definition entry to TTB flags.
404  */
405 static uint32_t
406 encode_ttb_flags(int idx)
407 {
408         uint32_t inner, outer, nos, reg;
409
410         inner = (tex_class[idx] >> TEXDEF_INNER_SHIFT) &
411                 TEXDEF_INNER_MASK;
412         outer = (tex_class[idx] >> TEXDEF_OUTER_SHIFT) &
413                 TEXDEF_OUTER_MASK;
414         nos = (tex_class[idx] >> TEXDEF_NOS_SHIFT) &
415                 TEXDEF_NOS_MASK;
416
417         reg = nos << 5;
418         reg |= outer << 3;
419         if (cpuinfo.coherent_walk)
420                 reg |= (inner & 0x1) << 6;
421         reg |= (inner & 0x2) >> 1;
422 #ifdef SMP
423         reg |= 1 << 1;
424 #endif
425         return reg;
426 }
427
428 /*
429  *  Set TEX remapping registers in current CPU.
430  */
431 void
432 pmap_set_tex(void)
433 {
434         uint32_t prrr, nmrr;
435         uint32_t type, inner, outer, nos;
436         int i;
437
438 #ifdef PMAP_PTE_NOCACHE
439         /* XXX fixme */
440         if (cpuinfo.coherent_walk) {
441                 pt_memattr = VM_MEMATTR_WB_WA;
442                 ttb_flags = encode_ttb_flags(0);
443         }
444         else {
445                 pt_memattr = VM_MEMATTR_NOCACHE;
446                 ttb_flags = encode_ttb_flags(1);
447         }
448 #else
449         pt_memattr = VM_MEMATTR_WB_WA;
450         ttb_flags = encode_ttb_flags(0);
451 #endif
452
453         prrr = 0;
454         nmrr = 0;
455
456         /* Build remapping register from TEX classes. */
457         for (i = 0; i < 8; i++) {
458                 type = (tex_class[i] >> TEXDEF_TYPE_SHIFT) &
459                         TEXDEF_TYPE_MASK;
460                 inner = (tex_class[i] >> TEXDEF_INNER_SHIFT) &
461                         TEXDEF_INNER_MASK;
462                 outer = (tex_class[i] >> TEXDEF_OUTER_SHIFT) &
463                         TEXDEF_OUTER_MASK;
464                 nos = (tex_class[i] >> TEXDEF_NOS_SHIFT) &
465                         TEXDEF_NOS_MASK;
466
467                 prrr |= type  << (i * 2);
468                 prrr |= nos   << (i + 24);
469                 nmrr |= inner << (i * 2);
470                 nmrr |= outer << (i * 2 + 16);
471         }
472         /* Add shareable bits for device memory. */
473         prrr |= PRRR_DS0 | PRRR_DS1;
474
475         /* Add shareable bits for normal memory in SMP case. */
476 #ifdef SMP
477         prrr |= PRRR_NS1;
478 #endif
479         cp15_prrr_set(prrr);
480         cp15_nmrr_set(nmrr);
481
482         /* Caches are disabled, so full TLB flush should be enough. */
483         tlb_flush_all_local();
484 }
485
486 /*
487  * KERNBASE must be multiple of NPT2_IN_PG * PTE1_SIZE. In other words,
488  * KERNBASE is mapped by first L2 page table in L2 page table page. It
489  * meets same constrain due to PT2MAP being placed just under KERNBASE.
490  */
491 CTASSERT((KERNBASE & (NPT2_IN_PG * PTE1_SIZE - 1)) == 0);
492 CTASSERT((KERNBASE - VM_MAXUSER_ADDRESS) >= PT2MAP_SIZE);
493
494 /*
495  *  In crazy dreams, PAGE_SIZE could be a multiple of PTE2_SIZE in general.
496  *  For now, anyhow, the following check must be fulfilled.
497  */
498 CTASSERT(PAGE_SIZE == PTE2_SIZE);
499 /*
500  *  We don't want to mess up MI code with all MMU and PMAP definitions,
501  *  so some things, which depend on other ones, are defined independently.
502  *  Now, it is time to check that we don't screw up something.
503  */
504 CTASSERT(PDRSHIFT == PTE1_SHIFT);
505 /*
506  *  Check L1 and L2 page table entries definitions consistency.
507  */
508 CTASSERT(NB_IN_PT1 == (sizeof(pt1_entry_t) * NPTE1_IN_PT1));
509 CTASSERT(NB_IN_PT2 == (sizeof(pt2_entry_t) * NPTE2_IN_PT2));
510 /*
511  *  Check L2 page tables page consistency.
512  */
513 CTASSERT(PAGE_SIZE == (NPT2_IN_PG * NB_IN_PT2));
514 CTASSERT((1 << PT2PG_SHIFT) == NPT2_IN_PG);
515 /*
516  *  Check PT2TAB consistency.
517  *  PT2TAB_ENTRIES is defined as a division of NPTE1_IN_PT1 by NPT2_IN_PG.
518  *  This should be done without remainder.
519  */
520 CTASSERT(NPTE1_IN_PT1 == (PT2TAB_ENTRIES * NPT2_IN_PG));
521
522 /*
523  *      A PT2MAP magic.
524  *
525  *  All level 2 page tables (PT2s) are mapped continuously and accordingly
526  *  into PT2MAP address space. As PT2 size is less than PAGE_SIZE, this can
527  *  be done only if PAGE_SIZE is a multiple of PT2 size. All PT2s in one page
528  *  must be used together, but not necessary at once. The first PT2 in a page
529  *  must map things on correctly aligned address and the others must follow
530  *  in right order.
531  */
532 #define NB_IN_PT2TAB    (PT2TAB_ENTRIES * sizeof(pt2_entry_t))
533 #define NPT2_IN_PT2TAB  (NB_IN_PT2TAB / NB_IN_PT2)
534 #define NPG_IN_PT2TAB   (NB_IN_PT2TAB / PAGE_SIZE)
535
536 /*
537  *  Check PT2TAB consistency.
538  *  NPT2_IN_PT2TAB is defined as a division of NB_IN_PT2TAB by NB_IN_PT2.
539  *  NPG_IN_PT2TAB is defined as a division of NB_IN_PT2TAB by PAGE_SIZE.
540  *  The both should be done without remainder.
541  */
542 CTASSERT(NB_IN_PT2TAB == (NPT2_IN_PT2TAB * NB_IN_PT2));
543 CTASSERT(NB_IN_PT2TAB == (NPG_IN_PT2TAB * PAGE_SIZE));
544 /*
545  *  The implementation was made general, however, with the assumption
546  *  bellow in mind. In case of another value of NPG_IN_PT2TAB,
547  *  the code should be once more rechecked.
548  */
549 CTASSERT(NPG_IN_PT2TAB == 1);
550
551 /*
552  *  Get offset of PT2 in a page
553  *  associated with given PT1 index.
554  */
555 static __inline u_int
556 page_pt2off(u_int pt1_idx)
557 {
558
559         return ((pt1_idx & PT2PG_MASK) * NB_IN_PT2);
560 }
561
562 /*
563  *  Get physical address of PT2
564  *  associated with given PT2s page and PT1 index.
565  */
566 static __inline vm_paddr_t
567 page_pt2pa(vm_paddr_t pgpa, u_int pt1_idx)
568 {
569
570         return (pgpa + page_pt2off(pt1_idx));
571 }
572
573 /*
574  *  Get first entry of PT2
575  *  associated with given PT2s page and PT1 index.
576  */
577 static __inline pt2_entry_t *
578 page_pt2(vm_offset_t pgva, u_int pt1_idx)
579 {
580
581         return ((pt2_entry_t *)(pgva + page_pt2off(pt1_idx)));
582 }
583
584 /*
585  *  Get virtual address of PT2s page (mapped in PT2MAP)
586  *  which holds PT2 which holds entry which maps given virtual address.
587  */
588 static __inline vm_offset_t
589 pt2map_pt2pg(vm_offset_t va)
590 {
591
592         va &= ~(NPT2_IN_PG * PTE1_SIZE - 1);
593         return ((vm_offset_t)pt2map_entry(va));
594 }
595
596 /*****************************************************************************
597  *
598  *     THREE pmap initialization milestones exist:
599  *
600  *  locore.S
601  *    -> fundamental init (including MMU) in ASM
602  *
603  *  initarm()
604  *    -> fundamental init continues in C
605  *    -> first available physical address is known
606  *
607  *    pmap_bootstrap_prepare() -> FIRST PMAP MILESTONE (first epoch begins)
608  *      -> basic (safe) interface for physical address allocation is made
609  *      -> basic (safe) interface for virtual mapping is made
610  *      -> limited not SMP coherent work is possible
611  *
612  *    -> more fundamental init continues in C
613  *    -> locks and some more things are available
614  *    -> all fundamental allocations and mappings are done
615  *
616  *    pmap_bootstrap() -> SECOND PMAP MILESTONE (second epoch begins)
617  *      -> phys_avail[] and virtual_avail is set
618  *      -> control is passed to vm subsystem
619  *      -> physical and virtual address allocation are off limit
620  *      -> low level mapping functions, some SMP coherent,
621  *         are available, which cannot be used before vm subsystem
622  *         is being inited
623  *
624  *  mi_startup()
625  *    -> vm subsystem is being inited
626  *
627  *      pmap_init() -> THIRD PMAP MILESTONE (third epoch begins)
628  *        -> pmap is fully inited
629  *
630  *****************************************************************************/
631
632 /*****************************************************************************
633  *
634  *      PMAP first stage initialization and utility functions
635  *      for pre-bootstrap epoch.
636  *
637  *  After pmap_bootstrap_prepare() is called, the following functions
638  *  can be used:
639  *
640  *  (1) strictly only for this stage functions for physical page allocations,
641  *      virtual space allocations, and mappings:
642  *
643  *  vm_paddr_t pmap_preboot_get_pages(u_int num);
644  *  void pmap_preboot_map_pages(vm_paddr_t pa, vm_offset_t va, u_int num);
645  *  vm_offset_t pmap_preboot_reserve_pages(u_int num);
646  *  vm_offset_t pmap_preboot_get_vpages(u_int num);
647  *  void pmap_preboot_map_attr(vm_paddr_t pa, vm_offset_t va, vm_size_t size,
648  *      int prot, int attr);
649  *
650  *  (2) for all stages:
651  *
652  *  vm_paddr_t pmap_kextract(vm_offset_t va);
653  *
654  *  NOTE: This is not SMP coherent stage.
655  *
656  *****************************************************************************/
657
658 #define KERNEL_P2V(pa) \
659     ((vm_offset_t)((pa) - arm_physmem_kernaddr + KERNVIRTADDR))
660 #define KERNEL_V2P(va) \
661     ((vm_paddr_t)((va) - KERNVIRTADDR + arm_physmem_kernaddr))
662
663 static vm_paddr_t last_paddr;
664
665 /*
666  *  Pre-bootstrap epoch page allocator.
667  */
668 vm_paddr_t
669 pmap_preboot_get_pages(u_int num)
670 {
671         vm_paddr_t ret;
672
673         ret = last_paddr;
674         last_paddr += num * PAGE_SIZE;
675
676         return (ret);
677 }
678
679 /*
680  *      The fundamental initalization of PMAP stuff.
681  *
682  *  Some things already happened in locore.S and some things could happen
683  *  before pmap_bootstrap_prepare() is called, so let's recall what is done:
684  *  1. Caches are disabled.
685  *  2. We are running on virtual addresses already with 'boot_pt1'
686  *     as L1 page table.
687  *  3. So far, all virtual addresses can be converted to physical ones and
688  *     vice versa by the following macros:
689  *       KERNEL_P2V(pa) .... physical to virtual ones,
690  *       KERNEL_V2P(va) .... virtual to physical ones.
691  *
692  *  What is done herein:
693  *  1. The 'boot_pt1' is replaced by real kernel L1 page table 'kern_pt1'.
694  *  2. PT2MAP magic is brought to live.
695  *  3. Basic preboot functions for page allocations and mappings can be used.
696  *  4. Everything is prepared for L1 cache enabling.
697  *
698  *  Variations:
699  *  1. To use second TTB register, so kernel and users page tables will be
700  *     separated. This way process forking - pmap_pinit() - could be faster,
701  *     it saves physical pages and KVA per a process, and it's simple change.
702  *     However, it will lead, due to hardware matter, to the following:
703  *     (a) 2G space for kernel and 2G space for users.
704  *     (b) 1G space for kernel in low addresses and 3G for users above it.
705  *     A question is: Is the case (b) really an option? Note that case (b)
706  *     does save neither physical memory and KVA.
707  */
708 void
709 pmap_bootstrap_prepare(vm_paddr_t last)
710 {
711         vm_paddr_t pt2pg_pa, pt2tab_pa, pa, size;
712         vm_offset_t pt2pg_va;
713         pt1_entry_t *pte1p;
714         pt2_entry_t *pte2p;
715         u_int i;
716         uint32_t actlr_mask, actlr_set;
717
718         /*
719          * Now, we are going to make real kernel mapping. Note that we are
720          * already running on some mapping made in locore.S and we expect
721          * that it's large enough to ensure nofault access to physical memory
722          * allocated herein before switch.
723          *
724          * As kernel image and everything needed before are and will be mapped
725          * by section mappings, we align last physical address to PTE1_SIZE.
726          */
727         last_paddr = pte1_roundup(last);
728
729         /*
730          * Allocate and zero page(s) for kernel L1 page table.
731          *
732          * Note that it's first allocation on space which was PTE1_SIZE
733          * aligned and as such base_pt1 is aligned to NB_IN_PT1 too.
734          */
735         base_pt1 = pmap_preboot_get_pages(NPG_IN_PT1);
736         kern_pt1 = (pt1_entry_t *)KERNEL_P2V(base_pt1);
737         bzero((void*)kern_pt1, NB_IN_PT1);
738         pte1_sync_range(kern_pt1, NB_IN_PT1);
739
740         /* Allocate and zero page(s) for kernel PT2TAB. */
741         pt2tab_pa = pmap_preboot_get_pages(NPG_IN_PT2TAB);
742         kern_pt2tab = (pt2_entry_t *)KERNEL_P2V(pt2tab_pa);
743         bzero(kern_pt2tab, NB_IN_PT2TAB);
744         pte2_sync_range(kern_pt2tab, NB_IN_PT2TAB);
745
746         /* Allocate and zero page(s) for kernel L2 page tables. */
747         pt2pg_pa = pmap_preboot_get_pages(NKPT2PG);
748         pt2pg_va = KERNEL_P2V(pt2pg_pa);
749         size = NKPT2PG * PAGE_SIZE;
750         bzero((void*)pt2pg_va, size);
751         pte2_sync_range((pt2_entry_t *)pt2pg_va, size);
752
753         /*
754          * Add a physical memory segment (vm_phys_seg) corresponding to the
755          * preallocated pages for kernel L2 page tables so that vm_page
756          * structures representing these pages will be created. The vm_page
757          * structures are required for promotion of the corresponding kernel
758          * virtual addresses to section mappings.
759          */
760         vm_phys_add_seg(pt2tab_pa, pmap_preboot_get_pages(0));
761
762         /*
763          * Insert allocated L2 page table pages to PT2TAB and make
764          * link to all PT2s in L1 page table. See how kernel_vm_end
765          * is initialized.
766          *
767          * We play simple and safe. So every KVA will have underlaying
768          * L2 page table, even kernel image mapped by sections.
769          */
770         pte2p = kern_pt2tab_entry(KERNBASE);
771         for (pa = pt2pg_pa; pa < pt2pg_pa + size; pa += PTE2_SIZE)
772                 pt2tab_store(pte2p++, PTE2_KPT(pa));
773
774         pte1p = kern_pte1(KERNBASE);
775         for (pa = pt2pg_pa; pa < pt2pg_pa + size; pa += NB_IN_PT2)
776                 pte1_store(pte1p++, PTE1_LINK(pa));
777
778         /* Make section mappings for kernel. */
779         pte1p = kern_pte1(KERNBASE);
780         for (pa = KERNEL_V2P(KERNBASE); pa < last; pa += PTE1_SIZE)
781                 pte1_store(pte1p++, PTE1_KERN(pa, PTE1_AP_KRW,
782                     ATTR_TO_L1(PTE2_ATTR_WB_WA)));
783
784         /*
785          * Get free and aligned space for PT2MAP and make L1 page table links
786          * to L2 page tables held in PT2TAB.
787          *
788          * Note that pages holding PT2s are stored in PT2TAB as pt2_entry_t
789          * descriptors and PT2TAB page(s) itself is(are) used as PT2s. Thus
790          * each entry in PT2TAB maps all PT2s in a page. This implies that
791          * virtual address of PT2MAP must be aligned to NPT2_IN_PG * PTE1_SIZE.
792          */
793         PT2MAP = (pt2_entry_t *)(KERNBASE - PT2MAP_SIZE);
794         pte1p = kern_pte1((vm_offset_t)PT2MAP);
795         for (pa = pt2tab_pa, i = 0; i < NPT2_IN_PT2TAB; i++, pa += NB_IN_PT2) {
796                 pte1_store(pte1p++, PTE1_LINK(pa));
797         }
798
799         /*
800          * Store PT2TAB in PT2TAB itself, i.e. self reference mapping.
801          * Each pmap will hold own PT2TAB, so the mapping should be not global.
802          */
803         pte2p = kern_pt2tab_entry((vm_offset_t)PT2MAP);
804         for (pa = pt2tab_pa, i = 0; i < NPG_IN_PT2TAB; i++, pa += PTE2_SIZE) {
805                 pt2tab_store(pte2p++, PTE2_KPT_NG(pa));
806         }
807
808         /*
809          * Choose correct L2 page table and make mappings for allocations
810          * made herein which replaces temporary locore.S mappings after a while.
811          * Note that PT2MAP cannot be used until we switch to kern_pt1.
812          *
813          * Note, that these allocations started aligned on 1M section and
814          * kernel PT1 was allocated first. Making of mappings must follow
815          * order of physical allocations as we've used KERNEL_P2V() macro
816          * for virtual addresses resolution.
817          */
818         pte2p = kern_pt2tab_entry((vm_offset_t)kern_pt1);
819         pt2pg_va = KERNEL_P2V(pte2_pa(pte2_load(pte2p)));
820
821         pte2p = page_pt2(pt2pg_va, pte1_index((vm_offset_t)kern_pt1));
822
823         /* Make mapping for kernel L1 page table. */
824         for (pa = base_pt1, i = 0; i < NPG_IN_PT1; i++, pa += PTE2_SIZE)
825                 pte2_store(pte2p++, PTE2_KPT(pa));
826
827         /* Make mapping for kernel PT2TAB. */
828         for (pa = pt2tab_pa, i = 0; i < NPG_IN_PT2TAB; i++, pa += PTE2_SIZE)
829                 pte2_store(pte2p++, PTE2_KPT(pa));
830
831         /* Finally, switch from 'boot_pt1' to 'kern_pt1'. */
832         pmap_kern_ttb = base_pt1 | ttb_flags;
833         cpuinfo_get_actlr_modifier(&actlr_mask, &actlr_set);
834         reinit_mmu(pmap_kern_ttb, actlr_mask, actlr_set);
835         /*
836          * Initialize the first available KVA. As kernel image is mapped by
837          * sections, we are leaving some gap behind.
838          */
839         virtual_avail = (vm_offset_t)kern_pt2tab + NPG_IN_PT2TAB * PAGE_SIZE;
840 }
841
842 /*
843  *  Setup L2 page table page for given KVA.
844  *  Used in pre-bootstrap epoch.
845  *
846  *  Note that we have allocated NKPT2PG pages for L2 page tables in advance
847  *  and used them for mapping KVA starting from KERNBASE. However, this is not
848  *  enough. Vectors and devices need L2 page tables too. Note that they are
849  *  even above VM_MAX_KERNEL_ADDRESS.
850  */
851 static __inline vm_paddr_t
852 pmap_preboot_pt2pg_setup(vm_offset_t va)
853 {
854         pt2_entry_t *pte2p, pte2;
855         vm_paddr_t pt2pg_pa;
856
857         /* Get associated entry in PT2TAB. */
858         pte2p = kern_pt2tab_entry(va);
859
860         /* Just return, if PT2s page exists already. */
861         pte2 = pt2tab_load(pte2p);
862         if (pte2_is_valid(pte2))
863                 return (pte2_pa(pte2));
864
865         KASSERT(va >= VM_MAX_KERNEL_ADDRESS,
866             ("%s: NKPT2PG too small", __func__));
867
868         /*
869          * Allocate page for PT2s and insert it to PT2TAB.
870          * In other words, map it into PT2MAP space.
871          */
872         pt2pg_pa = pmap_preboot_get_pages(1);
873         pt2tab_store(pte2p, PTE2_KPT(pt2pg_pa));
874
875         /* Zero all PT2s in allocated page. */
876         bzero((void*)pt2map_pt2pg(va), PAGE_SIZE);
877         pte2_sync_range((pt2_entry_t *)pt2map_pt2pg(va), PAGE_SIZE);
878
879         return (pt2pg_pa);
880 }
881
882 /*
883  *  Setup L2 page table for given KVA.
884  *  Used in pre-bootstrap epoch.
885  */
886 static void
887 pmap_preboot_pt2_setup(vm_offset_t va)
888 {
889         pt1_entry_t *pte1p;
890         vm_paddr_t pt2pg_pa, pt2_pa;
891
892         /* Setup PT2's page. */
893         pt2pg_pa = pmap_preboot_pt2pg_setup(va);
894         pt2_pa = page_pt2pa(pt2pg_pa, pte1_index(va));
895
896         /* Insert PT2 to PT1. */
897         pte1p = kern_pte1(va);
898         pte1_store(pte1p, PTE1_LINK(pt2_pa));
899 }
900
901 /*
902  *  Get L2 page entry associated with given KVA.
903  *  Used in pre-bootstrap epoch.
904  */
905 static __inline pt2_entry_t*
906 pmap_preboot_vtopte2(vm_offset_t va)
907 {
908         pt1_entry_t *pte1p;
909
910         /* Setup PT2 if needed. */
911         pte1p = kern_pte1(va);
912         if (!pte1_is_valid(pte1_load(pte1p))) /* XXX - sections ?! */
913                 pmap_preboot_pt2_setup(va);
914
915         return (pt2map_entry(va));
916 }
917
918 /*
919  *  Pre-bootstrap epoch page(s) mapping(s).
920  */
921 void
922 pmap_preboot_map_pages(vm_paddr_t pa, vm_offset_t va, u_int num)
923 {
924         u_int i;
925         pt2_entry_t *pte2p;
926
927         /* Map all the pages. */
928         for (i = 0; i < num; i++) {
929                 pte2p = pmap_preboot_vtopte2(va);
930                 pte2_store(pte2p, PTE2_KRW(pa));
931                 va += PAGE_SIZE;
932                 pa += PAGE_SIZE;
933         }
934 }
935
936 /*
937  *  Pre-bootstrap epoch virtual space alocator.
938  */
939 vm_offset_t
940 pmap_preboot_reserve_pages(u_int num)
941 {
942         u_int i;
943         vm_offset_t start, va;
944         pt2_entry_t *pte2p;
945
946         /* Allocate virtual space. */
947         start = va = virtual_avail;
948         virtual_avail += num * PAGE_SIZE;
949
950         /* Zero the mapping. */
951         for (i = 0; i < num; i++) {
952                 pte2p = pmap_preboot_vtopte2(va);
953                 pte2_store(pte2p, 0);
954                 va += PAGE_SIZE;
955         }
956
957         return (start);
958 }
959
960 /*
961  *  Pre-bootstrap epoch page(s) allocation and mapping(s).
962  */
963 vm_offset_t
964 pmap_preboot_get_vpages(u_int num)
965 {
966         vm_paddr_t  pa;
967         vm_offset_t va;
968
969         /* Allocate physical page(s). */
970         pa = pmap_preboot_get_pages(num);
971
972         /* Allocate virtual space. */
973         va = virtual_avail;
974         virtual_avail += num * PAGE_SIZE;
975
976         /* Map and zero all. */
977         pmap_preboot_map_pages(pa, va, num);
978         bzero((void *)va, num * PAGE_SIZE);
979
980         return (va);
981 }
982
983 /*
984  *  Pre-bootstrap epoch page mapping(s) with attributes.
985  */
986 void
987 pmap_preboot_map_attr(vm_paddr_t pa, vm_offset_t va, vm_size_t size, int prot,
988     int attr)
989 {
990         u_int num;
991         u_int l1_attr, l1_prot;
992         pt1_entry_t *pte1p;
993         pt2_entry_t *pte2p;
994
995         l1_prot = ATTR_TO_L1(prot);
996         l1_attr = ATTR_TO_L1(attr);
997
998         /* Map all the pages. */
999         num = round_page(size);
1000         while (num > 0) {
1001                 if ((((va | pa) & PTE1_OFFSET) == 0) && (num >= PTE1_SIZE)) {
1002                         pte1p = kern_pte1(va);
1003                         pte1_store(pte1p, PTE1_KERN(pa, l1_prot, l1_attr));
1004                         va += PTE1_SIZE;
1005                         pa += PTE1_SIZE;
1006                         num -= PTE1_SIZE;
1007                 } else {
1008                         pte2p = pmap_preboot_vtopte2(va);
1009                         pte2_store(pte2p, PTE2_KERN(pa, prot, attr));
1010                         va += PAGE_SIZE;
1011                         pa += PAGE_SIZE;
1012                         num -= PAGE_SIZE;
1013                 }
1014         }
1015
1016 }
1017
1018 /*
1019  *  Extract from the kernel page table the physical address
1020  *  that is mapped by the given virtual address "va".
1021  */
1022 vm_paddr_t
1023 pmap_kextract(vm_offset_t va)
1024 {
1025         vm_paddr_t pa;
1026         pt1_entry_t pte1;
1027         pt2_entry_t pte2;
1028
1029         pte1 = pte1_load(kern_pte1(va));
1030         if (pte1_is_section(pte1)) {
1031                 pa = pte1_pa(pte1) | (va & PTE1_OFFSET);
1032         } else if (pte1_is_link(pte1)) {
1033                 /*
1034                  * We should beware of concurrent promotion that changes
1035                  * pte1 at this point. However, it's not a problem as PT2
1036                  * page is preserved by promotion in PT2TAB. So even if
1037                  * it happens, using of PT2MAP is still safe.
1038                  *
1039                  * QQQ: However, concurrent removing is a problem which
1040                  *      ends in abort on PT2MAP space. Locking must be used
1041                  *      to deal with this.
1042                  */
1043                 pte2 = pte2_load(pt2map_entry(va));
1044                 pa = pte2_pa(pte2) | (va & PTE2_OFFSET);
1045         }
1046         else {
1047                 panic("%s: va %#x pte1 %#x", __func__, va, pte1);
1048         }
1049         return (pa);
1050 }
1051
1052 /*
1053  *  Extract from the kernel page table the physical address
1054  *  that is mapped by the given virtual address "va". Also
1055  *  return L2 page table entry which maps the address.
1056  *
1057  *  This is only intended to be used for panic dumps.
1058  */
1059 vm_paddr_t
1060 pmap_dump_kextract(vm_offset_t va, pt2_entry_t *pte2p)
1061 {
1062         vm_paddr_t pa;
1063         pt1_entry_t pte1;
1064         pt2_entry_t pte2;
1065
1066         pte1 = pte1_load(kern_pte1(va));
1067         if (pte1_is_section(pte1)) {
1068                 pa = pte1_pa(pte1) | (va & PTE1_OFFSET);
1069                 pte2 = pa | ATTR_TO_L2(pte1) | PTE2_V;
1070         } else if (pte1_is_link(pte1)) {
1071                 pte2 = pte2_load(pt2map_entry(va));
1072                 pa = pte2_pa(pte2);
1073         } else {
1074                 pte2 = 0;
1075                 pa = 0;
1076         }
1077         if (pte2p != NULL)
1078                 *pte2p = pte2;
1079         return (pa);
1080 }
1081
1082 /*****************************************************************************
1083  *
1084  *      PMAP second stage initialization and utility functions
1085  *      for bootstrap epoch.
1086  *
1087  *  After pmap_bootstrap() is called, the following functions for
1088  *  mappings can be used:
1089  *
1090  *  void pmap_kenter(vm_offset_t va, vm_paddr_t pa);
1091  *  void pmap_kremove(vm_offset_t va);
1092  *  vm_offset_t pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end,
1093  *      int prot);
1094  *
1095  *  NOTE: This is not SMP coherent stage. And physical page allocation is not
1096  *        allowed during this stage.
1097  *
1098  *****************************************************************************/
1099
1100 /*
1101  *  Initialize kernel PMAP locks and lists, kernel_pmap itself, and
1102  *  reserve various virtual spaces for temporary mappings.
1103  */
1104 void
1105 pmap_bootstrap(vm_offset_t firstaddr)
1106 {
1107         pt2_entry_t *unused __unused;
1108         struct sysmaps *sysmaps;
1109         u_int i;
1110
1111         /*
1112          * Initialize the kernel pmap (which is statically allocated).
1113          */
1114         PMAP_LOCK_INIT(kernel_pmap);
1115         kernel_l1pa = (vm_paddr_t)kern_pt1;  /* for libkvm */
1116         kernel_pmap->pm_pt1 = kern_pt1;
1117         kernel_pmap->pm_pt2tab = kern_pt2tab;
1118         CPU_FILL(&kernel_pmap->pm_active);  /* don't allow deactivation */
1119         TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1120
1121         /*
1122          * Initialize the global pv list lock.
1123          */
1124         rw_init(&pvh_global_lock, "pmap pv global");
1125
1126         LIST_INIT(&allpmaps);
1127
1128         /*
1129          * Request a spin mutex so that changes to allpmaps cannot be
1130          * preempted by smp_rendezvous_cpus().
1131          */
1132         mtx_init(&allpmaps_lock, "allpmaps", NULL, MTX_SPIN);
1133         mtx_lock_spin(&allpmaps_lock);
1134         LIST_INSERT_HEAD(&allpmaps, kernel_pmap, pm_list);
1135         mtx_unlock_spin(&allpmaps_lock);
1136
1137         /*
1138          * Reserve some special page table entries/VA space for temporary
1139          * mapping of pages.
1140          */
1141 #define SYSMAP(c, p, v, n)  do {                \
1142         v = (c)pmap_preboot_reserve_pages(n);   \
1143         p = pt2map_entry((vm_offset_t)v);       \
1144         } while (0)
1145
1146         /*
1147          * Local CMAP1/CMAP2 are used for zeroing and copying pages.
1148          * Local CMAP3 is used for data cache cleaning.
1149          * Global CMAP3 is used for the idle process page zeroing.
1150          */
1151         for (i = 0; i < MAXCPU; i++) {
1152                 sysmaps = &sysmaps_pcpu[i];
1153                 mtx_init(&sysmaps->lock, "SYSMAPS", NULL, MTX_DEF);
1154                 SYSMAP(caddr_t, sysmaps->CMAP1, sysmaps->CADDR1, 1);
1155                 SYSMAP(caddr_t, sysmaps->CMAP2, sysmaps->CADDR2, 1);
1156                 SYSMAP(caddr_t, sysmaps->CMAP3, sysmaps->CADDR3, 1);
1157         }
1158         SYSMAP(caddr_t, CMAP3, CADDR3, 1);
1159
1160         /*
1161          * Crashdump maps.
1162          */
1163         SYSMAP(caddr_t, unused, crashdumpmap, MAXDUMPPGS);
1164
1165         /*
1166          * _tmppt is used for reading arbitrary physical pages via /dev/mem.
1167          */
1168         SYSMAP(caddr_t, unused, _tmppt, 1);
1169
1170         /*
1171          * PADDR1 and PADDR2 are used by pmap_pte2_quick() and pmap_pte2(),
1172          * respectively. PADDR3 is used by pmap_pte2_ddb().
1173          */
1174         SYSMAP(pt2_entry_t *, PMAP1, PADDR1, 1);
1175         SYSMAP(pt2_entry_t *, PMAP2, PADDR2, 1);
1176 #ifdef DDB
1177         SYSMAP(pt2_entry_t *, PMAP3, PADDR3, 1);
1178 #endif
1179         mtx_init(&PMAP2mutex, "PMAP2", NULL, MTX_DEF);
1180
1181         /*
1182          * Note that in very short time in initarm(), we are going to
1183          * initialize phys_avail[] array and no futher page allocation
1184          * can happen after that until vm subsystem will be initialized.
1185          */
1186         kernel_vm_end_new = kernel_vm_end;
1187         virtual_end = vm_max_kernel_address;
1188 }
1189
1190 static void
1191 pmap_init_qpages(void)
1192 {
1193         struct pcpu *pc;
1194         int i;
1195
1196         CPU_FOREACH(i) {
1197                 pc = pcpu_find(i);
1198                 pc->pc_qmap_addr = kva_alloc(PAGE_SIZE);
1199                 if (pc->pc_qmap_addr == 0)
1200                         panic("%s: unable to allocate KVA", __func__);
1201         }
1202 }
1203 SYSINIT(qpages_init, SI_SUB_CPU, SI_ORDER_ANY, pmap_init_qpages, NULL);
1204
1205 /*
1206  *  The function can already be use in second initialization stage.
1207  *  As such, the function DOES NOT call pmap_growkernel() where PT2
1208  *  allocation can happen. So if used, be sure that PT2 for given
1209  *  virtual address is allocated already!
1210  *
1211  *  Add a wired page to the kva.
1212  *  Note: not SMP coherent.
1213  */
1214 static __inline void
1215 pmap_kenter_prot_attr(vm_offset_t va, vm_paddr_t pa, uint32_t prot,
1216     uint32_t attr)
1217 {
1218         pt1_entry_t *pte1p;
1219         pt2_entry_t *pte2p;
1220
1221         pte1p = kern_pte1(va);
1222         if (!pte1_is_valid(pte1_load(pte1p))) { /* XXX - sections ?! */
1223                 /*
1224                  * This is a very low level function, so PT2 and particularly
1225                  * PT2PG associated with given virtual address must be already
1226                  * allocated. It's a pain mainly during pmap initialization
1227                  * stage. However, called after pmap initialization with
1228                  * virtual address not under kernel_vm_end will lead to
1229                  * the same misery.
1230                  */
1231                 if (!pte2_is_valid(pte2_load(kern_pt2tab_entry(va))))
1232                         panic("%s: kernel PT2 not allocated!", __func__);
1233         }
1234
1235         pte2p = pt2map_entry(va);
1236         pte2_store(pte2p, PTE2_KERN(pa, prot, attr));
1237 }
1238
1239 static __inline void
1240 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int attr)
1241 {
1242
1243         pmap_kenter_prot_attr(va, pa, PTE2_AP_KRW, attr);
1244 }
1245
1246 PMAP_INLINE void
1247 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
1248 {
1249
1250         pmap_kenter_prot_attr(va, pa, PTE2_AP_KRW, PTE2_ATTR_NORMAL);
1251 }
1252
1253 /*
1254  *  Remove a page from the kernel pagetables.
1255  *  Note: not SMP coherent.
1256  */
1257 PMAP_INLINE void
1258 pmap_kremove(vm_offset_t va)
1259 {
1260         pt2_entry_t *pte2p;
1261
1262         pte2p = pt2map_entry(va);
1263         pte2_clear(pte2p);
1264 }
1265
1266 /*
1267  *  Share new kernel PT2PG with all pmaps.
1268  *  The caller is responsible for maintaining TLB consistency.
1269  */
1270 static void
1271 pmap_kenter_pt2tab(vm_offset_t va, pt2_entry_t npte2)
1272 {
1273         pmap_t pmap;
1274         pt2_entry_t *pte2p;
1275
1276         mtx_lock_spin(&allpmaps_lock);
1277         LIST_FOREACH(pmap, &allpmaps, pm_list) {
1278                 pte2p = pmap_pt2tab_entry(pmap, va);
1279                 pt2tab_store(pte2p, npte2);
1280         }
1281         mtx_unlock_spin(&allpmaps_lock);
1282 }
1283
1284 /*
1285  *  Share new kernel PTE1 with all pmaps.
1286  *  The caller is responsible for maintaining TLB consistency.
1287  */
1288 static void
1289 pmap_kenter_pte1(vm_offset_t va, pt1_entry_t npte1)
1290 {
1291         pmap_t pmap;
1292         pt1_entry_t *pte1p;
1293
1294         mtx_lock_spin(&allpmaps_lock);
1295         LIST_FOREACH(pmap, &allpmaps, pm_list) {
1296                 pte1p = pmap_pte1(pmap, va);
1297                 pte1_store(pte1p, npte1);
1298         }
1299         mtx_unlock_spin(&allpmaps_lock);
1300 }
1301
1302 /*
1303  *  Used to map a range of physical addresses into kernel
1304  *  virtual address space.
1305  *
1306  *  The value passed in '*virt' is a suggested virtual address for
1307  *  the mapping. Architectures which can support a direct-mapped
1308  *  physical to virtual region can return the appropriate address
1309  *  within that region, leaving '*virt' unchanged. Other
1310  *  architectures should map the pages starting at '*virt' and
1311  *  update '*virt' with the first usable address after the mapped
1312  *  region.
1313  *
1314  *  NOTE: Read the comments above pmap_kenter_prot_attr() as
1315  *        the function is used herein!
1316  */
1317 vm_offset_t
1318 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
1319 {
1320         vm_offset_t va, sva;
1321         vm_paddr_t pte1_offset;
1322         pt1_entry_t npte1;
1323         u_int l1prot,l2prot;
1324
1325         PDEBUG(1, printf("%s: virt = %#x, start = %#x, end = %#x (size = %#x),"
1326             " prot = %d\n", __func__, *virt, start, end, end - start,  prot));
1327
1328         l2prot = (prot & VM_PROT_WRITE) ? PTE2_AP_KRW : PTE1_AP_KR;
1329         l2prot |= (prot & VM_PROT_EXECUTE) ? PTE2_X : PTE2_NX;
1330         l1prot = ATTR_TO_L1(l2prot);
1331
1332         va = *virt;
1333         /*
1334          * Does the physical address range's size and alignment permit at
1335          * least one section mapping to be created?
1336          */
1337         pte1_offset = start & PTE1_OFFSET;
1338         if ((end - start) - ((PTE1_SIZE - pte1_offset) & PTE1_OFFSET) >=
1339             PTE1_SIZE) {
1340                 /*
1341                  * Increase the starting virtual address so that its alignment
1342                  * does not preclude the use of section mappings.
1343                  */
1344                 if ((va & PTE1_OFFSET) < pte1_offset)
1345                         va = pte1_trunc(va) + pte1_offset;
1346                 else if ((va & PTE1_OFFSET) > pte1_offset)
1347                         va = pte1_roundup(va) + pte1_offset;
1348         }
1349         sva = va;
1350         while (start < end) {
1351                 if ((start & PTE1_OFFSET) == 0 && end - start >= PTE1_SIZE) {
1352                         KASSERT((va & PTE1_OFFSET) == 0,
1353                             ("%s: misaligned va %#x", __func__, va));
1354                         npte1 = PTE1_KERN(start, l1prot, PTE1_ATTR_NORMAL);
1355                         pmap_kenter_pte1(va, npte1);
1356                         va += PTE1_SIZE;
1357                         start += PTE1_SIZE;
1358                 } else {
1359                         pmap_kenter_prot_attr(va, start, l2prot,
1360                             PTE2_ATTR_NORMAL);
1361                         va += PAGE_SIZE;
1362                         start += PAGE_SIZE;
1363                 }
1364         }
1365         tlb_flush_range(sva, va - sva);
1366         *virt = va;
1367         return (sva);
1368 }
1369
1370 /*
1371  *  Make a temporary mapping for a physical address.
1372  *  This is only intended to be used for panic dumps.
1373  */
1374 void *
1375 pmap_kenter_temporary(vm_paddr_t pa, int i)
1376 {
1377         vm_offset_t va;
1378
1379         /* QQQ: 'i' should be less or equal to MAXDUMPPGS. */
1380
1381         va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
1382         pmap_kenter(va, pa);
1383         tlb_flush_local(va);
1384         return ((void *)crashdumpmap);
1385 }
1386
1387
1388 /*************************************
1389  *
1390  *  TLB & cache maintenance routines.
1391  *
1392  *************************************/
1393
1394 /*
1395  *  We inline these within pmap.c for speed.
1396  */
1397 PMAP_INLINE void
1398 pmap_tlb_flush(pmap_t pmap, vm_offset_t va)
1399 {
1400
1401         if (pmap == kernel_pmap || !CPU_EMPTY(&pmap->pm_active))
1402                 tlb_flush(va);
1403 }
1404
1405 PMAP_INLINE void
1406 pmap_tlb_flush_range(pmap_t pmap, vm_offset_t sva, vm_size_t size)
1407 {
1408
1409         if (pmap == kernel_pmap || !CPU_EMPTY(&pmap->pm_active))
1410                 tlb_flush_range(sva, size);
1411 }
1412
1413 /*
1414  *  Abuse the pte2 nodes for unmapped kva to thread a kva freelist through.
1415  *  Requirements:
1416  *   - Must deal with pages in order to ensure that none of the PTE2_* bits
1417  *     are ever set, PTE2_V in particular.
1418  *   - Assumes we can write to pte2s without pte2_store() atomic ops.
1419  *   - Assumes nothing will ever test these addresses for 0 to indicate
1420  *     no mapping instead of correctly checking PTE2_V.
1421  *   - Assumes a vm_offset_t will fit in a pte2 (true for arm).
1422  *  Because PTE2_V is never set, there can be no mappings to invalidate.
1423  */
1424 static vm_offset_t
1425 pmap_pte2list_alloc(vm_offset_t *head)
1426 {
1427         pt2_entry_t *pte2p;
1428         vm_offset_t va;
1429
1430         va = *head;
1431         if (va == 0)
1432                 panic("pmap_ptelist_alloc: exhausted ptelist KVA");
1433         pte2p = pt2map_entry(va);
1434         *head = *pte2p;
1435         if (*head & PTE2_V)
1436                 panic("%s: va with PTE2_V set!", __func__);
1437         *pte2p = 0;
1438         return (va);
1439 }
1440
1441 static void
1442 pmap_pte2list_free(vm_offset_t *head, vm_offset_t va)
1443 {
1444         pt2_entry_t *pte2p;
1445
1446         if (va & PTE2_V)
1447                 panic("%s: freeing va with PTE2_V set!", __func__);
1448         pte2p = pt2map_entry(va);
1449         *pte2p = *head;         /* virtual! PTE2_V is 0 though */
1450         *head = va;
1451 }
1452
1453 static void
1454 pmap_pte2list_init(vm_offset_t *head, void *base, int npages)
1455 {
1456         int i;
1457         vm_offset_t va;
1458
1459         *head = 0;
1460         for (i = npages - 1; i >= 0; i--) {
1461                 va = (vm_offset_t)base + i * PAGE_SIZE;
1462                 pmap_pte2list_free(head, va);
1463         }
1464 }
1465
1466 /*****************************************************************************
1467  *
1468  *      PMAP third and final stage initialization.
1469  *
1470  *  After pmap_init() is called, PMAP subsystem is fully initialized.
1471  *
1472  *****************************************************************************/
1473
1474 SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD, 0, "VM/pmap parameters");
1475
1476 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_max, CTLFLAG_RD, &pv_entry_max, 0,
1477     "Max number of PV entries");
1478 SYSCTL_INT(_vm_pmap, OID_AUTO, shpgperproc, CTLFLAG_RD, &shpgperproc, 0,
1479     "Page share factor per proc");
1480
1481 static u_long nkpt2pg = NKPT2PG;
1482 SYSCTL_ULONG(_vm_pmap, OID_AUTO, nkpt2pg, CTLFLAG_RD,
1483     &nkpt2pg, 0, "Pre-allocated pages for kernel PT2s");
1484
1485 static int sp_enabled = 1;
1486 SYSCTL_INT(_vm_pmap, OID_AUTO, sp_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
1487     &sp_enabled, 0, "Are large page mappings enabled?");
1488
1489 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pte1, CTLFLAG_RD, 0,
1490     "1MB page mapping counters");
1491
1492 static u_long pmap_pte1_demotions;
1493 SYSCTL_ULONG(_vm_pmap_pte1, OID_AUTO, demotions, CTLFLAG_RD,
1494     &pmap_pte1_demotions, 0, "1MB page demotions");
1495
1496 static u_long pmap_pte1_mappings;
1497 SYSCTL_ULONG(_vm_pmap_pte1, OID_AUTO, mappings, CTLFLAG_RD,
1498     &pmap_pte1_mappings, 0, "1MB page mappings");
1499
1500 static u_long pmap_pte1_p_failures;
1501 SYSCTL_ULONG(_vm_pmap_pte1, OID_AUTO, p_failures, CTLFLAG_RD,
1502     &pmap_pte1_p_failures, 0, "1MB page promotion failures");
1503
1504 static u_long pmap_pte1_promotions;
1505 SYSCTL_ULONG(_vm_pmap_pte1, OID_AUTO, promotions, CTLFLAG_RD,
1506     &pmap_pte1_promotions, 0, "1MB page promotions");
1507
1508 static __inline ttb_entry_t
1509 pmap_ttb_get(pmap_t pmap)
1510 {
1511
1512         return (vtophys(pmap->pm_pt1) | ttb_flags);
1513 }
1514
1515 /*
1516  *  Initialize a vm_page's machine-dependent fields.
1517  *
1518  *  Variations:
1519  *  1. Pages for L2 page tables are always not managed. So, pv_list and
1520  *     pt2_wirecount can share same physical space. However, proper
1521  *     initialization on a page alloc for page tables and reinitialization
1522  *     on the page free must be ensured.
1523  */
1524 void
1525 pmap_page_init(vm_page_t m)
1526 {
1527
1528         TAILQ_INIT(&m->md.pv_list);
1529         pt2_wirecount_init(m);
1530         m->md.pat_mode = PTE2_ATTR_NORMAL;
1531 }
1532
1533 /*
1534  *  Virtualization for faster way how to zero whole page.
1535  */
1536 static __inline void
1537 pagezero(void *page)
1538 {
1539
1540         bzero(page, PAGE_SIZE);
1541 }
1542
1543 /*
1544  *  Zero L2 page table page.
1545  *  Use same KVA as in pmap_zero_page().
1546  */
1547 static __inline vm_paddr_t
1548 pmap_pt2pg_zero(vm_page_t m)
1549 {
1550         vm_paddr_t pa;
1551         struct sysmaps *sysmaps;
1552
1553         pa = VM_PAGE_TO_PHYS(m);
1554
1555         /*
1556          * XXX: For now, we map whole page even if it's already zero,
1557          *      to sync it even if the sync is only DSB.
1558          */
1559         sched_pin();
1560         sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
1561         mtx_lock(&sysmaps->lock);
1562         if (pte2_load(sysmaps->CMAP2) != 0)
1563                 panic("%s: CMAP2 busy", __func__);
1564         pte2_store(sysmaps->CMAP2, PTE2_KERN_NG(pa, PTE2_AP_KRW,
1565             m->md.pat_mode));
1566         /*  Even VM_ALLOC_ZERO request is only advisory. */
1567         if ((m->flags & PG_ZERO) == 0)
1568                 pagezero(sysmaps->CADDR2);
1569         pte2_sync_range((pt2_entry_t *)sysmaps->CADDR2, PAGE_SIZE);
1570         pte2_clear(sysmaps->CMAP2);
1571         tlb_flush((vm_offset_t)sysmaps->CADDR2);
1572         sched_unpin();
1573         mtx_unlock(&sysmaps->lock);
1574
1575         return (pa);
1576 }
1577
1578 /*
1579  *  Init just allocated page as L2 page table(s) holder
1580  *  and return its physical address.
1581  */
1582 static __inline vm_paddr_t
1583 pmap_pt2pg_init(pmap_t pmap, vm_offset_t va, vm_page_t m)
1584 {
1585         vm_paddr_t pa;
1586         pt2_entry_t *pte2p;
1587
1588         /* Check page attributes. */
1589         if (pmap_page_get_memattr(m) != pt_memattr)
1590                 pmap_page_set_memattr(m, pt_memattr);
1591
1592         /* Zero page and init wire counts. */
1593         pa = pmap_pt2pg_zero(m);
1594         pt2_wirecount_init(m);
1595
1596         /*
1597          * Map page to PT2MAP address space for given pmap.
1598          * Note that PT2MAP space is shared with all pmaps.
1599          */
1600         if (pmap == kernel_pmap)
1601                 pmap_kenter_pt2tab(va, PTE2_KPT(pa));
1602         else {
1603                 pte2p = pmap_pt2tab_entry(pmap, va);
1604                 pt2tab_store(pte2p, PTE2_KPT_NG(pa));
1605         }
1606
1607         return (pa);
1608 }
1609
1610 /*
1611  *  Initialize the pmap module.
1612  *  Called by vm_init, to initialize any structures that the pmap
1613  *  system needs to map virtual memory.
1614  */
1615 void
1616 pmap_init(void)
1617 {
1618         vm_size_t s;
1619         pt2_entry_t *pte2p, pte2;
1620         u_int i, pte1_idx, pv_npg;
1621
1622         PDEBUG(1, printf("%s: phys_start = %#x\n", __func__, PHYSADDR));
1623
1624         /*
1625          * Initialize the vm page array entries for kernel pmap's
1626          * L2 page table pages allocated in advance.
1627          */
1628         pte1_idx = pte1_index(KERNBASE - PT2MAP_SIZE);
1629         pte2p = kern_pt2tab_entry(KERNBASE - PT2MAP_SIZE);
1630         for (i = 0; i < nkpt2pg + NPG_IN_PT2TAB; i++, pte2p++) {
1631                 vm_paddr_t pa;
1632                 vm_page_t m;
1633
1634                 pte2 = pte2_load(pte2p);
1635                 KASSERT(pte2_is_valid(pte2), ("%s: no valid entry", __func__));
1636
1637                 pa = pte2_pa(pte2);
1638                 m = PHYS_TO_VM_PAGE(pa);
1639                 KASSERT(m >= vm_page_array &&
1640                     m < &vm_page_array[vm_page_array_size],
1641                     ("%s: L2 page table page is out of range", __func__));
1642
1643                 m->pindex = pte1_idx;
1644                 m->phys_addr = pa;
1645                 pte1_idx += NPT2_IN_PG;
1646         }
1647
1648         /*
1649          * Initialize the address space (zone) for the pv entries.  Set a
1650          * high water mark so that the system can recover from excessive
1651          * numbers of pv entries.
1652          */
1653         TUNABLE_INT_FETCH("vm.pmap.shpgperproc", &shpgperproc);
1654         pv_entry_max = shpgperproc * maxproc + vm_cnt.v_page_count;
1655         TUNABLE_INT_FETCH("vm.pmap.pv_entries", &pv_entry_max);
1656         pv_entry_max = roundup(pv_entry_max, _NPCPV);
1657         pv_entry_high_water = 9 * (pv_entry_max / 10);
1658
1659         /*
1660          * Are large page mappings enabled?
1661          */
1662         TUNABLE_INT_FETCH("vm.pmap.sp_enabled", &sp_enabled);
1663         if (sp_enabled) {
1664                 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1665                     ("%s: can't assign to pagesizes[1]", __func__));
1666                 pagesizes[1] = PTE1_SIZE;
1667         }
1668
1669         /*
1670          * Calculate the size of the pv head table for sections.
1671          * Handle the possibility that "vm_phys_segs[...].end" is zero.
1672          * Note that the table is only for sections which could be promoted.
1673          */
1674         first_managed_pa = pte1_trunc(vm_phys_segs[0].start);
1675         pv_npg = (pte1_trunc(vm_phys_segs[vm_phys_nsegs - 1].end - PAGE_SIZE)
1676             - first_managed_pa) / PTE1_SIZE + 1;
1677
1678         /*
1679          * Allocate memory for the pv head table for sections.
1680          */
1681         s = (vm_size_t)(pv_npg * sizeof(struct md_page));
1682         s = round_page(s);
1683         pv_table = (struct md_page *)kmem_malloc(kernel_arena, s,
1684             M_WAITOK | M_ZERO);
1685         for (i = 0; i < pv_npg; i++)
1686                 TAILQ_INIT(&pv_table[i].pv_list);
1687
1688         pv_maxchunks = MAX(pv_entry_max / _NPCPV, maxproc);
1689         pv_chunkbase = (struct pv_chunk *)kva_alloc(PAGE_SIZE * pv_maxchunks);
1690         if (pv_chunkbase == NULL)
1691                 panic("%s: not enough kvm for pv chunks", __func__);
1692         pmap_pte2list_init(&pv_vafree, pv_chunkbase, pv_maxchunks);
1693 }
1694
1695 /*
1696  *  Add a list of wired pages to the kva
1697  *  this routine is only used for temporary
1698  *  kernel mappings that do not need to have
1699  *  page modification or references recorded.
1700  *  Note that old mappings are simply written
1701  *  over.  The page *must* be wired.
1702  *  Note: SMP coherent.  Uses a ranged shootdown IPI.
1703  */
1704 void
1705 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
1706 {
1707         u_int anychanged;
1708         pt2_entry_t *epte2p, *pte2p, pte2;
1709         vm_page_t m;
1710         vm_paddr_t pa;
1711
1712         anychanged = 0;
1713         pte2p = pt2map_entry(sva);
1714         epte2p = pte2p + count;
1715         while (pte2p < epte2p) {
1716                 m = *ma++;
1717                 pa = VM_PAGE_TO_PHYS(m);
1718                 pte2 = pte2_load(pte2p);
1719                 if ((pte2_pa(pte2) != pa) ||
1720                     (pte2_attr(pte2) != m->md.pat_mode)) {
1721                         anychanged++;
1722                         pte2_store(pte2p, PTE2_KERN(pa, PTE2_AP_KRW,
1723                             m->md.pat_mode));
1724                 }
1725                 pte2p++;
1726         }
1727         if (__predict_false(anychanged))
1728                 tlb_flush_range(sva, count * PAGE_SIZE);
1729 }
1730
1731 /*
1732  *  This routine tears out page mappings from the
1733  *  kernel -- it is meant only for temporary mappings.
1734  *  Note: SMP coherent.  Uses a ranged shootdown IPI.
1735  */
1736 void
1737 pmap_qremove(vm_offset_t sva, int count)
1738 {
1739         vm_offset_t va;
1740
1741         va = sva;
1742         while (count-- > 0) {
1743                 pmap_kremove(va);
1744                 va += PAGE_SIZE;
1745         }
1746         tlb_flush_range(sva, va - sva);
1747 }
1748
1749 /*
1750  *  Are we current address space or kernel?
1751  */
1752 static __inline int
1753 pmap_is_current(pmap_t pmap)
1754 {
1755
1756         return (pmap == kernel_pmap ||
1757                 (pmap == vmspace_pmap(curthread->td_proc->p_vmspace)));
1758 }
1759
1760 /*
1761  *  If the given pmap is not the current or kernel pmap, the returned
1762  *  pte2 must be released by passing it to pmap_pte2_release().
1763  */
1764 static pt2_entry_t *
1765 pmap_pte2(pmap_t pmap, vm_offset_t va)
1766 {
1767         pt1_entry_t pte1;
1768         vm_paddr_t pt2pg_pa;
1769
1770         pte1 = pte1_load(pmap_pte1(pmap, va));
1771         if (pte1_is_section(pte1))
1772                 panic("%s: attempt to map PTE1", __func__);
1773         if (pte1_is_link(pte1)) {
1774                 /* Are we current address space or kernel? */
1775                 if (pmap_is_current(pmap))
1776                         return (pt2map_entry(va));
1777                 /* Note that L2 page table size is not equal to PAGE_SIZE. */
1778                 pt2pg_pa = trunc_page(pte1_link_pa(pte1));
1779                 mtx_lock(&PMAP2mutex);
1780                 if (pte2_pa(pte2_load(PMAP2)) != pt2pg_pa) {
1781                         pte2_store(PMAP2, PTE2_KPT(pt2pg_pa));
1782                         tlb_flush((vm_offset_t)PADDR2);
1783                 }
1784                 return (PADDR2 + (arm32_btop(va) & (NPTE2_IN_PG - 1)));
1785         }
1786         return (NULL);
1787 }
1788
1789 /*
1790  *  Releases a pte2 that was obtained from pmap_pte2().
1791  *  Be prepared for the pte2p being NULL.
1792  */
1793 static __inline void
1794 pmap_pte2_release(pt2_entry_t *pte2p)
1795 {
1796
1797         if ((pt2_entry_t *)(trunc_page((vm_offset_t)pte2p)) == PADDR2) {
1798                 mtx_unlock(&PMAP2mutex);
1799         }
1800 }
1801
1802 /*
1803  *  Super fast pmap_pte2 routine best used when scanning
1804  *  the pv lists.  This eliminates many coarse-grained
1805  *  invltlb calls.  Note that many of the pv list
1806  *  scans are across different pmaps.  It is very wasteful
1807  *  to do an entire tlb flush for checking a single mapping.
1808  *
1809  *  If the given pmap is not the current pmap, pvh_global_lock
1810  *  must be held and curthread pinned to a CPU.
1811  */
1812 static pt2_entry_t *
1813 pmap_pte2_quick(pmap_t pmap, vm_offset_t va)
1814 {
1815         pt1_entry_t pte1;
1816         vm_paddr_t pt2pg_pa;
1817
1818         pte1 = pte1_load(pmap_pte1(pmap, va));
1819         if (pte1_is_section(pte1))
1820                 panic("%s: attempt to map PTE1", __func__);
1821         if (pte1_is_link(pte1)) {
1822                 /* Are we current address space or kernel? */
1823                 if (pmap_is_current(pmap))
1824                         return (pt2map_entry(va));
1825                 rw_assert(&pvh_global_lock, RA_WLOCKED);
1826                 KASSERT(curthread->td_pinned > 0,
1827                     ("%s: curthread not pinned", __func__));
1828                 /* Note that L2 page table size is not equal to PAGE_SIZE. */
1829                 pt2pg_pa = trunc_page(pte1_link_pa(pte1));
1830                 if (pte2_pa(pte2_load(PMAP1)) != pt2pg_pa) {
1831                         pte2_store(PMAP1, PTE2_KPT(pt2pg_pa));
1832 #ifdef SMP
1833                         PMAP1cpu = PCPU_GET(cpuid);
1834 #endif
1835                         tlb_flush_local((vm_offset_t)PADDR1);
1836                         PMAP1changed++;
1837                 } else
1838 #ifdef SMP
1839                 if (PMAP1cpu != PCPU_GET(cpuid)) {
1840                         PMAP1cpu = PCPU_GET(cpuid);
1841                         tlb_flush_local((vm_offset_t)PADDR1);
1842                         PMAP1changedcpu++;
1843                 } else
1844 #endif
1845                         PMAP1unchanged++;
1846                 return (PADDR1 + (arm32_btop(va) & (NPTE2_IN_PG - 1)));
1847         }
1848         return (NULL);
1849 }
1850
1851 /*
1852  *  Routine: pmap_extract
1853  *  Function:
1854  *      Extract the physical page address associated
1855  *      with the given map/virtual_address pair.
1856  */
1857 vm_paddr_t
1858 pmap_extract(pmap_t pmap, vm_offset_t va)
1859 {
1860         vm_paddr_t pa;
1861         pt1_entry_t pte1;
1862         pt2_entry_t *pte2p;
1863
1864         PMAP_LOCK(pmap);
1865         pte1 = pte1_load(pmap_pte1(pmap, va));
1866         if (pte1_is_section(pte1))
1867                 pa = pte1_pa(pte1) | (va & PTE1_OFFSET);
1868         else if (pte1_is_link(pte1)) {
1869                 pte2p = pmap_pte2(pmap, va);
1870                 pa = pte2_pa(pte2_load(pte2p)) | (va & PTE2_OFFSET);
1871                 pmap_pte2_release(pte2p);
1872         } else
1873                 pa = 0;
1874         PMAP_UNLOCK(pmap);
1875         return (pa);
1876 }
1877
1878 /*
1879  *  Routine: pmap_extract_and_hold
1880  *  Function:
1881  *      Atomically extract and hold the physical page
1882  *      with the given pmap and virtual address pair
1883  *      if that mapping permits the given protection.
1884  */
1885 vm_page_t
1886 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
1887 {
1888         vm_paddr_t pa, lockpa;
1889         pt1_entry_t pte1;
1890         pt2_entry_t pte2, *pte2p;
1891         vm_page_t m;
1892
1893         lockpa = 0;
1894         m = NULL;
1895         PMAP_LOCK(pmap);
1896 retry:
1897         pte1 = pte1_load(pmap_pte1(pmap, va));
1898         if (pte1_is_section(pte1)) {
1899                 if (!(pte1 & PTE1_RO) || !(prot & VM_PROT_WRITE)) {
1900                         pa = pte1_pa(pte1) | (va & PTE1_OFFSET);
1901                         if (vm_page_pa_tryrelock(pmap, pa, &lockpa))
1902                                 goto retry;
1903                         m = PHYS_TO_VM_PAGE(pa);
1904                         vm_page_hold(m);
1905                 }
1906         } else if (pte1_is_link(pte1)) {
1907                 pte2p = pmap_pte2(pmap, va);
1908                 pte2 = pte2_load(pte2p);
1909                 pmap_pte2_release(pte2p);
1910                 if (pte2_is_valid(pte2) &&
1911                     (!(pte2 & PTE2_RO) || !(prot & VM_PROT_WRITE))) {
1912                         pa = pte2_pa(pte2);
1913                         if (vm_page_pa_tryrelock(pmap, pa, &lockpa))
1914                                 goto retry;
1915                         m = PHYS_TO_VM_PAGE(pa);
1916                         vm_page_hold(m);
1917                 }
1918         }
1919         PA_UNLOCK_COND(lockpa);
1920         PMAP_UNLOCK(pmap);
1921         return (m);
1922 }
1923
1924 /*
1925  *  Grow the number of kernel L2 page table entries, if needed.
1926  */
1927 void
1928 pmap_growkernel(vm_offset_t addr)
1929 {
1930         vm_page_t m;
1931         vm_paddr_t pt2pg_pa, pt2_pa;
1932         pt1_entry_t pte1;
1933         pt2_entry_t pte2;
1934
1935         PDEBUG(1, printf("%s: addr = %#x\n", __func__, addr));
1936         /*
1937          * All the time kernel_vm_end is first KVA for which underlying
1938          * L2 page table is either not allocated or linked from L1 page table
1939          * (not considering sections). Except for two possible cases:
1940          *
1941          *   (1) in the very beginning as long as pmap_growkernel() was
1942          *       not called, it could be first unused KVA (which is not
1943          *       rounded up to PTE1_SIZE),
1944          *
1945          *   (2) when all KVA space is mapped and kernel_map->max_offset
1946          *       address is not rounded up to PTE1_SIZE. (For example,
1947          *       it could be 0xFFFFFFFF.)
1948          */
1949         kernel_vm_end = pte1_roundup(kernel_vm_end);
1950         mtx_assert(&kernel_map->system_mtx, MA_OWNED);
1951         addr = roundup2(addr, PTE1_SIZE);
1952         if (addr - 1 >= kernel_map->max_offset)
1953                 addr = kernel_map->max_offset;
1954         while (kernel_vm_end < addr) {
1955                 pte1 = pte1_load(kern_pte1(kernel_vm_end));
1956                 if (pte1_is_valid(pte1)) {
1957                         kernel_vm_end += PTE1_SIZE;
1958                         if (kernel_vm_end - 1 >= kernel_map->max_offset) {
1959                                 kernel_vm_end = kernel_map->max_offset;
1960                                 break;
1961                         }
1962                         continue;
1963                 }
1964
1965                 /*
1966                  * kernel_vm_end_new is used in pmap_pinit() when kernel
1967                  * mappings are entered to new pmap all at once to avoid race
1968                  * between pmap_kenter_pte1() and kernel_vm_end increase.
1969                  * The same aplies to pmap_kenter_pt2tab().
1970                  */
1971                 kernel_vm_end_new = kernel_vm_end + PTE1_SIZE;
1972
1973                 pte2 = pt2tab_load(kern_pt2tab_entry(kernel_vm_end));
1974                 if (!pte2_is_valid(pte2)) {
1975                         /*
1976                          * Install new PT2s page into kernel PT2TAB.
1977                          */
1978                         m = vm_page_alloc(NULL,
1979                             pte1_index(kernel_vm_end) & ~PT2PG_MASK,
1980                             VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ |
1981                             VM_ALLOC_WIRED | VM_ALLOC_ZERO);
1982                         if (m == NULL)
1983                                 panic("%s: no memory to grow kernel", __func__);
1984                         /*
1985                          * QQQ: To link all new L2 page tables from L1 page
1986                          *      table now and so pmap_kenter_pte1() them
1987                          *      at once together with pmap_kenter_pt2tab()
1988                          *      could be nice speed up. However,
1989                          *      pmap_growkernel() does not happen so often...
1990                          * QQQ: The other TTBR is another option.
1991                          */
1992                         pt2pg_pa = pmap_pt2pg_init(kernel_pmap, kernel_vm_end,
1993                             m);
1994                 } else
1995                         pt2pg_pa = pte2_pa(pte2);
1996
1997                 pt2_pa = page_pt2pa(pt2pg_pa, pte1_index(kernel_vm_end));
1998                 pmap_kenter_pte1(kernel_vm_end, PTE1_LINK(pt2_pa));
1999
2000                 kernel_vm_end = kernel_vm_end_new;
2001                 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
2002                         kernel_vm_end = kernel_map->max_offset;
2003                         break;
2004                 }
2005         }
2006 }
2007
2008 static int
2009 kvm_size(SYSCTL_HANDLER_ARGS)
2010 {
2011         unsigned long ksize = vm_max_kernel_address - KERNBASE;
2012
2013         return (sysctl_handle_long(oidp, &ksize, 0, req));
2014 }
2015 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD,
2016     0, 0, kvm_size, "IU", "Size of KVM");
2017
2018 static int
2019 kvm_free(SYSCTL_HANDLER_ARGS)
2020 {
2021         unsigned long kfree = vm_max_kernel_address - kernel_vm_end;
2022
2023         return (sysctl_handle_long(oidp, &kfree, 0, req));
2024 }
2025 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD,
2026     0, 0, kvm_free, "IU", "Amount of KVM free");
2027
2028 /***********************************************
2029  *
2030  *  Pmap allocation/deallocation routines.
2031  *
2032  ***********************************************/
2033
2034 /*
2035  *  Initialize the pmap for the swapper process.
2036  */
2037 void
2038 pmap_pinit0(pmap_t pmap)
2039 {
2040         PDEBUG(1, printf("%s: pmap = %p\n", __func__, pmap));
2041
2042         PMAP_LOCK_INIT(pmap);
2043
2044         /*
2045          * Kernel page table directory and pmap stuff around is already
2046          * initialized, we are using it right now and here. So, finish
2047          * only PMAP structures initialization for process0 ...
2048          *
2049          * Since the L1 page table and PT2TAB is shared with the kernel pmap,
2050          * which is already included in the list "allpmaps", this pmap does
2051          * not need to be inserted into that list.
2052          */
2053         pmap->pm_pt1 = kern_pt1;
2054         pmap->pm_pt2tab = kern_pt2tab;
2055         CPU_ZERO(&pmap->pm_active);
2056         PCPU_SET(curpmap, pmap);
2057         TAILQ_INIT(&pmap->pm_pvchunk);
2058         bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2059         CPU_SET(0, &pmap->pm_active);
2060 }
2061
2062 static __inline void
2063 pte1_copy_nosync(pt1_entry_t *spte1p, pt1_entry_t *dpte1p, vm_offset_t sva,
2064     vm_offset_t eva)
2065 {
2066         u_int idx, count;
2067
2068         idx = pte1_index(sva);
2069         count = (pte1_index(eva) - idx + 1) * sizeof(pt1_entry_t);
2070         bcopy(spte1p + idx, dpte1p + idx, count);
2071 }
2072
2073 static __inline void
2074 pt2tab_copy_nosync(pt2_entry_t *spte2p, pt2_entry_t *dpte2p, vm_offset_t sva,
2075     vm_offset_t eva)
2076 {
2077         u_int idx, count;
2078
2079         idx = pt2tab_index(sva);
2080         count = (pt2tab_index(eva) - idx + 1) * sizeof(pt2_entry_t);
2081         bcopy(spte2p + idx, dpte2p + idx, count);
2082 }
2083
2084 /*
2085  *  Initialize a preallocated and zeroed pmap structure,
2086  *  such as one in a vmspace structure.
2087  */
2088 int
2089 pmap_pinit(pmap_t pmap)
2090 {
2091         pt1_entry_t *pte1p;
2092         pt2_entry_t *pte2p;
2093         vm_paddr_t pa, pt2tab_pa;
2094         u_int i;
2095
2096         PDEBUG(6, printf("%s: pmap = %p, pm_pt1 = %p\n", __func__, pmap,
2097             pmap->pm_pt1));
2098
2099         /*
2100          * No need to allocate L2 page table space yet but we do need
2101          * a valid L1 page table and PT2TAB table.
2102          *
2103          * Install shared kernel mappings to these tables. It's a little
2104          * tricky as some parts of KVA are reserved for vectors, devices,
2105          * and whatever else. These parts are supposed to be above
2106          * vm_max_kernel_address. Thus two regions should be installed:
2107          *
2108          *   (1) <KERNBASE, kernel_vm_end),
2109          *   (2) <vm_max_kernel_address, 0xFFFFFFFF>.
2110          *
2111          * QQQ: The second region should be stable enough to be installed
2112          *      only once in time when the tables are allocated.
2113          * QQQ: Maybe copy of both regions at once could be faster ...
2114          * QQQ: Maybe the other TTBR is an option.
2115          *
2116          * Finally, install own PT2TAB table to these tables.
2117          */
2118
2119         if (pmap->pm_pt1 == NULL) {
2120                 pmap->pm_pt1 = (pt1_entry_t *)kmem_alloc_contig(kernel_arena,
2121                     NB_IN_PT1, M_NOWAIT | M_ZERO, 0, -1UL, NB_IN_PT1, 0,
2122                     pt_memattr);
2123                 if (pmap->pm_pt1 == NULL)
2124                         return (0);
2125         }
2126         if (pmap->pm_pt2tab == NULL) {
2127                 /*
2128                  * QQQ: (1) PT2TAB must be contiguous. If PT2TAB is one page
2129                  *      only, what should be the only size for 32 bit systems,
2130                  *      then we could allocate it with vm_page_alloc() and all
2131                  *      the stuff needed as other L2 page table pages.
2132                  *      (2) Note that a process PT2TAB is special L2 page table
2133                  *      page. Its mapping in kernel_arena is permanent and can
2134                  *      be used no matter which process is current. Its mapping
2135                  *      in PT2MAP can be used only for current process.
2136                  */
2137                 pmap->pm_pt2tab = (pt2_entry_t *)kmem_alloc_attr(kernel_arena,
2138                     NB_IN_PT2TAB, M_NOWAIT | M_ZERO, 0, -1UL, pt_memattr);
2139                 if (pmap->pm_pt2tab == NULL) {
2140                         /*
2141                          * QQQ: As struct pmap is allocated from UMA with
2142                          *      UMA_ZONE_NOFREE flag, it's important to leave
2143                          *      no allocation in pmap if initialization failed.
2144                          */
2145                         kmem_free(kernel_arena, (vm_offset_t)pmap->pm_pt1,
2146                             NB_IN_PT1);
2147                         pmap->pm_pt1 = NULL;
2148                         return (0);
2149                 }
2150                 /*
2151                  * QQQ: Each L2 page table page vm_page_t has pindex set to
2152                  *      pte1 index of virtual address mapped by this page.
2153                  *      It's not valid for non kernel PT2TABs themselves.
2154                  *      The pindex of these pages can not be altered because
2155                  *      of the way how they are allocated now. However, it
2156                  *      should not be a problem.
2157                  */
2158         }
2159
2160         mtx_lock_spin(&allpmaps_lock);
2161         /*
2162          * To avoid race with pmap_kenter_pte1() and pmap_kenter_pt2tab(),
2163          * kernel_vm_end_new is used here instead of kernel_vm_end.
2164          */
2165         pte1_copy_nosync(kern_pt1, pmap->pm_pt1, KERNBASE,
2166             kernel_vm_end_new - 1);
2167         pte1_copy_nosync(kern_pt1, pmap->pm_pt1, vm_max_kernel_address,
2168             0xFFFFFFFF);
2169         pt2tab_copy_nosync(kern_pt2tab, pmap->pm_pt2tab, KERNBASE,
2170             kernel_vm_end_new - 1);
2171         pt2tab_copy_nosync(kern_pt2tab, pmap->pm_pt2tab, vm_max_kernel_address,
2172             0xFFFFFFFF);
2173         LIST_INSERT_HEAD(&allpmaps, pmap, pm_list);
2174         mtx_unlock_spin(&allpmaps_lock);
2175
2176         /*
2177          * Store PT2MAP PT2 pages (a.k.a. PT2TAB) in PT2TAB itself.
2178          * I.e. self reference mapping.  The PT2TAB is private, however mapped
2179          * into shared PT2MAP space, so the mapping should be not global.
2180          */
2181         pt2tab_pa = vtophys(pmap->pm_pt2tab);
2182         pte2p = pmap_pt2tab_entry(pmap, (vm_offset_t)PT2MAP);
2183         for (pa = pt2tab_pa, i = 0; i < NPG_IN_PT2TAB; i++, pa += PTE2_SIZE) {
2184                 pt2tab_store(pte2p++, PTE2_KPT_NG(pa));
2185         }
2186
2187         /* Insert PT2MAP PT2s into pmap PT1. */
2188         pte1p = pmap_pte1(pmap, (vm_offset_t)PT2MAP);
2189         for (pa = pt2tab_pa, i = 0; i < NPT2_IN_PT2TAB; i++, pa += NB_IN_PT2) {
2190                 pte1_store(pte1p++, PTE1_LINK(pa));
2191         }
2192
2193         /*
2194          * Now synchronize new mapping which was made above.
2195          */
2196         pte1_sync_range(pmap->pm_pt1, NB_IN_PT1);
2197         pte2_sync_range(pmap->pm_pt2tab, NB_IN_PT2TAB);
2198
2199         CPU_ZERO(&pmap->pm_active);
2200         TAILQ_INIT(&pmap->pm_pvchunk);
2201         bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2202
2203         return (1);
2204 }
2205
2206 #ifdef INVARIANTS
2207 static boolean_t
2208 pt2tab_user_is_empty(pt2_entry_t *tab)
2209 {
2210         u_int i, end;
2211
2212         end = pt2tab_index(VM_MAXUSER_ADDRESS);
2213         for (i = 0; i < end; i++)
2214                 if (tab[i] != 0) return (FALSE);
2215         return (TRUE);
2216 }
2217 #endif
2218 /*
2219  *  Release any resources held by the given physical map.
2220  *  Called when a pmap initialized by pmap_pinit is being released.
2221  *  Should only be called if the map contains no valid mappings.
2222  */
2223 void
2224 pmap_release(pmap_t pmap)
2225 {
2226 #ifdef INVARIANTS
2227         vm_offset_t start, end;
2228 #endif
2229         KASSERT(pmap->pm_stats.resident_count == 0,
2230             ("%s: pmap resident count %ld != 0", __func__,
2231             pmap->pm_stats.resident_count));
2232         KASSERT(pt2tab_user_is_empty(pmap->pm_pt2tab),
2233             ("%s: has allocated user PT2(s)", __func__));
2234         KASSERT(CPU_EMPTY(&pmap->pm_active),
2235             ("%s: pmap %p is active on some CPU(s)", __func__, pmap));
2236
2237         mtx_lock_spin(&allpmaps_lock);
2238         LIST_REMOVE(pmap, pm_list);
2239         mtx_unlock_spin(&allpmaps_lock);
2240
2241 #ifdef INVARIANTS
2242         start = pte1_index(KERNBASE) * sizeof(pt1_entry_t);
2243         end = (pte1_index(0xFFFFFFFF) + 1) * sizeof(pt1_entry_t);
2244         bzero((char *)pmap->pm_pt1 + start, end - start);
2245
2246         start = pt2tab_index(KERNBASE) * sizeof(pt2_entry_t);
2247         end = (pt2tab_index(0xFFFFFFFF) + 1) * sizeof(pt2_entry_t);
2248         bzero((char *)pmap->pm_pt2tab + start, end - start);
2249 #endif
2250         /*
2251          * We are leaving PT1 and PT2TAB allocated on released pmap,
2252          * so hopefully UMA vmspace_zone will always be inited with
2253          * UMA_ZONE_NOFREE flag.
2254          */
2255 }
2256
2257 /*********************************************************
2258  *
2259  *  L2 table pages and their pages management routines.
2260  *
2261  *********************************************************/
2262
2263 /*
2264  *  Virtual interface for L2 page table wire counting.
2265  *
2266  *  Each L2 page table in a page has own counter which counts a number of
2267  *  valid mappings in a table. Global page counter counts mappings in all
2268  *  tables in a page plus a single itself mapping in PT2TAB.
2269  *
2270  *  During a promotion we leave the associated L2 page table counter
2271  *  untouched, so the table (strictly speaking a page which holds it)
2272  *  is never freed if promoted.
2273  *
2274  *  If a page m->wire_count == 1 then no valid mappings exist in any L2 page
2275  *  table in the page and the page itself is only mapped in PT2TAB.
2276  */
2277
2278 static __inline void
2279 pt2_wirecount_init(vm_page_t m)
2280 {
2281         u_int i;
2282
2283         /*
2284          * Note: A page m is allocated with VM_ALLOC_WIRED flag and
2285          *       m->wire_count should be already set correctly.
2286          *       So, there is no need to set it again herein.
2287          */
2288         for (i = 0; i < NPT2_IN_PG; i++)
2289                 m->md.pt2_wirecount[i] = 0;
2290 }
2291
2292 static __inline void
2293 pt2_wirecount_inc(vm_page_t m, uint32_t pte1_idx)
2294 {
2295
2296         /*
2297          * Note: A just modificated pte2 (i.e. already allocated)
2298          *       is acquiring one extra reference which must be
2299          *       explicitly cleared. It influences the KASSERTs herein.
2300          *       All L2 page tables in a page always belong to the same
2301          *       pmap, so we allow only one extra reference for the page.
2302          */
2303         KASSERT(m->md.pt2_wirecount[pte1_idx & PT2PG_MASK] < (NPTE2_IN_PT2 + 1),
2304             ("%s: PT2 is overflowing ...", __func__));
2305         KASSERT(m->wire_count <= (NPTE2_IN_PG + 1),
2306             ("%s: PT2PG is overflowing ...", __func__));
2307
2308         m->wire_count++;
2309         m->md.pt2_wirecount[pte1_idx & PT2PG_MASK]++;
2310 }
2311
2312 static __inline void
2313 pt2_wirecount_dec(vm_page_t m, uint32_t pte1_idx)
2314 {
2315
2316         KASSERT(m->md.pt2_wirecount[pte1_idx & PT2PG_MASK] != 0,
2317             ("%s: PT2 is underflowing ...", __func__));
2318         KASSERT(m->wire_count > 1,
2319             ("%s: PT2PG is underflowing ...", __func__));
2320
2321         m->wire_count--;
2322         m->md.pt2_wirecount[pte1_idx & PT2PG_MASK]--;
2323 }
2324
2325 static __inline void
2326 pt2_wirecount_set(vm_page_t m, uint32_t pte1_idx, uint16_t count)
2327 {
2328
2329         KASSERT(count <= NPTE2_IN_PT2,
2330             ("%s: invalid count %u", __func__, count));
2331         KASSERT(m->wire_count >  m->md.pt2_wirecount[pte1_idx & PT2PG_MASK],
2332             ("%s: PT2PG corrupting (%u, %u) ...", __func__, m->wire_count,
2333             m->md.pt2_wirecount[pte1_idx & PT2PG_MASK]));
2334
2335         m->wire_count -= m->md.pt2_wirecount[pte1_idx & PT2PG_MASK];
2336         m->wire_count += count;
2337         m->md.pt2_wirecount[pte1_idx & PT2PG_MASK] = count;
2338
2339         KASSERT(m->wire_count <= (NPTE2_IN_PG + 1),
2340             ("%s: PT2PG is overflowed (%u) ...", __func__, m->wire_count));
2341 }
2342
2343 static __inline uint32_t
2344 pt2_wirecount_get(vm_page_t m, uint32_t pte1_idx)
2345 {
2346
2347         return (m->md.pt2_wirecount[pte1_idx & PT2PG_MASK]);
2348 }
2349
2350 static __inline boolean_t
2351 pt2_is_empty(vm_page_t m, vm_offset_t va)
2352 {
2353
2354         return (m->md.pt2_wirecount[pte1_index(va) & PT2PG_MASK] == 0);
2355 }
2356
2357 static __inline boolean_t
2358 pt2_is_full(vm_page_t m, vm_offset_t va)
2359 {
2360
2361         return (m->md.pt2_wirecount[pte1_index(va) & PT2PG_MASK] ==
2362             NPTE2_IN_PT2);
2363 }
2364
2365 static __inline boolean_t
2366 pt2pg_is_empty(vm_page_t m)
2367 {
2368
2369         return (m->wire_count == 1);
2370 }
2371
2372 /*
2373  *  This routine is called if the L2 page table
2374  *  is not mapped correctly.
2375  */
2376 static vm_page_t
2377 _pmap_allocpte2(pmap_t pmap, vm_offset_t va, u_int flags)
2378 {
2379         uint32_t pte1_idx;
2380         pt1_entry_t *pte1p;
2381         pt2_entry_t pte2;
2382         vm_page_t  m;
2383         vm_paddr_t pt2pg_pa, pt2_pa;
2384
2385         pte1_idx = pte1_index(va);
2386         pte1p = pmap->pm_pt1 + pte1_idx;
2387
2388         KASSERT(pte1_load(pte1p) == 0,
2389             ("%s: pm_pt1[%#x] is not zero: %#x", __func__, pte1_idx,
2390             pte1_load(pte1p)));
2391
2392         pte2 = pt2tab_load(pmap_pt2tab_entry(pmap, va));
2393         if (!pte2_is_valid(pte2)) {
2394                 /*
2395                  * Install new PT2s page into pmap PT2TAB.
2396                  */
2397                 m = vm_page_alloc(NULL, pte1_idx & ~PT2PG_MASK,
2398                     VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_ZERO);
2399                 if (m == NULL) {
2400                         if ((flags & PMAP_ENTER_NOSLEEP) == 0) {
2401                                 PMAP_UNLOCK(pmap);
2402                                 rw_wunlock(&pvh_global_lock);
2403                                 VM_WAIT;
2404                                 rw_wlock(&pvh_global_lock);
2405                                 PMAP_LOCK(pmap);
2406                         }
2407
2408                         /*
2409                          * Indicate the need to retry.  While waiting,
2410                          * the L2 page table page may have been allocated.
2411                          */
2412                         return (NULL);
2413                 }
2414                 pmap->pm_stats.resident_count++;
2415                 pt2pg_pa = pmap_pt2pg_init(pmap, va, m);
2416         } else {
2417                 pt2pg_pa = pte2_pa(pte2);
2418                 m = PHYS_TO_VM_PAGE(pt2pg_pa);
2419         }
2420
2421         pt2_wirecount_inc(m, pte1_idx);
2422         pt2_pa = page_pt2pa(pt2pg_pa, pte1_idx);
2423         pte1_store(pte1p, PTE1_LINK(pt2_pa));
2424
2425         return (m);
2426 }
2427
2428 static vm_page_t
2429 pmap_allocpte2(pmap_t pmap, vm_offset_t va, u_int flags)
2430 {
2431         u_int pte1_idx;
2432         pt1_entry_t *pte1p, pte1;
2433         vm_page_t m;
2434
2435         pte1_idx = pte1_index(va);
2436 retry:
2437         pte1p = pmap->pm_pt1 + pte1_idx;
2438         pte1 = pte1_load(pte1p);
2439
2440         /*
2441          * This supports switching from a 1MB page to a
2442          * normal 4K page.
2443          */
2444         if (pte1_is_section(pte1)) {
2445                 (void)pmap_demote_pte1(pmap, pte1p, va);
2446                 /*
2447                  * Reload pte1 after demotion.
2448                  *
2449                  * Note: Demotion can even fail as either PT2 is not find for
2450                  *       the virtual address or PT2PG can not be allocated.
2451                  */
2452                 pte1 = pte1_load(pte1p);
2453         }
2454
2455         /*
2456          * If the L2 page table page is mapped, we just increment the
2457          * hold count, and activate it.
2458          */
2459         if (pte1_is_link(pte1)) {
2460                 m = PHYS_TO_VM_PAGE(pte1_link_pa(pte1));
2461                 pt2_wirecount_inc(m, pte1_idx);
2462         } else  {
2463                 /*
2464                  * Here if the PT2 isn't mapped, or if it has
2465                  * been deallocated.
2466                  */
2467                 m = _pmap_allocpte2(pmap, va, flags);
2468                 if (m == NULL && (flags & PMAP_ENTER_NOSLEEP) == 0)
2469                         goto retry;
2470         }
2471
2472         return (m);
2473 }
2474
2475 static __inline void
2476 pmap_free_zero_pages(struct spglist *free)
2477 {
2478         vm_page_t m;
2479
2480         while ((m = SLIST_FIRST(free)) != NULL) {
2481                 SLIST_REMOVE_HEAD(free, plinks.s.ss);
2482                 /* Preserve the page's PG_ZERO setting. */
2483                 vm_page_free_toq(m);
2484         }
2485 }
2486
2487 /*
2488  *  Schedule the specified unused L2 page table page to be freed. Specifically,
2489  *  add the page to the specified list of pages that will be released to the
2490  *  physical memory manager after the TLB has been updated.
2491  */
2492 static __inline void
2493 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free)
2494 {
2495
2496         /*
2497          * Put page on a list so that it is released after
2498          * *ALL* TLB shootdown is done
2499          */
2500 #ifdef PMAP_DEBUG
2501         pmap_zero_page_check(m);
2502 #endif
2503         m->flags |= PG_ZERO;
2504         SLIST_INSERT_HEAD(free, m, plinks.s.ss);
2505 }
2506
2507 /*
2508  *  Unwire L2 page tables page.
2509  */
2510 static void
2511 pmap_unwire_pt2pg(pmap_t pmap, vm_offset_t va, vm_page_t m)
2512 {
2513         pt1_entry_t *pte1p, opte1 __unused;
2514         pt2_entry_t *pte2p;
2515         uint32_t i;
2516
2517         KASSERT(pt2pg_is_empty(m),
2518             ("%s: pmap %p PT2PG %p wired", __func__, pmap, m));
2519
2520         /*
2521          * Unmap all L2 page tables in the page from L1 page table.
2522          *
2523          * QQQ: Individual L2 page tables (except the last one) can be unmapped
2524          * earlier. However, we are doing that this way.
2525          */
2526         KASSERT(m->pindex == (pte1_index(va) & ~PT2PG_MASK),
2527             ("%s: pmap %p va %#x PT2PG %p bad index", __func__, pmap, va, m));
2528         pte1p = pmap->pm_pt1 + m->pindex;
2529         for (i = 0; i < NPT2_IN_PG; i++, pte1p++) {
2530                 KASSERT(m->md.pt2_wirecount[i] == 0,
2531                     ("%s: pmap %p PT2 %u (PG %p) wired", __func__, pmap, i, m));
2532                 opte1 = pte1_load(pte1p);
2533                 if (pte1_is_link(opte1)) {
2534                         pte1_clear(pte1p);
2535                         /*
2536                          * Flush intermediate TLB cache.
2537                          */
2538                         pmap_tlb_flush(pmap, (m->pindex + i) << PTE1_SHIFT);
2539                 }
2540 #ifdef INVARIANTS
2541                 else
2542                         KASSERT((opte1 == 0) || pte1_is_section(opte1),
2543                             ("%s: pmap %p va %#x bad pte1 %x at %u", __func__,
2544                             pmap, va, opte1, i));
2545 #endif
2546         }
2547
2548         /*
2549          * Unmap the page from PT2TAB.
2550          */
2551         pte2p = pmap_pt2tab_entry(pmap, va);
2552         (void)pt2tab_load_clear(pte2p);
2553         pmap_tlb_flush(pmap, pt2map_pt2pg(va));
2554
2555         m->wire_count = 0;
2556         pmap->pm_stats.resident_count--;
2557
2558         /*
2559          * This is a release store so that the ordinary store unmapping
2560          * the L2 page table page is globally performed before TLB shoot-
2561          * down is begun.
2562          */
2563         atomic_subtract_rel_int(&vm_cnt.v_wire_count, 1);
2564 }
2565
2566 /*
2567  *  Decrements a L2 page table page's wire count, which is used to record the
2568  *  number of valid page table entries within the page.  If the wire count
2569  *  drops to zero, then the page table page is unmapped.  Returns TRUE if the
2570  *  page table page was unmapped and FALSE otherwise.
2571  */
2572 static __inline boolean_t
2573 pmap_unwire_pt2(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2574 {
2575         pt2_wirecount_dec(m, pte1_index(va));
2576         if (pt2pg_is_empty(m)) {
2577                 /*
2578                  * QQQ: Wire count is zero, so whole page should be zero and
2579                  *      we can set PG_ZERO flag to it.
2580                  *      Note that when promotion is enabled, it takes some
2581                  *      more efforts. See pmap_unwire_pt2_all() below.
2582                  */
2583                 pmap_unwire_pt2pg(pmap, va, m);
2584                 pmap_add_delayed_free_list(m, free);
2585                 return (TRUE);
2586         } else
2587                 return (FALSE);
2588 }
2589
2590 /*
2591  *  Drop a L2 page table page's wire count at once, which is used to record
2592  *  the number of valid L2 page table entries within the page. If the wire
2593  *  count drops to zero, then the L2 page table page is unmapped.
2594  */
2595 static __inline void
2596 pmap_unwire_pt2_all(pmap_t pmap, vm_offset_t va, vm_page_t m,
2597     struct spglist *free)
2598 {
2599         u_int pte1_idx = pte1_index(va);
2600
2601         KASSERT(m->pindex == (pte1_idx & ~PT2PG_MASK),
2602                 ("%s: PT2 page's pindex is wrong", __func__));
2603         KASSERT(m->wire_count > pt2_wirecount_get(m, pte1_idx),
2604             ("%s: bad pt2 wire count %u > %u", __func__, m->wire_count,
2605             pt2_wirecount_get(m, pte1_idx)));
2606
2607         /*
2608          * It's possible that the L2 page table was never used.
2609          * It happened in case that a section was created without promotion.
2610          */
2611         if (pt2_is_full(m, va)) {
2612                 pt2_wirecount_set(m, pte1_idx, 0);
2613
2614                 /*
2615                  * QQQ: We clear L2 page table now, so when L2 page table page
2616                  *      is going to be freed, we can set it PG_ZERO flag ...
2617                  *      This function is called only on section mappings, so
2618                  *      hopefully it's not to big overload.
2619                  *
2620                  * XXX: If pmap is current, existing PT2MAP mapping could be
2621                  *      used for zeroing.
2622                  */
2623                 pmap_zero_page_area(m, page_pt2off(pte1_idx), NB_IN_PT2);
2624         }
2625 #ifdef INVARIANTS
2626         else
2627                 KASSERT(pt2_is_empty(m, va), ("%s: PT2 is not empty (%u)",
2628                     __func__, pt2_wirecount_get(m, pte1_idx)));
2629 #endif
2630         if (pt2pg_is_empty(m)) {
2631                 pmap_unwire_pt2pg(pmap, va, m);
2632                 pmap_add_delayed_free_list(m, free);
2633         }
2634 }
2635
2636 /*
2637  *  After removing a L2 page table entry, this routine is used to
2638  *  conditionally free the page, and manage the hold/wire counts.
2639  */
2640 static boolean_t
2641 pmap_unuse_pt2(pmap_t pmap, vm_offset_t va, struct spglist *free)
2642 {
2643         pt1_entry_t pte1;
2644         vm_page_t mpte;
2645
2646         if (va >= VM_MAXUSER_ADDRESS)
2647                 return (FALSE);
2648         pte1 = pte1_load(pmap_pte1(pmap, va));
2649         mpte = PHYS_TO_VM_PAGE(pte1_link_pa(pte1));
2650         return (pmap_unwire_pt2(pmap, va, mpte, free));
2651 }
2652
2653 /*************************************
2654  *
2655  *  Page management routines.
2656  *
2657  *************************************/
2658
2659 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
2660 CTASSERT(_NPCM == 11);
2661 CTASSERT(_NPCPV == 336);
2662
2663 static __inline struct pv_chunk *
2664 pv_to_chunk(pv_entry_t pv)
2665 {
2666
2667         return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
2668 }
2669
2670 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
2671
2672 #define PC_FREE0_9      0xfffffffful    /* Free values for index 0 through 9 */
2673 #define PC_FREE10       0x0000fffful    /* Free values for index 10 */
2674
2675 static const uint32_t pc_freemask[_NPCM] = {
2676         PC_FREE0_9, PC_FREE0_9, PC_FREE0_9,
2677         PC_FREE0_9, PC_FREE0_9, PC_FREE0_9,
2678         PC_FREE0_9, PC_FREE0_9, PC_FREE0_9,
2679         PC_FREE0_9, PC_FREE10
2680 };
2681
2682 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
2683         "Current number of pv entries");
2684
2685 #ifdef PV_STATS
2686 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
2687
2688 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
2689     "Current number of pv entry chunks");
2690 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
2691     "Current number of pv entry chunks allocated");
2692 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
2693     "Current number of pv entry chunks frees");
2694 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail,
2695     0, "Number of times tried to get a chunk page but failed.");
2696
2697 static long pv_entry_frees, pv_entry_allocs;
2698 static int pv_entry_spare;
2699
2700 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
2701     "Current number of pv entry frees");
2702 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs,
2703     0, "Current number of pv entry allocs");
2704 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
2705     "Current number of spare pv entries");
2706 #endif
2707
2708 /*
2709  *  Is given page managed?
2710  */
2711 static __inline boolean_t
2712 is_managed(vm_paddr_t pa)
2713 {
2714         vm_offset_t pgnum;
2715         vm_page_t m;
2716
2717         pgnum = atop(pa);
2718         if (pgnum >= first_page) {
2719                 m = PHYS_TO_VM_PAGE(pa);
2720                 if (m == NULL)
2721                         return (FALSE);
2722                 if ((m->oflags & VPO_UNMANAGED) == 0)
2723                         return (TRUE);
2724         }
2725         return (FALSE);
2726 }
2727
2728 static __inline boolean_t
2729 pte1_is_managed(pt1_entry_t pte1)
2730 {
2731
2732         return (is_managed(pte1_pa(pte1)));
2733 }
2734
2735 static __inline boolean_t
2736 pte2_is_managed(pt2_entry_t pte2)
2737 {
2738
2739         return (is_managed(pte2_pa(pte2)));
2740 }
2741
2742 /*
2743  *  We are in a serious low memory condition.  Resort to
2744  *  drastic measures to free some pages so we can allocate
2745  *  another pv entry chunk.
2746  */
2747 static vm_page_t
2748 pmap_pv_reclaim(pmap_t locked_pmap)
2749 {
2750         struct pch newtail;
2751         struct pv_chunk *pc;
2752         struct md_page *pvh;
2753         pt1_entry_t *pte1p;
2754         pmap_t pmap;
2755         pt2_entry_t *pte2p, tpte2;
2756         pv_entry_t pv;
2757         vm_offset_t va;
2758         vm_page_t m, m_pc;
2759         struct spglist free;
2760         uint32_t inuse;
2761         int bit, field, freed;
2762
2763         PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
2764         pmap = NULL;
2765         m_pc = NULL;
2766         SLIST_INIT(&free);
2767         TAILQ_INIT(&newtail);
2768         while ((pc = TAILQ_FIRST(&pv_chunks)) != NULL && (pv_vafree == 0 ||
2769             SLIST_EMPTY(&free))) {
2770                 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
2771                 if (pmap != pc->pc_pmap) {
2772                         if (pmap != NULL) {
2773                                 if (pmap != locked_pmap)
2774                                         PMAP_UNLOCK(pmap);
2775                         }
2776                         pmap = pc->pc_pmap;
2777                         /* Avoid deadlock and lock recursion. */
2778                         if (pmap > locked_pmap)
2779                                 PMAP_LOCK(pmap);
2780                         else if (pmap != locked_pmap && !PMAP_TRYLOCK(pmap)) {
2781                                 pmap = NULL;
2782                                 TAILQ_INSERT_TAIL(&newtail, pc, pc_lru);
2783                                 continue;
2784                         }
2785                 }
2786
2787                 /*
2788                  * Destroy every non-wired, 4 KB page mapping in the chunk.
2789                  */
2790                 freed = 0;
2791                 for (field = 0; field < _NPCM; field++) {
2792                         for (inuse = ~pc->pc_map[field] & pc_freemask[field];
2793                             inuse != 0; inuse &= ~(1UL << bit)) {
2794                                 bit = ffs(inuse) - 1;
2795                                 pv = &pc->pc_pventry[field * 32 + bit];
2796                                 va = pv->pv_va;
2797                                 pte1p = pmap_pte1(pmap, va);
2798                                 if (pte1_is_section(pte1_load(pte1p)))
2799                                         continue;
2800                                 pte2p = pmap_pte2(pmap, va);
2801                                 tpte2 = pte2_load(pte2p);
2802                                 if ((tpte2 & PTE2_W) == 0)
2803                                         tpte2 = pte2_load_clear(pte2p);
2804                                 pmap_pte2_release(pte2p);
2805                                 if ((tpte2 & PTE2_W) != 0)
2806                                         continue;
2807                                 KASSERT(tpte2 != 0,
2808                                     ("pmap_pv_reclaim: pmap %p va %#x zero pte",
2809                                     pmap, va));
2810                                 pmap_tlb_flush(pmap, va);
2811                                 m = PHYS_TO_VM_PAGE(pte2_pa(tpte2));
2812                                 if (pte2_is_dirty(tpte2))
2813                                         vm_page_dirty(m);
2814                                 if ((tpte2 & PTE2_A) != 0)
2815                                         vm_page_aflag_set(m, PGA_REFERENCED);
2816                                 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
2817                                 if (TAILQ_EMPTY(&m->md.pv_list) &&
2818                                     (m->flags & PG_FICTITIOUS) == 0) {
2819                                         pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
2820                                         if (TAILQ_EMPTY(&pvh->pv_list)) {
2821                                                 vm_page_aflag_clear(m,
2822                                                     PGA_WRITEABLE);
2823                                         }
2824                                 }
2825                                 pc->pc_map[field] |= 1UL << bit;
2826                                 pmap_unuse_pt2(pmap, va, &free);
2827                                 freed++;
2828                         }
2829                 }
2830                 if (freed == 0) {
2831                         TAILQ_INSERT_TAIL(&newtail, pc, pc_lru);
2832                         continue;
2833                 }
2834                 /* Every freed mapping is for a 4 KB page. */
2835                 pmap->pm_stats.resident_count -= freed;
2836                 PV_STAT(pv_entry_frees += freed);
2837                 PV_STAT(pv_entry_spare += freed);
2838                 pv_entry_count -= freed;
2839                 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2840                 for (field = 0; field < _NPCM; field++)
2841                         if (pc->pc_map[field] != pc_freemask[field]) {
2842                                 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc,
2843                                     pc_list);
2844                                 TAILQ_INSERT_TAIL(&newtail, pc, pc_lru);
2845
2846                                 /*
2847                                  * One freed pv entry in locked_pmap is
2848                                  * sufficient.
2849                                  */
2850                                 if (pmap == locked_pmap)
2851                                         goto out;
2852                                 break;
2853                         }
2854                 if (field == _NPCM) {
2855                         PV_STAT(pv_entry_spare -= _NPCPV);
2856                         PV_STAT(pc_chunk_count--);
2857                         PV_STAT(pc_chunk_frees++);
2858                         /* Entire chunk is free; return it. */
2859                         m_pc = PHYS_TO_VM_PAGE(pmap_kextract((vm_offset_t)pc));
2860                         pmap_qremove((vm_offset_t)pc, 1);
2861                         pmap_pte2list_free(&pv_vafree, (vm_offset_t)pc);
2862                         break;
2863                 }
2864         }
2865 out:
2866         TAILQ_CONCAT(&pv_chunks, &newtail, pc_lru);
2867         if (pmap != NULL) {
2868                 if (pmap != locked_pmap)
2869                         PMAP_UNLOCK(pmap);
2870         }
2871         if (m_pc == NULL && pv_vafree != 0 && SLIST_EMPTY(&free)) {
2872                 m_pc = SLIST_FIRST(&free);
2873                 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2874                 /* Recycle a freed page table page. */
2875                 m_pc->wire_count = 1;
2876                 atomic_add_int(&vm_cnt.v_wire_count, 1);
2877         }
2878         pmap_free_zero_pages(&free);
2879         return (m_pc);
2880 }
2881
2882 static void
2883 free_pv_chunk(struct pv_chunk *pc)
2884 {
2885         vm_page_t m;
2886
2887         TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
2888         PV_STAT(pv_entry_spare -= _NPCPV);
2889         PV_STAT(pc_chunk_count--);
2890         PV_STAT(pc_chunk_frees++);
2891         /* entire chunk is free, return it */
2892         m = PHYS_TO_VM_PAGE(pmap_kextract((vm_offset_t)pc));
2893         pmap_qremove((vm_offset_t)pc, 1);
2894         vm_page_unwire(m, PQ_NONE);
2895         vm_page_free(m);
2896         pmap_pte2list_free(&pv_vafree, (vm_offset_t)pc);
2897 }
2898
2899 /*
2900  *  Free the pv_entry back to the free list.
2901  */
2902 static void
2903 free_pv_entry(pmap_t pmap, pv_entry_t pv)
2904 {
2905         struct pv_chunk *pc;
2906         int idx, field, bit;
2907
2908         rw_assert(&pvh_global_lock, RA_WLOCKED);
2909         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2910         PV_STAT(pv_entry_frees++);
2911         PV_STAT(pv_entry_spare++);
2912         pv_entry_count--;
2913         pc = pv_to_chunk(pv);
2914         idx = pv - &pc->pc_pventry[0];
2915         field = idx / 32;
2916         bit = idx % 32;
2917         pc->pc_map[field] |= 1ul << bit;
2918         for (idx = 0; idx < _NPCM; idx++)
2919                 if (pc->pc_map[idx] != pc_freemask[idx]) {
2920                         /*
2921                          * 98% of the time, pc is already at the head of the
2922                          * list.  If it isn't already, move it to the head.
2923                          */
2924                         if (__predict_false(TAILQ_FIRST(&pmap->pm_pvchunk) !=
2925                             pc)) {
2926                                 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2927                                 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc,
2928                                     pc_list);
2929                         }
2930                         return;
2931                 }
2932         TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2933         free_pv_chunk(pc);
2934 }
2935
2936 /*
2937  *  Get a new pv_entry, allocating a block from the system
2938  *  when needed.
2939  */
2940 static pv_entry_t
2941 get_pv_entry(pmap_t pmap, boolean_t try)
2942 {
2943         static const struct timeval printinterval = { 60, 0 };
2944         static struct timeval lastprint;
2945         int bit, field;
2946         pv_entry_t pv;
2947         struct pv_chunk *pc;
2948         vm_page_t m;
2949
2950         rw_assert(&pvh_global_lock, RA_WLOCKED);
2951         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2952         PV_STAT(pv_entry_allocs++);
2953         pv_entry_count++;
2954         if (pv_entry_count > pv_entry_high_water)
2955                 if (ratecheck(&lastprint, &printinterval))
2956                         printf("Approaching the limit on PV entries, consider "
2957                             "increasing either the vm.pmap.shpgperproc or the "
2958                             "vm.pmap.pv_entry_max tunable.\n");
2959 retry:
2960         pc = TAILQ_FIRST(&pmap->pm_pvchunk);
2961         if (pc != NULL) {
2962                 for (field = 0; field < _NPCM; field++) {
2963                         if (pc->pc_map[field]) {
2964                                 bit = ffs(pc->pc_map[field]) - 1;
2965                                 break;
2966                         }
2967                 }
2968                 if (field < _NPCM) {
2969                         pv = &pc->pc_pventry[field * 32 + bit];
2970                         pc->pc_map[field] &= ~(1ul << bit);
2971                         /* If this was the last item, move it to tail */
2972                         for (field = 0; field < _NPCM; field++)
2973                                 if (pc->pc_map[field] != 0) {
2974                                         PV_STAT(pv_entry_spare--);
2975                                         return (pv);    /* not full, return */
2976                                 }
2977                         TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2978                         TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
2979                         PV_STAT(pv_entry_spare--);
2980                         return (pv);
2981                 }
2982         }
2983         /*
2984          * Access to the pte2list "pv_vafree" is synchronized by the pvh
2985          * global lock.  If "pv_vafree" is currently non-empty, it will
2986          * remain non-empty until pmap_pte2list_alloc() completes.
2987          */
2988         if (pv_vafree == 0 || (m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
2989             VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
2990                 if (try) {
2991                         pv_entry_count--;
2992                         PV_STAT(pc_chunk_tryfail++);
2993                         return (NULL);
2994                 }
2995                 m = pmap_pv_reclaim(pmap);
2996                 if (m == NULL)
2997                         goto retry;
2998         }
2999         PV_STAT(pc_chunk_count++);
3000         PV_STAT(pc_chunk_allocs++);
3001         pc = (struct pv_chunk *)pmap_pte2list_alloc(&pv_vafree);
3002         pmap_qenter((vm_offset_t)pc, &m, 1);
3003         pc->pc_pmap = pmap;
3004         pc->pc_map[0] = pc_freemask[0] & ~1ul;  /* preallocated bit 0 */
3005         for (field = 1; field < _NPCM; field++)
3006                 pc->pc_map[field] = pc_freemask[field];
3007         TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3008         pv = &pc->pc_pventry[0];
3009         TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3010         PV_STAT(pv_entry_spare += _NPCPV - 1);
3011         return (pv);
3012 }
3013
3014 /*
3015  *  Create a pv entry for page at pa for
3016  *  (pmap, va).
3017  */
3018 static void
3019 pmap_insert_entry(pmap_t pmap, vm_offset_t va, vm_page_t m)
3020 {
3021         pv_entry_t pv;
3022
3023         rw_assert(&pvh_global_lock, RA_WLOCKED);
3024         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3025         pv = get_pv_entry(pmap, FALSE);
3026         pv->pv_va = va;
3027         TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3028 }
3029
3030 static __inline pv_entry_t
3031 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3032 {
3033         pv_entry_t pv;
3034
3035         rw_assert(&pvh_global_lock, RA_WLOCKED);
3036         TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
3037                 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
3038                         TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
3039                         break;
3040                 }
3041         }
3042         return (pv);
3043 }
3044
3045 static void
3046 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3047 {
3048         pv_entry_t pv;
3049
3050         pv = pmap_pvh_remove(pvh, pmap, va);
3051         KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
3052         free_pv_entry(pmap, pv);
3053 }
3054
3055 static void
3056 pmap_remove_entry(pmap_t pmap, vm_page_t m, vm_offset_t va)
3057 {
3058         struct md_page *pvh;
3059
3060         rw_assert(&pvh_global_lock, RA_WLOCKED);
3061         pmap_pvh_free(&m->md, pmap, va);
3062         if (TAILQ_EMPTY(&m->md.pv_list) && (m->flags & PG_FICTITIOUS) == 0) {
3063                 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3064                 if (TAILQ_EMPTY(&pvh->pv_list))
3065                         vm_page_aflag_clear(m, PGA_WRITEABLE);
3066         }
3067 }
3068
3069 static void
3070 pmap_pv_demote_pte1(pmap_t pmap, vm_offset_t va, vm_paddr_t pa)
3071 {
3072         struct md_page *pvh;
3073         pv_entry_t pv;
3074         vm_offset_t va_last;
3075         vm_page_t m;
3076
3077         rw_assert(&pvh_global_lock, RA_WLOCKED);
3078         KASSERT((pa & PTE1_OFFSET) == 0,
3079             ("pmap_pv_demote_pte1: pa is not 1mpage aligned"));
3080
3081         /*
3082          * Transfer the 1mpage's pv entry for this mapping to the first
3083          * page's pv list.
3084          */
3085         pvh = pa_to_pvh(pa);
3086         va = pte1_trunc(va);
3087         pv = pmap_pvh_remove(pvh, pmap, va);
3088         KASSERT(pv != NULL, ("pmap_pv_demote_pte1: pv not found"));
3089         m = PHYS_TO_VM_PAGE(pa);
3090         TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3091         /* Instantiate the remaining NPTE2_IN_PT2 - 1 pv entries. */
3092         va_last = va + PTE1_SIZE - PAGE_SIZE;
3093         do {
3094                 m++;
3095                 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3096                     ("pmap_pv_demote_pte1: page %p is not managed", m));
3097                 va += PAGE_SIZE;
3098                 pmap_insert_entry(pmap, va, m);
3099         } while (va < va_last);
3100 }
3101
3102 static void
3103 pmap_pv_promote_pte1(pmap_t pmap, vm_offset_t va, vm_paddr_t pa)
3104 {
3105         struct md_page *pvh;
3106         pv_entry_t pv;
3107         vm_offset_t va_last;
3108         vm_page_t m;
3109
3110         rw_assert(&pvh_global_lock, RA_WLOCKED);
3111         KASSERT((pa & PTE1_OFFSET) == 0,
3112             ("pmap_pv_promote_pte1: pa is not 1mpage aligned"));
3113
3114         /*
3115          * Transfer the first page's pv entry for this mapping to the
3116          * 1mpage's pv list.  Aside from avoiding the cost of a call
3117          * to get_pv_entry(), a transfer avoids the possibility that
3118          * get_pv_entry() calls pmap_pv_reclaim() and that pmap_pv_reclaim()
3119          * removes one of the mappings that is being promoted.
3120          */
3121         m = PHYS_TO_VM_PAGE(pa);
3122         va = pte1_trunc(va);
3123         pv = pmap_pvh_remove(&m->md, pmap, va);
3124         KASSERT(pv != NULL, ("pmap_pv_promote_pte1: pv not found"));
3125         pvh = pa_to_pvh(pa);
3126         TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3127         /* Free the remaining NPTE2_IN_PT2 - 1 pv entries. */
3128         va_last = va + PTE1_SIZE - PAGE_SIZE;
3129         do {
3130                 m++;
3131                 va += PAGE_SIZE;
3132                 pmap_pvh_free(&m->md, pmap, va);
3133         } while (va < va_last);
3134 }
3135
3136 /*
3137  *  Conditionally create a pv entry.
3138  */
3139 static boolean_t
3140 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m)
3141 {
3142         pv_entry_t pv;
3143
3144         rw_assert(&pvh_global_lock, RA_WLOCKED);
3145         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3146         if (pv_entry_count < pv_entry_high_water &&
3147             (pv = get_pv_entry(pmap, TRUE)) != NULL) {
3148                 pv->pv_va = va;
3149                 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3150                 return (TRUE);
3151         } else
3152                 return (FALSE);
3153 }
3154
3155 /*
3156  *  Create the pv entries for each of the pages within a section.
3157  */
3158 static boolean_t
3159 pmap_pv_insert_pte1(pmap_t pmap, vm_offset_t va, vm_paddr_t pa)
3160 {
3161         struct md_page *pvh;
3162         pv_entry_t pv;
3163
3164         rw_assert(&pvh_global_lock, RA_WLOCKED);
3165         if (pv_entry_count < pv_entry_high_water &&
3166             (pv = get_pv_entry(pmap, TRUE)) != NULL) {
3167                 pv->pv_va = va;
3168                 pvh = pa_to_pvh(pa);
3169                 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3170                 return (TRUE);
3171         } else
3172                 return (FALSE);
3173 }
3174
3175 /*
3176  *  Tries to promote the NPTE2_IN_PT2, contiguous 4KB page mappings that are
3177  *  within a single page table page (PT2) to a single 1MB page mapping.
3178  *  For promotion to occur, two conditions must be met: (1) the 4KB page
3179  *  mappings must map aligned, contiguous physical memory and (2) the 4KB page
3180  *  mappings must have identical characteristics.
3181  *
3182  *  Managed (PG_MANAGED) mappings within the kernel address space are not
3183  *  promoted.  The reason is that kernel PTE1s are replicated in each pmap but
3184  *  pmap_remove_write(), pmap_clear_modify(), and pmap_clear_reference() only
3185  *  read the PTE1 from the kernel pmap.
3186  */
3187 static void
3188 pmap_promote_pte1(pmap_t pmap, pt1_entry_t *pte1p, vm_offset_t va)
3189 {
3190         pt1_entry_t npte1;
3191         pt2_entry_t *fpte2p, fpte2, fpte2_fav;
3192         pt2_entry_t *pte2p, pte2;
3193         vm_offset_t pteva __unused;
3194         vm_page_t m __unused;
3195
3196         PDEBUG(6, printf("%s(%p): try for va %#x pte1 %#x at %p\n", __func__,
3197             pmap, va, pte1_load(pte1p), pte1p));
3198
3199         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3200
3201         /*
3202          * Examine the first PTE2 in the specified PT2. Abort if this PTE2 is
3203          * either invalid, unused, or does not map the first 4KB physical page
3204          * within a 1MB page.
3205          */
3206         fpte2p = pmap_pte2_quick(pmap, pte1_trunc(va));
3207 setpte1:
3208         fpte2 = pte2_load(fpte2p);
3209         if ((fpte2 & ((PTE2_FRAME & PTE1_OFFSET) | PTE2_A | PTE2_V)) !=
3210             (PTE2_A | PTE2_V)) {
3211                 pmap_pte1_p_failures++;
3212                 CTR3(KTR_PMAP, "%s: failure(1) for va %#x in pmap %p",
3213                     __func__, va, pmap);
3214                 return;
3215         }
3216         if (pte2_is_managed(fpte2) && pmap == kernel_pmap) {
3217                 pmap_pte1_p_failures++;
3218                 CTR3(KTR_PMAP, "%s: failure(2) for va %#x in pmap %p",
3219                     __func__, va, pmap);
3220                 return;
3221         }
3222         if ((fpte2 & (PTE2_NM | PTE2_RO)) == PTE2_NM) {
3223                 /*
3224                  * When page is not modified, PTE2_RO can be set without
3225                  * a TLB invalidation.
3226                  *
3227                  * Note: When modified bit is being set, then in hardware case,
3228                  *       the TLB entry is re-read (updated) from PT2, and in
3229                  *       software case (abort), the PTE2 is read from PT2 and
3230                  *       TLB flushed if changed. The following cmpset() solves
3231                  *       any race with setting this bit in both cases.
3232                  */
3233                 if (!pte2_cmpset(fpte2p, fpte2, fpte2 | PTE2_RO))
3234                         goto setpte1;
3235                 fpte2 |= PTE2_RO;
3236         }
3237
3238         /*
3239          * Examine each of the other PTE2s in the specified PT2. Abort if this
3240          * PTE2 maps an unexpected 4KB physical page or does not have identical
3241          * characteristics to the first PTE2.
3242          */
3243         fpte2_fav = (fpte2 & (PTE2_FRAME | PTE2_A | PTE2_V));
3244         fpte2_fav += PTE1_SIZE - PTE2_SIZE; /* examine from the end */
3245         for (pte2p = fpte2p + NPTE2_IN_PT2 - 1; pte2p > fpte2p; pte2p--) {
3246 setpte2:
3247                 pte2 = pte2_load(pte2p);
3248                 if ((pte2 & (PTE2_FRAME | PTE2_A | PTE2_V)) != fpte2_fav) {
3249                         pmap_pte1_p_failures++;
3250                         CTR3(KTR_PMAP, "%s: failure(3) for va %#x in pmap %p",
3251                             __func__, va, pmap);
3252                         return;
3253                 }
3254                 if ((pte2 & (PTE2_NM | PTE2_RO)) == PTE2_NM) {
3255                         /*
3256                          * When page is not modified, PTE2_RO can be set
3257                          * without a TLB invalidation. See note above.
3258                          */
3259                         if (!pte2_cmpset(pte2p, pte2, pte2 | PTE2_RO))
3260                                 goto setpte2;
3261                         pte2 |= PTE2_RO;
3262                         pteva = pte1_trunc(va) | (pte2 & PTE1_OFFSET &
3263                             PTE2_FRAME);
3264                         CTR3(KTR_PMAP, "%s: protect for va %#x in pmap %p",
3265                             __func__, pteva, pmap);
3266                 }
3267                 if ((pte2 & PTE2_PROMOTE) != (fpte2 & PTE2_PROMOTE)) {
3268                         pmap_pte1_p_failures++;
3269                         CTR3(KTR_PMAP, "%s: failure(4) for va %#x in pmap %p",
3270                             __func__, va, pmap);
3271                         return;
3272                 }
3273
3274                 fpte2_fav -= PTE2_SIZE;
3275         }
3276         /*
3277          * The page table page in its current state will stay in PT2TAB
3278          * until the PTE1 mapping the section is demoted by pmap_demote_pte1()
3279          * or destroyed by pmap_remove_pte1().
3280          *
3281          * Note that L2 page table size is not equal to PAGE_SIZE.
3282          */
3283         m = PHYS_TO_VM_PAGE(trunc_page(pte1_link_pa(pte1_load(pte1p))));
3284         KASSERT(m >= vm_page_array && m < &vm_page_array[vm_page_array_size],
3285             ("%s: PT2 page is out of range", __func__));
3286         KASSERT(m->pindex == (pte1_index(va) & ~PT2PG_MASK),
3287             ("%s: PT2 page's pindex is wrong", __func__));
3288
3289         /*
3290          *  Get pte1 from pte2 format.
3291         */
3292         npte1 = (fpte2 & PTE1_FRAME) | ATTR_TO_L1(fpte2) | PTE1_V;
3293
3294         /*
3295          * Promote the pv entries.
3296          */
3297         if (pte2_is_managed(fpte2))
3298                 pmap_pv_promote_pte1(pmap, va, pte1_pa(npte1));
3299
3300         /*
3301          * Map the section.
3302          */
3303         if (pmap == kernel_pmap)
3304                 pmap_kenter_pte1(va, npte1);
3305         else
3306                 pte1_store(pte1p, npte1);
3307         /*
3308          * Flush old small mappings. We call single pmap_tlb_flush() in
3309          * pmap_demote_pte1() and pmap_remove_pte1(), so we must be sure that
3310          * no small mappings survive. We assume that given pmap is current and
3311          * don't play game with PTE2_NG.
3312          */
3313         pmap_tlb_flush_range(pmap, pte1_trunc(va), PTE1_SIZE);
3314
3315         pmap_pte1_promotions++;
3316         CTR3(KTR_PMAP, "%s: success for va %#x in pmap %p",
3317             __func__, va, pmap);
3318
3319         PDEBUG(6, printf("%s(%p): success for va %#x pte1 %#x(%#x) at %p\n",
3320             __func__, pmap, va, npte1, pte1_load(pte1p), pte1p));
3321 }
3322
3323 /*
3324  *  Zero L2 page table page.
3325  */
3326 static __inline void
3327 pmap_clear_pt2(pt2_entry_t *fpte2p)
3328 {
3329         pt2_entry_t *pte2p;
3330
3331         for (pte2p = fpte2p; pte2p < fpte2p + NPTE2_IN_PT2; pte2p++)
3332                 pte2_clear(pte2p);
3333
3334 }
3335
3336 /*
3337  *  Removes a 1MB page mapping from the kernel pmap.
3338  */
3339 static void
3340 pmap_remove_kernel_pte1(pmap_t pmap, pt1_entry_t *pte1p, vm_offset_t va)
3341 {
3342         vm_page_t m;
3343         uint32_t pte1_idx;
3344         pt2_entry_t *fpte2p;
3345         vm_paddr_t pt2_pa;
3346
3347         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3348         m = pmap_pt2_page(pmap, va);
3349         if (m == NULL)
3350                 /*
3351                  * QQQ: Is this function called only on promoted pte1?
3352                  *      We certainly do section mappings directly
3353                  *      (without promotion) in kernel !!!
3354                  */
3355                 panic("%s: missing pt2 page", __func__);
3356
3357         pte1_idx = pte1_index(va);
3358
3359         /*
3360          * Initialize the L2 page table.
3361          */
3362         fpte2p = page_pt2(pt2map_pt2pg(va), pte1_idx);
3363         pmap_clear_pt2(fpte2p);
3364
3365         /*
3366          * Remove the mapping.
3367          */
3368         pt2_pa = page_pt2pa(VM_PAGE_TO_PHYS(m), pte1_idx);
3369         pmap_kenter_pte1(va, PTE1_LINK(pt2_pa));
3370
3371         /*
3372          * QQQ: We do not need to invalidate PT2MAP mapping
3373          * as we did not change it. I.e. the L2 page table page
3374          * was and still is mapped the same way.
3375          */
3376 }
3377
3378 /*
3379  *  Do the things to unmap a section in a process
3380  */
3381 static void
3382 pmap_remove_pte1(pmap_t pmap, pt1_entry_t *pte1p, vm_offset_t sva,
3383     struct spglist *free)
3384 {
3385         pt1_entry_t opte1;
3386         struct md_page *pvh;
3387         vm_offset_t eva, va;
3388         vm_page_t m;
3389
3390         PDEBUG(6, printf("%s(%p): va %#x pte1 %#x at %p\n", __func__, pmap, sva,
3391             pte1_load(pte1p), pte1p));
3392
3393         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3394         KASSERT((sva & PTE1_OFFSET) == 0,
3395             ("%s: sva is not 1mpage aligned", __func__));
3396
3397         /*
3398          * Clear and invalidate the mapping. It should occupy one and only TLB
3399          * entry. So, pmap_tlb_flush() called with aligned address should be
3400          * sufficient.
3401          */
3402         opte1 = pte1_load_clear(pte1p);
3403         pmap_tlb_flush(pmap, sva);
3404
3405         if (pte1_is_wired(opte1))
3406                 pmap->pm_stats.wired_count -= PTE1_SIZE / PAGE_SIZE;
3407         pmap->pm_stats.resident_count -= PTE1_SIZE / PAGE_SIZE;
3408         if (pte1_is_managed(opte1)) {
3409                 pvh = pa_to_pvh(pte1_pa(opte1));
3410                 pmap_pvh_free(pvh, pmap, sva);
3411                 eva = sva + PTE1_SIZE;
3412                 for (va = sva, m = PHYS_TO_VM_PAGE(pte1_pa(opte1));
3413                     va < eva; va += PAGE_SIZE, m++) {
3414                         if (pte1_is_dirty(opte1))
3415                                 vm_page_dirty(m);
3416                         if (opte1 & PTE1_A)
3417                                 vm_page_aflag_set(m, PGA_REFERENCED);
3418                         if (TAILQ_EMPTY(&m->md.pv_list) &&
3419                             TAILQ_EMPTY(&pvh->pv_list))
3420                                 vm_page_aflag_clear(m, PGA_WRITEABLE);
3421                 }
3422         }
3423         if (pmap == kernel_pmap) {
3424                 /*
3425                  * L2 page table(s) can't be removed from kernel map as
3426                  * kernel counts on it (stuff around pmap_growkernel()).
3427                  */
3428                  pmap_remove_kernel_pte1(pmap, pte1p, sva);
3429         } else {
3430                 /*
3431                  * Get associated L2 page table page.
3432                  * It's possible that the page was never allocated.
3433                  */
3434                 m = pmap_pt2_page(pmap, sva);
3435                 if (m != NULL)
3436                         pmap_unwire_pt2_all(pmap, sva, m, free);
3437         }
3438 }
3439
3440 /*
3441  *  Fills L2 page table page with mappings to consecutive physical pages.
3442  */
3443 static __inline void
3444 pmap_fill_pt2(pt2_entry_t *fpte2p, pt2_entry_t npte2)
3445 {
3446         pt2_entry_t *pte2p;
3447
3448         for (pte2p = fpte2p; pte2p < fpte2p + NPTE2_IN_PT2; pte2p++) {
3449                 pte2_store(pte2p, npte2);
3450                 npte2 += PTE2_SIZE;
3451         }
3452 }
3453
3454 /*
3455  *  Tries to demote a 1MB page mapping. If demotion fails, the
3456  *  1MB page mapping is invalidated.
3457  */
3458 static boolean_t
3459 pmap_demote_pte1(pmap_t pmap, pt1_entry_t *pte1p, vm_offset_t va)
3460 {
3461         pt1_entry_t opte1, npte1;
3462         pt2_entry_t *fpte2p, npte2;
3463         vm_paddr_t pt2pg_pa, pt2_pa;
3464         vm_page_t m;
3465         struct spglist free;
3466         uint32_t pte1_idx, isnew = 0;
3467
3468         PDEBUG(6, printf("%s(%p): try for va %#x pte1 %#x at %p\n", __func__,
3469             pmap, va, pte1_load(pte1p), pte1p));
3470
3471         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3472
3473         opte1 = pte1_load(pte1p);
3474         KASSERT(pte1_is_section(opte1), ("%s: opte1 not a section", __func__));
3475
3476         if ((opte1 & PTE1_A) == 0 || (m = pmap_pt2_page(pmap, va)) == NULL) {
3477                 KASSERT(!pte1_is_wired(opte1),
3478                     ("%s: PT2 page for a wired mapping is missing", __func__));
3479
3480                 /*
3481                  * Invalidate the 1MB page mapping and return
3482                  * "failure" if the mapping was never accessed or the
3483                  * allocation of the new page table page fails.
3484                  */
3485                 if ((opte1 & PTE1_A) == 0 || (m = vm_page_alloc(NULL,
3486                     pte1_index(va) & ~PT2PG_MASK, VM_ALLOC_NOOBJ |
3487                     VM_ALLOC_NORMAL | VM_ALLOC_WIRED)) == NULL) {
3488                         SLIST_INIT(&free);
3489                         pmap_remove_pte1(pmap, pte1p, pte1_trunc(va), &free);
3490                         pmap_free_zero_pages(&free);
3491                         CTR3(KTR_PMAP, "%s: failure for va %#x in pmap %p",
3492                             __func__, va, pmap);
3493                         return (FALSE);
3494                 }
3495                 if (va < VM_MAXUSER_ADDRESS)
3496                         pmap->pm_stats.resident_count++;
3497
3498                 isnew = 1;
3499
3500                 /*
3501                  * We init all L2 page tables in the page even if
3502                  * we are going to change everything for one L2 page
3503                  * table in a while.
3504                  */
3505                 pt2pg_pa = pmap_pt2pg_init(pmap, va, m);
3506         } else {
3507                 if (va < VM_MAXUSER_ADDRESS) {
3508                         if (pt2_is_empty(m, va))
3509                                 isnew = 1; /* Demoting section w/o promotion. */
3510 #ifdef INVARIANTS
3511                         else
3512                                 KASSERT(pt2_is_full(m, va), ("%s: bad PT2 wire"
3513                                     " count %u", __func__,
3514                                     pt2_wirecount_get(m, pte1_index(va))));
3515 #endif
3516                 }
3517         }
3518
3519         pt2pg_pa = VM_PAGE_TO_PHYS(m);
3520         pte1_idx = pte1_index(va);
3521         /*
3522          * If the pmap is current, then the PT2MAP can provide access to
3523          * the page table page (promoted L2 page tables are not unmapped).
3524          * Otherwise, temporarily map the L2 page table page (m) into
3525          * the kernel's address space at either PADDR1 or PADDR2.
3526          *
3527          * Note that L2 page table size is not equal to PAGE_SIZE.
3528          */
3529         if (pmap_is_current(pmap))
3530                 fpte2p = page_pt2(pt2map_pt2pg(va), pte1_idx);
3531         else if (curthread->td_pinned > 0 && rw_wowned(&pvh_global_lock)) {
3532                 if (pte2_pa(pte2_load(PMAP1)) != pt2pg_pa) {
3533                         pte2_store(PMAP1, PTE2_KPT(pt2pg_pa));
3534 #ifdef SMP
3535                         PMAP1cpu = PCPU_GET(cpuid);
3536 #endif
3537                         tlb_flush_local((vm_offset_t)PADDR1);
3538                         PMAP1changed++;
3539                 } else
3540 #ifdef SMP
3541                 if (PMAP1cpu != PCPU_GET(cpuid)) {
3542                         PMAP1cpu = PCPU_GET(cpuid);
3543                         tlb_flush_local((vm_offset_t)PADDR1);
3544                         PMAP1changedcpu++;
3545                 } else
3546 #endif
3547                         PMAP1unchanged++;
3548                 fpte2p = page_pt2((vm_offset_t)PADDR1, pte1_idx);
3549         } else {
3550                 mtx_lock(&PMAP2mutex);
3551                 if (pte2_pa(pte2_load(PMAP2)) != pt2pg_pa) {
3552                         pte2_store(PMAP2, PTE2_KPT(pt2pg_pa));
3553                         tlb_flush((vm_offset_t)PADDR2);
3554                 }
3555                 fpte2p = page_pt2((vm_offset_t)PADDR2, pte1_idx);
3556         }
3557         pt2_pa = page_pt2pa(pt2pg_pa, pte1_idx);
3558         npte1 = PTE1_LINK(pt2_pa);
3559
3560         KASSERT((opte1 & PTE1_A) != 0,
3561             ("%s: opte1 is missing PTE1_A", __func__));
3562         KASSERT((opte1 & (PTE1_NM | PTE1_RO)) != PTE1_NM,
3563             ("%s: opte1 has PTE1_NM", __func__));
3564
3565         /*
3566          *  Get pte2 from pte1 format.
3567         */
3568         npte2 = pte1_pa(opte1) | ATTR_TO_L2(opte1) | PTE2_V;
3569
3570         /*
3571          * If the L2 page table page is new, initialize it. If the mapping
3572          * has changed attributes, update the page table entries.
3573          */
3574         if (isnew != 0) {
3575                 pt2_wirecount_set(m, pte1_idx, NPTE2_IN_PT2);
3576                 pmap_fill_pt2(fpte2p, npte2);
3577         } else if ((pte2_load(fpte2p) & PTE2_PROMOTE) !=
3578                     (npte2 & PTE2_PROMOTE))
3579                 pmap_fill_pt2(fpte2p, npte2);
3580
3581         KASSERT(pte2_pa(pte2_load(fpte2p)) == pte2_pa(npte2),
3582             ("%s: fpte2p and npte2 map different physical addresses",
3583             __func__));
3584
3585         if (fpte2p == PADDR2)
3586                 mtx_unlock(&PMAP2mutex);
3587
3588         /*
3589          * Demote the mapping. This pmap is locked. The old PTE1 has
3590          * PTE1_A set. If the old PTE1 has not PTE1_RO set, it also
3591          * has not PTE1_NM set. Thus, there is no danger of a race with
3592          * another processor changing the setting of PTE1_A and/or PTE1_NM
3593          * between the read above and the store below.
3594          */
3595         if (pmap == kernel_pmap)
3596                 pmap_kenter_pte1(va, npte1);
3597         else
3598                 pte1_store(pte1p, npte1);
3599
3600         /*
3601          * Flush old big mapping. The mapping should occupy one and only
3602          * TLB entry. So, pmap_tlb_flush() called with aligned address
3603          * should be sufficient.
3604          */
3605         pmap_tlb_flush(pmap, pte1_trunc(va));
3606
3607         /*
3608          * Demote the pv entry. This depends on the earlier demotion
3609          * of the mapping. Specifically, the (re)creation of a per-
3610          * page pv entry might trigger the execution of pmap_pv_reclaim(),
3611          * which might reclaim a newly (re)created per-page pv entry
3612          * and destroy the associated mapping. In order to destroy
3613          * the mapping, the PTE1 must have already changed from mapping
3614          * the 1mpage to referencing the page table page.
3615          */
3616         if (pte1_is_managed(opte1))
3617                 pmap_pv_demote_pte1(pmap, va, pte1_pa(opte1));
3618
3619         pmap_pte1_demotions++;
3620         CTR3(KTR_PMAP, "%s: success for va %#x in pmap %p",
3621             __func__, va, pmap);
3622
3623         PDEBUG(6, printf("%s(%p): success for va %#x pte1 %#x(%#x) at %p\n",
3624             __func__, pmap, va, npte1, pte1_load(pte1p), pte1p));
3625         return (TRUE);
3626 }
3627
3628 /*
3629  *      Insert the given physical page (p) at
3630  *      the specified virtual address (v) in the
3631  *      target physical map with the protection requested.
3632  *
3633  *      If specified, the page will be wired down, meaning
3634  *      that the related pte can not be reclaimed.
3635  *
3636  *      NB:  This is the only routine which MAY NOT lazy-evaluate
3637  *      or lose information.  That is, this routine must actually
3638  *      insert this page into the given map NOW.
3639  */
3640 int
3641 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
3642     u_int flags, int8_t psind)
3643 {
3644         pt1_entry_t *pte1p;
3645         pt2_entry_t *pte2p;
3646         pt2_entry_t npte2, opte2;
3647         pv_entry_t pv;
3648         vm_paddr_t opa, pa;
3649         vm_page_t mpte2, om;
3650         boolean_t wired;
3651
3652         va = trunc_page(va);
3653         mpte2 = NULL;
3654         wired = (flags & PMAP_ENTER_WIRED) != 0;
3655
3656         KASSERT(va <= vm_max_kernel_address, ("%s: toobig", __func__));
3657         KASSERT(va < UPT2V_MIN_ADDRESS || va >= UPT2V_MAX_ADDRESS,
3658             ("%s: invalid to pmap_enter page table pages (va: 0x%x)", __func__,
3659             va));
3660         if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_xbusied(m))
3661                 VM_OBJECT_ASSERT_LOCKED(m->object);
3662
3663         rw_wlock(&pvh_global_lock);
3664         PMAP_LOCK(pmap);
3665         sched_pin();
3666
3667         /*
3668          * In the case that a page table page is not
3669          * resident, we are creating it here.
3670          */
3671         if (va < VM_MAXUSER_ADDRESS) {
3672                 mpte2 = pmap_allocpte2(pmap, va, flags);
3673                 if (mpte2 == NULL) {
3674                         KASSERT((flags & PMAP_ENTER_NOSLEEP) != 0,
3675                             ("pmap_allocpte2 failed with sleep allowed"));
3676                         sched_unpin();
3677                         rw_wunlock(&pvh_global_lock);
3678                         PMAP_UNLOCK(pmap);
3679                         return (KERN_RESOURCE_SHORTAGE);
3680                 }
3681         }
3682         pte1p = pmap_pte1(pmap, va);
3683         if (pte1_is_section(pte1_load(pte1p)))
3684                 panic("%s: attempted on 1MB page", __func__);
3685         pte2p = pmap_pte2_quick(pmap, va);
3686         if (pte2p == NULL)
3687                 panic("%s: invalid L1 page table entry va=%#x", __func__, va);
3688
3689         om = NULL;
3690         pa = VM_PAGE_TO_PHYS(m);
3691         opte2 = pte2_load(pte2p);
3692         opa = pte2_pa(opte2);
3693         /*
3694          * Mapping has not changed, must be protection or wiring change.
3695          */
3696         if (pte2_is_valid(opte2) && (opa == pa)) {
3697                 /*
3698                  * Wiring change, just update stats. We don't worry about
3699                  * wiring PT2 pages as they remain resident as long as there
3700                  * are valid mappings in them. Hence, if a user page is wired,
3701                  * the PT2 page will be also.
3702                  */
3703                 if (wired && !pte2_is_wired(opte2))
3704                         pmap->pm_stats.wired_count++;
3705                 else if (!wired && pte2_is_wired(opte2))
3706                         pmap->pm_stats.wired_count--;
3707
3708                 /*
3709                  * Remove extra pte2 reference
3710                  */
3711                 if (mpte2)
3712                         pt2_wirecount_dec(mpte2, pte1_index(va));
3713                 if (pte2_is_managed(opte2))
3714                         om = m;
3715                 goto validate;
3716         }
3717
3718         /*
3719          * QQQ: We think that changing physical address on writeable mapping
3720          *      is not safe. Well, maybe on kernel address space with correct
3721          *      locking, it can make a sense. However, we have no idea why
3722          *      anyone should do that on user address space. Are we wrong?
3723          */
3724         KASSERT((opa == 0) || (opa == pa) ||
3725             !pte2_is_valid(opte2) || ((opte2 & PTE2_RO) != 0),
3726             ("%s: pmap %p va %#x(%#x) opa %#x pa %#x - gotcha %#x %#x!",
3727             __func__, pmap, va, opte2, opa, pa, flags, prot));
3728
3729         pv = NULL;
3730
3731         /*
3732          * Mapping has changed, invalidate old range and fall through to
3733          * handle validating new mapping.
3734          */
3735         if (opa) {
3736                 if (pte2_is_wired(opte2))
3737                         pmap->pm_stats.wired_count--;
3738                 if (pte2_is_managed(opte2)) {
3739                         om = PHYS_TO_VM_PAGE(opa);
3740                         pv = pmap_pvh_remove(&om->md, pmap, va);
3741                 }
3742                 /*
3743                  * Remove extra pte2 reference
3744                  */
3745                 if (mpte2 != NULL)
3746                         pt2_wirecount_dec(mpte2, va >> PTE1_SHIFT);
3747         } else
3748                 pmap->pm_stats.resident_count++;
3749
3750         /*
3751          * Enter on the PV list if part of our managed memory.
3752          */
3753         if ((m->oflags & VPO_UNMANAGED) == 0) {
3754                 KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva,
3755                     ("%s: managed mapping within the clean submap", __func__));
3756                 if (pv == NULL)
3757                         pv = get_pv_entry(pmap, FALSE);
3758                 pv->pv_va = va;
3759                 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3760         } else if (pv != NULL)
3761                 free_pv_entry(pmap, pv);
3762
3763         /*
3764          * Increment counters
3765          */
3766         if (wired)
3767                 pmap->pm_stats.wired_count++;
3768
3769 validate:
3770         /*
3771          * Now validate mapping with desired protection/wiring.
3772          */
3773         npte2 = PTE2(pa, PTE2_NM, m->md.pat_mode);
3774         if (prot & VM_PROT_WRITE) {
3775                 if (pte2_is_managed(npte2))
3776                         vm_page_aflag_set(m, PGA_WRITEABLE);
3777         }
3778         else
3779                 npte2 |= PTE2_RO;
3780         if ((prot & VM_PROT_EXECUTE) == 0)
3781                 npte2 |= PTE2_NX;
3782         if (wired)
3783                 npte2 |= PTE2_W;
3784         if (va < VM_MAXUSER_ADDRESS)
3785                 npte2 |= PTE2_U;
3786         if (pmap != kernel_pmap)
3787                 npte2 |= PTE2_NG;
3788
3789         /*
3790          * If the mapping or permission bits are different, we need
3791          * to update the pte2.
3792          *
3793          * QQQ: Think again and again what to do
3794          *      if the mapping is going to be changed!
3795          */
3796         if ((opte2 & ~(PTE2_NM | PTE2_A)) != (npte2 & ~(PTE2_NM | PTE2_A))) {
3797                 /*
3798                  * Sync icache if exec permission and attribute PTE2_ATTR_WB_WA
3799                  * is set. Do it now, before the mapping is stored and made
3800                  * valid for hardware table walk. If done later, there is a race
3801                  * for other threads of current process in lazy loading case.
3802                  * Don't do it for kernel memory which is mapped with exec
3803                  * permission even if the memory isn't going to hold executable
3804                  * code. The only time when icache sync is needed is after
3805                  * kernel module is loaded and the relocation info is processed.
3806                  * And it's done in elf_cpu_load_file().
3807                  *
3808                  * QQQ: (1) Does it exist any better way where
3809                  *          or how to sync icache?
3810                  *      (2) Now, we do it on a page basis.
3811                  */
3812                 if ((prot & VM_PROT_EXECUTE) && pmap != kernel_pmap &&
3813                     m->md.pat_mode == PTE2_ATTR_WB_WA &&
3814                     (opa != pa || (opte2 & PTE2_NX)))
3815                         cache_icache_sync_fresh(va, pa, PAGE_SIZE);
3816
3817                 npte2 |= PTE2_A;
3818                 if (flags & VM_PROT_WRITE)
3819                         npte2 &= ~PTE2_NM;
3820                 if (opte2 & PTE2_V) {
3821                         /* Change mapping with break-before-make approach. */
3822                         opte2 = pte2_load_clear(pte2p);
3823                         pmap_tlb_flush(pmap, va);
3824                         pte2_store(pte2p, npte2);
3825                         if (opte2 & PTE2_A) {
3826                                 if (pte2_is_managed(opte2))
3827                                         vm_page_aflag_set(om, PGA_REFERENCED);
3828                         }
3829                         if (pte2_is_dirty(opte2)) {
3830                                 if (pte2_is_managed(opte2))
3831                                         vm_page_dirty(om);
3832                         }
3833                         if (pte2_is_managed(opte2) &&
3834                             TAILQ_EMPTY(&om->md.pv_list) &&
3835                             ((om->flags & PG_FICTITIOUS) != 0 ||
3836                             TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
3837                                 vm_page_aflag_clear(om, PGA_WRITEABLE);
3838                 } else
3839                         pte2_store(pte2p, npte2);
3840         }
3841 #if 0
3842         else {
3843                 /*
3844                  * QQQ: In time when both access and not mofified bits are
3845                  *      emulated by software, this should not happen. Some
3846                  *      analysis is need, if this really happen. Missing
3847                  *      tlb flush somewhere could be the reason.
3848                  */
3849                 panic("%s: pmap %p va %#x opte2 %x npte2 %x !!", __func__, pmap,
3850                     va, opte2, npte2);
3851         }
3852 #endif
3853         /*
3854          * If both the L2 page table page and the reservation are fully
3855          * populated, then attempt promotion.
3856          */
3857         if ((mpte2 == NULL || pt2_is_full(mpte2, va)) &&
3858             sp_enabled && (m->flags & PG_FICTITIOUS) == 0 &&
3859             vm_reserv_level_iffullpop(m) == 0)
3860                 pmap_promote_pte1(pmap, pte1p, va);
3861         sched_unpin();
3862         rw_wunlock(&pvh_global_lock);
3863         PMAP_UNLOCK(pmap);
3864         return (KERN_SUCCESS);
3865 }
3866
3867 /*
3868  *  Do the things to unmap a page in a process.
3869  */
3870 static int
3871 pmap_remove_pte2(pmap_t pmap, pt2_entry_t *pte2p, vm_offset_t va,
3872     struct spglist *free)
3873 {
3874         pt2_entry_t opte2;
3875         vm_page_t m;
3876
3877         rw_assert(&pvh_global_lock, RA_WLOCKED);
3878         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3879
3880         /* Clear and invalidate the mapping. */
3881         opte2 = pte2_load_clear(pte2p);
3882         pmap_tlb_flush(pmap, va);
3883
3884         KASSERT(pte2_is_valid(opte2), ("%s: pmap %p va %#x not link pte2 %#x",
3885             __func__, pmap, va, opte2));
3886
3887         if (opte2 & PTE2_W)
3888                 pmap->pm_stats.wired_count -= 1;
3889         pmap->pm_stats.resident_count -= 1;
3890         if (pte2_is_managed(opte2)) {
3891                 m = PHYS_TO_VM_PAGE(pte2_pa(opte2));
3892                 if (pte2_is_dirty(opte2))
3893                         vm_page_dirty(m);
3894                 if (opte2 & PTE2_A)
3895                         vm_page_aflag_set(m, PGA_REFERENCED);
3896                 pmap_remove_entry(pmap, m, va);
3897         }
3898         return (pmap_unuse_pt2(pmap, va, free));
3899 }
3900
3901 /*
3902  *  Remove a single page from a process address space.
3903  */
3904 static void
3905 pmap_remove_page(pmap_t pmap, vm_offset_t va, struct spglist *free)
3906 {
3907         pt2_entry_t *pte2p;
3908
3909         rw_assert(&pvh_global_lock, RA_WLOCKED);
3910         KASSERT(curthread->td_pinned > 0,
3911             ("%s: curthread not pinned", __func__));
3912         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3913         if ((pte2p = pmap_pte2_quick(pmap, va)) == NULL ||
3914             !pte2_is_valid(pte2_load(pte2p)))
3915                 return;
3916         pmap_remove_pte2(pmap, pte2p, va, free);
3917 }
3918
3919 /*
3920  *  Remove the given range of addresses from the specified map.
3921  *
3922  *  It is assumed that the start and end are properly
3923  *  rounded to the page size.
3924  */
3925 void
3926 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3927 {
3928         vm_offset_t nextva;
3929         pt1_entry_t *pte1p, pte1;
3930         pt2_entry_t *pte2p, pte2;
3931         struct spglist free;
3932
3933         /*
3934          * Perform an unsynchronized read. This is, however, safe.
3935          */
3936         if (pmap->pm_stats.resident_count == 0)
3937                 return;
3938
3939         SLIST_INIT(&free);
3940
3941         rw_wlock(&pvh_global_lock);
3942         sched_pin();
3943         PMAP_LOCK(pmap);
3944
3945         /*
3946          * Special handling of removing one page. A very common
3947          * operation and easy to short circuit some code.
3948          */
3949         if (sva + PAGE_SIZE == eva) {
3950                 pte1 = pte1_load(pmap_pte1(pmap, sva));
3951                 if (pte1_is_link(pte1)) {
3952                         pmap_remove_page(pmap, sva, &free);
3953                         goto out;
3954                 }
3955         }
3956
3957         for (; sva < eva; sva = nextva) {
3958                 /*
3959                  * Calculate address for next L2 page table.
3960                  */
3961                 nextva = pte1_trunc(sva + PTE1_SIZE);
3962                 if (nextva < sva)
3963                         nextva = eva;
3964                 if (pmap->pm_stats.resident_count == 0)
3965                         break;
3966
3967                 pte1p = pmap_pte1(pmap, sva);
3968                 pte1 = pte1_load(pte1p);
3969
3970                 /*
3971                  * Weed out invalid mappings. Note: we assume that the L1 page
3972                  * table is always allocated, and in kernel virtual.
3973                  */
3974                 if (pte1 == 0)
3975                         continue;
3976
3977                 if (pte1_is_section(pte1)) {
3978                         /*
3979                          * Are we removing the entire large page?  If not,
3980                          * demote the mapping and fall through.
3981                          */
3982                         if (sva + PTE1_SIZE == nextva && eva >= nextva) {
3983                                 pmap_remove_pte1(pmap, pte1p, sva, &free);
3984                                 continue;
3985                         } else if (!pmap_demote_pte1(pmap, pte1p, sva)) {
3986                                 /* The large page mapping was destroyed. */
3987                                 continue;
3988                         }
3989 #ifdef INVARIANTS
3990                         else {
3991                                 /* Update pte1 after demotion. */
3992                                 pte1 = pte1_load(pte1p);
3993                         }
3994 #endif
3995                 }
3996
3997                 KASSERT(pte1_is_link(pte1), ("%s: pmap %p va %#x pte1 %#x at %p"
3998                     " is not link", __func__, pmap, sva, pte1, pte1p));
3999
4000                 /*
4001                  * Limit our scan to either the end of the va represented
4002                  * by the current L2 page table page, or to the end of the
4003                  * range being removed.
4004                  */
4005                 if (nextva > eva)
4006                         nextva = eva;
4007
4008                 for (pte2p = pmap_pte2_quick(pmap, sva); sva != nextva;
4009                     pte2p++, sva += PAGE_SIZE) {
4010                         pte2 = pte2_load(pte2p);
4011                         if (!pte2_is_valid(pte2))
4012                                 continue;
4013                         if (pmap_remove_pte2(pmap, pte2p, sva, &free))
4014                                 break;
4015                 }
4016         }
4017 out:
4018         sched_unpin();
4019         rw_wunlock(&pvh_global_lock);
4020         PMAP_UNLOCK(pmap);
4021         pmap_free_zero_pages(&free);
4022 }
4023
4024 /*
4025  *      Routine:        pmap_remove_all
4026  *      Function:
4027  *              Removes this physical page from
4028  *              all physical maps in which it resides.
4029  *              Reflects back modify bits to the pager.
4030  *
4031  *      Notes:
4032  *              Original versions of this routine were very
4033  *              inefficient because they iteratively called
4034  *              pmap_remove (slow...)
4035  */
4036
4037 void
4038 pmap_remove_all(vm_page_t m)
4039 {
4040         struct md_page *pvh;
4041         pv_entry_t pv;
4042         pmap_t pmap;
4043         pt2_entry_t *pte2p, opte2;
4044         pt1_entry_t *pte1p;
4045         vm_offset_t va;
4046         struct spglist free;
4047
4048         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4049             ("%s: page %p is not managed", __func__, m));
4050         SLIST_INIT(&free);
4051         rw_wlock(&pvh_global_lock);
4052         sched_pin();
4053         if ((m->flags & PG_FICTITIOUS) != 0)
4054                 goto small_mappings;
4055         pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
4056         while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
4057                 va = pv->pv_va;
4058                 pmap = PV_PMAP(pv);
4059                 PMAP_LOCK(pmap);
4060                 pte1p = pmap_pte1(pmap, va);
4061                 (void)pmap_demote_pte1(pmap, pte1p, va);
4062                 PMAP_UNLOCK(pmap);
4063         }
4064 small_mappings:
4065         while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
4066                 pmap = PV_PMAP(pv);
4067                 PMAP_LOCK(pmap);
4068                 pmap->pm_stats.resident_count--;
4069                 pte1p = pmap_pte1(pmap, pv->pv_va);
4070                 KASSERT(!pte1_is_section(pte1_load(pte1p)), ("%s: found "
4071                     "a 1mpage in page %p's pv list", __func__, m));
4072                 pte2p = pmap_pte2_quick(pmap, pv->pv_va);
4073                 opte2 = pte2_load_clear(pte2p);
4074                 pmap_tlb_flush(pmap, pv->pv_va);
4075                 KASSERT(pte2_is_valid(opte2), ("%s: pmap %p va %x zero pte2",
4076                     __func__, pmap, pv->pv_va));
4077                 if (pte2_is_wired(opte2))
4078                         pmap->pm_stats.wired_count--;
4079                 if (opte2 & PTE2_A)
4080                         vm_page_aflag_set(m, PGA_REFERENCED);
4081
4082                 /*
4083                  * Update the vm_page_t clean and reference bits.
4084                  */
4085                 if (pte2_is_dirty(opte2))
4086                         vm_page_dirty(m);
4087                 pmap_unuse_pt2(pmap, pv->pv_va, &free);
4088                 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
4089                 free_pv_entry(pmap, pv);
4090                 PMAP_UNLOCK(pmap);
4091         }
4092         vm_page_aflag_clear(m, PGA_WRITEABLE);
4093         sched_unpin();
4094         rw_wunlock(&pvh_global_lock);
4095         pmap_free_zero_pages(&free);
4096 }
4097
4098 /*
4099  *  Just subroutine for pmap_remove_pages() to reasonably satisfy
4100  *  good coding style, a.k.a. 80 character line width limit hell.
4101  */
4102 static __inline void
4103 pmap_remove_pte1_quick(pmap_t pmap, pt1_entry_t pte1, pv_entry_t pv,
4104     struct spglist *free)
4105 {
4106         vm_paddr_t pa;
4107         vm_page_t m, mt, mpt2pg;
4108         struct md_page *pvh;
4109
4110         pa = pte1_pa(pte1);
4111         m = PHYS_TO_VM_PAGE(pa);
4112
4113         KASSERT(m->phys_addr == pa, ("%s: vm_page_t %p addr mismatch %#x %#x",
4114             __func__, m, m->phys_addr, pa));
4115         KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
4116             m < &vm_page_array[vm_page_array_size],
4117             ("%s: bad pte1 %#x", __func__, pte1));
4118
4119         if (pte1_is_dirty(pte1)) {
4120                 for (mt = m; mt < &m[PTE1_SIZE / PAGE_SIZE]; mt++)
4121                         vm_page_dirty(mt);
4122         }
4123
4124         pmap->pm_stats.resident_count -= PTE1_SIZE / PAGE_SIZE;
4125         pvh = pa_to_pvh(pa);
4126         TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
4127         if (TAILQ_EMPTY(&pvh->pv_list)) {
4128                 for (mt = m; mt < &m[PTE1_SIZE / PAGE_SIZE]; mt++)
4129                         if (TAILQ_EMPTY(&mt->md.pv_list))
4130                                 vm_page_aflag_clear(mt, PGA_WRITEABLE);
4131         }
4132         mpt2pg = pmap_pt2_page(pmap, pv->pv_va);
4133         if (mpt2pg != NULL)
4134                 pmap_unwire_pt2_all(pmap, pv->pv_va, mpt2pg, free);
4135 }
4136
4137 /*
4138  *  Just subroutine for pmap_remove_pages() to reasonably satisfy
4139  *  good coding style, a.k.a. 80 character line width limit hell.
4140  */
4141 static __inline void
4142 pmap_remove_pte2_quick(pmap_t pmap, pt2_entry_t pte2, pv_entry_t pv,
4143     struct spglist *free)
4144 {
4145         vm_paddr_t pa;
4146         vm_page_t m;
4147         struct md_page *pvh;
4148
4149         pa = pte2_pa(pte2);
4150         m = PHYS_TO_VM_PAGE(pa);
4151
4152         KASSERT(m->phys_addr == pa, ("%s: vm_page_t %p addr mismatch %#x %#x",
4153             __func__, m, m->phys_addr, pa));
4154         KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
4155             m < &vm_page_array[vm_page_array_size],
4156             ("%s: bad pte2 %#x", __func__, pte2));
4157
4158         if (pte2_is_dirty(pte2))
4159                 vm_page_dirty(m);
4160
4161         pmap->pm_stats.resident_count--;
4162         TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
4163         if (TAILQ_EMPTY(&m->md.pv_list) && (m->flags & PG_FICTITIOUS) == 0) {
4164                 pvh = pa_to_pvh(pa);
4165                 if (TAILQ_EMPTY(&pvh->pv_list))
4166                         vm_page_aflag_clear(m, PGA_WRITEABLE);
4167         }
4168         pmap_unuse_pt2(pmap, pv->pv_va, free);
4169 }
4170
4171 /*
4172  *  Remove all pages from specified address space this aids process
4173  *  exit speeds. Also, this code is special cased for current process
4174  *  only, but can have the more generic (and slightly slower) mode enabled.
4175  *  This is much faster than pmap_remove in the case of running down
4176  *  an entire address space.
4177  */
4178 void
4179 pmap_remove_pages(pmap_t pmap)
4180 {
4181         pt1_entry_t *pte1p, pte1;
4182         pt2_entry_t *pte2p, pte2;
4183         pv_entry_t pv;
4184         struct pv_chunk *pc, *npc;
4185         struct spglist free;
4186         int field, idx;
4187         int32_t bit;
4188         uint32_t inuse, bitmask;
4189         boolean_t allfree;
4190
4191         /*
4192          * Assert that the given pmap is only active on the current
4193          * CPU.  Unfortunately, we cannot block another CPU from
4194          * activating the pmap while this function is executing.
4195          */
4196         KASSERT(pmap == vmspace_pmap(curthread->td_proc->p_vmspace),
4197             ("%s: non-current pmap %p", __func__, pmap));
4198 #if defined(SMP) && defined(INVARIANTS)
4199         {
4200                 cpuset_t other_cpus;
4201
4202                 sched_pin();
4203                 other_cpus = pmap->pm_active;
4204                 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
4205                 sched_unpin();
4206                 KASSERT(CPU_EMPTY(&other_cpus),
4207                     ("%s: pmap %p active on other cpus", __func__, pmap));
4208         }
4209 #endif
4210         SLIST_INIT(&free);
4211         rw_wlock(&pvh_global_lock);
4212         PMAP_LOCK(pmap);
4213         sched_pin();
4214         TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
4215                 KASSERT(pc->pc_pmap == pmap, ("%s: wrong pmap %p %p",
4216                     __func__, pmap, pc->pc_pmap));
4217                 allfree = TRUE;
4218                 for (field = 0; field < _NPCM; field++) {
4219                         inuse = (~(pc->pc_map[field])) & pc_freemask[field];
4220                         while (inuse != 0) {
4221                                 bit = ffs(inuse) - 1;
4222                                 bitmask = 1UL << bit;
4223                                 idx = field * 32 + bit;
4224                                 pv = &pc->pc_pventry[idx];
4225                                 inuse &= ~bitmask;
4226
4227                                 /*
4228                                  * Note that we cannot remove wired pages
4229                                  * from a process' mapping at this time
4230                                  */
4231                                 pte1p = pmap_pte1(pmap, pv->pv_va);
4232                                 pte1 = pte1_load(pte1p);
4233                                 if (pte1_is_section(pte1)) {
4234                                         if (pte1_is_wired(pte1))  {
4235                                                 allfree = FALSE;
4236                                                 continue;
4237                                         }
4238                                         pte1_clear(pte1p);
4239                                         pmap_remove_pte1_quick(pmap, pte1, pv,
4240                                             &free);
4241                                 }
4242                                 else if (pte1_is_link(pte1)) {
4243                                         pte2p = pt2map_entry(pv->pv_va);
4244                                         pte2 = pte2_load(pte2p);
4245
4246                                         if (!pte2_is_valid(pte2)) {
4247                                                 printf("%s: pmap %p va %#x "
4248                                                     "pte2 %#x\n", __func__,
4249                                                     pmap, pv->pv_va, pte2);
4250                                                 panic("bad pte2");
4251                                         }
4252
4253                                         if (pte2_is_wired(pte2))   {
4254                                                 allfree = FALSE;
4255                                                 continue;
4256                                         }
4257                                         pte2_clear(pte2p);
4258                                         pmap_remove_pte2_quick(pmap, pte2, pv,
4259                                             &free);
4260                                 } else {
4261                                         printf("%s: pmap %p va %#x pte1 %#x\n",
4262                                             __func__, pmap, pv->pv_va, pte1);
4263                                         panic("bad pte1");
4264                                 }
4265
4266                                 /* Mark free */
4267                                 PV_STAT(pv_entry_frees++);
4268                                 PV_STAT(pv_entry_spare++);
4269                                 pv_entry_count--;
4270                                 pc->pc_map[field] |= bitmask;
4271                         }
4272                 }
4273                 if (allfree) {
4274                         TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
4275                         free_pv_chunk(pc);
4276                 }
4277         }
4278         tlb_flush_all_ng_local();
4279         sched_unpin();
4280         rw_wunlock(&pvh_global_lock);
4281         PMAP_UNLOCK(pmap);
4282         pmap_free_zero_pages(&free);
4283 }
4284
4285 /*
4286  *  This code makes some *MAJOR* assumptions:
4287  *  1. Current pmap & pmap exists.
4288  *  2. Not wired.
4289  *  3. Read access.
4290  *  4. No L2 page table pages.
4291  *  but is *MUCH* faster than pmap_enter...
4292  */
4293 static vm_page_t
4294 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
4295     vm_prot_t prot, vm_page_t mpt2pg)
4296 {
4297         pt2_entry_t *pte2p, pte2;
4298         vm_paddr_t pa;
4299         struct spglist free;
4300         uint32_t l2prot;
4301
4302         KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
4303             (m->oflags & VPO_UNMANAGED) != 0,
4304             ("%s: managed mapping within the clean submap", __func__));
4305         rw_assert(&pvh_global_lock, RA_WLOCKED);
4306         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4307
4308         /*
4309          * In the case that a L2 page table page is not
4310          * resident, we are creating it here.
4311          */
4312         if (va < VM_MAXUSER_ADDRESS) {
4313                 u_int pte1_idx;
4314                 pt1_entry_t pte1, *pte1p;
4315                 vm_paddr_t pt2_pa;
4316
4317                 /*
4318                  * Get L1 page table things.
4319                  */
4320                 pte1_idx = pte1_index(va);
4321                 pte1p = pmap_pte1(pmap, va);
4322                 pte1 = pte1_load(pte1p);
4323
4324                 if (mpt2pg && (mpt2pg->pindex == (pte1_idx & ~PT2PG_MASK))) {
4325                         /*
4326                          * Each of NPT2_IN_PG L2 page tables on the page can
4327                          * come here. Make sure that associated L1 page table
4328                          * link is established.
4329                          *
4330                          * QQQ: It comes that we don't establish all links to
4331                          *      L2 page tables for newly allocated L2 page
4332                          *      tables page.
4333                          */
4334                         KASSERT(!pte1_is_section(pte1),
4335                             ("%s: pte1 %#x is section", __func__, pte1));
4336                         if (!pte1_is_link(pte1)) {
4337                                 pt2_pa = page_pt2pa(VM_PAGE_TO_PHYS(mpt2pg),
4338                                     pte1_idx);
4339                                 pte1_store(pte1p, PTE1_LINK(pt2_pa));
4340                         }
4341                         pt2_wirecount_inc(mpt2pg, pte1_idx);
4342                 } else {
4343                         /*
4344                          * If the L2 page table page is mapped, we just
4345                          * increment the hold count, and activate it.
4346                          */
4347                         if (pte1_is_section(pte1)) {
4348                                 return (NULL);
4349                         } else if (pte1_is_link(pte1)) {
4350                                 mpt2pg = PHYS_TO_VM_PAGE(pte1_link_pa(pte1));
4351                                 pt2_wirecount_inc(mpt2pg, pte1_idx);
4352                         } else {
4353                                 mpt2pg = _pmap_allocpte2(pmap, va,
4354                                     PMAP_ENTER_NOSLEEP);
4355                                 if (mpt2pg == NULL)
4356                                         return (NULL);
4357                         }
4358                 }
4359         } else {
4360                 mpt2pg = NULL;
4361         }
4362
4363         /*
4364          * This call to pt2map_entry() makes the assumption that we are
4365          * entering the page into the current pmap.  In order to support
4366          * quick entry into any pmap, one would likely use pmap_pte2_quick().
4367          * But that isn't as quick as pt2map_entry().
4368          */
4369         pte2p = pt2map_entry(va);
4370         pte2 = pte2_load(pte2p);
4371         if (pte2_is_valid(pte2)) {
4372                 if (mpt2pg != NULL) {
4373                         /*
4374                          * Remove extra pte2 reference
4375                          */
4376                         pt2_wirecount_dec(mpt2pg, pte1_index(va));
4377                         mpt2pg = NULL;
4378                 }
4379                 return (NULL);
4380         }
4381
4382         /*
4383          * Enter on the PV list if part of our managed memory.
4384          */
4385         if ((m->oflags & VPO_UNMANAGED) == 0 &&
4386             !pmap_try_insert_pv_entry(pmap, va, m)) {
4387                 if (mpt2pg != NULL) {
4388                         SLIST_INIT(&free);
4389                         if (pmap_unwire_pt2(pmap, va, mpt2pg, &free)) {
4390                                 pmap_tlb_flush(pmap, va);
4391                                 pmap_free_zero_pages(&free);
4392                         }
4393
4394                         mpt2pg = NULL;
4395                 }
4396                 return (NULL);
4397         }
4398
4399         /*
4400          * Increment counters
4401          */
4402         pmap->pm_stats.resident_count++;
4403
4404         /*
4405          * Now validate mapping with RO protection
4406          */
4407         pa = VM_PAGE_TO_PHYS(m);
4408         l2prot = PTE2_RO | PTE2_NM;
4409         if (va < VM_MAXUSER_ADDRESS)
4410                 l2prot |= PTE2_U | PTE2_NG;
4411         if ((prot & VM_PROT_EXECUTE) == 0)
4412                 l2prot |= PTE2_NX;
4413         else if (m->md.pat_mode == PTE2_ATTR_WB_WA && pmap != kernel_pmap) {
4414                 /*
4415                  * Sync icache if exec permission and attribute PTE2_ATTR_WB_WA
4416                  * is set. QQQ: For more info, see comments in pmap_enter().
4417                  */
4418                 cache_icache_sync_fresh(va, pa, PAGE_SIZE);
4419         }
4420         pte2_store(pte2p, PTE2(pa, l2prot, m->md.pat_mode));
4421
4422         return (mpt2pg);
4423 }
4424
4425 void
4426 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
4427 {
4428
4429         rw_wlock(&pvh_global_lock);
4430         PMAP_LOCK(pmap);
4431         (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL);
4432         rw_wunlock(&pvh_global_lock);
4433         PMAP_UNLOCK(pmap);
4434 }
4435
4436 /*
4437  *  Tries to create 1MB page mapping.  Returns TRUE if successful and
4438  *  FALSE otherwise.  Fails if (1) a page table page cannot be allocated without
4439  *  blocking, (2) a mapping already exists at the specified virtual address, or
4440  *  (3) a pv entry cannot be allocated without reclaiming another pv entry.
4441  */
4442 static boolean_t
4443 pmap_enter_pte1(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
4444 {
4445         pt1_entry_t *pte1p;
4446         vm_paddr_t pa;
4447         uint32_t l1prot;
4448
4449         rw_assert(&pvh_global_lock, RA_WLOCKED);
4450         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4451         pte1p = pmap_pte1(pmap, va);
4452         if (pte1_is_valid(pte1_load(pte1p))) {
4453                 CTR3(KTR_PMAP, "%s: failure for va %#lx in pmap %p", __func__,
4454                     va, pmap);
4455                 return (FALSE);
4456         }
4457         if ((m->oflags & VPO_UNMANAGED) == 0) {
4458                 /*
4459                  * Abort this mapping if its PV entry could not be created.
4460                  */
4461                 if (!pmap_pv_insert_pte1(pmap, va, VM_PAGE_TO_PHYS(m))) {
4462                         CTR3(KTR_PMAP, "%s: failure for va %#lx in pmap %p",
4463                             __func__, va, pmap);
4464                         return (FALSE);
4465                 }
4466         }
4467         /*
4468          * Increment counters.
4469          */
4470         pmap->pm_stats.resident_count += PTE1_SIZE / PAGE_SIZE;
4471
4472         /*
4473          * Map the section.
4474          *
4475          * QQQ: Why VM_PROT_WRITE is not evaluated and the mapping is
4476          *      made readonly?
4477          */
4478         pa = VM_PAGE_TO_PHYS(m);
4479         l1prot = PTE1_RO | PTE1_NM;
4480         if (va < VM_MAXUSER_ADDRESS)
4481                 l1prot |= PTE1_U | PTE1_NG;
4482         if ((prot & VM_PROT_EXECUTE) == 0)
4483                 l1prot |= PTE1_NX;
4484         else if (m->md.pat_mode == PTE2_ATTR_WB_WA && pmap != kernel_pmap) {
4485                 /*
4486                  * Sync icache if exec permission and attribute PTE2_ATTR_WB_WA
4487                  * is set. QQQ: For more info, see comments in pmap_enter().
4488                  */
4489                 cache_icache_sync_fresh(va, pa, PTE1_SIZE);
4490         }
4491         pte1_store(pte1p, PTE1(pa, l1prot, ATTR_TO_L1(m->md.pat_mode)));
4492
4493         pmap_pte1_mappings++;
4494         CTR3(KTR_PMAP, "%s: success for va %#lx in pmap %p", __func__, va,
4495             pmap);
4496         return (TRUE);
4497 }
4498
4499 /*
4500  *  Maps a sequence of resident pages belonging to the same object.
4501  *  The sequence begins with the given page m_start.  This page is
4502  *  mapped at the given virtual address start.  Each subsequent page is
4503  *  mapped at a virtual address that is offset from start by the same
4504  *  amount as the page is offset from m_start within the object.  The
4505  *  last page in the sequence is the page with the largest offset from
4506  *  m_start that can be mapped at a virtual address less than the given
4507  *  virtual address end.  Not every virtual page between start and end
4508  *  is mapped; only those for which a resident page exists with the
4509  *  corresponding offset from m_start are mapped.
4510  */
4511 void
4512 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
4513     vm_page_t m_start, vm_prot_t prot)
4514 {
4515         vm_offset_t va;
4516         vm_page_t m, mpt2pg;
4517         vm_pindex_t diff, psize;
4518
4519         PDEBUG(6, printf("%s: pmap %p start %#x end  %#x m %p prot %#x\n",
4520             __func__, pmap, start, end, m_start, prot));
4521
4522         VM_OBJECT_ASSERT_LOCKED(m_start->object);
4523         psize = atop(end - start);
4524         mpt2pg = NULL;
4525         m = m_start;
4526         rw_wlock(&pvh_global_lock);
4527         PMAP_LOCK(pmap);
4528         while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
4529                 va = start + ptoa(diff);
4530                 if ((va & PTE1_OFFSET) == 0 && va + PTE1_SIZE <= end &&
4531                     m->psind == 1 && sp_enabled &&
4532                     pmap_enter_pte1(pmap, va, m, prot))
4533                         m = &m[PTE1_SIZE / PAGE_SIZE - 1];
4534                 else
4535                         mpt2pg = pmap_enter_quick_locked(pmap, va, m, prot,
4536                             mpt2pg);
4537                 m = TAILQ_NEXT(m, listq);
4538         }
4539         rw_wunlock(&pvh_global_lock);
4540         PMAP_UNLOCK(pmap);
4541 }
4542
4543 /*
4544  *  This code maps large physical mmap regions into the
4545  *  processor address space.  Note that some shortcuts
4546  *  are taken, but the code works.
4547  */
4548 void
4549 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
4550     vm_pindex_t pindex, vm_size_t size)
4551 {
4552         pt1_entry_t *pte1p;
4553         vm_paddr_t pa, pte2_pa;
4554         vm_page_t p;
4555         int pat_mode;
4556         u_int l1attr, l1prot;
4557
4558         VM_OBJECT_ASSERT_WLOCKED(object);
4559         KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
4560             ("%s: non-device object", __func__));
4561         if ((addr & PTE1_OFFSET) == 0 && (size & PTE1_OFFSET) == 0) {
4562                 if (!vm_object_populate(object, pindex, pindex + atop(size)))
4563                         return;
4564                 p = vm_page_lookup(object, pindex);
4565                 KASSERT(p->valid == VM_PAGE_BITS_ALL,
4566                     ("%s: invalid page %p", __func__, p));
4567                 pat_mode = p->md.pat_mode;
4568
4569                 /*
4570                  * Abort the mapping if the first page is not physically
4571                  * aligned to a 1MB page boundary.
4572                  */
4573                 pte2_pa = VM_PAGE_TO_PHYS(p);
4574                 if (pte2_pa & PTE1_OFFSET)
4575                         return;
4576
4577                 /*
4578                  * Skip the first page. Abort the mapping if the rest of
4579                  * the pages are not physically contiguous or have differing
4580                  * memory attributes.
4581                  */
4582                 p = TAILQ_NEXT(p, listq);
4583                 for (pa = pte2_pa + PAGE_SIZE; pa < pte2_pa + size;
4584                     pa += PAGE_SIZE) {
4585                         KASSERT(p->valid == VM_PAGE_BITS_ALL,
4586                             ("%s: invalid page %p", __func__, p));
4587                         if (pa != VM_PAGE_TO_PHYS(p) ||
4588                             pat_mode != p->md.pat_mode)
4589                                 return;
4590                         p = TAILQ_NEXT(p, listq);
4591                 }
4592
4593                 /*
4594                  * Map using 1MB pages.
4595                  *
4596                  * QQQ: Well, we are mapping a section, so same condition must
4597                  * be hold like during promotion. It looks that only RW mapping
4598                  * is done here, so readonly mapping must be done elsewhere.
4599                  */
4600                 l1prot = PTE1_U | PTE1_NG | PTE1_RW | PTE1_M | PTE1_A;
4601                 l1attr = ATTR_TO_L1(pat_mode);
4602                 PMAP_LOCK(pmap);
4603                 for (pa = pte2_pa; pa < pte2_pa + size; pa += PTE1_SIZE) {
4604                         pte1p = pmap_pte1(pmap, addr);
4605                         if (!pte1_is_valid(pte1_load(pte1p))) {
4606                                 pte1_store(pte1p, PTE1(pa, l1prot, l1attr));
4607                                 pmap->pm_stats.resident_count += PTE1_SIZE /
4608                                     PAGE_SIZE;
4609                                 pmap_pte1_mappings++;
4610                         }
4611                         /* Else continue on if the PTE1 is already valid. */
4612                         addr += PTE1_SIZE;
4613                 }
4614                 PMAP_UNLOCK(pmap);
4615         }
4616 }
4617
4618 /*
4619  *  Do the things to protect a 1mpage in a process.
4620  */
4621 static void
4622 pmap_protect_pte1(pmap_t pmap, pt1_entry_t *pte1p, vm_offset_t sva,
4623     vm_prot_t prot)
4624 {
4625         pt1_entry_t npte1, opte1;
4626         vm_offset_t eva, va;
4627         vm_page_t m;
4628
4629         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4630         KASSERT((sva & PTE1_OFFSET) == 0,
4631             ("%s: sva is not 1mpage aligned", __func__));
4632 retry:
4633         opte1 = npte1 = pte1_load(pte1p);
4634         if (pte1_is_managed(opte1)) {
4635                 eva = sva + PTE1_SIZE;
4636                 for (va = sva, m = PHYS_TO_VM_PAGE(pte1_pa(opte1));
4637                     va < eva; va += PAGE_SIZE, m++)
4638                         if (pte1_is_dirty(opte1))
4639                                 vm_page_dirty(m);
4640         }
4641         if ((prot & VM_PROT_WRITE) == 0)
4642                 npte1 |= PTE1_RO | PTE1_NM;
4643         if ((prot & VM_PROT_EXECUTE) == 0)
4644                 npte1 |= PTE1_NX;
4645
4646         /*
4647          * QQQ: Herein, execute permission is never set.
4648          *      It only can be cleared. So, no icache
4649          *      syncing is needed.
4650          */
4651
4652         if (npte1 != opte1) {
4653                 if (!pte1_cmpset(pte1p, opte1, npte1))
4654                         goto retry;
4655                 pmap_tlb_flush(pmap, sva);
4656         }
4657 }
4658
4659 /*
4660  *      Set the physical protection on the
4661  *      specified range of this map as requested.
4662  */
4663 void
4664 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
4665 {
4666         boolean_t pv_lists_locked;
4667         vm_offset_t nextva;
4668         pt1_entry_t *pte1p, pte1;
4669         pt2_entry_t *pte2p, opte2, npte2;
4670
4671         KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
4672         if (prot == VM_PROT_NONE) {
4673                 pmap_remove(pmap, sva, eva);
4674                 return;
4675         }
4676
4677         if ((prot & (VM_PROT_WRITE | VM_PROT_EXECUTE)) ==
4678             (VM_PROT_WRITE | VM_PROT_EXECUTE))
4679                 return;
4680
4681         if (pmap_is_current(pmap))
4682                 pv_lists_locked = FALSE;
4683         else {
4684                 pv_lists_locked = TRUE;
4685 resume:
4686                 rw_wlock(&pvh_global_lock);
4687                 sched_pin();
4688         }
4689
4690         PMAP_LOCK(pmap);
4691         for (; sva < eva; sva = nextva) {
4692                 /*
4693                  * Calculate address for next L2 page table.
4694                  */
4695                 nextva = pte1_trunc(sva + PTE1_SIZE);
4696                 if (nextva < sva)
4697                         nextva = eva;
4698
4699                 pte1p = pmap_pte1(pmap, sva);
4700                 pte1 = pte1_load(pte1p);
4701
4702                 /*
4703                  * Weed out invalid mappings. Note: we assume that L1 page
4704                  * page table is always allocated, and in kernel virtual.
4705                  */
4706                 if (pte1 == 0)
4707                         continue;
4708
4709                 if (pte1_is_section(pte1)) {
4710                         /*
4711                          * Are we protecting the entire large page?  If not,
4712                          * demote the mapping and fall through.
4713                          */
4714                         if (sva + PTE1_SIZE == nextva && eva >= nextva) {
4715                                 pmap_protect_pte1(pmap, pte1p, sva, prot);
4716                                 continue;
4717                         } else {
4718                                 if (!pv_lists_locked) {
4719                                         pv_lists_locked = TRUE;
4720                                         if (!rw_try_wlock(&pvh_global_lock)) {
4721                                                 PMAP_UNLOCK(pmap);
4722                                                 goto resume;
4723                                         }
4724                                         sched_pin();
4725                                 }
4726                                 if (!pmap_demote_pte1(pmap, pte1p, sva)) {
4727                                         /*
4728                                          * The large page mapping
4729                                          * was destroyed.
4730                                          */
4731                                         continue;
4732                                 }
4733 #ifdef INVARIANTS
4734                                 else {
4735                                         /* Update pte1 after demotion */
4736                                         pte1 = pte1_load(pte1p);
4737                                 }
4738 #endif
4739                         }
4740                 }
4741
4742                 KASSERT(pte1_is_link(pte1), ("%s: pmap %p va %#x pte1 %#x at %p"
4743                     " is not link", __func__, pmap, sva, pte1, pte1p));
4744
4745                 /*
4746                  * Limit our scan to either the end of the va represented
4747                  * by the current L2 page table page, or to the end of the
4748                  * range being protected.
4749                  */
4750                 if (nextva > eva)
4751                         nextva = eva;
4752
4753                 for (pte2p = pmap_pte2_quick(pmap, sva); sva != nextva; pte2p++,
4754                     sva += PAGE_SIZE) {
4755                         vm_page_t m;
4756 retry:
4757                         opte2 = npte2 = pte2_load(pte2p);
4758                         if (!pte2_is_valid(opte2))
4759                                 continue;
4760
4761                         if ((prot & VM_PROT_WRITE) == 0) {
4762                                 if (pte2_is_managed(opte2) &&
4763                                     pte2_is_dirty(opte2)) {
4764                                         m = PHYS_TO_VM_PAGE(pte2_pa(opte2));
4765                                         vm_page_dirty(m);
4766                                 }
4767                                 npte2 |= PTE2_RO | PTE2_NM;
4768                         }
4769
4770                         if ((prot & VM_PROT_EXECUTE) == 0)
4771                                 npte2 |= PTE2_NX;
4772
4773                         /*
4774                          * QQQ: Herein, execute permission is never set.
4775                          *      It only can be cleared. So, no icache
4776                          *      syncing is needed.
4777                          */
4778
4779                         if (npte2 != opte2) {
4780
4781                                 if (!pte2_cmpset(pte2p, opte2, npte2))
4782                                         goto retry;
4783                                 pmap_tlb_flush(pmap, sva);
4784                         }
4785                 }
4786         }
4787         if (pv_lists_locked) {
4788                 sched_unpin();
4789                 rw_wunlock(&pvh_global_lock);
4790         }
4791         PMAP_UNLOCK(pmap);
4792 }
4793
4794 /*
4795  *      pmap_pvh_wired_mappings:
4796  *
4797  *      Return the updated number "count" of managed mappings that are wired.
4798  */
4799 static int
4800 pmap_pvh_wired_mappings(struct md_page *pvh, int count)
4801 {
4802         pmap_t pmap;
4803         pt1_entry_t pte1;
4804         pt2_entry_t pte2;
4805         pv_entry_t pv;
4806
4807         rw_assert(&pvh_global_lock, RA_WLOCKED);
4808         sched_pin();
4809         TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
4810                 pmap = PV_PMAP(pv);
4811                 PMAP_LOCK(pmap);
4812                 pte1 = pte1_load(pmap_pte1(pmap, pv->pv_va));
4813                 if (pte1_is_section(pte1)) {
4814                         if (pte1_is_wired(pte1))
4815                                 count++;
4816                 } else {
4817                         KASSERT(pte1_is_link(pte1),
4818                             ("%s: pte1 %#x is not link", __func__, pte1));
4819                         pte2 = pte2_load(pmap_pte2_quick(pmap, pv->pv_va));
4820                         if (pte2_is_wired(pte2))
4821                                 count++;
4822                 }
4823                 PMAP_UNLOCK(pmap);
4824         }
4825         sched_unpin();
4826         return (count);
4827 }
4828
4829 /*
4830  *      pmap_page_wired_mappings:
4831  *
4832  *      Return the number of managed mappings to the given physical page
4833  *      that are wired.
4834  */
4835 int
4836 pmap_page_wired_mappings(vm_page_t m)
4837 {
4838         int count;
4839
4840         count = 0;
4841         if ((m->oflags & VPO_UNMANAGED) != 0)
4842                 return (count);
4843         rw_wlock(&pvh_global_lock);
4844         count = pmap_pvh_wired_mappings(&m->md, count);
4845         if ((m->flags & PG_FICTITIOUS) == 0) {
4846                 count = pmap_pvh_wired_mappings(pa_to_pvh(VM_PAGE_TO_PHYS(m)),
4847                     count);
4848         }
4849         rw_wunlock(&pvh_global_lock);
4850         return (count);
4851 }
4852
4853 /*
4854  *  Returns TRUE if any of the given mappings were used to modify
4855  *  physical memory.  Otherwise, returns FALSE.  Both page and 1mpage
4856  *  mappings are supported.
4857  */
4858 static boolean_t
4859 pmap_is_modified_pvh(struct md_page *pvh)
4860 {
4861         pv_entry_t pv;
4862         pt1_entry_t pte1;
4863         pt2_entry_t pte2;
4864         pmap_t pmap;
4865         boolean_t rv;
4866
4867         rw_assert(&pvh_global_lock, RA_WLOCKED);
4868         rv = FALSE;
4869         sched_pin();
4870         TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
4871                 pmap = PV_PMAP(pv);
4872                 PMAP_LOCK(pmap);
4873                 pte1 = pte1_load(pmap_pte1(pmap, pv->pv_va));
4874                 if (pte1_is_section(pte1)) {
4875                         rv = pte1_is_dirty(pte1);
4876                 } else {
4877                         KASSERT(pte1_is_link(pte1),
4878                             ("%s: pte1 %#x is not link", __func__, pte1));
4879                         pte2 = pte2_load(pmap_pte2_quick(pmap, pv->pv_va));
4880                         rv = pte2_is_dirty(pte2);
4881                 }
4882                 PMAP_UNLOCK(pmap);
4883                 if (rv)
4884                         break;
4885         }
4886         sched_unpin();
4887         return (rv);
4888 }
4889
4890 /*
4891  *      pmap_is_modified:
4892  *
4893  *      Return whether or not the specified physical page was modified
4894  *      in any physical maps.
4895  */
4896 boolean_t
4897 pmap_is_modified(vm_page_t m)
4898 {
4899         boolean_t rv;
4900
4901         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4902             ("%s: page %p is not managed", __func__, m));
4903
4904         /*
4905          * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
4906          * concurrently set while the object is locked.  Thus, if PGA_WRITEABLE
4907          * is clear, no PTE2s can have PG_M set.
4908          */
4909         VM_OBJECT_ASSERT_WLOCKED(m->object);
4910         if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
4911                 return (FALSE);
4912         rw_wlock(&pvh_global_lock);
4913         rv = pmap_is_modified_pvh(&m->md) ||
4914             ((m->flags & PG_FICTITIOUS) == 0 &&
4915             pmap_is_modified_pvh(pa_to_pvh(VM_PAGE_TO_PHYS(m))));
4916         rw_wunlock(&pvh_global_lock);
4917         return (rv);
4918 }
4919
4920 /*
4921  *      pmap_is_prefaultable:
4922  *
4923  *      Return whether or not the specified virtual address is eligible
4924  *      for prefault.
4925  */
4926 boolean_t
4927 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
4928 {
4929         pt1_entry_t pte1;
4930         pt2_entry_t pte2;
4931         boolean_t rv;
4932
4933         rv = FALSE;
4934         PMAP_LOCK(pmap);
4935         pte1 = pte1_load(pmap_pte1(pmap, addr));
4936         if (pte1_is_link(pte1)) {
4937                 pte2 = pte2_load(pt2map_entry(addr));
4938                 rv = !pte2_is_valid(pte2) ;
4939         }
4940         PMAP_UNLOCK(pmap);
4941         return (rv);
4942 }
4943
4944 /*
4945  *  Returns TRUE if any of the given mappings were referenced and FALSE
4946  *  otherwise. Both page and 1mpage mappings are supported.
4947  */
4948 static boolean_t
4949 pmap_is_referenced_pvh(struct md_page *pvh)
4950 {
4951
4952         pv_entry_t pv;
4953         pt1_entry_t pte1;
4954         pt2_entry_t pte2;
4955         pmap_t pmap;
4956         boolean_t rv;
4957
4958         rw_assert(&pvh_global_lock, RA_WLOCKED);
4959         rv = FALSE;
4960         sched_pin();
4961         TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
4962                 pmap = PV_PMAP(pv);
4963                 PMAP_LOCK(pmap);
4964                 pte1 = pte1_load(pmap_pte1(pmap, pv->pv_va));
4965                 if (pte1_is_section(pte1)) {
4966                         rv = (pte1 & (PTE1_A | PTE1_V)) == (PTE1_A | PTE1_V);
4967                 } else {
4968                         pte2 = pte2_load(pmap_pte2_quick(pmap, pv->pv_va));
4969                         rv = (pte2 & (PTE2_A | PTE2_V)) == (PTE2_A | PTE2_V);
4970                 }
4971                 PMAP_UNLOCK(pmap);
4972                 if (rv)
4973                         break;
4974         }
4975         sched_unpin();
4976         return (rv);
4977 }
4978
4979 /*
4980  *      pmap_is_referenced:
4981  *
4982  *      Return whether or not the specified physical page was referenced
4983  *      in any physical maps.
4984  */
4985 boolean_t
4986 pmap_is_referenced(vm_page_t m)
4987 {
4988         boolean_t rv;
4989
4990         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4991             ("%s: page %p is not managed", __func__, m));
4992         rw_wlock(&pvh_global_lock);
4993         rv = pmap_is_referenced_pvh(&m->md) ||
4994             ((m->flags & PG_FICTITIOUS) == 0 &&
4995             pmap_is_referenced_pvh(pa_to_pvh(VM_PAGE_TO_PHYS(m))));
4996         rw_wunlock(&pvh_global_lock);
4997         return (rv);
4998 }
4999
5000 #define PMAP_TS_REFERENCED_MAX  5
5001
5002 /*
5003  *      pmap_ts_referenced:
5004  *
5005  *      Return a count of reference bits for a page, clearing those bits.
5006  *      It is not necessary for every reference bit to be cleared, but it
5007  *      is necessary that 0 only be returned when there are truly no
5008  *      reference bits set.
5009  *
5010  *      XXX: The exact number of bits to check and clear is a matter that
5011  *      should be tested and standardized at some point in the future for
5012  *      optimal aging of shared pages.
5013  */
5014 int
5015 pmap_ts_referenced(vm_page_t m)
5016 {
5017         struct md_page *pvh;
5018         pv_entry_t pv, pvf;
5019         pmap_t pmap;
5020         pt1_entry_t  *pte1p, opte1;
5021         pt2_entry_t *pte2p;
5022         vm_paddr_t pa;
5023         int rtval = 0;
5024
5025         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5026             ("%s: page %p is not managed", __func__, m));
5027         pa = VM_PAGE_TO_PHYS(m);
5028         pvh = pa_to_pvh(pa);
5029         rw_wlock(&pvh_global_lock);
5030         sched_pin();
5031         if ((m->flags & PG_FICTITIOUS) != 0 ||
5032             (pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
5033                 goto small_mappings;
5034         pv = pvf;
5035         do {
5036                 pmap = PV_PMAP(pv);
5037                 PMAP_LOCK(pmap);
5038                 pte1p = pmap_pte1(pmap, pv->pv_va);
5039                 opte1 = pte1_load(pte1p);
5040                 if ((opte1 & PTE1_A) != 0) {
5041                         /*
5042                          * Since this reference bit is shared by 256 4KB pages,
5043                          * it should not be cleared every time it is tested.
5044                          * Apply a simple "hash" function on the physical page
5045                          * number, the virtual section number, and the pmap
5046                          * address to select one 4KB page out of the 256
5047                          * on which testing the reference bit will result
5048                          * in clearing that bit. This function is designed
5049                          * to avoid the selection of the same 4KB page
5050                          * for every 1MB page mapping.
5051                          *
5052                          * On demotion, a mapping that hasn't been referenced
5053                          * is simply destroyed.  To avoid the possibility of a
5054                          * subsequent page fault on a demoted wired mapping,
5055                          * always leave its reference bit set.  Moreover,
5056                          * since the section is wired, the current state of
5057                          * its reference bit won't affect page replacement.
5058                          */
5059                          if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PTE1_SHIFT) ^
5060                             (uintptr_t)pmap) & (NPTE2_IN_PG - 1)) == 0 &&
5061                             !pte1_is_wired(opte1)) {
5062                                 pte1_clear_bit(pte1p, PTE1_A);
5063                                 pmap_tlb_flush(pmap, pv->pv_va);
5064                         }
5065                         rtval++;
5066                 }
5067                 PMAP_UNLOCK(pmap);
5068                 /* Rotate the PV list if it has more than one entry. */
5069                 if (TAILQ_NEXT(pv, pv_next) != NULL) {
5070                         TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
5071                         TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
5072                 }
5073                 if (rtval >= PMAP_TS_REFERENCED_MAX)
5074                         goto out;
5075         } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
5076 small_mappings:
5077         if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
5078                 goto out;
5079         pv = pvf;
5080         do {
5081                 pmap = PV_PMAP(pv);
5082                 PMAP_LOCK(pmap);
5083                 pte1p = pmap_pte1(pmap, pv->pv_va);
5084                 KASSERT(pte1_is_link(pte1_load(pte1p)),
5085                     ("%s: not found a link in page %p's pv list", __func__, m));
5086
5087                 pte2p = pmap_pte2_quick(pmap, pv->pv_va);
5088                 if ((pte2_load(pte2p) & PTE2_A) != 0) {
5089                         pte2_clear_bit(pte2p, PTE2_A);
5090                         pmap_tlb_flush(pmap, pv->pv_va);
5091                         rtval++;
5092                 }
5093                 PMAP_UNLOCK(pmap);
5094                 /* Rotate the PV list if it has more than one entry. */
5095                 if (TAILQ_NEXT(pv, pv_next) != NULL) {
5096                         TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
5097                         TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
5098                 }
5099         } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && rtval <
5100             PMAP_TS_REFERENCED_MAX);
5101 out:
5102         sched_unpin();
5103         rw_wunlock(&pvh_global_lock);
5104         return (rtval);
5105 }
5106
5107 /*
5108  *      Clear the wired attribute from the mappings for the specified range of
5109  *      addresses in the given pmap.  Every valid mapping within that range
5110  *      must have the wired attribute set.  In contrast, invalid mappings
5111  *      cannot have the wired attribute set, so they are ignored.
5112  *
5113  *      The wired attribute of the page table entry is not a hardware feature,
5114  *      so there is no need to invalidate any TLB entries.
5115  */
5116 void
5117 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5118 {
5119         vm_offset_t nextva;
5120         pt1_entry_t *pte1p, pte1;
5121         pt2_entry_t *pte2p, pte2;
5122         boolean_t pv_lists_locked;
5123
5124         if (pmap_is_current(pmap))
5125                 pv_lists_locked = FALSE;
5126         else {
5127                 pv_lists_locked = TRUE;
5128 resume:
5129                 rw_wlock(&pvh_global_lock);
5130                 sched_pin();
5131         }
5132         PMAP_LOCK(pmap);
5133         for (; sva < eva; sva = nextva) {
5134                 nextva = pte1_trunc(sva + PTE1_SIZE);
5135                 if (nextva < sva)
5136                         nextva = eva;
5137
5138                 pte1p = pmap_pte1(pmap, sva);
5139                 pte1 = pte1_load(pte1p);
5140
5141                 /*
5142                  * Weed out invalid mappings. Note: we assume that L1 page
5143                  * page table is always allocated, and in kernel virtual.
5144                  */
5145                 if (pte1 == 0)
5146                         continue;
5147
5148                 if (pte1_is_section(pte1)) {
5149                         if (!pte1_is_wired(pte1))
5150                                 panic("%s: pte1 %#x not wired", __func__, pte1);
5151
5152                         /*
5153                          * Are we unwiring the entire large page?  If not,
5154                          * demote the mapping and fall through.
5155                          */
5156                         if (sva + PTE1_SIZE == nextva && eva >= nextva) {
5157                                 pte1_clear_bit(pte1p, PTE1_W);
5158                                 pmap->pm_stats.wired_count -= PTE1_SIZE /
5159                                     PAGE_SIZE;
5160                                 continue;
5161                         } else {
5162                                 if (!pv_lists_locked) {
5163                                         pv_lists_locked = TRUE;
5164                                         if (!rw_try_wlock(&pvh_global_lock)) {
5165                                                 PMAP_UNLOCK(pmap);
5166                                                 /* Repeat sva. */
5167                                                 goto resume;
5168                                         }
5169                                         sched_pin();
5170                                 }
5171                                 if (!pmap_demote_pte1(pmap, pte1p, sva))
5172                                         panic("%s: demotion failed", __func__);
5173 #ifdef INVARIANTS
5174                                 else {
5175                                         /* Update pte1 after demotion */
5176                                         pte1 = pte1_load(pte1p);
5177                                 }
5178 #endif
5179                         }
5180                 }
5181
5182                 KASSERT(pte1_is_link(pte1), ("%s: pmap %p va %#x pte1 %#x at %p"
5183                     " is not link", __func__, pmap, sva, pte1, pte1p));
5184
5185                 /*
5186                  * Limit our scan to either the end of the va represented
5187                  * by the current L2 page table page, or to the end of the
5188                  * range being protected.
5189                  */
5190                 if (nextva > eva)
5191                         nextva = eva;
5192
5193                 for (pte2p = pmap_pte2_quick(pmap, sva); sva != nextva; pte2p++,
5194                     sva += PAGE_SIZE) {
5195                         pte2 = pte2_load(pte2p);
5196                         if (!pte2_is_valid(pte2))
5197                                 continue;
5198                         if (!pte2_is_wired(pte2))
5199                                 panic("%s: pte2 %#x is missing PTE2_W",
5200                                     __func__, pte2);
5201
5202                         /*
5203                          * PTE2_W must be cleared atomically. Although the pmap
5204                          * lock synchronizes access to PTE2_W, another processor
5205                          * could be changing PTE2_NM and/or PTE2_A concurrently.
5206                          */
5207                         pte2_clear_bit(pte2p, PTE2_W);
5208                         pmap->pm_stats.wired_count--;
5209                 }
5210         }
5211         if (pv_lists_locked) {
5212                 sched_unpin();
5213                 rw_wunlock(&pvh_global_lock);
5214         }
5215         PMAP_UNLOCK(pmap);
5216 }
5217
5218 /*
5219  *  Clear the write and modified bits in each of the given page's mappings.
5220  */
5221 void
5222 pmap_remove_write(vm_page_t m)
5223 {
5224         struct md_page *pvh;
5225         pv_entry_t next_pv, pv;
5226         pmap_t pmap;
5227         pt1_entry_t *pte1p;
5228         pt2_entry_t *pte2p, opte2;
5229         vm_offset_t va;
5230
5231         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5232             ("%s: page %p is not managed", __func__, m));
5233
5234         /*
5235          * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
5236          * set by another thread while the object is locked.  Thus,
5237          * if PGA_WRITEABLE is clear, no page table entries need updating.
5238          */
5239         VM_OBJECT_ASSERT_WLOCKED(m->object);
5240         if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
5241                 return;
5242         rw_wlock(&pvh_global_lock);
5243         sched_pin();
5244         if ((m->flags & PG_FICTITIOUS) != 0)
5245                 goto small_mappings;
5246         pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5247         TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
5248                 va = pv->pv_va;
5249                 pmap = PV_PMAP(pv);
5250                 PMAP_LOCK(pmap);
5251                 pte1p = pmap_pte1(pmap, va);
5252                 if (!(pte1_load(pte1p) & PTE1_RO))
5253                         (void)pmap_demote_pte1(pmap, pte1p, va);
5254                 PMAP_UNLOCK(pmap);
5255         }
5256 small_mappings:
5257         TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5258                 pmap = PV_PMAP(pv);
5259                 PMAP_LOCK(pmap);
5260                 pte1p = pmap_pte1(pmap, pv->pv_va);
5261                 KASSERT(!pte1_is_section(pte1_load(pte1p)), ("%s: found"
5262                     " a section in page %p's pv list", __func__, m));
5263                 pte2p = pmap_pte2_quick(pmap, pv->pv_va);
5264 retry:
5265                 opte2 = pte2_load(pte2p);
5266                 if (!(opte2 & PTE2_RO)) {
5267                         if (!pte2_cmpset(pte2p, opte2,
5268                             opte2 | (PTE2_RO | PTE2_NM)))
5269                                 goto retry;
5270                         if (pte2_is_dirty(opte2))
5271                                 vm_page_dirty(m);
5272                         pmap_tlb_flush(pmap, pv->pv_va);
5273                 }
5274                 PMAP_UNLOCK(pmap);
5275         }
5276         vm_page_aflag_clear(m, PGA_WRITEABLE);
5277         sched_unpin();
5278         rw_wunlock(&pvh_global_lock);
5279 }
5280
5281 /*
5282  *      Apply the given advice to the specified range of addresses within the
5283  *      given pmap.  Depending on the advice, clear the referenced and/or
5284  *      modified flags in each mapping and set the mapped page's dirty field.
5285  */
5286 void
5287 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
5288 {
5289         pt1_entry_t *pte1p, opte1;
5290         pt2_entry_t *pte2p, pte2;
5291         vm_offset_t pdnxt;
5292         vm_page_t m;
5293         boolean_t pv_lists_locked;
5294
5295         if (advice != MADV_DONTNEED && advice != MADV_FREE)
5296                 return;
5297         if (pmap_is_current(pmap))
5298                 pv_lists_locked = FALSE;
5299         else {
5300                 pv_lists_locked = TRUE;
5301 resume:
5302                 rw_wlock(&pvh_global_lock);
5303                 sched_pin();
5304         }
5305         PMAP_LOCK(pmap);
5306         for (; sva < eva; sva = pdnxt) {
5307                 pdnxt = pte1_trunc(sva + PTE1_SIZE);
5308                 if (pdnxt < sva)
5309                         pdnxt = eva;
5310                 pte1p = pmap_pte1(pmap, sva);
5311                 opte1 = pte1_load(pte1p);
5312                 if (!pte1_is_valid(opte1)) /* XXX */
5313                         continue;
5314                 else if (pte1_is_section(opte1)) {
5315                         if (!pte1_is_managed(opte1))
5316                                 continue;
5317                         if (!pv_lists_locked) {
5318                                 pv_lists_locked = TRUE;
5319                                 if (!rw_try_wlock(&pvh_global_lock)) {
5320                                         PMAP_UNLOCK(pmap);
5321                                         goto resume;
5322                                 }
5323                                 sched_pin();
5324                         }
5325                         if (!pmap_demote_pte1(pmap, pte1p, sva)) {
5326                                 /*
5327                                  * The large page mapping was destroyed.
5328                                  */
5329                                 continue;
5330                         }
5331
5332                         /*
5333                          * Unless the page mappings are wired, remove the
5334                          * mapping to a single page so that a subsequent
5335                          * access may repromote.  Since the underlying L2 page
5336                          * table is fully populated, this removal never
5337                          * frees a L2 page table page.
5338                          */
5339                         if (!pte1_is_wired(opte1)) {
5340                                 pte2p = pmap_pte2_quick(pmap, sva);
5341                                 KASSERT(pte2_is_valid(pte2_load(pte2p)),
5342                                     ("%s: invalid PTE2", __func__));
5343                                 pmap_remove_pte2(pmap, pte2p, sva, NULL);
5344                         }
5345                 }
5346                 if (pdnxt > eva)
5347                         pdnxt = eva;
5348                 for (pte2p = pmap_pte2_quick(pmap, sva); sva != pdnxt; pte2p++,
5349                     sva += PAGE_SIZE) {
5350                         pte2 = pte2_load(pte2p);
5351                         if (!pte2_is_valid(pte2) || !pte2_is_managed(pte2))
5352                                 continue;
5353                         else if (pte2_is_dirty(pte2)) {
5354                                 if (advice == MADV_DONTNEED) {
5355                                         /*
5356                                          * Future calls to pmap_is_modified()
5357                                          * can be avoided by making the page
5358                                          * dirty now.
5359                                          */
5360                                         m = PHYS_TO_VM_PAGE(pte2_pa(pte2));
5361                                         vm_page_dirty(m);
5362                                 }
5363                                 pte2_set_bit(pte2p, PTE2_NM);
5364                                 pte2_clear_bit(pte2p, PTE2_A);
5365                         } else if ((pte2 & PTE2_A) != 0)
5366                                 pte2_clear_bit(pte2p, PTE2_A);
5367                         else
5368                                 continue;
5369                         pmap_tlb_flush(pmap, sva);
5370                 }
5371         }
5372         if (pv_lists_locked) {
5373                 sched_unpin();
5374                 rw_wunlock(&pvh_global_lock);
5375         }
5376         PMAP_UNLOCK(pmap);
5377 }
5378
5379 /*
5380  *      Clear the modify bits on the specified physical page.
5381  */
5382 void
5383 pmap_clear_modify(vm_page_t m)
5384 {
5385         struct md_page *pvh;
5386         pv_entry_t next_pv, pv;
5387         pmap_t pmap;
5388         pt1_entry_t *pte1p, opte1;
5389         pt2_entry_t *pte2p, opte2;
5390         vm_offset_t va;
5391
5392         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5393             ("%s: page %p is not managed", __func__, m));
5394         VM_OBJECT_ASSERT_WLOCKED(m->object);
5395         KASSERT(!vm_page_xbusied(m),
5396             ("%s: page %p is exclusive busy", __func__, m));
5397
5398         /*
5399          * If the page is not PGA_WRITEABLE, then no PTE2s can have PTE2_NM
5400          * cleared. If the object containing the page is locked and the page
5401          * is not exclusive busied, then PGA_WRITEABLE cannot be concurrently
5402          * set.
5403          */
5404         if ((m->flags & PGA_WRITEABLE) == 0)
5405                 return;
5406         rw_wlock(&pvh_global_lock);
5407         sched_pin();
5408         if ((m->flags & PG_FICTITIOUS) != 0)
5409                 goto small_mappings;
5410         pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5411         TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
5412                 va = pv->pv_va;
5413                 pmap = PV_PMAP(pv);
5414                 PMAP_LOCK(pmap);
5415                 pte1p = pmap_pte1(pmap, va);
5416                 opte1 = pte1_load(pte1p);
5417                 if (!(opte1 & PTE1_RO)) {
5418                         if (pmap_demote_pte1(pmap, pte1p, va) &&
5419                             !pte1_is_wired(opte1)) {
5420                                 /*
5421                                  * Write protect the mapping to a
5422                                  * single page so that a subsequent
5423                                  * write access may repromote.
5424                                  */
5425                                 va += VM_PAGE_TO_PHYS(m) - pte1_pa(opte1);
5426                                 pte2p = pmap_pte2_quick(pmap, va);
5427                                 opte2 = pte2_load(pte2p);
5428                                 if ((opte2 & PTE2_V)) {
5429                                         pte2_set_bit(pte2p, PTE2_NM | PTE2_RO);
5430                                         vm_page_dirty(m);
5431                                         pmap_tlb_flush(pmap, va);
5432                                 }
5433                         }
5434                 }
5435                 PMAP_UNLOCK(pmap);
5436         }
5437 small_mappings:
5438         TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5439                 pmap = PV_PMAP(pv);
5440                 PMAP_LOCK(pmap);
5441                 pte1p = pmap_pte1(pmap, pv->pv_va);
5442                 KASSERT(!pte1_is_section(pte1_load(pte1p)), ("%s: found"
5443                     " a section in page %p's pv list", __func__, m));
5444                 pte2p = pmap_pte2_quick(pmap, pv->pv_va);
5445                 if (pte2_is_dirty(pte2_load(pte2p))) {
5446                         pte2_set_bit(pte2p, PTE2_NM);
5447                         pmap_tlb_flush(pmap, pv->pv_va);
5448                 }
5449                 PMAP_UNLOCK(pmap);
5450         }
5451         sched_unpin();
5452         rw_wunlock(&pvh_global_lock);
5453 }
5454
5455
5456 /*
5457  *  Sets the memory attribute for the specified page.
5458  */
5459 void
5460 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
5461 {
5462         struct sysmaps *sysmaps;
5463         vm_memattr_t oma;
5464         vm_paddr_t pa;
5465
5466         oma = m->md.pat_mode;
5467         m->md.pat_mode = ma;
5468
5469         CTR5(KTR_PMAP, "%s: page %p - 0x%08X oma: %d, ma: %d", __func__, m,
5470             VM_PAGE_TO_PHYS(m), oma, ma);
5471         if ((m->flags & PG_FICTITIOUS) != 0)
5472                 return;
5473 #if 0
5474         /*
5475          * If "m" is a normal page, flush it from the cache.
5476          *
5477          * First, try to find an existing mapping of the page by sf
5478          * buffer. sf_buf_invalidate_cache() modifies mapping and
5479          * flushes the cache.
5480          */
5481         if (sf_buf_invalidate_cache(m, oma))
5482                 return;
5483 #endif
5484         /*
5485          * If page is not mapped by sf buffer, map the page
5486          * transient and do invalidation.
5487          */
5488         if (ma != oma) {
5489                 pa = VM_PAGE_TO_PHYS(m);
5490                 sched_pin();
5491                 sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
5492                 mtx_lock(&sysmaps->lock);
5493                 if (*sysmaps->CMAP2)
5494                         panic("%s: CMAP2 busy", __func__);
5495                 pte2_store(sysmaps->CMAP2, PTE2_KERN_NG(pa, PTE2_AP_KRW, ma));
5496                 dcache_wbinv_poc((vm_offset_t)sysmaps->CADDR2, pa, PAGE_SIZE);
5497                 pte2_clear(sysmaps->CMAP2);
5498                 tlb_flush((vm_offset_t)sysmaps->CADDR2);
5499                 sched_unpin();
5500                 mtx_unlock(&sysmaps->lock);
5501         }
5502 }
5503
5504 /*
5505  *  Miscellaneous support routines follow
5506  */
5507
5508 /*
5509  *  Returns TRUE if the given page is mapped individually or as part of
5510  *  a 1mpage.  Otherwise, returns FALSE.
5511  */
5512 boolean_t
5513 pmap_page_is_mapped(vm_page_t m)
5514 {
5515         boolean_t rv;
5516
5517         if ((m->oflags & VPO_UNMANAGED) != 0)
5518                 return (FALSE);
5519         rw_wlock(&pvh_global_lock);
5520         rv = !TAILQ_EMPTY(&m->md.pv_list) ||
5521             ((m->flags & PG_FICTITIOUS) == 0 &&
5522             !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
5523         rw_wunlock(&pvh_global_lock);
5524         return (rv);
5525 }
5526
5527 /*
5528  *  Returns true if the pmap's pv is one of the first
5529  *  16 pvs linked to from this page.  This count may
5530  *  be changed upwards or downwards in the future; it
5531  *  is only necessary that true be returned for a small
5532  *  subset of pmaps for proper page aging.
5533  */
5534 boolean_t
5535 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5536 {
5537         struct md_page *pvh;
5538         pv_entry_t pv;
5539         int loops = 0;
5540         boolean_t rv;
5541
5542         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5543             ("%s: page %p is not managed", __func__, m));
5544         rv = FALSE;
5545         rw_wlock(&pvh_global_lock);
5546         TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5547                 if (PV_PMAP(pv) == pmap) {
5548                         rv = TRUE;
5549                         break;
5550                 }
5551                 loops++;
5552                 if (loops >= 16)
5553                         break;
5554         }
5555         if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
5556                 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5557                 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5558                         if (PV_PMAP(pv) == pmap) {
5559                                 rv = TRUE;
5560                                 break;
5561                         }
5562                         loops++;
5563                         if (loops >= 16)
5564                                 break;
5565                 }
5566         }
5567         rw_wunlock(&pvh_global_lock);
5568         return (rv);
5569 }
5570
5571 /*
5572  *      pmap_zero_page zeros the specified hardware page by mapping
5573  *      the page into KVM and using bzero to clear its contents.
5574  */
5575 void
5576 pmap_zero_page(vm_page_t m)
5577 {
5578         struct sysmaps *sysmaps;
5579
5580         sched_pin();
5581         sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
5582         mtx_lock(&sysmaps->lock);
5583         if (pte2_load(sysmaps->CMAP2) != 0)
5584                 panic("%s: CMAP2 busy", __func__);
5585         pte2_store(sysmaps->CMAP2, PTE2_KERN_NG(VM_PAGE_TO_PHYS(m), PTE2_AP_KRW,
5586             m->md.pat_mode));
5587         pagezero(sysmaps->CADDR2);
5588         pte2_clear(sysmaps->CMAP2);
5589         tlb_flush((vm_offset_t)sysmaps->CADDR2);
5590         sched_unpin();
5591         mtx_unlock(&sysmaps->lock);
5592 }
5593
5594 /*
5595  *      pmap_zero_page_area zeros the specified hardware page by mapping
5596  *      the page into KVM and using bzero to clear its contents.
5597  *
5598  *      off and size may not cover an area beyond a single hardware page.
5599  */
5600 void
5601 pmap_zero_page_area(vm_page_t m, int off, int size)
5602 {
5603         struct sysmaps *sysmaps;
5604
5605         sched_pin();
5606         sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
5607         mtx_lock(&sysmaps->lock);
5608         if (pte2_load(sysmaps->CMAP2) != 0)
5609                 panic("%s: CMAP2 busy", __func__);
5610         pte2_store(sysmaps->CMAP2, PTE2_KERN_NG(VM_PAGE_TO_PHYS(m), PTE2_AP_KRW,
5611             m->md.pat_mode));
5612         if (off == 0 && size == PAGE_SIZE)
5613                 pagezero(sysmaps->CADDR2);
5614         else
5615                 bzero(sysmaps->CADDR2 + off, size);
5616         pte2_clear(sysmaps->CMAP2);
5617         tlb_flush((vm_offset_t)sysmaps->CADDR2);
5618         sched_unpin();
5619         mtx_unlock(&sysmaps->lock);
5620 }
5621
5622 /*
5623  *      pmap_zero_page_idle zeros the specified hardware page by mapping
5624  *      the page into KVM and using bzero to clear its contents.  This
5625  *      is intended to be called from the vm_pagezero process only and
5626  *      outside of Giant.
5627  */
5628 void
5629 pmap_zero_page_idle(vm_page_t m)
5630 {
5631
5632         if (pte2_load(CMAP3) != 0)
5633                 panic("%s: CMAP3 busy", __func__);
5634         sched_pin();
5635         pte2_store(CMAP3, PTE2_KERN_NG(VM_PAGE_TO_PHYS(m), PTE2_AP_KRW,
5636             m->md.pat_mode));
5637         pagezero(CADDR3);
5638         pte2_clear(CMAP3);
5639         tlb_flush((vm_offset_t)CADDR3);
5640         sched_unpin();
5641 }
5642
5643 /*
5644  *      pmap_copy_page copies the specified (machine independent)
5645  *      page by mapping the page into virtual memory and using
5646  *      bcopy to copy the page, one machine dependent page at a
5647  *      time.
5648  */
5649 void
5650 pmap_copy_page(vm_page_t src, vm_page_t dst)
5651 {
5652         struct sysmaps *sysmaps;
5653
5654         sched_pin();
5655         sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
5656         mtx_lock(&sysmaps->lock);
5657         if (pte2_load(sysmaps->CMAP1) != 0)
5658                 panic("%s: CMAP1 busy", __func__);
5659         if (pte2_load(sysmaps->CMAP2) != 0)
5660                 panic("%s: CMAP2 busy", __func__);
5661         pte2_store(sysmaps->CMAP1, PTE2_KERN_NG(VM_PAGE_TO_PHYS(src),
5662             PTE2_AP_KR | PTE2_NM, src->md.pat_mode));
5663         pte2_store(sysmaps->CMAP2, PTE2_KERN_NG(VM_PAGE_TO_PHYS(dst),
5664             PTE2_AP_KRW, dst->md.pat_mode));
5665         bcopy(sysmaps->CADDR1, sysmaps->CADDR2, PAGE_SIZE);
5666         pte2_clear(sysmaps->CMAP1);
5667         tlb_flush((vm_offset_t)sysmaps->CADDR1);
5668         pte2_clear(sysmaps->CMAP2);
5669         tlb_flush((vm_offset_t)sysmaps->CADDR2);
5670         sched_unpin();
5671         mtx_unlock(&sysmaps->lock);
5672 }
5673
5674 int unmapped_buf_allowed = 1;
5675
5676 void
5677 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
5678     vm_offset_t b_offset, int xfersize)
5679 {
5680         struct sysmaps *sysmaps;
5681         vm_page_t a_pg, b_pg;
5682         char *a_cp, *b_cp;
5683         vm_offset_t a_pg_offset, b_pg_offset;
5684         int cnt;
5685
5686         sched_pin();
5687         sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
5688         mtx_lock(&sysmaps->lock);
5689         if (*sysmaps->CMAP1 != 0)
5690                 panic("pmap_copy_pages: CMAP1 busy");
5691         if (*sysmaps->CMAP2 != 0)
5692                 panic("pmap_copy_pages: CMAP2 busy");
5693         while (xfersize > 0) {
5694                 a_pg = ma[a_offset >> PAGE_SHIFT];
5695                 a_pg_offset = a_offset & PAGE_MASK;
5696                 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
5697                 b_pg = mb[b_offset >> PAGE_SHIFT];
5698                 b_pg_offset = b_offset & PAGE_MASK;
5699                 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
5700                 pte2_store(sysmaps->CMAP1, PTE2_KERN_NG(VM_PAGE_TO_PHYS(a_pg),
5701                     PTE2_AP_KR | PTE2_NM, a_pg->md.pat_mode));
5702                 tlb_flush_local((vm_offset_t)sysmaps->CADDR1);
5703                 pte2_store(sysmaps->CMAP2, PTE2_KERN_NG(VM_PAGE_TO_PHYS(b_pg),
5704                     PTE2_AP_KRW, b_pg->md.pat_mode));
5705                 tlb_flush_local((vm_offset_t)sysmaps->CADDR2);
5706                 a_cp = sysmaps->CADDR1 + a_pg_offset;
5707                 b_cp = sysmaps->CADDR2 + b_pg_offset;
5708                 bcopy(a_cp, b_cp, cnt);
5709                 a_offset += cnt;
5710                 b_offset += cnt;
5711                 xfersize -= cnt;
5712         }
5713         pte2_clear(sysmaps->CMAP1);
5714         tlb_flush((vm_offset_t)sysmaps->CADDR1);
5715         pte2_clear(sysmaps->CMAP2);
5716         tlb_flush((vm_offset_t)sysmaps->CADDR2);
5717         sched_unpin();
5718         mtx_unlock(&sysmaps->lock);
5719 }
5720
5721 vm_offset_t
5722 pmap_quick_enter_page(vm_page_t m)
5723 {
5724         pt2_entry_t *pte2p;
5725         vm_offset_t qmap_addr;
5726
5727         critical_enter();
5728         qmap_addr = PCPU_GET(qmap_addr);
5729         pte2p = pt2map_entry(qmap_addr);
5730
5731         KASSERT(pte2_load(pte2p) == 0, ("%s: PTE2 busy", __func__));
5732
5733         pte2_store(pte2p, PTE2_KERN_NG(VM_PAGE_TO_PHYS(m), PTE2_AP_KRW,
5734             pmap_page_get_memattr(m)));
5735         return (qmap_addr);
5736 }
5737
5738 void
5739 pmap_quick_remove_page(vm_offset_t addr)
5740 {
5741         pt2_entry_t *pte2p;
5742         vm_offset_t qmap_addr;
5743
5744         qmap_addr = PCPU_GET(qmap_addr);
5745         pte2p = pt2map_entry(qmap_addr);
5746
5747         KASSERT(addr == qmap_addr, ("%s: invalid address", __func__));
5748         KASSERT(pte2_load(pte2p) != 0, ("%s: PTE2 not in use", __func__));
5749
5750         pte2_clear(pte2p);
5751         tlb_flush(qmap_addr);
5752         critical_exit();
5753 }
5754
5755 /*
5756  *      Copy the range specified by src_addr/len
5757  *      from the source map to the range dst_addr/len
5758  *      in the destination map.
5759  *
5760  *      This routine is only advisory and need not do anything.
5761  */
5762 void
5763 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
5764     vm_offset_t src_addr)
5765 {
5766         struct spglist free;
5767         vm_offset_t addr;
5768         vm_offset_t end_addr = src_addr + len;
5769         vm_offset_t nextva;
5770
5771         if (dst_addr != src_addr)
5772                 return;
5773
5774         if (!pmap_is_current(src_pmap))
5775                 return;
5776
5777         rw_wlock(&pvh_global_lock);
5778         if (dst_pmap < src_pmap) {
5779                 PMAP_LOCK(dst_pmap);
5780                 PMAP_LOCK(src_pmap);
5781         } else {
5782                 PMAP_LOCK(src_pmap);
5783                 PMAP_LOCK(dst_pmap);
5784         }
5785         sched_pin();
5786         for (addr = src_addr; addr < end_addr; addr = nextva) {
5787                 pt2_entry_t *src_pte2p, *dst_pte2p;
5788                 vm_page_t dst_mpt2pg, src_mpt2pg;
5789                 pt1_entry_t src_pte1;
5790                 u_int pte1_idx;
5791
5792                 KASSERT(addr < VM_MAXUSER_ADDRESS,
5793                     ("%s: invalid to pmap_copy page tables", __func__));
5794
5795                 nextva = pte1_trunc(addr + PTE1_SIZE);
5796                 if (nextva < addr)
5797                         nextva = end_addr;
5798
5799                 pte1_idx = pte1_index(addr);
5800                 src_pte1 = src_pmap->pm_pt1[pte1_idx];
5801                 if (pte1_is_section(src_pte1)) {
5802                         if ((addr & PTE1_OFFSET) != 0 ||
5803                             (addr + PTE1_SIZE) > end_addr)
5804                                 continue;
5805                         if (dst_pmap->pm_pt1[pte1_idx] == 0 &&
5806                             (!pte1_is_managed(src_pte1) ||
5807                             pmap_pv_insert_pte1(dst_pmap, addr,
5808                             pte1_pa(src_pte1)))) {
5809                                 dst_pmap->pm_pt1[pte1_idx] = src_pte1 &
5810                                     ~PTE1_W;
5811                                 dst_pmap->pm_stats.resident_count +=
5812                                     PTE1_SIZE / PAGE_SIZE;
5813                                 pmap_pte1_mappings++;
5814                         }
5815                         continue;
5816                 } else if (!pte1_is_link(src_pte1))
5817                         continue;
5818
5819                 src_mpt2pg = PHYS_TO_VM_PAGE(pte1_link_pa(src_pte1));
5820
5821                 /*
5822                  * We leave PT2s to be linked from PT1 even if they are not
5823                  * referenced until all PT2s in a page are without reference.
5824                  *
5825                  * QQQ: It could be changed ...
5826                  */
5827 #if 0 /* single_pt2_link_is_cleared */
5828                 KASSERT(pt2_wirecount_get(src_mpt2pg, pte1_idx) > 0,
5829                     ("%s: source page table page is unused", __func__));
5830 #else
5831                 if (pt2_wirecount_get(src_mpt2pg, pte1_idx) == 0)
5832                         continue;
5833 #endif
5834                 if (nextva > end_addr)
5835                         nextva = end_addr;
5836
5837                 src_pte2p = pt2map_entry(addr);
5838                 while (addr < nextva) {
5839                         pt2_entry_t temp_pte2;
5840                         temp_pte2 = pte2_load(src_pte2p);
5841                         /*
5842                          * we only virtual copy managed pages
5843                          */
5844                         if (pte2_is_managed(temp_pte2)) {
5845                                 dst_mpt2pg = pmap_allocpte2(dst_pmap, addr,
5846                                     PMAP_ENTER_NOSLEEP);
5847                                 if (dst_mpt2pg == NULL)
5848                                         goto out;
5849                                 dst_pte2p = pmap_pte2_quick(dst_pmap, addr);
5850                                 if (!pte2_is_valid(pte2_load(dst_pte2p)) &&
5851                                     pmap_try_insert_pv_entry(dst_pmap, addr,
5852                                     PHYS_TO_VM_PAGE(pte2_pa(temp_pte2)))) {
5853                                         /*
5854                                          * Clear the wired, modified, and
5855                                          * accessed (referenced) bits
5856                                          * during the copy.
5857                                          */
5858                                         temp_pte2 &=  ~(PTE2_W | PTE2_A);
5859                                         temp_pte2 |= PTE2_NM;
5860                                         pte2_store(dst_pte2p, temp_pte2);
5861                                         dst_pmap->pm_stats.resident_count++;
5862                                 } else {
5863                                         SLIST_INIT(&free);
5864                                         if (pmap_unwire_pt2(dst_pmap, addr,
5865                                             dst_mpt2pg, &free)) {
5866                                                 pmap_tlb_flush(dst_pmap, addr);
5867                                                 pmap_free_zero_pages(&free);
5868                                         }
5869                                         goto out;
5870                                 }
5871                                 if (pt2_wirecount_get(dst_mpt2pg, pte1_idx) >=
5872                                     pt2_wirecount_get(src_mpt2pg, pte1_idx))
5873                                         break;
5874                         }
5875                         addr += PAGE_SIZE;
5876                         src_pte2p++;
5877                 }
5878         }
5879 out:
5880         sched_unpin();
5881         rw_wunlock(&pvh_global_lock);
5882         PMAP_UNLOCK(src_pmap);
5883         PMAP_UNLOCK(dst_pmap);
5884 }
5885
5886 /*
5887  *      Increase the starting virtual address of the given mapping if a
5888  *      different alignment might result in more section mappings.
5889  */
5890 void
5891 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
5892     vm_offset_t *addr, vm_size_t size)
5893 {
5894         vm_offset_t pte1_offset;
5895
5896         if (size < PTE1_SIZE)
5897                 return;
5898         if (object != NULL && (object->flags & OBJ_COLORED) != 0)
5899                 offset += ptoa(object->pg_color);
5900         pte1_offset = offset & PTE1_OFFSET;
5901         if (size - ((PTE1_SIZE - pte1_offset) & PTE1_OFFSET) < PTE1_SIZE ||
5902             (*addr & PTE1_OFFSET) == pte1_offset)
5903                 return;
5904         if ((*addr & PTE1_OFFSET) < pte1_offset)
5905                 *addr = pte1_trunc(*addr) + pte1_offset;
5906         else
5907                 *addr = pte1_roundup(*addr) + pte1_offset;
5908 }
5909
5910 void
5911 pmap_activate(struct thread *td)
5912 {
5913         pmap_t pmap, oldpmap;
5914         u_int cpuid, ttb;
5915
5916         PDEBUG(9, printf("%s: td = %08x\n", __func__, (uint32_t)td));
5917
5918         critical_enter();
5919         pmap = vmspace_pmap(td->td_proc->p_vmspace);
5920         oldpmap = PCPU_GET(curpmap);
5921         cpuid = PCPU_GET(cpuid);
5922
5923 #if defined(SMP)
5924         CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
5925         CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
5926 #else
5927         CPU_CLR(cpuid, &oldpmap->pm_active);
5928         CPU_SET(cpuid, &pmap->pm_active);
5929 #endif
5930
5931         ttb = pmap_ttb_get(pmap);
5932
5933         /*
5934          * pmap_activate is for the current thread on the current cpu
5935          */
5936         td->td_pcb->pcb_pagedir = ttb;
5937         cp15_ttbr_set(ttb);
5938         PCPU_SET(curpmap, pmap);
5939         critical_exit();
5940 }
5941
5942 /*
5943  *  Perform the pmap work for mincore.
5944  */
5945 int
5946 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *locked_pa)
5947 {
5948         pt1_entry_t *pte1p, pte1;
5949         pt2_entry_t *pte2p, pte2;
5950         vm_paddr_t pa;
5951         boolean_t managed;
5952         int val;
5953
5954         PMAP_LOCK(pmap);
5955 retry:
5956         pte1p = pmap_pte1(pmap, addr);
5957         pte1 = pte1_load(pte1p);
5958         if (pte1_is_section(pte1)) {
5959                 pa = trunc_page(pte1_pa(pte1) | (addr & PTE1_OFFSET));
5960                 managed = pte1_is_managed(pte1);
5961                 val = MINCORE_SUPER | MINCORE_INCORE;
5962                 if (pte1_is_dirty(pte1))
5963                         val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
5964                 if (pte1 & PTE1_A)
5965                         val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
5966         } else if (pte1_is_link(pte1)) {
5967                 pte2p = pmap_pte2(pmap, addr);
5968                 pte2 = pte2_load(pte2p);
5969                 pmap_pte2_release(pte2p);
5970                 pa = pte2_pa(pte2);
5971                 managed = pte2_is_managed(pte2);
5972                 val = MINCORE_INCORE;
5973                 if (pte2_is_dirty(pte2))
5974                         val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
5975                 if (pte2 & PTE2_A)
5976                         val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
5977         } else {
5978                 managed = FALSE;
5979                 val = 0;
5980         }
5981         if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
5982             (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) && managed) {
5983                 /* Ensure that "PHYS_TO_VM_PAGE(pa)->object" doesn't change. */
5984                 if (vm_page_pa_tryrelock(pmap, pa, locked_pa))
5985                         goto retry;
5986         } else
5987                 PA_UNLOCK_COND(*locked_pa);
5988         PMAP_UNLOCK(pmap);
5989         return (val);
5990 }
5991
5992 void
5993 pmap_kenter_device(vm_offset_t va, vm_size_t size, vm_paddr_t pa)
5994 {
5995         vm_offset_t sva;
5996
5997         KASSERT((size & PAGE_MASK) == 0,
5998             ("%s: device mapping not page-sized", __func__));
5999
6000         sva = va;
6001         while (size != 0) {
6002                 pmap_kenter_prot_attr(va, pa, PTE2_AP_KRW, PTE2_ATTR_DEVICE);
6003                 va += PAGE_SIZE;
6004                 pa += PAGE_SIZE;
6005                 size -= PAGE_SIZE;
6006         }
6007         tlb_flush_range(sva, va - sva);
6008 }
6009
6010 void
6011 pmap_kremove_device(vm_offset_t va, vm_size_t size)
6012 {
6013         vm_offset_t sva;
6014
6015         KASSERT((size & PAGE_MASK) == 0,
6016             ("%s: device mapping not page-sized", __func__));
6017
6018         sva = va;
6019         while (size != 0) {
6020                 pmap_kremove(va);
6021                 va += PAGE_SIZE;
6022                 size -= PAGE_SIZE;
6023         }
6024         tlb_flush_range(sva, va - sva);
6025 }
6026
6027 void
6028 pmap_set_pcb_pagedir(pmap_t pmap, struct pcb *pcb)
6029 {
6030
6031         pcb->pcb_pagedir = pmap_ttb_get(pmap);
6032 }
6033
6034
6035 /*
6036  *  Clean L1 data cache range by physical address.
6037  *  The range must be within a single page.
6038  */
6039 static void
6040 pmap_dcache_wb_pou(vm_paddr_t pa, vm_size_t size, vm_memattr_t ma)
6041 {
6042         struct sysmaps *sysmaps;
6043
6044         KASSERT(((pa & PAGE_MASK) + size) <= PAGE_SIZE,
6045             ("%s: not on single page", __func__));
6046
6047         sched_pin();
6048         sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
6049         mtx_lock(&sysmaps->lock);
6050         if (*sysmaps->CMAP3)
6051                 panic("%s: CMAP3 busy", __func__);
6052         pte2_store(sysmaps->CMAP3, PTE2_KERN_NG(pa, PTE2_AP_KRW, ma));
6053         dcache_wb_pou((vm_offset_t)sysmaps->CADDR3 + (pa & PAGE_MASK), size);
6054         pte2_clear(sysmaps->CMAP3);
6055         tlb_flush((vm_offset_t)sysmaps->CADDR3);
6056         sched_unpin();
6057         mtx_unlock(&sysmaps->lock);
6058 }
6059
6060 /*
6061  *  Sync instruction cache range which is not mapped yet.
6062  */
6063 void
6064 cache_icache_sync_fresh(vm_offset_t va, vm_paddr_t pa, vm_size_t size)
6065 {
6066         uint32_t len, offset;
6067         vm_page_t m;
6068
6069         /* Write back d-cache on given address range. */
6070         offset = pa & PAGE_MASK;
6071         for ( ; size != 0; size -= len, pa += len, offset = 0) {
6072                 len = min(PAGE_SIZE - offset, size);
6073                 m = PHYS_TO_VM_PAGE(pa);
6074                 KASSERT(m != NULL, ("%s: vm_page_t is null for %#x",
6075                   __func__, pa));
6076                 pmap_dcache_wb_pou(pa, len, m->md.pat_mode);
6077         }
6078         /*
6079          * I-cache is VIPT. Only way how to flush all virtual mappings
6080          * on given physical address is to invalidate all i-cache.
6081          */
6082         icache_inv_all();
6083 }
6084
6085 void
6086 pmap_sync_icache(pmap_t pmap, vm_offset_t va, vm_size_t size)
6087 {
6088
6089         /* Write back d-cache on given address range. */
6090         if (va >= VM_MIN_KERNEL_ADDRESS) {
6091                 dcache_wb_pou(va, size);
6092         } else {
6093                 uint32_t len, offset;
6094                 vm_paddr_t pa;
6095                 vm_page_t m;
6096
6097                 offset = va & PAGE_MASK;
6098                 for ( ; size != 0; size -= len, va += len, offset = 0) {
6099                         pa = pmap_extract(pmap, va); /* offset is preserved */
6100                         len = min(PAGE_SIZE - offset, size);
6101                         m = PHYS_TO_VM_PAGE(pa);
6102                         KASSERT(m != NULL, ("%s: vm_page_t is null for %#x",
6103                                 __func__, pa));
6104                         pmap_dcache_wb_pou(pa, len, m->md.pat_mode);
6105                 }
6106         }
6107         /*
6108          * I-cache is VIPT. Only way how to flush all virtual mappings
6109          * on given physical address is to invalidate all i-cache.
6110          */
6111         icache_inv_all();
6112 }
6113
6114 /*
6115  *  The implementation of pmap_fault() uses IN_RANGE2() macro which
6116  *  depends on the fact that given range size is a power of 2.
6117  */
6118 CTASSERT(powerof2(NB_IN_PT1));
6119 CTASSERT(powerof2(PT2MAP_SIZE));
6120
6121 #define IN_RANGE2(addr, start, size)    \
6122     ((vm_offset_t)(start) == ((vm_offset_t)(addr) & ~((size) - 1)))
6123
6124 /*
6125  *  Handle access and R/W emulation faults.
6126  */
6127 int
6128 pmap_fault(pmap_t pmap, vm_offset_t far, uint32_t fsr, int idx, bool usermode)
6129 {
6130         pt1_entry_t *pte1p, pte1;
6131         pt2_entry_t *pte2p, pte2;
6132
6133         if (pmap == NULL)
6134                 pmap = kernel_pmap;
6135
6136         /*
6137          * In kernel, we should never get abort with FAR which is in range of
6138          * pmap->pm_pt1 or PT2MAP address spaces. If it happens, stop here
6139          * and print out a useful abort message and even get to the debugger
6140          * otherwise it likely ends with never ending loop of aborts.
6141          */
6142         if (__predict_false(IN_RANGE2(far, pmap->pm_pt1, NB_IN_PT1))) {
6143                 /*
6144                  * All L1 tables should always be mapped and present.
6145                  * However, we check only current one herein. For user mode,
6146                  * only permission abort from malicious user is not fatal.
6147                  * And alignment abort as it may have higher priority.
6148                  */
6149                 if (!usermode || (idx != FAULT_ALIGN && idx != FAULT_PERM_L2)) {
6150                         CTR4(KTR_PMAP, "%s: pmap %#x pm_pt1 %#x far %#x",
6151                             __func__, pmap, pmap->pm_pt1, far);
6152                         panic("%s: pm_pt1 abort", __func__);
6153                 }
6154                 return (KERN_INVALID_ADDRESS);
6155         }
6156         if (__predict_false(IN_RANGE2(far, PT2MAP, PT2MAP_SIZE))) {
6157                 /*
6158                  * PT2MAP should be always mapped and present in current
6159                  * L1 table. However, only existing L2 tables are mapped
6160                  * in PT2MAP. For user mode, only L2 translation abort and
6161                  * permission abort from malicious user is not fatal.
6162                  * And alignment abort as it may have higher priority.
6163                  */
6164                 if (!usermode || (idx != FAULT_ALIGN &&
6165                     idx != FAULT_TRAN_L2 && idx != FAULT_PERM_L2)) {
6166                         CTR4(KTR_PMAP, "%s: pmap %#x PT2MAP %#x far %#x",
6167                             __func__, pmap, PT2MAP, far);
6168                         panic("%s: PT2MAP abort", __func__);
6169                 }
6170                 return (KERN_INVALID_ADDRESS);
6171         }
6172
6173         /*
6174          * Accesss bits for page and section. Note that the entry
6175          * is not in TLB yet, so TLB flush is not necessary.
6176          *
6177          * QQQ: This is hardware emulation, we do not call userret()
6178          *      for aborts from user mode.
6179          *      We do not lock PMAP, so cmpset() is a need. Hopefully,
6180          *      no one removes the mapping when we are here.
6181          */
6182         if (idx == FAULT_ACCESS_L2) {
6183                 pte2p = pt2map_entry(far);
6184 pte2_seta:
6185                 pte2 = pte2_load(pte2p);
6186                 if (pte2_is_valid(pte2)) {
6187                         if (!pte2_cmpset(pte2p, pte2, pte2 | PTE2_A)) {
6188                                 goto pte2_seta;
6189                         }
6190                         return (KERN_SUCCESS);
6191                 }
6192         }
6193         if (idx == FAULT_ACCESS_L1) {
6194                 pte1p = pmap_pte1(pmap, far);
6195 pte1_seta:
6196                 pte1 = pte1_load(pte1p);
6197                 if (pte1_is_section(pte1)) {
6198                         if (!pte1_cmpset(pte1p, pte1, pte1 | PTE1_A)) {
6199                                 goto pte1_seta;
6200                         }
6201                         return (KERN_SUCCESS);
6202                 }
6203         }
6204
6205         /*
6206          * Handle modify bits for page and section. Note that the modify
6207          * bit is emulated by software. So PTEx_RO is software read only
6208          * bit and PTEx_NM flag is real hardware read only bit.
6209          *
6210          * QQQ: This is hardware emulation, we do not call userret()
6211          *      for aborts from user mode.
6212          *      We do not lock PMAP, so cmpset() is a need. Hopefully,
6213          *      no one removes the mapping when we are here.
6214          */
6215         if ((fsr & FSR_WNR) && (idx == FAULT_PERM_L2)) {
6216                 pte2p = pt2map_entry(far);
6217 pte2_setrw:
6218                 pte2 = pte2_load(pte2p);
6219                 if (pte2_is_valid(pte2) && !(pte2 & PTE2_RO) &&
6220                     (pte2 & PTE2_NM)) {
6221                         if (!pte2_cmpset(pte2p, pte2, pte2 & ~PTE2_NM)) {
6222                                 goto pte2_setrw;
6223                         }
6224                         tlb_flush(trunc_page(far));
6225                         return (KERN_SUCCESS);
6226                 }
6227         }
6228         if ((fsr & FSR_WNR) && (idx == FAULT_PERM_L1)) {
6229                 pte1p = pmap_pte1(pmap, far);
6230 pte1_setrw:
6231                 pte1 = pte1_load(pte1p);
6232                 if (pte1_is_section(pte1) && !(pte1 & PTE1_RO) &&
6233                     (pte1 & PTE1_NM)) {
6234                         if (!pte1_cmpset(pte1p, pte1, pte1 & ~PTE1_NM)) {
6235                                 goto pte1_setrw;
6236                         }
6237                         tlb_flush(pte1_trunc(far));
6238                         return (KERN_SUCCESS);
6239                 }
6240         }
6241
6242         /*
6243          * QQQ: The previous code, mainly fast handling of access and
6244          *      modify bits aborts, could be moved to ASM. Now we are
6245          *      starting to deal with not fast aborts.
6246          */
6247
6248 #ifdef INVARIANTS
6249         /*
6250          * Read an entry in PT2TAB associated with both pmap and far.
6251          * It's safe because PT2TAB is always mapped.
6252          *
6253          * QQQ: We do not lock PMAP, so false positives could happen if
6254          *      the mapping is removed concurrently.
6255          */
6256         pte2 = pt2tab_load(pmap_pt2tab_entry(pmap, far));
6257         if (pte2_is_valid(pte2)) {
6258                 /*
6259                  * Now, when we know that L2 page table is allocated,
6260                  * we can use PT2MAP to get L2 page table entry.
6261                  */
6262                 pte2 = pte2_load(pt2map_entry(far));
6263                 if (pte2_is_valid(pte2)) {
6264                         /*
6265                          * If L2 page table entry is valid, make sure that
6266                          * L1 page table entry is valid too.  Note that we
6267                          * leave L2 page entries untouched when promoted.
6268                          */
6269                         pte1 = pte1_load(pmap_pte1(pmap, far));
6270                         if (!pte1_is_valid(pte1)) {
6271                                 panic("%s: missing L1 page entry (%p, %#x)",
6272                                     __func__, pmap, far);
6273                         }
6274                 }
6275         }
6276 #endif
6277         return (KERN_FAILURE);
6278 }
6279
6280 /* !!!! REMOVE !!!! */
6281 void
6282 pmap_pte_init_mmu_v6(void)
6283 {
6284 }
6285
6286 void vector_page_setprot(int p)
6287 {
6288 }
6289
6290 #if defined(PMAP_DEBUG)
6291 /*
6292  *  Reusing of KVA used in pmap_zero_page function !!!
6293  */
6294 static void
6295 pmap_zero_page_check(vm_page_t m)
6296 {
6297         uint32_t *p, *end;
6298         struct sysmaps *sysmaps;
6299
6300         sched_pin();
6301         sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
6302         mtx_lock(&sysmaps->lock);
6303         if (pte2_load(sysmaps->CMAP2) != 0)
6304                 panic("%s: CMAP2 busy", __func__);
6305         pte2_store(sysmaps->CMAP2, PTE2_KERN_NG(VM_PAGE_TO_PHYS(m), PTE2_AP_KRW,
6306             m->md.pat_mode));
6307         end = (uint32_t*)(sysmaps->CADDR2 + PAGE_SIZE);
6308         for (p = (uint32_t*)sysmaps->CADDR2; p < end; p++)
6309                 if (*p != 0)
6310                         panic("%s: page %p not zero, va: %p", __func__, m,
6311                             sysmaps->CADDR2);
6312         pte2_clear(sysmaps->CMAP2);
6313         tlb_flush((vm_offset_t)sysmaps->CADDR2);
6314         sched_unpin();
6315         mtx_unlock(&sysmaps->lock);
6316 }
6317
6318 int
6319 pmap_pid_dump(int pid)
6320 {
6321         pmap_t pmap;
6322         struct proc *p;
6323         int npte2 = 0;
6324         int i, j, index;
6325
6326         sx_slock(&allproc_lock);
6327         FOREACH_PROC_IN_SYSTEM(p) {
6328                 if (p->p_pid != pid || p->p_vmspace == NULL)
6329                         continue;
6330                 index = 0;
6331                 pmap = vmspace_pmap(p->p_vmspace);
6332                 for (i = 0; i < NPTE1_IN_PT1; i++) {
6333                         pt1_entry_t pte1;
6334                         pt2_entry_t *pte2p, pte2;
6335                         vm_offset_t base, va;
6336                         vm_paddr_t pa;
6337                         vm_page_t m;
6338
6339                         base = i << PTE1_SHIFT;
6340                         pte1 = pte1_load(&pmap->pm_pt1[i]);
6341
6342                         if (pte1_is_section(pte1)) {
6343                                 /*
6344                                  * QQQ: Do something here!
6345                                  */
6346                         } else if (pte1_is_link(pte1)) {
6347                                 for (j = 0; j < NPTE2_IN_PT2; j++) {
6348                                         va = base + (j << PAGE_SHIFT);
6349                                         if (va >= VM_MIN_KERNEL_ADDRESS) {
6350                                                 if (index) {
6351                                                         index = 0;
6352                                                         printf("\n");
6353                                                 }
6354                                                 sx_sunlock(&allproc_lock);
6355                                                 return (npte2);
6356                                         }
6357                                         pte2p = pmap_pte2(pmap, va);
6358                                         pte2 = pte2_load(pte2p);
6359                                         pmap_pte2_release(pte2p);
6360                                         if (!pte2_is_valid(pte2))
6361                                                 continue;
6362
6363                                         pa = pte2_pa(pte2);
6364                                         m = PHYS_TO_VM_PAGE(pa);
6365                                         printf("va: 0x%x, pa: 0x%x, h: %d, w:"
6366                                             " %d, f: 0x%x", va, pa,
6367                                             m->hold_count, m->wire_count,
6368                                             m->flags);
6369                                         npte2++;
6370                                         index++;
6371                                         if (index >= 2) {
6372                                                 index = 0;
6373                                                 printf("\n");
6374                                         } else {
6375                                                 printf(" ");
6376                                         }
6377                                 }
6378                         }
6379                 }
6380         }
6381         sx_sunlock(&allproc_lock);
6382         return (npte2);
6383 }
6384
6385 #endif
6386
6387 #ifdef DDB
6388 static pt2_entry_t *
6389 pmap_pte2_ddb(pmap_t pmap, vm_offset_t va)
6390 {
6391         pt1_entry_t pte1;
6392         vm_paddr_t pt2pg_pa;
6393
6394         pte1 = pte1_load(pmap_pte1(pmap, va));
6395         if (!pte1_is_link(pte1))
6396                 return (NULL);
6397
6398         if (pmap_is_current(pmap))
6399                 return (pt2map_entry(va));
6400
6401         /* Note that L2 page table size is not equal to PAGE_SIZE. */
6402         pt2pg_pa = trunc_page(pte1_link_pa(pte1));
6403         if (pte2_pa(pte2_load(PMAP3)) != pt2pg_pa) {
6404                 pte2_store(PMAP3, PTE2_KPT(pt2pg_pa));
6405 #ifdef SMP
6406                 PMAP3cpu = PCPU_GET(cpuid);
6407 #endif
6408                 tlb_flush_local((vm_offset_t)PADDR3);
6409         }
6410 #ifdef SMP
6411         else if (PMAP3cpu != PCPU_GET(cpuid)) {
6412                 PMAP3cpu = PCPU_GET(cpuid);
6413                 tlb_flush_local((vm_offset_t)PADDR3);
6414         }
6415 #endif
6416         return (PADDR3 + (arm32_btop(va) & (NPTE2_IN_PG - 1)));
6417 }
6418
6419 static void
6420 dump_pmap(pmap_t pmap)
6421 {
6422
6423         printf("pmap %p\n", pmap);
6424         printf("  pm_pt1: %p\n", pmap->pm_pt1);
6425         printf("  pm_pt2tab: %p\n", pmap->pm_pt2tab);
6426         printf("  pm_active: 0x%08lX\n", pmap->pm_active.__bits[0]);
6427 }
6428
6429 DB_SHOW_COMMAND(pmaps, pmap_list_pmaps)
6430 {
6431
6432         pmap_t pmap;
6433         LIST_FOREACH(pmap, &allpmaps, pm_list) {
6434                 dump_pmap(pmap);
6435         }
6436 }
6437
6438 static int
6439 pte2_class(pt2_entry_t pte2)
6440 {
6441         int cls;
6442
6443         cls = (pte2 >> 2) & 0x03;
6444         cls |= (pte2 >> 4) & 0x04;
6445         return (cls);
6446 }
6447
6448 static void
6449 dump_section(pmap_t pmap, uint32_t pte1_idx)
6450 {
6451 }
6452
6453 static void
6454 dump_link(pmap_t pmap, uint32_t pte1_idx, boolean_t invalid_ok)
6455 {
6456         uint32_t i;
6457         vm_offset_t va;
6458         pt2_entry_t *pte2p, pte2;
6459         vm_page_t m;
6460
6461         va = pte1_idx << PTE1_SHIFT;
6462         pte2p = pmap_pte2_ddb(pmap, va);
6463         for (i = 0; i < NPTE2_IN_PT2; i++, pte2p++, va += PAGE_SIZE) {
6464                 pte2 = pte2_load(pte2p);
6465                 if (pte2 == 0)
6466                         continue;
6467                 if (!pte2_is_valid(pte2)) {
6468                         printf(" 0x%08X: 0x%08X", va, pte2);
6469                         if (!invalid_ok)
6470                                 printf(" - not valid !!!");
6471                         printf("\n");
6472                         continue;
6473                 }
6474                 m = PHYS_TO_VM_PAGE(pte2_pa(pte2));
6475                 printf(" 0x%08X: 0x%08X, TEX%d, s:%d, g:%d, m:%p", va , pte2,
6476                     pte2_class(pte2), !!(pte2 & PTE2_S), !(pte2 & PTE2_NG), m);
6477                 if (m != NULL) {
6478                         printf(" v:%d h:%d w:%d f:0x%04X\n", m->valid,
6479                             m->hold_count, m->wire_count, m->flags);
6480                 } else {
6481                         printf("\n");
6482                 }
6483         }
6484 }
6485
6486 static __inline boolean_t
6487 is_pv_chunk_space(vm_offset_t va)
6488 {
6489
6490         if ((((vm_offset_t)pv_chunkbase) <= va) &&
6491             (va < ((vm_offset_t)pv_chunkbase + PAGE_SIZE * pv_maxchunks)))
6492                 return (TRUE);
6493         return (FALSE);
6494 }
6495
6496 DB_SHOW_COMMAND(pmap, pmap_pmap_print)
6497 {
6498         /* XXX convert args. */
6499         pmap_t pmap = (pmap_t)addr;
6500         pt1_entry_t pte1;
6501         pt2_entry_t pte2;
6502         vm_offset_t va, eva;
6503         vm_page_t m;
6504         uint32_t i;
6505         boolean_t invalid_ok, dump_link_ok, dump_pv_chunk;
6506
6507         if (have_addr) {
6508                 pmap_t pm;
6509
6510                 LIST_FOREACH(pm, &allpmaps, pm_list)
6511                         if (pm == pmap) break;
6512                 if (pm == NULL) {
6513                         printf("given pmap %p is not in allpmaps list\n", pmap);
6514                         return;
6515                 }
6516         } else
6517                 pmap = PCPU_GET(curpmap);
6518
6519         eva = (modif[0] == 'u') ? VM_MAXUSER_ADDRESS : 0xFFFFFFFF;
6520         dump_pv_chunk = FALSE; /* XXX evaluate from modif[] */
6521
6522         printf("pmap: 0x%08X\n", (uint32_t)pmap);
6523         printf("PT2MAP: 0x%08X\n", (uint32_t)PT2MAP);
6524         printf("pt2tab: 0x%08X\n", (uint32_t)pmap->pm_pt2tab);
6525
6526         for(i = 0; i < NPTE1_IN_PT1; i++) {
6527                 pte1 = pte1_load(&pmap->pm_pt1[i]);
6528                 if (pte1 == 0)
6529                         continue;
6530                 va = i << PTE1_SHIFT;
6531                 if (va >= eva)
6532                         break;
6533
6534                 if (pte1_is_section(pte1)) {
6535                         printf("0x%08X: Section 0x%08X, s:%d g:%d\n", va, pte1,
6536                             !!(pte1 & PTE1_S), !(pte1 & PTE1_NG));
6537                         dump_section(pmap, i);
6538                 } else if (pte1_is_link(pte1)) {
6539                         dump_link_ok = TRUE;
6540                         invalid_ok = FALSE;
6541                         pte2 = pte2_load(pmap_pt2tab_entry(pmap, va));
6542                         m = PHYS_TO_VM_PAGE(pte1_link_pa(pte1));
6543                         printf("0x%08X: Link 0x%08X, pt2tab: 0x%08X m: %p",
6544                             va, pte1, pte2, m);
6545                         if (is_pv_chunk_space(va)) {
6546                                 printf(" - pv_chunk space");
6547                                 if (dump_pv_chunk)
6548                                         invalid_ok = TRUE;
6549                                 else
6550                                         dump_link_ok = FALSE;
6551                         }
6552                         else if (m != NULL)
6553                                 printf(" w:%d w2:%u", m->wire_count,
6554                                     pt2_wirecount_get(m, pte1_index(va)));
6555                         if (pte2 == 0)
6556                                 printf(" !!! pt2tab entry is ZERO");
6557                         else if (pte2_pa(pte1) != pte2_pa(pte2))
6558                                 printf(" !!! pt2tab entry is DIFFERENT - m: %p",
6559                                     PHYS_TO_VM_PAGE(pte2_pa(pte2)));
6560                         printf("\n");
6561                         if (dump_link_ok)
6562                                 dump_link(pmap, i, invalid_ok);
6563                 } else
6564                         printf("0x%08X: Invalid entry 0x%08X\n", va, pte1);
6565         }
6566 }
6567
6568 static void
6569 dump_pt2tab(pmap_t pmap)
6570 {
6571         uint32_t i;
6572         pt2_entry_t pte2;
6573         vm_offset_t va;
6574         vm_paddr_t pa;
6575         vm_page_t m;
6576
6577         printf("PT2TAB:\n");
6578         for (i = 0; i < PT2TAB_ENTRIES; i++) {
6579                 pte2 = pte2_load(&pmap->pm_pt2tab[i]);
6580                 if (!pte2_is_valid(pte2))
6581                         continue;
6582                 va = i << PT2TAB_SHIFT;
6583                 pa = pte2_pa(pte2);
6584                 m = PHYS_TO_VM_PAGE(pa);
6585                 printf(" 0x%08X: 0x%08X, TEX%d, s:%d, m:%p", va, pte2,
6586                     pte2_class(pte2), !!(pte2 & PTE2_S), m);
6587                 if (m != NULL)
6588                         printf(" , h: %d, w: %d, f: 0x%04X pidx: %lld",
6589                             m->hold_count, m->wire_count, m->flags, m->pindex);
6590                 printf("\n");
6591         }
6592 }
6593
6594 DB_SHOW_COMMAND(pmap_pt2tab, pmap_pt2tab_print)
6595 {
6596         /* XXX convert args. */
6597         pmap_t pmap = (pmap_t)addr;
6598         pt1_entry_t pte1;
6599         pt2_entry_t pte2;
6600         vm_offset_t va;
6601         uint32_t i, start;
6602
6603         if (have_addr) {
6604                 printf("supported only on current pmap\n");
6605                 return;
6606         }
6607
6608         pmap = PCPU_GET(curpmap);
6609         printf("curpmap: 0x%08X\n", (uint32_t)pmap);
6610         printf("PT2MAP: 0x%08X\n", (uint32_t)PT2MAP);
6611         printf("pt2tab: 0x%08X\n", (uint32_t)pmap->pm_pt2tab);
6612
6613         start = pte1_index((vm_offset_t)PT2MAP);
6614         for (i = start; i < (start + NPT2_IN_PT2TAB); i++) {
6615                 pte1 = pte1_load(&pmap->pm_pt1[i]);
6616                 if (pte1 == 0)
6617                         continue;
6618                 va = i << PTE1_SHIFT;
6619                 if (pte1_is_section(pte1)) {
6620                         printf("0x%08X: Section 0x%08X, s:%d\n", va, pte1,
6621                             !!(pte1 & PTE1_S));
6622                         dump_section(pmap, i);
6623                 } else if (pte1_is_link(pte1)) {
6624                         pte2 = pte2_load(pmap_pt2tab_entry(pmap, va));
6625                         printf("0x%08X: Link 0x%08X, pt2tab: 0x%08X\n", va,
6626                             pte1, pte2);
6627                         if (pte2 == 0)
6628                                 printf("  !!! pt2tab entry is ZERO\n");
6629                 } else
6630                         printf("0x%08X: Invalid entry 0x%08X\n", va, pte1);
6631         }
6632         dump_pt2tab(pmap);
6633 }
6634 #endif