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