xref: /netbsd-src/sys/arch/powerpc/ibm4xx/pmap.c (revision df0caa2637da0538ecdf6b878c4d08e684b43d8f)
1 /*	$NetBSD: pmap.c,v 1.36 2005/06/03 11:42:44 scw Exp $	*/
2 
3 /*
4  * Copyright 2001 Wasabi Systems, Inc.
5  * All rights reserved.
6  *
7  * Written by Eduardo Horvath and Simon Burge 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) 1995, 1996 Wolfgang Solfrank.
40  * Copyright (C) 1995, 1996 TooLs GmbH.
41  * All rights reserved.
42  *
43  * Redistribution and use in source and binary forms, with or without
44  * modification, are permitted provided that the following conditions
45  * are met:
46  * 1. Redistributions of source code must retain the above copyright
47  *    notice, this list of conditions and the following disclaimer.
48  * 2. Redistributions in binary form must reproduce the above copyright
49  *    notice, this list of conditions and the following disclaimer in the
50  *    documentation and/or other materials provided with the distribution.
51  * 3. All advertising materials mentioning features or use of this software
52  *    must display the following acknowledgement:
53  *	This product includes software developed by TooLs GmbH.
54  * 4. The name of TooLs GmbH may not be used to endorse or promote products
55  *    derived from this software without specific prior written permission.
56  *
57  * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``AS IS'' AND ANY EXPRESS OR
58  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
59  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
60  * IN NO EVENT SHALL TOOLS GMBH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
61  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
62  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
63  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
64  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
65  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
66  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
67  */
68 
69 #include <sys/cdefs.h>
70 __KERNEL_RCSID(0, "$NetBSD: pmap.c,v 1.36 2005/06/03 11:42:44 scw Exp $");
71 
72 #include <sys/param.h>
73 #include <sys/malloc.h>
74 #include <sys/proc.h>
75 #include <sys/user.h>
76 #include <sys/queue.h>
77 #include <sys/systm.h>
78 #include <sys/pool.h>
79 #include <sys/device.h>
80 
81 #include <uvm/uvm.h>
82 
83 #include <machine/cpu.h>
84 #include <machine/pcb.h>
85 #include <machine/powerpc.h>
86 
87 #include <powerpc/spr.h>
88 #include <machine/tlb.h>
89 
90 /*
91  * kernmap is an array of PTEs large enough to map in
92  * 4GB.  At 16KB/page it is 256K entries or 2MB.
93  */
94 #define KERNMAP_SIZE	((0xffffffffU/PAGE_SIZE)+1)
95 caddr_t kernmap;
96 
97 #define MINCTX		2
98 #define NUMCTX		256
99 volatile struct pmap *ctxbusy[NUMCTX];
100 
101 #define TLBF_USED	0x1
102 #define	TLBF_REF	0x2
103 #define	TLBF_LOCKED	0x4
104 #define	TLB_LOCKED(i)	(tlb_info[(i)].ti_flags & TLBF_LOCKED)
105 typedef struct tlb_info_s {
106 	char	ti_flags;
107 	char	ti_ctx;		/* TLB_PID assiciated with the entry */
108 	u_int	ti_va;
109 } tlb_info_t;
110 
111 volatile tlb_info_t tlb_info[NTLB];
112 /* We'll use a modified FIFO replacement policy cause it's cheap */
113 volatile int tlbnext = TLB_NRESERVED;
114 
115 u_long dtlb_miss_count = 0;
116 u_long itlb_miss_count = 0;
117 u_long ktlb_miss_count = 0;
118 u_long utlb_miss_count = 0;
119 
120 /* Event counters */
121 struct evcnt tlbmiss_ev = EVCNT_INITIALIZER(EVCNT_TYPE_TRAP,
122 	NULL, "cpu", "tlbmiss");
123 struct evcnt tlbhit_ev = EVCNT_INITIALIZER(EVCNT_TYPE_TRAP,
124 	NULL, "cpu", "tlbhit");
125 struct evcnt tlbflush_ev = EVCNT_INITIALIZER(EVCNT_TYPE_TRAP,
126 	NULL, "cpu", "tlbflush");
127 struct evcnt tlbenter_ev = EVCNT_INITIALIZER(EVCNT_TYPE_TRAP,
128 	NULL, "cpu", "tlbenter");
129 
130 struct pmap kernel_pmap_;
131 
132 int physmem;
133 static int npgs;
134 static u_int nextavail;
135 #ifndef MSGBUFADDR
136 extern paddr_t msgbuf_paddr;
137 #endif
138 
139 static struct mem_region *mem, *avail;
140 
141 /*
142  * This is a cache of referenced/modified bits.
143  * Bits herein are shifted by ATTRSHFT.
144  */
145 static char *pmap_attrib;
146 
147 #define PV_WIRED	0x1
148 #define PV_WIRE(pv)	((pv)->pv_va |= PV_WIRED)
149 #define PV_UNWIRE(pv)	((pv)->pv_va &= ~PV_WIRED)
150 #define PV_ISWIRED(pv)	((pv)->pv_va & PV_WIRED)
151 #define PV_CMPVA(va,pv)	(!(((pv)->pv_va ^ (va)) & (~PV_WIRED)))
152 
153 struct pv_entry {
154 	struct pv_entry *pv_next;	/* Linked list of mappings */
155 	vaddr_t pv_va;			/* virtual address of mapping */
156 	struct pmap *pv_pm;
157 };
158 
159 struct pv_entry *pv_table;
160 static struct pool pv_pool;
161 
162 static int pmap_initialized;
163 
164 static int ctx_flush(int);
165 
166 inline struct pv_entry *pa_to_pv(paddr_t);
167 static inline char *pa_to_attr(paddr_t);
168 
169 static inline volatile u_int *pte_find(struct pmap *, vaddr_t);
170 static inline int pte_enter(struct pmap *, vaddr_t, u_int);
171 
172 static inline int pmap_enter_pv(struct pmap *, vaddr_t, paddr_t, boolean_t);
173 static void pmap_remove_pv(struct pmap *, vaddr_t, paddr_t);
174 
175 
176 inline struct pv_entry *
177 pa_to_pv(paddr_t pa)
178 {
179 	int bank, pg;
180 
181 	bank = vm_physseg_find(atop(pa), &pg);
182 	if (bank == -1)
183 		return NULL;
184 	return &vm_physmem[bank].pmseg.pvent[pg];
185 }
186 
187 static inline char *
188 pa_to_attr(paddr_t pa)
189 {
190 	int bank, pg;
191 
192 	bank = vm_physseg_find(atop(pa), &pg);
193 	if (bank == -1)
194 		return NULL;
195 	return &vm_physmem[bank].pmseg.attrs[pg];
196 }
197 
198 /*
199  * Insert PTE into page table.
200  */
201 int
202 pte_enter(struct pmap *pm, vaddr_t va, u_int pte)
203 {
204 	int seg = STIDX(va);
205 	int ptn = PTIDX(va);
206 	u_int oldpte;
207 
208 	if (!pm->pm_ptbl[seg]) {
209 		/* Don't allocate a page to clear a non-existent mapping. */
210 		if (!pte)
211 			return (0);
212 		/* Allocate a page XXXX this will sleep! */
213 		pm->pm_ptbl[seg] =
214 		    (uint *)uvm_km_alloc(kernel_map, PAGE_SIZE, 0,
215 		    UVM_KMF_WIRED | UVM_KMF_ZERO);
216 	}
217 	oldpte = pm->pm_ptbl[seg][ptn];
218 	pm->pm_ptbl[seg][ptn] = pte;
219 
220 	/* Flush entry. */
221 	ppc4xx_tlb_flush(va, pm->pm_ctx);
222 	if (oldpte != pte) {
223 		if (pte == 0)
224 			pm->pm_stats.resident_count--;
225 		else
226 			pm->pm_stats.resident_count++;
227 	}
228 	return (1);
229 }
230 
231 /*
232  * Get a pointer to a PTE in a page table.
233  */
234 volatile u_int *
235 pte_find(struct pmap *pm, vaddr_t va)
236 {
237 	int seg = STIDX(va);
238 	int ptn = PTIDX(va);
239 
240 	if (pm->pm_ptbl[seg])
241 		return (&pm->pm_ptbl[seg][ptn]);
242 
243 	return (NULL);
244 }
245 
246 /*
247  * This is called during initppc, before the system is really initialized.
248  */
249 void
250 pmap_bootstrap(u_int kernelstart, u_int kernelend)
251 {
252 	struct mem_region *mp, *mp1;
253 	int cnt, i;
254 	u_int s, e, sz;
255 
256 	/*
257 	 * Allocate the kernel page table at the end of
258 	 * kernel space so it's in the locked TTE.
259 	 */
260 	kernmap = (caddr_t)kernelend;
261 
262 	/*
263 	 * Initialize kernel page table.
264 	 */
265 	for (i = 0; i < STSZ; i++) {
266 		pmap_kernel()->pm_ptbl[i] = 0;
267 	}
268 	ctxbusy[0] = ctxbusy[1] = pmap_kernel();
269 
270 	/*
271 	 * Announce page-size to the VM-system
272 	 */
273 	uvmexp.pagesize = NBPG;
274 	uvm_setpagesize();
275 
276 	/*
277 	 * Get memory.
278 	 */
279 	mem_regions(&mem, &avail);
280 	for (mp = mem; mp->size; mp++) {
281 		physmem += btoc(mp->size);
282 		printf("+%lx,",mp->size);
283 	}
284 	printf("\n");
285 	ppc4xx_tlb_init();
286 	/*
287 	 * Count the number of available entries.
288 	 */
289 	for (cnt = 0, mp = avail; mp->size; mp++)
290 		cnt++;
291 
292 	/*
293 	 * Page align all regions.
294 	 * Non-page aligned memory isn't very interesting to us.
295 	 * Also, sort the entries for ascending addresses.
296 	 */
297 	kernelstart &= ~PGOFSET;
298 	kernelend = (kernelend + PGOFSET) & ~PGOFSET;
299 	for (mp = avail; mp->size; mp++) {
300 		s = mp->start;
301 		e = mp->start + mp->size;
302 		printf("%08x-%08x -> ",s,e);
303 		/*
304 		 * Check whether this region holds all of the kernel.
305 		 */
306 		if (s < kernelstart && e > kernelend) {
307 			avail[cnt].start = kernelend;
308 			avail[cnt++].size = e - kernelend;
309 			e = kernelstart;
310 		}
311 		/*
312 		 * Look whether this regions starts within the kernel.
313 		 */
314 		if (s >= kernelstart && s < kernelend) {
315 			if (e <= kernelend)
316 				goto empty;
317 			s = kernelend;
318 		}
319 		/*
320 		 * Now look whether this region ends within the kernel.
321 		 */
322 		if (e > kernelstart && e <= kernelend) {
323 			if (s >= kernelstart)
324 				goto empty;
325 			e = kernelstart;
326 		}
327 		/*
328 		 * Now page align the start and size of the region.
329 		 */
330 		s = round_page(s);
331 		e = trunc_page(e);
332 		if (e < s)
333 			e = s;
334 		sz = e - s;
335 		printf("%08x-%08x = %x\n",s,e,sz);
336 		/*
337 		 * Check whether some memory is left here.
338 		 */
339 		if (sz == 0) {
340 		empty:
341 			memmove(mp, mp + 1,
342 				(cnt - (mp - avail)) * sizeof *mp);
343 			cnt--;
344 			mp--;
345 			continue;
346 		}
347 		/*
348 		 * Do an insertion sort.
349 		 */
350 		npgs += btoc(sz);
351 		for (mp1 = avail; mp1 < mp; mp1++)
352 			if (s < mp1->start)
353 				break;
354 		if (mp1 < mp) {
355 			memmove(mp1 + 1, mp1, (char *)mp - (char *)mp1);
356 			mp1->start = s;
357 			mp1->size = sz;
358 		} else {
359 			mp->start = s;
360 			mp->size = sz;
361 		}
362 	}
363 
364 	/*
365 	 * We cannot do pmap_steal_memory here,
366 	 * since we don't run with translation enabled yet.
367 	 */
368 #ifndef MSGBUFADDR
369 	/*
370 	 * allow for msgbuf
371 	 */
372 	sz = round_page(MSGBUFSIZE);
373 	mp = NULL;
374 	for (mp1 = avail; mp1->size; mp1++)
375 		if (mp1->size >= sz)
376 			mp = mp1;
377 	if (mp == NULL)
378 		panic("not enough memory?");
379 
380 	npgs -= btoc(sz);
381 	msgbuf_paddr = mp->start + mp->size - sz;
382 	mp->size -= sz;
383 	if (mp->size <= 0)
384 		memmove(mp, mp + 1, (cnt - (mp - avail)) * sizeof *mp);
385 #endif
386 
387 	for (mp = avail; mp->size; mp++)
388 		uvm_page_physload(atop(mp->start), atop(mp->start + mp->size),
389 			atop(mp->start), atop(mp->start + mp->size),
390 			VM_FREELIST_DEFAULT);
391 
392 	/*
393 	 * Initialize kernel pmap and hardware.
394 	 */
395 	/* Setup TLB pid allocator so it knows we alreadu using PID 1 */
396 	pmap_kernel()->pm_ctx = KERNEL_PID;
397 	nextavail = avail->start;
398 
399 
400 	evcnt_attach_static(&tlbmiss_ev);
401 	evcnt_attach_static(&tlbhit_ev);
402 	evcnt_attach_static(&tlbflush_ev);
403 	evcnt_attach_static(&tlbenter_ev);
404 }
405 
406 /*
407  * Restrict given range to physical memory
408  *
409  * (Used by /dev/mem)
410  */
411 void
412 pmap_real_memory(paddr_t *start, psize_t *size)
413 {
414 	struct mem_region *mp;
415 
416 	for (mp = mem; mp->size; mp++) {
417 		if (*start + *size > mp->start &&
418 		    *start < mp->start + mp->size) {
419 			if (*start < mp->start) {
420 				*size -= mp->start - *start;
421 				*start = mp->start;
422 			}
423 			if (*start + *size > mp->start + mp->size)
424 				*size = mp->start + mp->size - *start;
425 			return;
426 		}
427 	}
428 	*size = 0;
429 }
430 
431 /*
432  * Initialize anything else for pmap handling.
433  * Called during vm_init().
434  */
435 void
436 pmap_init(void)
437 {
438 	struct pv_entry *pv;
439 	vsize_t sz;
440 	vaddr_t addr;
441 	int i, s;
442 	int bank;
443 	char *attr;
444 
445 	sz = (vsize_t)((sizeof(struct pv_entry) + 1) * npgs);
446 	sz = round_page(sz);
447 	addr = uvm_km_alloc(kernel_map, sz, 0, UVM_KMF_WIRED | UVM_KMF_ZERO);
448 	s = splvm();
449 	pv = pv_table = (struct pv_entry *)addr;
450 	for (i = npgs; --i >= 0;)
451 		pv++->pv_pm = NULL;
452 	pmap_attrib = (char *)pv;
453 	memset(pv, 0, npgs);
454 
455 	pv = pv_table;
456 	attr = pmap_attrib;
457 	for (bank = 0; bank < vm_nphysseg; bank++) {
458 		sz = vm_physmem[bank].end - vm_physmem[bank].start;
459 		vm_physmem[bank].pmseg.pvent = pv;
460 		vm_physmem[bank].pmseg.attrs = attr;
461 		pv += sz;
462 		attr += sz;
463 	}
464 
465 	pmap_initialized = 1;
466 	splx(s);
467 
468 	/* Setup a pool for additional pvlist structures */
469 	pool_init(&pv_pool, sizeof(struct pv_entry), 0, 0, 0, "pv_entry", NULL);
470 }
471 
472 /*
473  * How much virtual space is available to the kernel?
474  */
475 void
476 pmap_virtual_space(vaddr_t *start, vaddr_t *end)
477 {
478 
479 #if 0
480 	/*
481 	 * Reserve one segment for kernel virtual memory
482 	 */
483 	*start = (vaddr_t)(KERNEL_SR << ADDR_SR_SHFT);
484 	*end = *start + SEGMENT_LENGTH;
485 #else
486 	*start = (vaddr_t) VM_MIN_KERNEL_ADDRESS;
487 	*end = (vaddr_t) VM_MAX_KERNEL_ADDRESS;
488 #endif
489 }
490 
491 #ifdef PMAP_GROWKERNEL
492 /*
493  * Preallocate kernel page tables to a specified VA.
494  * This simply loops through the first TTE for each
495  * page table from the beginning of the kernel pmap,
496  * reads the entry, and if the result is
497  * zero (either invalid entry or no page table) it stores
498  * a zero there, populating page tables in the process.
499  * This is not the most efficient technique but i don't
500  * expect it to be called that often.
501  */
502 extern struct vm_page *vm_page_alloc1 __P((void));
503 extern void vm_page_free1 __P((struct vm_page *));
504 
505 vaddr_t kbreak = VM_MIN_KERNEL_ADDRESS;
506 
507 vaddr_t
508 pmap_growkernel(vaddr_t maxkvaddr)
509 {
510 	int s;
511 	int seg;
512 	paddr_t pg;
513 	struct pmap *pm = pmap_kernel();
514 
515 	s = splvm();
516 
517 	/* Align with the start of a page table */
518 	for (kbreak &= ~(PTMAP-1); kbreak < maxkvaddr;
519 	     kbreak += PTMAP) {
520 		seg = STIDX(kbreak);
521 
522 		if (pte_find(pm, kbreak))
523 			continue;
524 
525 		if (uvm.page_init_done) {
526 			pg = (paddr_t)VM_PAGE_TO_PHYS(vm_page_alloc1());
527 		} else {
528 			if (!uvm_page_physget(&pg))
529 				panic("pmap_growkernel: no memory");
530 		}
531 		if (!pg)
532 			panic("pmap_growkernel: no pages");
533 		pmap_zero_page((paddr_t)pg);
534 
535 		/* XXX This is based on all phymem being addressable */
536 		pm->pm_ptbl[seg] = (u_int *)pg;
537 	}
538 	splx(s);
539 	return (kbreak);
540 }
541 
542 /*
543  *	vm_page_alloc1:
544  *
545  *	Allocate and return a memory cell with no associated object.
546  */
547 struct vm_page *
548 vm_page_alloc1(void)
549 {
550 	struct vm_page *pg;
551 
552 	pg = uvm_pagealloc(NULL, 0, NULL, UVM_PGA_USERESERVE);
553 	if (pg) {
554 		pg->wire_count = 1;	/* no mappings yet */
555 		pg->flags &= ~PG_BUSY;	/* never busy */
556 	}
557 	return pg;
558 }
559 
560 /*
561  *	vm_page_free1:
562  *
563  *	Returns the given page to the free list,
564  *	disassociating it with any VM object.
565  *
566  *	Object and page must be locked prior to entry.
567  */
568 void
569 vm_page_free1(struct vm_page *pg)
570 {
571 #ifdef DIAGNOSTIC
572 	if (pg->flags != (PG_CLEAN|PG_FAKE)) {
573 		printf("Freeing invalid page %p\n", pg);
574 		printf("pa = %llx\n", (unsigned long long)VM_PAGE_TO_PHYS(pg));
575 #ifdef DDB
576 		Debugger();
577 #endif
578 		return;
579 	}
580 #endif
581 	pg->flags |= PG_BUSY;
582 	pg->wire_count = 0;
583 	uvm_pagefree(pg);
584 }
585 #endif
586 
587 /*
588  * Create and return a physical map.
589  */
590 struct pmap *
591 pmap_create(void)
592 {
593 	struct pmap *pm;
594 
595 	pm = malloc(sizeof *pm, M_VMPMAP, M_WAITOK);
596 	memset(pm, 0, sizeof *pm);
597 	pm->pm_refs = 1;
598 	return pm;
599 }
600 
601 /*
602  * Add a reference to the given pmap.
603  */
604 void
605 pmap_reference(struct pmap *pm)
606 {
607 
608 	pm->pm_refs++;
609 }
610 
611 /*
612  * Retire the given pmap from service.
613  * Should only be called if the map contains no valid mappings.
614  */
615 void
616 pmap_destroy(struct pmap *pm)
617 {
618 	int i;
619 
620 	if (--pm->pm_refs > 0) {
621 		return;
622 	}
623 	KASSERT(pm->pm_stats.resident_count == 0);
624 	KASSERT(pm->pm_stats.wired_count == 0);
625 	for (i = 0; i < STSZ; i++)
626 		if (pm->pm_ptbl[i]) {
627 			uvm_km_free(kernel_map, (vaddr_t)pm->pm_ptbl[i],
628 			    PAGE_SIZE, UVM_KMF_WIRED);
629 			pm->pm_ptbl[i] = NULL;
630 		}
631 	if (pm->pm_ctx)
632 		ctx_free(pm);
633 	free(pm, M_VMPMAP);
634 }
635 
636 /*
637  * Copy the range specified by src_addr/len
638  * from the source map to the range dst_addr/len
639  * in the destination map.
640  *
641  * This routine is only advisory and need not do anything.
642  */
643 void
644 pmap_copy(struct pmap *dst_pmap, struct pmap *src_pmap, vaddr_t dst_addr,
645 	  vsize_t len, vaddr_t src_addr)
646 {
647 }
648 
649 /*
650  * Require that all active physical maps contain no
651  * incorrect entries NOW.
652  */
653 void
654 pmap_update(struct pmap *pmap)
655 {
656 }
657 
658 /*
659  * Garbage collects the physical map system for
660  * pages which are no longer used.
661  * Success need not be guaranteed -- that is, there
662  * may well be pages which are not referenced, but
663  * others may be collected.
664  * Called by the pageout daemon when pages are scarce.
665  */
666 void
667 pmap_collect(struct pmap *pm)
668 {
669 }
670 
671 /*
672  * Fill the given physical page with zeroes.
673  */
674 void
675 pmap_zero_page(paddr_t pa)
676 {
677 
678 #ifdef PPC_4XX_NOCACHE
679 	memset((caddr_t)pa, 0, PAGE_SIZE);
680 #else
681 	int i;
682 
683 	for (i = PAGE_SIZE/CACHELINESIZE; i > 0; i--) {
684 		__asm __volatile ("dcbz 0,%0" :: "r"(pa));
685 		pa += CACHELINESIZE;
686 	}
687 #endif
688 }
689 
690 /*
691  * Copy the given physical source page to its destination.
692  */
693 void
694 pmap_copy_page(paddr_t src, paddr_t dst)
695 {
696 
697 	memcpy((caddr_t)dst, (caddr_t)src, PAGE_SIZE);
698 	dcache_flush_page(dst);
699 }
700 
701 /*
702  * This returns whether this is the first mapping of a page.
703  */
704 static inline int
705 pmap_enter_pv(struct pmap *pm, vaddr_t va, paddr_t pa, boolean_t wired)
706 {
707 	struct pv_entry *pv, *npv = NULL;
708 	int s;
709 
710 	if (!pmap_initialized)
711 		return 0;
712 
713 	s = splvm();
714 	pv = pa_to_pv(pa);
715 	if (!pv->pv_pm) {
716 		/*
717 		 * No entries yet, use header as the first entry.
718 		 */
719 		pv->pv_va = va;
720 		pv->pv_pm = pm;
721 		pv->pv_next = NULL;
722 	} else {
723 		/*
724 		 * There is at least one other VA mapping this page.
725 		 * Place this entry after the header.
726 		 */
727 		npv = pool_get(&pv_pool, PR_WAITOK);
728 		npv->pv_va = va;
729 		npv->pv_pm = pm;
730 		npv->pv_next = pv->pv_next;
731 		pv->pv_next = npv;
732 		pv = npv;
733 	}
734 	if (wired) {
735 		PV_WIRE(pv);
736 		pm->pm_stats.wired_count++;
737 	}
738 	splx(s);
739 	return (1);
740 }
741 
742 static void
743 pmap_remove_pv(struct pmap *pm, vaddr_t va, paddr_t pa)
744 {
745 	struct pv_entry *pv, *npv;
746 
747 	/*
748 	 * Remove from the PV table.
749 	 */
750 	pv = pa_to_pv(pa);
751 	if (!pv)
752 		return;
753 
754 	/*
755 	 * If it is the first entry on the list, it is actually
756 	 * in the header and we must copy the following entry up
757 	 * to the header.  Otherwise we must search the list for
758 	 * the entry.  In either case we free the now unused entry.
759 	 */
760 	if (pm == pv->pv_pm && PV_CMPVA(va, pv)) {
761 		if (PV_ISWIRED(pv)) {
762 			pm->pm_stats.wired_count--;
763 		}
764 		if ((npv = pv->pv_next)) {
765 			*pv = *npv;
766 			pool_put(&pv_pool, npv);
767 		} else
768 			pv->pv_pm = NULL;
769 	} else {
770 		for (; (npv = pv->pv_next) != NULL; pv = npv)
771 			if (pm == npv->pv_pm && PV_CMPVA(va, npv))
772 				break;
773 		if (npv) {
774 			pv->pv_next = npv->pv_next;
775 			if (PV_ISWIRED(npv)) {
776 				pm->pm_stats.wired_count--;
777 			}
778 			pool_put(&pv_pool, npv);
779 		}
780 	}
781 }
782 
783 /*
784  * Insert physical page at pa into the given pmap at virtual address va.
785  */
786 int
787 pmap_enter(struct pmap *pm, vaddr_t va, paddr_t pa, vm_prot_t prot, int flags)
788 {
789 	int s;
790 	u_int tte;
791 	int managed;
792 
793 	/*
794 	 * Have to remove any existing mapping first.
795 	 */
796 	pmap_remove(pm, va, va + PAGE_SIZE);
797 
798 	if (flags & PMAP_WIRED)
799 		flags |= prot;
800 
801 	managed = 0;
802 	if (vm_physseg_find(atop(pa), NULL) != -1)
803 		managed = 1;
804 
805 	/*
806 	 * Generate TTE.
807 	 */
808 	tte = TTE_PA(pa);
809 	/* XXXX -- need to support multiple page sizes. */
810 	tte |= TTE_SZ_16K;
811 #ifdef	DIAGNOSTIC
812 	if ((flags & (PME_NOCACHE | PME_WRITETHROUG)) ==
813 		(PME_NOCACHE | PME_WRITETHROUG))
814 		panic("pmap_enter: uncached & writethrough");
815 #endif
816 	if (flags & PME_NOCACHE)
817 		/* Must be I/O mapping */
818 		tte |= TTE_I | TTE_G;
819 #ifdef PPC_4XX_NOCACHE
820 	tte |= TTE_I;
821 #else
822 	else if (flags & PME_WRITETHROUG)
823 		/* Uncached and writethrough are not compatible */
824 		tte |= TTE_W;
825 #endif
826 	if (pm == pmap_kernel())
827 		tte |= TTE_ZONE(ZONE_PRIV);
828 	else
829 		tte |= TTE_ZONE(ZONE_USER);
830 
831 	if (flags & VM_PROT_WRITE)
832 		tte |= TTE_WR;
833 
834 	if (flags & VM_PROT_EXECUTE)
835 		tte |= TTE_EX;
836 
837 	/*
838 	 * Now record mapping for later back-translation.
839 	 */
840 	if (pmap_initialized && managed) {
841 		char *attr;
842 
843 		if (!pmap_enter_pv(pm, va, pa, flags & PMAP_WIRED)) {
844 			/* Could not enter pv on a managed page */
845 			return 1;
846 		}
847 
848 		/* Now set attributes. */
849 		attr = pa_to_attr(pa);
850 #ifdef DIAGNOSTIC
851 		if (!attr)
852 			panic("managed but no attr");
853 #endif
854 		if (flags & VM_PROT_ALL)
855 			*attr |= PMAP_ATTR_REF;
856 		if (flags & VM_PROT_WRITE)
857 			*attr |= PMAP_ATTR_CHG;
858 	}
859 
860 	s = splvm();
861 
862 	/* Insert page into page table. */
863 	pte_enter(pm, va, tte);
864 
865 	/* If this is a real fault, enter it in the tlb */
866 	if (tte && ((flags & PMAP_WIRED) == 0)) {
867 		ppc4xx_tlb_enter(pm->pm_ctx, va, tte);
868 	}
869 	splx(s);
870 
871 	/* Flush the real memory from the instruction cache. */
872 	if ((prot & VM_PROT_EXECUTE) && (tte & TTE_I) == 0)
873 		__syncicache((void *)pa, PAGE_SIZE);
874 
875 	return 0;
876 }
877 
878 void
879 pmap_unwire(struct pmap *pm, vaddr_t va)
880 {
881 	struct pv_entry *pv;
882 	paddr_t pa;
883 	int s;
884 
885 	if (!pmap_extract(pm, va, &pa)) {
886 		return;
887 	}
888 
889 	pv = pa_to_pv(pa);
890 	if (!pv)
891 		return;
892 
893 	s = splvm();
894 	while (pv != NULL) {
895 		if (pm == pv->pv_pm && PV_CMPVA(va, pv)) {
896 			if (PV_ISWIRED(pv)) {
897 				PV_UNWIRE(pv);
898 				pm->pm_stats.wired_count--;
899 			}
900 			break;
901 		}
902 		pv = pv->pv_next;
903 	}
904 	splx(s);
905 }
906 
907 void
908 pmap_kenter_pa(vaddr_t va, paddr_t pa, vm_prot_t prot)
909 {
910 	int s;
911 	u_int tte;
912 	struct pmap *pm = pmap_kernel();
913 
914 	/*
915 	 * Have to remove any existing mapping first.
916 	 */
917 
918 	/*
919 	 * Generate TTE.
920 	 *
921 	 * XXXX
922 	 *
923 	 * Since the kernel does not handle execution privileges properly,
924 	 * we will handle read and execute permissions together.
925 	 */
926 	tte = 0;
927 	if (prot & VM_PROT_ALL) {
928 
929 		tte = TTE_PA(pa) | TTE_EX | TTE_ZONE(ZONE_PRIV);
930 		/* XXXX -- need to support multiple page sizes. */
931 		tte |= TTE_SZ_16K;
932 #ifdef DIAGNOSTIC
933 		if ((prot & (PME_NOCACHE | PME_WRITETHROUG)) ==
934 			(PME_NOCACHE | PME_WRITETHROUG))
935 			panic("pmap_kenter_pa: uncached & writethrough");
936 #endif
937 		if (prot & PME_NOCACHE)
938 			/* Must be I/O mapping */
939 			tte |= TTE_I | TTE_G;
940 #ifdef PPC_4XX_NOCACHE
941 		tte |= TTE_I;
942 #else
943 		else if (prot & PME_WRITETHROUG)
944 			/* Uncached and writethrough are not compatible */
945 			tte |= TTE_W;
946 #endif
947 		if (prot & VM_PROT_WRITE)
948 			tte |= TTE_WR;
949 	}
950 
951 	s = splvm();
952 
953 	/* Insert page into page table. */
954 	pte_enter(pm, va, tte);
955 	splx(s);
956 }
957 
958 void
959 pmap_kremove(vaddr_t va, vsize_t len)
960 {
961 
962 	while (len > 0) {
963 		pte_enter(pmap_kernel(), va, 0);
964 		va += PAGE_SIZE;
965 		len -= PAGE_SIZE;
966 	}
967 }
968 
969 /*
970  * Remove the given range of mapping entries.
971  */
972 void
973 pmap_remove(struct pmap *pm, vaddr_t va, vaddr_t endva)
974 {
975 	int s;
976 	paddr_t pa;
977 	volatile u_int *ptp;
978 
979 	s = splvm();
980 	while (va < endva) {
981 
982 		if ((ptp = pte_find(pm, va)) && (pa = *ptp)) {
983 			pa = TTE_PA(pa);
984 			pmap_remove_pv(pm, va, pa);
985 			*ptp = 0;
986 			ppc4xx_tlb_flush(va, pm->pm_ctx);
987 			pm->pm_stats.resident_count--;
988 		}
989 		va += PAGE_SIZE;
990 	}
991 
992 	splx(s);
993 }
994 
995 /*
996  * Get the physical page address for the given pmap/virtual address.
997  */
998 boolean_t
999 pmap_extract(struct pmap *pm, vaddr_t va, paddr_t *pap)
1000 {
1001 	int seg = STIDX(va);
1002 	int ptn = PTIDX(va);
1003 	u_int pa = 0;
1004 	int s;
1005 
1006 	s = splvm();
1007 	if (pm->pm_ptbl[seg] && (pa = pm->pm_ptbl[seg][ptn])) {
1008 		*pap = TTE_PA(pa) | (va & PGOFSET);
1009 	}
1010 	splx(s);
1011 	return (pa != 0);
1012 }
1013 
1014 /*
1015  * Lower the protection on the specified range of this pmap.
1016  *
1017  * There are only two cases: either the protection is going to 0,
1018  * or it is going to read-only.
1019  */
1020 void
1021 pmap_protect(struct pmap *pm, vaddr_t sva, vaddr_t eva, vm_prot_t prot)
1022 {
1023 	volatile u_int *ptp;
1024 	int s, bic;
1025 
1026 	if ((prot & VM_PROT_READ) == 0) {
1027 		pmap_remove(pm, sva, eva);
1028 		return;
1029 	}
1030 	bic = 0;
1031 	if ((prot & VM_PROT_WRITE) == 0) {
1032 		bic |= TTE_WR;
1033 	}
1034 	if ((prot & VM_PROT_EXECUTE) == 0) {
1035 		bic |= TTE_EX;
1036 	}
1037 	if (bic == 0) {
1038 		return;
1039 	}
1040 	s = splvm();
1041 	while (sva < eva) {
1042 		if ((ptp = pte_find(pm, sva)) != NULL) {
1043 			*ptp &= ~bic;
1044 			ppc4xx_tlb_flush(sva, pm->pm_ctx);
1045 		}
1046 		sva += PAGE_SIZE;
1047 	}
1048 	splx(s);
1049 }
1050 
1051 boolean_t
1052 pmap_check_attr(struct vm_page *pg, u_int mask, int clear)
1053 {
1054 	paddr_t pa;
1055 	char *attr;
1056 	int s, rv;
1057 
1058 	/*
1059 	 * First modify bits in cache.
1060 	 */
1061 	pa = VM_PAGE_TO_PHYS(pg);
1062 	attr = pa_to_attr(pa);
1063 	if (attr == NULL)
1064 		return FALSE;
1065 
1066 	s = splvm();
1067 	rv = ((*attr & mask) != 0);
1068 	if (clear) {
1069 		*attr &= ~mask;
1070 		pmap_page_protect(pg, mask == PMAP_ATTR_CHG ? VM_PROT_READ : 0);
1071 	}
1072 	splx(s);
1073 	return rv;
1074 }
1075 
1076 
1077 /*
1078  * Lower the protection on the specified physical page.
1079  *
1080  * There are only two cases: either the protection is going to 0,
1081  * or it is going to read-only.
1082  */
1083 void
1084 pmap_page_protect(struct vm_page *pg, vm_prot_t prot)
1085 {
1086 	paddr_t pa = VM_PAGE_TO_PHYS(pg);
1087 	vaddr_t va;
1088 	struct pv_entry *pvh, *pv, *npv;
1089 	struct pmap *pm;
1090 
1091 	pvh = pa_to_pv(pa);
1092 	if (pvh == NULL)
1093 		return;
1094 
1095 	/* Handle extra pvs which may be deleted in the operation */
1096 	for (pv = pvh->pv_next; pv; pv = npv) {
1097 		npv = pv->pv_next;
1098 
1099 		pm = pv->pv_pm;
1100 		va = pv->pv_va;
1101 		pmap_protect(pm, va, va + PAGE_SIZE, prot);
1102 	}
1103 	/* Now check the head pv */
1104 	if (pvh->pv_pm) {
1105 		pv = pvh;
1106 		pm = pv->pv_pm;
1107 		va = pv->pv_va;
1108 		pmap_protect(pm, va, va + PAGE_SIZE, prot);
1109 	}
1110 }
1111 
1112 /*
1113  * Activate the address space for the specified process.  If the process
1114  * is the current process, load the new MMU context.
1115  */
1116 void
1117 pmap_activate(struct lwp *l)
1118 {
1119 #if 0
1120 	struct pcb *pcb = &l->l_proc->p_addr->u_pcb;
1121 	pmap_t pmap = l->l_proc->p_vmspace->vm_map.pmap;
1122 
1123 	/*
1124 	 * XXX Normally performed in cpu_fork().
1125 	 */
1126 	printf("pmap_activate(%p), pmap=%p\n",l,pmap);
1127 	pcb->pcb_pm = pmap;
1128 #endif
1129 }
1130 
1131 /*
1132  * Deactivate the specified process's address space.
1133  */
1134 void
1135 pmap_deactivate(struct lwp *l)
1136 {
1137 }
1138 
1139 /*
1140  * Synchronize caches corresponding to [addr, addr+len) in p.
1141  */
1142 void
1143 pmap_procwr(struct proc *p, vaddr_t va, size_t len)
1144 {
1145 	struct pmap *pm = p->p_vmspace->vm_map.pmap;
1146 	int msr, ctx, opid, step;
1147 
1148 	step = CACHELINESIZE;
1149 
1150 	/*
1151 	 * Need to turn off IMMU and switch to user context.
1152 	 * (icbi uses DMMU).
1153 	 */
1154 	if (!(ctx = pm->pm_ctx)) {
1155 		/* No context -- assign it one */
1156 		ctx_alloc(pm);
1157 		ctx = pm->pm_ctx;
1158 	}
1159 	__asm __volatile("mfmsr %0;"
1160 		"li %1, %7;"
1161 		"andc %1,%0,%1;"
1162 		"mtmsr %1;"
1163 		"sync;isync;"
1164 		"mfpid %1;"
1165 		"mtpid %2;"
1166 		"sync; isync;"
1167 		"1:"
1168 		"dcbf 0,%3;"
1169 		"icbi 0,%3;"
1170 		"add %3,%3,%5;"
1171 		"addc. %4,%4,%6;"
1172 		"bge 1b;"
1173 		"mtpid %1;"
1174 		"mtmsr %0;"
1175 		"sync; isync"
1176 		: "=&r" (msr), "=&r" (opid)
1177 		: "r" (ctx), "r" (va), "r" (len), "r" (step), "r" (-step),
1178 		  "K" (PSL_IR | PSL_DR));
1179 }
1180 
1181 
1182 /* This has to be done in real mode !!! */
1183 void
1184 ppc4xx_tlb_flush(vaddr_t va, int pid)
1185 {
1186 	u_long i, found;
1187 	u_long msr;
1188 
1189 	/* If there's no context then it can't be mapped. */
1190 	if (!pid)
1191 		return;
1192 
1193 	asm("mfpid %1;"			/* Save PID */
1194 		"mfmsr %2;"		/* Save MSR */
1195 		"li %0,0;"		/* Now clear MSR */
1196 		"mtmsr %0;"
1197 		"mtpid %4;"		/* Set PID */
1198 		"sync;"
1199 		"tlbsx. %0,0,%3;"	/* Search TLB */
1200 		"sync;"
1201 		"mtpid %1;"		/* Restore PID */
1202 		"mtmsr %2;"		/* Restore MSR */
1203 		"sync;isync;"
1204 		"li %1,1;"
1205 		"beq 1f;"
1206 		"li %1,0;"
1207 		"1:"
1208 		: "=&r" (i), "=&r" (found), "=&r" (msr)
1209 		: "r" (va), "r" (pid));
1210 	if (found && !TLB_LOCKED(i)) {
1211 
1212 		/* Now flush translation */
1213 		asm volatile(
1214 			"tlbwe %0,%1,0;"
1215 			"sync;isync;"
1216 			: : "r" (0), "r" (i));
1217 
1218 		tlb_info[i].ti_ctx = 0;
1219 		tlb_info[i].ti_flags = 0;
1220 		tlbnext = i;
1221 		/* Successful flushes */
1222 		tlbflush_ev.ev_count++;
1223 	}
1224 }
1225 
1226 void
1227 ppc4xx_tlb_flush_all(void)
1228 {
1229 	u_long i;
1230 
1231 	for (i = 0; i < NTLB; i++)
1232 		if (!TLB_LOCKED(i)) {
1233 			asm volatile(
1234 				"tlbwe %0,%1,0;"
1235 				"sync;isync;"
1236 				: : "r" (0), "r" (i));
1237 			tlb_info[i].ti_ctx = 0;
1238 			tlb_info[i].ti_flags = 0;
1239 		}
1240 
1241 	asm volatile("sync;isync");
1242 }
1243 
1244 /* Find a TLB entry to evict. */
1245 static int
1246 ppc4xx_tlb_find_victim(void)
1247 {
1248 	int flags;
1249 
1250 	for (;;) {
1251 		if (++tlbnext >= NTLB)
1252 			tlbnext = TLB_NRESERVED;
1253 		flags = tlb_info[tlbnext].ti_flags;
1254 		if (!(flags & TLBF_USED) ||
1255 			(flags & (TLBF_LOCKED | TLBF_REF)) == 0) {
1256 			u_long va, stack = (u_long)&va;
1257 
1258 			if (!((tlb_info[tlbnext].ti_va ^ stack) & (~PGOFSET)) &&
1259 			    (tlb_info[tlbnext].ti_ctx == KERNEL_PID) &&
1260 			     (flags & TLBF_USED)) {
1261 				/* Kernel stack page */
1262 				flags |= TLBF_USED;
1263 				tlb_info[tlbnext].ti_flags = flags;
1264 			} else {
1265 				/* Found it! */
1266 				return (tlbnext);
1267 			}
1268 		} else {
1269 			tlb_info[tlbnext].ti_flags = (flags & ~TLBF_REF);
1270 		}
1271 	}
1272 }
1273 
1274 void
1275 ppc4xx_tlb_enter(int ctx, vaddr_t va, u_int pte)
1276 {
1277 	u_long th, tl, idx;
1278 	tlbpid_t pid;
1279 	u_short msr;
1280 	paddr_t pa;
1281 	int s, sz;
1282 
1283 	tlbenter_ev.ev_count++;
1284 
1285 	sz = (pte & TTE_SZ_MASK) >> TTE_SZ_SHIFT;
1286 	pa = (pte & TTE_RPN_MASK(sz));
1287 	th = (va & TLB_EPN_MASK) | (sz << TLB_SIZE_SHFT) | TLB_VALID;
1288 	tl = (pte & ~TLB_RPN_MASK) | pa;
1289 	tl |= ppc4xx_tlbflags(va, pa);
1290 
1291 	s = splhigh();
1292 	idx = ppc4xx_tlb_find_victim();
1293 
1294 #ifdef DIAGNOSTIC
1295 	if ((idx < TLB_NRESERVED) || (idx >= NTLB)) {
1296 		panic("ppc4xx_tlb_enter: replacing entry %ld", idx);
1297 	}
1298 #endif
1299 
1300 	tlb_info[idx].ti_va = (va & TLB_EPN_MASK);
1301 	tlb_info[idx].ti_ctx = ctx;
1302 	tlb_info[idx].ti_flags = TLBF_USED | TLBF_REF;
1303 
1304 	asm volatile(
1305 		"mfmsr %0;"			/* Save MSR */
1306 		"li %1,0;"
1307 		"tlbwe %1,%3,0;"		/* Invalidate old entry. */
1308 		"mtmsr %1;"			/* Clear MSR */
1309 		"mfpid %1;"			/* Save old PID */
1310 		"mtpid %2;"			/* Load translation ctx */
1311 		"sync; isync;"
1312 #ifdef DEBUG
1313 		"andi. %3,%3,63;"
1314 		"tweqi %3,0;" 			/* XXXXX DEBUG trap on index 0 */
1315 #endif
1316 		"tlbwe %4,%3,1; tlbwe %5,%3,0;"	/* Set TLB */
1317 		"sync; isync;"
1318 		"mtpid %1; mtmsr %0;"		/* Restore PID and MSR */
1319 		"sync; isync;"
1320 	: "=&r" (msr), "=&r" (pid)
1321 	: "r" (ctx), "r" (idx), "r" (tl), "r" (th));
1322 	splx(s);
1323 }
1324 
1325 void
1326 ppc4xx_tlb_unpin(int i)
1327 {
1328 
1329 	if (i == -1)
1330 		for (i = 0; i < TLB_NRESERVED; i++)
1331 			tlb_info[i].ti_flags &= ~TLBF_LOCKED;
1332 	else
1333 		tlb_info[i].ti_flags &= ~TLBF_LOCKED;
1334 }
1335 
1336 void
1337 ppc4xx_tlb_init(void)
1338 {
1339 	int i;
1340 
1341 	/* Mark reserved TLB entries */
1342 	for (i = 0; i < TLB_NRESERVED; i++) {
1343 		tlb_info[i].ti_flags = TLBF_LOCKED | TLBF_USED;
1344 		tlb_info[i].ti_ctx = KERNEL_PID;
1345 	}
1346 
1347 	/* Setup security zones */
1348 	/* Z0 - accessible by kernel only if TLB entry permissions allow
1349 	 * Z1,Z2 - access is controlled by TLB entry permissions
1350 	 * Z3 - full access regardless of TLB entry permissions
1351 	 */
1352 
1353 	asm volatile(
1354 		"mtspr %0,%1;"
1355 		"sync;"
1356 		::  "K"(SPR_ZPR), "r" (0x1b000000));
1357 }
1358 
1359 
1360 /*
1361  * We should pass the ctx in from trap code.
1362  */
1363 int
1364 pmap_tlbmiss(vaddr_t va, int ctx)
1365 {
1366 	volatile u_int *pte;
1367 	u_long tte;
1368 
1369 	tlbmiss_ev.ev_count++;
1370 
1371 	/*
1372 	 * XXXX We will reserve 0-0x80000000 for va==pa mappings.
1373 	 */
1374 	if (ctx != KERNEL_PID || (va & 0x80000000)) {
1375 		pte = pte_find((struct pmap *)__UNVOLATILE(ctxbusy[ctx]), va);
1376 		if (pte == NULL) {
1377 			/* Map unmanaged addresses directly for kernel access */
1378 			return 1;
1379 		}
1380 		tte = *pte;
1381 		if (tte == 0) {
1382 			return 1;
1383 		}
1384 	} else {
1385 		/* Create a 16MB writable mapping. */
1386 #ifdef PPC_4XX_NOCACHE
1387 		tte = TTE_PA(va) | TTE_ZONE(ZONE_PRIV) | TTE_SZ_16M | TTE_I | TTE_WR;
1388 #else
1389 		tte = TTE_PA(va) | TTE_ZONE(ZONE_PRIV) | TTE_SZ_16M | TTE_WR;
1390 #endif
1391 	}
1392 	tlbhit_ev.ev_count++;
1393 	ppc4xx_tlb_enter(ctx, va, tte);
1394 
1395 	return 0;
1396 }
1397 
1398 /*
1399  * Flush all the entries matching a context from the TLB.
1400  */
1401 static int
1402 ctx_flush(int cnum)
1403 {
1404 	int i;
1405 
1406 	/* We gotta steal this context */
1407 	for (i = TLB_NRESERVED; i < NTLB; i++) {
1408 		if (tlb_info[i].ti_ctx == cnum) {
1409 			/* Can't steal ctx if it has a locked entry. */
1410 			if (TLB_LOCKED(i)) {
1411 #ifdef DIAGNOSTIC
1412 				printf("ctx_flush: can't invalidate "
1413 					"locked mapping %d "
1414 					"for context %d\n", i, cnum);
1415 #ifdef DDB
1416 				Debugger();
1417 #endif
1418 #endif
1419 				return (1);
1420 			}
1421 #ifdef DIAGNOSTIC
1422 			if (i < TLB_NRESERVED)
1423 				panic("TLB entry %d not locked", i);
1424 #endif
1425 			/* Invalidate particular TLB entry regardless of locked status */
1426 			asm volatile("tlbwe %0,%1,0" : :"r"(0),"r"(i));
1427 			tlb_info[i].ti_flags = 0;
1428 		}
1429 	}
1430 	return (0);
1431 }
1432 
1433 /*
1434  * Allocate a context.  If necessary, steal one from someone else.
1435  *
1436  * The new context is flushed from the TLB before returning.
1437  */
1438 int
1439 ctx_alloc(struct pmap *pm)
1440 {
1441 	int s, cnum;
1442 	static int next = MINCTX;
1443 
1444 	if (pm == pmap_kernel()) {
1445 #ifdef DIAGNOSTIC
1446 		printf("ctx_alloc: kernel pmap!\n");
1447 #endif
1448 		return (0);
1449 	}
1450 	s = splvm();
1451 
1452 	/* Find a likely context. */
1453 	cnum = next;
1454 	do {
1455 		if ((++cnum) > NUMCTX)
1456 			cnum = MINCTX;
1457 	} while (ctxbusy[cnum] != NULL && cnum != next);
1458 
1459 	/* Now clean it out */
1460 oops:
1461 	if (cnum < MINCTX)
1462 		cnum = MINCTX; /* Never steal ctx 0 or 1 */
1463 	if (ctx_flush(cnum)) {
1464 		/* oops -- something's wired. */
1465 		if ((++cnum) > NUMCTX)
1466 			cnum = MINCTX;
1467 		goto oops;
1468 	}
1469 
1470 	if (ctxbusy[cnum]) {
1471 #ifdef DEBUG
1472 		/* We should identify this pmap and clear it */
1473 		printf("Warning: stealing context %d\n", cnum);
1474 #endif
1475 		ctxbusy[cnum]->pm_ctx = 0;
1476 	}
1477 	ctxbusy[cnum] = pm;
1478 	next = cnum;
1479 	splx(s);
1480 	pm->pm_ctx = cnum;
1481 
1482 	return cnum;
1483 }
1484 
1485 /*
1486  * Give away a context.
1487  */
1488 void
1489 ctx_free(struct pmap *pm)
1490 {
1491 	int oldctx;
1492 
1493 	oldctx = pm->pm_ctx;
1494 
1495 	if (oldctx == 0)
1496 		panic("ctx_free: freeing kernel context");
1497 #ifdef DIAGNOSTIC
1498 	if (ctxbusy[oldctx] == 0)
1499 		printf("ctx_free: freeing free context %d\n", oldctx);
1500 	if (ctxbusy[oldctx] != pm) {
1501 		printf("ctx_free: freeing someone esle's context\n "
1502 		       "ctxbusy[%d] = %p, pm->pm_ctx = %p\n",
1503 		       oldctx, (void *)(u_long)ctxbusy[oldctx], pm);
1504 #ifdef DDB
1505 		Debugger();
1506 #endif
1507 	}
1508 #endif
1509 	/* We should verify it has not been stolen and reallocated... */
1510 	ctxbusy[oldctx] = NULL;
1511 	ctx_flush(oldctx);
1512 }
1513 
1514 
1515 #ifdef DEBUG
1516 /*
1517  * Test ref/modify handling.
1518  */
1519 void pmap_testout __P((void));
1520 void
1521 pmap_testout()
1522 {
1523 	vaddr_t va;
1524 	volatile int *loc;
1525 	int val = 0;
1526 	paddr_t pa;
1527 	struct vm_page *pg;
1528 	int ref, mod;
1529 
1530 	/* Allocate a page */
1531 	va = (vaddr_t)uvm_km_alloc(kernel_map, PAGE_SIZE, 0,
1532 	    UVM_KMF_WIRED | UVM_KMF_ZERO);
1533 	loc = (int*)va;
1534 
1535 	pmap_extract(pmap_kernel(), va, &pa);
1536 	pg = PHYS_TO_VM_PAGE(pa);
1537 	pmap_unwire(pmap_kernel(), va);
1538 
1539 	pmap_kremove(va, PAGE_SIZE);
1540 	pmap_enter(pmap_kernel(), va, pa, VM_PROT_ALL, 0);
1541 	pmap_update(pmap_kernel());
1542 
1543 	/* Now clear reference and modify */
1544 	ref = pmap_clear_reference(pg);
1545 	mod = pmap_clear_modify(pg);
1546 	printf("Clearing page va %p pa %lx: ref %d, mod %d\n",
1547 	       (void *)(u_long)va, (long)pa,
1548 	       ref, mod);
1549 
1550 	/* Check it's properly cleared */
1551 	ref = pmap_is_referenced(pg);
1552 	mod = pmap_is_modified(pg);
1553 	printf("Checking cleared page: ref %d, mod %d\n",
1554 	       ref, mod);
1555 
1556 	/* Reference page */
1557 	val = *loc;
1558 
1559 	ref = pmap_is_referenced(pg);
1560 	mod = pmap_is_modified(pg);
1561 	printf("Referenced page: ref %d, mod %d val %x\n",
1562 	       ref, mod, val);
1563 
1564 	/* Now clear reference and modify */
1565 	ref = pmap_clear_reference(pg);
1566 	mod = pmap_clear_modify(pg);
1567 	printf("Clearing page va %p pa %lx: ref %d, mod %d\n",
1568 	       (void *)(u_long)va, (long)pa,
1569 	       ref, mod);
1570 
1571 	/* Modify page */
1572 	*loc = 1;
1573 
1574 	ref = pmap_is_referenced(pg);
1575 	mod = pmap_is_modified(pg);
1576 	printf("Modified page: ref %d, mod %d\n",
1577 	       ref, mod);
1578 
1579 	/* Now clear reference and modify */
1580 	ref = pmap_clear_reference(pg);
1581 	mod = pmap_clear_modify(pg);
1582 	printf("Clearing page va %p pa %lx: ref %d, mod %d\n",
1583 	       (void *)(u_long)va, (long)pa,
1584 	       ref, mod);
1585 
1586 	/* Check it's properly cleared */
1587 	ref = pmap_is_referenced(pg);
1588 	mod = pmap_is_modified(pg);
1589 	printf("Checking cleared page: ref %d, mod %d\n",
1590 	       ref, mod);
1591 
1592 	/* Modify page */
1593 	*loc = 1;
1594 
1595 	ref = pmap_is_referenced(pg);
1596 	mod = pmap_is_modified(pg);
1597 	printf("Modified page: ref %d, mod %d\n",
1598 	       ref, mod);
1599 
1600 	/* Check pmap_protect() */
1601 	pmap_protect(pmap_kernel(), va, va+1, VM_PROT_READ);
1602 	pmap_update(pmap_kernel());
1603 	ref = pmap_is_referenced(pg);
1604 	mod = pmap_is_modified(pg);
1605 	printf("pmap_protect(VM_PROT_READ): ref %d, mod %d\n",
1606 	       ref, mod);
1607 
1608 	/* Now clear reference and modify */
1609 	ref = pmap_clear_reference(pg);
1610 	mod = pmap_clear_modify(pg);
1611 	printf("Clearing page va %p pa %lx: ref %d, mod %d\n",
1612 	       (void *)(u_long)va, (long)pa,
1613 	       ref, mod);
1614 
1615 	/* Reference page */
1616 	val = *loc;
1617 
1618 	ref = pmap_is_referenced(pg);
1619 	mod = pmap_is_modified(pg);
1620 	printf("Referenced page: ref %d, mod %d val %x\n",
1621 	       ref, mod, val);
1622 
1623 	/* Now clear reference and modify */
1624 	ref = pmap_clear_reference(pg);
1625 	mod = pmap_clear_modify(pg);
1626 	printf("Clearing page va %p pa %lx: ref %d, mod %d\n",
1627 	       (void *)(u_long)va, (long)pa,
1628 	       ref, mod);
1629 
1630 	/* Modify page */
1631 #if 0
1632 	pmap_enter(pmap_kernel(), va, pa, VM_PROT_ALL, 0);
1633 	pmap_update(pmap_kernel());
1634 #endif
1635 	*loc = 1;
1636 
1637 	ref = pmap_is_referenced(pg);
1638 	mod = pmap_is_modified(pg);
1639 	printf("Modified page: ref %d, mod %d\n",
1640 	       ref, mod);
1641 
1642 	/* Check pmap_protect() */
1643 	pmap_protect(pmap_kernel(), va, va+1, VM_PROT_NONE);
1644 	pmap_update(pmap_kernel());
1645 	ref = pmap_is_referenced(pg);
1646 	mod = pmap_is_modified(pg);
1647 	printf("pmap_protect(): ref %d, mod %d\n",
1648 	       ref, mod);
1649 
1650 	/* Now clear reference and modify */
1651 	ref = pmap_clear_reference(pg);
1652 	mod = pmap_clear_modify(pg);
1653 	printf("Clearing page va %p pa %lx: ref %d, mod %d\n",
1654 	       (void *)(u_long)va, (long)pa,
1655 	       ref, mod);
1656 
1657 	/* Reference page */
1658 	val = *loc;
1659 
1660 	ref = pmap_is_referenced(pg);
1661 	mod = pmap_is_modified(pg);
1662 	printf("Referenced page: ref %d, mod %d val %x\n",
1663 	       ref, mod, val);
1664 
1665 	/* Now clear reference and modify */
1666 	ref = pmap_clear_reference(pg);
1667 	mod = pmap_clear_modify(pg);
1668 	printf("Clearing page va %p pa %lx: ref %d, mod %d\n",
1669 	       (void *)(u_long)va, (long)pa,
1670 	       ref, mod);
1671 
1672 	/* Modify page */
1673 #if 0
1674 	pmap_enter(pmap_kernel(), va, pa, VM_PROT_ALL, 0);
1675 	pmap_update(pmap_kernel());
1676 #endif
1677 	*loc = 1;
1678 
1679 	ref = pmap_is_referenced(pg);
1680 	mod = pmap_is_modified(pg);
1681 	printf("Modified page: ref %d, mod %d\n",
1682 	       ref, mod);
1683 
1684 	/* Check pmap_pag_protect() */
1685 	pmap_page_protect(pg, VM_PROT_READ);
1686 	ref = pmap_is_referenced(pg);
1687 	mod = pmap_is_modified(pg);
1688 	printf("pmap_page_protect(VM_PROT_READ): ref %d, mod %d\n",
1689 	       ref, mod);
1690 
1691 	/* Now clear reference and modify */
1692 	ref = pmap_clear_reference(pg);
1693 	mod = pmap_clear_modify(pg);
1694 	printf("Clearing page va %p pa %lx: ref %d, mod %d\n",
1695 	       (void *)(u_long)va, (long)pa,
1696 	       ref, mod);
1697 
1698 	/* Reference page */
1699 	val = *loc;
1700 
1701 	ref = pmap_is_referenced(pg);
1702 	mod = pmap_is_modified(pg);
1703 	printf("Referenced page: ref %d, mod %d val %x\n",
1704 	       ref, mod, val);
1705 
1706 	/* Now clear reference and modify */
1707 	ref = pmap_clear_reference(pg);
1708 	mod = pmap_clear_modify(pg);
1709 	printf("Clearing page va %p pa %lx: ref %d, mod %d\n",
1710 	       (void *)(u_long)va, (long)pa,
1711 	       ref, mod);
1712 
1713 	/* Modify page */
1714 #if 0
1715 	pmap_enter(pmap_kernel(), va, pa, VM_PROT_ALL, 0);
1716 	pmap_update(pmap_kernel());
1717 #endif
1718 	*loc = 1;
1719 
1720 	ref = pmap_is_referenced(pg);
1721 	mod = pmap_is_modified(pg);
1722 	printf("Modified page: ref %d, mod %d\n",
1723 	       ref, mod);
1724 
1725 	/* Check pmap_pag_protect() */
1726 	pmap_page_protect(pg, VM_PROT_NONE);
1727 	ref = pmap_is_referenced(pg);
1728 	mod = pmap_is_modified(pg);
1729 	printf("pmap_page_protect(): ref %d, mod %d\n",
1730 	       ref, mod);
1731 
1732 	/* Now clear reference and modify */
1733 	ref = pmap_clear_reference(pg);
1734 	mod = pmap_clear_modify(pg);
1735 	printf("Clearing page va %p pa %lx: ref %d, mod %d\n",
1736 	       (void *)(u_long)va, (long)pa,
1737 	       ref, mod);
1738 
1739 
1740 	/* Reference page */
1741 	val = *loc;
1742 
1743 	ref = pmap_is_referenced(pg);
1744 	mod = pmap_is_modified(pg);
1745 	printf("Referenced page: ref %d, mod %d val %x\n",
1746 	       ref, mod, val);
1747 
1748 	/* Now clear reference and modify */
1749 	ref = pmap_clear_reference(pg);
1750 	mod = pmap_clear_modify(pg);
1751 	printf("Clearing page va %p pa %lx: ref %d, mod %d\n",
1752 	       (void *)(u_long)va, (long)pa,
1753 	       ref, mod);
1754 
1755 	/* Modify page */
1756 #if 0
1757 	pmap_enter(pmap_kernel(), va, pa, VM_PROT_ALL, 0);
1758 	pmap_update(pmap_kernel());
1759 #endif
1760 	*loc = 1;
1761 
1762 	ref = pmap_is_referenced(pg);
1763 	mod = pmap_is_modified(pg);
1764 	printf("Modified page: ref %d, mod %d\n",
1765 	       ref, mod);
1766 
1767 	/* Unmap page */
1768 	pmap_remove(pmap_kernel(), va, va+1);
1769 	pmap_update(pmap_kernel());
1770 	ref = pmap_is_referenced(pg);
1771 	mod = pmap_is_modified(pg);
1772 	printf("Unmapped page: ref %d, mod %d\n", ref, mod);
1773 
1774 	/* Now clear reference and modify */
1775 	ref = pmap_clear_reference(pg);
1776 	mod = pmap_clear_modify(pg);
1777 	printf("Clearing page va %p pa %lx: ref %d, mod %d\n",
1778 	       (void *)(u_long)va, (long)pa, ref, mod);
1779 
1780 	/* Check it's properly cleared */
1781 	ref = pmap_is_referenced(pg);
1782 	mod = pmap_is_modified(pg);
1783 	printf("Checking cleared page: ref %d, mod %d\n",
1784 	       ref, mod);
1785 
1786 	pmap_remove(pmap_kernel(), va, va + PAGE_SIZE);
1787 	pmap_kenter_pa(va, pa, VM_PROT_ALL);
1788 	uvm_km_free(kernel_map, (vaddr_t)va, PAGE_SIZE, UVM_KMF_WIRED);
1789 }
1790 #endif
1791