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