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