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