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