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