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