]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/arm/arm/pmap-v6.c
MFV r293125: less v481.
[FreeBSD/FreeBSD.git] / sys / arm / arm / pmap-v6.c
1 /* From: $NetBSD: pmap.c,v 1.148 2004/04/03 04:35:48 bsh Exp $ */
2 /*-
3  * Copyright 2011 Semihalf
4  * Copyright 2004 Olivier Houchard.
5  * Copyright 2003 Wasabi Systems, Inc.
6  * All rights reserved.
7  *
8  * Written by Steve C. Woodford for Wasabi Systems, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed for the NetBSD Project by
21  *      Wasabi Systems, Inc.
22  * 4. The name of Wasabi Systems, Inc. may not be used to endorse
23  *    or promote products derived from this software without specific prior
24  *    written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL WASABI SYSTEMS, INC
30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36  * POSSIBILITY OF SUCH DAMAGE.
37  *
38  * From: FreeBSD: src/sys/arm/arm/pmap.c,v 1.113 2009/07/24 13:50:29
39  */
40
41 /*-
42  * Copyright (c) 2002-2003 Wasabi Systems, Inc.
43  * Copyright (c) 2001 Richard Earnshaw
44  * Copyright (c) 2001-2002 Christopher Gilbert
45  * All rights reserved.
46  *
47  * 1. Redistributions of source code must retain the above copyright
48  *    notice, this list of conditions and the following disclaimer.
49  * 2. Redistributions in binary form must reproduce the above copyright
50  *    notice, this list of conditions and the following disclaimer in the
51  *    documentation and/or other materials provided with the distribution.
52  * 3. The name of the company nor the name of the author may be used to
53  *    endorse or promote products derived from this software without specific
54  *    prior written permission.
55  *
56  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
57  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
58  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
59  * IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
60  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
61  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
62  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
63  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
64  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
65  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
66  * SUCH DAMAGE.
67  */
68 /*-
69  * Copyright (c) 1999 The NetBSD Foundation, Inc.
70  * All rights reserved.
71  *
72  * This code is derived from software contributed to The NetBSD Foundation
73  * by Charles M. Hannum.
74  *
75  * Redistribution and use in source and binary forms, with or without
76  * modification, are permitted provided that the following conditions
77  * are met:
78  * 1. Redistributions of source code must retain the above copyright
79  *    notice, this list of conditions and the following disclaimer.
80  * 2. Redistributions in binary form must reproduce the above copyright
81  *    notice, this list of conditions and the following disclaimer in the
82  *    documentation and/or other materials provided with the distribution.
83  *
84  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
85  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
86  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
87  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
88  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
89  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
90  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
91  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
92  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
93  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
94  * POSSIBILITY OF SUCH DAMAGE.
95  */
96
97 /*-
98  * Copyright (c) 1994-1998 Mark Brinicombe.
99  * Copyright (c) 1994 Brini.
100  * All rights reserved.
101  *
102  * This code is derived from software written for Brini by Mark Brinicombe
103  *
104  * Redistribution and use in source and binary forms, with or without
105  * modification, are permitted provided that the following conditions
106  * are met:
107  * 1. Redistributions of source code must retain the above copyright
108  *    notice, this list of conditions and the following disclaimer.
109  * 2. Redistributions in binary form must reproduce the above copyright
110  *    notice, this list of conditions and the following disclaimer in the
111  *    documentation and/or other materials provided with the distribution.
112  * 3. All advertising materials mentioning features or use of this software
113  *    must display the following acknowledgement:
114  *      This product includes software developed by Mark Brinicombe.
115  * 4. The name of the author may not be used to endorse or promote products
116  *    derived from this software without specific prior written permission.
117  *
118  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
119  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
120  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
121  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
122  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
123  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
124  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
125  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
126  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
127  *
128  * RiscBSD kernel project
129  *
130  * pmap.c
131  *
132  * Machine dependant vm stuff
133  *
134  * Created      : 20/09/94
135  */
136
137 /*
138  * Special compilation symbols
139  * PMAP_DEBUG           - Build in pmap_debug_level code
140  *
141  * Note that pmap_mapdev() and pmap_unmapdev() are implemented in arm/devmap.c
142 */
143 /* Include header files */
144
145 #include "opt_vm.h"
146 #include "opt_pmap.h"
147
148 #include <sys/cdefs.h>
149 __FBSDID("$FreeBSD$");
150 #include <sys/param.h>
151 #include <sys/systm.h>
152 #include <sys/kernel.h>
153 #include <sys/ktr.h>
154 #include <sys/lock.h>
155 #include <sys/proc.h>
156 #include <sys/malloc.h>
157 #include <sys/msgbuf.h>
158 #include <sys/mutex.h>
159 #include <sys/vmmeter.h>
160 #include <sys/mman.h>
161 #include <sys/rwlock.h>
162 #include <sys/smp.h>
163 #include <sys/sched.h>
164 #include <sys/sysctl.h>
165
166 #include <vm/vm.h>
167 #include <vm/vm_param.h>
168 #include <vm/uma.h>
169 #include <vm/pmap.h>
170 #include <vm/vm_kern.h>
171 #include <vm/vm_object.h>
172 #include <vm/vm_map.h>
173 #include <vm/vm_page.h>
174 #include <vm/vm_pageout.h>
175 #include <vm/vm_phys.h>
176 #include <vm/vm_extern.h>
177 #include <vm/vm_reserv.h>
178
179 #include <machine/md_var.h>
180 #include <machine/cpu.h>
181 #include <machine/cpufunc.h>
182 #include <machine/pcb.h>
183
184 #ifdef DEBUG
185 extern int last_fault_code;
186 #endif
187
188 #ifdef PMAP_DEBUG
189 #define PDEBUG(_lev_,_stat_) \
190         if (pmap_debug_level >= (_lev_)) \
191                 ((_stat_))
192 #define dprintf printf
193
194 int pmap_debug_level = 0;
195 #define PMAP_INLINE
196 #else   /* PMAP_DEBUG */
197 #define PDEBUG(_lev_,_stat_) /* Nothing */
198 #define dprintf(x, arg...)
199 #define PMAP_INLINE __inline
200 #endif  /* PMAP_DEBUG */
201
202 #ifdef PV_STATS
203 #define PV_STAT(x)      do { x ; } while (0)
204 #else
205 #define PV_STAT(x)      do { } while (0)
206 #endif
207
208 #define pa_to_pvh(pa)   (&pv_table[pa_index(pa)])
209
210 #ifdef ARM_L2_PIPT
211 #define pmap_l2cache_wbinv_range(va, pa, size) cpu_l2cache_wbinv_range((pa), (size))
212 #define pmap_l2cache_inv_range(va, pa, size) cpu_l2cache_inv_range((pa), (size))
213 #else
214 #define pmap_l2cache_wbinv_range(va, pa, size) cpu_l2cache_wbinv_range((va), (size))
215 #define pmap_l2cache_inv_range(va, pa, size) cpu_l2cache_inv_range((va), (size))
216 #endif
217
218 extern struct pv_addr systempage;
219
220 /*
221  * Internal function prototypes
222  */
223
224 static PMAP_INLINE
225 struct pv_entry         *pmap_find_pv(struct md_page *, pmap_t, vm_offset_t);
226 static void             pmap_free_pv_chunk(struct pv_chunk *pc);
227 static void             pmap_free_pv_entry(pmap_t pmap, pv_entry_t pv);
228 static pv_entry_t       pmap_get_pv_entry(pmap_t pmap, boolean_t try);
229 static vm_page_t        pmap_pv_reclaim(pmap_t locked_pmap);
230 static boolean_t        pmap_pv_insert_section(pmap_t, vm_offset_t,
231     vm_paddr_t);
232 static struct pv_entry  *pmap_remove_pv(struct vm_page *, pmap_t, vm_offset_t);
233 static int              pmap_pvh_wired_mappings(struct md_page *, int);
234
235 static int              pmap_enter_locked(pmap_t, vm_offset_t, vm_page_t,
236     vm_prot_t, u_int);
237 static vm_paddr_t       pmap_extract_locked(pmap_t pmap, vm_offset_t va);
238 static void             pmap_alloc_l1(pmap_t);
239 static void             pmap_free_l1(pmap_t);
240
241 static void             pmap_map_section(pmap_t, vm_offset_t, vm_offset_t,
242     vm_prot_t, boolean_t);
243 static void             pmap_promote_section(pmap_t, vm_offset_t);
244 static boolean_t        pmap_demote_section(pmap_t, vm_offset_t);
245 static boolean_t        pmap_enter_section(pmap_t, vm_offset_t, vm_page_t,
246     vm_prot_t);
247 static void             pmap_remove_section(pmap_t, vm_offset_t);
248
249 static int              pmap_clearbit(struct vm_page *, u_int);
250
251 static struct l2_bucket *pmap_get_l2_bucket(pmap_t, vm_offset_t);
252 static struct l2_bucket *pmap_alloc_l2_bucket(pmap_t, vm_offset_t);
253 static void             pmap_free_l2_bucket(pmap_t, struct l2_bucket *, u_int);
254 static vm_offset_t      kernel_pt_lookup(vm_paddr_t);
255
256 static MALLOC_DEFINE(M_VMPMAP, "pmap", "PMAP L1");
257
258 vm_offset_t virtual_avail;      /* VA of first avail page (after kernel bss) */
259 vm_offset_t virtual_end;        /* VA of last avail page (end of kernel AS) */
260 vm_offset_t pmap_curmaxkvaddr;
261 vm_paddr_t kernel_l1pa;
262
263 vm_offset_t kernel_vm_end = 0;
264
265 vm_offset_t vm_max_kernel_address;
266
267 struct pmap kernel_pmap_store;
268
269 /*
270  * Resources for quickly copying and zeroing pages using virtual address space
271  * and page table entries that are pre-allocated per-CPU by pmap_init().
272  */
273 struct czpages {
274         struct  mtx     lock;
275         pt_entry_t      *srcptep;
276         pt_entry_t      *dstptep;
277         vm_offset_t     srcva;
278         vm_offset_t     dstva;
279 };
280 static struct czpages cpu_czpages[MAXCPU];
281
282 static void             pmap_init_l1(struct l1_ttable *, pd_entry_t *);
283 /*
284  * These routines are called when the CPU type is identified to set up
285  * the PTE prototypes, cache modes, etc.
286  *
287  * The variables are always here, just in case LKMs need to reference
288  * them (though, they shouldn't).
289  */
290 static void pmap_set_prot(pt_entry_t *pte, vm_prot_t prot, uint8_t user);
291 pt_entry_t      pte_l1_s_cache_mode;
292 pt_entry_t      pte_l1_s_cache_mode_pt;
293
294 pt_entry_t      pte_l2_l_cache_mode;
295 pt_entry_t      pte_l2_l_cache_mode_pt;
296
297 pt_entry_t      pte_l2_s_cache_mode;
298 pt_entry_t      pte_l2_s_cache_mode_pt;
299
300 struct msgbuf *msgbufp = 0;
301
302 /*
303  * Crashdump maps.
304  */
305 static caddr_t crashdumpmap;
306
307 extern void bcopy_page(vm_offset_t, vm_offset_t);
308 extern void bzero_page(vm_offset_t);
309
310 char *_tmppt;
311
312 /*
313  * Metadata for L1 translation tables.
314  */
315 struct l1_ttable {
316         /* Entry on the L1 Table list */
317         SLIST_ENTRY(l1_ttable) l1_link;
318
319         /* Entry on the L1 Least Recently Used list */
320         TAILQ_ENTRY(l1_ttable) l1_lru;
321
322         /* Track how many domains are allocated from this L1 */
323         volatile u_int l1_domain_use_count;
324
325         /*
326          * A free-list of domain numbers for this L1.
327          * We avoid using ffs() and a bitmap to track domains since ffs()
328          * is slow on ARM.
329          */
330         u_int8_t l1_domain_first;
331         u_int8_t l1_domain_free[PMAP_DOMAINS];
332
333         /* Physical address of this L1 page table */
334         vm_paddr_t l1_physaddr;
335
336         /* KVA of this L1 page table */
337         pd_entry_t *l1_kva;
338 };
339
340 /*
341  * Convert a virtual address into its L1 table index. That is, the
342  * index used to locate the L2 descriptor table pointer in an L1 table.
343  * This is basically used to index l1->l1_kva[].
344  *
345  * Each L2 descriptor table represents 1MB of VA space.
346  */
347 #define L1_IDX(va)              (((vm_offset_t)(va)) >> L1_S_SHIFT)
348
349 /*
350  * L1 Page Tables are tracked using a Least Recently Used list.
351  *  - New L1s are allocated from the HEAD.
352  *  - Freed L1s are added to the TAIl.
353  *  - Recently accessed L1s (where an 'access' is some change to one of
354  *    the userland pmaps which owns this L1) are moved to the TAIL.
355  */
356 static TAILQ_HEAD(, l1_ttable) l1_lru_list;
357 /*
358  * A list of all L1 tables
359  */
360 static SLIST_HEAD(, l1_ttable) l1_list;
361 static struct mtx l1_lru_lock;
362
363 /*
364  * The l2_dtable tracks L2_BUCKET_SIZE worth of L1 slots.
365  *
366  * This is normally 16MB worth L2 page descriptors for any given pmap.
367  * Reference counts are maintained for L2 descriptors so they can be
368  * freed when empty.
369  */
370 struct l2_dtable {
371         /* The number of L2 page descriptors allocated to this l2_dtable */
372         u_int l2_occupancy;
373
374         /* List of L2 page descriptors */
375         struct l2_bucket {
376                 pt_entry_t *l2b_kva;    /* KVA of L2 Descriptor Table */
377                 vm_paddr_t l2b_phys;    /* Physical address of same */
378                 u_short l2b_l1idx;      /* This L2 table's L1 index */
379                 u_short l2b_occupancy;  /* How many active descriptors */
380         } l2_bucket[L2_BUCKET_SIZE];
381 };
382
383 /* pmap_kenter_internal flags */
384 #define KENTER_CACHE    0x1
385 #define KENTER_DEVICE   0x2
386 #define KENTER_USER     0x4
387
388 /*
389  * Given an L1 table index, calculate the corresponding l2_dtable index
390  * and bucket index within the l2_dtable.
391  */
392 #define L2_IDX(l1idx)           (((l1idx) >> L2_BUCKET_LOG2) & \
393                                  (L2_SIZE - 1))
394 #define L2_BUCKET(l1idx)        ((l1idx) & (L2_BUCKET_SIZE - 1))
395
396 /*
397  * Given a virtual address, this macro returns the
398  * virtual address required to drop into the next L2 bucket.
399  */
400 #define L2_NEXT_BUCKET(va)      (((va) & L1_S_FRAME) + L1_S_SIZE)
401
402 /*
403  * We try to map the page tables write-through, if possible.  However, not
404  * all CPUs have a write-through cache mode, so on those we have to sync
405  * the cache when we frob page tables.
406  *
407  * We try to evaluate this at compile time, if possible.  However, it's
408  * not always possible to do that, hence this run-time var.
409  */
410 int     pmap_needs_pte_sync;
411
412 /*
413  * Macro to determine if a mapping might be resident in the
414  * instruction cache and/or TLB
415  */
416 #define PTE_BEEN_EXECD(pte)  (L2_S_EXECUTABLE(pte) && L2_S_REFERENCED(pte))
417
418 /*
419  * Macro to determine if a mapping might be resident in the
420  * data cache and/or TLB
421  */
422 #define PTE_BEEN_REFD(pte)   (L2_S_REFERENCED(pte))
423
424 #ifndef PMAP_SHPGPERPROC
425 #define PMAP_SHPGPERPROC 200
426 #endif
427
428 #define pmap_is_current(pm)     ((pm) == pmap_kernel() || \
429             curproc->p_vmspace->vm_map.pmap == (pm))
430
431 /*
432  * Data for the pv entry allocation mechanism
433  */
434 static TAILQ_HEAD(pch, pv_chunk) pv_chunks = TAILQ_HEAD_INITIALIZER(pv_chunks);
435 static int pv_entry_count, pv_entry_max, pv_entry_high_water;
436 static struct md_page *pv_table;
437 static int shpgperproc = PMAP_SHPGPERPROC;
438
439 struct pv_chunk *pv_chunkbase;          /* KVA block for pv_chunks */
440 int pv_maxchunks;                       /* How many chunks we have KVA for */
441 vm_offset_t pv_vafree;                  /* Freelist stored in the PTE */
442
443 static __inline struct pv_chunk *
444 pv_to_chunk(pv_entry_t pv)
445 {
446
447         return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
448 }
449
450 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
451
452 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
453 CTASSERT(_NPCM == 8);
454 CTASSERT(_NPCPV == 252);
455
456 #define PC_FREE0_6      0xfffffffful    /* Free values for index 0 through 6 */
457 #define PC_FREE7        0x0ffffffful    /* Free values for index 7 */
458
459 static const uint32_t pc_freemask[_NPCM] = {
460         PC_FREE0_6, PC_FREE0_6, PC_FREE0_6,
461         PC_FREE0_6, PC_FREE0_6, PC_FREE0_6,
462         PC_FREE0_6, PC_FREE7
463 };
464
465 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD, 0, "VM/pmap parameters");
466
467 /* Superpages utilization enabled = 1 / disabled = 0 */
468 static int sp_enabled = 1;
469 SYSCTL_INT(_vm_pmap, OID_AUTO, sp_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &sp_enabled, 0,
470     "Are large page mappings enabled?");
471
472 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
473     "Current number of pv entries");
474
475 #ifdef PV_STATS
476 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
477
478 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
479     "Current number of pv entry chunks");
480 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
481     "Current number of pv entry chunks allocated");
482 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
483     "Current number of pv entry chunks frees");
484 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
485     "Number of times tried to get a chunk page but failed.");
486
487 static long pv_entry_frees, pv_entry_allocs;
488 static int pv_entry_spare;
489
490 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
491     "Current number of pv entry frees");
492 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
493     "Current number of pv entry allocs");
494 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
495     "Current number of spare pv entries");
496 #endif
497
498 uma_zone_t l2zone;
499 static uma_zone_t l2table_zone;
500 static vm_offset_t pmap_kernel_l2dtable_kva;
501 static vm_offset_t pmap_kernel_l2ptp_kva;
502 static vm_paddr_t pmap_kernel_l2ptp_phys;
503 static struct rwlock pvh_global_lock;
504
505 int l1_mem_types[] = {
506         ARM_L1S_STRONG_ORD,
507         ARM_L1S_DEVICE_NOSHARE,
508         ARM_L1S_DEVICE_SHARE,
509         ARM_L1S_NRML_NOCACHE,
510         ARM_L1S_NRML_IWT_OWT,
511         ARM_L1S_NRML_IWB_OWB,
512         ARM_L1S_NRML_IWBA_OWBA
513 };
514
515 int l2l_mem_types[] = {
516         ARM_L2L_STRONG_ORD,
517         ARM_L2L_DEVICE_NOSHARE,
518         ARM_L2L_DEVICE_SHARE,
519         ARM_L2L_NRML_NOCACHE,
520         ARM_L2L_NRML_IWT_OWT,
521         ARM_L2L_NRML_IWB_OWB,
522         ARM_L2L_NRML_IWBA_OWBA
523 };
524
525 int l2s_mem_types[] = {
526         ARM_L2S_STRONG_ORD,
527         ARM_L2S_DEVICE_NOSHARE,
528         ARM_L2S_DEVICE_SHARE,
529         ARM_L2S_NRML_NOCACHE,
530         ARM_L2S_NRML_IWT_OWT,
531         ARM_L2S_NRML_IWB_OWB,
532         ARM_L2S_NRML_IWBA_OWBA
533 };
534
535 /*
536  * This list exists for the benefit of pmap_map_chunk().  It keeps track
537  * of the kernel L2 tables during bootstrap, so that pmap_map_chunk() can
538  * find them as necessary.
539  *
540  * Note that the data on this list MUST remain valid after initarm() returns,
541  * as pmap_bootstrap() uses it to contruct L2 table metadata.
542  */
543 SLIST_HEAD(, pv_addr) kernel_pt_list = SLIST_HEAD_INITIALIZER(kernel_pt_list);
544
545 static void
546 pmap_init_l1(struct l1_ttable *l1, pd_entry_t *l1pt)
547 {
548         int i;
549
550         l1->l1_kva = l1pt;
551         l1->l1_domain_use_count = 0;
552         l1->l1_domain_first = 0;
553
554         for (i = 0; i < PMAP_DOMAINS; i++)
555                 l1->l1_domain_free[i] = i + 1;
556
557         /*
558          * Copy the kernel's L1 entries to each new L1.
559          */
560         if (l1pt != pmap_kernel()->pm_l1->l1_kva)
561                 memcpy(l1pt, pmap_kernel()->pm_l1->l1_kva, L1_TABLE_SIZE);
562
563         if ((l1->l1_physaddr = pmap_extract(pmap_kernel(), (vm_offset_t)l1pt)) == 0)
564                 panic("pmap_init_l1: can't get PA of L1 at %p", l1pt);
565         SLIST_INSERT_HEAD(&l1_list, l1, l1_link);
566         TAILQ_INSERT_TAIL(&l1_lru_list, l1, l1_lru);
567 }
568
569 static vm_offset_t
570 kernel_pt_lookup(vm_paddr_t pa)
571 {
572         struct pv_addr *pv;
573
574         SLIST_FOREACH(pv, &kernel_pt_list, pv_list) {
575                 if (pv->pv_pa == pa)
576                         return (pv->pv_va);
577         }
578         return (0);
579 }
580
581 void
582 pmap_pte_init_mmu_v6(void)
583 {
584
585         if (PTE_PAGETABLE >= 3)
586                 pmap_needs_pte_sync = 1;
587         pte_l1_s_cache_mode = l1_mem_types[PTE_CACHE];
588         pte_l2_l_cache_mode = l2l_mem_types[PTE_CACHE];
589         pte_l2_s_cache_mode = l2s_mem_types[PTE_CACHE];
590
591         pte_l1_s_cache_mode_pt = l1_mem_types[PTE_PAGETABLE];
592         pte_l2_l_cache_mode_pt = l2l_mem_types[PTE_PAGETABLE];
593         pte_l2_s_cache_mode_pt = l2s_mem_types[PTE_PAGETABLE];
594
595 }
596
597 /*
598  * Allocate an L1 translation table for the specified pmap.
599  * This is called at pmap creation time.
600  */
601 static void
602 pmap_alloc_l1(pmap_t pmap)
603 {
604         struct l1_ttable *l1;
605         u_int8_t domain;
606
607         /*
608          * Remove the L1 at the head of the LRU list
609          */
610         mtx_lock(&l1_lru_lock);
611         l1 = TAILQ_FIRST(&l1_lru_list);
612         TAILQ_REMOVE(&l1_lru_list, l1, l1_lru);
613
614         /*
615          * Pick the first available domain number, and update
616          * the link to the next number.
617          */
618         domain = l1->l1_domain_first;
619         l1->l1_domain_first = l1->l1_domain_free[domain];
620
621         /*
622          * If there are still free domain numbers in this L1,
623          * put it back on the TAIL of the LRU list.
624          */
625         if (++l1->l1_domain_use_count < PMAP_DOMAINS)
626                 TAILQ_INSERT_TAIL(&l1_lru_list, l1, l1_lru);
627
628         mtx_unlock(&l1_lru_lock);
629
630         /*
631          * Fix up the relevant bits in the pmap structure
632          */
633         pmap->pm_l1 = l1;
634         pmap->pm_domain = domain + 1;
635 }
636
637 /*
638  * Free an L1 translation table.
639  * This is called at pmap destruction time.
640  */
641 static void
642 pmap_free_l1(pmap_t pmap)
643 {
644         struct l1_ttable *l1 = pmap->pm_l1;
645
646         mtx_lock(&l1_lru_lock);
647
648         /*
649          * If this L1 is currently on the LRU list, remove it.
650          */
651         if (l1->l1_domain_use_count < PMAP_DOMAINS)
652                 TAILQ_REMOVE(&l1_lru_list, l1, l1_lru);
653
654         /*
655          * Free up the domain number which was allocated to the pmap
656          */
657         l1->l1_domain_free[pmap->pm_domain - 1] = l1->l1_domain_first;
658         l1->l1_domain_first = pmap->pm_domain - 1;
659         l1->l1_domain_use_count--;
660
661         /*
662          * The L1 now must have at least 1 free domain, so add
663          * it back to the LRU list. If the use count is zero,
664          * put it at the head of the list, otherwise it goes
665          * to the tail.
666          */
667         if (l1->l1_domain_use_count == 0) {
668                 TAILQ_INSERT_HEAD(&l1_lru_list, l1, l1_lru);
669         }       else
670                 TAILQ_INSERT_TAIL(&l1_lru_list, l1, l1_lru);
671
672         mtx_unlock(&l1_lru_lock);
673 }
674
675 /*
676  * Returns a pointer to the L2 bucket associated with the specified pmap
677  * and VA, or NULL if no L2 bucket exists for the address.
678  */
679 static PMAP_INLINE struct l2_bucket *
680 pmap_get_l2_bucket(pmap_t pmap, vm_offset_t va)
681 {
682         struct l2_dtable *l2;
683         struct l2_bucket *l2b;
684         u_short l1idx;
685
686         l1idx = L1_IDX(va);
687
688         if ((l2 = pmap->pm_l2[L2_IDX(l1idx)]) == NULL ||
689             (l2b = &l2->l2_bucket[L2_BUCKET(l1idx)])->l2b_kva == NULL)
690                 return (NULL);
691
692         return (l2b);
693 }
694
695 /*
696  * Returns a pointer to the L2 bucket associated with the specified pmap
697  * and VA.
698  *
699  * If no L2 bucket exists, perform the necessary allocations to put an L2
700  * bucket/page table in place.
701  *
702  * Note that if a new L2 bucket/page was allocated, the caller *must*
703  * increment the bucket occupancy counter appropriately *before*
704  * releasing the pmap's lock to ensure no other thread or cpu deallocates
705  * the bucket/page in the meantime.
706  */
707 static struct l2_bucket *
708 pmap_alloc_l2_bucket(pmap_t pmap, vm_offset_t va)
709 {
710         struct l2_dtable *l2;
711         struct l2_bucket *l2b;
712         u_short l1idx;
713
714         l1idx = L1_IDX(va);
715
716         PMAP_ASSERT_LOCKED(pmap);
717         rw_assert(&pvh_global_lock, RA_WLOCKED);
718         if ((l2 = pmap->pm_l2[L2_IDX(l1idx)]) == NULL) {
719                 /*
720                  * No mapping at this address, as there is
721                  * no entry in the L1 table.
722                  * Need to allocate a new l2_dtable.
723                  */
724                 PMAP_UNLOCK(pmap);
725                 rw_wunlock(&pvh_global_lock);
726                 if ((l2 = uma_zalloc(l2table_zone, M_NOWAIT)) == NULL) {
727                         rw_wlock(&pvh_global_lock);
728                         PMAP_LOCK(pmap);
729                         return (NULL);
730                 }
731                 rw_wlock(&pvh_global_lock);
732                 PMAP_LOCK(pmap);
733                 if (pmap->pm_l2[L2_IDX(l1idx)] != NULL) {
734                         /*
735                          * Someone already allocated the l2_dtable while
736                          * we were doing the same.
737                          */
738                         uma_zfree(l2table_zone, l2);
739                         l2 = pmap->pm_l2[L2_IDX(l1idx)];
740                 } else {
741                         bzero(l2, sizeof(*l2));
742                         /*
743                          * Link it into the parent pmap
744                          */
745                         pmap->pm_l2[L2_IDX(l1idx)] = l2;
746                 }
747         }
748
749         l2b = &l2->l2_bucket[L2_BUCKET(l1idx)];
750
751         /*
752          * Fetch pointer to the L2 page table associated with the address.
753          */
754         if (l2b->l2b_kva == NULL) {
755                 pt_entry_t *ptep;
756
757                 /*
758                  * No L2 page table has been allocated. Chances are, this
759                  * is because we just allocated the l2_dtable, above.
760                  */
761                 l2->l2_occupancy++;
762                 PMAP_UNLOCK(pmap);
763                 rw_wunlock(&pvh_global_lock);
764                 ptep = uma_zalloc(l2zone, M_NOWAIT);
765                 rw_wlock(&pvh_global_lock);
766                 PMAP_LOCK(pmap);
767                 if (l2b->l2b_kva != 0) {
768                         /* We lost the race. */
769                         l2->l2_occupancy--;
770                         uma_zfree(l2zone, ptep);
771                         return (l2b);
772                 }
773                 l2b->l2b_phys = vtophys(ptep);
774                 if (ptep == NULL) {
775                         /*
776                          * Oops, no more L2 page tables available at this
777                          * time. We may need to deallocate the l2_dtable
778                          * if we allocated a new one above.
779                          */
780                         l2->l2_occupancy--;
781                         if (l2->l2_occupancy == 0) {
782                                 pmap->pm_l2[L2_IDX(l1idx)] = NULL;
783                                 uma_zfree(l2table_zone, l2);
784                         }
785                         return (NULL);
786                 }
787
788                 l2b->l2b_kva = ptep;
789                 l2b->l2b_l1idx = l1idx;
790         }
791
792         return (l2b);
793 }
794
795 static PMAP_INLINE void
796 pmap_free_l2_ptp(pt_entry_t *l2)
797 {
798         uma_zfree(l2zone, l2);
799 }
800 /*
801  * One or more mappings in the specified L2 descriptor table have just been
802  * invalidated.
803  *
804  * Garbage collect the metadata and descriptor table itself if necessary.
805  *
806  * The pmap lock must be acquired when this is called (not necessary
807  * for the kernel pmap).
808  */
809 static void
810 pmap_free_l2_bucket(pmap_t pmap, struct l2_bucket *l2b, u_int count)
811 {
812         struct l2_dtable *l2;
813         pd_entry_t *pl1pd, l1pd;
814         pt_entry_t *ptep;
815         u_short l1idx;
816
817
818         /*
819          * Update the bucket's reference count according to how many
820          * PTEs the caller has just invalidated.
821          */
822         l2b->l2b_occupancy -= count;
823
824         /*
825          * Note:
826          *
827          * Level 2 page tables allocated to the kernel pmap are never freed
828          * as that would require checking all Level 1 page tables and
829          * removing any references to the Level 2 page table. See also the
830          * comment elsewhere about never freeing bootstrap L2 descriptors.
831          *
832          * We make do with just invalidating the mapping in the L2 table.
833          *
834          * This isn't really a big deal in practice and, in fact, leads
835          * to a performance win over time as we don't need to continually
836          * alloc/free.
837          */
838         if (l2b->l2b_occupancy > 0 || pmap == pmap_kernel())
839                 return;
840
841         /*
842          * There are no more valid mappings in this level 2 page table.
843          * Go ahead and NULL-out the pointer in the bucket, then
844          * free the page table.
845          */
846         l1idx = l2b->l2b_l1idx;
847         ptep = l2b->l2b_kva;
848         l2b->l2b_kva = NULL;
849
850         pl1pd = &pmap->pm_l1->l1_kva[l1idx];
851
852         /*
853          * If the L1 slot matches the pmap's domain
854          * number, then invalidate it.
855          */
856         l1pd = *pl1pd & (L1_TYPE_MASK | L1_C_DOM_MASK);
857         if (l1pd == (L1_C_DOM(pmap->pm_domain) | L1_TYPE_C)) {
858                 *pl1pd = 0;
859                 PTE_SYNC(pl1pd);
860                 cpu_tlb_flushD_SE((vm_offset_t)ptep);
861                 cpu_cpwait();
862         }
863
864         /*
865          * Release the L2 descriptor table back to the pool cache.
866          */
867         pmap_free_l2_ptp(ptep);
868
869         /*
870          * Update the reference count in the associated l2_dtable
871          */
872         l2 = pmap->pm_l2[L2_IDX(l1idx)];
873         if (--l2->l2_occupancy > 0)
874                 return;
875
876         /*
877          * There are no more valid mappings in any of the Level 1
878          * slots managed by this l2_dtable. Go ahead and NULL-out
879          * the pointer in the parent pmap and free the l2_dtable.
880          */
881         pmap->pm_l2[L2_IDX(l1idx)] = NULL;
882         uma_zfree(l2table_zone, l2);
883 }
884
885 /*
886  * Pool cache constructors for L2 descriptor tables, metadata and pmap
887  * structures.
888  */
889 static int
890 pmap_l2ptp_ctor(void *mem, int size, void *arg, int flags)
891 {
892         struct l2_bucket *l2b;
893         pt_entry_t *ptep, pte;
894         vm_offset_t va = (vm_offset_t)mem & ~PAGE_MASK;
895
896         /*
897          * The mappings for these page tables were initially made using
898          * pmap_kenter() by the pool subsystem. Therefore, the cache-
899          * mode will not be right for page table mappings. To avoid
900          * polluting the pmap_kenter() code with a special case for
901          * page tables, we simply fix up the cache-mode here if it's not
902          * correct.
903          */
904         l2b = pmap_get_l2_bucket(pmap_kernel(), va);
905         ptep = &l2b->l2b_kva[l2pte_index(va)];
906         pte = *ptep;
907
908         cpu_idcache_wbinv_range(va, PAGE_SIZE);
909         pmap_l2cache_wbinv_range(va, pte & L2_S_FRAME, PAGE_SIZE);
910         if ((pte & L2_S_CACHE_MASK) != pte_l2_s_cache_mode_pt) {
911                 /*
912                  * Page tables must have the cache-mode set to
913                  * Write-Thru.
914                  */
915                 *ptep = (pte & ~L2_S_CACHE_MASK) | pte_l2_s_cache_mode_pt;
916                 PTE_SYNC(ptep);
917                 cpu_tlb_flushD_SE(va);
918                 cpu_cpwait();
919         }
920
921         memset(mem, 0, L2_TABLE_SIZE_REAL);
922         return (0);
923 }
924
925 /*
926  * Modify pte bits for all ptes corresponding to the given physical address.
927  * We use `maskbits' rather than `clearbits' because we're always passing
928  * constants and the latter would require an extra inversion at run-time.
929  */
930 static int
931 pmap_clearbit(struct vm_page *m, u_int maskbits)
932 {
933         struct l2_bucket *l2b;
934         struct pv_entry *pv, *pve, *next_pv;
935         struct md_page *pvh;
936         pd_entry_t *pl1pd;
937         pt_entry_t *ptep, npte, opte;
938         pmap_t pmap;
939         vm_offset_t va;
940         u_int oflags;
941         int count = 0;
942
943         rw_wlock(&pvh_global_lock);
944         if ((m->flags & PG_FICTITIOUS) != 0)
945                 goto small_mappings;
946
947         pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
948         TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_list, next_pv) {
949                 va = pv->pv_va;
950                 pmap = PV_PMAP(pv);
951                 PMAP_LOCK(pmap);
952                 pl1pd = &pmap->pm_l1->l1_kva[L1_IDX(va)];
953                 KASSERT((*pl1pd & L1_TYPE_MASK) == L1_S_PROTO,
954                     ("pmap_clearbit: valid section mapping expected"));
955                 if ((maskbits & PVF_WRITE) && (pv->pv_flags & PVF_WRITE))
956                         (void)pmap_demote_section(pmap, va);
957                 else if ((maskbits & PVF_REF) && L1_S_REFERENCED(*pl1pd)) {
958                         if (pmap_demote_section(pmap, va)) {
959                                 if ((pv->pv_flags & PVF_WIRED) == 0) {
960                                         /*
961                                          * Remove the mapping to a single page
962                                          * so that a subsequent access may
963                                          * repromote. Since the underlying
964                                          * l2_bucket is fully populated, this
965                                          * removal never frees an entire
966                                          * l2_bucket.
967                                          */
968                                         va += (VM_PAGE_TO_PHYS(m) &
969                                             L1_S_OFFSET);
970                                         l2b = pmap_get_l2_bucket(pmap, va);
971                                         KASSERT(l2b != NULL,
972                                             ("pmap_clearbit: no l2 bucket for "
973                                              "va 0x%#x, pmap 0x%p", va, pmap));
974                                         ptep = &l2b->l2b_kva[l2pte_index(va)];
975                                         *ptep = 0;
976                                         PTE_SYNC(ptep);
977                                         pmap_free_l2_bucket(pmap, l2b, 1);
978                                         pve = pmap_remove_pv(m, pmap, va);
979                                         KASSERT(pve != NULL, ("pmap_clearbit: "
980                                             "no PV entry for managed mapping"));
981                                         pmap_free_pv_entry(pmap, pve);
982
983                                 }
984                         }
985                 } else if ((maskbits & PVF_MOD) && L1_S_WRITABLE(*pl1pd)) {
986                         if (pmap_demote_section(pmap, va)) {
987                                 if ((pv->pv_flags & PVF_WIRED) == 0) {
988                                         /*
989                                          * Write protect the mapping to a
990                                          * single page so that a subsequent
991                                          * write access may repromote.
992                                          */
993                                         va += (VM_PAGE_TO_PHYS(m) &
994                                             L1_S_OFFSET);
995                                         l2b = pmap_get_l2_bucket(pmap, va);
996                                         KASSERT(l2b != NULL,
997                                             ("pmap_clearbit: no l2 bucket for "
998                                              "va 0x%#x, pmap 0x%p", va, pmap));
999                                         ptep = &l2b->l2b_kva[l2pte_index(va)];
1000                                         if ((*ptep & L2_S_PROTO) != 0) {
1001                                                 pve = pmap_find_pv(&m->md,
1002                                                     pmap, va);
1003                                                 KASSERT(pve != NULL,
1004                                                     ("pmap_clearbit: no PV "
1005                                                     "entry for managed mapping"));
1006                                                 pve->pv_flags &= ~PVF_WRITE;
1007                                                 *ptep |= L2_APX;
1008                                                 PTE_SYNC(ptep);
1009                                         }
1010                                 }
1011                         }
1012                 }
1013                 PMAP_UNLOCK(pmap);
1014         }
1015
1016 small_mappings:
1017         if (TAILQ_EMPTY(&m->md.pv_list)) {
1018                 rw_wunlock(&pvh_global_lock);
1019                 return (0);
1020         }
1021
1022         /*
1023          * Loop over all current mappings setting/clearing as appropos
1024          */
1025         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
1026                 va = pv->pv_va;
1027                 pmap = PV_PMAP(pv);
1028                 oflags = pv->pv_flags;
1029                 pv->pv_flags &= ~maskbits;
1030
1031                 PMAP_LOCK(pmap);
1032
1033                 l2b = pmap_get_l2_bucket(pmap, va);
1034                 KASSERT(l2b != NULL, ("pmap_clearbit: no l2 bucket for "
1035                     "va 0x%#x, pmap 0x%p", va, pmap));
1036
1037                 ptep = &l2b->l2b_kva[l2pte_index(va)];
1038                 npte = opte = *ptep;
1039
1040                 if (maskbits & (PVF_WRITE | PVF_MOD)) {
1041                         /* make the pte read only */
1042                         npte |= L2_APX;
1043                 }
1044
1045                 if (maskbits & PVF_REF) {
1046                         /*
1047                          * Clear referenced flag in PTE so that we
1048                          * will take a flag fault the next time the mapping
1049                          * is referenced.
1050                          */
1051                         npte &= ~L2_S_REF;
1052                 }
1053
1054                 CTR4(KTR_PMAP,"clearbit: pmap:%p bits:%x pte:%x->%x",
1055                     pmap, maskbits, opte, npte);
1056                 if (npte != opte) {
1057                         count++;
1058                         *ptep = npte;
1059                         PTE_SYNC(ptep);
1060                         /* Flush the TLB entry if a current pmap. */
1061                         if (PTE_BEEN_EXECD(opte))
1062                                 cpu_tlb_flushID_SE(pv->pv_va);
1063                         else if (PTE_BEEN_REFD(opte))
1064                                 cpu_tlb_flushD_SE(pv->pv_va);
1065                         cpu_cpwait();
1066                 }
1067
1068                 PMAP_UNLOCK(pmap);
1069
1070         }
1071
1072         if (maskbits & PVF_WRITE)
1073                 vm_page_aflag_clear(m, PGA_WRITEABLE);
1074         rw_wunlock(&pvh_global_lock);
1075         return (count);
1076 }
1077
1078 /*
1079  * main pv_entry manipulation functions:
1080  *   pmap_enter_pv: enter a mapping onto a vm_page list
1081  *   pmap_remove_pv: remove a mappiing from a vm_page list
1082  *
1083  * NOTE: pmap_enter_pv expects to lock the pvh itself
1084  *       pmap_remove_pv expects the caller to lock the pvh before calling
1085  */
1086
1087 /*
1088  * pmap_enter_pv: enter a mapping onto a vm_page's PV list
1089  *
1090  * => caller should hold the proper lock on pvh_global_lock
1091  * => caller should have pmap locked
1092  * => we will (someday) gain the lock on the vm_page's PV list
1093  * => caller should adjust ptp's wire_count before calling
1094  * => caller should not adjust pmap's wire_count
1095  */
1096 static void
1097 pmap_enter_pv(struct vm_page *m, struct pv_entry *pve, pmap_t pmap,
1098     vm_offset_t va, u_int flags)
1099 {
1100
1101         rw_assert(&pvh_global_lock, RA_WLOCKED);
1102
1103         PMAP_ASSERT_LOCKED(pmap);
1104         pve->pv_va = va;
1105         pve->pv_flags = flags;
1106
1107         TAILQ_INSERT_HEAD(&m->md.pv_list, pve, pv_list);
1108         if (pve->pv_flags & PVF_WIRED)
1109                 ++pmap->pm_stats.wired_count;
1110 }
1111
1112 /*
1113  *
1114  * pmap_find_pv: Find a pv entry
1115  *
1116  * => caller should hold lock on vm_page
1117  */
1118 static PMAP_INLINE struct pv_entry *
1119 pmap_find_pv(struct md_page *md, pmap_t pmap, vm_offset_t va)
1120 {
1121         struct pv_entry *pv;
1122
1123         rw_assert(&pvh_global_lock, RA_WLOCKED);
1124         TAILQ_FOREACH(pv, &md->pv_list, pv_list)
1125                 if (pmap == PV_PMAP(pv) && va == pv->pv_va)
1126                         break;
1127
1128         return (pv);
1129 }
1130
1131 /*
1132  * vector_page_setprot:
1133  *
1134  *      Manipulate the protection of the vector page.
1135  */
1136 void
1137 vector_page_setprot(int prot)
1138 {
1139         struct l2_bucket *l2b;
1140         pt_entry_t *ptep;
1141
1142         l2b = pmap_get_l2_bucket(pmap_kernel(), vector_page);
1143
1144         ptep = &l2b->l2b_kva[l2pte_index(vector_page)];
1145         /*
1146          * Set referenced flag.
1147          * Vectors' page is always desired
1148          * to be allowed to reside in TLB.
1149          */
1150         *ptep |= L2_S_REF;
1151
1152         pmap_set_prot(ptep, prot|VM_PROT_EXECUTE, 0);
1153         PTE_SYNC(ptep);
1154         cpu_tlb_flushID_SE(vector_page);
1155         cpu_cpwait();
1156 }
1157
1158 static void
1159 pmap_set_prot(pt_entry_t *ptep, vm_prot_t prot, uint8_t user)
1160 {
1161
1162         *ptep &= ~(L2_S_PROT_MASK | L2_XN);
1163
1164         if (!(prot & VM_PROT_EXECUTE))
1165                 *ptep |= L2_XN;
1166
1167         /* Set defaults first - kernel read access */
1168         *ptep |= L2_APX;
1169         *ptep |= L2_S_PROT_R;
1170         /* Now tune APs as desired */
1171         if (user)
1172                 *ptep |= L2_S_PROT_U;
1173
1174         if (prot & VM_PROT_WRITE)
1175                 *ptep &= ~(L2_APX);
1176 }
1177
1178 /*
1179  * pmap_remove_pv: try to remove a mapping from a pv_list
1180  *
1181  * => caller should hold proper lock on pmap_main_lock
1182  * => pmap should be locked
1183  * => caller should hold lock on vm_page [so that attrs can be adjusted]
1184  * => caller should adjust ptp's wire_count and free PTP if needed
1185  * => caller should NOT adjust pmap's wire_count
1186  * => we return the removed pve
1187  */
1188 static struct pv_entry *
1189 pmap_remove_pv(struct vm_page *m, pmap_t pmap, vm_offset_t va)
1190 {
1191         struct pv_entry *pve;
1192
1193         rw_assert(&pvh_global_lock, RA_WLOCKED);
1194         PMAP_ASSERT_LOCKED(pmap);
1195
1196         pve = pmap_find_pv(&m->md, pmap, va);   /* find corresponding pve */
1197         if (pve != NULL) {
1198                 TAILQ_REMOVE(&m->md.pv_list, pve, pv_list);
1199                 if (pve->pv_flags & PVF_WIRED)
1200                         --pmap->pm_stats.wired_count;
1201         }
1202         if (TAILQ_EMPTY(&m->md.pv_list))
1203                 vm_page_aflag_clear(m, PGA_WRITEABLE);
1204
1205         return(pve);                            /* return removed pve */
1206 }
1207
1208 /*
1209  *
1210  * pmap_modify_pv: Update pv flags
1211  *
1212  * => caller should hold lock on vm_page [so that attrs can be adjusted]
1213  * => caller should NOT adjust pmap's wire_count
1214  * => we return the old flags
1215  *
1216  * Modify a physical-virtual mapping in the pv table
1217  */
1218 static u_int
1219 pmap_modify_pv(struct vm_page *m, pmap_t pmap, vm_offset_t va,
1220     u_int clr_mask, u_int set_mask)
1221 {
1222         struct pv_entry *npv;
1223         u_int flags, oflags;
1224
1225         PMAP_ASSERT_LOCKED(pmap);
1226         rw_assert(&pvh_global_lock, RA_WLOCKED);
1227         if ((npv = pmap_find_pv(&m->md, pmap, va)) == NULL)
1228                 return (0);
1229
1230         /*
1231          * There is at least one VA mapping this page.
1232          */
1233         oflags = npv->pv_flags;
1234         npv->pv_flags = flags = (oflags & ~clr_mask) | set_mask;
1235
1236         if ((flags ^ oflags) & PVF_WIRED) {
1237                 if (flags & PVF_WIRED)
1238                         ++pmap->pm_stats.wired_count;
1239                 else
1240                         --pmap->pm_stats.wired_count;
1241         }
1242
1243         return (oflags);
1244 }
1245
1246 /* Function to set the debug level of the pmap code */
1247 #ifdef PMAP_DEBUG
1248 void
1249 pmap_debug(int level)
1250 {
1251         pmap_debug_level = level;
1252         dprintf("pmap_debug: level=%d\n", pmap_debug_level);
1253 }
1254 #endif  /* PMAP_DEBUG */
1255
1256 void
1257 pmap_pinit0(struct pmap *pmap)
1258 {
1259         PDEBUG(1, printf("pmap_pinit0: pmap = %08x\n", (u_int32_t) pmap));
1260
1261         bcopy(kernel_pmap, pmap, sizeof(*pmap));
1262         bzero(&pmap->pm_mtx, sizeof(pmap->pm_mtx));
1263         PMAP_LOCK_INIT(pmap);
1264         TAILQ_INIT(&pmap->pm_pvchunk);
1265 }
1266
1267 /*
1268  *      Initialize a vm_page's machine-dependent fields.
1269  */
1270 void
1271 pmap_page_init(vm_page_t m)
1272 {
1273
1274         TAILQ_INIT(&m->md.pv_list);
1275         m->md.pv_memattr = VM_MEMATTR_DEFAULT;
1276 }
1277
1278 static vm_offset_t
1279 pmap_ptelist_alloc(vm_offset_t *head)
1280 {
1281         pt_entry_t *pte;
1282         vm_offset_t va;
1283
1284         va = *head;
1285         if (va == 0)
1286                 return (va);    /* Out of memory */
1287         pte = vtopte(va);
1288         *head = *pte;
1289         if ((*head & L2_TYPE_MASK) != L2_TYPE_INV)
1290                 panic("%s: va is not L2_TYPE_INV!", __func__);
1291         *pte = 0;
1292         return (va);
1293 }
1294
1295 static void
1296 pmap_ptelist_free(vm_offset_t *head, vm_offset_t va)
1297 {
1298         pt_entry_t *pte;
1299
1300         if ((va & L2_TYPE_MASK) != L2_TYPE_INV)
1301                 panic("%s: freeing va that is not L2_TYPE INV!", __func__);
1302         pte = vtopte(va);
1303         *pte = *head;           /* virtual! L2_TYPE is L2_TYPE_INV though */
1304         *head = va;
1305 }
1306
1307 static void
1308 pmap_ptelist_init(vm_offset_t *head, void *base, int npages)
1309 {
1310         int i;
1311         vm_offset_t va;
1312
1313         *head = 0;
1314         for (i = npages - 1; i >= 0; i--) {
1315                 va = (vm_offset_t)base + i * PAGE_SIZE;
1316                 pmap_ptelist_free(head, va);
1317         }
1318 }
1319
1320 /*
1321  *      Initialize the pmap module.
1322  *      Called by vm_init, to initialize any structures that the pmap
1323  *      system needs to map virtual memory.
1324  */
1325 void
1326 pmap_init(void)
1327 {
1328         vm_size_t s;
1329         int i, pv_npg;
1330
1331         l2zone = uma_zcreate("L2 Table", L2_TABLE_SIZE_REAL, pmap_l2ptp_ctor,
1332             NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_VM | UMA_ZONE_NOFREE);
1333         l2table_zone = uma_zcreate("L2 Table", sizeof(struct l2_dtable), NULL,
1334             NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_VM | UMA_ZONE_NOFREE);
1335
1336         /*
1337          * Are large page mappings supported and enabled?
1338          */
1339         TUNABLE_INT_FETCH("vm.pmap.sp_enabled", &sp_enabled);
1340         if (sp_enabled) {
1341                 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1342                     ("pmap_init: can't assign to pagesizes[1]"));
1343                 pagesizes[1] = NBPDR;
1344         }
1345
1346         /*
1347          * Calculate the size of the pv head table for superpages.
1348          * Handle the possibility that "vm_phys_segs[...].end" is zero.
1349          */
1350         pv_npg = trunc_1mpage(vm_phys_segs[vm_phys_nsegs - 1].end -
1351             PAGE_SIZE) / NBPDR + 1;
1352
1353         /*
1354          * Allocate memory for the pv head table for superpages.
1355          */
1356         s = (vm_size_t)(pv_npg * sizeof(struct md_page));
1357         s = round_page(s);
1358         pv_table = (struct md_page *)kmem_malloc(kernel_arena, s,
1359             M_WAITOK | M_ZERO);
1360         for (i = 0; i < pv_npg; i++)
1361                 TAILQ_INIT(&pv_table[i].pv_list);
1362
1363         /*
1364          * Initialize the address space for the pv chunks.
1365          */
1366
1367         TUNABLE_INT_FETCH("vm.pmap.shpgperproc", &shpgperproc);
1368         pv_entry_max = shpgperproc * maxproc + vm_cnt.v_page_count;
1369         TUNABLE_INT_FETCH("vm.pmap.pv_entries", &pv_entry_max);
1370         pv_entry_max = roundup(pv_entry_max, _NPCPV);
1371         pv_entry_high_water = 9 * (pv_entry_max / 10);
1372
1373         pv_maxchunks = MAX(pv_entry_max / _NPCPV, maxproc);
1374         pv_chunkbase = (struct pv_chunk *)kva_alloc(PAGE_SIZE * pv_maxchunks);
1375
1376         if (pv_chunkbase == NULL)
1377                 panic("pmap_init: not enough kvm for pv chunks");
1378
1379         pmap_ptelist_init(&pv_vafree, pv_chunkbase, pv_maxchunks);
1380
1381         /*
1382          * Now it is safe to enable pv_table recording.
1383          */
1384         PDEBUG(1, printf("pmap_init: done!\n"));
1385 }
1386
1387 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_max, CTLFLAG_RD, &pv_entry_max, 0,
1388         "Max number of PV entries");
1389 SYSCTL_INT(_vm_pmap, OID_AUTO, shpgperproc, CTLFLAG_RD, &shpgperproc, 0,
1390         "Page share factor per proc");
1391
1392 static SYSCTL_NODE(_vm_pmap, OID_AUTO, section, CTLFLAG_RD, 0,
1393     "1MB page mapping counters");
1394
1395 static u_long pmap_section_demotions;
1396 SYSCTL_ULONG(_vm_pmap_section, OID_AUTO, demotions, CTLFLAG_RD,
1397     &pmap_section_demotions, 0, "1MB page demotions");
1398
1399 static u_long pmap_section_mappings;
1400 SYSCTL_ULONG(_vm_pmap_section, OID_AUTO, mappings, CTLFLAG_RD,
1401     &pmap_section_mappings, 0, "1MB page mappings");
1402
1403 static u_long pmap_section_p_failures;
1404 SYSCTL_ULONG(_vm_pmap_section, OID_AUTO, p_failures, CTLFLAG_RD,
1405     &pmap_section_p_failures, 0, "1MB page promotion failures");
1406
1407 static u_long pmap_section_promotions;
1408 SYSCTL_ULONG(_vm_pmap_section, OID_AUTO, promotions, CTLFLAG_RD,
1409     &pmap_section_promotions, 0, "1MB page promotions");
1410
1411 int
1412 pmap_fault_fixup(pmap_t pmap, vm_offset_t va, vm_prot_t ftype, int user)
1413 {
1414         struct l2_dtable *l2;
1415         struct l2_bucket *l2b;
1416         pd_entry_t *pl1pd, l1pd;
1417         pt_entry_t *ptep, pte;
1418         vm_paddr_t pa;
1419         u_int l1idx;
1420         int rv = 0;
1421
1422         l1idx = L1_IDX(va);
1423         rw_wlock(&pvh_global_lock);
1424         PMAP_LOCK(pmap);
1425         /*
1426          * Check and possibly fix-up L1 section mapping
1427          * only when superpage mappings are enabled to speed up.
1428          */
1429         if (sp_enabled) {
1430                 pl1pd = &pmap->pm_l1->l1_kva[l1idx];
1431                 l1pd = *pl1pd;
1432                 if ((l1pd & L1_TYPE_MASK) == L1_S_PROTO) {
1433                         /* Catch an access to the vectors section */
1434                         if (l1idx == L1_IDX(vector_page))
1435                                 goto out;
1436                         /*
1437                          * Stay away from the kernel mappings.
1438                          * None of them should fault from L1 entry.
1439                          */
1440                         if (pmap == pmap_kernel())
1441                                 goto out;
1442                         /*
1443                          * Catch a forbidden userland access
1444                          */
1445                         if (user && !(l1pd & L1_S_PROT_U))
1446                                 goto out;
1447                         /*
1448                          * Superpage is always either mapped read only
1449                          * or it is modified and permitted to be written
1450                          * by default. Therefore, process only reference
1451                          * flag fault and demote page in case of write fault.
1452                          */
1453                         if ((ftype & VM_PROT_WRITE) && !L1_S_WRITABLE(l1pd) &&
1454                             L1_S_REFERENCED(l1pd)) {
1455                                 (void)pmap_demote_section(pmap, va);
1456                                 goto out;
1457                         } else if (!L1_S_REFERENCED(l1pd)) {
1458                                 /* Mark the page "referenced" */
1459                                 *pl1pd = l1pd | L1_S_REF;
1460                                 PTE_SYNC(pl1pd);
1461                                 goto l1_section_out;
1462                         } else
1463                                 goto out;
1464                 }
1465         }
1466         /*
1467          * If there is no l2_dtable for this address, then the process
1468          * has no business accessing it.
1469          *
1470          * Note: This will catch userland processes trying to access
1471          * kernel addresses.
1472          */
1473         l2 = pmap->pm_l2[L2_IDX(l1idx)];
1474         if (l2 == NULL)
1475                 goto out;
1476
1477         /*
1478          * Likewise if there is no L2 descriptor table
1479          */
1480         l2b = &l2->l2_bucket[L2_BUCKET(l1idx)];
1481         if (l2b->l2b_kva == NULL)
1482                 goto out;
1483
1484         /*
1485          * Check the PTE itself.
1486          */
1487         ptep = &l2b->l2b_kva[l2pte_index(va)];
1488         pte = *ptep;
1489         if (pte == 0)
1490                 goto out;
1491
1492         /*
1493          * Catch a userland access to the vector page mapped at 0x0
1494          */
1495         if (user && !(pte & L2_S_PROT_U))
1496                 goto out;
1497         if (va == vector_page)
1498                 goto out;
1499
1500         pa = l2pte_pa(pte);
1501         CTR5(KTR_PMAP, "pmap_fault_fix: pmap:%p va:%x pte:0x%x ftype:%x user:%x",
1502             pmap, va, pte, ftype, user);
1503         if ((ftype & VM_PROT_WRITE) && !(L2_S_WRITABLE(pte)) &&
1504             L2_S_REFERENCED(pte)) {
1505                 /*
1506                  * This looks like a good candidate for "page modified"
1507                  * emulation...
1508                  */
1509                 struct pv_entry *pv;
1510                 struct vm_page *m;
1511
1512                 /* Extract the physical address of the page */
1513                 if ((m = PHYS_TO_VM_PAGE(pa)) == NULL) {
1514                         goto out;
1515                 }
1516                 /* Get the current flags for this page. */
1517
1518                 pv = pmap_find_pv(&m->md, pmap, va);
1519                 if (pv == NULL) {
1520                         goto out;
1521                 }
1522
1523                 /*
1524                  * Do the flags say this page is writable? If not then it
1525                  * is a genuine write fault. If yes then the write fault is
1526                  * our fault as we did not reflect the write access in the
1527                  * PTE. Now we know a write has occurred we can correct this
1528                  * and also set the modified bit
1529                  */
1530                 if ((pv->pv_flags & PVF_WRITE) == 0) {
1531                         goto out;
1532                 }
1533
1534                 vm_page_dirty(m);
1535
1536                 /* Re-enable write permissions for the page */
1537                 *ptep = (pte & ~L2_APX);
1538                 PTE_SYNC(ptep);
1539                 rv = 1;
1540                 CTR1(KTR_PMAP, "pmap_fault_fix: new pte:0x%x", *ptep);
1541         } else if (!L2_S_REFERENCED(pte)) {
1542                 /*
1543                  * This looks like a good candidate for "page referenced"
1544                  * emulation.
1545                  */
1546                 struct pv_entry *pv;
1547                 struct vm_page *m;
1548
1549                 /* Extract the physical address of the page */
1550                 if ((m = PHYS_TO_VM_PAGE(pa)) == NULL)
1551                         goto out;
1552                 /* Get the current flags for this page. */
1553                 pv = pmap_find_pv(&m->md, pmap, va);
1554                 if (pv == NULL)
1555                         goto out;
1556
1557                 vm_page_aflag_set(m, PGA_REFERENCED);
1558
1559                 /* Mark the page "referenced" */
1560                 *ptep = pte | L2_S_REF;
1561                 PTE_SYNC(ptep);
1562                 rv = 1;
1563                 CTR1(KTR_PMAP, "pmap_fault_fix: new pte:0x%x", *ptep);
1564         }
1565
1566         /*
1567          * We know there is a valid mapping here, so simply
1568          * fix up the L1 if necessary.
1569          */
1570         pl1pd = &pmap->pm_l1->l1_kva[l1idx];
1571         l1pd = l2b->l2b_phys | L1_C_DOM(pmap->pm_domain) | L1_C_PROTO;
1572         if (*pl1pd != l1pd) {
1573                 *pl1pd = l1pd;
1574                 PTE_SYNC(pl1pd);
1575                 rv = 1;
1576         }
1577
1578 #ifdef DEBUG
1579         /*
1580          * If 'rv == 0' at this point, it generally indicates that there is a
1581          * stale TLB entry for the faulting address. This happens when two or
1582          * more processes are sharing an L1. Since we don't flush the TLB on
1583          * a context switch between such processes, we can take domain faults
1584          * for mappings which exist at the same VA in both processes. EVEN IF
1585          * WE'VE RECENTLY FIXED UP THE CORRESPONDING L1 in pmap_enter(), for
1586          * example.
1587          *
1588          * This is extremely likely to happen if pmap_enter() updated the L1
1589          * entry for a recently entered mapping. In this case, the TLB is
1590          * flushed for the new mapping, but there may still be TLB entries for
1591          * other mappings belonging to other processes in the 1MB range
1592          * covered by the L1 entry.
1593          *
1594          * Since 'rv == 0', we know that the L1 already contains the correct
1595          * value, so the fault must be due to a stale TLB entry.
1596          *
1597          * Since we always need to flush the TLB anyway in the case where we
1598          * fixed up the L1, or frobbed the L2 PTE, we effectively deal with
1599          * stale TLB entries dynamically.
1600          *
1601          * However, the above condition can ONLY happen if the current L1 is
1602          * being shared. If it happens when the L1 is unshared, it indicates
1603          * that other parts of the pmap are not doing their job WRT managing
1604          * the TLB.
1605          */
1606         if (rv == 0 && pmap->pm_l1->l1_domain_use_count == 1) {
1607                 printf("fixup: pmap %p, va 0x%08x, ftype %d - nothing to do!\n",
1608                     pmap, va, ftype);
1609                 printf("fixup: l2 %p, l2b %p, ptep %p, pl1pd %p\n",
1610                     l2, l2b, ptep, pl1pd);
1611                 printf("fixup: pte 0x%x, l1pd 0x%x, last code 0x%x\n",
1612                     pte, l1pd, last_fault_code);
1613 #ifdef DDB
1614                 Debugger();
1615 #endif
1616         }
1617 #endif
1618
1619 l1_section_out:
1620         cpu_tlb_flushID_SE(va);
1621         cpu_cpwait();
1622
1623         rv = 1;
1624
1625 out:
1626         rw_wunlock(&pvh_global_lock);
1627         PMAP_UNLOCK(pmap);
1628         return (rv);
1629 }
1630
1631 void
1632 pmap_postinit(void)
1633 {
1634         struct l2_bucket *l2b;
1635         struct l1_ttable *l1;
1636         pd_entry_t *pl1pt;
1637         pt_entry_t *ptep, pte;
1638         vm_offset_t va, eva;
1639         u_int loop, needed;
1640
1641         needed = (maxproc / PMAP_DOMAINS) + ((maxproc % PMAP_DOMAINS) ? 1 : 0);
1642         needed -= 1;
1643         l1 = malloc(sizeof(*l1) * needed, M_VMPMAP, M_WAITOK);
1644
1645         for (loop = 0; loop < needed; loop++, l1++) {
1646                 /* Allocate a L1 page table */
1647                 va = (vm_offset_t)contigmalloc(L1_TABLE_SIZE, M_VMPMAP, 0, 0x0,
1648                     0xffffffff, L1_TABLE_SIZE, 0);
1649
1650                 if (va == 0)
1651                         panic("Cannot allocate L1 KVM");
1652
1653                 eva = va + L1_TABLE_SIZE;
1654                 pl1pt = (pd_entry_t *)va;
1655
1656                 while (va < eva) {
1657                                 l2b = pmap_get_l2_bucket(pmap_kernel(), va);
1658                                 ptep = &l2b->l2b_kva[l2pte_index(va)];
1659                                 pte = *ptep;
1660                                 pte = (pte & ~L2_S_CACHE_MASK) | pte_l2_s_cache_mode_pt;
1661                                 *ptep = pte;
1662                                 PTE_SYNC(ptep);
1663                                 cpu_tlb_flushID_SE(va);
1664                                 cpu_cpwait();
1665                                 va += PAGE_SIZE;
1666                 }
1667                 pmap_init_l1(l1, pl1pt);
1668         }
1669 #ifdef DEBUG
1670         printf("pmap_postinit: Allocated %d static L1 descriptor tables\n",
1671             needed);
1672 #endif
1673 }
1674
1675 /*
1676  * This is used to stuff certain critical values into the PCB where they
1677  * can be accessed quickly from cpu_switch() et al.
1678  */
1679 void
1680 pmap_set_pcb_pagedir(pmap_t pmap, struct pcb *pcb)
1681 {
1682         struct l2_bucket *l2b;
1683
1684         pcb->pcb_pagedir = pmap->pm_l1->l1_physaddr;
1685         pcb->pcb_dacr = (DOMAIN_CLIENT << (PMAP_DOMAIN_KERNEL * 2)) |
1686             (DOMAIN_CLIENT << (pmap->pm_domain * 2));
1687
1688         if (vector_page < KERNBASE) {
1689                 pcb->pcb_pl1vec = &pmap->pm_l1->l1_kva[L1_IDX(vector_page)];
1690                 l2b = pmap_get_l2_bucket(pmap, vector_page);
1691                 pcb->pcb_l1vec = l2b->l2b_phys | L1_C_PROTO |
1692                     L1_C_DOM(pmap->pm_domain) | L1_C_DOM(PMAP_DOMAIN_KERNEL);
1693         } else
1694                 pcb->pcb_pl1vec = NULL;
1695 }
1696
1697 void
1698 pmap_activate(struct thread *td)
1699 {
1700         pmap_t pmap;
1701         struct pcb *pcb;
1702
1703         pmap = vmspace_pmap(td->td_proc->p_vmspace);
1704         pcb = td->td_pcb;
1705
1706         critical_enter();
1707         pmap_set_pcb_pagedir(pmap, pcb);
1708
1709         if (td == curthread) {
1710                 u_int cur_dacr, cur_ttb;
1711
1712                 __asm __volatile("mrc p15, 0, %0, c2, c0, 0" : "=r"(cur_ttb));
1713                 __asm __volatile("mrc p15, 0, %0, c3, c0, 0" : "=r"(cur_dacr));
1714
1715                 cur_ttb &= ~(L1_TABLE_SIZE - 1);
1716
1717                 if (cur_ttb == (u_int)pcb->pcb_pagedir &&
1718                     cur_dacr == pcb->pcb_dacr) {
1719                         /*
1720                          * No need to switch address spaces.
1721                          */
1722                         critical_exit();
1723                         return;
1724                 }
1725
1726
1727                 /*
1728                  * We MUST, I repeat, MUST fix up the L1 entry corresponding
1729                  * to 'vector_page' in the incoming L1 table before switching
1730                  * to it otherwise subsequent interrupts/exceptions (including
1731                  * domain faults!) will jump into hyperspace.
1732                  */
1733                 if (pcb->pcb_pl1vec) {
1734                         *pcb->pcb_pl1vec = pcb->pcb_l1vec;
1735                 }
1736
1737                 cpu_domains(pcb->pcb_dacr);
1738                 cpu_setttb(pcb->pcb_pagedir);
1739         }
1740         critical_exit();
1741 }
1742
1743 static int
1744 pmap_set_pt_cache_mode(pd_entry_t *kl1, vm_offset_t va)
1745 {
1746         pd_entry_t *pdep, pde;
1747         pt_entry_t *ptep, pte;
1748         vm_offset_t pa;
1749         int rv = 0;
1750
1751         /*
1752          * Make sure the descriptor itself has the correct cache mode
1753          */
1754         pdep = &kl1[L1_IDX(va)];
1755         pde = *pdep;
1756
1757         if (l1pte_section_p(pde)) {
1758                 if ((pde & L1_S_CACHE_MASK) != pte_l1_s_cache_mode_pt) {
1759                         *pdep = (pde & ~L1_S_CACHE_MASK) |
1760                             pte_l1_s_cache_mode_pt;
1761                         PTE_SYNC(pdep);
1762                         rv = 1;
1763                 }
1764         } else {
1765                 pa = (vm_paddr_t)(pde & L1_C_ADDR_MASK);
1766                 ptep = (pt_entry_t *)kernel_pt_lookup(pa);
1767                 if (ptep == NULL)
1768                         panic("pmap_bootstrap: No L2 for L2 @ va %p\n", ptep);
1769
1770                 ptep = &ptep[l2pte_index(va)];
1771                 pte = *ptep;
1772                 if ((pte & L2_S_CACHE_MASK) != pte_l2_s_cache_mode_pt) {
1773                         *ptep = (pte & ~L2_S_CACHE_MASK) |
1774                             pte_l2_s_cache_mode_pt;
1775                         PTE_SYNC(ptep);
1776                         rv = 1;
1777                 }
1778         }
1779
1780         return (rv);
1781 }
1782
1783 static void
1784 pmap_alloc_specials(vm_offset_t *availp, int pages, vm_offset_t *vap,
1785     pt_entry_t **ptep)
1786 {
1787         vm_offset_t va = *availp;
1788         struct l2_bucket *l2b;
1789
1790         if (ptep) {
1791                 l2b = pmap_get_l2_bucket(pmap_kernel(), va);
1792                 if (l2b == NULL)
1793                         panic("pmap_alloc_specials: no l2b for 0x%x", va);
1794
1795                 *ptep = &l2b->l2b_kva[l2pte_index(va)];
1796         }
1797
1798         *vap = va;
1799         *availp = va + (PAGE_SIZE * pages);
1800 }
1801
1802 /*
1803  *      Bootstrap the system enough to run with virtual memory.
1804  *
1805  *      On the arm this is called after mapping has already been enabled
1806  *      and just syncs the pmap module with what has already been done.
1807  *      [We can't call it easily with mapping off since the kernel is not
1808  *      mapped with PA == VA, hence we would have to relocate every address
1809  *      from the linked base (virtual) address "KERNBASE" to the actual
1810  *      (physical) address starting relative to 0]
1811  */
1812 #define PMAP_STATIC_L2_SIZE 16
1813
1814 void
1815 pmap_bootstrap(vm_offset_t firstaddr, struct pv_addr *l1pt)
1816 {
1817         static struct l1_ttable static_l1;
1818         static struct l2_dtable static_l2[PMAP_STATIC_L2_SIZE];
1819         struct l1_ttable *l1 = &static_l1;
1820         struct l2_dtable *l2;
1821         struct l2_bucket *l2b;
1822         struct czpages *czp;
1823         pd_entry_t pde;
1824         pd_entry_t *kernel_l1pt = (pd_entry_t *)l1pt->pv_va;
1825         pt_entry_t *ptep;
1826         vm_paddr_t pa;
1827         vm_offset_t va;
1828         vm_size_t size;
1829         int i, l1idx, l2idx, l2next = 0;
1830
1831         PDEBUG(1, printf("firstaddr = %08x, lastaddr = %08x\n",
1832             firstaddr, vm_max_kernel_address));
1833
1834         virtual_avail = firstaddr;
1835         kernel_pmap->pm_l1 = l1;
1836         kernel_l1pa = l1pt->pv_pa;
1837
1838         /*
1839          * Scan the L1 translation table created by initarm() and create
1840          * the required metadata for all valid mappings found in it.
1841          */
1842         for (l1idx = 0; l1idx < (L1_TABLE_SIZE / sizeof(pd_entry_t)); l1idx++) {
1843                 pde = kernel_l1pt[l1idx];
1844
1845                 /*
1846                  * We're only interested in Coarse mappings.
1847                  * pmap_extract() can deal with section mappings without
1848                  * recourse to checking L2 metadata.
1849                  */
1850                 if ((pde & L1_TYPE_MASK) != L1_TYPE_C)
1851                         continue;
1852
1853                 /*
1854                  * Lookup the KVA of this L2 descriptor table
1855                  */
1856                 pa = (vm_paddr_t)(pde & L1_C_ADDR_MASK);
1857                 ptep = (pt_entry_t *)kernel_pt_lookup(pa);
1858
1859                 if (ptep == NULL) {
1860                         panic("pmap_bootstrap: No L2 for va 0x%x, pa 0x%lx",
1861                             (u_int)l1idx << L1_S_SHIFT, (long unsigned int)pa);
1862                 }
1863
1864                 /*
1865                  * Fetch the associated L2 metadata structure.
1866                  * Allocate a new one if necessary.
1867                  */
1868                 if ((l2 = kernel_pmap->pm_l2[L2_IDX(l1idx)]) == NULL) {
1869                         if (l2next == PMAP_STATIC_L2_SIZE)
1870                                 panic("pmap_bootstrap: out of static L2s");
1871                         kernel_pmap->pm_l2[L2_IDX(l1idx)] = l2 =
1872                             &static_l2[l2next++];
1873                 }
1874
1875                 /*
1876                  * One more L1 slot tracked...
1877                  */
1878                 l2->l2_occupancy++;
1879
1880                 /*
1881                  * Fill in the details of the L2 descriptor in the
1882                  * appropriate bucket.
1883                  */
1884                 l2b = &l2->l2_bucket[L2_BUCKET(l1idx)];
1885                 l2b->l2b_kva = ptep;
1886                 l2b->l2b_phys = pa;
1887                 l2b->l2b_l1idx = l1idx;
1888
1889                 /*
1890                  * Establish an initial occupancy count for this descriptor
1891                  */
1892                 for (l2idx = 0;
1893                     l2idx < (L2_TABLE_SIZE_REAL / sizeof(pt_entry_t));
1894                     l2idx++) {
1895                         if ((ptep[l2idx] & L2_TYPE_MASK) != L2_TYPE_INV) {
1896                                 l2b->l2b_occupancy++;
1897                         }
1898                 }
1899
1900                 /*
1901                  * Make sure the descriptor itself has the correct cache mode.
1902                  * If not, fix it, but whine about the problem. Port-meisters
1903                  * should consider this a clue to fix up their initarm()
1904                  * function. :)
1905                  */
1906                 if (pmap_set_pt_cache_mode(kernel_l1pt, (vm_offset_t)ptep)) {
1907                         printf("pmap_bootstrap: WARNING! wrong cache mode for "
1908                             "L2 pte @ %p\n", ptep);
1909                 }
1910         }
1911
1912
1913         /*
1914          * Ensure the primary (kernel) L1 has the correct cache mode for
1915          * a page table. Bitch if it is not correctly set.
1916          */
1917         for (va = (vm_offset_t)kernel_l1pt;
1918             va < ((vm_offset_t)kernel_l1pt + L1_TABLE_SIZE); va += PAGE_SIZE) {
1919                 if (pmap_set_pt_cache_mode(kernel_l1pt, va))
1920                         printf("pmap_bootstrap: WARNING! wrong cache mode for "
1921                             "primary L1 @ 0x%x\n", va);
1922         }
1923
1924         cpu_dcache_wbinv_all();
1925         cpu_l2cache_wbinv_all();
1926         cpu_tlb_flushID();
1927         cpu_cpwait();
1928
1929         PMAP_LOCK_INIT(kernel_pmap);
1930         CPU_FILL(&kernel_pmap->pm_active);
1931         kernel_pmap->pm_domain = PMAP_DOMAIN_KERNEL;
1932         TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1933
1934         /*
1935          * Initialize the global pv list lock.
1936          */
1937         rw_init(&pvh_global_lock, "pmap pv global");
1938
1939         /*
1940          * Reserve some special page table entries/VA space for temporary
1941          * mapping of pages that are being copied or zeroed.
1942          */
1943         for (czp = cpu_czpages, i = 0; i < MAXCPU; ++i, ++czp) {
1944                 mtx_init(&czp->lock, "czpages", NULL, MTX_DEF);
1945                 pmap_alloc_specials(&virtual_avail, 1, &czp->srcva, &czp->srcptep);
1946                 pmap_set_pt_cache_mode(kernel_l1pt, (vm_offset_t)czp->srcptep);
1947                 pmap_alloc_specials(&virtual_avail, 1, &czp->dstva, &czp->dstptep);
1948                 pmap_set_pt_cache_mode(kernel_l1pt, (vm_offset_t)czp->dstptep);
1949         }
1950
1951         size = ((vm_max_kernel_address - pmap_curmaxkvaddr) + L1_S_OFFSET) /
1952             L1_S_SIZE;
1953         pmap_alloc_specials(&virtual_avail,
1954             round_page(size * L2_TABLE_SIZE_REAL) / PAGE_SIZE,
1955             &pmap_kernel_l2ptp_kva, NULL);
1956
1957         size = (size + (L2_BUCKET_SIZE - 1)) / L2_BUCKET_SIZE;
1958         pmap_alloc_specials(&virtual_avail,
1959             round_page(size * sizeof(struct l2_dtable)) / PAGE_SIZE,
1960             &pmap_kernel_l2dtable_kva, NULL);
1961
1962         pmap_alloc_specials(&virtual_avail,
1963             1, (vm_offset_t*)&_tmppt, NULL);
1964         pmap_alloc_specials(&virtual_avail,
1965             MAXDUMPPGS, (vm_offset_t *)&crashdumpmap, NULL);
1966         SLIST_INIT(&l1_list);
1967         TAILQ_INIT(&l1_lru_list);
1968         mtx_init(&l1_lru_lock, "l1 list lock", NULL, MTX_DEF);
1969         pmap_init_l1(l1, kernel_l1pt);
1970         cpu_dcache_wbinv_all();
1971         cpu_l2cache_wbinv_all();
1972         cpu_tlb_flushID();
1973         cpu_cpwait();
1974
1975         virtual_avail = round_page(virtual_avail);
1976         virtual_end = vm_max_kernel_address;
1977         kernel_vm_end = pmap_curmaxkvaddr;
1978
1979         pmap_set_pcb_pagedir(kernel_pmap, thread0.td_pcb);
1980 }
1981
1982
1983 /***************************************************
1984  * Pmap allocation/deallocation routines.
1985  ***************************************************/
1986
1987 /*
1988  * Release any resources held by the given physical map.
1989  * Called when a pmap initialized by pmap_pinit is being released.
1990  * Should only be called if the map contains no valid mappings.
1991  */
1992 void
1993 pmap_release(pmap_t pmap)
1994 {
1995         struct pcb *pcb;
1996
1997         cpu_tlb_flushID();
1998         cpu_cpwait();
1999         if (vector_page < KERNBASE) {
2000                 struct pcb *curpcb = PCPU_GET(curpcb);
2001                 pcb = thread0.td_pcb;
2002                 if (pmap_is_current(pmap)) {
2003                         /*
2004                          * Frob the L1 entry corresponding to the vector
2005                          * page so that it contains the kernel pmap's domain
2006                          * number. This will ensure pmap_remove() does not
2007                          * pull the current vector page out from under us.
2008                          */
2009                         critical_enter();
2010                         *pcb->pcb_pl1vec = pcb->pcb_l1vec;
2011                         cpu_domains(pcb->pcb_dacr);
2012                         cpu_setttb(pcb->pcb_pagedir);
2013                         critical_exit();
2014                 }
2015                 pmap_remove(pmap, vector_page, vector_page + PAGE_SIZE);
2016                 /*
2017                  * Make sure cpu_switch(), et al, DTRT. This is safe to do
2018                  * since this process has no remaining mappings of its own.
2019                  */
2020                 curpcb->pcb_pl1vec = pcb->pcb_pl1vec;
2021                 curpcb->pcb_l1vec = pcb->pcb_l1vec;
2022                 curpcb->pcb_dacr = pcb->pcb_dacr;
2023                 curpcb->pcb_pagedir = pcb->pcb_pagedir;
2024
2025         }
2026         pmap_free_l1(pmap);
2027
2028         dprintf("pmap_release()\n");
2029 }
2030
2031
2032
2033 /*
2034  * Helper function for pmap_grow_l2_bucket()
2035  */
2036 static __inline int
2037 pmap_grow_map(vm_offset_t va, pt_entry_t cache_mode, vm_paddr_t *pap)
2038 {
2039         struct l2_bucket *l2b;
2040         pt_entry_t *ptep;
2041         vm_paddr_t pa;
2042         struct vm_page *m;
2043
2044         m = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ | VM_ALLOC_WIRED);
2045         if (m == NULL)
2046                 return (1);
2047         pa = VM_PAGE_TO_PHYS(m);
2048
2049         if (pap)
2050                 *pap = pa;
2051
2052         l2b = pmap_get_l2_bucket(pmap_kernel(), va);
2053
2054         ptep = &l2b->l2b_kva[l2pte_index(va)];
2055         *ptep = L2_S_PROTO | pa | cache_mode | L2_S_REF;
2056         pmap_set_prot(ptep, VM_PROT_READ | VM_PROT_WRITE, 0);
2057         PTE_SYNC(ptep);
2058         cpu_tlb_flushD_SE(va);
2059         cpu_cpwait();
2060
2061         return (0);
2062 }
2063
2064 /*
2065  * This is the same as pmap_alloc_l2_bucket(), except that it is only
2066  * used by pmap_growkernel().
2067  */
2068 static __inline struct l2_bucket *
2069 pmap_grow_l2_bucket(pmap_t pmap, vm_offset_t va)
2070 {
2071         struct l2_dtable *l2;
2072         struct l2_bucket *l2b;
2073         struct l1_ttable *l1;
2074         pd_entry_t *pl1pd;
2075         u_short l1idx;
2076         vm_offset_t nva;
2077
2078         l1idx = L1_IDX(va);
2079
2080         if ((l2 = pmap->pm_l2[L2_IDX(l1idx)]) == NULL) {
2081                 /*
2082                  * No mapping at this address, as there is
2083                  * no entry in the L1 table.
2084                  * Need to allocate a new l2_dtable.
2085                  */
2086                 nva = pmap_kernel_l2dtable_kva;
2087                 if ((nva & PAGE_MASK) == 0) {
2088                         /*
2089                          * Need to allocate a backing page
2090                          */
2091                         if (pmap_grow_map(nva, pte_l2_s_cache_mode, NULL))
2092                                 return (NULL);
2093                 }
2094
2095                 l2 = (struct l2_dtable *)nva;
2096                 nva += sizeof(struct l2_dtable);
2097
2098                 if ((nva & PAGE_MASK) < (pmap_kernel_l2dtable_kva &
2099                     PAGE_MASK)) {
2100                         /*
2101                          * The new l2_dtable straddles a page boundary.
2102                          * Map in another page to cover it.
2103                          */
2104                         if (pmap_grow_map(nva, pte_l2_s_cache_mode, NULL))
2105                                 return (NULL);
2106                 }
2107
2108                 pmap_kernel_l2dtable_kva = nva;
2109
2110                 /*
2111                  * Link it into the parent pmap
2112                  */
2113                 pmap->pm_l2[L2_IDX(l1idx)] = l2;
2114                 memset(l2, 0, sizeof(*l2));
2115         }
2116
2117         l2b = &l2->l2_bucket[L2_BUCKET(l1idx)];
2118
2119         /*
2120          * Fetch pointer to the L2 page table associated with the address.
2121          */
2122         if (l2b->l2b_kva == NULL) {
2123                 pt_entry_t *ptep;
2124
2125                 /*
2126                  * No L2 page table has been allocated. Chances are, this
2127                  * is because we just allocated the l2_dtable, above.
2128                  */
2129                 nva = pmap_kernel_l2ptp_kva;
2130                 ptep = (pt_entry_t *)nva;
2131                 if ((nva & PAGE_MASK) == 0) {
2132                         /*
2133                          * Need to allocate a backing page
2134                          */
2135                         if (pmap_grow_map(nva, pte_l2_s_cache_mode_pt,
2136                             &pmap_kernel_l2ptp_phys))
2137                                 return (NULL);
2138                 }
2139                 memset(ptep, 0, L2_TABLE_SIZE_REAL);
2140                 l2->l2_occupancy++;
2141                 l2b->l2b_kva = ptep;
2142                 l2b->l2b_l1idx = l1idx;
2143                 l2b->l2b_phys = pmap_kernel_l2ptp_phys;
2144
2145                 pmap_kernel_l2ptp_kva += L2_TABLE_SIZE_REAL;
2146                 pmap_kernel_l2ptp_phys += L2_TABLE_SIZE_REAL;
2147         }
2148
2149         /* Distribute new L1 entry to all other L1s */
2150         SLIST_FOREACH(l1, &l1_list, l1_link) {
2151                         pl1pd = &l1->l1_kva[L1_IDX(va)];
2152                         *pl1pd = l2b->l2b_phys | L1_C_DOM(PMAP_DOMAIN_KERNEL) |
2153                             L1_C_PROTO;
2154                         PTE_SYNC(pl1pd);
2155         }
2156         cpu_tlb_flushID_SE(va);
2157         cpu_cpwait();
2158
2159         return (l2b);
2160 }
2161
2162
2163 /*
2164  * grow the number of kernel page table entries, if needed
2165  */
2166 void
2167 pmap_growkernel(vm_offset_t addr)
2168 {
2169         pmap_t kpmap = pmap_kernel();
2170
2171         if (addr <= pmap_curmaxkvaddr)
2172                 return;         /* we are OK */
2173
2174         /*
2175          * whoops!   we need to add kernel PTPs
2176          */
2177
2178         /* Map 1MB at a time */
2179         for (; pmap_curmaxkvaddr < addr; pmap_curmaxkvaddr += L1_S_SIZE)
2180                 pmap_grow_l2_bucket(kpmap, pmap_curmaxkvaddr);
2181
2182         kernel_vm_end = pmap_curmaxkvaddr;
2183 }
2184
2185 /*
2186  * Returns TRUE if the given page is mapped individually or as part of
2187  * a 1MB section.  Otherwise, returns FALSE.
2188  */
2189 boolean_t
2190 pmap_page_is_mapped(vm_page_t m)
2191 {
2192         boolean_t rv;
2193
2194         if ((m->oflags & VPO_UNMANAGED) != 0)
2195                 return (FALSE);
2196         rw_wlock(&pvh_global_lock);
2197         rv = !TAILQ_EMPTY(&m->md.pv_list) ||
2198             ((m->flags & PG_FICTITIOUS) == 0 &&
2199             !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
2200         rw_wunlock(&pvh_global_lock);
2201         return (rv);
2202 }
2203
2204 /*
2205  * Remove all pages from specified address space
2206  * this aids process exit speeds.  Also, this code
2207  * is special cased for current process only, but
2208  * can have the more generic (and slightly slower)
2209  * mode enabled.  This is much faster than pmap_remove
2210  * in the case of running down an entire address space.
2211  */
2212 void
2213 pmap_remove_pages(pmap_t pmap)
2214 {
2215         struct pv_entry *pv;
2216         struct l2_bucket *l2b = NULL;
2217         struct pv_chunk *pc, *npc;
2218         struct md_page *pvh;
2219         pd_entry_t *pl1pd, l1pd;
2220         pt_entry_t *ptep;
2221         vm_page_t m, mt;
2222         vm_offset_t va;
2223         uint32_t inuse, bitmask;
2224         int allfree, bit, field, idx;
2225
2226         rw_wlock(&pvh_global_lock);
2227         PMAP_LOCK(pmap);
2228
2229         TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
2230                 allfree = 1;
2231                 for (field = 0; field < _NPCM; field++) {
2232                         inuse = ~pc->pc_map[field] & pc_freemask[field];
2233                         while (inuse != 0) {
2234                                 bit = ffs(inuse) - 1;
2235                                 bitmask = 1ul << bit;
2236                                 idx = field * sizeof(inuse) * NBBY + bit;
2237                                 pv = &pc->pc_pventry[idx];
2238                                 va = pv->pv_va;
2239                                 inuse &= ~bitmask;
2240                                 if (pv->pv_flags & PVF_WIRED) {
2241                                         /* Cannot remove wired pages now. */
2242                                         allfree = 0;
2243                                         continue;
2244                                 }
2245                                 pl1pd = &pmap->pm_l1->l1_kva[L1_IDX(va)];
2246                                 l1pd = *pl1pd;
2247                                 l2b = pmap_get_l2_bucket(pmap, va);
2248                                 if ((l1pd & L1_TYPE_MASK) == L1_S_PROTO) {
2249                                         pvh = pa_to_pvh(l1pd & L1_S_FRAME);
2250                                         TAILQ_REMOVE(&pvh->pv_list, pv, pv_list);
2251                                         if (TAILQ_EMPTY(&pvh->pv_list)) {
2252                                                 m = PHYS_TO_VM_PAGE(l1pd & L1_S_FRAME);
2253                                                 KASSERT((vm_offset_t)m >= KERNBASE,
2254                                                     ("Trying to access non-existent page "
2255                                                      "va %x l1pd %x", trunc_1mpage(va), l1pd));
2256                                                 for (mt = m; mt < &m[L2_PTE_NUM_TOTAL]; mt++) {
2257                                                         if (TAILQ_EMPTY(&mt->md.pv_list))
2258                                                                 vm_page_aflag_clear(mt, PGA_WRITEABLE);
2259                                                 }
2260                                         }
2261                                         if (l2b != NULL) {
2262                                                 KASSERT(l2b->l2b_occupancy == L2_PTE_NUM_TOTAL,
2263                                                     ("pmap_remove_pages: l2_bucket occupancy error"));
2264                                                 pmap_free_l2_bucket(pmap, l2b, L2_PTE_NUM_TOTAL);
2265                                         }
2266                                         pmap->pm_stats.resident_count -= L2_PTE_NUM_TOTAL;
2267                                         *pl1pd = 0;
2268                                         PTE_SYNC(pl1pd);
2269                                 } else {
2270                                         KASSERT(l2b != NULL,
2271                                             ("No L2 bucket in pmap_remove_pages"));
2272                                         ptep = &l2b->l2b_kva[l2pte_index(va)];
2273                                         m = PHYS_TO_VM_PAGE(l2pte_pa(*ptep));
2274                                         KASSERT((vm_offset_t)m >= KERNBASE,
2275                                             ("Trying to access non-existent page "
2276                                              "va %x pte %x", va, *ptep));
2277                                         TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
2278                                         if (TAILQ_EMPTY(&m->md.pv_list) &&
2279                                             (m->flags & PG_FICTITIOUS) == 0) {
2280                                                 pvh = pa_to_pvh(l2pte_pa(*ptep));
2281                                                 if (TAILQ_EMPTY(&pvh->pv_list))
2282                                                         vm_page_aflag_clear(m, PGA_WRITEABLE);
2283                                         }
2284                                         *ptep = 0;
2285                                         PTE_SYNC(ptep);
2286                                         pmap_free_l2_bucket(pmap, l2b, 1);
2287                                         pmap->pm_stats.resident_count--;
2288                                 }
2289
2290                                 /* Mark free */
2291                                 PV_STAT(pv_entry_frees++);
2292                                 PV_STAT(pv_entry_spare++);
2293                                 pv_entry_count--;
2294                                 pc->pc_map[field] |= bitmask;
2295                         }
2296                 }
2297                 if (allfree) {
2298                         TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2299                         pmap_free_pv_chunk(pc);
2300                 }
2301
2302         }
2303
2304         rw_wunlock(&pvh_global_lock);
2305         cpu_tlb_flushID();
2306         cpu_cpwait();
2307         PMAP_UNLOCK(pmap);
2308 }
2309
2310 static void
2311 pmap_init_qpages(void)
2312 {
2313         struct pcpu *pc;
2314         struct l2_bucket *l2b;
2315         int i;
2316
2317         CPU_FOREACH(i) {
2318                 pc = pcpu_find(i);
2319                 pc->pc_qmap_addr = kva_alloc(PAGE_SIZE);
2320                 if (pc->pc_qmap_addr == 0)
2321                         panic("pmap_init_qpages: unable to allocate KVA");
2322
2323                 l2b = pmap_get_l2_bucket(pmap_kernel(), pc->pc_qmap_addr);
2324                 if (l2b == NULL)
2325                         l2b = pmap_grow_l2_bucket(pmap_kernel(),
2326                             pc->pc_qmap_addr);
2327                 if (l2b == NULL)
2328                         panic("pmap_alloc_specials: no l2b for 0x%x",
2329                             pc->pc_qmap_addr);
2330                 pc->pc_qmap_pte = &l2b->l2b_kva[l2pte_index(pc->pc_qmap_addr)];
2331         }
2332 }
2333
2334 SYSINIT(qpages_init, SI_SUB_CPU, SI_ORDER_ANY, pmap_init_qpages, NULL);
2335
2336 /***************************************************
2337  * Low level mapping routines.....
2338  ***************************************************/
2339
2340 #ifdef ARM_HAVE_SUPERSECTIONS
2341 /* Map a super section into the KVA. */
2342
2343 void
2344 pmap_kenter_supersection(vm_offset_t va, uint64_t pa, int flags)
2345 {
2346         pd_entry_t pd = L1_S_PROTO | L1_S_SUPERSEC | (pa & L1_SUP_FRAME) |
2347             (((pa >> 32) & 0xf) << 20) | L1_S_PROT(PTE_KERNEL,
2348             VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE) |
2349             L1_S_DOM(PMAP_DOMAIN_KERNEL);
2350         struct l1_ttable *l1;
2351         vm_offset_t va0, va_end;
2352
2353         KASSERT(((va | pa) & L1_SUP_OFFSET) == 0,
2354             ("Not a valid super section mapping"));
2355         if (flags & SECTION_CACHE)
2356                 pd |= pte_l1_s_cache_mode;
2357         else if (flags & SECTION_PT)
2358                 pd |= pte_l1_s_cache_mode_pt;
2359
2360         va0 = va & L1_SUP_FRAME;
2361         va_end = va + L1_SUP_SIZE;
2362         SLIST_FOREACH(l1, &l1_list, l1_link) {
2363                 va = va0;
2364                 for (; va < va_end; va += L1_S_SIZE) {
2365                         l1->l1_kva[L1_IDX(va)] = pd;
2366                         PTE_SYNC(&l1->l1_kva[L1_IDX(va)]);
2367                 }
2368         }
2369 }
2370 #endif
2371
2372 /* Map a section into the KVA. */
2373
2374 void
2375 pmap_kenter_section(vm_offset_t va, vm_offset_t pa, int flags)
2376 {
2377         pd_entry_t pd = L1_S_PROTO | pa | L1_S_PROT(PTE_KERNEL,
2378             VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE) | L1_S_REF |
2379             L1_S_DOM(PMAP_DOMAIN_KERNEL);
2380         struct l1_ttable *l1;
2381
2382         KASSERT(((va | pa) & L1_S_OFFSET) == 0,
2383             ("Not a valid section mapping"));
2384         if (flags & SECTION_CACHE)
2385                 pd |= pte_l1_s_cache_mode;
2386         else if (flags & SECTION_PT)
2387                 pd |= pte_l1_s_cache_mode_pt;
2388
2389         SLIST_FOREACH(l1, &l1_list, l1_link) {
2390                 l1->l1_kva[L1_IDX(va)] = pd;
2391                 PTE_SYNC(&l1->l1_kva[L1_IDX(va)]);
2392         }
2393         cpu_tlb_flushID_SE(va);
2394         cpu_cpwait();
2395 }
2396
2397 /*
2398  * Make a temporary mapping for a physical address.  This is only intended
2399  * to be used for panic dumps.
2400  */
2401 void *
2402 pmap_kenter_temporary(vm_paddr_t pa, int i)
2403 {
2404         vm_offset_t va;
2405
2406         va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
2407         pmap_kenter(va, pa);
2408         return ((void *)crashdumpmap);
2409 }
2410
2411 /*
2412  * add a wired page to the kva
2413  * note that in order for the mapping to take effect -- you
2414  * should do a invltlb after doing the pmap_kenter...
2415  */
2416 static PMAP_INLINE void
2417 pmap_kenter_internal(vm_offset_t va, vm_offset_t pa, int flags)
2418 {
2419         struct l2_bucket *l2b;
2420         pt_entry_t *ptep;
2421         pt_entry_t opte;
2422
2423         PDEBUG(1, printf("pmap_kenter: va = %08x, pa = %08x\n",
2424             (uint32_t) va, (uint32_t) pa));
2425
2426
2427         l2b = pmap_get_l2_bucket(pmap_kernel(), va);
2428         if (l2b == NULL)
2429                 l2b = pmap_grow_l2_bucket(pmap_kernel(), va);
2430         KASSERT(l2b != NULL, ("No L2 Bucket"));
2431
2432         ptep = &l2b->l2b_kva[l2pte_index(va)];
2433         opte = *ptep;
2434
2435         if (flags & KENTER_CACHE)
2436                 *ptep = L2_S_PROTO | l2s_mem_types[PTE_CACHE] | pa | L2_S_REF;
2437         else if (flags & KENTER_DEVICE)
2438                 *ptep = L2_S_PROTO | l2s_mem_types[PTE_DEVICE] | pa | L2_S_REF;
2439         else
2440                 *ptep = L2_S_PROTO | l2s_mem_types[PTE_NOCACHE] | pa | L2_S_REF;
2441
2442         if (flags & KENTER_CACHE) {
2443                 pmap_set_prot(ptep, VM_PROT_READ | VM_PROT_WRITE,
2444                     flags & KENTER_USER);
2445         } else {
2446                 pmap_set_prot(ptep, VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE,
2447                     0);
2448         }
2449
2450         PTE_SYNC(ptep);
2451         if (l2pte_valid(opte)) {
2452                 if (L2_S_EXECUTABLE(opte) || L2_S_EXECUTABLE(*ptep))
2453                         cpu_tlb_flushID_SE(va);
2454                 else
2455                         cpu_tlb_flushD_SE(va);
2456         } else {
2457                 if (opte == 0)
2458                         l2b->l2b_occupancy++;
2459         }
2460         cpu_cpwait();
2461
2462         PDEBUG(1, printf("pmap_kenter: pte = %08x, opte = %08x, npte = %08x\n",
2463             (uint32_t) ptep, opte, *ptep));
2464 }
2465
2466 void
2467 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
2468 {
2469         pmap_kenter_internal(va, pa, KENTER_CACHE);
2470 }
2471
2472 void
2473 pmap_kenter_nocache(vm_offset_t va, vm_paddr_t pa)
2474 {
2475
2476         pmap_kenter_internal(va, pa, 0);
2477 }
2478
2479 void
2480 pmap_kenter_device(vm_offset_t va, vm_size_t size, vm_paddr_t pa)
2481 {
2482         vm_offset_t sva;
2483
2484         KASSERT((size & PAGE_MASK) == 0,
2485             ("%s: device mapping not page-sized", __func__));
2486
2487         sva = va;
2488         while (size != 0) {
2489                 pmap_kenter_internal(va, pa, KENTER_DEVICE);
2490                 va += PAGE_SIZE;
2491                 pa += PAGE_SIZE;
2492                 size -= PAGE_SIZE;
2493         }
2494 }
2495
2496 void
2497 pmap_kremove_device(vm_offset_t va, vm_size_t size)
2498 {
2499         vm_offset_t sva;
2500
2501         KASSERT((size & PAGE_MASK) == 0,
2502             ("%s: device mapping not page-sized", __func__));
2503
2504         sva = va;
2505         while (size != 0) {
2506                 pmap_kremove(va);
2507                 va += PAGE_SIZE;
2508                 size -= PAGE_SIZE;
2509         }
2510 }
2511
2512 void
2513 pmap_kenter_user(vm_offset_t va, vm_paddr_t pa)
2514 {
2515
2516         pmap_kenter_internal(va, pa, KENTER_CACHE|KENTER_USER);
2517         /*
2518          * Call pmap_fault_fixup now, to make sure we'll have no exception
2519          * at the first use of the new address, or bad things will happen,
2520          * as we use one of these addresses in the exception handlers.
2521          */
2522         pmap_fault_fixup(pmap_kernel(), va, VM_PROT_READ|VM_PROT_WRITE, 1);
2523 }
2524
2525 vm_paddr_t
2526 pmap_kextract(vm_offset_t va)
2527 {
2528
2529         if (kernel_vm_end == 0)
2530                 return (0);
2531         return (pmap_extract_locked(kernel_pmap, va));
2532 }
2533
2534 /*
2535  * remove a page from the kernel pagetables
2536  */
2537 void
2538 pmap_kremove(vm_offset_t va)
2539 {
2540         struct l2_bucket *l2b;
2541         pt_entry_t *ptep, opte;
2542
2543         l2b = pmap_get_l2_bucket(pmap_kernel(), va);
2544         if (!l2b)
2545                 return;
2546         KASSERT(l2b != NULL, ("No L2 Bucket"));
2547         ptep = &l2b->l2b_kva[l2pte_index(va)];
2548         opte = *ptep;
2549         if (l2pte_valid(opte)) {
2550                 va = va & ~PAGE_MASK;
2551                 *ptep = 0;
2552                 PTE_SYNC(ptep);
2553                 if (L2_S_EXECUTABLE(opte))
2554                         cpu_tlb_flushID_SE(va);
2555                 else
2556                         cpu_tlb_flushD_SE(va);
2557                 cpu_cpwait();
2558         }
2559 }
2560
2561
2562 /*
2563  *      Used to map a range of physical addresses into kernel
2564  *      virtual address space.
2565  *
2566  *      The value passed in '*virt' is a suggested virtual address for
2567  *      the mapping. Architectures which can support a direct-mapped
2568  *      physical to virtual region can return the appropriate address
2569  *      within that region, leaving '*virt' unchanged. Other
2570  *      architectures should map the pages starting at '*virt' and
2571  *      update '*virt' with the first usable address after the mapped
2572  *      region.
2573  */
2574 vm_offset_t
2575 pmap_map(vm_offset_t *virt, vm_offset_t start, vm_offset_t end, int prot)
2576 {
2577         vm_offset_t sva = *virt;
2578         vm_offset_t va = sva;
2579
2580         PDEBUG(1, printf("pmap_map: virt = %08x, start = %08x, end = %08x, "
2581             "prot = %d\n", (uint32_t) *virt, (uint32_t) start, (uint32_t) end,
2582             prot));
2583
2584         while (start < end) {
2585                 pmap_kenter(va, start);
2586                 va += PAGE_SIZE;
2587                 start += PAGE_SIZE;
2588         }
2589         *virt = va;
2590         return (sva);
2591 }
2592
2593 /*
2594  * Add a list of wired pages to the kva
2595  * this routine is only used for temporary
2596  * kernel mappings that do not need to have
2597  * page modification or references recorded.
2598  * Note that old mappings are simply written
2599  * over.  The page *must* be wired.
2600  */
2601 void
2602 pmap_qenter(vm_offset_t va, vm_page_t *m, int count)
2603 {
2604         int i;
2605
2606         for (i = 0; i < count; i++) {
2607                 pmap_kenter_internal(va, VM_PAGE_TO_PHYS(m[i]),
2608                     KENTER_CACHE);
2609                 va += PAGE_SIZE;
2610         }
2611 }
2612
2613
2614 /*
2615  * this routine jerks page mappings from the
2616  * kernel -- it is meant only for temporary mappings.
2617  */
2618 void
2619 pmap_qremove(vm_offset_t va, int count)
2620 {
2621         int i;
2622
2623         for (i = 0; i < count; i++) {
2624                 if (vtophys(va))
2625                         pmap_kremove(va);
2626
2627                 va += PAGE_SIZE;
2628         }
2629 }
2630
2631
2632 /*
2633  * pmap_object_init_pt preloads the ptes for a given object
2634  * into the specified pmap.  This eliminates the blast of soft
2635  * faults on process startup and immediately after an mmap.
2636  */
2637 void
2638 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
2639     vm_pindex_t pindex, vm_size_t size)
2640 {
2641
2642         VM_OBJECT_ASSERT_WLOCKED(object);
2643         KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
2644             ("pmap_object_init_pt: non-device object"));
2645 }
2646
2647
2648 /*
2649  *      pmap_is_prefaultable:
2650  *
2651  *      Return whether or not the specified virtual address is elgible
2652  *      for prefault.
2653  */
2654 boolean_t
2655 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
2656 {
2657         pd_entry_t *pdep;
2658         pt_entry_t *ptep;
2659
2660         if (!pmap_get_pde_pte(pmap, addr, &pdep, &ptep))
2661                 return (FALSE);
2662         KASSERT((pdep != NULL && (l1pte_section_p(*pdep) || ptep != NULL)),
2663             ("Valid mapping but no pte ?"));
2664         if (*pdep != 0 && !l1pte_section_p(*pdep))
2665                 if (*ptep == 0)
2666                         return (TRUE);
2667         return (FALSE);
2668 }
2669
2670 /*
2671  * Fetch pointers to the PDE/PTE for the given pmap/VA pair.
2672  * Returns TRUE if the mapping exists, else FALSE.
2673  *
2674  * NOTE: This function is only used by a couple of arm-specific modules.
2675  * It is not safe to take any pmap locks here, since we could be right
2676  * in the middle of debugging the pmap anyway...
2677  *
2678  * It is possible for this routine to return FALSE even though a valid
2679  * mapping does exist. This is because we don't lock, so the metadata
2680  * state may be inconsistent.
2681  *
2682  * NOTE: We can return a NULL *ptp in the case where the L1 pde is
2683  * a "section" mapping.
2684  */
2685 boolean_t
2686 pmap_get_pde_pte(pmap_t pmap, vm_offset_t va, pd_entry_t **pdp,
2687     pt_entry_t **ptp)
2688 {
2689         struct l2_dtable *l2;
2690         pd_entry_t *pl1pd, l1pd;
2691         pt_entry_t *ptep;
2692         u_short l1idx;
2693
2694         if (pmap->pm_l1 == NULL)
2695                 return (FALSE);
2696
2697         l1idx = L1_IDX(va);
2698         *pdp = pl1pd = &pmap->pm_l1->l1_kva[l1idx];
2699         l1pd = *pl1pd;
2700
2701         if (l1pte_section_p(l1pd)) {
2702                 *ptp = NULL;
2703                 return (TRUE);
2704         }
2705
2706         if (pmap->pm_l2 == NULL)
2707                 return (FALSE);
2708
2709         l2 = pmap->pm_l2[L2_IDX(l1idx)];
2710
2711         if (l2 == NULL ||
2712             (ptep = l2->l2_bucket[L2_BUCKET(l1idx)].l2b_kva) == NULL) {
2713                 return (FALSE);
2714         }
2715
2716         *ptp = &ptep[l2pte_index(va)];
2717         return (TRUE);
2718 }
2719
2720 /*
2721  *      Routine:        pmap_remove_all
2722  *      Function:
2723  *              Removes this physical page from
2724  *              all physical maps in which it resides.
2725  *              Reflects back modify bits to the pager.
2726  *
2727  *      Notes:
2728  *              Original versions of this routine were very
2729  *              inefficient because they iteratively called
2730  *              pmap_remove (slow...)
2731  */
2732 void
2733 pmap_remove_all(vm_page_t m)
2734 {
2735         struct md_page *pvh;
2736         pv_entry_t pv;
2737         pmap_t pmap;
2738         pt_entry_t *ptep;
2739         struct l2_bucket *l2b;
2740         boolean_t flush = FALSE;
2741         pmap_t curpmap;
2742         u_int is_exec = 0;
2743
2744         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
2745             ("pmap_remove_all: page %p is not managed", m));
2746         rw_wlock(&pvh_global_lock);
2747         if ((m->flags & PG_FICTITIOUS) != 0)
2748                 goto small_mappings;
2749         pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
2750         while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
2751                 pmap = PV_PMAP(pv);
2752                 PMAP_LOCK(pmap);
2753                 pd_entry_t *pl1pd;
2754                 pl1pd = &pmap->pm_l1->l1_kva[L1_IDX(pv->pv_va)];
2755                 KASSERT((*pl1pd & L1_TYPE_MASK) == L1_S_PROTO,
2756                     ("pmap_remove_all: valid section mapping expected"));
2757                 (void)pmap_demote_section(pmap, pv->pv_va);
2758                 PMAP_UNLOCK(pmap);
2759         }
2760 small_mappings:
2761         curpmap = vmspace_pmap(curproc->p_vmspace);
2762         while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
2763                 pmap = PV_PMAP(pv);
2764                 if (flush == FALSE && (pmap == curpmap ||
2765                     pmap == pmap_kernel()))
2766                         flush = TRUE;
2767
2768                 PMAP_LOCK(pmap);
2769                 l2b = pmap_get_l2_bucket(pmap, pv->pv_va);
2770                 KASSERT(l2b != NULL, ("No l2 bucket"));
2771                 ptep = &l2b->l2b_kva[l2pte_index(pv->pv_va)];
2772                 is_exec |= PTE_BEEN_EXECD(*ptep);
2773                 *ptep = 0;
2774                 if (pmap_is_current(pmap))
2775                         PTE_SYNC(ptep);
2776                 pmap_free_l2_bucket(pmap, l2b, 1);
2777                 pmap->pm_stats.resident_count--;
2778                 TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
2779                 if (pv->pv_flags & PVF_WIRED)
2780                         pmap->pm_stats.wired_count--;
2781                 pmap_free_pv_entry(pmap, pv);
2782                 PMAP_UNLOCK(pmap);
2783         }
2784
2785         if (flush) {
2786                 if (is_exec)
2787                         cpu_tlb_flushID();
2788                 else
2789                         cpu_tlb_flushD();
2790                 cpu_cpwait();
2791         }
2792         vm_page_aflag_clear(m, PGA_WRITEABLE);
2793         rw_wunlock(&pvh_global_lock);
2794 }
2795
2796 int
2797 pmap_change_attr(vm_offset_t sva, vm_size_t len, int mode)
2798 {
2799         vm_offset_t base, offset, tmpva;
2800         vm_size_t size;
2801         struct l2_bucket *l2b;
2802         pt_entry_t *ptep, pte;
2803         vm_offset_t next_bucket;
2804
2805         PMAP_LOCK(kernel_pmap);
2806
2807         base = trunc_page(sva);
2808         offset = sva & PAGE_MASK;
2809         size = roundup(offset + len, PAGE_SIZE);
2810
2811         for (tmpva = base; tmpva < base + size; ) {
2812                 next_bucket = L2_NEXT_BUCKET(tmpva);
2813                 if (next_bucket > base + size)
2814                         next_bucket = base + size;
2815
2816                 l2b = pmap_get_l2_bucket(kernel_pmap, tmpva);
2817                 if (l2b == NULL) {
2818                         tmpva = next_bucket;
2819                         continue;
2820                 }
2821
2822                 ptep = &l2b->l2b_kva[l2pte_index(tmpva)];
2823
2824                 if (*ptep == 0) {
2825                         PMAP_UNLOCK(kernel_pmap);
2826                         return(EINVAL);
2827                 }
2828
2829                 pte = *ptep &~ L2_S_CACHE_MASK;
2830                 cpu_idcache_wbinv_range(tmpva, PAGE_SIZE);
2831                 pmap_l2cache_wbinv_range(tmpva, pte & L2_S_FRAME, PAGE_SIZE);
2832                 *ptep = pte;
2833                 cpu_tlb_flushID_SE(tmpva);
2834                 cpu_cpwait();
2835
2836                 dprintf("%s: for va:%x ptep:%x pte:%x\n",
2837                     __func__, tmpva, (uint32_t)ptep, pte);
2838                 tmpva += PAGE_SIZE;
2839         }
2840
2841         PMAP_UNLOCK(kernel_pmap);
2842
2843         return (0);
2844 }
2845
2846 /*
2847  *      Set the physical protection on the
2848  *      specified range of this map as requested.
2849  */
2850 void
2851 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
2852 {
2853         struct l2_bucket *l2b;
2854         struct md_page *pvh;
2855         struct pv_entry *pve;
2856         pd_entry_t *pl1pd, l1pd;
2857         pt_entry_t *ptep, pte;
2858         vm_offset_t next_bucket;
2859         u_int is_exec, is_refd;
2860         int flush;
2861
2862         if ((prot & VM_PROT_READ) == 0) {
2863                 pmap_remove(pmap, sva, eva);
2864                 return;
2865         }
2866
2867         if (prot & VM_PROT_WRITE) {
2868                 /*
2869                  * If this is a read->write transition, just ignore it and let
2870                  * vm_fault() take care of it later.
2871                  */
2872                 return;
2873         }
2874
2875         rw_wlock(&pvh_global_lock);
2876         PMAP_LOCK(pmap);
2877
2878         /*
2879          * OK, at this point, we know we're doing write-protect operation.
2880          * If the pmap is active, write-back the range.
2881          */
2882
2883         flush = ((eva - sva) >= (PAGE_SIZE * 4)) ? 0 : -1;
2884         is_exec = is_refd = 0;
2885
2886         while (sva < eva) {
2887                 next_bucket = L2_NEXT_BUCKET(sva);
2888                 /*
2889                  * Check for large page.
2890                  */
2891                 pl1pd = &pmap->pm_l1->l1_kva[L1_IDX(sva)];
2892                 l1pd = *pl1pd;
2893                 if ((l1pd & L1_TYPE_MASK) == L1_S_PROTO) {
2894                         KASSERT(pmap != pmap_kernel(),
2895                             ("pmap_protect: trying to modify "
2896                             "kernel section protections"));
2897                         /*
2898                          * Are we protecting the entire large page? If not,
2899                          * demote the mapping and fall through.
2900                          */
2901                         if (sva + L1_S_SIZE == next_bucket &&
2902                             eva >= next_bucket) {
2903                                 l1pd &= ~(L1_S_PROT_MASK | L1_S_XN);
2904                                 if (!(prot & VM_PROT_EXECUTE))
2905                                         l1pd |= L1_S_XN;
2906                                 /*
2907                                  * At this point we are always setting
2908                                  * write-protect bit.
2909                                  */
2910                                 l1pd |= L1_S_APX;
2911                                 /* All managed superpages are user pages. */
2912                                 l1pd |= L1_S_PROT_U;
2913                                 *pl1pd = l1pd;
2914                                 PTE_SYNC(pl1pd);
2915                                 pvh = pa_to_pvh(l1pd & L1_S_FRAME);
2916                                 pve = pmap_find_pv(pvh, pmap,
2917                                     trunc_1mpage(sva));
2918                                 pve->pv_flags &= ~PVF_WRITE;
2919                                 sva = next_bucket;
2920                                 continue;
2921                         } else if (!pmap_demote_section(pmap, sva)) {
2922                                 /* The large page mapping was destroyed. */
2923                                 sva = next_bucket;
2924                                 continue;
2925                         }
2926                 }
2927                 if (next_bucket > eva)
2928                         next_bucket = eva;
2929                 l2b = pmap_get_l2_bucket(pmap, sva);
2930                 if (l2b == NULL) {
2931                         sva = next_bucket;
2932                         continue;
2933                 }
2934
2935                 ptep = &l2b->l2b_kva[l2pte_index(sva)];
2936
2937                 while (sva < next_bucket) {
2938                         if ((pte = *ptep) != 0 && L2_S_WRITABLE(pte)) {
2939                                 struct vm_page *m;
2940
2941                                 m = PHYS_TO_VM_PAGE(l2pte_pa(pte));
2942                                 pmap_set_prot(ptep, prot,
2943                                     !(pmap == pmap_kernel()));
2944                                 PTE_SYNC(ptep);
2945
2946                                 pmap_modify_pv(m, pmap, sva, PVF_WRITE, 0);
2947
2948                                 if (flush >= 0) {
2949                                         flush++;
2950                                         is_exec |= PTE_BEEN_EXECD(pte);
2951                                         is_refd |= PTE_BEEN_REFD(pte);
2952                                 } else {
2953                                         if (PTE_BEEN_EXECD(pte))
2954                                                 cpu_tlb_flushID_SE(sva);
2955                                         else if (PTE_BEEN_REFD(pte))
2956                                                 cpu_tlb_flushD_SE(sva);
2957                                 }
2958                         }
2959
2960                         sva += PAGE_SIZE;
2961                         ptep++;
2962                 }
2963         }
2964
2965
2966         if (flush) {
2967                 if (is_exec)
2968                         cpu_tlb_flushID();
2969                 else
2970                 if (is_refd)
2971                         cpu_tlb_flushD();
2972                 cpu_cpwait();
2973         }
2974         rw_wunlock(&pvh_global_lock);
2975
2976         PMAP_UNLOCK(pmap);
2977 }
2978
2979
2980 /*
2981  *      Insert the given physical page (p) at
2982  *      the specified virtual address (v) in the
2983  *      target physical map with the protection requested.
2984  *
2985  *      If specified, the page will be wired down, meaning
2986  *      that the related pte can not be reclaimed.
2987  *
2988  *      NB:  This is the only routine which MAY NOT lazy-evaluate
2989  *      or lose information.  That is, this routine must actually
2990  *      insert this page into the given map NOW.
2991  */
2992
2993 int
2994 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
2995     u_int flags, int8_t psind __unused)
2996 {
2997         struct l2_bucket *l2b;
2998         int rv;
2999
3000         rw_wlock(&pvh_global_lock);
3001         PMAP_LOCK(pmap);
3002         rv = pmap_enter_locked(pmap, va, m, prot, flags);
3003         if (rv == KERN_SUCCESS) {
3004                 /*
3005                  * If both the l2b_occupancy and the reservation are fully
3006                  * populated, then attempt promotion.
3007                  */
3008                 l2b = pmap_get_l2_bucket(pmap, va);
3009                 if (l2b != NULL && l2b->l2b_occupancy == L2_PTE_NUM_TOTAL &&
3010                     sp_enabled && (m->flags & PG_FICTITIOUS) == 0 &&
3011                     vm_reserv_level_iffullpop(m) == 0)
3012                         pmap_promote_section(pmap, va);
3013         }
3014         PMAP_UNLOCK(pmap);
3015         rw_wunlock(&pvh_global_lock);
3016         return (rv);
3017 }
3018
3019 /*
3020  *      The pvh global and pmap locks must be held.
3021  */
3022 static int
3023 pmap_enter_locked(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
3024     u_int flags)
3025 {
3026         struct l2_bucket *l2b = NULL;
3027         struct vm_page *om;
3028         struct pv_entry *pve = NULL;
3029         pd_entry_t *pl1pd, l1pd;
3030         pt_entry_t *ptep, npte, opte;
3031         u_int nflags;
3032         u_int is_exec, is_refd;
3033         vm_paddr_t pa;
3034         u_char user;
3035
3036         PMAP_ASSERT_LOCKED(pmap);
3037         rw_assert(&pvh_global_lock, RA_WLOCKED);
3038         if (va == vector_page) {
3039                 pa = systempage.pv_pa;
3040                 m = NULL;
3041         } else {
3042                 if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_xbusied(m))
3043                         VM_OBJECT_ASSERT_LOCKED(m->object);
3044                 pa = VM_PAGE_TO_PHYS(m);
3045         }
3046
3047         pl1pd = &pmap->pm_l1->l1_kva[L1_IDX(va)];
3048         if ((va < VM_MAXUSER_ADDRESS) &&
3049             (*pl1pd & L1_TYPE_MASK) == L1_S_PROTO) {
3050                 (void)pmap_demote_section(pmap, va);
3051         }
3052
3053         user = 0;
3054         /*
3055          * Make sure userland mappings get the right permissions
3056          */
3057         if (pmap != pmap_kernel() && va != vector_page)
3058                 user = 1;
3059
3060         nflags = 0;
3061
3062         if (prot & VM_PROT_WRITE)
3063                 nflags |= PVF_WRITE;
3064         if ((flags & PMAP_ENTER_WIRED) != 0)
3065                 nflags |= PVF_WIRED;
3066
3067         PDEBUG(1, printf("pmap_enter: pmap = %08x, va = %08x, m = %08x, "
3068             "prot = %x, flags = %x\n", (uint32_t) pmap, va, (uint32_t) m,
3069             prot, flags));
3070
3071         if (pmap == pmap_kernel()) {
3072                 l2b = pmap_get_l2_bucket(pmap, va);
3073                 if (l2b == NULL)
3074                         l2b = pmap_grow_l2_bucket(pmap, va);
3075         } else {
3076 do_l2b_alloc:
3077                 l2b = pmap_alloc_l2_bucket(pmap, va);
3078                 if (l2b == NULL) {
3079                         if ((flags & PMAP_ENTER_NOSLEEP) == 0) {
3080                                 PMAP_UNLOCK(pmap);
3081                                 rw_wunlock(&pvh_global_lock);
3082                                 VM_WAIT;
3083                                 rw_wlock(&pvh_global_lock);
3084                                 PMAP_LOCK(pmap);
3085                                 goto do_l2b_alloc;
3086                         }
3087                         return (KERN_RESOURCE_SHORTAGE);
3088                 }
3089         }
3090
3091         pl1pd = &pmap->pm_l1->l1_kva[L1_IDX(va)];
3092         if ((*pl1pd & L1_TYPE_MASK) == L1_S_PROTO)
3093                 panic("pmap_enter: attempt to enter on 1MB page, va: %#x", va);
3094
3095         ptep = &l2b->l2b_kva[l2pte_index(va)];
3096
3097         opte = *ptep;
3098         npte = pa;
3099         is_exec = is_refd = 0;
3100
3101         if (opte) {
3102                 if (l2pte_pa(opte) == pa) {
3103                         /*
3104                          * We're changing the attrs of an existing mapping.
3105                          */
3106                         if (m != NULL)
3107                                 pmap_modify_pv(m, pmap, va,
3108                                     PVF_WRITE | PVF_WIRED, nflags);
3109                         is_exec |= PTE_BEEN_EXECD(opte);
3110                         is_refd |= PTE_BEEN_REFD(opte);
3111                         goto validate;
3112                 }
3113                 if ((om = PHYS_TO_VM_PAGE(l2pte_pa(opte)))) {
3114                         /*
3115                          * Replacing an existing mapping with a new one.
3116                          * It is part of our managed memory so we
3117                          * must remove it from the PV list
3118                          */
3119                         if ((pve = pmap_remove_pv(om, pmap, va))) {
3120                                 is_exec |= PTE_BEEN_EXECD(opte);
3121                                 is_refd |= PTE_BEEN_REFD(opte);
3122
3123                                 if (m && ((m->oflags & VPO_UNMANAGED)))
3124                                         pmap_free_pv_entry(pmap, pve);
3125                         }
3126                 }
3127
3128         } else {
3129                 /*
3130                  * Keep the stats up to date
3131                  */
3132                 l2b->l2b_occupancy++;
3133                 pmap->pm_stats.resident_count++;
3134         }
3135
3136         /*
3137          * Enter on the PV list if part of our managed memory.
3138          */
3139         if ((m && !(m->oflags & VPO_UNMANAGED))) {
3140                 if ((!pve) && (pve = pmap_get_pv_entry(pmap, FALSE)) == NULL)
3141                         panic("pmap_enter: no pv entries");
3142
3143                 KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva,
3144                 ("pmap_enter: managed mapping within the clean submap"));
3145                 KASSERT(pve != NULL, ("No pv"));
3146                 pmap_enter_pv(m, pve, pmap, va, nflags);
3147         }
3148
3149 validate:
3150         /* Make the new PTE valid */
3151         npte |= L2_S_PROTO;
3152 #ifdef SMP
3153         npte |= L2_SHARED;
3154 #endif
3155         /* Set defaults first - kernel read access */
3156         npte |= L2_APX;
3157         npte |= L2_S_PROT_R;
3158         /* Set "referenced" flag */
3159         npte |= L2_S_REF;
3160
3161         /* Now tune APs as desired */
3162         if (user)
3163                 npte |= L2_S_PROT_U;
3164         /*
3165          * If this is not a vector_page
3166          * then continue setting mapping parameters
3167          */
3168         if (m != NULL) {
3169                 if ((m->oflags & VPO_UNMANAGED) == 0) {
3170                         if (prot & (VM_PROT_ALL)) {
3171                                 vm_page_aflag_set(m, PGA_REFERENCED);
3172                         } else {
3173                                 /*
3174                                  * Need to do page referenced emulation.
3175                                  */
3176                                 npte &= ~L2_S_REF;
3177                         }
3178                 }
3179
3180                 if (prot & VM_PROT_WRITE) {
3181                         if ((m->oflags & VPO_UNMANAGED) == 0) {
3182                                 vm_page_aflag_set(m, PGA_WRITEABLE);
3183                                 /*
3184                                  * XXX: Skip modified bit emulation for now.
3185                                  *      The emulation reveals problems
3186                                  *      that result in random failures
3187                                  *      during memory allocation on some
3188                                  *      platforms.
3189                                  *      Therefore, the page is marked RW
3190                                  *      immediately.
3191                                  */
3192                                 npte &= ~(L2_APX);
3193                                 vm_page_dirty(m);
3194                         } else
3195                                 npte &= ~(L2_APX);
3196                 }
3197                 if (!(prot & VM_PROT_EXECUTE))
3198                         npte |= L2_XN;
3199
3200                 if (m->md.pv_memattr != VM_MEMATTR_UNCACHEABLE)
3201                         npte |= pte_l2_s_cache_mode;
3202         }
3203
3204         CTR5(KTR_PMAP,"enter: pmap:%p va:%x prot:%x pte:%x->%x",
3205             pmap, va, prot, opte, npte);
3206         /*
3207          * If this is just a wiring change, the two PTEs will be
3208          * identical, so there's no need to update the page table.
3209          */
3210         if (npte != opte) {
3211                 boolean_t is_cached = pmap_is_current(pmap);
3212
3213                 *ptep = npte;
3214                 PTE_SYNC(ptep);
3215                 if (is_cached) {
3216                         /*
3217                          * We only need to frob the cache/tlb if this pmap
3218                          * is current
3219                          */
3220                         if (L1_IDX(va) != L1_IDX(vector_page) &&
3221                             l2pte_valid(npte)) {
3222                                 /*
3223                                  * This mapping is likely to be accessed as
3224                                  * soon as we return to userland. Fix up the
3225                                  * L1 entry to avoid taking another
3226                                  * page/domain fault.
3227                                  */
3228                                 l1pd = l2b->l2b_phys |
3229                                     L1_C_DOM(pmap->pm_domain) | L1_C_PROTO;
3230                                 if (*pl1pd != l1pd) {
3231                                         *pl1pd = l1pd;
3232                                         PTE_SYNC(pl1pd);
3233                                 }
3234                         }
3235                 }
3236
3237                 if (is_exec)
3238                         cpu_tlb_flushID_SE(va);
3239                 else if (is_refd)
3240                         cpu_tlb_flushD_SE(va);
3241                 cpu_cpwait();
3242         }
3243
3244         if ((pmap != pmap_kernel()) && (pmap == &curproc->p_vmspace->vm_pmap))
3245                 cpu_icache_sync_range(va, PAGE_SIZE);
3246         return (KERN_SUCCESS);
3247 }
3248
3249 /*
3250  * Maps a sequence of resident pages belonging to the same object.
3251  * The sequence begins with the given page m_start.  This page is
3252  * mapped at the given virtual address start.  Each subsequent page is
3253  * mapped at a virtual address that is offset from start by the same
3254  * amount as the page is offset from m_start within the object.  The
3255  * last page in the sequence is the page with the largest offset from
3256  * m_start that can be mapped at a virtual address less than the given
3257  * virtual address end.  Not every virtual page between start and end
3258  * is mapped; only those for which a resident page exists with the
3259  * corresponding offset from m_start are mapped.
3260  */
3261 void
3262 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
3263     vm_page_t m_start, vm_prot_t prot)
3264 {
3265         vm_offset_t va;
3266         vm_page_t m;
3267         vm_pindex_t diff, psize;
3268
3269         VM_OBJECT_ASSERT_LOCKED(m_start->object);
3270
3271         psize = atop(end - start);
3272         m = m_start;
3273         prot &= VM_PROT_READ | VM_PROT_EXECUTE;
3274         rw_wlock(&pvh_global_lock);
3275         PMAP_LOCK(pmap);
3276         while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
3277                 va = start + ptoa(diff);
3278                 if ((va & L1_S_OFFSET) == 0 && L2_NEXT_BUCKET(va) <= end &&
3279                     m->psind == 1 && sp_enabled &&
3280                     pmap_enter_section(pmap, va, m, prot))
3281                         m = &m[L1_S_SIZE / PAGE_SIZE - 1];
3282                 else
3283                         pmap_enter_locked(pmap, va, m, prot,
3284                             PMAP_ENTER_NOSLEEP);
3285                 m = TAILQ_NEXT(m, listq);
3286         }
3287         PMAP_UNLOCK(pmap);
3288         rw_wunlock(&pvh_global_lock);
3289 }
3290
3291 /*
3292  * this code makes some *MAJOR* assumptions:
3293  * 1. Current pmap & pmap exists.
3294  * 2. Not wired.
3295  * 3. Read access.
3296  * 4. No page table pages.
3297  * but is *MUCH* faster than pmap_enter...
3298  */
3299
3300 void
3301 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
3302 {
3303
3304         prot &= VM_PROT_READ | VM_PROT_EXECUTE;
3305         rw_wlock(&pvh_global_lock);
3306         PMAP_LOCK(pmap);
3307         pmap_enter_locked(pmap, va, m, prot, PMAP_ENTER_NOSLEEP);
3308         PMAP_UNLOCK(pmap);
3309         rw_wunlock(&pvh_global_lock);
3310 }
3311
3312 /*
3313  *      Clear the wired attribute from the mappings for the specified range of
3314  *      addresses in the given pmap.  Every valid mapping within that range
3315  *      must have the wired attribute set.  In contrast, invalid mappings
3316  *      cannot have the wired attribute set, so they are ignored.
3317  *
3318  *      XXX Wired mappings of unmanaged pages cannot be counted by this pmap
3319  *      implementation.
3320  */
3321 void
3322 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3323 {
3324         struct l2_bucket *l2b;
3325         struct md_page *pvh;
3326         pd_entry_t l1pd;
3327         pt_entry_t *ptep, pte;
3328         pv_entry_t pv;
3329         vm_offset_t next_bucket;
3330         vm_paddr_t pa;
3331         vm_page_t m;
3332
3333         rw_wlock(&pvh_global_lock);
3334         PMAP_LOCK(pmap);
3335         while (sva < eva) {
3336                 next_bucket = L2_NEXT_BUCKET(sva);
3337                 l1pd = pmap->pm_l1->l1_kva[L1_IDX(sva)];
3338                 if ((l1pd & L1_TYPE_MASK) == L1_S_PROTO) {
3339                         pa = l1pd & L1_S_FRAME;
3340                         m = PHYS_TO_VM_PAGE(pa);
3341                         KASSERT(m != NULL && (m->oflags & VPO_UNMANAGED) == 0,
3342                             ("pmap_unwire: unmanaged 1mpage %p", m));
3343                         pvh = pa_to_pvh(pa);
3344                         pv = pmap_find_pv(pvh, pmap, trunc_1mpage(sva));
3345                         if ((pv->pv_flags & PVF_WIRED) == 0)
3346                                 panic("pmap_unwire: pv %p isn't wired", pv);
3347
3348                         /*
3349                          * Are we unwiring the entire large page? If not,
3350                          * demote the mapping and fall through.
3351                          */
3352                         if (sva + L1_S_SIZE == next_bucket &&
3353                             eva >= next_bucket) {
3354                                 pv->pv_flags &= ~PVF_WIRED;
3355                                 pmap->pm_stats.wired_count -= L2_PTE_NUM_TOTAL;
3356                                 sva = next_bucket;
3357                                 continue;
3358                         } else if (!pmap_demote_section(pmap, sva))
3359                                 panic("pmap_unwire: demotion failed");
3360                 }
3361                 if (next_bucket > eva)
3362                         next_bucket = eva;
3363                 l2b = pmap_get_l2_bucket(pmap, sva);
3364                 if (l2b == NULL) {
3365                         sva = next_bucket;
3366                         continue;
3367                 }
3368                 for (ptep = &l2b->l2b_kva[l2pte_index(sva)]; sva < next_bucket;
3369                     sva += PAGE_SIZE, ptep++) {
3370                         if ((pte = *ptep) == 0 ||
3371                             (m = PHYS_TO_VM_PAGE(l2pte_pa(pte))) == NULL ||
3372                             (m->oflags & VPO_UNMANAGED) != 0)
3373                                 continue;
3374                         pv = pmap_find_pv(&m->md, pmap, sva);
3375                         if ((pv->pv_flags & PVF_WIRED) == 0)
3376                                 panic("pmap_unwire: pv %p isn't wired", pv);
3377                         pv->pv_flags &= ~PVF_WIRED;
3378                         pmap->pm_stats.wired_count--;
3379                 }
3380         }
3381         rw_wunlock(&pvh_global_lock);
3382         PMAP_UNLOCK(pmap);
3383 }
3384
3385
3386 /*
3387  *      Copy the range specified by src_addr/len
3388  *      from the source map to the range dst_addr/len
3389  *      in the destination map.
3390  *
3391  *      This routine is only advisory and need not do anything.
3392  */
3393 void
3394 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr,
3395     vm_size_t len, vm_offset_t src_addr)
3396 {
3397 }
3398
3399
3400 /*
3401  *      Routine:        pmap_extract
3402  *      Function:
3403  *              Extract the physical page address associated
3404  *              with the given map/virtual_address pair.
3405  */
3406 vm_paddr_t
3407 pmap_extract(pmap_t pmap, vm_offset_t va)
3408 {
3409         vm_paddr_t pa;
3410
3411         PMAP_LOCK(pmap);
3412         pa = pmap_extract_locked(pmap, va);
3413         PMAP_UNLOCK(pmap);
3414         return (pa);
3415 }
3416
3417 static vm_paddr_t
3418 pmap_extract_locked(pmap_t pmap, vm_offset_t va)
3419 {
3420         struct l2_dtable *l2;
3421         pd_entry_t l1pd;
3422         pt_entry_t *ptep, pte;
3423         vm_paddr_t pa;
3424         u_int l1idx;
3425
3426         if (kernel_vm_end != 0 && pmap != kernel_pmap)
3427                 PMAP_ASSERT_LOCKED(pmap);
3428         l1idx = L1_IDX(va);
3429         l1pd = pmap->pm_l1->l1_kva[l1idx];
3430         if (l1pte_section_p(l1pd)) {
3431                 /* XXX: what to do about the bits > 32 ? */
3432                 if (l1pd & L1_S_SUPERSEC)
3433                         pa = (l1pd & L1_SUP_FRAME) | (va & L1_SUP_OFFSET);
3434                 else
3435                         pa = (l1pd & L1_S_FRAME) | (va & L1_S_OFFSET);
3436         } else {
3437                 /*
3438                  * Note that we can't rely on the validity of the L1
3439                  * descriptor as an indication that a mapping exists.
3440                  * We have to look it up in the L2 dtable.
3441                  */
3442                 l2 = pmap->pm_l2[L2_IDX(l1idx)];
3443                 if (l2 == NULL ||
3444                     (ptep = l2->l2_bucket[L2_BUCKET(l1idx)].l2b_kva) == NULL)
3445                         return (0);
3446                 pte = ptep[l2pte_index(va)];
3447                 if (pte == 0)
3448                         return (0);
3449                 switch (pte & L2_TYPE_MASK) {
3450                 case L2_TYPE_L:
3451                         pa = (pte & L2_L_FRAME) | (va & L2_L_OFFSET);
3452                         break;
3453                 default:
3454                         pa = (pte & L2_S_FRAME) | (va & L2_S_OFFSET);
3455                         break;
3456                 }
3457         }
3458         return (pa);
3459 }
3460
3461 /*
3462  * Atomically extract and hold the physical page with the given
3463  * pmap and virtual address pair if that mapping permits the given
3464  * protection.
3465  *
3466  */
3467 vm_page_t
3468 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
3469 {
3470         struct l2_dtable *l2;
3471         pd_entry_t l1pd;
3472         pt_entry_t *ptep, pte;
3473         vm_paddr_t pa, paddr;
3474         vm_page_t m = NULL;
3475         u_int l1idx;
3476         l1idx = L1_IDX(va);
3477         paddr = 0;
3478
3479         PMAP_LOCK(pmap);
3480 retry:
3481         l1pd = pmap->pm_l1->l1_kva[l1idx];
3482         if (l1pte_section_p(l1pd)) {
3483                 /* XXX: what to do about the bits > 32 ? */
3484                 if (l1pd & L1_S_SUPERSEC)
3485                         pa = (l1pd & L1_SUP_FRAME) | (va & L1_SUP_OFFSET);
3486                 else
3487                         pa = (l1pd & L1_S_FRAME) | (va & L1_S_OFFSET);
3488                 if (vm_page_pa_tryrelock(pmap, pa & PG_FRAME, &paddr))
3489                         goto retry;
3490                 if (L1_S_WRITABLE(l1pd) || (prot & VM_PROT_WRITE) == 0) {
3491                         m = PHYS_TO_VM_PAGE(pa);
3492                         vm_page_hold(m);
3493                 }
3494         } else {
3495                 /*
3496                  * Note that we can't rely on the validity of the L1
3497                  * descriptor as an indication that a mapping exists.
3498                  * We have to look it up in the L2 dtable.
3499                  */
3500                 l2 = pmap->pm_l2[L2_IDX(l1idx)];
3501
3502                 if (l2 == NULL ||
3503                     (ptep = l2->l2_bucket[L2_BUCKET(l1idx)].l2b_kva) == NULL) {
3504                         PMAP_UNLOCK(pmap);
3505                         return (NULL);
3506                 }
3507
3508                 ptep = &ptep[l2pte_index(va)];
3509                 pte = *ptep;
3510
3511                 if (pte == 0) {
3512                         PMAP_UNLOCK(pmap);
3513                         return (NULL);
3514                 } else if ((prot & VM_PROT_WRITE) && (pte & L2_APX)) {
3515                         PMAP_UNLOCK(pmap);
3516                         return (NULL);
3517                 } else {
3518                         switch (pte & L2_TYPE_MASK) {
3519                         case L2_TYPE_L:
3520                                 panic("extract and hold section mapping");
3521                                 break;
3522                         default:
3523                                 pa = (pte & L2_S_FRAME) | (va & L2_S_OFFSET);
3524                                 break;
3525                         }
3526                         if (vm_page_pa_tryrelock(pmap, pa & PG_FRAME, &paddr))
3527                                 goto retry;
3528                         m = PHYS_TO_VM_PAGE(pa);
3529                         vm_page_hold(m);
3530                 }
3531
3532         }
3533
3534         PMAP_UNLOCK(pmap);
3535         PA_UNLOCK_COND(paddr);
3536         return (m);
3537 }
3538
3539 /*
3540  * Initialize a preallocated and zeroed pmap structure,
3541  * such as one in a vmspace structure.
3542  */
3543
3544 int
3545 pmap_pinit(pmap_t pmap)
3546 {
3547         PDEBUG(1, printf("pmap_pinit: pmap = %08x\n", (uint32_t) pmap));
3548
3549         pmap_alloc_l1(pmap);
3550         bzero(pmap->pm_l2, sizeof(pmap->pm_l2));
3551
3552         CPU_ZERO(&pmap->pm_active);
3553
3554         TAILQ_INIT(&pmap->pm_pvchunk);
3555         bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
3556         pmap->pm_stats.resident_count = 1;
3557         if (vector_page < KERNBASE) {
3558                 pmap_enter(pmap, vector_page,
3559                     PHYS_TO_VM_PAGE(systempage.pv_pa), VM_PROT_READ,
3560                     PMAP_ENTER_WIRED, 0);
3561         }
3562         return (1);
3563 }
3564
3565
3566 /***************************************************
3567  * Superpage management routines.
3568  ***************************************************/
3569
3570 static PMAP_INLINE struct pv_entry *
3571 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3572 {
3573         pv_entry_t pv;
3574
3575         rw_assert(&pvh_global_lock, RA_WLOCKED);
3576
3577         pv = pmap_find_pv(pvh, pmap, va);
3578         if (pv != NULL)
3579                 TAILQ_REMOVE(&pvh->pv_list, pv, pv_list);
3580
3581         return (pv);
3582 }
3583
3584 static void
3585 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3586 {
3587         pv_entry_t pv;
3588
3589         pv = pmap_pvh_remove(pvh, pmap, va);
3590         KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
3591         pmap_free_pv_entry(pmap, pv);
3592 }
3593
3594 static boolean_t
3595 pmap_pv_insert_section(pmap_t pmap, vm_offset_t va, vm_paddr_t pa)
3596 {
3597         struct md_page *pvh;
3598         pv_entry_t pv;
3599
3600         rw_assert(&pvh_global_lock, RA_WLOCKED);
3601         if (pv_entry_count < pv_entry_high_water &&
3602             (pv = pmap_get_pv_entry(pmap, TRUE)) != NULL) {
3603                 pv->pv_va = va;
3604                 pvh = pa_to_pvh(pa);
3605                 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_list);
3606                 return (TRUE);
3607         } else
3608                 return (FALSE);
3609 }
3610
3611 /*
3612  * Create the pv entries for each of the pages within a superpage.
3613  */
3614 static void
3615 pmap_pv_demote_section(pmap_t pmap, vm_offset_t va, vm_paddr_t pa)
3616 {
3617         struct md_page *pvh;
3618         pv_entry_t pve, pv;
3619         vm_offset_t va_last;
3620         vm_page_t m;
3621
3622         rw_assert(&pvh_global_lock, RA_WLOCKED);
3623         KASSERT((pa & L1_S_OFFSET) == 0,
3624             ("pmap_pv_demote_section: pa is not 1mpage aligned"));
3625
3626         /*
3627          * Transfer the 1mpage's pv entry for this mapping to the first
3628          * page's pv list.
3629          */
3630         pvh = pa_to_pvh(pa);
3631         va = trunc_1mpage(va);
3632         pv = pmap_pvh_remove(pvh, pmap, va);
3633         KASSERT(pv != NULL, ("pmap_pv_demote_section: pv not found"));
3634         m = PHYS_TO_VM_PAGE(pa);
3635         TAILQ_INSERT_HEAD(&m->md.pv_list, pv, pv_list);
3636         /* Instantiate the remaining pv entries. */
3637         va_last = L2_NEXT_BUCKET(va) - PAGE_SIZE;
3638         do {
3639                 m++;
3640                 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3641                     ("pmap_pv_demote_section: page %p is not managed", m));
3642                 va += PAGE_SIZE;
3643                 pve = pmap_get_pv_entry(pmap, FALSE);
3644                 pmap_enter_pv(m, pve, pmap, va, pv->pv_flags);
3645         } while (va < va_last);
3646 }
3647
3648 static void
3649 pmap_pv_promote_section(pmap_t pmap, vm_offset_t va, vm_paddr_t pa)
3650 {
3651         struct md_page *pvh;
3652         pv_entry_t pv;
3653         vm_offset_t va_last;
3654         vm_page_t m;
3655
3656         rw_assert(&pvh_global_lock, RA_WLOCKED);
3657         KASSERT((pa & L1_S_OFFSET) == 0,
3658             ("pmap_pv_promote_section: pa is not 1mpage aligned"));
3659
3660         /*
3661          * Transfer the first page's pv entry for this mapping to the
3662          * 1mpage's pv list.  Aside from avoiding the cost of a call
3663          * to get_pv_entry(), a transfer avoids the possibility that
3664          * get_pv_entry() calls pmap_pv_reclaim() and that pmap_pv_reclaim()
3665          * removes one of the mappings that is being promoted.
3666          */
3667         m = PHYS_TO_VM_PAGE(pa);
3668         va = trunc_1mpage(va);
3669         pv = pmap_pvh_remove(&m->md, pmap, va);
3670         KASSERT(pv != NULL, ("pmap_pv_promote_section: pv not found"));
3671         pvh = pa_to_pvh(pa);
3672         TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_list);
3673         /* Free the remaining pv entries in the newly mapped section pages */
3674         va_last = L2_NEXT_BUCKET(va) - PAGE_SIZE;
3675         do {
3676                 m++;
3677                 va += PAGE_SIZE;
3678                 /*
3679                  * Don't care the flags, first pv contains sufficient
3680                  * information for all of the pages so nothing is really lost.
3681                  */
3682                 pmap_pvh_free(&m->md, pmap, va);
3683         } while (va < va_last);
3684 }
3685
3686 /*
3687  * Tries to create a 1MB page mapping.  Returns TRUE if successful and
3688  * FALSE otherwise.  Fails if (1) page is unmanageg, kernel pmap or vectors
3689  * page, (2) a mapping already exists at the specified virtual address, or
3690  * (3) a pv entry cannot be allocated without reclaiming another pv entry.
3691  */
3692 static boolean_t
3693 pmap_enter_section(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
3694 {
3695         pd_entry_t *pl1pd;
3696         vm_offset_t pa;
3697         struct l2_bucket *l2b;
3698
3699         rw_assert(&pvh_global_lock, RA_WLOCKED);
3700         PMAP_ASSERT_LOCKED(pmap);
3701
3702         /* Skip kernel, vectors page and unmanaged mappings */
3703         if ((pmap == pmap_kernel()) || (L1_IDX(va) == L1_IDX(vector_page)) ||
3704             ((m->oflags & VPO_UNMANAGED) != 0)) {
3705                 CTR2(KTR_PMAP, "pmap_enter_section: failure for va %#lx"
3706                     " in pmap %p", va, pmap);
3707                 return (FALSE);
3708         }
3709         /*
3710          * Check whether this is a valid section superpage entry or
3711          * there is a l2_bucket associated with that L1 page directory.
3712          */
3713         va = trunc_1mpage(va);
3714         pl1pd = &pmap->pm_l1->l1_kva[L1_IDX(va)];
3715         l2b = pmap_get_l2_bucket(pmap, va);
3716         if ((*pl1pd & L1_S_PROTO) || (l2b != NULL)) {
3717                 CTR2(KTR_PMAP, "pmap_enter_section: failure for va %#lx"
3718                     " in pmap %p", va, pmap);
3719                 return (FALSE);
3720         }
3721         pa = VM_PAGE_TO_PHYS(m);
3722         /*
3723          * Abort this mapping if its PV entry could not be created.
3724          */
3725         if (!pmap_pv_insert_section(pmap, va, VM_PAGE_TO_PHYS(m))) {
3726                 CTR2(KTR_PMAP, "pmap_enter_section: failure for va %#lx"
3727                     " in pmap %p", va, pmap);
3728                 return (FALSE);
3729         }
3730         /*
3731          * Increment counters.
3732          */
3733         pmap->pm_stats.resident_count += L2_PTE_NUM_TOTAL;
3734         /*
3735          * Despite permissions, mark the superpage read-only.
3736          */
3737         prot &= ~VM_PROT_WRITE;
3738         /*
3739          * Map the superpage.
3740          */
3741         pmap_map_section(pmap, va, pa, prot, FALSE);
3742
3743         pmap_section_mappings++;
3744         CTR2(KTR_PMAP, "pmap_enter_section: success for va %#lx"
3745             " in pmap %p", va, pmap);
3746         return (TRUE);
3747 }
3748
3749 /*
3750  * pmap_remove_section: do the things to unmap a superpage in a process
3751  */
3752 static void
3753 pmap_remove_section(pmap_t pmap, vm_offset_t sva)
3754 {
3755         struct md_page *pvh;
3756         struct l2_bucket *l2b;
3757         pd_entry_t *pl1pd, l1pd;
3758         vm_offset_t eva, va;
3759         vm_page_t m;
3760
3761         PMAP_ASSERT_LOCKED(pmap);
3762         if ((pmap == pmap_kernel()) || (L1_IDX(sva) == L1_IDX(vector_page)))
3763                 return;
3764
3765         KASSERT((sva & L1_S_OFFSET) == 0,
3766             ("pmap_remove_section: sva is not 1mpage aligned"));
3767
3768         pl1pd = &pmap->pm_l1->l1_kva[L1_IDX(sva)];
3769         l1pd = *pl1pd;
3770
3771         m = PHYS_TO_VM_PAGE(l1pd & L1_S_FRAME);
3772         KASSERT((m != NULL && ((m->oflags & VPO_UNMANAGED) == 0)),
3773             ("pmap_remove_section: no corresponding vm_page or "
3774             "page unmanaged"));
3775
3776         pmap->pm_stats.resident_count -= L2_PTE_NUM_TOTAL;
3777         pvh = pa_to_pvh(l1pd & L1_S_FRAME);
3778         pmap_pvh_free(pvh, pmap, sva);
3779         eva = L2_NEXT_BUCKET(sva);
3780         for (va = sva, m = PHYS_TO_VM_PAGE(l1pd & L1_S_FRAME);
3781             va < eva; va += PAGE_SIZE, m++) {
3782                 /*
3783                  * Mark base pages referenced but skip marking them dirty.
3784                  * If the superpage is writeable, hence all base pages were
3785                  * already marked as dirty in pmap_fault_fixup() before
3786                  * promotion. Reference bit however, might not have been set
3787                  * for each base page when the superpage was created at once,
3788                  * not as a result of promotion.
3789                  */
3790                 if (L1_S_REFERENCED(l1pd))
3791                         vm_page_aflag_set(m, PGA_REFERENCED);
3792                 if (TAILQ_EMPTY(&m->md.pv_list) &&
3793                     TAILQ_EMPTY(&pvh->pv_list))
3794                         vm_page_aflag_clear(m, PGA_WRITEABLE);
3795         }
3796
3797         l2b = pmap_get_l2_bucket(pmap, sva);
3798         if (l2b != NULL) {
3799                 KASSERT(l2b->l2b_occupancy == L2_PTE_NUM_TOTAL,
3800                     ("pmap_remove_section: l2_bucket occupancy error"));
3801                 pmap_free_l2_bucket(pmap, l2b, L2_PTE_NUM_TOTAL);
3802         }
3803         /* Now invalidate L1 slot */
3804         *pl1pd = 0;
3805         PTE_SYNC(pl1pd);
3806         if (L1_S_EXECUTABLE(l1pd))
3807                 cpu_tlb_flushID_SE(sva);
3808         else
3809                 cpu_tlb_flushD_SE(sva);
3810         cpu_cpwait();
3811 }
3812
3813 /*
3814  * Tries to promote the 256, contiguous 4KB page mappings that are
3815  * within a single l2_bucket to a single 1MB section mapping.
3816  * For promotion to occur, two conditions must be met: (1) the 4KB page
3817  * mappings must map aligned, contiguous physical memory and (2) the 4KB page
3818  * mappings must have identical characteristics.
3819  */
3820 static void
3821 pmap_promote_section(pmap_t pmap, vm_offset_t va)
3822 {
3823         pt_entry_t *firstptep, firstpte, oldpte, pa, *pte;
3824         vm_page_t m, oldm;
3825         vm_offset_t first_va, old_va;
3826         struct l2_bucket *l2b = NULL;
3827         vm_prot_t prot;
3828         struct pv_entry *pve, *first_pve;
3829
3830         PMAP_ASSERT_LOCKED(pmap);
3831
3832         prot = VM_PROT_ALL;
3833         /*
3834          * Skip promoting kernel pages. This is justified by following:
3835          * 1. Kernel is already mapped using section mappings in each pmap
3836          * 2. Managed mappings within the kernel are not to be promoted anyway
3837          */
3838         if (pmap == pmap_kernel()) {
3839                 pmap_section_p_failures++;
3840                 CTR2(KTR_PMAP, "pmap_promote_section: failure for va %#x"
3841                     " in pmap %p", va, pmap);
3842                 return;
3843         }
3844         /* Do not attemp to promote vectors pages */
3845         if (L1_IDX(va) == L1_IDX(vector_page)) {
3846                 pmap_section_p_failures++;
3847                 CTR2(KTR_PMAP, "pmap_promote_section: failure for va %#x"
3848                     " in pmap %p", va, pmap);
3849                 return;
3850         }
3851         /*
3852          * Examine the first PTE in the specified l2_bucket. Abort if this PTE
3853          * is either invalid, unused, or does not map the first 4KB physical
3854          * page within 1MB page.
3855          */
3856         first_va = trunc_1mpage(va);
3857         l2b = pmap_get_l2_bucket(pmap, first_va);
3858         KASSERT(l2b != NULL, ("pmap_promote_section: trying to promote "
3859             "not existing l2 bucket"));
3860         firstptep = &l2b->l2b_kva[0];
3861
3862         firstpte = *firstptep;
3863         if ((l2pte_pa(firstpte) & L1_S_OFFSET) != 0) {
3864                 pmap_section_p_failures++;
3865                 CTR2(KTR_PMAP, "pmap_promote_section: failure for va %#x"
3866                     " in pmap %p", va, pmap);
3867                 return;
3868         }
3869
3870         if ((firstpte & (L2_S_PROTO | L2_S_REF)) != (L2_S_PROTO | L2_S_REF)) {
3871                 pmap_section_p_failures++;
3872                 CTR2(KTR_PMAP, "pmap_promote_section: failure for va %#x"
3873                     " in pmap %p", va, pmap);
3874                 return;
3875         }
3876         /*
3877          * ARM uses pv_entry to mark particular mapping WIRED so don't promote
3878          * unmanaged pages since it is impossible to determine, whether the
3879          * page is wired or not if there is no corresponding pv_entry.
3880          */
3881         m = PHYS_TO_VM_PAGE(l2pte_pa(firstpte));
3882         if (m && ((m->oflags & VPO_UNMANAGED) != 0)) {
3883                 pmap_section_p_failures++;
3884                 CTR2(KTR_PMAP, "pmap_promote_section: failure for va %#x"
3885                     " in pmap %p", va, pmap);
3886                 return;
3887         }
3888         first_pve = pmap_find_pv(&m->md, pmap, first_va);
3889         /*
3890          * PTE is modified only on write due to modified bit
3891          * emulation. If the entry is referenced and writable
3892          * then it is modified and we don't clear write enable.
3893          * Otherwise, writing is disabled in PTE anyway and
3894          * we just configure protections for the section mapping
3895          * that is going to be created.
3896          */
3897         if ((first_pve->pv_flags & PVF_WRITE) != 0) {
3898                 if (!L2_S_WRITABLE(firstpte)) {
3899                         first_pve->pv_flags &= ~PVF_WRITE;
3900                         prot &= ~VM_PROT_WRITE;
3901                 }
3902         } else
3903                 prot &= ~VM_PROT_WRITE;
3904
3905         if (!L2_S_EXECUTABLE(firstpte))
3906                 prot &= ~VM_PROT_EXECUTE;
3907
3908         /*
3909          * Examine each of the other PTEs in the specified l2_bucket.
3910          * Abort if this PTE maps an unexpected 4KB physical page or
3911          * does not have identical characteristics to the first PTE.
3912          */
3913         pa = l2pte_pa(firstpte) + ((L2_PTE_NUM_TOTAL - 1) * PAGE_SIZE);
3914         old_va = L2_NEXT_BUCKET(first_va) - PAGE_SIZE;
3915
3916         for (pte = (firstptep + L2_PTE_NUM_TOTAL - 1); pte > firstptep; pte--) {
3917                 oldpte = *pte;
3918                 if (l2pte_pa(oldpte) != pa) {
3919                         pmap_section_p_failures++;
3920                         CTR2(KTR_PMAP, "pmap_promote_section: failure for "
3921                             "va %#x in pmap %p", va, pmap);
3922                         return;
3923                 }
3924                 if ((oldpte & L2_S_PROMOTE) != (firstpte & L2_S_PROMOTE)) {
3925                         pmap_section_p_failures++;
3926                         CTR2(KTR_PMAP, "pmap_promote_section: failure for "
3927                             "va %#x in pmap %p", va, pmap);
3928                         return;
3929                 }
3930                 oldm = PHYS_TO_VM_PAGE(l2pte_pa(oldpte));
3931                 if (oldm && ((oldm->oflags & VPO_UNMANAGED) != 0)) {
3932                         pmap_section_p_failures++;
3933                         CTR2(KTR_PMAP, "pmap_promote_section: failure for "
3934                             "va %#x in pmap %p", va, pmap);
3935                         return;
3936                 }
3937
3938                 pve = pmap_find_pv(&oldm->md, pmap, old_va);
3939                 if (pve == NULL) {
3940                         pmap_section_p_failures++;
3941                         CTR2(KTR_PMAP, "pmap_promote_section: failure for "
3942                             "va %#x old_va  %x - no pve", va, old_va);
3943                         return;
3944                 }
3945
3946                 if (!L2_S_WRITABLE(oldpte) && (pve->pv_flags & PVF_WRITE))
3947                         pve->pv_flags &= ~PVF_WRITE;
3948                 if (pve->pv_flags != first_pve->pv_flags) {
3949                         pmap_section_p_failures++;
3950                         CTR2(KTR_PMAP, "pmap_promote_section: failure for "
3951                             "va %#x in pmap %p", va, pmap);
3952                         return;
3953                 }
3954
3955                 old_va -= PAGE_SIZE;
3956                 pa -= PAGE_SIZE;
3957         }
3958         /*
3959          * Promote the pv entries.
3960          */
3961         pmap_pv_promote_section(pmap, first_va, l2pte_pa(firstpte));
3962         /*
3963          * Map the superpage.
3964          */
3965         pmap_map_section(pmap, first_va, l2pte_pa(firstpte), prot, TRUE);
3966         /*
3967          * Invalidate all possible TLB mappings for small
3968          * pages within the newly created superpage.
3969          * Rely on the first PTE's attributes since they
3970          * have to be consistent across all of the base pages
3971          * within the superpage. If page is not executable it
3972          * is at least referenced.
3973          * The fastest way to do that is to invalidate whole
3974          * TLB at once instead of executing 256 CP15 TLB
3975          * invalidations by single entry. TLBs usually maintain
3976          * several dozen entries so loss of unrelated entries is
3977          * still a less agresive approach.
3978          */
3979         if (L2_S_EXECUTABLE(firstpte))
3980                 cpu_tlb_flushID();
3981         else
3982                 cpu_tlb_flushD();
3983         cpu_cpwait();
3984
3985         pmap_section_promotions++;
3986         CTR2(KTR_PMAP, "pmap_promote_section: success for va %#x"
3987             " in pmap %p", first_va, pmap);
3988 }
3989
3990 /*
3991  * Fills a l2_bucket with mappings to consecutive physical pages.
3992  */
3993 static void
3994 pmap_fill_l2b(struct l2_bucket *l2b, pt_entry_t newpte)
3995 {
3996         pt_entry_t *ptep;
3997         int i;
3998
3999         for (i = 0; i < L2_PTE_NUM_TOTAL; i++) {
4000                 ptep = &l2b->l2b_kva[i];
4001                 *ptep = newpte;
4002                 PTE_SYNC(ptep);
4003
4004                 newpte += PAGE_SIZE;
4005         }
4006
4007         l2b->l2b_occupancy = L2_PTE_NUM_TOTAL;
4008 }
4009
4010 /*
4011  * Tries to demote a 1MB section mapping. If demotion fails, the
4012  * 1MB section mapping is invalidated.
4013  */
4014 static boolean_t
4015 pmap_demote_section(pmap_t pmap, vm_offset_t va)
4016 {
4017         struct l2_bucket *l2b;
4018         struct pv_entry *l1pdpve;
4019         struct md_page *pvh;
4020         pd_entry_t *pl1pd, l1pd, newl1pd;
4021         pt_entry_t *firstptep, newpte;
4022         vm_offset_t pa;
4023         vm_page_t m;
4024
4025         PMAP_ASSERT_LOCKED(pmap);
4026         /*
4027          * According to assumptions described in pmap_promote_section,
4028          * kernel is and always should be mapped using 1MB section mappings.
4029          * What more, managed kernel pages were not to be promoted.
4030          */
4031         KASSERT(pmap != pmap_kernel() && L1_IDX(va) != L1_IDX(vector_page),
4032             ("pmap_demote_section: forbidden section mapping"));
4033
4034         va = trunc_1mpage(va);
4035         pl1pd = &pmap->pm_l1->l1_kva[L1_IDX(va)];
4036         l1pd = *pl1pd;
4037         KASSERT((l1pd & L1_TYPE_MASK) == L1_S_PROTO,
4038             ("pmap_demote_section: not section or invalid section"));
4039
4040         pa = l1pd & L1_S_FRAME;
4041         m = PHYS_TO_VM_PAGE(pa);
4042         KASSERT((m != NULL && (m->oflags & VPO_UNMANAGED) == 0),
4043             ("pmap_demote_section: no vm_page for selected superpage or"
4044              "unmanaged"));
4045
4046         pvh = pa_to_pvh(pa);
4047         l1pdpve = pmap_find_pv(pvh, pmap, va);
4048         KASSERT(l1pdpve != NULL, ("pmap_demote_section: no pv entry for "
4049             "managed page"));
4050
4051         l2b = pmap_get_l2_bucket(pmap, va);
4052         if (l2b == NULL) {
4053                 KASSERT((l1pdpve->pv_flags & PVF_WIRED) == 0,
4054                     ("pmap_demote_section: No l2_bucket for wired mapping"));
4055                 /*
4056                  * Invalidate the 1MB section mapping and return
4057                  * "failure" if the mapping was never accessed or the
4058                  * allocation of the new l2_bucket fails.
4059                  */
4060                 if (!L1_S_REFERENCED(l1pd) ||
4061                     (l2b = pmap_alloc_l2_bucket(pmap, va)) == NULL) {
4062                         /* Unmap and invalidate superpage. */
4063                         pmap_remove_section(pmap, trunc_1mpage(va));
4064                         CTR2(KTR_PMAP, "pmap_demote_section: failure for "
4065                             "va %#x in pmap %p", va, pmap);
4066                         return (FALSE);
4067                 }
4068         }
4069
4070         /*
4071          * Now we should have corresponding l2_bucket available.
4072          * Let's process it to recreate 256 PTEs for each base page
4073          * within superpage.
4074          */
4075         newpte = pa | L1_S_DEMOTE(l1pd);
4076         if (m->md.pv_memattr != VM_MEMATTR_UNCACHEABLE)
4077                 newpte |= pte_l2_s_cache_mode;
4078
4079         /*
4080          * If the l2_bucket is new, initialize it.
4081          */
4082         if (l2b->l2b_occupancy == 0)
4083                 pmap_fill_l2b(l2b, newpte);
4084         else {
4085                 firstptep = &l2b->l2b_kva[0];
4086                 KASSERT(l2pte_pa(*firstptep) == (pa),
4087                     ("pmap_demote_section: firstpte and newpte map different "
4088                      "physical addresses"));
4089                 /*
4090                  * If the mapping has changed attributes, update the page table
4091                  * entries.
4092                  */
4093                 if ((*firstptep & L2_S_PROMOTE) != (L1_S_DEMOTE(l1pd)))
4094                         pmap_fill_l2b(l2b, newpte);
4095         }
4096         /* Demote PV entry */
4097         pmap_pv_demote_section(pmap, va, pa);
4098
4099         /* Now fix-up L1 */
4100         newl1pd = l2b->l2b_phys | L1_C_DOM(pmap->pm_domain) | L1_C_PROTO;
4101         *pl1pd = newl1pd;
4102         PTE_SYNC(pl1pd);
4103         /* Invalidate old TLB mapping */
4104         if (L1_S_EXECUTABLE(l1pd))
4105                 cpu_tlb_flushID_SE(va);
4106         else if (L1_S_REFERENCED(l1pd))
4107                 cpu_tlb_flushD_SE(va);
4108         cpu_cpwait();
4109
4110         pmap_section_demotions++;
4111         CTR2(KTR_PMAP, "pmap_demote_section: success for va %#x"
4112             " in pmap %p", va, pmap);
4113         return (TRUE);
4114 }
4115
4116 /***************************************************
4117  * page management routines.
4118  ***************************************************/
4119
4120 /*
4121  * We are in a serious low memory condition.  Resort to
4122  * drastic measures to free some pages so we can allocate
4123  * another pv entry chunk.
4124  */
4125 static vm_page_t
4126 pmap_pv_reclaim(pmap_t locked_pmap)
4127 {
4128         struct pch newtail;
4129         struct pv_chunk *pc;
4130         struct l2_bucket *l2b = NULL;
4131         pmap_t pmap;
4132         pd_entry_t *pl1pd;
4133         pt_entry_t *ptep;
4134         pv_entry_t pv;
4135         vm_offset_t va;
4136         vm_page_t free, m, m_pc;
4137         uint32_t inuse;
4138         int bit, field, freed, idx;
4139
4140         PMAP_ASSERT_LOCKED(locked_pmap);
4141         pmap = NULL;
4142         free = m_pc = NULL;
4143         TAILQ_INIT(&newtail);
4144         while ((pc = TAILQ_FIRST(&pv_chunks)) != NULL && (pv_vafree == 0 ||
4145             free == NULL)) {
4146                 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
4147                 if (pmap != pc->pc_pmap) {
4148                         if (pmap != NULL) {
4149                                 cpu_tlb_flushID();
4150                                 cpu_cpwait();
4151                                 if (pmap != locked_pmap)
4152                                         PMAP_UNLOCK(pmap);
4153                         }
4154                         pmap = pc->pc_pmap;
4155                         /* Avoid deadlock and lock recursion. */
4156                         if (pmap > locked_pmap)
4157                                 PMAP_LOCK(pmap);
4158                         else if (pmap != locked_pmap && !PMAP_TRYLOCK(pmap)) {
4159                                 pmap = NULL;
4160                                 TAILQ_INSERT_TAIL(&newtail, pc, pc_lru);
4161                                 continue;
4162                         }
4163                 }
4164
4165                 /*
4166                  * Destroy every non-wired, 4 KB page mapping in the chunk.
4167                  */
4168                 freed = 0;
4169                 for (field = 0; field < _NPCM; field++) {
4170                         for (inuse = ~pc->pc_map[field] & pc_freemask[field];
4171                             inuse != 0; inuse &= ~(1UL << bit)) {
4172                                 bit = ffs(inuse) - 1;
4173                                 idx = field * sizeof(inuse) * NBBY + bit;
4174                                 pv = &pc->pc_pventry[idx];
4175                                 va = pv->pv_va;
4176
4177                                 pl1pd = &pmap->pm_l1->l1_kva[L1_IDX(va)];
4178                                 if ((*pl1pd & L1_TYPE_MASK) == L1_S_PROTO)
4179                                         continue;
4180                                 if (pv->pv_flags & PVF_WIRED)
4181                                         continue;
4182
4183                                 l2b = pmap_get_l2_bucket(pmap, va);
4184                                 KASSERT(l2b != NULL, ("No l2 bucket"));
4185                                 ptep = &l2b->l2b_kva[l2pte_index(va)];
4186                                 m = PHYS_TO_VM_PAGE(l2pte_pa(*ptep));
4187                                 KASSERT((vm_offset_t)m >= KERNBASE,
4188                                     ("Trying to access non-existent page "
4189                                      "va %x pte %x", va, *ptep));
4190                                 *ptep = 0;
4191                                 PTE_SYNC(ptep);
4192                                 TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
4193                                 if (TAILQ_EMPTY(&m->md.pv_list))
4194                                         vm_page_aflag_clear(m, PGA_WRITEABLE);
4195                                 pc->pc_map[field] |= 1UL << bit;
4196                                 freed++;
4197                         }
4198                 }
4199
4200                 if (freed == 0) {
4201                         TAILQ_INSERT_TAIL(&newtail, pc, pc_lru);
4202                         continue;
4203                 }
4204                 /* Every freed mapping is for a 4 KB page. */
4205                 pmap->pm_stats.resident_count -= freed;
4206                 PV_STAT(pv_entry_frees += freed);
4207                 PV_STAT(pv_entry_spare += freed);
4208                 pv_entry_count -= freed;
4209                 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
4210                 for (field = 0; field < _NPCM; field++)
4211                         if (pc->pc_map[field] != pc_freemask[field]) {
4212                                 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc,
4213                                     pc_list);
4214                                 TAILQ_INSERT_TAIL(&newtail, pc, pc_lru);
4215
4216                                 /*
4217                                  * One freed pv entry in locked_pmap is
4218                                  * sufficient.
4219                                  */
4220                                 if (pmap == locked_pmap)
4221                                         goto out;
4222                                 break;
4223                         }
4224                 if (field == _NPCM) {
4225                         PV_STAT(pv_entry_spare -= _NPCPV);
4226                         PV_STAT(pc_chunk_count--);
4227                         PV_STAT(pc_chunk_frees++);
4228                         /* Entire chunk is free; return it. */
4229                         m_pc = PHYS_TO_VM_PAGE(pmap_kextract((vm_offset_t)pc));
4230                         pmap_qremove((vm_offset_t)pc, 1);
4231                         pmap_ptelist_free(&pv_vafree, (vm_offset_t)pc);
4232                         break;
4233                 }
4234         }
4235 out:
4236         TAILQ_CONCAT(&pv_chunks, &newtail, pc_lru);
4237         if (pmap != NULL) {
4238                 cpu_tlb_flushID();
4239                 cpu_cpwait();
4240                 if (pmap != locked_pmap)
4241                         PMAP_UNLOCK(pmap);
4242         }
4243         return (m_pc);
4244 }
4245
4246 /*
4247  * free the pv_entry back to the free list
4248  */
4249 static void
4250 pmap_free_pv_entry(pmap_t pmap, pv_entry_t pv)
4251 {
4252         struct pv_chunk *pc;
4253         int bit, field, idx;
4254
4255         rw_assert(&pvh_global_lock, RA_WLOCKED);
4256         PMAP_ASSERT_LOCKED(pmap);
4257         PV_STAT(pv_entry_frees++);
4258         PV_STAT(pv_entry_spare++);
4259         pv_entry_count--;
4260         pc = pv_to_chunk(pv);
4261         idx = pv - &pc->pc_pventry[0];
4262         field = idx / (sizeof(u_long) * NBBY);
4263         bit = idx % (sizeof(u_long) * NBBY);
4264         pc->pc_map[field] |= 1ul << bit;
4265         for (idx = 0; idx < _NPCM; idx++)
4266                 if (pc->pc_map[idx] != pc_freemask[idx]) {
4267                         /*
4268                          * 98% of the time, pc is already at the head of the
4269                          * list.  If it isn't already, move it to the head.
4270                          */
4271                         if (__predict_false(TAILQ_FIRST(&pmap->pm_pvchunk) !=
4272                             pc)) {
4273                                 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
4274                                 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc,
4275                                     pc_list);
4276                         }
4277                         return;
4278                 }
4279         TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
4280         pmap_free_pv_chunk(pc);
4281 }
4282
4283 static void
4284 pmap_free_pv_chunk(struct pv_chunk *pc)
4285 {
4286         vm_page_t m;
4287
4288         TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
4289         PV_STAT(pv_entry_spare -= _NPCPV);
4290         PV_STAT(pc_chunk_count--);
4291         PV_STAT(pc_chunk_frees++);
4292         /* entire chunk is free, return it */
4293         m = PHYS_TO_VM_PAGE(pmap_kextract((vm_offset_t)pc));
4294         pmap_qremove((vm_offset_t)pc, 1);
4295         vm_page_unwire(m, PQ_NONE);
4296         vm_page_free(m);
4297         pmap_ptelist_free(&pv_vafree, (vm_offset_t)pc);
4298
4299 }
4300
4301 static pv_entry_t
4302 pmap_get_pv_entry(pmap_t pmap, boolean_t try)
4303 {
4304         static const struct timeval printinterval = { 60, 0 };
4305         static struct timeval lastprint;
4306         struct pv_chunk *pc;
4307         pv_entry_t pv;
4308         vm_page_t m;
4309         int bit, field, idx;
4310
4311         rw_assert(&pvh_global_lock, RA_WLOCKED);
4312         PMAP_ASSERT_LOCKED(pmap);
4313         PV_STAT(pv_entry_allocs++);
4314         pv_entry_count++;
4315
4316         if (pv_entry_count > pv_entry_high_water)
4317                 if (ratecheck(&lastprint, &printinterval))
4318                         printf("%s: Approaching the limit on PV entries.\n",
4319                             __func__);
4320 retry:
4321         pc = TAILQ_FIRST(&pmap->pm_pvchunk);
4322         if (pc != NULL) {
4323                 for (field = 0; field < _NPCM; field++) {
4324                         if (pc->pc_map[field]) {
4325                                 bit = ffs(pc->pc_map[field]) - 1;
4326                                 break;
4327                         }
4328                 }
4329                 if (field < _NPCM) {
4330                         idx = field * sizeof(pc->pc_map[field]) * NBBY + bit;
4331                         pv = &pc->pc_pventry[idx];
4332                         pc->pc_map[field] &= ~(1ul << bit);
4333                         /* If this was the last item, move it to tail */
4334                         for (field = 0; field < _NPCM; field++)
4335                                 if (pc->pc_map[field] != 0) {
4336                                         PV_STAT(pv_entry_spare--);
4337                                         return (pv);    /* not full, return */
4338                                 }
4339                         TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
4340                         TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
4341                         PV_STAT(pv_entry_spare--);
4342                         return (pv);
4343                 }
4344         }
4345         /*
4346          * Access to the ptelist "pv_vafree" is synchronized by the pvh
4347          * global lock.  If "pv_vafree" is currently non-empty, it will
4348          * remain non-empty until pmap_ptelist_alloc() completes.
4349          */
4350         if (pv_vafree == 0 || (m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
4351             VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
4352                 if (try) {
4353                         pv_entry_count--;
4354                         PV_STAT(pc_chunk_tryfail++);
4355                         return (NULL);
4356                 }
4357                 m = pmap_pv_reclaim(pmap);
4358                 if (m == NULL)
4359                         goto retry;
4360         }
4361         PV_STAT(pc_chunk_count++);
4362         PV_STAT(pc_chunk_allocs++);
4363         pc = (struct pv_chunk *)pmap_ptelist_alloc(&pv_vafree);
4364         pmap_qenter((vm_offset_t)pc, &m, 1);
4365         pc->pc_pmap = pmap;
4366         pc->pc_map[0] = pc_freemask[0] & ~1ul;  /* preallocated bit 0 */
4367         for (field = 1; field < _NPCM; field++)
4368                 pc->pc_map[field] = pc_freemask[field];
4369         TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
4370         pv = &pc->pc_pventry[0];
4371         TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
4372         PV_STAT(pv_entry_spare += _NPCPV - 1);
4373         return (pv);
4374 }
4375
4376 /*
4377  *      Remove the given range of addresses from the specified map.
4378  *
4379  *      It is assumed that the start and end are properly
4380  *      rounded to the page size.
4381  */
4382 #define PMAP_REMOVE_CLEAN_LIST_SIZE     3
4383 void
4384 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
4385 {
4386         struct l2_bucket *l2b;
4387         vm_offset_t next_bucket;
4388         pd_entry_t l1pd;
4389         pt_entry_t *ptep;
4390         u_int total;
4391         u_int mappings, is_exec, is_refd;
4392         int flushall = 0;
4393
4394
4395         /*
4396          * we lock in the pmap => pv_head direction
4397          */
4398
4399         rw_wlock(&pvh_global_lock);
4400         PMAP_LOCK(pmap);
4401         total = 0;
4402         while (sva < eva) {
4403                 next_bucket = L2_NEXT_BUCKET(sva);
4404
4405                 /*
4406                  * Check for large page.
4407                  */
4408                 l1pd = pmap->pm_l1->l1_kva[L1_IDX(sva)];
4409                 if ((l1pd & L1_TYPE_MASK) == L1_S_PROTO) {
4410                         KASSERT((l1pd & L1_S_DOM_MASK) !=
4411                             L1_S_DOM(PMAP_DOMAIN_KERNEL), ("pmap_remove: "
4412                             "Trying to remove kernel section mapping"));
4413                         /*
4414                          * Are we removing the entire large page?  If not,
4415                          * demote the mapping and fall through.
4416                          */
4417                         if (sva + L1_S_SIZE == next_bucket &&
4418                             eva >= next_bucket) {
4419                                 pmap_remove_section(pmap, sva);
4420                                 sva = next_bucket;
4421                                 continue;
4422                         } else if (!pmap_demote_section(pmap, sva)) {
4423                                 /* The large page mapping was destroyed. */
4424                                 sva = next_bucket;
4425                                 continue;
4426                         }
4427                 }
4428                 /*
4429                  * Do one L2 bucket's worth at a time.
4430                  */
4431                 if (next_bucket > eva)
4432                         next_bucket = eva;
4433
4434                 l2b = pmap_get_l2_bucket(pmap, sva);
4435                 if (l2b == NULL) {
4436                         sva = next_bucket;
4437                         continue;
4438                 }
4439
4440                 ptep = &l2b->l2b_kva[l2pte_index(sva)];
4441                 mappings = 0;
4442
4443                 while (sva < next_bucket) {
4444                         struct vm_page *m;
4445                         pt_entry_t pte;
4446                         vm_paddr_t pa;
4447
4448                         pte = *ptep;
4449
4450                         if (pte == 0) {
4451                                 /*
4452                                  * Nothing here, move along
4453                                  */
4454                                 sva += PAGE_SIZE;
4455                                 ptep++;
4456                                 continue;
4457                         }
4458
4459                         pmap->pm_stats.resident_count--;
4460                         pa = l2pte_pa(pte);
4461                         is_exec = 0;
4462                         is_refd = 1;
4463
4464                         /*
4465                          * Update flags. In a number of circumstances,
4466                          * we could cluster a lot of these and do a
4467                          * number of sequential pages in one go.
4468                          */
4469                         if ((m = PHYS_TO_VM_PAGE(pa)) != NULL) {
4470                                 struct pv_entry *pve;
4471
4472                                 pve = pmap_remove_pv(m, pmap, sva);
4473                                 if (pve) {
4474                                         is_exec = PTE_BEEN_EXECD(pte);
4475                                         is_refd = PTE_BEEN_REFD(pte);
4476                                         pmap_free_pv_entry(pmap, pve);
4477                                 }
4478                         }
4479
4480                         *ptep = 0;
4481                         PTE_SYNC(ptep);
4482                         if (pmap_is_current(pmap)) {
4483                                 total++;
4484                                 if (total < PMAP_REMOVE_CLEAN_LIST_SIZE) {
4485                                         if (is_exec)
4486                                                 cpu_tlb_flushID_SE(sva);
4487                                         else if (is_refd)
4488                                                 cpu_tlb_flushD_SE(sva);
4489                                 } else if (total == PMAP_REMOVE_CLEAN_LIST_SIZE)
4490                                         flushall = 1;
4491                         }
4492
4493                         sva += PAGE_SIZE;
4494                         ptep++;
4495                         mappings++;
4496                 }
4497
4498                 pmap_free_l2_bucket(pmap, l2b, mappings);
4499         }
4500
4501         rw_wunlock(&pvh_global_lock);
4502         if (flushall)
4503                 cpu_tlb_flushID();
4504         cpu_cpwait();
4505
4506         PMAP_UNLOCK(pmap);
4507 }
4508
4509 /*
4510  * pmap_zero_page()
4511  *
4512  * Zero a given physical page by mapping it at a page hook point.
4513  * In doing the zero page op, the page we zero is mapped cachable, as with
4514  * StrongARM accesses to non-cached pages are non-burst making writing
4515  * _any_ bulk data very slow.
4516  */
4517 static void
4518 pmap_zero_page_gen(vm_page_t m, int off, int size)
4519 {
4520         struct czpages *czp;
4521
4522         KASSERT(TAILQ_EMPTY(&m->md.pv_list),
4523             ("pmap_zero_page_gen: page has mappings"));
4524
4525         vm_paddr_t phys = VM_PAGE_TO_PHYS(m);
4526
4527         sched_pin();
4528         czp = &cpu_czpages[PCPU_GET(cpuid)];
4529         mtx_lock(&czp->lock);
4530
4531         /*
4532          * Hook in the page, zero it.
4533          */
4534         *czp->dstptep = L2_S_PROTO | phys | pte_l2_s_cache_mode | L2_S_REF;
4535         pmap_set_prot(czp->dstptep, VM_PROT_WRITE, 0);
4536         PTE_SYNC(czp->dstptep);
4537         cpu_tlb_flushD_SE(czp->dstva);
4538         cpu_cpwait();
4539
4540         if (off || size != PAGE_SIZE)
4541                 bzero((void *)(czp->dstva + off), size);
4542         else
4543                 bzero_page(czp->dstva);
4544
4545         /*
4546          * Although aliasing is not possible, if we use temporary mappings with
4547          * memory that will be mapped later as non-cached or with write-through
4548          * caches, we might end up overwriting it when calling wbinv_all.  So
4549          * make sure caches are clean after the operation.
4550          */
4551         cpu_idcache_wbinv_range(czp->dstva, size);
4552         pmap_l2cache_wbinv_range(czp->dstva, phys, size);
4553
4554         mtx_unlock(&czp->lock);
4555         sched_unpin();
4556 }
4557
4558 /*
4559  *      pmap_zero_page zeros the specified hardware page by mapping
4560  *      the page into KVM and using bzero to clear its contents.
4561  */
4562 void
4563 pmap_zero_page(vm_page_t m)
4564 {
4565         pmap_zero_page_gen(m, 0, PAGE_SIZE);
4566 }
4567
4568
4569 /*
4570  *      pmap_zero_page_area zeros the specified hardware page by mapping
4571  *      the page into KVM and using bzero to clear its contents.
4572  *
4573  *      off and size may not cover an area beyond a single hardware page.
4574  */
4575 void
4576 pmap_zero_page_area(vm_page_t m, int off, int size)
4577 {
4578
4579         pmap_zero_page_gen(m, off, size);
4580 }
4581
4582
4583 /*
4584  *      pmap_zero_page_idle zeros the specified hardware page by mapping
4585  *      the page into KVM and using bzero to clear its contents.  This
4586  *      is intended to be called from the vm_pagezero process only and
4587  *      outside of Giant.
4588  */
4589 void
4590 pmap_zero_page_idle(vm_page_t m)
4591 {
4592
4593         pmap_zero_page(m);
4594 }
4595
4596 /*
4597  *      pmap_copy_page copies the specified (machine independent)
4598  *      page by mapping the page into virtual memory and using
4599  *      bcopy to copy the page, one machine dependent page at a
4600  *      time.
4601  */
4602
4603 /*
4604  * pmap_copy_page()
4605  *
4606  * Copy one physical page into another, by mapping the pages into
4607  * hook points. The same comment regarding cachability as in
4608  * pmap_zero_page also applies here.
4609  */
4610 void
4611 pmap_copy_page_generic(vm_paddr_t src, vm_paddr_t dst)
4612 {
4613         struct czpages *czp;
4614
4615         sched_pin();
4616         czp = &cpu_czpages[PCPU_GET(cpuid)];
4617         mtx_lock(&czp->lock);
4618
4619         /*
4620          * Map the pages into the page hook points, copy them, and purge the
4621          * cache for the appropriate page.
4622          */
4623         *czp->srcptep = L2_S_PROTO | src | pte_l2_s_cache_mode | L2_S_REF;
4624         pmap_set_prot(czp->srcptep, VM_PROT_READ, 0);
4625         PTE_SYNC(czp->srcptep);
4626         cpu_tlb_flushD_SE(czp->srcva);
4627         *czp->dstptep = L2_S_PROTO | dst | pte_l2_s_cache_mode | L2_S_REF;
4628         pmap_set_prot(czp->dstptep, VM_PROT_READ | VM_PROT_WRITE, 0);
4629         PTE_SYNC(czp->dstptep);
4630         cpu_tlb_flushD_SE(czp->dstva);
4631         cpu_cpwait();
4632
4633         bcopy_page(czp->srcva, czp->dstva);
4634
4635         /*
4636          * Although aliasing is not possible, if we use temporary mappings with
4637          * memory that will be mapped later as non-cached or with write-through
4638          * caches, we might end up overwriting it when calling wbinv_all.  So
4639          * make sure caches are clean after the operation.
4640          */
4641         cpu_idcache_wbinv_range(czp->dstva, PAGE_SIZE);
4642         pmap_l2cache_wbinv_range(czp->dstva, dst, PAGE_SIZE);
4643
4644         mtx_unlock(&czp->lock);
4645         sched_unpin();
4646 }
4647
4648 int unmapped_buf_allowed = 1;
4649
4650 void
4651 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
4652     vm_offset_t b_offset, int xfersize)
4653 {
4654         vm_page_t a_pg, b_pg;
4655         vm_offset_t a_pg_offset, b_pg_offset;
4656         int cnt;
4657         struct czpages *czp;
4658
4659         sched_pin();
4660         czp = &cpu_czpages[PCPU_GET(cpuid)];
4661         mtx_lock(&czp->lock);
4662
4663         while (xfersize > 0) {
4664                 a_pg = ma[a_offset >> PAGE_SHIFT];
4665                 a_pg_offset = a_offset & PAGE_MASK;
4666                 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
4667                 b_pg = mb[b_offset >> PAGE_SHIFT];
4668                 b_pg_offset = b_offset & PAGE_MASK;
4669                 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
4670                 *czp->srcptep = L2_S_PROTO | VM_PAGE_TO_PHYS(a_pg) |
4671                     pte_l2_s_cache_mode | L2_S_REF;
4672                 pmap_set_prot(czp->srcptep, VM_PROT_READ, 0);
4673                 PTE_SYNC(czp->srcptep);
4674                 cpu_tlb_flushD_SE(czp->srcva);
4675                 *czp->dstptep = L2_S_PROTO | VM_PAGE_TO_PHYS(b_pg) |
4676                     pte_l2_s_cache_mode | L2_S_REF;
4677                 pmap_set_prot(czp->dstptep, VM_PROT_READ | VM_PROT_WRITE, 0);
4678                 PTE_SYNC(czp->dstptep);
4679                 cpu_tlb_flushD_SE(czp->dstva);
4680                 cpu_cpwait();
4681                 bcopy((char *)czp->srcva + a_pg_offset, (char *)czp->dstva + b_pg_offset,
4682                     cnt);
4683                 cpu_idcache_wbinv_range(czp->dstva + b_pg_offset, cnt);
4684                 pmap_l2cache_wbinv_range(czp->dstva + b_pg_offset,
4685                     VM_PAGE_TO_PHYS(b_pg) + b_pg_offset, cnt);
4686                 xfersize -= cnt;
4687                 a_offset += cnt;
4688                 b_offset += cnt;
4689         }
4690
4691         mtx_unlock(&czp->lock);
4692         sched_unpin();
4693 }
4694
4695 void
4696 pmap_copy_page(vm_page_t src, vm_page_t dst)
4697 {
4698
4699         if (_arm_memcpy && PAGE_SIZE >= _min_memcpy_size &&
4700             _arm_memcpy((void *)VM_PAGE_TO_PHYS(dst),
4701             (void *)VM_PAGE_TO_PHYS(src), PAGE_SIZE, IS_PHYSICAL) == 0)
4702                 return;
4703
4704         pmap_copy_page_generic(VM_PAGE_TO_PHYS(src), VM_PAGE_TO_PHYS(dst));
4705 }
4706
4707 vm_offset_t
4708 pmap_quick_enter_page(vm_page_t m)
4709 {
4710         pt_entry_t *qmap_pte;
4711         vm_offset_t qmap_addr; 
4712
4713         critical_enter();
4714
4715         qmap_addr = PCPU_GET(qmap_addr);
4716         qmap_pte = PCPU_GET(qmap_pte);
4717
4718         KASSERT(*qmap_pte == 0, ("pmap_quick_enter_page: PTE busy"));
4719
4720         *qmap_pte = L2_S_PROTO | VM_PAGE_TO_PHYS(m) | L2_S_REF;
4721         if (m->md.pv_memattr != VM_MEMATTR_UNCACHEABLE)
4722                 *qmap_pte |= pte_l2_s_cache_mode;
4723         pmap_set_prot(qmap_pte, VM_PROT_READ | VM_PROT_WRITE, 0);
4724         PTE_SYNC(qmap_pte);
4725         cpu_tlb_flushD_SE(qmap_addr);
4726         cpu_cpwait();
4727
4728         return (qmap_addr);
4729 }
4730
4731 void
4732 pmap_quick_remove_page(vm_offset_t addr)
4733 {
4734         pt_entry_t *qmap_pte;
4735
4736         qmap_pte = PCPU_GET(qmap_pte);
4737
4738         KASSERT(addr == PCPU_GET(qmap_addr),
4739             ("pmap_quick_remove_page: invalid address"));
4740         KASSERT(*qmap_pte != 0,
4741             ("pmap_quick_remove_page: PTE not in use"));
4742
4743         cpu_idcache_wbinv_range(addr, PAGE_SIZE);
4744         pmap_l2cache_wbinv_range(addr, *qmap_pte & L2_S_FRAME, PAGE_SIZE);
4745         *qmap_pte = 0;
4746         PTE_SYNC(qmap_pte);
4747         critical_exit();
4748 }
4749
4750 /*
4751  * this routine returns true if a physical page resides
4752  * in the given pmap.
4753  */
4754 boolean_t
4755 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
4756 {
4757         struct md_page *pvh;
4758         pv_entry_t pv;
4759         int loops = 0;
4760         boolean_t rv;
4761
4762         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4763             ("pmap_page_exists_quick: page %p is not managed", m));
4764         rv = FALSE;
4765         rw_wlock(&pvh_global_lock);
4766         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
4767                 if (PV_PMAP(pv) == pmap) {
4768                         rv = TRUE;
4769                         break;
4770                 }
4771                 loops++;
4772                 if (loops >= 16)
4773                         break;
4774         }
4775         if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
4776                 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
4777                 TAILQ_FOREACH(pv, &pvh->pv_list, pv_list) {
4778                         if (PV_PMAP(pv) == pmap) {
4779                                 rv = TRUE;
4780                                 break;
4781                         }
4782                         loops++;
4783                         if (loops >= 16)
4784                                 break;
4785                 }
4786         }
4787         rw_wunlock(&pvh_global_lock);
4788         return (rv);
4789 }
4790
4791 /*
4792  *      pmap_page_wired_mappings:
4793  *
4794  *      Return the number of managed mappings to the given physical page
4795  *      that are wired.
4796  */
4797 int
4798 pmap_page_wired_mappings(vm_page_t m)
4799 {
4800         int count;
4801
4802         count = 0;
4803         if ((m->oflags & VPO_UNMANAGED) != 0)
4804                 return (count);
4805         rw_wlock(&pvh_global_lock);
4806         count = pmap_pvh_wired_mappings(&m->md, count);
4807         if ((m->flags & PG_FICTITIOUS) == 0) {
4808             count = pmap_pvh_wired_mappings(pa_to_pvh(VM_PAGE_TO_PHYS(m)),
4809                 count);
4810         }
4811         rw_wunlock(&pvh_global_lock);
4812         return (count);
4813 }
4814
4815 /*
4816  *      pmap_pvh_wired_mappings:
4817  *
4818  *      Return the updated number "count" of managed mappings that are wired.
4819  */
4820 static int
4821 pmap_pvh_wired_mappings(struct md_page *pvh, int count)
4822 {
4823         pv_entry_t pv;
4824
4825         rw_assert(&pvh_global_lock, RA_WLOCKED);
4826         TAILQ_FOREACH(pv, &pvh->pv_list, pv_list) {
4827                 if ((pv->pv_flags & PVF_WIRED) != 0)
4828                         count++;
4829         }
4830         return (count);
4831 }
4832
4833 /*
4834  * Returns TRUE if any of the given mappings were referenced and FALSE
4835  * otherwise.  Both page and section mappings are supported.
4836  */
4837 static boolean_t
4838 pmap_is_referenced_pvh(struct md_page *pvh)
4839 {
4840         struct l2_bucket *l2b;
4841         pv_entry_t pv;
4842         pd_entry_t *pl1pd;
4843         pt_entry_t *ptep;
4844         pmap_t pmap;
4845         boolean_t rv;
4846
4847         rw_assert(&pvh_global_lock, RA_WLOCKED);
4848         rv = FALSE;
4849         TAILQ_FOREACH(pv, &pvh->pv_list, pv_list) {
4850                 pmap = PV_PMAP(pv);
4851                 PMAP_LOCK(pmap);
4852                 pl1pd = &pmap->pm_l1->l1_kva[L1_IDX(pv->pv_va)];
4853                 if ((*pl1pd & L1_TYPE_MASK) == L1_S_PROTO)
4854                         rv = L1_S_REFERENCED(*pl1pd);
4855                 else {
4856                         l2b = pmap_get_l2_bucket(pmap, pv->pv_va);
4857                         ptep = &l2b->l2b_kva[l2pte_index(pv->pv_va)];
4858                         rv = L2_S_REFERENCED(*ptep);
4859                 }
4860                 PMAP_UNLOCK(pmap);
4861                 if (rv)
4862                         break;
4863         }
4864         return (rv);
4865 }
4866
4867 /*
4868  *      pmap_is_referenced:
4869  *
4870  *      Return whether or not the specified physical page was referenced
4871  *      in any physical maps.
4872  */
4873 boolean_t
4874 pmap_is_referenced(vm_page_t m)
4875 {
4876         boolean_t rv;
4877
4878         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4879             ("pmap_is_referenced: page %p is not managed", m));
4880         rw_wlock(&pvh_global_lock);
4881         rv = pmap_is_referenced_pvh(&m->md) ||
4882             ((m->flags & PG_FICTITIOUS) == 0 &&
4883             pmap_is_referenced_pvh(pa_to_pvh(VM_PAGE_TO_PHYS(m))));
4884         rw_wunlock(&pvh_global_lock);
4885         return (rv);
4886 }
4887
4888 /*
4889  *      pmap_ts_referenced:
4890  *
4891  *      Return the count of reference bits for a page, clearing all of them.
4892  */
4893 int
4894 pmap_ts_referenced(vm_page_t m)
4895 {
4896
4897         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4898             ("pmap_ts_referenced: page %p is not managed", m));
4899         return (pmap_clearbit(m, PVF_REF));
4900 }
4901
4902 /*
4903  * Returns TRUE if any of the given mappings were used to modify
4904  * physical memory. Otherwise, returns FALSE. Both page and 1MB section
4905  * mappings are supported.
4906  */
4907 static boolean_t
4908 pmap_is_modified_pvh(struct md_page *pvh)
4909 {
4910         pd_entry_t *pl1pd;
4911         struct l2_bucket *l2b;
4912         pv_entry_t pv;
4913         pt_entry_t *ptep;
4914         pmap_t pmap;
4915         boolean_t rv;
4916
4917         rw_assert(&pvh_global_lock, RA_WLOCKED);
4918         rv = FALSE;
4919
4920         TAILQ_FOREACH(pv, &pvh->pv_list, pv_list) {
4921                 pmap = PV_PMAP(pv);
4922                 PMAP_LOCK(pmap);
4923                 pl1pd = &pmap->pm_l1->l1_kva[L1_IDX(pv->pv_va)];
4924                 if ((*pl1pd & L1_TYPE_MASK) == L1_S_PROTO)
4925                         rv = L1_S_WRITABLE(*pl1pd);
4926                 else {
4927                         l2b = pmap_get_l2_bucket(pmap, pv->pv_va);
4928                         ptep = &l2b->l2b_kva[l2pte_index(pv->pv_va)];
4929                         rv = L2_S_WRITABLE(*ptep);
4930                 }
4931                 PMAP_UNLOCK(pmap);
4932                 if (rv)
4933                         break;
4934         }
4935
4936         return (rv);
4937 }
4938
4939 boolean_t
4940 pmap_is_modified(vm_page_t m)
4941 {
4942         boolean_t rv;
4943
4944         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4945             ("pmap_is_modified: page %p is not managed", m));
4946         /*
4947          * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
4948          * concurrently set while the object is locked.  Thus, if PGA_WRITEABLE
4949          * is clear, no PTEs can have APX cleared.
4950          */
4951         VM_OBJECT_ASSERT_WLOCKED(m->object);
4952         if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
4953                 return (FALSE);
4954         rw_wlock(&pvh_global_lock);
4955         rv = pmap_is_modified_pvh(&m->md) ||
4956             ((m->flags & PG_FICTITIOUS) == 0 &&
4957             pmap_is_modified_pvh(pa_to_pvh(VM_PAGE_TO_PHYS(m))));
4958         rw_wunlock(&pvh_global_lock);
4959         return (rv);
4960 }
4961
4962 /*
4963  *      Apply the given advice to the specified range of addresses within the
4964  *      given pmap.  Depending on the advice, clear the referenced and/or
4965  *      modified flags in each mapping.
4966  */
4967 void
4968 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
4969 {
4970         struct l2_bucket *l2b;
4971         struct pv_entry *pve;
4972         pd_entry_t l1pd;
4973         pt_entry_t *ptep, opte, pte;
4974         vm_offset_t next_bucket;
4975         vm_page_t m;
4976
4977         if (advice != MADV_DONTNEED && advice != MADV_FREE)
4978                 return;
4979         rw_wlock(&pvh_global_lock);
4980         PMAP_LOCK(pmap);
4981         for (; sva < eva; sva = next_bucket) {
4982                 next_bucket = L2_NEXT_BUCKET(sva);
4983                 if (next_bucket < sva)
4984                         next_bucket = eva;
4985                 l1pd = pmap->pm_l1->l1_kva[L1_IDX(sva)];
4986                 if ((l1pd & L1_TYPE_MASK) == L1_S_PROTO) {
4987                         if (pmap == pmap_kernel())
4988                                 continue;
4989                         if (!pmap_demote_section(pmap, sva)) {
4990                                 /*
4991                                  * The large page mapping was destroyed.
4992                                  */
4993                                 continue;
4994                         }
4995                         /*
4996                          * Unless the page mappings are wired, remove the
4997                          * mapping to a single page so that a subsequent
4998                          * access may repromote. Since the underlying
4999                          * l2_bucket is fully populated, this removal
5000                          * never frees an entire l2_bucket.
5001                          */
5002                         l2b = pmap_get_l2_bucket(pmap, sva);
5003                         KASSERT(l2b != NULL,
5004                             ("pmap_advise: no l2 bucket for "
5005                              "va 0x%#x, pmap 0x%p", sva, pmap));
5006                         ptep = &l2b->l2b_kva[l2pte_index(sva)];
5007                         opte = *ptep;
5008                         m = PHYS_TO_VM_PAGE(l2pte_pa(*ptep));
5009                         KASSERT(m != NULL,
5010                             ("pmap_advise: no vm_page for demoted superpage"));
5011                         pve = pmap_find_pv(&m->md, pmap, sva);
5012                         KASSERT(pve != NULL,
5013                             ("pmap_advise: no PV entry for managed mapping"));
5014                         if ((pve->pv_flags & PVF_WIRED) == 0) {
5015                                 pmap_free_l2_bucket(pmap, l2b, 1);
5016                                 pve = pmap_remove_pv(m, pmap, sva);
5017                                 pmap_free_pv_entry(pmap, pve);
5018                                 *ptep = 0;
5019                                 PTE_SYNC(ptep);
5020                                 if (pmap_is_current(pmap)) {
5021                                         if (PTE_BEEN_EXECD(opte))
5022                                                 cpu_tlb_flushID_SE(sva);
5023                                         else if (PTE_BEEN_REFD(opte))
5024                                                 cpu_tlb_flushD_SE(sva);
5025                                 }
5026                         }
5027                 }
5028                 if (next_bucket > eva)
5029                         next_bucket = eva;
5030                 l2b = pmap_get_l2_bucket(pmap, sva);
5031                 if (l2b == NULL)
5032                         continue;
5033                 for (ptep = &l2b->l2b_kva[l2pte_index(sva)];
5034                     sva != next_bucket; ptep++, sva += PAGE_SIZE) {
5035                         opte = pte = *ptep;
5036                         if ((opte & L2_S_PROTO) == 0)
5037                                 continue;
5038                         m = PHYS_TO_VM_PAGE(l2pte_pa(opte));
5039                         if (m == NULL || (m->oflags & VPO_UNMANAGED) != 0)
5040                                 continue;
5041                         else if (L2_S_WRITABLE(opte)) {
5042                                 if (advice == MADV_DONTNEED) {
5043                                         /*
5044                                          * Don't need to mark the page
5045                                          * dirty as it was already marked as
5046                                          * such in pmap_fault_fixup() or
5047                                          * pmap_enter_locked().
5048                                          * Just clear the state.
5049                                          */
5050                                 } else
5051                                         pte |= L2_APX;
5052
5053                                 pte &= ~L2_S_REF;
5054                                 *ptep = pte;
5055                                 PTE_SYNC(ptep);
5056                         } else if (L2_S_REFERENCED(opte)) {
5057                                 pte &= ~L2_S_REF;
5058                                 *ptep = pte;
5059                                 PTE_SYNC(ptep);
5060                         } else
5061                                 continue;
5062                         if (pmap_is_current(pmap)) {
5063                                 if (PTE_BEEN_EXECD(opte))
5064                                         cpu_tlb_flushID_SE(sva);
5065                                 else if (PTE_BEEN_REFD(opte))
5066                                         cpu_tlb_flushD_SE(sva);
5067                         }
5068                 }
5069         }
5070         cpu_cpwait();
5071         rw_wunlock(&pvh_global_lock);
5072         PMAP_UNLOCK(pmap);
5073 }
5074
5075 /*
5076  *      Clear the modify bits on the specified physical page.
5077  */
5078 void
5079 pmap_clear_modify(vm_page_t m)
5080 {
5081
5082         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5083             ("pmap_clear_modify: page %p is not managed", m));
5084         VM_OBJECT_ASSERT_WLOCKED(m->object);
5085         KASSERT(!vm_page_xbusied(m),
5086             ("pmap_clear_modify: page %p is exclusive busied", m));
5087
5088         /*
5089          * If the page is not PGA_WRITEABLE, then no mappings can be modified.
5090          * If the object containing the page is locked and the page is not
5091          * exclusive busied, then PGA_WRITEABLE cannot be concurrently set.
5092          */
5093         if ((m->aflags & PGA_WRITEABLE) == 0)
5094                 return;
5095         if (pmap_is_modified(m))
5096                 pmap_clearbit(m, PVF_MOD);
5097 }
5098
5099
5100 /*
5101  * Clear the write and modified bits in each of the given page's mappings.
5102  */
5103 void
5104 pmap_remove_write(vm_page_t m)
5105 {
5106         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5107             ("pmap_remove_write: page %p is not managed", m));
5108
5109         /*
5110          * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
5111          * set by another thread while the object is locked.  Thus,
5112          * if PGA_WRITEABLE is clear, no page table entries need updating.
5113          */
5114         VM_OBJECT_ASSERT_WLOCKED(m->object);
5115         if (vm_page_xbusied(m) || (m->aflags & PGA_WRITEABLE) != 0)
5116                 pmap_clearbit(m, PVF_WRITE);
5117 }
5118
5119
5120 /*
5121  * perform the pmap work for mincore
5122  */
5123 int
5124 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *locked_pa)
5125 {
5126         struct l2_bucket *l2b;
5127         pd_entry_t *pl1pd, l1pd;
5128         pt_entry_t *ptep, pte;
5129         vm_paddr_t pa;
5130         vm_page_t m;
5131         int val;
5132         boolean_t managed;
5133
5134         PMAP_LOCK(pmap);
5135 retry:
5136         pl1pd = &pmap->pm_l1->l1_kva[L1_IDX(addr)];
5137         l1pd = *pl1pd;
5138         if ((l1pd & L1_TYPE_MASK) == L1_S_PROTO) {
5139                 pa = (l1pd & L1_S_FRAME);
5140                 val = MINCORE_SUPER | MINCORE_INCORE;
5141                 if (L1_S_WRITABLE(l1pd))
5142                         val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
5143                 managed = FALSE;
5144                 m = PHYS_TO_VM_PAGE(pa);
5145                 if (m != NULL && (m->oflags & VPO_UNMANAGED) == 0)
5146                         managed = TRUE;
5147                 if (managed) {
5148                         if (L1_S_REFERENCED(l1pd))
5149                                 val |= MINCORE_REFERENCED |
5150                                     MINCORE_REFERENCED_OTHER;
5151                 }
5152         } else {
5153                 l2b = pmap_get_l2_bucket(pmap, addr);
5154                 if (l2b == NULL) {
5155                         val = 0;
5156                         goto out;
5157                 }
5158                 ptep = &l2b->l2b_kva[l2pte_index(addr)];
5159                 pte = *ptep;
5160                 if (!l2pte_valid(pte)) {
5161                         val = 0;
5162                         goto out;
5163                 }
5164                 val = MINCORE_INCORE;
5165                 if (L2_S_WRITABLE(pte))
5166                         val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
5167                 managed = FALSE;
5168                 pa = l2pte_pa(pte);
5169                 m = PHYS_TO_VM_PAGE(pa);
5170                 if (m != NULL && (m->oflags & VPO_UNMANAGED) == 0)
5171                         managed = TRUE;
5172                 if (managed) {
5173                         if (L2_S_REFERENCED(pte))
5174                                 val |= MINCORE_REFERENCED |
5175                                     MINCORE_REFERENCED_OTHER;
5176                 }
5177         }
5178         if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
5179             (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) && managed) {
5180                 /* Ensure that "PHYS_TO_VM_PAGE(pa)->object" doesn't change. */
5181                 if (vm_page_pa_tryrelock(pmap, pa, locked_pa))
5182                         goto retry;
5183         } else
5184 out:
5185                 PA_UNLOCK_COND(*locked_pa);
5186         PMAP_UNLOCK(pmap);
5187         return (val);
5188 }
5189
5190 void
5191 pmap_sync_icache(pmap_t pmap, vm_offset_t va, vm_size_t sz)
5192 {
5193 }
5194
5195 /*
5196  *      Increase the starting virtual address of the given mapping if a
5197  *      different alignment might result in more superpage mappings.
5198  */
5199 void
5200 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
5201     vm_offset_t *addr, vm_size_t size)
5202 {
5203         vm_offset_t superpage_offset;
5204
5205         if (size < NBPDR)
5206                 return;
5207         if (object != NULL && (object->flags & OBJ_COLORED) != 0)
5208                 offset += ptoa(object->pg_color);
5209         superpage_offset = offset & PDRMASK;
5210         if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
5211             (*addr & PDRMASK) == superpage_offset)
5212                 return;
5213         if ((*addr & PDRMASK) < superpage_offset)
5214                 *addr = (*addr & ~PDRMASK) + superpage_offset;
5215         else
5216                 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
5217 }
5218
5219 /*
5220  * pmap_map_section:
5221  *
5222  *      Create a single section mapping.
5223  */
5224 void
5225 pmap_map_section(pmap_t pmap, vm_offset_t va, vm_offset_t pa, vm_prot_t prot,
5226     boolean_t ref)
5227 {
5228         pd_entry_t *pl1pd, l1pd;
5229         pd_entry_t fl;
5230
5231         KASSERT(((va | pa) & L1_S_OFFSET) == 0,
5232             ("Not a valid section mapping"));
5233
5234         fl = pte_l1_s_cache_mode;
5235
5236         pl1pd = &pmap->pm_l1->l1_kva[L1_IDX(va)];
5237         l1pd = L1_S_PROTO | pa | L1_S_PROT(PTE_USER, prot) | fl |
5238             L1_S_DOM(pmap->pm_domain);
5239
5240         /* Mark page referenced if this section is a result of a promotion. */
5241         if (ref == TRUE)
5242                 l1pd |= L1_S_REF;
5243 #ifdef SMP
5244         l1pd |= L1_SHARED;
5245 #endif
5246         *pl1pd = l1pd;
5247         PTE_SYNC(pl1pd);
5248 }
5249
5250 /*
5251  * pmap_link_l2pt:
5252  *
5253  *      Link the L2 page table specified by l2pv.pv_pa into the L1
5254  *      page table at the slot for "va".
5255  */
5256 void
5257 pmap_link_l2pt(vm_offset_t l1pt, vm_offset_t va, struct pv_addr *l2pv)
5258 {
5259         pd_entry_t *pde = (pd_entry_t *) l1pt, proto;
5260         u_int slot = va >> L1_S_SHIFT;
5261
5262         proto = L1_S_DOM(PMAP_DOMAIN_KERNEL) | L1_C_PROTO;
5263
5264 #ifdef VERBOSE_INIT_ARM
5265         printf("pmap_link_l2pt: pa=0x%x va=0x%x\n", l2pv->pv_pa, l2pv->pv_va);
5266 #endif
5267
5268         pde[slot + 0] = proto | (l2pv->pv_pa + 0x000);
5269         PTE_SYNC(&pde[slot]);
5270
5271         SLIST_INSERT_HEAD(&kernel_pt_list, l2pv, pv_list);
5272
5273 }
5274
5275 /*
5276  * pmap_map_entry
5277  *
5278  *      Create a single page mapping.
5279  */
5280 void
5281 pmap_map_entry(vm_offset_t l1pt, vm_offset_t va, vm_offset_t pa, int prot,
5282     int cache)
5283 {
5284         pd_entry_t *pde = (pd_entry_t *) l1pt;
5285         pt_entry_t fl;
5286         pt_entry_t *ptep;
5287
5288         KASSERT(((va | pa) & PAGE_MASK) == 0, ("ouin"));
5289
5290         fl = l2s_mem_types[cache];
5291
5292         if ((pde[va >> L1_S_SHIFT] & L1_TYPE_MASK) != L1_TYPE_C)
5293                 panic("pmap_map_entry: no L2 table for VA 0x%08x", va);
5294
5295         ptep = (pt_entry_t *)kernel_pt_lookup(pde[L1_IDX(va)] & L1_C_ADDR_MASK);
5296
5297         if (ptep == NULL)
5298                 panic("pmap_map_entry: can't find L2 table for VA 0x%08x", va);
5299
5300         ptep[l2pte_index(va)] = L2_S_PROTO | pa | fl | L2_S_REF;
5301         pmap_set_prot(&ptep[l2pte_index(va)], prot, 0);
5302         PTE_SYNC(&ptep[l2pte_index(va)]);
5303 }
5304
5305 /*
5306  * pmap_map_chunk:
5307  *
5308  *      Map a chunk of memory using the most efficient mappings
5309  *      possible (section. large page, small page) into the
5310  *      provided L1 and L2 tables at the specified virtual address.
5311  */
5312 vm_size_t
5313 pmap_map_chunk(vm_offset_t l1pt, vm_offset_t va, vm_offset_t pa,
5314     vm_size_t size, int prot, int type)
5315 {
5316         pd_entry_t *pde = (pd_entry_t *) l1pt;
5317         pt_entry_t *ptep, f1, f2s, f2l;
5318         vm_size_t resid;
5319         int i;
5320
5321         resid = (size + (PAGE_SIZE - 1)) & ~(PAGE_SIZE - 1);
5322
5323         if (l1pt == 0)
5324                 panic("pmap_map_chunk: no L1 table provided");
5325
5326 #ifdef VERBOSE_INIT_ARM
5327         printf("pmap_map_chunk: pa=0x%x va=0x%x size=0x%x resid=0x%x "
5328             "prot=0x%x type=%d\n", pa, va, size, resid, prot, type);
5329 #endif
5330
5331         f1 = l1_mem_types[type];
5332         f2l = l2l_mem_types[type];
5333         f2s = l2s_mem_types[type];
5334
5335         size = resid;
5336
5337         while (resid > 0) {
5338                 /* See if we can use a section mapping. */
5339                 if (L1_S_MAPPABLE_P(va, pa, resid)) {
5340 #ifdef VERBOSE_INIT_ARM
5341                         printf("S");
5342 #endif
5343                         pde[va >> L1_S_SHIFT] = L1_S_PROTO | pa |
5344                             L1_S_PROT(PTE_KERNEL, prot | VM_PROT_EXECUTE) |
5345                             f1 | L1_S_DOM(PMAP_DOMAIN_KERNEL) | L1_S_REF;
5346                         PTE_SYNC(&pde[va >> L1_S_SHIFT]);
5347                         va += L1_S_SIZE;
5348                         pa += L1_S_SIZE;
5349                         resid -= L1_S_SIZE;
5350                         continue;
5351                 }
5352
5353                 /*
5354                  * Ok, we're going to use an L2 table.  Make sure
5355                  * one is actually in the corresponding L1 slot
5356                  * for the current VA.
5357                  */
5358                 if ((pde[va >> L1_S_SHIFT] & L1_TYPE_MASK) != L1_TYPE_C)
5359                         panic("pmap_map_chunk: no L2 table for VA 0x%08x", va);
5360
5361                 ptep = (pt_entry_t *) kernel_pt_lookup(
5362                     pde[L1_IDX(va)] & L1_C_ADDR_MASK);
5363                 if (ptep == NULL)
5364                         panic("pmap_map_chunk: can't find L2 table for VA"
5365                             "0x%08x", va);
5366                 /* See if we can use a L2 large page mapping. */
5367                 if (L2_L_MAPPABLE_P(va, pa, resid)) {
5368 #ifdef VERBOSE_INIT_ARM
5369                         printf("L");
5370 #endif
5371                         for (i = 0; i < 16; i++) {
5372                                 ptep[l2pte_index(va) + i] =
5373                                     L2_L_PROTO | pa |
5374                                     L2_L_PROT(PTE_KERNEL, prot) | f2l;
5375                                 PTE_SYNC(&ptep[l2pte_index(va) + i]);
5376                         }
5377                         va += L2_L_SIZE;
5378                         pa += L2_L_SIZE;
5379                         resid -= L2_L_SIZE;
5380                         continue;
5381                 }
5382
5383                 /* Use a small page mapping. */
5384 #ifdef VERBOSE_INIT_ARM
5385                 printf("P");
5386 #endif
5387                 ptep[l2pte_index(va)] = L2_S_PROTO | pa | f2s | L2_S_REF;
5388                 pmap_set_prot(&ptep[l2pte_index(va)], prot, 0);
5389                 PTE_SYNC(&ptep[l2pte_index(va)]);
5390                 va += PAGE_SIZE;
5391                 pa += PAGE_SIZE;
5392                 resid -= PAGE_SIZE;
5393         }
5394 #ifdef VERBOSE_INIT_ARM
5395         printf("\n");
5396 #endif
5397         return (size);
5398
5399 }
5400
5401 void
5402 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
5403 {
5404         /*
5405          * Remember the memattr in a field that gets used to set the appropriate
5406          * bits in the PTEs as mappings are established.
5407          */
5408         m->md.pv_memattr = ma;
5409
5410         /*
5411          * It appears that this function can only be called before any mappings
5412          * for the page are established on ARM.  If this ever changes, this code
5413          * will need to walk the pv_list and make each of the existing mappings
5414          * uncacheable, being careful to sync caches and PTEs (and maybe
5415          * invalidate TLB?) for any current mapping it modifies.
5416          */
5417         if (TAILQ_FIRST(&m->md.pv_list) != NULL)
5418                 panic("Can't change memattr on page with existing mappings");
5419 }