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