]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/arm/arm/pmap-v6.c
o Relax locking assertions for vm_page_find_least()
[FreeBSD/FreeBSD.git] / sys / arm / arm / pmap-v6.c
1 /* From: $NetBSD: pmap.c,v 1.148 2004/04/03 04:35:48 bsh Exp $ */
2 /*-
3  * Copyright 2011 Semihalf
4  * Copyright 2004 Olivier Houchard.
5  * Copyright 2003 Wasabi Systems, Inc.
6  * All rights reserved.
7  *
8  * Written by Steve C. Woodford for Wasabi Systems, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed for the NetBSD Project by
21  *      Wasabi Systems, Inc.
22  * 4. The name of Wasabi Systems, Inc. may not be used to endorse
23  *    or promote products derived from this software without specific prior
24  *    written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL WASABI SYSTEMS, INC
30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36  * POSSIBILITY OF SUCH DAMAGE.
37  *
38  * From: FreeBSD: src/sys/arm/arm/pmap.c,v 1.113 2009/07/24 13:50:29
39  */
40
41 /*-
42  * Copyright (c) 2002-2003 Wasabi Systems, Inc.
43  * Copyright (c) 2001 Richard Earnshaw
44  * Copyright (c) 2001-2002 Christopher Gilbert
45  * All rights reserved.
46  *
47  * 1. Redistributions of source code must retain the above copyright
48  *    notice, this list of conditions and the following disclaimer.
49  * 2. Redistributions in binary form must reproduce the above copyright
50  *    notice, this list of conditions and the following disclaimer in the
51  *    documentation and/or other materials provided with the distribution.
52  * 3. The name of the company nor the name of the author may be used to
53  *    endorse or promote products derived from this software without specific
54  *    prior written permission.
55  *
56  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
57  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
58  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
59  * IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
60  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
61  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
62  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
63  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
64  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
65  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
66  * SUCH DAMAGE.
67  */
68 /*-
69  * Copyright (c) 1999 The NetBSD Foundation, Inc.
70  * All rights reserved.
71  *
72  * This code is derived from software contributed to The NetBSD Foundation
73  * by Charles M. Hannum.
74  *
75  * Redistribution and use in source and binary forms, with or without
76  * modification, are permitted provided that the following conditions
77  * are met:
78  * 1. Redistributions of source code must retain the above copyright
79  *    notice, this list of conditions and the following disclaimer.
80  * 2. Redistributions in binary form must reproduce the above copyright
81  *    notice, this list of conditions and the following disclaimer in the
82  *    documentation and/or other materials provided with the distribution.
83  *
84  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
85  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
86  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
87  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
88  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
89  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
90  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
91  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
92  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
93  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
94  * POSSIBILITY OF SUCH DAMAGE.
95  */
96
97 /*-
98  * Copyright (c) 1994-1998 Mark Brinicombe.
99  * Copyright (c) 1994 Brini.
100  * All rights reserved.
101  *
102  * This code is derived from software written for Brini by Mark Brinicombe
103  *
104  * Redistribution and use in source and binary forms, with or without
105  * modification, are permitted provided that the following conditions
106  * are met:
107  * 1. Redistributions of source code must retain the above copyright
108  *    notice, this list of conditions and the following disclaimer.
109  * 2. Redistributions in binary form must reproduce the above copyright
110  *    notice, this list of conditions and the following disclaimer in the
111  *    documentation and/or other materials provided with the distribution.
112  * 3. All advertising materials mentioning features or use of this software
113  *    must display the following acknowledgement:
114  *      This product includes software developed by Mark Brinicombe.
115  * 4. The name of the author may not be used to endorse or promote products
116  *    derived from this software without specific prior written permission.
117  *
118  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
119  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
120  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
121  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
122  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
123  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
124  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
125  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
126  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
127  *
128  * RiscBSD kernel project
129  *
130  * pmap.c
131  *
132  * Machine dependant vm stuff
133  *
134  * Created      : 20/09/94
135  */
136
137 /*
138  * Special compilation symbols
139  * PMAP_DEBUG           - Build in pmap_debug_level code
140  */
141 /* Include header files */
142
143 #include "opt_vm.h"
144 #include "opt_pmap.h"
145
146 #include <sys/cdefs.h>
147 __FBSDID("$FreeBSD$");
148 #include <sys/param.h>
149 #include <sys/systm.h>
150 #include <sys/kernel.h>
151 #include <sys/ktr.h>
152 #include <sys/lock.h>
153 #include <sys/proc.h>
154 #include <sys/malloc.h>
155 #include <sys/msgbuf.h>
156 #include <sys/mutex.h>
157 #include <sys/vmmeter.h>
158 #include <sys/mman.h>
159 #include <sys/rwlock.h>
160 #include <sys/smp.h>
161 #include <sys/sched.h>
162 #include <sys/sysctl.h>
163
164 #include <vm/vm.h>
165 #include <vm/vm_param.h>
166 #include <vm/uma.h>
167 #include <vm/pmap.h>
168 #include <vm/vm_kern.h>
169 #include <vm/vm_object.h>
170 #include <vm/vm_map.h>
171 #include <vm/vm_page.h>
172 #include <vm/vm_pageout.h>
173 #include <vm/vm_extern.h>
174
175 #include <machine/md_var.h>
176 #include <machine/cpu.h>
177 #include <machine/cpufunc.h>
178 #include <machine/pcb.h>
179
180 #ifdef DEBUG
181 extern int last_fault_code;
182 #endif
183
184 #ifdef PMAP_DEBUG
185 #define PDEBUG(_lev_,_stat_) \
186         if (pmap_debug_level >= (_lev_)) \
187                 ((_stat_))
188 #define dprintf printf
189
190 int pmap_debug_level = 0;
191 #define PMAP_INLINE
192 #else   /* PMAP_DEBUG */
193 #define PDEBUG(_lev_,_stat_) /* Nothing */
194 #define dprintf(x, arg...)
195 #define PMAP_INLINE __inline
196 #endif  /* PMAP_DEBUG */
197
198 #ifdef PV_STATS
199 #define PV_STAT(x)      do { x ; } while (0)
200 #else
201 #define PV_STAT(x)      do { } while (0)
202 #endif
203
204 #ifdef ARM_L2_PIPT
205 #define pmap_l2cache_wbinv_range(va, pa, size) cpu_l2cache_wbinv_range((pa), (size))
206 #define pmap_l2cache_inv_range(va, pa, size) cpu_l2cache_inv_range((pa), (size))
207 #else
208 #define pmap_l2cache_wbinv_range(va, pa, size) cpu_l2cache_wbinv_range((va), (size))
209 #define pmap_l2cache_inv_range(va, pa, size) cpu_l2cache_inv_range((va), (size))
210 #endif
211
212 extern struct pv_addr systempage;
213
214 /*
215  * Internal function prototypes
216  */
217
218 static void             pmap_free_pv_chunk(struct pv_chunk *pc);
219 static void             pmap_free_pv_entry(pmap_t pmap, pv_entry_t pv);
220 static pv_entry_t       pmap_get_pv_entry(pmap_t pmap, boolean_t try);
221 static vm_page_t        pmap_pv_reclaim(pmap_t locked_pmap);
222
223 static void             pmap_enter_locked(pmap_t, vm_offset_t, vm_page_t,
224     vm_prot_t, boolean_t, int);
225 static vm_paddr_t       pmap_extract_locked(pmap_t pmap, vm_offset_t va);
226 static void             pmap_alloc_l1(pmap_t);
227 static void             pmap_free_l1(pmap_t);
228
229 static int              pmap_clearbit(struct vm_page *, u_int);
230
231 static struct l2_bucket *pmap_get_l2_bucket(pmap_t, vm_offset_t);
232 static struct l2_bucket *pmap_alloc_l2_bucket(pmap_t, vm_offset_t);
233 static void             pmap_free_l2_bucket(pmap_t, struct l2_bucket *, u_int);
234 static vm_offset_t      kernel_pt_lookup(vm_paddr_t);
235
236 static MALLOC_DEFINE(M_VMPMAP, "pmap", "PMAP L1");
237
238 vm_offset_t virtual_avail;      /* VA of first avail page (after kernel bss) */
239 vm_offset_t virtual_end;        /* VA of last avail page (end of kernel AS) */
240 vm_offset_t pmap_curmaxkvaddr;
241 vm_paddr_t kernel_l1pa;
242
243 vm_offset_t kernel_vm_end = 0;
244
245 vm_offset_t vm_max_kernel_address;
246
247 struct pmap kernel_pmap_store;
248
249 static pt_entry_t *csrc_pte, *cdst_pte;
250 static vm_offset_t csrcp, cdstp;
251 static struct mtx cmtx;
252
253 static void             pmap_init_l1(struct l1_ttable *, pd_entry_t *);
254 /*
255  * These routines are called when the CPU type is identified to set up
256  * the PTE prototypes, cache modes, etc.
257  *
258  * The variables are always here, just in case LKMs need to reference
259  * them (though, they shouldn't).
260  */
261 static void pmap_set_prot(pt_entry_t *pte, vm_prot_t prot, uint8_t user);
262 pt_entry_t      pte_l1_s_cache_mode;
263 pt_entry_t      pte_l1_s_cache_mode_pt;
264
265 pt_entry_t      pte_l2_l_cache_mode;
266 pt_entry_t      pte_l2_l_cache_mode_pt;
267
268 pt_entry_t      pte_l2_s_cache_mode;
269 pt_entry_t      pte_l2_s_cache_mode_pt;
270
271 struct msgbuf *msgbufp = 0;
272
273 /*
274  * Crashdump maps.
275  */
276 static caddr_t crashdumpmap;
277
278 extern void bcopy_page(vm_offset_t, vm_offset_t);
279 extern void bzero_page(vm_offset_t);
280
281 char *_tmppt;
282
283 /*
284  * Metadata for L1 translation tables.
285  */
286 struct l1_ttable {
287         /* Entry on the L1 Table list */
288         SLIST_ENTRY(l1_ttable) l1_link;
289
290         /* Entry on the L1 Least Recently Used list */
291         TAILQ_ENTRY(l1_ttable) l1_lru;
292
293         /* Track how many domains are allocated from this L1 */
294         volatile u_int l1_domain_use_count;
295
296         /*
297          * A free-list of domain numbers for this L1.
298          * We avoid using ffs() and a bitmap to track domains since ffs()
299          * is slow on ARM.
300          */
301         u_int8_t l1_domain_first;
302         u_int8_t l1_domain_free[PMAP_DOMAINS];
303
304         /* Physical address of this L1 page table */
305         vm_paddr_t l1_physaddr;
306
307         /* KVA of this L1 page table */
308         pd_entry_t *l1_kva;
309 };
310
311 /*
312  * Convert a virtual address into its L1 table index. That is, the
313  * index used to locate the L2 descriptor table pointer in an L1 table.
314  * This is basically used to index l1->l1_kva[].
315  *
316  * Each L2 descriptor table represents 1MB of VA space.
317  */
318 #define L1_IDX(va)              (((vm_offset_t)(va)) >> L1_S_SHIFT)
319
320 /*
321  * L1 Page Tables are tracked using a Least Recently Used list.
322  *  - New L1s are allocated from the HEAD.
323  *  - Freed L1s are added to the TAIl.
324  *  - Recently accessed L1s (where an 'access' is some change to one of
325  *    the userland pmaps which owns this L1) are moved to the TAIL.
326  */
327 static TAILQ_HEAD(, l1_ttable) l1_lru_list;
328 /*
329  * A list of all L1 tables
330  */
331 static SLIST_HEAD(, l1_ttable) l1_list;
332 static struct mtx l1_lru_lock;
333
334 /*
335  * The l2_dtable tracks L2_BUCKET_SIZE worth of L1 slots.
336  *
337  * This is normally 16MB worth L2 page descriptors for any given pmap.
338  * Reference counts are maintained for L2 descriptors so they can be
339  * freed when empty.
340  */
341 struct l2_dtable {
342         /* The number of L2 page descriptors allocated to this l2_dtable */
343         u_int l2_occupancy;
344
345         /* List of L2 page descriptors */
346         struct l2_bucket {
347                 pt_entry_t *l2b_kva;    /* KVA of L2 Descriptor Table */
348                 vm_paddr_t l2b_phys;    /* Physical address of same */
349                 u_short l2b_l1idx;      /* This L2 table's L1 index */
350                 u_short l2b_occupancy;  /* How many active descriptors */
351         } l2_bucket[L2_BUCKET_SIZE];
352 };
353
354 /* pmap_kenter_internal flags */
355 #define KENTER_CACHE    0x1
356 #define KENTER_USER     0x2
357
358 /*
359  * Given an L1 table index, calculate the corresponding l2_dtable index
360  * and bucket index within the l2_dtable.
361  */
362 #define L2_IDX(l1idx)           (((l1idx) >> L2_BUCKET_LOG2) & \
363                                  (L2_SIZE - 1))
364 #define L2_BUCKET(l1idx)        ((l1idx) & (L2_BUCKET_SIZE - 1))
365
366 /*
367  * Given a virtual address, this macro returns the
368  * virtual address required to drop into the next L2 bucket.
369  */
370 #define L2_NEXT_BUCKET(va)      (((va) & L1_S_FRAME) + L1_S_SIZE)
371
372 /*
373  * We try to map the page tables write-through, if possible.  However, not
374  * all CPUs have a write-through cache mode, so on those we have to sync
375  * the cache when we frob page tables.
376  *
377  * We try to evaluate this at compile time, if possible.  However, it's
378  * not always possible to do that, hence this run-time var.
379  */
380 int     pmap_needs_pte_sync;
381
382 /*
383  * Macro to determine if a mapping might be resident in the
384  * instruction cache and/or TLB
385  */
386 #define PV_BEEN_EXECD(f)  (((f) & (PVF_REF | PVF_EXEC)) == (PVF_REF | PVF_EXEC))
387
388 /*
389  * Macro to determine if a mapping might be resident in the
390  * data cache and/or TLB
391  */
392 #define PV_BEEN_REFD(f)   (((f) & PVF_REF) != 0)
393
394 #ifndef PMAP_SHPGPERPROC
395 #define PMAP_SHPGPERPROC 200
396 #endif
397
398 #define pmap_is_current(pm)     ((pm) == pmap_kernel() || \
399             curproc->p_vmspace->vm_map.pmap == (pm))
400
401 /*
402  * Data for the pv entry allocation mechanism
403  */
404 static TAILQ_HEAD(pch, pv_chunk) pv_chunks = TAILQ_HEAD_INITIALIZER(pv_chunks);
405 static int pv_entry_count, pv_entry_max, pv_entry_high_water;
406 static int shpgperproc = PMAP_SHPGPERPROC;
407
408 struct pv_chunk *pv_chunkbase;          /* KVA block for pv_chunks */
409 int pv_maxchunks;                       /* How many chunks we have KVA for */
410 vm_offset_t pv_vafree;                  /* Freelist stored in the PTE */
411
412 static __inline struct pv_chunk *
413 pv_to_chunk(pv_entry_t pv)
414 {
415
416         return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
417 }
418
419 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
420
421 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
422 CTASSERT(_NPCM == 8);
423 CTASSERT(_NPCPV == 252);
424
425 #define PC_FREE0_6      0xfffffffful    /* Free values for index 0 through 6 */
426 #define PC_FREE7        0x0ffffffful    /* Free values for index 7 */
427
428 static const uint32_t pc_freemask[_NPCM] = {
429         PC_FREE0_6, PC_FREE0_6, PC_FREE0_6,
430         PC_FREE0_6, PC_FREE0_6, PC_FREE0_6,
431         PC_FREE0_6, PC_FREE7
432 };
433
434 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD, 0, "VM/pmap parameters");
435
436 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
437     "Current number of pv entries");
438
439 #ifdef PV_STATS
440 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
441
442 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
443     "Current number of pv entry chunks");
444 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
445     "Current number of pv entry chunks allocated");
446 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
447     "Current number of pv entry chunks frees");
448 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
449     "Number of times tried to get a chunk page but failed.");
450
451 static long pv_entry_frees, pv_entry_allocs;
452 static int pv_entry_spare;
453
454 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
455     "Current number of pv entry frees");
456 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
457     "Current number of pv entry allocs");
458 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
459     "Current number of spare pv entries");
460 #endif
461
462 uma_zone_t l2zone;
463 static uma_zone_t l2table_zone;
464 static vm_offset_t pmap_kernel_l2dtable_kva;
465 static vm_offset_t pmap_kernel_l2ptp_kva;
466 static vm_paddr_t pmap_kernel_l2ptp_phys;
467 static struct rwlock pvh_global_lock;
468
469 int l1_mem_types[] = {
470         ARM_L1S_STRONG_ORD,
471         ARM_L1S_DEVICE_NOSHARE,
472         ARM_L1S_DEVICE_SHARE,
473         ARM_L1S_NRML_NOCACHE,
474         ARM_L1S_NRML_IWT_OWT,
475         ARM_L1S_NRML_IWB_OWB,
476         ARM_L1S_NRML_IWBA_OWBA
477 };
478
479 int l2l_mem_types[] = {
480         ARM_L2L_STRONG_ORD,
481         ARM_L2L_DEVICE_NOSHARE,
482         ARM_L2L_DEVICE_SHARE,
483         ARM_L2L_NRML_NOCACHE,
484         ARM_L2L_NRML_IWT_OWT,
485         ARM_L2L_NRML_IWB_OWB,
486         ARM_L2L_NRML_IWBA_OWBA
487 };
488
489 int l2s_mem_types[] = {
490         ARM_L2S_STRONG_ORD,
491         ARM_L2S_DEVICE_NOSHARE,
492         ARM_L2S_DEVICE_SHARE,
493         ARM_L2S_NRML_NOCACHE,
494         ARM_L2S_NRML_IWT_OWT,
495         ARM_L2S_NRML_IWB_OWB,
496         ARM_L2S_NRML_IWBA_OWBA
497 };
498
499 /*
500  * This list exists for the benefit of pmap_map_chunk().  It keeps track
501  * of the kernel L2 tables during bootstrap, so that pmap_map_chunk() can
502  * find them as necessary.
503  *
504  * Note that the data on this list MUST remain valid after initarm() returns,
505  * as pmap_bootstrap() uses it to contruct L2 table metadata.
506  */
507 SLIST_HEAD(, pv_addr) kernel_pt_list = SLIST_HEAD_INITIALIZER(kernel_pt_list);
508
509 static void
510 pmap_init_l1(struct l1_ttable *l1, pd_entry_t *l1pt)
511 {
512         int i;
513
514         l1->l1_kva = l1pt;
515         l1->l1_domain_use_count = 0;
516         l1->l1_domain_first = 0;
517
518         for (i = 0; i < PMAP_DOMAINS; i++)
519                 l1->l1_domain_free[i] = i + 1;
520
521         /*
522          * Copy the kernel's L1 entries to each new L1.
523          */
524         if (l1pt != pmap_kernel()->pm_l1->l1_kva)
525                 memcpy(l1pt, pmap_kernel()->pm_l1->l1_kva, L1_TABLE_SIZE);
526
527         if ((l1->l1_physaddr = pmap_extract(pmap_kernel(), (vm_offset_t)l1pt)) == 0)
528                 panic("pmap_init_l1: can't get PA of L1 at %p", l1pt);
529         SLIST_INSERT_HEAD(&l1_list, l1, l1_link);
530         TAILQ_INSERT_TAIL(&l1_lru_list, l1, l1_lru);
531 }
532
533 static vm_offset_t
534 kernel_pt_lookup(vm_paddr_t pa)
535 {
536         struct pv_addr *pv;
537
538         SLIST_FOREACH(pv, &kernel_pt_list, pv_list) {
539                 if (pv->pv_pa == pa)
540                         return (pv->pv_va);
541         }
542         return (0);
543 }
544
545 void
546 pmap_pte_init_mmu_v6(void)
547 {
548
549         if (PTE_PAGETABLE >= 3)
550                 pmap_needs_pte_sync = 1;
551         pte_l1_s_cache_mode = l1_mem_types[PTE_CACHE];
552         pte_l2_l_cache_mode = l2l_mem_types[PTE_CACHE];
553         pte_l2_s_cache_mode = l2s_mem_types[PTE_CACHE];
554
555         pte_l1_s_cache_mode_pt = l1_mem_types[PTE_PAGETABLE];
556         pte_l2_l_cache_mode_pt = l2l_mem_types[PTE_PAGETABLE];
557         pte_l2_s_cache_mode_pt = l2s_mem_types[PTE_PAGETABLE];
558
559 }
560
561 /*
562  * Allocate an L1 translation table for the specified pmap.
563  * This is called at pmap creation time.
564  */
565 static void
566 pmap_alloc_l1(pmap_t pm)
567 {
568         struct l1_ttable *l1;
569         u_int8_t domain;
570
571         /*
572          * Remove the L1 at the head of the LRU list
573          */
574         mtx_lock(&l1_lru_lock);
575         l1 = TAILQ_FIRST(&l1_lru_list);
576         TAILQ_REMOVE(&l1_lru_list, l1, l1_lru);
577
578         /*
579          * Pick the first available domain number, and update
580          * the link to the next number.
581          */
582         domain = l1->l1_domain_first;
583         l1->l1_domain_first = l1->l1_domain_free[domain];
584
585         /*
586          * If there are still free domain numbers in this L1,
587          * put it back on the TAIL of the LRU list.
588          */
589         if (++l1->l1_domain_use_count < PMAP_DOMAINS)
590                 TAILQ_INSERT_TAIL(&l1_lru_list, l1, l1_lru);
591
592         mtx_unlock(&l1_lru_lock);
593
594         /*
595          * Fix up the relevant bits in the pmap structure
596          */
597         pm->pm_l1 = l1;
598         pm->pm_domain = domain + 1;
599 }
600
601 /*
602  * Free an L1 translation table.
603  * This is called at pmap destruction time.
604  */
605 static void
606 pmap_free_l1(pmap_t pm)
607 {
608         struct l1_ttable *l1 = pm->pm_l1;
609
610         mtx_lock(&l1_lru_lock);
611
612         /*
613          * If this L1 is currently on the LRU list, remove it.
614          */
615         if (l1->l1_domain_use_count < PMAP_DOMAINS)
616                 TAILQ_REMOVE(&l1_lru_list, l1, l1_lru);
617
618         /*
619          * Free up the domain number which was allocated to the pmap
620          */
621         l1->l1_domain_free[pm->pm_domain - 1] = l1->l1_domain_first;
622         l1->l1_domain_first = pm->pm_domain - 1;
623         l1->l1_domain_use_count--;
624
625         /*
626          * The L1 now must have at least 1 free domain, so add
627          * it back to the LRU list. If the use count is zero,
628          * put it at the head of the list, otherwise it goes
629          * to the tail.
630          */
631         if (l1->l1_domain_use_count == 0) {
632                 TAILQ_INSERT_HEAD(&l1_lru_list, l1, l1_lru);
633         }       else
634                 TAILQ_INSERT_TAIL(&l1_lru_list, l1, l1_lru);
635
636         mtx_unlock(&l1_lru_lock);
637 }
638
639 /*
640  * Returns a pointer to the L2 bucket associated with the specified pmap
641  * and VA, or NULL if no L2 bucket exists for the address.
642  */
643 static PMAP_INLINE struct l2_bucket *
644 pmap_get_l2_bucket(pmap_t pm, vm_offset_t va)
645 {
646         struct l2_dtable *l2;
647         struct l2_bucket *l2b;
648         u_short l1idx;
649
650         l1idx = L1_IDX(va);
651
652         if ((l2 = pm->pm_l2[L2_IDX(l1idx)]) == NULL ||
653             (l2b = &l2->l2_bucket[L2_BUCKET(l1idx)])->l2b_kva == NULL)
654                 return (NULL);
655
656         return (l2b);
657 }
658
659 /*
660  * Returns a pointer to the L2 bucket associated with the specified pmap
661  * and VA.
662  *
663  * If no L2 bucket exists, perform the necessary allocations to put an L2
664  * bucket/page table in place.
665  *
666  * Note that if a new L2 bucket/page was allocated, the caller *must*
667  * increment the bucket occupancy counter appropriately *before*
668  * releasing the pmap's lock to ensure no other thread or cpu deallocates
669  * the bucket/page in the meantime.
670  */
671 static struct l2_bucket *
672 pmap_alloc_l2_bucket(pmap_t pm, vm_offset_t va)
673 {
674         struct l2_dtable *l2;
675         struct l2_bucket *l2b;
676         u_short l1idx;
677
678         l1idx = L1_IDX(va);
679
680         PMAP_ASSERT_LOCKED(pm);
681         rw_assert(&pvh_global_lock, RA_WLOCKED);
682         if ((l2 = pm->pm_l2[L2_IDX(l1idx)]) == NULL) {
683                 /*
684                  * No mapping at this address, as there is
685                  * no entry in the L1 table.
686                  * Need to allocate a new l2_dtable.
687                  */
688                 PMAP_UNLOCK(pm);
689                 rw_wunlock(&pvh_global_lock);
690                 if ((l2 = uma_zalloc(l2table_zone, M_NOWAIT)) == NULL) {
691                         rw_wlock(&pvh_global_lock);
692                         PMAP_LOCK(pm);
693                         return (NULL);
694                 }
695                 rw_wlock(&pvh_global_lock);
696                 PMAP_LOCK(pm);
697                 if (pm->pm_l2[L2_IDX(l1idx)] != NULL) {
698                         /*
699                          * Someone already allocated the l2_dtable while
700                          * we were doing the same.
701                          */
702                         uma_zfree(l2table_zone, l2);
703                         l2 = pm->pm_l2[L2_IDX(l1idx)];
704                 } else {
705                         bzero(l2, sizeof(*l2));
706                         /*
707                          * Link it into the parent pmap
708                          */
709                         pm->pm_l2[L2_IDX(l1idx)] = l2;
710                 }
711         }
712
713         l2b = &l2->l2_bucket[L2_BUCKET(l1idx)];
714
715         /*
716          * Fetch pointer to the L2 page table associated with the address.
717          */
718         if (l2b->l2b_kva == NULL) {
719                 pt_entry_t *ptep;
720
721                 /*
722                  * No L2 page table has been allocated. Chances are, this
723                  * is because we just allocated the l2_dtable, above.
724                  */
725                 PMAP_UNLOCK(pm);
726                 rw_wunlock(&pvh_global_lock);
727                 ptep = uma_zalloc(l2zone, M_NOWAIT);
728                 rw_wlock(&pvh_global_lock);
729                 PMAP_LOCK(pm);
730                 if (l2b->l2b_kva != 0) {
731                         /* We lost the race. */
732                         uma_zfree(l2zone, ptep);
733                         return (l2b);
734                 }
735                 l2b->l2b_phys = vtophys(ptep);
736                 if (ptep == NULL) {
737                         /*
738                          * Oops, no more L2 page tables available at this
739                          * time. We may need to deallocate the l2_dtable
740                          * if we allocated a new one above.
741                          */
742                         if (l2->l2_occupancy == 0) {
743                                 pm->pm_l2[L2_IDX(l1idx)] = NULL;
744                                 uma_zfree(l2table_zone, l2);
745                         }
746                         return (NULL);
747                 }
748
749                 l2->l2_occupancy++;
750                 l2b->l2b_kva = ptep;
751                 l2b->l2b_l1idx = l1idx;
752         }
753
754         return (l2b);
755 }
756
757 static PMAP_INLINE void
758 pmap_free_l2_ptp(pt_entry_t *l2)
759 {
760         uma_zfree(l2zone, l2);
761 }
762 /*
763  * One or more mappings in the specified L2 descriptor table have just been
764  * invalidated.
765  *
766  * Garbage collect the metadata and descriptor table itself if necessary.
767  *
768  * The pmap lock must be acquired when this is called (not necessary
769  * for the kernel pmap).
770  */
771 static void
772 pmap_free_l2_bucket(pmap_t pm, struct l2_bucket *l2b, u_int count)
773 {
774         struct l2_dtable *l2;
775         pd_entry_t *pl1pd, l1pd;
776         pt_entry_t *ptep;
777         u_short l1idx;
778
779
780         /*
781          * Update the bucket's reference count according to how many
782          * PTEs the caller has just invalidated.
783          */
784         l2b->l2b_occupancy -= count;
785
786         /*
787          * Note:
788          *
789          * Level 2 page tables allocated to the kernel pmap are never freed
790          * as that would require checking all Level 1 page tables and
791          * removing any references to the Level 2 page table. See also the
792          * comment elsewhere about never freeing bootstrap L2 descriptors.
793          *
794          * We make do with just invalidating the mapping in the L2 table.
795          *
796          * This isn't really a big deal in practice and, in fact, leads
797          * to a performance win over time as we don't need to continually
798          * alloc/free.
799          */
800         if (l2b->l2b_occupancy > 0 || pm == pmap_kernel())
801                 return;
802
803         /*
804          * There are no more valid mappings in this level 2 page table.
805          * Go ahead and NULL-out the pointer in the bucket, then
806          * free the page table.
807          */
808         l1idx = l2b->l2b_l1idx;
809         ptep = l2b->l2b_kva;
810         l2b->l2b_kva = NULL;
811
812         pl1pd = &pm->pm_l1->l1_kva[l1idx];
813
814         /*
815          * If the L1 slot matches the pmap's domain
816          * number, then invalidate it.
817          */
818         l1pd = *pl1pd & (L1_TYPE_MASK | L1_C_DOM_MASK);
819         if (l1pd == (L1_C_DOM(pm->pm_domain) | L1_TYPE_C)) {
820                 *pl1pd = 0;
821                 PTE_SYNC(pl1pd);
822         }
823
824         /*
825          * Release the L2 descriptor table back to the pool cache.
826          */
827         pmap_free_l2_ptp(ptep);
828
829         /*
830          * Update the reference count in the associated l2_dtable
831          */
832         l2 = pm->pm_l2[L2_IDX(l1idx)];
833         if (--l2->l2_occupancy > 0)
834                 return;
835
836         /*
837          * There are no more valid mappings in any of the Level 1
838          * slots managed by this l2_dtable. Go ahead and NULL-out
839          * the pointer in the parent pmap and free the l2_dtable.
840          */
841         pm->pm_l2[L2_IDX(l1idx)] = NULL;
842         uma_zfree(l2table_zone, l2);
843 }
844
845 /*
846  * Pool cache constructors for L2 descriptor tables, metadata and pmap
847  * structures.
848  */
849 static int
850 pmap_l2ptp_ctor(void *mem, int size, void *arg, int flags)
851 {
852         struct l2_bucket *l2b;
853         pt_entry_t *ptep, pte;
854         vm_offset_t va = (vm_offset_t)mem & ~PAGE_MASK;
855
856         /*
857          * The mappings for these page tables were initially made using
858          * pmap_kenter() by the pool subsystem. Therefore, the cache-
859          * mode will not be right for page table mappings. To avoid
860          * polluting the pmap_kenter() code with a special case for
861          * page tables, we simply fix up the cache-mode here if it's not
862          * correct.
863          */
864         l2b = pmap_get_l2_bucket(pmap_kernel(), va);
865         ptep = &l2b->l2b_kva[l2pte_index(va)];
866         pte = *ptep;
867
868         cpu_idcache_wbinv_range(va, PAGE_SIZE);
869         pmap_l2cache_wbinv_range(va, pte & L2_S_FRAME, PAGE_SIZE);
870         if ((pte & L2_S_CACHE_MASK) != pte_l2_s_cache_mode_pt) {
871                 /*
872                  * Page tables must have the cache-mode set to
873                  * Write-Thru.
874                  */
875                 *ptep = (pte & ~L2_S_CACHE_MASK) | pte_l2_s_cache_mode_pt;
876                 PTE_SYNC(ptep);
877                 cpu_tlb_flushD_SE(va);
878                 cpu_cpwait();
879         }
880
881         memset(mem, 0, L2_TABLE_SIZE_REAL);
882         return (0);
883 }
884
885 /*
886  * Modify pte bits for all ptes corresponding to the given physical address.
887  * We use `maskbits' rather than `clearbits' because we're always passing
888  * constants and the latter would require an extra inversion at run-time.
889  */
890 static int
891 pmap_clearbit(struct vm_page *pg, u_int maskbits)
892 {
893         struct l2_bucket *l2b;
894         struct pv_entry *pv;
895         pt_entry_t *ptep, npte, opte;
896         pmap_t pm;
897         vm_offset_t va;
898         u_int oflags;
899         int count = 0;
900
901         rw_wlock(&pvh_global_lock);
902
903         if (maskbits & PVF_WRITE)
904                 maskbits |= PVF_MOD;
905         /*
906          * Clear saved attributes (modify, reference)
907          */
908         pg->md.pvh_attrs &= ~(maskbits & (PVF_MOD | PVF_REF));
909
910         if (TAILQ_EMPTY(&pg->md.pv_list)) {
911                 rw_wunlock(&pvh_global_lock);
912                 return (0);
913         }
914
915         /*
916          * Loop over all current mappings setting/clearing as appropos
917          */
918         TAILQ_FOREACH(pv, &pg->md.pv_list, pv_list) {
919                 va = pv->pv_va;
920                 pm = PV_PMAP(pv);
921                 oflags = pv->pv_flags;
922                 pv->pv_flags &= ~maskbits;
923
924                 PMAP_LOCK(pm);
925
926                 l2b = pmap_get_l2_bucket(pm, va);
927
928                 ptep = &l2b->l2b_kva[l2pte_index(va)];
929                 npte = opte = *ptep;
930
931                 if ((maskbits & (PVF_WRITE|PVF_MOD)) && L2_S_WRITABLE(opte)) {
932                         vm_page_dirty(pg);
933
934                         /* make the pte read only */
935                         npte |= L2_APX;
936                 }
937
938                 if (maskbits & PVF_REF) {
939                         /*
940                          * Make the PTE invalid so that we will take a
941                          * page fault the next time the mapping is
942                          * referenced.
943                          */
944                         npte &= ~L2_TYPE_MASK;
945                         npte |= L2_TYPE_INV;
946                 }
947
948                 CTR4(KTR_PMAP,"clearbit: pmap:%p bits:%x pte:%x->%x",
949                     pm, maskbits, opte, npte);
950                 if (npte != opte) {
951                         count++;
952                         *ptep = npte;
953                         PTE_SYNC(ptep);
954                         /* Flush the TLB entry if a current pmap. */
955                         if (PV_BEEN_EXECD(oflags))
956                                 cpu_tlb_flushID_SE(pv->pv_va);
957                         else if (PV_BEEN_REFD(oflags))
958                                 cpu_tlb_flushD_SE(pv->pv_va);
959                 }
960
961                 PMAP_UNLOCK(pm);
962
963         }
964
965         if (maskbits & PVF_WRITE)
966                 vm_page_aflag_clear(pg, PGA_WRITEABLE);
967         rw_wunlock(&pvh_global_lock);
968         return (count);
969 }
970
971 /*
972  * main pv_entry manipulation functions:
973  *   pmap_enter_pv: enter a mapping onto a vm_page list
974  *   pmap_remove_pv: remove a mappiing from a vm_page list
975  *
976  * NOTE: pmap_enter_pv expects to lock the pvh itself
977  *       pmap_remove_pv expects the caller to lock the pvh before calling
978  */
979
980 /*
981  * pmap_enter_pv: enter a mapping onto a vm_page's PV list
982  *
983  * => caller should hold the proper lock on pvh_global_lock
984  * => caller should have pmap locked
985  * => we will (someday) gain the lock on the vm_page's PV list
986  * => caller should adjust ptp's wire_count before calling
987  * => caller should not adjust pmap's wire_count
988  */
989 static void
990 pmap_enter_pv(struct vm_page *pg, struct pv_entry *pve, pmap_t pm,
991     vm_offset_t va, u_int flags)
992 {
993
994         rw_assert(&pvh_global_lock, RA_WLOCKED);
995
996         PMAP_ASSERT_LOCKED(pm);
997         pve->pv_va = va;
998         pve->pv_flags = flags;
999
1000         TAILQ_INSERT_HEAD(&pg->md.pv_list, pve, pv_list);
1001         pg->md.pvh_attrs |= flags & (PVF_REF | PVF_MOD);
1002         if (pve->pv_flags & PVF_WIRED)
1003                 ++pm->pm_stats.wired_count;
1004         vm_page_aflag_set(pg, PGA_REFERENCED);
1005 }
1006
1007 /*
1008  *
1009  * pmap_find_pv: Find a pv entry
1010  *
1011  * => caller should hold lock on vm_page
1012  */
1013 static PMAP_INLINE struct pv_entry *
1014 pmap_find_pv(struct vm_page *pg, pmap_t pm, vm_offset_t va)
1015 {
1016         struct pv_entry *pv;
1017
1018         rw_assert(&pvh_global_lock, RA_WLOCKED);
1019         TAILQ_FOREACH(pv, &pg->md.pv_list, pv_list)
1020             if (pm == PV_PMAP(pv) && va == pv->pv_va)
1021                     break;
1022         return (pv);
1023 }
1024
1025 /*
1026  * vector_page_setprot:
1027  *
1028  *      Manipulate the protection of the vector page.
1029  */
1030 void
1031 vector_page_setprot(int prot)
1032 {
1033         struct l2_bucket *l2b;
1034         pt_entry_t *ptep;
1035
1036         l2b = pmap_get_l2_bucket(pmap_kernel(), vector_page);
1037
1038         ptep = &l2b->l2b_kva[l2pte_index(vector_page)];
1039
1040         pmap_set_prot(ptep, prot|VM_PROT_EXECUTE, 0);
1041
1042         cpu_tlb_flushD_SE(vector_page);
1043         cpu_cpwait();
1044 }
1045
1046 static void
1047 pmap_set_prot(pt_entry_t *ptep, vm_prot_t prot, uint8_t user)
1048 {
1049
1050         *ptep &= ~L2_S_PROT_MASK;
1051
1052         if (!(prot & VM_PROT_EXECUTE))
1053                 *ptep |= L2_XN;
1054
1055         *ptep |= L2_APX;
1056         *ptep |= L2_S_PROT_R;
1057
1058         if (user)
1059                 *ptep |= L2_S_PROT_U;
1060
1061         if (prot & VM_PROT_WRITE)
1062                 *ptep &= ~(L2_APX);
1063         else if (user)
1064                 *ptep &= ~(L2_S_PROT_R);
1065 }
1066
1067 /*
1068  * pmap_remove_pv: try to remove a mapping from a pv_list
1069  *
1070  * => caller should hold proper lock on pmap_main_lock
1071  * => pmap should be locked
1072  * => caller should hold lock on vm_page [so that attrs can be adjusted]
1073  * => caller should adjust ptp's wire_count and free PTP if needed
1074  * => caller should NOT adjust pmap's wire_count
1075  * => we return the removed pve
1076  */
1077
1078 static void
1079 pmap_nuke_pv(struct vm_page *pg, pmap_t pm, struct pv_entry *pve)
1080 {
1081
1082         rw_assert(&pvh_global_lock, RA_WLOCKED);
1083         PMAP_ASSERT_LOCKED(pm);
1084
1085         TAILQ_REMOVE(&pg->md.pv_list, pve, pv_list);
1086
1087         if (pve->pv_flags & PVF_WIRED)
1088                 --pm->pm_stats.wired_count;
1089
1090         if (pg->md.pvh_attrs & PVF_MOD)
1091                 vm_page_dirty(pg);
1092
1093         if (TAILQ_FIRST(&pg->md.pv_list) == NULL)
1094                 pg->md.pvh_attrs &= ~PVF_REF;
1095         else
1096                 vm_page_aflag_set(pg, PGA_REFERENCED);
1097
1098         if (pve->pv_flags & PVF_WRITE) {
1099                 TAILQ_FOREACH(pve, &pg->md.pv_list, pv_list)
1100                     if (pve->pv_flags & PVF_WRITE)
1101                             break;
1102                 if (!pve) {
1103                         pg->md.pvh_attrs &= ~PVF_MOD;
1104                         vm_page_aflag_clear(pg, PGA_WRITEABLE);
1105                 }
1106         }
1107 }
1108
1109 static struct pv_entry *
1110 pmap_remove_pv(struct vm_page *pg, pmap_t pm, vm_offset_t va)
1111 {
1112         struct pv_entry *pve;
1113
1114         rw_assert(&pvh_global_lock, RA_WLOCKED);
1115         pve = TAILQ_FIRST(&pg->md.pv_list);
1116
1117         while (pve) {
1118                 if (PV_PMAP(pve) == pm && pve->pv_va == va) {   /* match? */
1119                         pmap_nuke_pv(pg, pm, pve);
1120                         break;
1121                 }
1122                 pve = TAILQ_NEXT(pve, pv_list);
1123         }
1124
1125         return(pve);                            /* return removed pve */
1126 }
1127
1128 /*
1129  *
1130  * pmap_modify_pv: Update pv flags
1131  *
1132  * => caller should hold lock on vm_page [so that attrs can be adjusted]
1133  * => caller should NOT adjust pmap's wire_count
1134  * => we return the old flags
1135  *
1136  * Modify a physical-virtual mapping in the pv table
1137  */
1138 static u_int
1139 pmap_modify_pv(struct vm_page *pg, pmap_t pm, vm_offset_t va,
1140     u_int clr_mask, u_int set_mask)
1141 {
1142         struct pv_entry *npv;
1143         u_int flags, oflags;
1144
1145         PMAP_ASSERT_LOCKED(pm);
1146         rw_assert(&pvh_global_lock, RA_WLOCKED);
1147         if ((npv = pmap_find_pv(pg, pm, va)) == NULL)
1148                 return (0);
1149
1150         /*
1151          * There is at least one VA mapping this page.
1152          */
1153
1154         if (clr_mask & (PVF_REF | PVF_MOD))
1155                 pg->md.pvh_attrs |= set_mask & (PVF_REF | PVF_MOD);
1156
1157         oflags = npv->pv_flags;
1158         npv->pv_flags = flags = (oflags & ~clr_mask) | set_mask;
1159
1160         if ((flags ^ oflags) & PVF_WIRED) {
1161                 if (flags & PVF_WIRED)
1162                         ++pm->pm_stats.wired_count;
1163                 else
1164                         --pm->pm_stats.wired_count;
1165         }
1166         if ((oflags & PVF_WRITE) && !(flags & PVF_WRITE)) {
1167                 TAILQ_FOREACH(npv, &pg->md.pv_list, pv_list) {
1168                         if (npv->pv_flags & PVF_WRITE)
1169                                 break;
1170                 }
1171                 if (!npv) {
1172                         pg->md.pvh_attrs &= ~PVF_MOD;
1173                         vm_page_aflag_clear(pg, PGA_WRITEABLE);
1174                 }
1175         }
1176
1177         return (oflags);
1178 }
1179
1180 /* Function to set the debug level of the pmap code */
1181 #ifdef PMAP_DEBUG
1182 void
1183 pmap_debug(int level)
1184 {
1185         pmap_debug_level = level;
1186         dprintf("pmap_debug: level=%d\n", pmap_debug_level);
1187 }
1188 #endif  /* PMAP_DEBUG */
1189
1190 void
1191 pmap_pinit0(struct pmap *pmap)
1192 {
1193         PDEBUG(1, printf("pmap_pinit0: pmap = %08x\n", (u_int32_t) pmap));
1194
1195         dprintf("pmap_pinit0: pmap = %08x, pm_pdir = %08x\n",
1196                 (u_int32_t) pmap, (u_int32_t) pmap->pm_pdir);
1197         bcopy(kernel_pmap, pmap, sizeof(*pmap));
1198         bzero(&pmap->pm_mtx, sizeof(pmap->pm_mtx));
1199         PMAP_LOCK_INIT(pmap);
1200 }
1201
1202 /*
1203  *      Initialize a vm_page's machine-dependent fields.
1204  */
1205 void
1206 pmap_page_init(vm_page_t m)
1207 {
1208
1209         TAILQ_INIT(&m->md.pv_list);
1210         m->md.pv_memattr = VM_MEMATTR_DEFAULT;
1211 }
1212
1213 static vm_offset_t
1214 pmap_ptelist_alloc(vm_offset_t *head)
1215 {
1216         pt_entry_t *pte;
1217         vm_offset_t va;
1218
1219         va = *head;
1220         if (va == 0)
1221                 return (va);    /* Out of memory */
1222         pte = vtopte(va);
1223         *head = *pte;
1224         if ((*head & L2_TYPE_MASK) != L2_TYPE_INV)
1225                 panic("%s: va is not L2_TYPE_INV!", __func__);
1226         *pte = 0;
1227         return (va);
1228 }
1229
1230 static void
1231 pmap_ptelist_free(vm_offset_t *head, vm_offset_t va)
1232 {
1233         pt_entry_t *pte;
1234
1235         if ((va & L2_TYPE_MASK) != L2_TYPE_INV)
1236                 panic("%s: freeing va that is not L2_TYPE INV!", __func__);
1237         pte = vtopte(va);
1238         *pte = *head;           /* virtual! L2_TYPE is L2_TYPE_INV though */
1239         *head = va;
1240 }
1241
1242 static void
1243 pmap_ptelist_init(vm_offset_t *head, void *base, int npages)
1244 {
1245         int i;
1246         vm_offset_t va;
1247
1248         *head = 0;
1249         for (i = npages - 1; i >= 0; i--) {
1250                 va = (vm_offset_t)base + i * PAGE_SIZE;
1251                 pmap_ptelist_free(head, va);
1252         }
1253 }
1254
1255 /*
1256  *      Initialize the pmap module.
1257  *      Called by vm_init, to initialize any structures that the pmap
1258  *      system needs to map virtual memory.
1259  */
1260 void
1261 pmap_init(void)
1262 {
1263
1264         PDEBUG(1, printf("pmap_init: phys_start = %08x\n", PHYSADDR));
1265
1266         l2zone = uma_zcreate("L2 Table", L2_TABLE_SIZE_REAL, pmap_l2ptp_ctor,
1267             NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_VM | UMA_ZONE_NOFREE);
1268         l2table_zone = uma_zcreate("L2 Table", sizeof(struct l2_dtable), NULL,
1269             NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_VM | UMA_ZONE_NOFREE);
1270
1271         /*
1272          * Initialize the address space for the pv chunks.
1273          */
1274
1275         TUNABLE_INT_FETCH("vm.pmap.shpgperproc", &shpgperproc);
1276         pv_entry_max = shpgperproc * maxproc + cnt.v_page_count;
1277         TUNABLE_INT_FETCH("vm.pmap.pv_entries", &pv_entry_max);
1278         pv_entry_max = roundup(pv_entry_max, _NPCPV);
1279         pv_entry_high_water = 9 * (pv_entry_max / 10);
1280
1281         pv_maxchunks = MAX(pv_entry_max / _NPCPV, maxproc);
1282         pv_chunkbase = (struct pv_chunk *)kmem_alloc_nofault(kernel_map,
1283             PAGE_SIZE * pv_maxchunks);
1284
1285         if (pv_chunkbase == NULL)
1286                 panic("pmap_init: not enough kvm for pv chunks");
1287
1288         pmap_ptelist_init(&pv_vafree, pv_chunkbase, pv_maxchunks);
1289
1290         /*
1291          * Now it is safe to enable pv_table recording.
1292          */
1293         PDEBUG(1, printf("pmap_init: done!\n"));
1294 }
1295
1296 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_max, CTLFLAG_RD, &pv_entry_max, 0,
1297         "Max number of PV entries");
1298 SYSCTL_INT(_vm_pmap, OID_AUTO, shpgperproc, CTLFLAG_RD, &shpgperproc, 0,
1299         "Page share factor per proc");
1300
1301 int
1302 pmap_fault_fixup(pmap_t pm, vm_offset_t va, vm_prot_t ftype, int user)
1303 {
1304         struct l2_dtable *l2;
1305         struct l2_bucket *l2b;
1306         pd_entry_t *pl1pd, l1pd;
1307         pt_entry_t *ptep, pte;
1308         vm_paddr_t pa;
1309         u_int l1idx;
1310         int rv = 0;
1311
1312         l1idx = L1_IDX(va);
1313         rw_wlock(&pvh_global_lock);
1314         PMAP_LOCK(pm);
1315
1316         /*
1317          * If there is no l2_dtable for this address, then the process
1318          * has no business accessing it.
1319          *
1320          * Note: This will catch userland processes trying to access
1321          * kernel addresses.
1322          */
1323         l2 = pm->pm_l2[L2_IDX(l1idx)];
1324         if (l2 == NULL)
1325                 goto out;
1326
1327         /*
1328          * Likewise if there is no L2 descriptor table
1329          */
1330         l2b = &l2->l2_bucket[L2_BUCKET(l1idx)];
1331         if (l2b->l2b_kva == NULL)
1332                 goto out;
1333
1334         /*
1335          * Check the PTE itself.
1336          */
1337         ptep = &l2b->l2b_kva[l2pte_index(va)];
1338         pte = *ptep;
1339         if (pte == 0)
1340                 goto out;
1341
1342         /*
1343          * Catch a userland access to the vector page mapped at 0x0
1344          */
1345         if (user && !(pte & L2_S_PROT_U))
1346                 goto out;
1347         if (va == vector_page)
1348                 goto out;
1349
1350         pa = l2pte_pa(pte);
1351         CTR5(KTR_PMAP, "pmap_fault_fix: pmap:%p va:%x pte:0x%x ftype:%x user:%x",
1352             pm, va, pte, ftype, user);
1353         if ((ftype & VM_PROT_WRITE) && !(L2_S_WRITABLE(pte))) {
1354                 /*
1355                  * This looks like a good candidate for "page modified"
1356                  * emulation...
1357                  */
1358                 struct pv_entry *pv;
1359                 struct vm_page *pg;
1360
1361                 /* Extract the physical address of the page */
1362                 if ((pg = PHYS_TO_VM_PAGE(pa)) == NULL) {
1363                         goto out;
1364                 }
1365                 /* Get the current flags for this page. */
1366
1367                 pv = pmap_find_pv(pg, pm, va);
1368                 if (pv == NULL) {
1369                         goto out;
1370                 }
1371
1372                 /*
1373                  * Do the flags say this page is writable? If not then it
1374                  * is a genuine write fault. If yes then the write fault is
1375                  * our fault as we did not reflect the write access in the
1376                  * PTE. Now we know a write has occurred we can correct this
1377                  * and also set the modified bit
1378                  */
1379                 if ((pv->pv_flags & PVF_WRITE) == 0) {
1380                         goto out;
1381                 }
1382                 pg->md.pvh_attrs |= PVF_REF | PVF_MOD;
1383                 vm_page_dirty(pg);
1384                 pv->pv_flags |= PVF_REF | PVF_MOD;
1385
1386                 /* Re-enable write permissions for the page */
1387                 *ptep = (pte & ~L2_TYPE_MASK) | L2_S_PROTO;
1388                 pmap_set_prot(ptep, VM_PROT_WRITE, *ptep & L2_S_PROT_U);
1389                 CTR1(KTR_PMAP, "pmap_fault_fix: new pte:0x%x", pte);
1390                 PTE_SYNC(ptep);
1391                 rv = 1;
1392         } else if ((pte & L2_TYPE_MASK) == L2_TYPE_INV) {
1393                 /*
1394                  * This looks like a good candidate for "page referenced"
1395                  * emulation.
1396                  */
1397                 struct pv_entry *pv;
1398                 struct vm_page *pg;
1399
1400                 /* Extract the physical address of the page */
1401                 if ((pg = PHYS_TO_VM_PAGE(pa)) == NULL)
1402                         goto out;
1403                 /* Get the current flags for this page. */
1404
1405                 pv = pmap_find_pv(pg, pm, va);
1406                 if (pv == NULL)
1407                         goto out;
1408
1409                 pg->md.pvh_attrs |= PVF_REF;
1410                 pv->pv_flags |= PVF_REF;
1411
1412
1413                 *ptep = (pte & ~L2_TYPE_MASK) | L2_S_PROTO;
1414                 PTE_SYNC(ptep);
1415                 rv = 1;
1416         }
1417
1418         /*
1419          * We know there is a valid mapping here, so simply
1420          * fix up the L1 if necessary.
1421          */
1422         pl1pd = &pm->pm_l1->l1_kva[l1idx];
1423         l1pd = l2b->l2b_phys | L1_C_DOM(pm->pm_domain) | L1_C_PROTO;
1424         if (*pl1pd != l1pd) {
1425                 *pl1pd = l1pd;
1426                 PTE_SYNC(pl1pd);
1427                 rv = 1;
1428         }
1429
1430 #ifdef DEBUG
1431         /*
1432          * If 'rv == 0' at this point, it generally indicates that there is a
1433          * stale TLB entry for the faulting address. This happens when two or
1434          * more processes are sharing an L1. Since we don't flush the TLB on
1435          * a context switch between such processes, we can take domain faults
1436          * for mappings which exist at the same VA in both processes. EVEN IF
1437          * WE'VE RECENTLY FIXED UP THE CORRESPONDING L1 in pmap_enter(), for
1438          * example.
1439          *
1440          * This is extremely likely to happen if pmap_enter() updated the L1
1441          * entry for a recently entered mapping. In this case, the TLB is
1442          * flushed for the new mapping, but there may still be TLB entries for
1443          * other mappings belonging to other processes in the 1MB range
1444          * covered by the L1 entry.
1445          *
1446          * Since 'rv == 0', we know that the L1 already contains the correct
1447          * value, so the fault must be due to a stale TLB entry.
1448          *
1449          * Since we always need to flush the TLB anyway in the case where we
1450          * fixed up the L1, or frobbed the L2 PTE, we effectively deal with
1451          * stale TLB entries dynamically.
1452          *
1453          * However, the above condition can ONLY happen if the current L1 is
1454          * being shared. If it happens when the L1 is unshared, it indicates
1455          * that other parts of the pmap are not doing their job WRT managing
1456          * the TLB.
1457          */
1458         if (rv == 0 && pm->pm_l1->l1_domain_use_count == 1) {
1459                 printf("fixup: pm %p, va 0x%08x, ftype %d - nothing to do!\n",
1460                     pm, va, ftype);
1461                 printf("fixup: l2 %p, l2b %p, ptep %p, pl1pd %p\n",
1462                     l2, l2b, ptep, pl1pd);
1463                 printf("fixup: pte 0x%x, l1pd 0x%x, last code 0x%x\n",
1464                     pte, l1pd, last_fault_code);
1465 #ifdef DDB
1466                 Debugger();
1467 #endif
1468         }
1469 #endif
1470
1471         cpu_tlb_flushID_SE(va);
1472         cpu_cpwait();
1473
1474         rv = 1;
1475
1476 out:
1477         rw_wunlock(&pvh_global_lock);
1478         PMAP_UNLOCK(pm);
1479         return (rv);
1480 }
1481
1482 void
1483 pmap_postinit(void)
1484 {
1485         struct l2_bucket *l2b;
1486         struct l1_ttable *l1;
1487         pd_entry_t *pl1pt;
1488         pt_entry_t *ptep, pte;
1489         vm_offset_t va, eva;
1490         u_int loop, needed;
1491
1492         needed = (maxproc / PMAP_DOMAINS) + ((maxproc % PMAP_DOMAINS) ? 1 : 0);
1493         needed -= 1;
1494         l1 = malloc(sizeof(*l1) * needed, M_VMPMAP, M_WAITOK);
1495
1496         for (loop = 0; loop < needed; loop++, l1++) {
1497                 /* Allocate a L1 page table */
1498                 va = (vm_offset_t)contigmalloc(L1_TABLE_SIZE, M_VMPMAP, 0, 0x0,
1499                     0xffffffff, L1_TABLE_SIZE, 0);
1500
1501                 if (va == 0)
1502                         panic("Cannot allocate L1 KVM");
1503
1504                 eva = va + L1_TABLE_SIZE;
1505                 pl1pt = (pd_entry_t *)va;
1506
1507                 while (va < eva) {
1508                                 l2b = pmap_get_l2_bucket(pmap_kernel(), va);
1509                                 ptep = &l2b->l2b_kva[l2pte_index(va)];
1510                                 pte = *ptep;
1511                                 pte = (pte & ~L2_S_CACHE_MASK) | pte_l2_s_cache_mode_pt;
1512                                 *ptep = pte;
1513                                 PTE_SYNC(ptep);
1514                                 cpu_tlb_flushD_SE(va);
1515
1516                                 va += PAGE_SIZE;
1517                 }
1518                 pmap_init_l1(l1, pl1pt);
1519         }
1520 #ifdef DEBUG
1521         printf("pmap_postinit: Allocated %d static L1 descriptor tables\n",
1522             needed);
1523 #endif
1524 }
1525
1526 /*
1527  * This is used to stuff certain critical values into the PCB where they
1528  * can be accessed quickly from cpu_switch() et al.
1529  */
1530 void
1531 pmap_set_pcb_pagedir(pmap_t pm, struct pcb *pcb)
1532 {
1533         struct l2_bucket *l2b;
1534
1535         pcb->pcb_pagedir = pm->pm_l1->l1_physaddr;
1536         pcb->pcb_dacr = (DOMAIN_CLIENT << (PMAP_DOMAIN_KERNEL * 2)) |
1537             (DOMAIN_CLIENT << (pm->pm_domain * 2));
1538
1539         if (vector_page < KERNBASE) {
1540                 pcb->pcb_pl1vec = &pm->pm_l1->l1_kva[L1_IDX(vector_page)];
1541                 l2b = pmap_get_l2_bucket(pm, vector_page);
1542                 pcb->pcb_l1vec = l2b->l2b_phys | L1_C_PROTO |
1543                     L1_C_DOM(pm->pm_domain) | L1_C_DOM(PMAP_DOMAIN_KERNEL);
1544         } else
1545                 pcb->pcb_pl1vec = NULL;
1546 }
1547
1548 void
1549 pmap_activate(struct thread *td)
1550 {
1551         pmap_t pm;
1552         struct pcb *pcb;
1553
1554         pm = vmspace_pmap(td->td_proc->p_vmspace);
1555         pcb = td->td_pcb;
1556
1557         critical_enter();
1558         pmap_set_pcb_pagedir(pm, pcb);
1559
1560         if (td == curthread) {
1561                 u_int cur_dacr, cur_ttb;
1562
1563                 __asm __volatile("mrc p15, 0, %0, c2, c0, 0" : "=r"(cur_ttb));
1564                 __asm __volatile("mrc p15, 0, %0, c3, c0, 0" : "=r"(cur_dacr));
1565
1566                 cur_ttb &= ~(L1_TABLE_SIZE - 1);
1567
1568                 if (cur_ttb == (u_int)pcb->pcb_pagedir &&
1569                     cur_dacr == pcb->pcb_dacr) {
1570                         /*
1571                          * No need to switch address spaces.
1572                          */
1573                         critical_exit();
1574                         return;
1575                 }
1576
1577
1578                 /*
1579                  * We MUST, I repeat, MUST fix up the L1 entry corresponding
1580                  * to 'vector_page' in the incoming L1 table before switching
1581                  * to it otherwise subsequent interrupts/exceptions (including
1582                  * domain faults!) will jump into hyperspace.
1583                  */
1584                 if (pcb->pcb_pl1vec) {
1585                         *pcb->pcb_pl1vec = pcb->pcb_l1vec;
1586                 }
1587
1588                 cpu_domains(pcb->pcb_dacr);
1589                 cpu_setttb(pcb->pcb_pagedir);
1590         }
1591         critical_exit();
1592 }
1593
1594 static int
1595 pmap_set_pt_cache_mode(pd_entry_t *kl1, vm_offset_t va)
1596 {
1597         pd_entry_t *pdep, pde;
1598         pt_entry_t *ptep, pte;
1599         vm_offset_t pa;
1600         int rv = 0;
1601
1602         /*
1603          * Make sure the descriptor itself has the correct cache mode
1604          */
1605         pdep = &kl1[L1_IDX(va)];
1606         pde = *pdep;
1607
1608         if (l1pte_section_p(pde)) {
1609                 if ((pde & L1_S_CACHE_MASK) != pte_l1_s_cache_mode_pt) {
1610                         *pdep = (pde & ~L1_S_CACHE_MASK) |
1611                             pte_l1_s_cache_mode_pt;
1612                         PTE_SYNC(pdep);
1613                         rv = 1;
1614                 }
1615         } else {
1616                 pa = (vm_paddr_t)(pde & L1_C_ADDR_MASK);
1617                 ptep = (pt_entry_t *)kernel_pt_lookup(pa);
1618                 if (ptep == NULL)
1619                         panic("pmap_bootstrap: No L2 for L2 @ va %p\n", ptep);
1620
1621                 ptep = &ptep[l2pte_index(va)];
1622                 pte = *ptep;
1623                 if ((pte & L2_S_CACHE_MASK) != pte_l2_s_cache_mode_pt) {
1624                         *ptep = (pte & ~L2_S_CACHE_MASK) |
1625                             pte_l2_s_cache_mode_pt;
1626                         PTE_SYNC(ptep);
1627                         rv = 1;
1628                 }
1629         }
1630
1631         return (rv);
1632 }
1633
1634 static void
1635 pmap_alloc_specials(vm_offset_t *availp, int pages, vm_offset_t *vap,
1636     pt_entry_t **ptep)
1637 {
1638         vm_offset_t va = *availp;
1639         struct l2_bucket *l2b;
1640
1641         if (ptep) {
1642                 l2b = pmap_get_l2_bucket(pmap_kernel(), va);
1643                 if (l2b == NULL)
1644                         panic("pmap_alloc_specials: no l2b for 0x%x", va);
1645
1646                 *ptep = &l2b->l2b_kva[l2pte_index(va)];
1647         }
1648
1649         *vap = va;
1650         *availp = va + (PAGE_SIZE * pages);
1651 }
1652
1653 /*
1654  *      Bootstrap the system enough to run with virtual memory.
1655  *
1656  *      On the arm this is called after mapping has already been enabled
1657  *      and just syncs the pmap module with what has already been done.
1658  *      [We can't call it easily with mapping off since the kernel is not
1659  *      mapped with PA == VA, hence we would have to relocate every address
1660  *      from the linked base (virtual) address "KERNBASE" to the actual
1661  *      (physical) address starting relative to 0]
1662  */
1663 #define PMAP_STATIC_L2_SIZE 16
1664
1665 void
1666 pmap_bootstrap(vm_offset_t firstaddr, struct pv_addr *l1pt)
1667 {
1668         static struct l1_ttable static_l1;
1669         static struct l2_dtable static_l2[PMAP_STATIC_L2_SIZE];
1670         struct l1_ttable *l1 = &static_l1;
1671         struct l2_dtable *l2;
1672         struct l2_bucket *l2b;
1673         pd_entry_t pde;
1674         pd_entry_t *kernel_l1pt = (pd_entry_t *)l1pt->pv_va;
1675         pt_entry_t *ptep;
1676         vm_paddr_t pa;
1677         vm_offset_t va;
1678         vm_size_t size;
1679         int l1idx, l2idx, l2next = 0;
1680
1681         PDEBUG(1, printf("firstaddr = %08x, lastaddr = %08x\n",
1682             firstaddr, vm_max_kernel_address));
1683
1684         virtual_avail = firstaddr;
1685         kernel_pmap->pm_l1 = l1;
1686         kernel_l1pa = l1pt->pv_pa;
1687
1688         /*
1689          * Scan the L1 translation table created by initarm() and create
1690          * the required metadata for all valid mappings found in it.
1691          */
1692         for (l1idx = 0; l1idx < (L1_TABLE_SIZE / sizeof(pd_entry_t)); l1idx++) {
1693                 pde = kernel_l1pt[l1idx];
1694
1695                 /*
1696                  * We're only interested in Coarse mappings.
1697                  * pmap_extract() can deal with section mappings without
1698                  * recourse to checking L2 metadata.
1699                  */
1700                 if ((pde & L1_TYPE_MASK) != L1_TYPE_C)
1701                         continue;
1702
1703                 /*
1704                  * Lookup the KVA of this L2 descriptor table
1705                  */
1706                 pa = (vm_paddr_t)(pde & L1_C_ADDR_MASK);
1707                 ptep = (pt_entry_t *)kernel_pt_lookup(pa);
1708
1709                 if (ptep == NULL) {
1710                         panic("pmap_bootstrap: No L2 for va 0x%x, pa 0x%lx",
1711                             (u_int)l1idx << L1_S_SHIFT, (long unsigned int)pa);
1712                 }
1713
1714                 /*
1715                  * Fetch the associated L2 metadata structure.
1716                  * Allocate a new one if necessary.
1717                  */
1718                 if ((l2 = kernel_pmap->pm_l2[L2_IDX(l1idx)]) == NULL) {
1719                         if (l2next == PMAP_STATIC_L2_SIZE)
1720                                 panic("pmap_bootstrap: out of static L2s");
1721                         kernel_pmap->pm_l2[L2_IDX(l1idx)] = l2 =
1722                             &static_l2[l2next++];
1723                 }
1724
1725                 /*
1726                  * One more L1 slot tracked...
1727                  */
1728                 l2->l2_occupancy++;
1729
1730                 /*
1731                  * Fill in the details of the L2 descriptor in the
1732                  * appropriate bucket.
1733                  */
1734                 l2b = &l2->l2_bucket[L2_BUCKET(l1idx)];
1735                 l2b->l2b_kva = ptep;
1736                 l2b->l2b_phys = pa;
1737                 l2b->l2b_l1idx = l1idx;
1738
1739                 /*
1740                  * Establish an initial occupancy count for this descriptor
1741                  */
1742                 for (l2idx = 0;
1743                     l2idx < (L2_TABLE_SIZE_REAL / sizeof(pt_entry_t));
1744                     l2idx++) {
1745                         if ((ptep[l2idx] & L2_TYPE_MASK) != L2_TYPE_INV) {
1746                                 l2b->l2b_occupancy++;
1747                         }
1748                 }
1749
1750                 /*
1751                  * Make sure the descriptor itself has the correct cache mode.
1752                  * If not, fix it, but whine about the problem. Port-meisters
1753                  * should consider this a clue to fix up their initarm()
1754                  * function. :)
1755                  */
1756                 if (pmap_set_pt_cache_mode(kernel_l1pt, (vm_offset_t)ptep)) {
1757                         printf("pmap_bootstrap: WARNING! wrong cache mode for "
1758                             "L2 pte @ %p\n", ptep);
1759                 }
1760         }
1761
1762
1763         /*
1764          * Ensure the primary (kernel) L1 has the correct cache mode for
1765          * a page table. Bitch if it is not correctly set.
1766          */
1767         for (va = (vm_offset_t)kernel_l1pt;
1768             va < ((vm_offset_t)kernel_l1pt + L1_TABLE_SIZE); va += PAGE_SIZE) {
1769                 if (pmap_set_pt_cache_mode(kernel_l1pt, va))
1770                         printf("pmap_bootstrap: WARNING! wrong cache mode for "
1771                             "primary L1 @ 0x%x\n", va);
1772         }
1773
1774         cpu_dcache_wbinv_all();
1775         cpu_l2cache_wbinv_all();
1776         cpu_tlb_flushID();
1777         cpu_cpwait();
1778
1779         PMAP_LOCK_INIT(kernel_pmap);
1780         CPU_FILL(&kernel_pmap->pm_active);
1781         kernel_pmap->pm_domain = PMAP_DOMAIN_KERNEL;
1782         TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1783
1784         /*
1785          * Initialize the global pv list lock.
1786          */
1787         rw_init(&pvh_global_lock, "pmap pv global");
1788
1789         /*
1790          * Reserve some special page table entries/VA space for temporary
1791          * mapping of pages.
1792          */
1793
1794         pmap_alloc_specials(&virtual_avail, 1, &csrcp, &csrc_pte);
1795         pmap_set_pt_cache_mode(kernel_l1pt, (vm_offset_t)csrc_pte);
1796         pmap_alloc_specials(&virtual_avail, 1, &cdstp, &cdst_pte);
1797         pmap_set_pt_cache_mode(kernel_l1pt, (vm_offset_t)cdst_pte);
1798         size = ((vm_max_kernel_address - pmap_curmaxkvaddr) + L1_S_OFFSET) /
1799             L1_S_SIZE;
1800         pmap_alloc_specials(&virtual_avail,
1801             round_page(size * L2_TABLE_SIZE_REAL) / PAGE_SIZE,
1802             &pmap_kernel_l2ptp_kva, NULL);
1803
1804         size = (size + (L2_BUCKET_SIZE - 1)) / L2_BUCKET_SIZE;
1805         pmap_alloc_specials(&virtual_avail,
1806             round_page(size * sizeof(struct l2_dtable)) / PAGE_SIZE,
1807             &pmap_kernel_l2dtable_kva, NULL);
1808
1809         pmap_alloc_specials(&virtual_avail,
1810             1, (vm_offset_t*)&_tmppt, NULL);
1811         pmap_alloc_specials(&virtual_avail,
1812             MAXDUMPPGS, (vm_offset_t *)&crashdumpmap, NULL);
1813         SLIST_INIT(&l1_list);
1814         TAILQ_INIT(&l1_lru_list);
1815         mtx_init(&l1_lru_lock, "l1 list lock", NULL, MTX_DEF);
1816         pmap_init_l1(l1, kernel_l1pt);
1817         cpu_dcache_wbinv_all();
1818         cpu_l2cache_wbinv_all();
1819
1820         virtual_avail = round_page(virtual_avail);
1821         virtual_end = vm_max_kernel_address;
1822         kernel_vm_end = pmap_curmaxkvaddr;
1823         arm_nocache_startaddr = vm_max_kernel_address;
1824         mtx_init(&cmtx, "TMP mappings mtx", NULL, MTX_DEF);
1825
1826         pmap_set_pcb_pagedir(kernel_pmap, thread0.td_pcb);
1827 }
1828
1829 /***************************************************
1830  * Pmap allocation/deallocation routines.
1831  ***************************************************/
1832
1833 /*
1834  * Release any resources held by the given physical map.
1835  * Called when a pmap initialized by pmap_pinit is being released.
1836  * Should only be called if the map contains no valid mappings.
1837  */
1838 void
1839 pmap_release(pmap_t pmap)
1840 {
1841         struct pcb *pcb;
1842
1843         cpu_idcache_wbinv_all();
1844         cpu_l2cache_wbinv_all();
1845         cpu_tlb_flushID();
1846         cpu_cpwait();
1847         if (vector_page < KERNBASE) {
1848                 struct pcb *curpcb = PCPU_GET(curpcb);
1849                 pcb = thread0.td_pcb;
1850                 if (pmap_is_current(pmap)) {
1851                         /*
1852                          * Frob the L1 entry corresponding to the vector
1853                          * page so that it contains the kernel pmap's domain
1854                          * number. This will ensure pmap_remove() does not
1855                          * pull the current vector page out from under us.
1856                          */
1857                         critical_enter();
1858                         *pcb->pcb_pl1vec = pcb->pcb_l1vec;
1859                         cpu_domains(pcb->pcb_dacr);
1860                         cpu_setttb(pcb->pcb_pagedir);
1861                         critical_exit();
1862                 }
1863                 pmap_remove(pmap, vector_page, vector_page + PAGE_SIZE);
1864                 /*
1865                  * Make sure cpu_switch(), et al, DTRT. This is safe to do
1866                  * since this process has no remaining mappings of its own.
1867                  */
1868                 curpcb->pcb_pl1vec = pcb->pcb_pl1vec;
1869                 curpcb->pcb_l1vec = pcb->pcb_l1vec;
1870                 curpcb->pcb_dacr = pcb->pcb_dacr;
1871                 curpcb->pcb_pagedir = pcb->pcb_pagedir;
1872
1873         }
1874         pmap_free_l1(pmap);
1875         PMAP_LOCK_DESTROY(pmap);
1876
1877         dprintf("pmap_release()\n");
1878 }
1879
1880
1881
1882 /*
1883  * Helper function for pmap_grow_l2_bucket()
1884  */
1885 static __inline int
1886 pmap_grow_map(vm_offset_t va, pt_entry_t cache_mode, vm_paddr_t *pap)
1887 {
1888         struct l2_bucket *l2b;
1889         pt_entry_t *ptep;
1890         vm_paddr_t pa;
1891         struct vm_page *pg;
1892
1893         pg = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ | VM_ALLOC_WIRED);
1894         if (pg == NULL)
1895                 return (1);
1896         pa = VM_PAGE_TO_PHYS(pg);
1897
1898         if (pap)
1899                 *pap = pa;
1900
1901         l2b = pmap_get_l2_bucket(pmap_kernel(), va);
1902
1903         ptep = &l2b->l2b_kva[l2pte_index(va)];
1904         *ptep = L2_S_PROTO | pa | cache_mode;
1905         pmap_set_prot(ptep, VM_PROT_READ | VM_PROT_WRITE, 0);
1906         PTE_SYNC(ptep);
1907
1908         return (0);
1909 }
1910
1911 /*
1912  * This is the same as pmap_alloc_l2_bucket(), except that it is only
1913  * used by pmap_growkernel().
1914  */
1915 static __inline struct l2_bucket *
1916 pmap_grow_l2_bucket(pmap_t pm, vm_offset_t va)
1917 {
1918         struct l2_dtable *l2;
1919         struct l2_bucket *l2b;
1920         struct l1_ttable *l1;
1921         pd_entry_t *pl1pd;
1922         u_short l1idx;
1923         vm_offset_t nva;
1924
1925         l1idx = L1_IDX(va);
1926
1927         if ((l2 = pm->pm_l2[L2_IDX(l1idx)]) == NULL) {
1928                 /*
1929                  * No mapping at this address, as there is
1930                  * no entry in the L1 table.
1931                  * Need to allocate a new l2_dtable.
1932                  */
1933                 nva = pmap_kernel_l2dtable_kva;
1934                 if ((nva & PAGE_MASK) == 0) {
1935                         /*
1936                          * Need to allocate a backing page
1937                          */
1938                         if (pmap_grow_map(nva, pte_l2_s_cache_mode, NULL))
1939                                 return (NULL);
1940                 }
1941
1942                 l2 = (struct l2_dtable *)nva;
1943                 nva += sizeof(struct l2_dtable);
1944
1945                 if ((nva & PAGE_MASK) < (pmap_kernel_l2dtable_kva &
1946                     PAGE_MASK)) {
1947                         /*
1948                          * The new l2_dtable straddles a page boundary.
1949                          * Map in another page to cover it.
1950                          */
1951                         if (pmap_grow_map(nva, pte_l2_s_cache_mode, NULL))
1952                                 return (NULL);
1953                 }
1954
1955                 pmap_kernel_l2dtable_kva = nva;
1956
1957                 /*
1958                  * Link it into the parent pmap
1959                  */
1960                 pm->pm_l2[L2_IDX(l1idx)] = l2;
1961                 memset(l2, 0, sizeof(*l2));
1962         }
1963
1964         l2b = &l2->l2_bucket[L2_BUCKET(l1idx)];
1965
1966         /*
1967          * Fetch pointer to the L2 page table associated with the address.
1968          */
1969         if (l2b->l2b_kva == NULL) {
1970                 pt_entry_t *ptep;
1971
1972                 /*
1973                  * No L2 page table has been allocated. Chances are, this
1974                  * is because we just allocated the l2_dtable, above.
1975                  */
1976                 nva = pmap_kernel_l2ptp_kva;
1977                 ptep = (pt_entry_t *)nva;
1978                 if ((nva & PAGE_MASK) == 0) {
1979                         /*
1980                          * Need to allocate a backing page
1981                          */
1982                         if (pmap_grow_map(nva, pte_l2_s_cache_mode_pt,
1983                             &pmap_kernel_l2ptp_phys))
1984                                 return (NULL);
1985                 }
1986                 memset(ptep, 0, L2_TABLE_SIZE_REAL);
1987                 l2->l2_occupancy++;
1988                 l2b->l2b_kva = ptep;
1989                 l2b->l2b_l1idx = l1idx;
1990                 l2b->l2b_phys = pmap_kernel_l2ptp_phys;
1991
1992                 pmap_kernel_l2ptp_kva += L2_TABLE_SIZE_REAL;
1993                 pmap_kernel_l2ptp_phys += L2_TABLE_SIZE_REAL;
1994         }
1995
1996         /* Distribute new L1 entry to all other L1s */
1997         SLIST_FOREACH(l1, &l1_list, l1_link) {
1998                         pl1pd = &l1->l1_kva[L1_IDX(va)];
1999                         *pl1pd = l2b->l2b_phys | L1_C_DOM(PMAP_DOMAIN_KERNEL) |
2000                             L1_C_PROTO;
2001                         PTE_SYNC(pl1pd);
2002         }
2003
2004         return (l2b);
2005 }
2006
2007
2008 /*
2009  * grow the number of kernel page table entries, if needed
2010  */
2011 void
2012 pmap_growkernel(vm_offset_t addr)
2013 {
2014         pmap_t kpm = pmap_kernel();
2015
2016         if (addr <= pmap_curmaxkvaddr)
2017                 return;         /* we are OK */
2018
2019         /*
2020          * whoops!   we need to add kernel PTPs
2021          */
2022
2023         /* Map 1MB at a time */
2024         for (; pmap_curmaxkvaddr < addr; pmap_curmaxkvaddr += L1_S_SIZE)
2025                 pmap_grow_l2_bucket(kpm, pmap_curmaxkvaddr);
2026
2027         /*
2028          * flush out the cache, expensive but growkernel will happen so
2029          * rarely
2030          */
2031         cpu_dcache_wbinv_all();
2032         cpu_l2cache_wbinv_all();
2033         cpu_tlb_flushD();
2034         cpu_cpwait();
2035         kernel_vm_end = pmap_curmaxkvaddr;
2036 }
2037
2038
2039 /*
2040  * Remove all pages from specified address space
2041  * this aids process exit speeds.  Also, this code
2042  * is special cased for current process only, but
2043  * can have the more generic (and slightly slower)
2044  * mode enabled.  This is much faster than pmap_remove
2045  * in the case of running down an entire address space.
2046  */
2047 void
2048 pmap_remove_pages(pmap_t pmap)
2049 {
2050         struct pv_entry *pv;
2051         struct l2_bucket *l2b = NULL;
2052         vm_page_t m;
2053         pt_entry_t *pt;
2054         struct pv_chunk *pc, *npc;
2055         uint32_t inuse, bitmask;
2056         int allfree, bit, field, idx;
2057  
2058         rw_wlock(&pvh_global_lock);
2059         PMAP_LOCK(pmap);
2060
2061         TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
2062                 allfree = 1;
2063                 for (field = 0; field < _NPCM; field++) {
2064                         inuse = ~pc->pc_map[field] & pc_freemask[field];
2065                         while (inuse != 0) {
2066                                 bit = ffs(inuse) - 1;
2067                                 bitmask = 1ul << bit;
2068                                 idx = field * sizeof(inuse) * NBBY + bit;
2069                                 pv = &pc->pc_pventry[idx];
2070                                 inuse &= ~bitmask;
2071                                 if (pv->pv_flags & PVF_WIRED) {
2072                                         /* Cannot remove wired pages now. */
2073                                         allfree = 0;
2074                                         continue;
2075                                 }
2076                                 l2b = pmap_get_l2_bucket(pmap, pv->pv_va);
2077                                 KASSERT(l2b != NULL, ("No L2 bucket in pmap_remove_pages"));
2078                                 pt = &l2b->l2b_kva[l2pte_index(pv->pv_va)];
2079                                 m = PHYS_TO_VM_PAGE(*pt & L2_ADDR_MASK);
2080                                 KASSERT((vm_offset_t)m >= KERNBASE, ("Trying to access non-existent page va %x pte %x", pv->pv_va, *pt));
2081                                 *pt = 0;
2082                                 PTE_SYNC(pt);
2083
2084                                 /* Mark free */
2085                                 PV_STAT(pv_entry_frees++);
2086                                 PV_STAT(pv_entry_spare++);
2087                                 pv_entry_count--;
2088                                 pmap->pm_stats.resident_count--;
2089                                 pc->pc_map[field] |= bitmask;
2090                                 pmap_nuke_pv(m, pmap, pv);
2091                                 pmap_free_l2_bucket(pmap, l2b, 1);
2092                         }
2093                 }
2094                 if (allfree) {
2095                         TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2096                         pmap_free_pv_chunk(pc);
2097                 }
2098
2099         }
2100
2101         rw_wunlock(&pvh_global_lock);
2102         cpu_tlb_flushID();
2103         cpu_cpwait();
2104         PMAP_UNLOCK(pmap);
2105 }
2106
2107
2108 /***************************************************
2109  * Low level mapping routines.....
2110  ***************************************************/
2111
2112 #ifdef ARM_HAVE_SUPERSECTIONS
2113 /* Map a super section into the KVA. */
2114
2115 void
2116 pmap_kenter_supersection(vm_offset_t va, uint64_t pa, int flags)
2117 {
2118         pd_entry_t pd = L1_S_PROTO | L1_S_SUPERSEC | (pa & L1_SUP_FRAME) |
2119             (((pa >> 32) & 0xf) << 20) | L1_S_PROT(PTE_KERNEL,
2120             VM_PROT_READ|VM_PROT_WRITE) | L1_S_DOM(PMAP_DOMAIN_KERNEL);
2121         struct l1_ttable *l1;
2122         vm_offset_t va0, va_end;
2123
2124         KASSERT(((va | pa) & L1_SUP_OFFSET) == 0,
2125             ("Not a valid super section mapping"));
2126         if (flags & SECTION_CACHE)
2127                 pd |= pte_l1_s_cache_mode;
2128         else if (flags & SECTION_PT)
2129                 pd |= pte_l1_s_cache_mode_pt;
2130
2131         va0 = va & L1_SUP_FRAME;
2132         va_end = va + L1_SUP_SIZE;
2133         SLIST_FOREACH(l1, &l1_list, l1_link) {
2134                 va = va0;
2135                 for (; va < va_end; va += L1_S_SIZE) {
2136                         l1->l1_kva[L1_IDX(va)] = pd;
2137                         PTE_SYNC(&l1->l1_kva[L1_IDX(va)]);
2138                 }
2139         }
2140 }
2141 #endif
2142
2143 /* Map a section into the KVA. */
2144
2145 void
2146 pmap_kenter_section(vm_offset_t va, vm_offset_t pa, int flags)
2147 {
2148         pd_entry_t pd = L1_S_PROTO | pa | L1_S_PROT(PTE_KERNEL,
2149             VM_PROT_READ|VM_PROT_WRITE) | L1_S_DOM(PMAP_DOMAIN_KERNEL);
2150         struct l1_ttable *l1;
2151
2152         KASSERT(((va | pa) & L1_S_OFFSET) == 0,
2153             ("Not a valid section mapping"));
2154         if (flags & SECTION_CACHE)
2155                 pd |= pte_l1_s_cache_mode;
2156         else if (flags & SECTION_PT)
2157                 pd |= pte_l1_s_cache_mode_pt;
2158
2159         SLIST_FOREACH(l1, &l1_list, l1_link) {
2160                 l1->l1_kva[L1_IDX(va)] = pd;
2161                 PTE_SYNC(&l1->l1_kva[L1_IDX(va)]);
2162         }
2163 }
2164
2165 /*
2166  * Make a temporary mapping for a physical address.  This is only intended
2167  * to be used for panic dumps.
2168  */
2169 void *
2170 pmap_kenter_temp(vm_paddr_t pa, int i)
2171 {
2172         vm_offset_t va;
2173
2174         va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
2175         pmap_kenter(va, pa);
2176         return ((void *)crashdumpmap);
2177 }
2178
2179 /*
2180  * add a wired page to the kva
2181  * note that in order for the mapping to take effect -- you
2182  * should do a invltlb after doing the pmap_kenter...
2183  */
2184 static PMAP_INLINE void
2185 pmap_kenter_internal(vm_offset_t va, vm_offset_t pa, int flags)
2186 {
2187         struct l2_bucket *l2b;
2188         pt_entry_t *pte;
2189         pt_entry_t opte;
2190
2191         PDEBUG(1, printf("pmap_kenter: va = %08x, pa = %08x\n",
2192             (uint32_t) va, (uint32_t) pa));
2193
2194
2195         l2b = pmap_get_l2_bucket(pmap_kernel(), va);
2196         if (l2b == NULL)
2197                 l2b = pmap_grow_l2_bucket(pmap_kernel(), va);
2198         KASSERT(l2b != NULL, ("No L2 Bucket"));
2199
2200         pte = &l2b->l2b_kva[l2pte_index(va)];
2201         opte = *pte;
2202         if (l2pte_valid(opte)) {
2203                 cpu_tlb_flushD_SE(va);
2204                 cpu_cpwait();
2205         } else {
2206                 if (opte == 0)
2207                         l2b->l2b_occupancy++;
2208         }
2209
2210         if (flags & KENTER_CACHE) {
2211                 *pte = L2_S_PROTO | pa | pte_l2_s_cache_mode;
2212                 pmap_set_prot(pte, VM_PROT_READ | VM_PROT_WRITE,
2213                     flags & KENTER_USER);
2214         } else {
2215                 *pte = L2_S_PROTO | pa;
2216                 pmap_set_prot(pte, VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE,
2217                     0);
2218         }
2219
2220         PDEBUG(1, printf("pmap_kenter: pte = %08x, opte = %08x, npte = %08x\n",
2221             (uint32_t) pte, opte, *pte));
2222         PTE_SYNC(pte);
2223         cpu_cpwait();
2224 }
2225
2226 void
2227 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
2228 {
2229         pmap_kenter_internal(va, pa, KENTER_CACHE);
2230 }
2231
2232 void
2233 pmap_kenter_nocache(vm_offset_t va, vm_paddr_t pa)
2234 {
2235
2236         pmap_kenter_internal(va, pa, 0);
2237 }
2238
2239 void
2240 pmap_kenter_user(vm_offset_t va, vm_paddr_t pa)
2241 {
2242
2243         pmap_kenter_internal(va, pa, KENTER_CACHE|KENTER_USER);
2244         /*
2245          * Call pmap_fault_fixup now, to make sure we'll have no exception
2246          * at the first use of the new address, or bad things will happen,
2247          * as we use one of these addresses in the exception handlers.
2248          */
2249         pmap_fault_fixup(pmap_kernel(), va, VM_PROT_READ|VM_PROT_WRITE, 1);
2250 }
2251
2252 vm_paddr_t
2253 pmap_kextract(vm_offset_t va)
2254 {
2255
2256         return (pmap_extract_locked(kernel_pmap, va));
2257 }
2258
2259 /*
2260  * remove a page from the kernel pagetables
2261  */
2262 void
2263 pmap_kremove(vm_offset_t va)
2264 {
2265         struct l2_bucket *l2b;
2266         pt_entry_t *pte, opte;
2267
2268         l2b = pmap_get_l2_bucket(pmap_kernel(), va);
2269         if (!l2b)
2270                 return;
2271         KASSERT(l2b != NULL, ("No L2 Bucket"));
2272         pte = &l2b->l2b_kva[l2pte_index(va)];
2273         opte = *pte;
2274         if (l2pte_valid(opte)) {
2275                 va = va & ~PAGE_MASK;
2276                 cpu_tlb_flushD_SE(va);
2277                 cpu_cpwait();
2278                 *pte = 0;
2279                 PTE_SYNC(pte);
2280         }
2281 }
2282
2283
2284 /*
2285  *      Used to map a range of physical addresses into kernel
2286  *      virtual address space.
2287  *
2288  *      The value passed in '*virt' is a suggested virtual address for
2289  *      the mapping. Architectures which can support a direct-mapped
2290  *      physical to virtual region can return the appropriate address
2291  *      within that region, leaving '*virt' unchanged. Other
2292  *      architectures should map the pages starting at '*virt' and
2293  *      update '*virt' with the first usable address after the mapped
2294  *      region.
2295  */
2296 vm_offset_t
2297 pmap_map(vm_offset_t *virt, vm_offset_t start, vm_offset_t end, int prot)
2298 {
2299         vm_offset_t sva = *virt;
2300         vm_offset_t va = sva;
2301
2302         PDEBUG(1, printf("pmap_map: virt = %08x, start = %08x, end = %08x, "
2303             "prot = %d\n", (uint32_t) *virt, (uint32_t) start, (uint32_t) end,
2304             prot));
2305
2306         while (start < end) {
2307                 pmap_kenter(va, start);
2308                 va += PAGE_SIZE;
2309                 start += PAGE_SIZE;
2310         }
2311         *virt = va;
2312         return (sva);
2313 }
2314
2315 /*
2316  * Add a list of wired pages to the kva
2317  * this routine is only used for temporary
2318  * kernel mappings that do not need to have
2319  * page modification or references recorded.
2320  * Note that old mappings are simply written
2321  * over.  The page *must* be wired.
2322  */
2323 void
2324 pmap_qenter(vm_offset_t va, vm_page_t *m, int count)
2325 {
2326         int i;
2327
2328         for (i = 0; i < count; i++) {
2329                 pmap_kenter_internal(va, VM_PAGE_TO_PHYS(m[i]),
2330                     KENTER_CACHE);
2331                 va += PAGE_SIZE;
2332         }
2333 }
2334
2335
2336 /*
2337  * this routine jerks page mappings from the
2338  * kernel -- it is meant only for temporary mappings.
2339  */
2340 void
2341 pmap_qremove(vm_offset_t va, int count)
2342 {
2343         int i;
2344
2345         for (i = 0; i < count; i++) {
2346                 if (vtophys(va))
2347                         pmap_kremove(va);
2348
2349                 va += PAGE_SIZE;
2350         }
2351 }
2352
2353
2354 /*
2355  * pmap_object_init_pt preloads the ptes for a given object
2356  * into the specified pmap.  This eliminates the blast of soft
2357  * faults on process startup and immediately after an mmap.
2358  */
2359 void
2360 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
2361     vm_pindex_t pindex, vm_size_t size)
2362 {
2363
2364         VM_OBJECT_ASSERT_WLOCKED(object);
2365         KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
2366             ("pmap_object_init_pt: non-device object"));
2367 }
2368
2369
2370 /*
2371  *      pmap_is_prefaultable:
2372  *
2373  *      Return whether or not the specified virtual address is elgible
2374  *      for prefault.
2375  */
2376 boolean_t
2377 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
2378 {
2379         pd_entry_t *pde;
2380         pt_entry_t *pte;
2381
2382         if (!pmap_get_pde_pte(pmap, addr, &pde, &pte))
2383                 return (FALSE);
2384         KASSERT(pte != NULL, ("Valid mapping but no pte ?"));
2385         if (*pte == 0)
2386                 return (TRUE);
2387         return (FALSE);
2388 }
2389
2390 /*
2391  * Fetch pointers to the PDE/PTE for the given pmap/VA pair.
2392  * Returns TRUE if the mapping exists, else FALSE.
2393  *
2394  * NOTE: This function is only used by a couple of arm-specific modules.
2395  * It is not safe to take any pmap locks here, since we could be right
2396  * in the middle of debugging the pmap anyway...
2397  *
2398  * It is possible for this routine to return FALSE even though a valid
2399  * mapping does exist. This is because we don't lock, so the metadata
2400  * state may be inconsistent.
2401  *
2402  * NOTE: We can return a NULL *ptp in the case where the L1 pde is
2403  * a "section" mapping.
2404  */
2405 boolean_t
2406 pmap_get_pde_pte(pmap_t pm, vm_offset_t va, pd_entry_t **pdp, pt_entry_t **ptp)
2407 {
2408         struct l2_dtable *l2;
2409         pd_entry_t *pl1pd, l1pd;
2410         pt_entry_t *ptep;
2411         u_short l1idx;
2412
2413         if (pm->pm_l1 == NULL)
2414                 return (FALSE);
2415
2416         l1idx = L1_IDX(va);
2417         *pdp = pl1pd = &pm->pm_l1->l1_kva[l1idx];
2418         l1pd = *pl1pd;
2419
2420         if (l1pte_section_p(l1pd)) {
2421                 *ptp = NULL;
2422                 return (TRUE);
2423         }
2424
2425         if (pm->pm_l2 == NULL)
2426                 return (FALSE);
2427
2428         l2 = pm->pm_l2[L2_IDX(l1idx)];
2429
2430         if (l2 == NULL ||
2431             (ptep = l2->l2_bucket[L2_BUCKET(l1idx)].l2b_kva) == NULL) {
2432                 return (FALSE);
2433         }
2434
2435         *ptp = &ptep[l2pte_index(va)];
2436         return (TRUE);
2437 }
2438
2439 /*
2440  *      Routine:        pmap_remove_all
2441  *      Function:
2442  *              Removes this physical page from
2443  *              all physical maps in which it resides.
2444  *              Reflects back modify bits to the pager.
2445  *
2446  *      Notes:
2447  *              Original versions of this routine were very
2448  *              inefficient because they iteratively called
2449  *              pmap_remove (slow...)
2450  */
2451 void
2452 pmap_remove_all(vm_page_t m)
2453 {
2454         pv_entry_t pv;
2455         pmap_t pmap;
2456         pt_entry_t *ptep;
2457         struct l2_bucket *l2b;
2458         boolean_t flush = FALSE;
2459         pmap_t curpm;
2460         int flags = 0;
2461
2462         KASSERT((m->flags & PG_FICTITIOUS) == 0,
2463             ("pmap_remove_all: page %p is fictitious", m));
2464
2465         if (TAILQ_EMPTY(&m->md.pv_list))
2466                 return;
2467         rw_wlock(&pvh_global_lock);
2468         curpm = vmspace_pmap(curproc->p_vmspace);
2469         while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
2470                 pmap = PV_PMAP(pv);
2471                 if (flush == FALSE && (pmap == curpm ||
2472                     pmap == pmap_kernel()))
2473                         flush = TRUE;
2474
2475                 PMAP_LOCK(pmap);
2476                 l2b = pmap_get_l2_bucket(pmap, pv->pv_va);
2477                 KASSERT(l2b != NULL, ("No l2 bucket"));
2478                 ptep = &l2b->l2b_kva[l2pte_index(pv->pv_va)];
2479                 if (L2_S_WRITABLE(*ptep))
2480                         vm_page_dirty(m);
2481                 *ptep = 0;
2482                 if (pmap_is_current(pmap))
2483                         PTE_SYNC(ptep);
2484                 pmap_free_l2_bucket(pmap, l2b, 1);
2485                 pmap->pm_stats.resident_count--;
2486                 flags |= pv->pv_flags;
2487                 pmap_nuke_pv(m, pmap, pv);
2488                 pmap_free_pv_entry(pmap, pv);
2489                 PMAP_UNLOCK(pmap);
2490         }
2491         m->md.pvh_attrs &= ~(PVF_MOD | PVF_REF);
2492
2493         if (flush) {
2494                 if (PV_BEEN_EXECD(flags))
2495                         cpu_tlb_flushID();
2496                 else
2497                         cpu_tlb_flushD();
2498         }
2499         vm_page_aflag_clear(m, PGA_WRITEABLE);
2500         rw_wunlock(&pvh_global_lock);
2501 }
2502
2503 int
2504 pmap_change_attr(vm_offset_t sva, vm_size_t len, int mode)
2505 {
2506         vm_offset_t base, offset, tmpva;
2507         vm_size_t size;
2508         struct l2_bucket *l2b;
2509         pt_entry_t *ptep, pte;
2510         vm_offset_t next_bucket;
2511
2512         PMAP_LOCK(kernel_pmap);
2513
2514         base = trunc_page(sva);
2515         offset = sva & PAGE_MASK;
2516         size = roundup(offset + len, PAGE_SIZE);
2517
2518 #ifdef checkit
2519         /*
2520          * Only supported on kernel virtual addresses, including the direct
2521          * map but excluding the recursive map.
2522          */
2523         if (base < DMAP_MIN_ADDRESS) {
2524                 PMAP_UNLOCK(kernel_pmap);
2525                 return (EINVAL);
2526         }
2527 #endif
2528         for (tmpva = base; tmpva < base + size; ) {
2529                 next_bucket = L2_NEXT_BUCKET(tmpva);
2530                 if (next_bucket > base + size)
2531                         next_bucket = base + size;
2532
2533                 l2b = pmap_get_l2_bucket(kernel_pmap, tmpva);
2534                 if (l2b == NULL) {
2535                         tmpva = next_bucket;
2536                         continue;
2537                 }
2538
2539                 ptep = &l2b->l2b_kva[l2pte_index(tmpva)];
2540
2541                 if (*ptep == 0) {
2542                         PMAP_UNLOCK(kernel_pmap);
2543                         return(EINVAL);
2544                 }
2545
2546                 pte = *ptep &~ L2_S_CACHE_MASK;
2547                 cpu_idcache_wbinv_range(tmpva, PAGE_SIZE);
2548                 pmap_l2cache_wbinv_range(tmpva, pte & L2_S_FRAME, PAGE_SIZE);
2549                 *ptep = pte;
2550                 cpu_tlb_flushID_SE(tmpva);
2551
2552                 dprintf("%s: for va:%x ptep:%x pte:%x\n",
2553                     __func__, tmpva, (uint32_t)ptep, pte);
2554                 tmpva += PAGE_SIZE;
2555         }
2556
2557         PMAP_UNLOCK(kernel_pmap);
2558
2559         return (0);
2560 }
2561
2562 /*
2563  *      Set the physical protection on the
2564  *      specified range of this map as requested.
2565  */
2566 void
2567 pmap_protect(pmap_t pm, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
2568 {
2569         struct l2_bucket *l2b;
2570         pt_entry_t *ptep, pte;
2571         vm_offset_t next_bucket;
2572         u_int flags;
2573         int flush;
2574
2575         if ((prot & VM_PROT_READ) == 0) {
2576                 pmap_remove(pm, sva, eva);
2577                 return;
2578         }
2579
2580         if (prot & VM_PROT_WRITE) {
2581                 /*
2582                  * If this is a read->write transition, just ignore it and let
2583                  * vm_fault() take care of it later.
2584                  */
2585                 return;
2586         }
2587
2588         rw_wlock(&pvh_global_lock);
2589         PMAP_LOCK(pm);
2590
2591         /*
2592          * OK, at this point, we know we're doing write-protect operation.
2593          * If the pmap is active, write-back the range.
2594          */
2595
2596         flush = ((eva - sva) >= (PAGE_SIZE * 4)) ? 0 : -1;
2597         flags = 0;
2598
2599         while (sva < eva) {
2600                 next_bucket = L2_NEXT_BUCKET(sva);
2601                 if (next_bucket > eva)
2602                         next_bucket = eva;
2603
2604                 l2b = pmap_get_l2_bucket(pm, sva);
2605                 if (l2b == NULL) {
2606                         sva = next_bucket;
2607                         continue;
2608                 }
2609
2610                 ptep = &l2b->l2b_kva[l2pte_index(sva)];
2611
2612                 while (sva < next_bucket) {
2613                         if ((pte = *ptep) != 0 && L2_S_WRITABLE(pte)) {
2614                                 struct vm_page *pg;
2615                                 u_int f;
2616
2617                                 pg = PHYS_TO_VM_PAGE(l2pte_pa(pte));
2618                                 pmap_set_prot(ptep, prot, !(pm == pmap_kernel()));
2619                                 PTE_SYNC(ptep);
2620
2621                                 f = pmap_modify_pv(pg, pm, sva,
2622                                     PVF_WRITE, 0);
2623                                 if (f & PVF_WRITE)
2624                                         vm_page_dirty(pg);
2625
2626                                 if (flush >= 0) {
2627                                         flush++;
2628                                         flags |= f;
2629                                 } else
2630                                 if (PV_BEEN_EXECD(f))
2631                                         cpu_tlb_flushID_SE(sva);
2632                                 else
2633                                 if (PV_BEEN_REFD(f))
2634                                         cpu_tlb_flushD_SE(sva);
2635                         }
2636
2637                         sva += PAGE_SIZE;
2638                         ptep++;
2639                 }
2640         }
2641
2642
2643         if (flush) {
2644                 if (PV_BEEN_EXECD(flags))
2645                         cpu_tlb_flushID();
2646                 else
2647                 if (PV_BEEN_REFD(flags))
2648                         cpu_tlb_flushD();
2649         }
2650         rw_wunlock(&pvh_global_lock);
2651
2652         PMAP_UNLOCK(pm);
2653 }
2654
2655
2656 /*
2657  *      Insert the given physical page (p) at
2658  *      the specified virtual address (v) in the
2659  *      target physical map with the protection requested.
2660  *
2661  *      If specified, the page will be wired down, meaning
2662  *      that the related pte can not be reclaimed.
2663  *
2664  *      NB:  This is the only routine which MAY NOT lazy-evaluate
2665  *      or lose information.  That is, this routine must actually
2666  *      insert this page into the given map NOW.
2667  */
2668
2669 void
2670 pmap_enter(pmap_t pmap, vm_offset_t va, vm_prot_t access, vm_page_t m,
2671     vm_prot_t prot, boolean_t wired)
2672 {
2673
2674         rw_wlock(&pvh_global_lock);
2675         PMAP_LOCK(pmap);
2676         pmap_enter_locked(pmap, va, m, prot, wired, M_WAITOK);
2677         PMAP_UNLOCK(pmap);
2678         rw_wunlock(&pvh_global_lock);
2679 }
2680
2681 /*
2682  *      The pvh global and pmap locks must be held.
2683  */
2684 static void
2685 pmap_enter_locked(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
2686     boolean_t wired, int flags)
2687 {
2688         struct l2_bucket *l2b = NULL;
2689         struct vm_page *opg;
2690         struct pv_entry *pve = NULL;
2691         pt_entry_t *ptep, npte, opte;
2692         u_int nflags;
2693         u_int oflags;
2694         vm_paddr_t pa;
2695         u_char user;
2696
2697         PMAP_ASSERT_LOCKED(pmap);
2698         rw_assert(&pvh_global_lock, RA_WLOCKED);
2699         if (va == vector_page) {
2700                 pa = systempage.pv_pa;
2701                 m = NULL;
2702         } else {
2703                 KASSERT((m->oflags & (VPO_UNMANAGED | VPO_BUSY)) != 0 ||
2704                     (flags & M_NOWAIT) != 0,
2705                     ("pmap_enter_locked: page %p is not busy", m));
2706                 pa = VM_PAGE_TO_PHYS(m);
2707         }
2708
2709         user = 0;
2710         /*
2711          * Make sure userland mappings get the right permissions
2712          */
2713         if (pmap != pmap_kernel() && va != vector_page)
2714                 user = 1;
2715
2716         nflags = 0;
2717
2718         if (prot & VM_PROT_WRITE)
2719                 nflags |= PVF_WRITE;
2720         if (prot & VM_PROT_EXECUTE)
2721                 nflags |= PVF_EXEC;
2722         if (wired)
2723                 nflags |= PVF_WIRED;
2724
2725         PDEBUG(1, printf("pmap_enter: pmap = %08x, va = %08x, m = %08x, prot = %x, "
2726             "wired = %x\n", (uint32_t) pmap, va, (uint32_t) m, prot, wired));
2727
2728         if (pmap == pmap_kernel()) {
2729                 l2b = pmap_get_l2_bucket(pmap, va);
2730                 if (l2b == NULL)
2731                         l2b = pmap_grow_l2_bucket(pmap, va);
2732         } else {
2733 do_l2b_alloc:
2734                 l2b = pmap_alloc_l2_bucket(pmap, va);
2735                 if (l2b == NULL) {
2736                         if (flags & M_WAITOK) {
2737                                 PMAP_UNLOCK(pmap);
2738                                 rw_wunlock(&pvh_global_lock);
2739                                 VM_WAIT;
2740                                 rw_wlock(&pvh_global_lock);
2741                                 PMAP_LOCK(pmap);
2742                                 goto do_l2b_alloc;
2743                         }
2744                         return;
2745                 }
2746         }
2747
2748         ptep = &l2b->l2b_kva[l2pte_index(va)];
2749
2750         opte = *ptep;
2751         npte = pa;
2752         oflags = 0;
2753         if (opte) {
2754                 /*
2755                  * There is already a mapping at this address.
2756                  * If the physical address is different, lookup the
2757                  * vm_page.
2758                  */
2759                 if (l2pte_pa(opte) != pa)
2760                         opg = PHYS_TO_VM_PAGE(l2pte_pa(opte));
2761                 else
2762                         opg = m;
2763         } else
2764                 opg = NULL;
2765
2766         if ((prot & (VM_PROT_ALL)) ||
2767             (!m || m->md.pvh_attrs & PVF_REF)) {
2768                 /*
2769                  * - The access type indicates that we don't need
2770                  *   to do referenced emulation.
2771                  * OR
2772                  * - The physical page has already been referenced
2773                  *   so no need to re-do referenced emulation here.
2774                  */
2775                 npte |= L2_S_PROTO;
2776 #ifdef SMP
2777                 npte |= L2_SHARED;
2778 #endif
2779
2780                 nflags |= PVF_REF;
2781
2782                 if (m && ((prot & VM_PROT_WRITE) != 0 ||
2783                     (m->md.pvh_attrs & PVF_MOD))) {
2784                         /*
2785                          * This is a writable mapping, and the
2786                          * page's mod state indicates it has
2787                          * already been modified. Make it
2788                          * writable from the outset.
2789                          */
2790                         nflags |= PVF_MOD;
2791                         if (!(m->md.pvh_attrs & PVF_MOD))
2792                                 vm_page_dirty(m);
2793                 }
2794                 if (m && opte)
2795                         vm_page_aflag_set(m, PGA_REFERENCED);
2796         } else {
2797                 /*
2798                  * Need to do page referenced emulation.
2799                  */
2800                 npte &= ~L2_TYPE_MASK;
2801                 npte |= L2_TYPE_INV;
2802         }
2803
2804         npte |= L2_APX;
2805         npte |= L2_S_PROT_R;
2806         if (user)
2807                 npte |= L2_S_PROT_U;
2808
2809         if (prot & VM_PROT_WRITE) {
2810                 npte &= ~(L2_APX);
2811
2812                 if (m != NULL &&
2813                     (m->oflags & VPO_UNMANAGED) == 0)
2814                         vm_page_aflag_set(m, PGA_WRITEABLE);
2815         } else if (user)
2816                 npte &= ~(L2_S_PROT_R);
2817
2818         if (!(prot & VM_PROT_EXECUTE) && m)
2819                 npte |= L2_XN;
2820
2821         if (m->md.pv_memattr != VM_MEMATTR_UNCACHEABLE)
2822                 npte |= pte_l2_s_cache_mode;
2823
2824         if (m && m == opg) {
2825                 /*
2826                  * We're changing the attrs of an existing mapping.
2827                  */
2828                 oflags = pmap_modify_pv(m, pmap, va,
2829                     PVF_WRITE | PVF_EXEC | PVF_WIRED |
2830                     PVF_MOD | PVF_REF, nflags);
2831         } else {
2832                 /*
2833                  * New mapping, or changing the backing page
2834                  * of an existing mapping.
2835                  */
2836                 if (opg) {
2837                         /*
2838                          * Replacing an existing mapping with a new one.
2839                          * It is part of our managed memory so we
2840                          * must remove it from the PV list
2841                          */
2842                         if ((pve = pmap_remove_pv(opg, pmap, va))) {
2843                             oflags = pve->pv_flags;
2844
2845                             if (m && ((m->oflags & VPO_UNMANAGED)))
2846                                 pmap_free_pv_entry(pmap, pve);
2847                         }
2848                 }
2849
2850                 if ((m && !(m->oflags & VPO_UNMANAGED))) {
2851                         if ((!pve) && (pve = pmap_get_pv_entry(pmap, FALSE)) == NULL)
2852                                 panic("pmap_enter: no pv entries");
2853
2854                         KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva,
2855                         ("pmap_enter: managed mapping within the clean submap"));
2856                         KASSERT(pve != NULL, ("No pv"));
2857                         pmap_enter_pv(m, pve, pmap, va, nflags);
2858                 }
2859         }
2860
2861         /*
2862          * Keep the stats up to date
2863          */
2864         if (opte == 0) {
2865                 l2b->l2b_occupancy++;
2866                 pmap->pm_stats.resident_count++;
2867         }
2868
2869         CTR5(KTR_PMAP,"enter: pmap:%p va:%x prot:%x pte:%x->%x",
2870             pmap, va, prot, opte, npte);
2871         /*
2872          * If this is just a wiring change, the two PTEs will be
2873          * identical, so there's no need to update the page table.
2874          */
2875         if (npte != opte) {
2876                 boolean_t is_cached = pmap_is_current(pmap);
2877
2878                 *ptep = npte;
2879                 PTE_SYNC(ptep);
2880                 if (is_cached) {
2881                         /*
2882                          * We only need to frob the cache/tlb if this pmap
2883                          * is current
2884                          */
2885                         if (L1_IDX(va) != L1_IDX(vector_page) &&
2886                             l2pte_valid(npte)) {
2887                                 /*
2888                                  * This mapping is likely to be accessed as
2889                                  * soon as we return to userland. Fix up the
2890                                  * L1 entry to avoid taking another
2891                                  * page/domain fault.
2892                                  */
2893                                 pd_entry_t *pl1pd, l1pd;
2894
2895                                 pl1pd = &pmap->pm_l1->l1_kva[L1_IDX(va)];
2896                                 l1pd = l2b->l2b_phys | L1_C_DOM(pmap->pm_domain) |
2897                                     L1_C_PROTO;
2898                                 if (*pl1pd != l1pd) {
2899                                         *pl1pd = l1pd;
2900                                         PTE_SYNC(pl1pd);
2901                                 }
2902                         }
2903                 }
2904
2905                 if (PV_BEEN_EXECD(oflags))
2906                         cpu_tlb_flushID_SE(va);
2907                 else if (PV_BEEN_REFD(oflags))
2908                         cpu_tlb_flushD_SE(va);
2909         }
2910
2911         if ((pmap != pmap_kernel()) && (pmap == &curproc->p_vmspace->vm_pmap))
2912                 cpu_icache_sync_range(va, PAGE_SIZE);
2913 }
2914
2915 /*
2916  * Maps a sequence of resident pages belonging to the same object.
2917  * The sequence begins with the given page m_start.  This page is
2918  * mapped at the given virtual address start.  Each subsequent page is
2919  * mapped at a virtual address that is offset from start by the same
2920  * amount as the page is offset from m_start within the object.  The
2921  * last page in the sequence is the page with the largest offset from
2922  * m_start that can be mapped at a virtual address less than the given
2923  * virtual address end.  Not every virtual page between start and end
2924  * is mapped; only those for which a resident page exists with the
2925  * corresponding offset from m_start are mapped.
2926  */
2927 void
2928 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
2929     vm_page_t m_start, vm_prot_t prot)
2930 {
2931         vm_page_t m;
2932         vm_pindex_t diff, psize;
2933
2934         VM_OBJECT_ASSERT_LOCKED(m_start->object);
2935
2936         psize = atop(end - start);
2937         m = m_start;
2938         rw_wlock(&pvh_global_lock);
2939         PMAP_LOCK(pmap);
2940         while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
2941                 pmap_enter_locked(pmap, start + ptoa(diff), m, prot &
2942                     (VM_PROT_READ | VM_PROT_EXECUTE), FALSE, M_NOWAIT);
2943                 m = TAILQ_NEXT(m, listq);
2944         }
2945         PMAP_UNLOCK(pmap);
2946         rw_wunlock(&pvh_global_lock);
2947 }
2948
2949 /*
2950  * this code makes some *MAJOR* assumptions:
2951  * 1. Current pmap & pmap exists.
2952  * 2. Not wired.
2953  * 3. Read access.
2954  * 4. No page table pages.
2955  * but is *MUCH* faster than pmap_enter...
2956  */
2957
2958 void
2959 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
2960 {
2961
2962         rw_wlock(&pvh_global_lock);
2963         PMAP_LOCK(pmap);
2964         pmap_enter_locked(pmap, va, m, prot & (VM_PROT_READ | VM_PROT_EXECUTE),
2965             FALSE, M_NOWAIT);
2966         PMAP_UNLOCK(pmap);
2967         rw_wunlock(&pvh_global_lock);
2968 }
2969
2970 /*
2971  *      Routine:        pmap_change_wiring
2972  *      Function:       Change the wiring attribute for a map/virtual-address
2973  *                      pair.
2974  *      In/out conditions:
2975  *                      The mapping must already exist in the pmap.
2976  */
2977 void
2978 pmap_change_wiring(pmap_t pmap, vm_offset_t va, boolean_t wired)
2979 {
2980         struct l2_bucket *l2b;
2981         pt_entry_t *ptep, pte;
2982         vm_page_t pg;
2983
2984         rw_wlock(&pvh_global_lock);
2985         PMAP_LOCK(pmap);
2986         l2b = pmap_get_l2_bucket(pmap, va);
2987         KASSERT(l2b, ("No l2b bucket in pmap_change_wiring"));
2988         ptep = &l2b->l2b_kva[l2pte_index(va)];
2989         pte = *ptep;
2990         pg = PHYS_TO_VM_PAGE(l2pte_pa(pte));
2991         if (pg)
2992                 pmap_modify_pv(pg, pmap, va, PVF_WIRED, wired);
2993         rw_wunlock(&pvh_global_lock);
2994         PMAP_UNLOCK(pmap);
2995 }
2996
2997
2998 /*
2999  *      Copy the range specified by src_addr/len
3000  *      from the source map to the range dst_addr/len
3001  *      in the destination map.
3002  *
3003  *      This routine is only advisory and need not do anything.
3004  */
3005 void
3006 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr,
3007     vm_size_t len, vm_offset_t src_addr)
3008 {
3009 }
3010
3011
3012 /*
3013  *      Routine:        pmap_extract
3014  *      Function:
3015  *              Extract the physical page address associated
3016  *              with the given map/virtual_address pair.
3017  */
3018 vm_paddr_t
3019 pmap_extract(pmap_t pmap, vm_offset_t va)
3020 {
3021         vm_paddr_t pa;
3022
3023         PMAP_LOCK(pmap);
3024         pa = pmap_extract_locked(pmap, va);
3025         PMAP_UNLOCK(pmap);
3026         return (pa);
3027 }
3028
3029 static vm_paddr_t
3030 pmap_extract_locked(pmap_t pmap, vm_offset_t va)
3031 {
3032         struct l2_dtable *l2;
3033         pd_entry_t l1pd;
3034         pt_entry_t *ptep, pte;
3035         vm_paddr_t pa;
3036         u_int l1idx;
3037
3038         if (pmap != kernel_pmap)
3039                 PMAP_ASSERT_LOCKED(pmap);
3040         l1idx = L1_IDX(va);
3041         l1pd = pmap->pm_l1->l1_kva[l1idx];
3042         if (l1pte_section_p(l1pd)) {
3043                 /*
3044                  * These should only happen for the kernel pmap.
3045                  */
3046                 KASSERT(pmap == kernel_pmap, ("unexpected section"));
3047                 /* XXX: what to do about the bits > 32 ? */
3048                 if (l1pd & L1_S_SUPERSEC)
3049                         pa = (l1pd & L1_SUP_FRAME) | (va & L1_SUP_OFFSET);
3050                 else
3051                         pa = (l1pd & L1_S_FRAME) | (va & L1_S_OFFSET);
3052         } else {
3053                 /*
3054                  * Note that we can't rely on the validity of the L1
3055                  * descriptor as an indication that a mapping exists.
3056                  * We have to look it up in the L2 dtable.
3057                  */
3058                 l2 = pmap->pm_l2[L2_IDX(l1idx)];
3059                 if (l2 == NULL ||
3060                     (ptep = l2->l2_bucket[L2_BUCKET(l1idx)].l2b_kva) == NULL)
3061                         return (0);
3062                 pte = ptep[l2pte_index(va)];
3063                 if (pte == 0)
3064                         return (0);
3065                 switch (pte & L2_TYPE_MASK) {
3066                 case L2_TYPE_L:
3067                         pa = (pte & L2_L_FRAME) | (va & L2_L_OFFSET);
3068                         break;
3069                 default:
3070                         pa = (pte & L2_S_FRAME) | (va & L2_S_OFFSET);
3071                         break;
3072                 }
3073         }
3074         return (pa);
3075 }
3076
3077 /*
3078  * Atomically extract and hold the physical page with the given
3079  * pmap and virtual address pair if that mapping permits the given
3080  * protection.
3081  *
3082  */
3083 vm_page_t
3084 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
3085 {
3086         struct l2_dtable *l2;
3087         pd_entry_t l1pd;
3088         pt_entry_t *ptep, pte;
3089         vm_paddr_t pa, paddr;
3090         vm_page_t m = NULL;
3091         u_int l1idx;
3092         l1idx = L1_IDX(va);
3093         paddr = 0;
3094
3095         PMAP_LOCK(pmap);
3096 retry:
3097         l1pd = pmap->pm_l1->l1_kva[l1idx];
3098         if (l1pte_section_p(l1pd)) {
3099                 /*
3100                  * These should only happen for pmap_kernel()
3101                  */
3102                 KASSERT(pmap == pmap_kernel(), ("huh"));
3103                 /* XXX: what to do about the bits > 32 ? */
3104                 if (l1pd & L1_S_SUPERSEC)
3105                         pa = (l1pd & L1_SUP_FRAME) | (va & L1_SUP_OFFSET);
3106                 else
3107                         pa = (l1pd & L1_S_FRAME) | (va & L1_S_OFFSET);
3108                 if (vm_page_pa_tryrelock(pmap, pa & PG_FRAME, &paddr))
3109                         goto retry;
3110                 if (L1_S_WRITABLE(l1pd) || (prot & VM_PROT_WRITE) == 0) {
3111                         m = PHYS_TO_VM_PAGE(pa);
3112                         vm_page_hold(m);
3113                 }
3114         } else {
3115                 /*
3116                  * Note that we can't rely on the validity of the L1
3117                  * descriptor as an indication that a mapping exists.
3118                  * We have to look it up in the L2 dtable.
3119                  */
3120                 l2 = pmap->pm_l2[L2_IDX(l1idx)];
3121
3122                 if (l2 == NULL ||
3123                     (ptep = l2->l2_bucket[L2_BUCKET(l1idx)].l2b_kva) == NULL) {
3124                         PMAP_UNLOCK(pmap);
3125                         return (NULL);
3126                 }
3127
3128                 ptep = &ptep[l2pte_index(va)];
3129                 pte = *ptep;
3130
3131                 if (pte == 0) {
3132                         PMAP_UNLOCK(pmap);
3133                         return (NULL);
3134                 } else if ((prot & VM_PROT_WRITE) && (pte & L2_APX)) {
3135                         PMAP_UNLOCK(pmap);
3136                         return (NULL);
3137                 } else {
3138                         switch (pte & L2_TYPE_MASK) {
3139                         case L2_TYPE_L:
3140                                 panic("extract and hold section mapping");
3141                                 break;
3142                         default:
3143                                 pa = (pte & L2_S_FRAME) | (va & L2_S_OFFSET);
3144                                 break;
3145                         }
3146                         if (vm_page_pa_tryrelock(pmap, pa & PG_FRAME, &paddr))
3147                                 goto retry;
3148                         m = PHYS_TO_VM_PAGE(pa);
3149                         vm_page_hold(m);
3150                 }
3151
3152         }
3153
3154         PMAP_UNLOCK(pmap);
3155         PA_UNLOCK_COND(paddr);
3156         return (m);
3157 }
3158
3159 /*
3160  * Initialize a preallocated and zeroed pmap structure,
3161  * such as one in a vmspace structure.
3162  */
3163
3164 int
3165 pmap_pinit(pmap_t pmap)
3166 {
3167         PDEBUG(1, printf("pmap_pinit: pmap = %08x\n", (uint32_t) pmap));
3168
3169         PMAP_LOCK_INIT(pmap);
3170         pmap_alloc_l1(pmap);
3171         bzero(pmap->pm_l2, sizeof(pmap->pm_l2));
3172
3173         CPU_ZERO(&pmap->pm_active);
3174
3175         TAILQ_INIT(&pmap->pm_pvchunk);
3176         bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
3177         pmap->pm_stats.resident_count = 1;
3178         if (vector_page < KERNBASE) {
3179                 pmap_enter(pmap, vector_page,
3180                     VM_PROT_READ, PHYS_TO_VM_PAGE(systempage.pv_pa),
3181                     VM_PROT_READ, 1);
3182         }
3183         return (1);
3184 }
3185
3186
3187 /***************************************************
3188  * page management routines.
3189  ***************************************************/
3190
3191 /*
3192  * We are in a serious low memory condition.  Resort to
3193  * drastic measures to free some pages so we can allocate
3194  * another pv entry chunk.
3195  */
3196 static vm_page_t
3197 pmap_pv_reclaim(pmap_t locked_pmap)
3198 {
3199         struct pch newtail;
3200         struct pv_chunk *pc;
3201         struct l2_bucket *l2b = NULL;
3202         pmap_t pmap;
3203         pt_entry_t *pt;
3204         pv_entry_t pv;
3205         vm_offset_t va;
3206         vm_page_t free, m, m_pc;
3207         uint32_t inuse;
3208         int bit, field, freed, idx;
3209
3210         PMAP_ASSERT_LOCKED(locked_pmap);
3211         pmap = NULL;
3212         free = m_pc = NULL;
3213         TAILQ_INIT(&newtail);
3214         while ((pc = TAILQ_FIRST(&pv_chunks)) != NULL && (pv_vafree == 0 ||
3215             free == NULL)) {
3216                 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3217                 if (pmap != pc->pc_pmap) {
3218                         if (pmap != NULL) {
3219                                 cpu_tlb_flushID();
3220                                 cpu_cpwait();
3221                                 if (pmap != locked_pmap)
3222                                         PMAP_UNLOCK(pmap);
3223                         }
3224                         pmap = pc->pc_pmap;
3225                         /* Avoid deadlock and lock recursion. */
3226                         if (pmap > locked_pmap)
3227                                 PMAP_LOCK(pmap);
3228                         else if (pmap != locked_pmap && !PMAP_TRYLOCK(pmap)) {
3229                                 pmap = NULL;
3230                                 TAILQ_INSERT_TAIL(&newtail, pc, pc_lru);
3231                                 continue;
3232                         }
3233                 }
3234
3235                 /*
3236                  * Destroy every non-wired, 4 KB page mapping in the chunk.
3237                  */
3238                 freed = 0;
3239                 for (field = 0; field < _NPCM; field++) {
3240                         for (inuse = ~pc->pc_map[field] & pc_freemask[field];
3241                             inuse != 0; inuse &= ~(1UL << bit)) {
3242                                 bit = ffs(inuse) - 1;
3243                                 idx = field * sizeof(inuse) * NBBY + bit;
3244                                 pv = &pc->pc_pventry[idx];
3245                                 if (pv->pv_flags & PVF_WIRED)
3246                                         continue;
3247
3248                                 va = pv->pv_va;
3249                                 l2b = pmap_get_l2_bucket(pmap, va);
3250                                 KASSERT(l2b != NULL, ("No l2 bucket"));
3251                                 pt = &l2b->l2b_kva[l2pte_index(va)];
3252                                 m = PHYS_TO_VM_PAGE(l2pte_pa(*pt));
3253                                 KASSERT((vm_offset_t)m >= KERNBASE,
3254                                     ("Trying to access non-existent page "
3255                                      "va %x pte %x in %s", va, *pt));
3256                                 *pt = 0;
3257                                 PTE_SYNC(pt);
3258                                 pmap_nuke_pv(m, pmap, pv);
3259                                 pc->pc_map[field] |= 1UL << bit;
3260                                 freed++;
3261                         }
3262                 }
3263
3264                 if (freed == 0) {
3265                         TAILQ_INSERT_TAIL(&newtail, pc, pc_lru);
3266                         continue;
3267                 }
3268                 /* Every freed mapping is for a 4 KB page. */
3269                 pmap->pm_stats.resident_count -= freed;
3270                 PV_STAT(pv_entry_frees += freed);
3271                 PV_STAT(pv_entry_spare += freed);
3272                 pv_entry_count -= freed;
3273                 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3274                 for (field = 0; field < _NPCM; field++)
3275                         if (pc->pc_map[field] != pc_freemask[field]) {
3276                                 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc,
3277                                     pc_list);
3278                                 TAILQ_INSERT_TAIL(&newtail, pc, pc_lru);
3279
3280                                 /*
3281                                  * One freed pv entry in locked_pmap is
3282                                  * sufficient.
3283                                  */
3284                                 if (pmap == locked_pmap)
3285                                         goto out;
3286                                 break;
3287                         }
3288                 if (field == _NPCM) {
3289                         PV_STAT(pv_entry_spare -= _NPCPV);
3290                         PV_STAT(pc_chunk_count--);
3291                         PV_STAT(pc_chunk_frees++);
3292                         /* Entire chunk is free; return it. */
3293                         m_pc = PHYS_TO_VM_PAGE(pmap_kextract((vm_offset_t)pc));
3294                         pmap_qremove((vm_offset_t)pc, 1);
3295                         pmap_ptelist_free(&pv_vafree, (vm_offset_t)pc);
3296                         break;
3297                 }
3298         }
3299 out:
3300         TAILQ_CONCAT(&pv_chunks, &newtail, pc_lru);
3301         if (pmap != NULL) {
3302                 cpu_tlb_flushID();
3303                 cpu_cpwait();
3304                 if (pmap != locked_pmap)
3305                         PMAP_UNLOCK(pmap);
3306         }
3307         return (m_pc);
3308 }
3309
3310 /*
3311  * free the pv_entry back to the free list
3312  */
3313 static void
3314 pmap_free_pv_entry(pmap_t pmap, pv_entry_t pv)
3315 {
3316         struct pv_chunk *pc;
3317         int bit, field, idx;
3318
3319         rw_assert(&pvh_global_lock, RA_WLOCKED);
3320         PMAP_ASSERT_LOCKED(pmap);
3321         PV_STAT(pv_entry_frees++);
3322         PV_STAT(pv_entry_spare++);
3323         pv_entry_count--;
3324         pc = pv_to_chunk(pv);
3325         idx = pv - &pc->pc_pventry[0];
3326         field = idx / (sizeof(u_long) * NBBY);
3327         bit = idx % (sizeof(u_long) * NBBY);
3328         pc->pc_map[field] |= 1ul << bit;
3329         for (idx = 0; idx < _NPCM; idx++)
3330                 if (pc->pc_map[idx] != pc_freemask[idx]) {
3331                         /*
3332                          * 98% of the time, pc is already at the head of the
3333                          * list.  If it isn't already, move it to the head.
3334                          */
3335                         if (__predict_false(TAILQ_FIRST(&pmap->pm_pvchunk) !=
3336                             pc)) {
3337                                 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3338                                 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc,
3339                                     pc_list);
3340                         }
3341                         return;
3342                 }
3343         TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3344         pmap_free_pv_chunk(pc);
3345 }
3346
3347 static void
3348 pmap_free_pv_chunk(struct pv_chunk *pc)
3349 {
3350         vm_page_t m;
3351
3352         TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3353         PV_STAT(pv_entry_spare -= _NPCPV);
3354         PV_STAT(pc_chunk_count--);
3355         PV_STAT(pc_chunk_frees++);
3356         /* entire chunk is free, return it */
3357         m = PHYS_TO_VM_PAGE(pmap_kextract((vm_offset_t)pc));
3358         pmap_qremove((vm_offset_t)pc, 1);
3359         vm_page_unwire(m, 0);
3360         vm_page_free(m);
3361         pmap_ptelist_free(&pv_vafree, (vm_offset_t)pc);
3362
3363 }
3364
3365 static pv_entry_t
3366 pmap_get_pv_entry(pmap_t pmap, boolean_t try)
3367 {
3368         static const struct timeval printinterval = { 60, 0 };
3369         static struct timeval lastprint;
3370         struct pv_chunk *pc;
3371         pv_entry_t pv;
3372         vm_page_t m;
3373         int bit, field, idx;
3374
3375         rw_assert(&pvh_global_lock, RA_WLOCKED);
3376         PMAP_ASSERT_LOCKED(pmap);
3377         PV_STAT(pv_entry_allocs++);
3378         pv_entry_count++;
3379
3380         if (pv_entry_count > pv_entry_high_water)
3381                 if (ratecheck(&lastprint, &printinterval))
3382                         printf("%s: Approaching the limit on PV entries.\n",
3383                             __func__);
3384 retry:
3385         pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3386         if (pc != NULL) {
3387                 for (field = 0; field < _NPCM; field++) {
3388                         if (pc->pc_map[field]) {
3389                                 bit = ffs(pc->pc_map[field]) - 1;
3390                                 break;
3391                         }
3392                 }
3393                 if (field < _NPCM) {
3394                         idx = field * sizeof(pc->pc_map[field]) * NBBY + bit;
3395                         pv = &pc->pc_pventry[idx];
3396                         pc->pc_map[field] &= ~(1ul << bit);
3397                         /* If this was the last item, move it to tail */
3398                         for (field = 0; field < _NPCM; field++)
3399                                 if (pc->pc_map[field] != 0) {
3400                                         PV_STAT(pv_entry_spare--);
3401                                         return (pv);    /* not full, return */
3402                                 }
3403                         TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3404                         TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3405                         PV_STAT(pv_entry_spare--);
3406                         return (pv);
3407                 }
3408         }
3409         /*
3410          * Access to the ptelist "pv_vafree" is synchronized by the pvh
3411          * global lock.  If "pv_vafree" is currently non-empty, it will
3412          * remain non-empty until pmap_ptelist_alloc() completes.
3413          */
3414         if (pv_vafree == 0 || (m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
3415             VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
3416                 if (try) {
3417                         pv_entry_count--;
3418                         PV_STAT(pc_chunk_tryfail++);
3419                         return (NULL);
3420                 }
3421                 m = pmap_pv_reclaim(pmap);
3422                 if (m == NULL)
3423                         goto retry;
3424         }
3425         PV_STAT(pc_chunk_count++);
3426         PV_STAT(pc_chunk_allocs++);
3427         pc = (struct pv_chunk *)pmap_ptelist_alloc(&pv_vafree);
3428         pmap_qenter((vm_offset_t)pc, &m, 1);
3429         pc->pc_pmap = pmap;
3430         pc->pc_map[0] = pc_freemask[0] & ~1ul;  /* preallocated bit 0 */
3431         for (field = 1; field < _NPCM; field++)
3432                 pc->pc_map[field] = pc_freemask[field];
3433         TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3434         pv = &pc->pc_pventry[0];
3435         TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3436         PV_STAT(pv_entry_spare += _NPCPV - 1);
3437         return (pv);
3438 }
3439
3440 /*
3441  *      Remove the given range of addresses from the specified map.
3442  *
3443  *      It is assumed that the start and end are properly
3444  *      rounded to the page size.
3445  */
3446 #define PMAP_REMOVE_CLEAN_LIST_SIZE     3
3447 void
3448 pmap_remove(pmap_t pm, vm_offset_t sva, vm_offset_t eva)
3449 {
3450         struct l2_bucket *l2b;
3451         vm_offset_t next_bucket;
3452         pt_entry_t *ptep;
3453         u_int total;
3454         u_int mappings, is_exec, is_refd;
3455         int flushall = 0;
3456
3457
3458         /*
3459          * we lock in the pmap => pv_head direction
3460          */
3461
3462         rw_wlock(&pvh_global_lock);
3463         PMAP_LOCK(pm);
3464         total = 0;
3465         while (sva < eva) {
3466                 /*
3467                  * Do one L2 bucket's worth at a time.
3468                  */
3469                 next_bucket = L2_NEXT_BUCKET(sva);
3470                 if (next_bucket > eva)
3471                         next_bucket = eva;
3472
3473                 l2b = pmap_get_l2_bucket(pm, sva);
3474                 if (l2b == NULL) {
3475                         sva = next_bucket;
3476                         continue;
3477                 }
3478
3479                 ptep = &l2b->l2b_kva[l2pte_index(sva)];
3480                 mappings = 0;
3481
3482                 while (sva < next_bucket) {
3483                         struct vm_page *pg;
3484                         pt_entry_t pte;
3485                         vm_paddr_t pa;
3486
3487                         pte = *ptep;
3488
3489                         if (pte == 0) {
3490                                 /*
3491                                  * Nothing here, move along
3492                                  */
3493                                 sva += PAGE_SIZE;
3494                                 ptep++;
3495                                 continue;
3496                         }
3497
3498                         pm->pm_stats.resident_count--;
3499                         pa = l2pte_pa(pte);
3500                         is_exec = 0;
3501                         is_refd = 1;
3502
3503                         /*
3504                          * Update flags. In a number of circumstances,
3505                          * we could cluster a lot of these and do a
3506                          * number of sequential pages in one go.
3507                          */
3508                         if ((pg = PHYS_TO_VM_PAGE(pa)) != NULL) {
3509                                 struct pv_entry *pve;
3510
3511                                 pve = pmap_remove_pv(pg, pm, sva);
3512                                 if (pve) {
3513                                         is_exec = PV_BEEN_EXECD(pve->pv_flags);
3514                                         is_refd = PV_BEEN_REFD(pve->pv_flags);
3515                                         pmap_free_pv_entry(pm, pve);
3516                                 }
3517                         }
3518
3519                         if (pmap_is_current(pm)) {
3520                                 total++;
3521                                 if (total < PMAP_REMOVE_CLEAN_LIST_SIZE) {
3522                                         if (is_exec)
3523                                                 cpu_tlb_flushID_SE(sva);
3524                                         else if (is_refd)
3525                                                 cpu_tlb_flushD_SE(sva);
3526                                 } else if (total == PMAP_REMOVE_CLEAN_LIST_SIZE) {
3527                                         flushall = 1;
3528                                 }
3529                         }
3530                         *ptep = 0;
3531                         PTE_SYNC(ptep);
3532
3533                         sva += PAGE_SIZE;
3534                         ptep++;
3535                         mappings++;
3536                 }
3537
3538                 pmap_free_l2_bucket(pm, l2b, mappings);
3539         }
3540
3541         rw_wunlock(&pvh_global_lock);
3542         if (flushall)
3543                 cpu_tlb_flushID();
3544         PMAP_UNLOCK(pm);
3545 }
3546
3547 /*
3548  * pmap_zero_page()
3549  *
3550  * Zero a given physical page by mapping it at a page hook point.
3551  * In doing the zero page op, the page we zero is mapped cachable, as with
3552  * StrongARM accesses to non-cached pages are non-burst making writing
3553  * _any_ bulk data very slow.
3554  */
3555 static void
3556 pmap_zero_page_gen(vm_page_t pg, int off, int size)
3557 {
3558
3559         vm_paddr_t phys = VM_PAGE_TO_PHYS(pg);
3560         if (!TAILQ_EMPTY(&pg->md.pv_list))
3561                 panic("pmap_zero_page: page has mappings");
3562
3563         mtx_lock(&cmtx);
3564         /*
3565          * Hook in the page, zero it, invalidate the TLB as needed.
3566          *
3567          * Note the temporary zero-page mapping must be a non-cached page in
3568          * order to work without corruption when write-allocate is enabled.
3569          */
3570         *cdst_pte = L2_S_PROTO | phys | pte_l2_s_cache_mode;
3571         pmap_set_prot(cdst_pte, VM_PROT_WRITE, 0);
3572         PTE_SYNC(cdst_pte);
3573         cpu_tlb_flushD_SE(cdstp);
3574         cpu_cpwait();
3575         if (off || size != PAGE_SIZE)
3576                 bzero((void *)(cdstp + off), size);
3577         else
3578                 bzero_page(cdstp);
3579
3580         /*
3581          * Although aliasing is not possible if we use 
3582          * cdstp temporary mappings with memory that 
3583          * will be mapped later as non-cached or with write-through 
3584          * caches we might end up overwriting it when calling wbinv_all
3585          * So make sure caches are clean after copy operation
3586          */
3587         cpu_idcache_wbinv_range(cdstp, size);
3588         pmap_l2cache_wbinv_range(cdstp, phys, size);
3589
3590         mtx_unlock(&cmtx);
3591 }
3592
3593 /*
3594  *      pmap_zero_page zeros the specified hardware page by mapping
3595  *      the page into KVM and using bzero to clear its contents.
3596  */
3597 void
3598 pmap_zero_page(vm_page_t m)
3599 {
3600         pmap_zero_page_gen(m, 0, PAGE_SIZE);
3601 }
3602
3603
3604 /*
3605  *      pmap_zero_page_area zeros the specified hardware page by mapping
3606  *      the page into KVM and using bzero to clear its contents.
3607  *
3608  *      off and size may not cover an area beyond a single hardware page.
3609  */
3610 void
3611 pmap_zero_page_area(vm_page_t m, int off, int size)
3612 {
3613
3614         pmap_zero_page_gen(m, off, size);
3615 }
3616
3617
3618 /*
3619  *      pmap_zero_page_idle zeros the specified hardware page by mapping
3620  *      the page into KVM and using bzero to clear its contents.  This
3621  *      is intended to be called from the vm_pagezero process only and
3622  *      outside of Giant.
3623  */
3624 void
3625 pmap_zero_page_idle(vm_page_t m)
3626 {
3627
3628         pmap_zero_page(m);
3629 }
3630
3631 /*
3632  *      pmap_copy_page copies the specified (machine independent)
3633  *      page by mapping the page into virtual memory and using
3634  *      bcopy to copy the page, one machine dependent page at a
3635  *      time.
3636  */
3637
3638 /*
3639  * pmap_copy_page()
3640  *
3641  * Copy one physical page into another, by mapping the pages into
3642  * hook points. The same comment regarding cachability as in
3643  * pmap_zero_page also applies here.
3644  */
3645 void
3646 pmap_copy_page_generic(vm_paddr_t src, vm_paddr_t dst)
3647 {
3648         /*
3649          * Hold the source page's lock for the duration of the copy
3650          * so that no other mappings can be created while we have a
3651          * potentially aliased mapping.
3652          * Map the pages into the page hook points, copy them, and purge
3653          * the cache for the appropriate page. Invalidate the TLB
3654          * as required.
3655          */
3656         mtx_lock(&cmtx);
3657
3658         /* For ARMv6 using System bit is deprecated and mapping with AP
3659          * bits set to 0x0 makes page not accessible. csrc_pte is mapped
3660          * read/write until proper mapping defines are created for ARMv6.
3661          */
3662         *csrc_pte = L2_S_PROTO | src | pte_l2_s_cache_mode;
3663         pmap_set_prot(csrc_pte, VM_PROT_READ, 0);
3664         PTE_SYNC(csrc_pte);
3665
3666         *cdst_pte = L2_S_PROTO | dst | pte_l2_s_cache_mode;
3667         pmap_set_prot(cdst_pte, VM_PROT_READ | VM_PROT_WRITE, 0);
3668         PTE_SYNC(cdst_pte);
3669
3670         cpu_tlb_flushD_SE(csrcp);
3671         cpu_tlb_flushD_SE(cdstp);
3672         cpu_cpwait();
3673
3674         /*
3675          * Although aliasing is not possible if we use 
3676          * cdstp temporary mappings with memory that 
3677          * will be mapped later as non-cached or with write-through 
3678          * caches we might end up overwriting it when calling wbinv_all
3679          * So make sure caches are clean after copy operation
3680          */
3681         bcopy_page(csrcp, cdstp);
3682
3683         cpu_idcache_wbinv_range(cdstp, PAGE_SIZE);
3684         pmap_l2cache_wbinv_range(cdstp, dst, PAGE_SIZE);
3685
3686         mtx_unlock(&cmtx);
3687 }
3688
3689 int unmapped_buf_allowed = 1;
3690
3691 void
3692 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
3693     vm_offset_t b_offset, int xfersize)
3694 {
3695         vm_page_t a_pg, b_pg;
3696         vm_offset_t a_pg_offset, b_pg_offset;
3697         int cnt;
3698
3699         mtx_lock(&cmtx);
3700         while (xfersize > 0) {
3701                 a_pg = ma[a_offset >> PAGE_SHIFT];
3702                 a_pg_offset = a_offset & PAGE_MASK;
3703                 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
3704                 b_pg = mb[b_offset >> PAGE_SHIFT];
3705                 b_pg_offset = b_offset & PAGE_MASK;
3706                 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
3707                 *csrc_pte = L2_S_PROTO | VM_PAGE_TO_PHYS(a_pg) |
3708                     pte_l2_s_cache_mode;
3709                 pmap_set_prot(csrc_pte, VM_PROT_READ, 0);
3710                 PTE_SYNC(csrc_pte);
3711                 *cdst_pte = L2_S_PROTO | VM_PAGE_TO_PHYS(b_pg) |
3712                     pte_l2_s_cache_mode;
3713                 pmap_set_prot(cdst_pte, VM_PROT_READ | VM_PROT_WRITE, 0);
3714                 PTE_SYNC(cdst_pte);
3715                 cpu_tlb_flushD_SE(csrcp);
3716                 cpu_tlb_flushD_SE(cdstp);
3717                 cpu_cpwait();
3718                 bcopy((char *)csrcp + a_pg_offset, (char *)cdstp + b_pg_offset,
3719                     cnt);
3720                 cpu_idcache_wbinv_range(cdstp + b_pg_offset, cnt);
3721                 pmap_l2cache_wbinv_range(cdstp + b_pg_offset,
3722                     VM_PAGE_TO_PHYS(b_pg) + b_pg_offset, cnt);
3723                 xfersize -= cnt;
3724                 a_offset += cnt;
3725                 b_offset += cnt;
3726         }
3727         mtx_unlock(&cmtx);
3728 }
3729
3730 void
3731 pmap_copy_page(vm_page_t src, vm_page_t dst)
3732 {
3733
3734         if (_arm_memcpy && PAGE_SIZE >= _min_memcpy_size &&
3735             _arm_memcpy((void *)VM_PAGE_TO_PHYS(dst),
3736             (void *)VM_PAGE_TO_PHYS(src), PAGE_SIZE, IS_PHYSICAL) == 0)
3737                 return;
3738
3739         pmap_copy_page_generic(VM_PAGE_TO_PHYS(src), VM_PAGE_TO_PHYS(dst));
3740 }
3741
3742 /*
3743  * this routine returns true if a physical page resides
3744  * in the given pmap.
3745  */
3746 boolean_t
3747 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
3748 {
3749         pv_entry_t pv;
3750         int loops = 0;
3751         boolean_t rv;
3752
3753         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3754             ("pmap_page_exists_quick: page %p is not managed", m));
3755         rv = FALSE;
3756         rw_wlock(&pvh_global_lock);
3757         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
3758                 if (PV_PMAP(pv) == pmap) {
3759                         rv = TRUE;
3760                         break;
3761                 }
3762                 loops++;
3763                 if (loops >= 16)
3764                         break;
3765         }
3766
3767         rw_wunlock(&pvh_global_lock);
3768         return (rv);
3769 }
3770
3771 /*
3772  *      pmap_page_wired_mappings:
3773  *
3774  *      Return the number of managed mappings to the given physical page
3775  *      that are wired.
3776  */
3777 int
3778 pmap_page_wired_mappings(vm_page_t m)
3779 {
3780         pv_entry_t pv;
3781         int count;
3782
3783         count = 0;
3784         if ((m->flags & PG_FICTITIOUS) != 0)
3785                 return (count);
3786         rw_wlock(&pvh_global_lock);
3787         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list)
3788                 if ((pv->pv_flags & PVF_WIRED) != 0)
3789                         count++;
3790         rw_wunlock(&pvh_global_lock);
3791         return (count);
3792 }
3793
3794 /*
3795  *      pmap_is_referenced:
3796  *
3797  *      Return whether or not the specified physical page was referenced
3798  *      in any physical maps.
3799  */
3800 boolean_t
3801 pmap_is_referenced(vm_page_t m)
3802 {
3803
3804         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3805             ("pmap_is_referenced: page %p is not managed", m));
3806         return ((m->md.pvh_attrs & PVF_REF) != 0);
3807 }
3808
3809 /*
3810  *      pmap_ts_referenced:
3811  *
3812  *      Return the count of reference bits for a page, clearing all of them.
3813  */
3814 int
3815 pmap_ts_referenced(vm_page_t m)
3816 {
3817
3818         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3819             ("pmap_ts_referenced: page %p is not managed", m));
3820         return (pmap_clearbit(m, PVF_REF));
3821 }
3822
3823
3824 boolean_t
3825 pmap_is_modified(vm_page_t m)
3826 {
3827
3828         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3829             ("pmap_is_modified: page %p is not managed", m));
3830         if (m->md.pvh_attrs & PVF_MOD)
3831                 return (TRUE);
3832
3833         return(FALSE);
3834 }
3835
3836
3837 /*
3838  *      Clear the modify bits on the specified physical page.
3839  */
3840 void
3841 pmap_clear_modify(vm_page_t m)
3842 {
3843
3844         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3845             ("pmap_clear_modify: page %p is not managed", m));
3846         VM_OBJECT_ASSERT_WLOCKED(m->object);
3847         KASSERT((m->oflags & VPO_BUSY) == 0,
3848             ("pmap_clear_modify: page %p is busy", m));
3849
3850         /*
3851          * If the page is not PGA_WRITEABLE, then no mappings can be modified.
3852          * If the object containing the page is locked and the page is not
3853          * VPO_BUSY, then PGA_WRITEABLE cannot be concurrently set.
3854          */
3855         if ((m->aflags & PGA_WRITEABLE) == 0)
3856                 return;
3857
3858         if (m->md.pvh_attrs & PVF_MOD)
3859                 pmap_clearbit(m, PVF_MOD);
3860 }
3861
3862
3863 /*
3864  *      pmap_clear_reference:
3865  *
3866  *      Clear the reference bit on the specified physical page.
3867  */
3868 void
3869 pmap_clear_reference(vm_page_t m)
3870 {
3871
3872         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3873             ("pmap_clear_reference: page %p is not managed", m));
3874         if (m->md.pvh_attrs & PVF_REF)
3875                 pmap_clearbit(m, PVF_REF);
3876 }
3877
3878
3879 /*
3880  * Clear the write and modified bits in each of the given page's mappings.
3881  */
3882 void
3883 pmap_remove_write(vm_page_t m)
3884 {
3885         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3886             ("pmap_remove_write: page %p is not managed", m));
3887
3888         /*
3889          * If the page is not VPO_BUSY, then PGA_WRITEABLE cannot be set by
3890          * another thread while the object is locked.  Thus, if PGA_WRITEABLE
3891          * is clear, no page table entries need updating.
3892          */
3893         VM_OBJECT_ASSERT_WLOCKED(m->object);
3894         if ((m->oflags & VPO_BUSY) != 0 ||
3895             (m->aflags & PGA_WRITEABLE) != 0)
3896                 pmap_clearbit(m, PVF_WRITE);
3897 }
3898
3899
3900 /*
3901  * perform the pmap work for mincore
3902  */
3903 int
3904 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *locked_pa)
3905 {
3906         struct l2_bucket *l2b;
3907         pt_entry_t *ptep, pte;
3908         vm_paddr_t pa;
3909         vm_page_t m;
3910         int val;
3911         boolean_t managed;
3912
3913         PMAP_LOCK(pmap);
3914 retry:
3915         l2b = pmap_get_l2_bucket(pmap, addr);
3916         if (l2b == NULL) {
3917                 val = 0;
3918                 goto out;
3919         }
3920         ptep = &l2b->l2b_kva[l2pte_index(addr)];
3921         pte = *ptep;
3922         if (!l2pte_valid(pte)) {
3923                 val = 0;
3924                 goto out;
3925         }
3926         val = MINCORE_INCORE;
3927         if (L2_S_WRITABLE(pte))
3928                 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
3929         managed = FALSE;
3930         pa = l2pte_pa(pte);
3931         m = PHYS_TO_VM_PAGE(pa);
3932         if (m != NULL && (m->oflags & VPO_UNMANAGED) == 0)
3933                 managed = TRUE;
3934         if (managed) {
3935                 /*
3936                  * The ARM pmap tries to maintain a per-mapping
3937                  * reference bit.  The trouble is that it's kept in
3938                  * the PV entry, not the PTE, so it's costly to access
3939                  * here.  You would need to acquire the pvh global
3940                  * lock, call pmap_find_pv(), and introduce a custom
3941                  * version of vm_page_pa_tryrelock() that releases and
3942                  * reacquires the pvh global lock.  In the end, I
3943                  * doubt it's worthwhile.  This may falsely report
3944                  * the given address as referenced.
3945                  */
3946                 if ((m->md.pvh_attrs & PVF_REF) != 0)
3947                         val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
3948         }
3949         if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
3950             (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) && managed) {
3951                 /* Ensure that "PHYS_TO_VM_PAGE(pa)->object" doesn't change. */
3952                 if (vm_page_pa_tryrelock(pmap, pa, locked_pa))
3953                         goto retry;
3954         } else
3955 out:
3956                 PA_UNLOCK_COND(*locked_pa);
3957         PMAP_UNLOCK(pmap);
3958         return (val);
3959 }
3960
3961 void
3962 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
3963 {
3964 }
3965
3966 /*
3967  *      Increase the starting virtual address of the given mapping if a
3968  *      different alignment might result in more superpage mappings.
3969  */
3970 void
3971 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
3972     vm_offset_t *addr, vm_size_t size)
3973 {
3974 }
3975
3976
3977 /*
3978  * Map a set of physical memory pages into the kernel virtual
3979  * address space. Return a pointer to where it is mapped. This
3980  * routine is intended to be used for mapping device memory,
3981  * NOT real memory.
3982  */
3983 void *
3984 pmap_mapdev(vm_offset_t pa, vm_size_t size)
3985 {
3986         vm_offset_t va, tmpva, offset;
3987
3988         offset = pa & PAGE_MASK;
3989         size = roundup(size, PAGE_SIZE);
3990
3991         GIANT_REQUIRED;
3992
3993         va = kmem_alloc_nofault(kernel_map, size);
3994         if (!va)
3995                 panic("pmap_mapdev: Couldn't alloc kernel virtual memory");
3996         for (tmpva = va; size > 0;) {
3997                 pmap_kenter_internal(tmpva, pa, 0);
3998                 size -= PAGE_SIZE;
3999                 tmpva += PAGE_SIZE;
4000                 pa += PAGE_SIZE;
4001         }
4002
4003         return ((void *)(va + offset));
4004 }
4005
4006 /*
4007  * pmap_map_section:
4008  *
4009  *      Create a single section mapping.
4010  */
4011 void
4012 pmap_map_section(vm_offset_t l1pt, vm_offset_t va, vm_offset_t pa,
4013     int prot, int cache)
4014 {
4015         pd_entry_t *pde = (pd_entry_t *) l1pt;
4016         pd_entry_t fl;
4017
4018         KASSERT(((va | pa) & L1_S_OFFSET) == 0, ("ouin2"));
4019
4020         fl = l1_mem_types[cache];
4021
4022         pde[va >> L1_S_SHIFT] = L1_S_PROTO | pa |
4023             L1_S_PROT(PTE_KERNEL, prot) | fl | L1_S_DOM(PMAP_DOMAIN_KERNEL);
4024         PTE_SYNC(&pde[va >> L1_S_SHIFT]);
4025 }
4026
4027 /*
4028  * pmap_link_l2pt:
4029  *
4030  *      Link the L2 page table specified by l2pv.pv_pa into the L1
4031  *      page table at the slot for "va".
4032  */
4033 void
4034 pmap_link_l2pt(vm_offset_t l1pt, vm_offset_t va, struct pv_addr *l2pv)
4035 {
4036         pd_entry_t *pde = (pd_entry_t *) l1pt, proto;
4037         u_int slot = va >> L1_S_SHIFT;
4038
4039         proto = L1_S_DOM(PMAP_DOMAIN_KERNEL) | L1_C_PROTO;
4040
4041 #ifdef VERBOSE_INIT_ARM
4042         printf("pmap_link_l2pt: pa=0x%x va=0x%x\n", l2pv->pv_pa, l2pv->pv_va);
4043 #endif
4044
4045         pde[slot + 0] = proto | (l2pv->pv_pa + 0x000);
4046         PTE_SYNC(&pde[slot]);
4047
4048         SLIST_INSERT_HEAD(&kernel_pt_list, l2pv, pv_list);
4049
4050 }
4051
4052 /*
4053  * pmap_map_entry
4054  *
4055  *      Create a single page mapping.
4056  */
4057 void
4058 pmap_map_entry(vm_offset_t l1pt, vm_offset_t va, vm_offset_t pa, int prot,
4059     int cache)
4060 {
4061         pd_entry_t *pde = (pd_entry_t *) l1pt;
4062         pt_entry_t fl;
4063         pt_entry_t *pte;
4064
4065         KASSERT(((va | pa) & PAGE_MASK) == 0, ("ouin"));
4066
4067         fl = l2s_mem_types[cache];
4068
4069         if ((pde[va >> L1_S_SHIFT] & L1_TYPE_MASK) != L1_TYPE_C)
4070                 panic("pmap_map_entry: no L2 table for VA 0x%08x", va);
4071
4072         pte = (pt_entry_t *) kernel_pt_lookup(pde[L1_IDX(va)] & L1_C_ADDR_MASK);
4073
4074         if (pte == NULL)
4075                 panic("pmap_map_entry: can't find L2 table for VA 0x%08x", va);
4076
4077         pte[l2pte_index(va)] = L2_S_PROTO | pa | fl;
4078         pmap_set_prot(&pte[l2pte_index(va)], prot, 0);
4079         PTE_SYNC(&pte[l2pte_index(va)]);
4080 }
4081
4082 /*
4083  * pmap_map_chunk:
4084  *
4085  *      Map a chunk of memory using the most efficient mappings
4086  *      possible (section. large page, small page) into the
4087  *      provided L1 and L2 tables at the specified virtual address.
4088  */
4089 vm_size_t
4090 pmap_map_chunk(vm_offset_t l1pt, vm_offset_t va, vm_offset_t pa,
4091     vm_size_t size, int prot, int type)
4092 {
4093         pd_entry_t *pde = (pd_entry_t *) l1pt;
4094         pt_entry_t *pte, f1, f2s, f2l;
4095         vm_size_t resid;
4096         int i;
4097
4098         resid = (size + (PAGE_SIZE - 1)) & ~(PAGE_SIZE - 1);
4099
4100         if (l1pt == 0)
4101                 panic("pmap_map_chunk: no L1 table provided");
4102
4103 #ifdef VERBOSE_INIT_ARM
4104         printf("pmap_map_chunk: pa=0x%x va=0x%x size=0x%x resid=0x%x "
4105             "prot=0x%x type=%d\n", pa, va, size, resid, prot, type);
4106 #endif
4107
4108         f1 = l1_mem_types[type];
4109         f2l = l2l_mem_types[type];
4110         f2s = l2s_mem_types[type];
4111
4112         size = resid;
4113
4114         while (resid > 0) {
4115                 /* See if we can use a section mapping. */
4116                 if (L1_S_MAPPABLE_P(va, pa, resid)) {
4117 #ifdef VERBOSE_INIT_ARM
4118                         printf("S");
4119 #endif
4120                         pde[va >> L1_S_SHIFT] = L1_S_PROTO | pa |
4121                             L1_S_PROT(PTE_KERNEL, prot) | f1 |
4122                             L1_S_DOM(PMAP_DOMAIN_KERNEL);
4123                         PTE_SYNC(&pde[va >> L1_S_SHIFT]);
4124                         va += L1_S_SIZE;
4125                         pa += L1_S_SIZE;
4126                         resid -= L1_S_SIZE;
4127                         continue;
4128                 }
4129
4130                 /*
4131                  * Ok, we're going to use an L2 table.  Make sure
4132                  * one is actually in the corresponding L1 slot
4133                  * for the current VA.
4134                  */
4135                 if ((pde[va >> L1_S_SHIFT] & L1_TYPE_MASK) != L1_TYPE_C)
4136                         panic("pmap_map_chunk: no L2 table for VA 0x%08x", va);
4137
4138                 pte = (pt_entry_t *) kernel_pt_lookup(
4139                     pde[L1_IDX(va)] & L1_C_ADDR_MASK);
4140                 if (pte == NULL)
4141                         panic("pmap_map_chunk: can't find L2 table for VA"
4142                             "0x%08x", va);
4143                 /* See if we can use a L2 large page mapping. */
4144                 if (L2_L_MAPPABLE_P(va, pa, resid)) {
4145 #ifdef VERBOSE_INIT_ARM
4146                         printf("L");
4147 #endif
4148                         for (i = 0; i < 16; i++) {
4149                                 pte[l2pte_index(va) + i] =
4150                                     L2_L_PROTO | pa |
4151                                     L2_L_PROT(PTE_KERNEL, prot) | f2l;
4152                                 PTE_SYNC(&pte[l2pte_index(va) + i]);
4153                         }
4154                         va += L2_L_SIZE;
4155                         pa += L2_L_SIZE;
4156                         resid -= L2_L_SIZE;
4157                         continue;
4158                 }
4159
4160                 /* Use a small page mapping. */
4161 #ifdef VERBOSE_INIT_ARM
4162                 printf("P");
4163 #endif
4164                 pte[l2pte_index(va)] = L2_S_PROTO | pa | f2s;
4165                 pmap_set_prot(&pte[l2pte_index(va)], prot, 0);
4166                 PTE_SYNC(&pte[l2pte_index(va)]);
4167                 va += PAGE_SIZE;
4168                 pa += PAGE_SIZE;
4169                 resid -= PAGE_SIZE;
4170         }
4171 #ifdef VERBOSE_INIT_ARM
4172         printf("\n");
4173 #endif
4174         return (size);
4175
4176 }
4177
4178 /********************** Static device map routines ***************************/
4179
4180 static const struct pmap_devmap *pmap_devmap_table;
4181
4182 /*
4183  * Register the devmap table.  This is provided in case early console
4184  * initialization needs to register mappings created by bootstrap code
4185  * before pmap_devmap_bootstrap() is called.
4186  */
4187 void
4188 pmap_devmap_register(const struct pmap_devmap *table)
4189 {
4190
4191         pmap_devmap_table = table;
4192 }
4193
4194 /*
4195  * Map all of the static regions in the devmap table, and remember
4196  * the devmap table so other parts of the kernel can look up entries
4197  * later.
4198  */
4199 void
4200 pmap_devmap_bootstrap(vm_offset_t l1pt, const struct pmap_devmap *table)
4201 {
4202         int i;
4203
4204         pmap_devmap_table = table;
4205
4206         for (i = 0; pmap_devmap_table[i].pd_size != 0; i++) {
4207 #ifdef VERBOSE_INIT_ARM
4208                 printf("devmap: %08x -> %08x @ %08x\n",
4209                     pmap_devmap_table[i].pd_pa,
4210                     pmap_devmap_table[i].pd_pa +
4211                         pmap_devmap_table[i].pd_size - 1,
4212                     pmap_devmap_table[i].pd_va);
4213 #endif
4214                 pmap_map_chunk(l1pt, pmap_devmap_table[i].pd_va,
4215                     pmap_devmap_table[i].pd_pa,
4216                     pmap_devmap_table[i].pd_size,
4217                     pmap_devmap_table[i].pd_prot,
4218                     pmap_devmap_table[i].pd_cache);
4219         }
4220 }
4221
4222 const struct pmap_devmap *
4223 pmap_devmap_find_pa(vm_paddr_t pa, vm_size_t size)
4224 {
4225         int i;
4226
4227         if (pmap_devmap_table == NULL)
4228                 return (NULL);
4229
4230         for (i = 0; pmap_devmap_table[i].pd_size != 0; i++) {
4231                 if (pa >= pmap_devmap_table[i].pd_pa &&
4232                     pa + size <= pmap_devmap_table[i].pd_pa +
4233                                  pmap_devmap_table[i].pd_size)
4234                         return (&pmap_devmap_table[i]);
4235         }
4236
4237         return (NULL);
4238 }
4239
4240 const struct pmap_devmap *
4241 pmap_devmap_find_va(vm_offset_t va, vm_size_t size)
4242 {
4243         int i;
4244
4245         if (pmap_devmap_table == NULL)
4246                 return (NULL);
4247
4248         for (i = 0; pmap_devmap_table[i].pd_size != 0; i++) {
4249                 if (va >= pmap_devmap_table[i].pd_va &&
4250                     va + size <= pmap_devmap_table[i].pd_va +
4251                                  pmap_devmap_table[i].pd_size)
4252                         return (&pmap_devmap_table[i]);
4253         }
4254
4255         return (NULL);
4256 }
4257
4258 int
4259 pmap_dmap_iscurrent(pmap_t pmap)
4260 {
4261         return(pmap_is_current(pmap));
4262 }
4263
4264 void
4265 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
4266 {
4267         /* 
4268          * Remember the memattr in a field that gets used to set the appropriate
4269          * bits in the PTEs as mappings are established.
4270          */
4271         m->md.pv_memattr = ma;
4272
4273         /*
4274          * It appears that this function can only be called before any mappings
4275          * for the page are established on ARM.  If this ever changes, this code
4276          * will need to walk the pv_list and make each of the existing mappings
4277          * uncacheable, being careful to sync caches and PTEs (and maybe
4278          * invalidate TLB?) for any current mapping it modifies.
4279          */
4280         if (m->md.pv_kva != 0 || TAILQ_FIRST(&m->md.pv_list) != NULL)
4281                 panic("Can't change memattr on page with existing mappings");
4282 }