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