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