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