xref: /freebsd/sys/powerpc/booke/pmap.c (revision d8f9d3388f5dfed0b426d11a1b985397c12010e8)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (C) 2007-2009 Semihalf, Rafal Jaworowski <raj@semihalf.com>
5  * Copyright (C) 2006 Semihalf, Marian Balakowicz <m8@semihalf.com>
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN
20  * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
22  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
23  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
24  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
25  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  *
28  * Some hw specific parts of this pmap were derived or influenced
29  * by NetBSD's ibm4xx pmap module. More generic code is shared with
30  * a few other pmap modules from the FreeBSD tree.
31  */
32 
33  /*
34   * VM layout notes:
35   *
36   * Kernel and user threads run within one common virtual address space
37   * defined by AS=0.
38   *
39   * 32-bit pmap:
40   * Virtual address space layout:
41   * -----------------------------
42   * 0x0000_0000 - 0x7fff_ffff	: user process
43   * 0x8000_0000 - 0xbfff_ffff	: pmap_mapdev()-ed area (PCI/PCIE etc.)
44   * 0xc000_0000 - 0xc0ff_ffff	: kernel reserved
45   *   0xc000_0000 - data_end	: kernel code+data, env, metadata etc.
46   * 0xc100_0000 - 0xffff_ffff	: KVA
47   *   0xc100_0000 - 0xc100_3fff : reserved for page zero/copy
48   *   0xc100_4000 - 0xc200_3fff : reserved for ptbl bufs
49   *   0xc200_4000 - 0xc200_8fff : guard page + kstack0
50   *   0xc200_9000 - 0xfeef_ffff	: actual free KVA space
51   *
52   * 64-bit pmap:
53   * Virtual address space layout:
54   * -----------------------------
55   * 0x0000_0000_0000_0000 - 0xbfff_ffff_ffff_ffff      : user process
56   *   0x0000_0000_0000_0000 - 0x8fff_ffff_ffff_ffff    : text, data, heap, maps, libraries
57   *   0x9000_0000_0000_0000 - 0xafff_ffff_ffff_ffff    : mmio region
58   *   0xb000_0000_0000_0000 - 0xbfff_ffff_ffff_ffff    : stack
59   * 0xc000_0000_0000_0000 - 0xcfff_ffff_ffff_ffff      : kernel reserved
60   *   0xc000_0000_0000_0000 - endkernel-1              : kernel code & data
61   *               endkernel - msgbufp-1                : flat device tree
62   *                 msgbufp - kernel_pdir-1            : message buffer
63   *             kernel_pdir - kernel_pp2d-1            : kernel page directory
64   *             kernel_pp2d - .                        : kernel pointers to page directory
65   *      pmap_zero_copy_min - crashdumpmap-1           : reserved for page zero/copy
66   *            crashdumpmap - ptbl_buf_pool_vabase-1   : reserved for ptbl bufs
67   *    ptbl_buf_pool_vabase - virtual_avail-1          : user page directories and page tables
68   *           virtual_avail - 0xcfff_ffff_ffff_ffff    : actual free KVA space
69   * 0xd000_0000_0000_0000 - 0xdfff_ffff_ffff_ffff      : coprocessor region
70   * 0xe000_0000_0000_0000 - 0xefff_ffff_ffff_ffff      : mmio region
71   * 0xf000_0000_0000_0000 - 0xffff_ffff_ffff_ffff      : direct map
72   *   0xf000_0000_0000_0000 - +Maxmem                  : physmem map
73   *                         - 0xffff_ffff_ffff_ffff    : device direct map
74   */
75 
76 #include <sys/cdefs.h>
77 #include "opt_ddb.h"
78 #include "opt_kstack_pages.h"
79 
80 #include <sys/param.h>
81 #include <sys/conf.h>
82 #include <sys/malloc.h>
83 #include <sys/ktr.h>
84 #include <sys/proc.h>
85 #include <sys/user.h>
86 #include <sys/queue.h>
87 #include <sys/systm.h>
88 #include <sys/kernel.h>
89 #include <sys/kerneldump.h>
90 #include <sys/limits.h>
91 #include <sys/linker.h>
92 #include <sys/msgbuf.h>
93 #include <sys/lock.h>
94 #include <sys/mutex.h>
95 #include <sys/rwlock.h>
96 #include <sys/sched.h>
97 #include <sys/smp.h>
98 #include <sys/vmmeter.h>
99 
100 #include <vm/vm.h>
101 #include <vm/vm_param.h>
102 #include <vm/vm_page.h>
103 #include <vm/vm_kern.h>
104 #include <vm/vm_pageout.h>
105 #include <vm/vm_extern.h>
106 #include <vm/vm_object.h>
107 #include <vm/vm_map.h>
108 #include <vm/vm_pager.h>
109 #include <vm/vm_phys.h>
110 #include <vm/vm_pagequeue.h>
111 #include <vm/vm_radix.h>
112 #include <vm/vm_dumpset.h>
113 #include <vm/uma.h>
114 
115 #include <machine/_inttypes.h>
116 #include <machine/cpu.h>
117 #include <machine/pcb.h>
118 #include <machine/platform.h>
119 
120 #include <machine/tlb.h>
121 #include <machine/spr.h>
122 #include <machine/md_var.h>
123 #include <machine/mmuvar.h>
124 #include <machine/pmap.h>
125 #include <machine/pte.h>
126 
127 #include <ddb/ddb.h>
128 
129 #define	SPARSE_MAPDEV
130 
131 /* Use power-of-two mappings in mmu_booke_mapdev(), to save entries. */
132 #define	POW2_MAPPINGS
133 
134 #ifdef  DEBUG
135 #define debugf(fmt, args...) printf(fmt, ##args)
136 #define	__debug_used
137 #else
138 #define debugf(fmt, args...)
139 #define	__debug_used	__unused
140 #endif
141 
142 #ifdef __powerpc64__
143 #define	PRI0ptrX	"016lx"
144 #else
145 #define	PRI0ptrX	"08x"
146 #endif
147 
148 #define TODO			panic("%s: not implemented", __func__);
149 
150 extern unsigned char _etext[];
151 extern unsigned char _end[];
152 
153 extern uint32_t *bootinfo;
154 
155 vm_paddr_t kernload;
156 vm_offset_t kernstart;
157 vm_size_t kernsize;
158 
159 /* Message buffer and tables. */
160 static vm_offset_t data_start;
161 static vm_size_t data_end;
162 
163 /* Phys/avail memory regions. */
164 static struct mem_region *availmem_regions;
165 static int availmem_regions_sz;
166 static struct mem_region *physmem_regions;
167 static int physmem_regions_sz;
168 
169 #ifndef __powerpc64__
170 /* Reserved KVA space and mutex for mmu_booke_zero_page. */
171 static vm_offset_t zero_page_va;
172 static struct mtx zero_page_mutex;
173 
174 /* Reserved KVA space and mutex for mmu_booke_copy_page. */
175 static vm_offset_t copy_page_src_va;
176 static vm_offset_t copy_page_dst_va;
177 static struct mtx copy_page_mutex;
178 #endif
179 
180 static struct mtx tlbivax_mutex;
181 static bool mmuv2;
182 
183 /**************************************************************************/
184 /* PMAP */
185 /**************************************************************************/
186 
187 static int mmu_booke_enter_locked(pmap_t, vm_offset_t, vm_page_t,
188     vm_prot_t, u_int flags, int8_t psind);
189 
190 unsigned int kptbl_min;		/* Index of the first kernel ptbl. */
191 static uma_zone_t ptbl_root_zone;
192 
193 /*
194  * If user pmap is processed with mmu_booke_remove and the resident count
195  * drops to 0, there are no more pages to remove, so we need not continue.
196  */
197 #define PMAP_REMOVE_DONE(pmap) \
198 	((pmap) != kernel_pmap && (pmap)->pm_stats.resident_count == 0)
199 
200 #if defined(COMPAT_FREEBSD32) || !defined(__powerpc64__)
201 extern int elf32_nxstack;
202 #endif
203 
204 /**************************************************************************/
205 /* TLB and TID handling */
206 /**************************************************************************/
207 
208 /* Translation ID busy table (dynamically allocated) */
209 static __inline void tid_set_busy(int cpu, int tid, pmap_t pmap);
210 static __inline pmap_t tid_get_busy(int cpu, int tid);
211 static volatile pmap_t *tidbusy;
212 uint32_t tid_max;
213 
214 /*
215  * TLB0 capabilities (entry, way numbers etc.). These can vary between e500
216  * core revisions and should be read from h/w registers during early config.
217  */
218 uint32_t tlb0_entries;
219 uint32_t tlb0_ways;
220 uint32_t tlb0_entries_per_way;
221 uint32_t tlb1_entries;
222 
223 #define TLB0_ENTRIES		(tlb0_entries)
224 #define TLB0_WAYS		(tlb0_ways)
225 #define TLB0_ENTRIES_PER_WAY	(tlb0_entries_per_way)
226 
227 #define TLB1_ENTRIES (tlb1_entries)
228 
229 static tlbtid_t tid_alloc(struct pmap *);
230 
231 #ifdef DDB
232 #ifdef __powerpc64__
233 static void tlb_print_entry(int, uint32_t, uint64_t, uint32_t, uint32_t);
234 #else
235 static void tlb_print_entry(int, uint32_t, uint32_t, uint32_t, uint32_t);
236 #endif
237 #endif
238 
239 static void tlb1_read_entry(tlb_entry_t *, unsigned int);
240 static void tlb1_write_entry(tlb_entry_t *, unsigned int);
241 static int tlb1_iomapped(int, vm_paddr_t, vm_size_t, vm_offset_t *);
242 static vm_size_t tlb1_mapin_region(vm_offset_t, vm_paddr_t, vm_size_t, int);
243 
244 static __inline uint32_t tlb_calc_wimg(vm_paddr_t pa, vm_memattr_t ma);
245 
246 static vm_size_t tsize2size(unsigned int);
247 static unsigned int size2tsize(vm_size_t);
248 
249 static void set_mas4_defaults(void);
250 
251 static inline void tlb0_flush_entry(vm_offset_t);
252 static inline unsigned int tlb0_tableidx(vm_offset_t, unsigned int);
253 
254 /**************************************************************************/
255 /* Page table management */
256 /**************************************************************************/
257 
258 static struct rwlock_padalign pvh_global_lock;
259 
260 /* Data for the pv entry allocation mechanism */
261 static uma_zone_t pvzone;
262 static int pv_entry_count = 0, pv_entry_max = 0, pv_entry_high_water = 0;
263 
264 #define PV_ENTRY_ZONE_MIN	2048	/* min pv entries in uma zone */
265 
266 #ifndef PMAP_SHPGPERPROC
267 #define PMAP_SHPGPERPROC	200
268 #endif
269 
270 static vm_paddr_t pte_vatopa(pmap_t, vm_offset_t);
271 static int pte_enter(pmap_t, vm_page_t, vm_offset_t, uint32_t, bool);
272 static int pte_remove(pmap_t, vm_offset_t, uint8_t);
273 static pte_t *pte_find(pmap_t, vm_offset_t);
274 static void kernel_pte_alloc(vm_offset_t, vm_offset_t);
275 
276 static pv_entry_t pv_alloc(void);
277 static void pv_free(pv_entry_t);
278 static void pv_insert(pmap_t, vm_offset_t, vm_page_t);
279 static void pv_remove(pmap_t, vm_offset_t, vm_page_t);
280 
281 static void booke_pmap_init_qpages(void);
282 
283 static inline void tlb_miss_lock(void);
284 static inline void tlb_miss_unlock(void);
285 
286 #ifdef SMP
287 extern tlb_entry_t __boot_tlb1[];
288 void pmap_bootstrap_ap(volatile uint32_t *);
289 #endif
290 
291 /*
292  * Kernel MMU interface
293  */
294 static void		mmu_booke_clear_modify(vm_page_t);
295 static void		mmu_booke_copy(pmap_t, pmap_t, vm_offset_t,
296     vm_size_t, vm_offset_t);
297 static void		mmu_booke_copy_page(vm_page_t, vm_page_t);
298 static void		mmu_booke_copy_pages(vm_page_t *,
299     vm_offset_t, vm_page_t *, vm_offset_t, int);
300 static int		mmu_booke_enter(pmap_t, vm_offset_t, vm_page_t,
301     vm_prot_t, u_int flags, int8_t psind);
302 static void		mmu_booke_enter_object(pmap_t, vm_offset_t, vm_offset_t,
303     vm_page_t, vm_prot_t);
304 static void		mmu_booke_enter_quick(pmap_t, vm_offset_t, vm_page_t,
305     vm_prot_t);
306 static vm_paddr_t	mmu_booke_extract(pmap_t, vm_offset_t);
307 static vm_page_t	mmu_booke_extract_and_hold(pmap_t, vm_offset_t,
308     vm_prot_t);
309 static void		mmu_booke_init(void);
310 static bool		mmu_booke_is_modified(vm_page_t);
311 static bool		mmu_booke_is_prefaultable(pmap_t, vm_offset_t);
312 static bool		mmu_booke_is_referenced(vm_page_t);
313 static int		mmu_booke_ts_referenced(vm_page_t);
314 static void		*mmu_booke_map(vm_offset_t *, vm_paddr_t, vm_paddr_t,
315     int);
316 static int		mmu_booke_mincore(pmap_t, vm_offset_t,
317     vm_paddr_t *);
318 static void		mmu_booke_object_init_pt(pmap_t, vm_offset_t,
319     vm_object_t, vm_pindex_t, vm_size_t);
320 static bool		mmu_booke_page_exists_quick(pmap_t, vm_page_t);
321 static void		mmu_booke_page_init(vm_page_t);
322 static int		mmu_booke_page_wired_mappings(vm_page_t);
323 static int		mmu_booke_pinit(pmap_t);
324 static void		mmu_booke_pinit0(pmap_t);
325 static void		mmu_booke_protect(pmap_t, vm_offset_t, vm_offset_t,
326     vm_prot_t);
327 static void		mmu_booke_qenter(void *, vm_page_t *, int);
328 static void		mmu_booke_qremove(void *, int);
329 static void		mmu_booke_release(pmap_t);
330 static void		mmu_booke_remove(pmap_t, vm_offset_t, vm_offset_t);
331 static void		mmu_booke_remove_all(vm_page_t);
332 static void		mmu_booke_remove_write(vm_page_t);
333 static void		mmu_booke_unwire(pmap_t, vm_offset_t, vm_offset_t);
334 static void		mmu_booke_zero_page(vm_page_t);
335 static void		mmu_booke_zero_page_area(vm_page_t, int, int);
336 static void		mmu_booke_activate(struct thread *);
337 static void		mmu_booke_deactivate(struct thread *);
338 static void		mmu_booke_bootstrap(vm_offset_t, vm_offset_t);
339 static void		*mmu_booke_mapdev(vm_paddr_t, vm_size_t);
340 static void		*mmu_booke_mapdev_attr(vm_paddr_t, vm_size_t, vm_memattr_t);
341 static void		mmu_booke_unmapdev(void *, vm_size_t);
342 static vm_paddr_t	mmu_booke_kextract(vm_offset_t);
343 static void		mmu_booke_kenter(vm_offset_t, vm_paddr_t);
344 static void		mmu_booke_kenter_attr(vm_offset_t, vm_paddr_t, vm_memattr_t);
345 static void		mmu_booke_kremove(vm_offset_t);
346 static int		mmu_booke_dev_direct_mapped(vm_paddr_t, vm_size_t);
347 static void		mmu_booke_sync_icache(pmap_t, vm_offset_t,
348     vm_size_t);
349 static void		mmu_booke_dumpsys_map(vm_paddr_t pa, size_t,
350     void **);
351 static void		mmu_booke_dumpsys_unmap(vm_paddr_t pa, size_t,
352     void *);
353 static void		mmu_booke_scan_init(void);
354 static void		*mmu_booke_quick_enter_page(vm_page_t m);
355 static void		mmu_booke_quick_remove_page(void *addr);
356 static int		mmu_booke_change_attr(void *addr,
357     vm_size_t sz, vm_memattr_t mode);
358 static int		mmu_booke_decode_kernel_ptr(vm_offset_t addr,
359     int *is_user, vm_offset_t *decoded_addr);
360 static void		mmu_booke_page_array_startup(long);
361 static bool mmu_booke_page_is_mapped(vm_page_t m);
362 static bool mmu_booke_ps_enabled(pmap_t pmap);
363 #ifdef __powerpc64__
364 static int		mmu_booke_growkernel(vm_offset_t);
365 #endif
366 
367 static struct pmap_funcs mmu_booke_methods = {
368 	/* pmap dispatcher interface */
369 	.clear_modify = mmu_booke_clear_modify,
370 	.copy = mmu_booke_copy,
371 	.copy_page = mmu_booke_copy_page,
372 	.copy_pages = mmu_booke_copy_pages,
373 	.enter = mmu_booke_enter,
374 	.enter_object = mmu_booke_enter_object,
375 	.enter_quick = mmu_booke_enter_quick,
376 	.extract = mmu_booke_extract,
377 	.extract_and_hold = mmu_booke_extract_and_hold,
378 	.init = mmu_booke_init,
379 	.is_modified = mmu_booke_is_modified,
380 	.is_prefaultable = mmu_booke_is_prefaultable,
381 	.is_referenced = mmu_booke_is_referenced,
382 	.ts_referenced = mmu_booke_ts_referenced,
383 	.map = mmu_booke_map,
384 	.mincore = mmu_booke_mincore,
385 	.object_init_pt = mmu_booke_object_init_pt,
386 	.page_exists_quick = mmu_booke_page_exists_quick,
387 	.page_init = mmu_booke_page_init,
388 	.page_wired_mappings =  mmu_booke_page_wired_mappings,
389 	.pinit = mmu_booke_pinit,
390 	.pinit0 = mmu_booke_pinit0,
391 	.protect = mmu_booke_protect,
392 	.qenter = mmu_booke_qenter,
393 	.qremove = mmu_booke_qremove,
394 	.release = mmu_booke_release,
395 	.remove = mmu_booke_remove,
396 	.remove_all = mmu_booke_remove_all,
397 	.remove_write = mmu_booke_remove_write,
398 	.sync_icache = mmu_booke_sync_icache,
399 	.unwire = mmu_booke_unwire,
400 	.zero_page = mmu_booke_zero_page,
401 	.zero_page_area = mmu_booke_zero_page_area,
402 	.activate = mmu_booke_activate,
403 	.deactivate = mmu_booke_deactivate,
404 	.quick_enter_page =  mmu_booke_quick_enter_page,
405 	.quick_remove_page =  mmu_booke_quick_remove_page,
406 	.page_array_startup = mmu_booke_page_array_startup,
407 	.page_is_mapped = mmu_booke_page_is_mapped,
408 	.ps_enabled = mmu_booke_ps_enabled,
409 #ifdef __powerpc64__
410 	.growkernel_nopanic = mmu_booke_growkernel,
411 #endif
412 
413 	/* Internal interfaces */
414 	.bootstrap = mmu_booke_bootstrap,
415 	.dev_direct_mapped = mmu_booke_dev_direct_mapped,
416 	.mapdev = mmu_booke_mapdev,
417 	.mapdev_attr = mmu_booke_mapdev_attr,
418 	.kenter = mmu_booke_kenter,
419 	.kenter_attr = mmu_booke_kenter_attr,
420 	.kextract = mmu_booke_kextract,
421 	.kremove = mmu_booke_kremove,
422 	.unmapdev = mmu_booke_unmapdev,
423 	.change_attr = mmu_booke_change_attr,
424 	.decode_kernel_ptr =  mmu_booke_decode_kernel_ptr,
425 
426 	/* dumpsys() support */
427 	.dumpsys_map_chunk = mmu_booke_dumpsys_map,
428 	.dumpsys_unmap_chunk = mmu_booke_dumpsys_unmap,
429 	.dumpsys_pa_init = mmu_booke_scan_init,
430 };
431 
432 MMU_DEF(booke_mmu, MMU_TYPE_BOOKE, mmu_booke_methods);
433 
434 #ifdef __powerpc64__
435 #include "pmap_64.c"
436 #else
437 #include "pmap_32.c"
438 #endif
439 
440 static vm_offset_t tlb1_map_base = VM_MAPDEV_BASE;
441 
442 static __inline uint32_t
tlb_calc_wimg(vm_paddr_t pa,vm_memattr_t ma)443 tlb_calc_wimg(vm_paddr_t pa, vm_memattr_t ma)
444 {
445 	uint32_t attrib;
446 	int i;
447 
448 	if (ma != VM_MEMATTR_DEFAULT) {
449 		switch (ma) {
450 		case VM_MEMATTR_UNCACHEABLE:
451 			return (MAS2_I | MAS2_G);
452 		case VM_MEMATTR_WRITE_COMBINING:
453 		case VM_MEMATTR_WRITE_BACK:
454 		case VM_MEMATTR_PREFETCHABLE:
455 			return (MAS2_I);
456 		case VM_MEMATTR_WRITE_THROUGH:
457 			return (MAS2_W | MAS2_M);
458 		case VM_MEMATTR_CACHEABLE:
459 			return (MAS2_M);
460 		}
461 	}
462 
463 	/*
464 	 * Assume the page is cache inhibited and access is guarded unless
465 	 * it's in our available memory array.
466 	 */
467 	attrib = _TLB_ENTRY_IO;
468 	for (i = 0; i < physmem_regions_sz; i++) {
469 		if ((pa >= physmem_regions[i].mr_start) &&
470 		    (pa < (physmem_regions[i].mr_start +
471 		     physmem_regions[i].mr_size))) {
472 			attrib = _TLB_ENTRY_MEM;
473 			break;
474 		}
475 	}
476 
477 	return (attrib);
478 }
479 
480 static inline void
tlb_miss_lock(void)481 tlb_miss_lock(void)
482 {
483 #ifdef SMP
484 	struct pcpu *pc;
485 
486 	if (!smp_started)
487 		return;
488 
489 	STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
490 		if (pc != pcpup) {
491 			CTR3(KTR_PMAP, "%s: tlb miss LOCK of CPU=%d, "
492 			    "tlb_lock=%p", __func__, pc->pc_cpuid, pc->pc_booke.tlb_lock);
493 
494 			KASSERT((pc->pc_cpuid != PCPU_GET(cpuid)),
495 			    ("tlb_miss_lock: tried to lock self"));
496 
497 			tlb_lock(pc->pc_booke.tlb_lock);
498 
499 			CTR1(KTR_PMAP, "%s: locked", __func__);
500 		}
501 	}
502 #endif
503 }
504 
505 static inline void
tlb_miss_unlock(void)506 tlb_miss_unlock(void)
507 {
508 #ifdef SMP
509 	struct pcpu *pc;
510 
511 	if (!smp_started)
512 		return;
513 
514 	STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
515 		if (pc != pcpup) {
516 			CTR2(KTR_PMAP, "%s: tlb miss UNLOCK of CPU=%d",
517 			    __func__, pc->pc_cpuid);
518 
519 			tlb_unlock(pc->pc_booke.tlb_lock);
520 
521 			CTR1(KTR_PMAP, "%s: unlocked", __func__);
522 		}
523 	}
524 #endif
525 }
526 
527 /* Return number of entries in TLB0. */
528 static __inline void
tlb0_get_tlbconf(void)529 tlb0_get_tlbconf(void)
530 {
531 	uint32_t tlb0_cfg;
532 
533 	tlb0_cfg = mfspr(SPR_TLB0CFG);
534 	tlb0_entries = tlb0_cfg & TLBCFG_NENTRY_MASK;
535 	tlb0_ways = (tlb0_cfg & TLBCFG_ASSOC_MASK) >> TLBCFG_ASSOC_SHIFT;
536 	tlb0_entries_per_way = tlb0_entries / tlb0_ways;
537 }
538 
539 /* Return number of entries in TLB1. */
540 static __inline void
tlb1_get_tlbconf(void)541 tlb1_get_tlbconf(void)
542 {
543 	uint32_t tlb1_cfg;
544 
545 	tlb1_cfg = mfspr(SPR_TLB1CFG);
546 	tlb1_entries = tlb1_cfg & TLBCFG_NENTRY_MASK;
547 }
548 
549 /**************************************************************************/
550 /* Page table related */
551 /**************************************************************************/
552 
553 /* Allocate pv_entry structure. */
554 pv_entry_t
pv_alloc(void)555 pv_alloc(void)
556 {
557 	pv_entry_t pv;
558 
559 	pv_entry_count++;
560 	if (pv_entry_count > pv_entry_high_water)
561 		pagedaemon_wakeup(0); /* XXX powerpc NUMA */
562 	pv = uma_zalloc(pvzone, M_NOWAIT);
563 
564 	return (pv);
565 }
566 
567 /* Free pv_entry structure. */
568 static __inline void
pv_free(pv_entry_t pve)569 pv_free(pv_entry_t pve)
570 {
571 
572 	pv_entry_count--;
573 	uma_zfree(pvzone, pve);
574 }
575 
576 /* Allocate and initialize pv_entry structure. */
577 static void
pv_insert(pmap_t pmap,vm_offset_t va,vm_page_t m)578 pv_insert(pmap_t pmap, vm_offset_t va, vm_page_t m)
579 {
580 	pv_entry_t pve;
581 
582 	//int su = (pmap == kernel_pmap);
583 	//debugf("pv_insert: s (su = %d pmap = 0x%08x va = 0x%08x m = 0x%08x)\n", su,
584 	//	(u_int32_t)pmap, va, (u_int32_t)m);
585 
586 	pve = pv_alloc();
587 	if (pve == NULL)
588 		panic("pv_insert: no pv entries!");
589 
590 	pve->pv_pmap = pmap;
591 	pve->pv_va = va;
592 
593 	/* add to pv_list */
594 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
595 	rw_assert(&pvh_global_lock, RA_WLOCKED);
596 
597 	TAILQ_INSERT_TAIL(&m->md.pv_list, pve, pv_link);
598 
599 	//debugf("pv_insert: e\n");
600 }
601 
602 /* Destroy pv entry. */
603 static void
pv_remove(pmap_t pmap,vm_offset_t va,vm_page_t m)604 pv_remove(pmap_t pmap, vm_offset_t va, vm_page_t m)
605 {
606 	pv_entry_t pve;
607 
608 	//int su = (pmap == kernel_pmap);
609 	//debugf("pv_remove: s (su = %d pmap = 0x%08x va = 0x%08x)\n", su, (u_int32_t)pmap, va);
610 
611 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
612 	rw_assert(&pvh_global_lock, RA_WLOCKED);
613 
614 	/* find pv entry */
615 	TAILQ_FOREACH(pve, &m->md.pv_list, pv_link) {
616 		if ((pmap == pve->pv_pmap) && (va == pve->pv_va)) {
617 			/* remove from pv_list */
618 			TAILQ_REMOVE(&m->md.pv_list, pve, pv_link);
619 			if (TAILQ_EMPTY(&m->md.pv_list))
620 				vm_page_aflag_clear(m, PGA_WRITEABLE);
621 
622 			/* free pv entry struct */
623 			pv_free(pve);
624 			break;
625 		}
626 	}
627 
628 	//debugf("pv_remove: e\n");
629 }
630 
631 /**************************************************************************/
632 /* PMAP related */
633 /**************************************************************************/
634 
635 /*
636  * This is called during booke_init, before the system is really initialized.
637  */
638 static void
mmu_booke_bootstrap(vm_offset_t start,vm_offset_t kernelend)639 mmu_booke_bootstrap(vm_offset_t start, vm_offset_t kernelend)
640 {
641 	vm_paddr_t phys_kernelend;
642 	struct mem_region *mp, *mp1;
643 	int cnt, i, j;
644 	vm_paddr_t s, e, sz;
645 	vm_paddr_t physsz, hwphyssz;
646 	u_int phys_avail_count __debug_used;
647 	vm_size_t kstack0_sz;
648 	vm_paddr_t kstack0_phys;
649 	vm_offset_t kstack0;
650 	uint32_t tid_bits;
651 	void *dpcpu;
652 
653 	debugf("mmu_booke_bootstrap: entered\n");
654 
655 	if ((mfspr(SPR_MMUCFG) & MMUCFG_MAVN_M) > 0)
656 		mmuv2 = true;
657 
658 	/* Set interesting system properties */
659 #ifdef __powerpc64__
660 	hw_direct_map = 1;
661 #else
662 	hw_direct_map = 0;
663 #endif
664 #if defined(COMPAT_FREEBSD32) || !defined(__powerpc64__)
665 	elf32_nxstack = 1;
666 #endif
667 
668 	/* Initialize invalidation mutex */
669 	mtx_init(&tlbivax_mutex, "tlbivax", NULL, MTX_SPIN);
670 
671 	/* Read TLB0 size and associativity. */
672 	tlb0_get_tlbconf();
673 
674 	/*
675 	 * Calculate the max TID from the hardware.  Allow overriding with a
676 	 * tunable.  The tunable should be a power of 2.
677 	 */
678 	tid_bits = ((mfspr(SPR_MMUCFG) & MMUCFG_PIDSIZE_M) >> MMUCFG_PIDSIZE_S);
679 	TUNABLE_INT_FETCH("machdep.tid_max", &tid_max);
680 	if (tid_max <= 0)
681 		tid_max = INT_MAX;
682 	else
683 		tid_max = 1 << ilog2(tid_max);
684 	tid_max = min((1 << tid_bits), tid_max) - 1;
685 
686 	/*
687 	 * Align kernel start and end address (kernel image).
688 	 * Note that kernel end does not necessarily relate to kernsize.
689 	 * kernsize is the size of the kernel that is actually mapped.
690 	 */
691 	data_start = round_page(kernelend);
692 	data_end = data_start;
693 
694 	tidbusy = (void *)data_end;
695 	printf("tidbusy at %p\n", tidbusy);
696 	printf("tidmax = %d\n", tid_max);
697 	data_end += round_page(sizeof(pmap_t) * MAXCPU * (tid_max + 1));
698 
699 	/* Allocate the dynamic per-cpu area. */
700 	dpcpu = (void *)data_end;
701 	data_end += DPCPU_SIZE;
702 
703 	/* Allocate space for the message buffer. */
704 	msgbufp = (struct msgbuf *)data_end;
705 	data_end += msgbufsize;
706 	debugf(" msgbufp at 0x%"PRI0ptrX" end = 0x%"PRI0ptrX"\n",
707 	    (uintptr_t)msgbufp, data_end);
708 
709 	data_end = round_page(data_end);
710 
711 	/* Retrieve phys/avail mem regions */
712 	mem_regions(&physmem_regions, &physmem_regions_sz,
713 	    &availmem_regions, &availmem_regions_sz);
714 
715 	if (PHYS_AVAIL_ENTRIES < availmem_regions_sz)
716 		panic("mmu_booke_bootstrap: phys_avail too small");
717 
718 	vm_page_array = (vm_page_t)data_end;
719 	/*
720 	 * Get a rough idea (upper bound) on the size of the page array.  The
721 	 * vm_page_array will not handle any more pages than we have in the
722 	 * avail_regions array, and most likely much less.
723 	 */
724 	sz = 0;
725 	for (mp = availmem_regions; mp->mr_size; mp++) {
726 		sz += mp->mr_size;
727 	}
728 	sz = (round_page(sz) / (PAGE_SIZE + sizeof(struct vm_page)));
729 	data_end += round_page(sz * sizeof(struct vm_page));
730 
731 	/*
732 	 * Reserve kernel page-table pages last, so their reservation size can
733 	 * be computed from the final bootstrap data_end (on 64-bit, only leaf
734 	 * ptbls covering [VM_MIN_KERNEL_ADDRESS, data_end + slack] are
735 	 * pre-allocated; the rest are added on demand by pmap_growkernel()).
736 	 */
737 	data_end = round_page(mmu_booke_alloc_kernel_pgtables(data_end));
738 
739 	/* Pre-round up to 1MB.  This wastes some space, but saves TLB entries */
740 	data_end = roundup2(data_end, 1 << 20);
741 
742 	debugf(" data_end: 0x%"PRI0ptrX"\n", data_end);
743 	debugf(" kernstart: %#zx\n", kernstart);
744 	debugf(" kernsize: %#zx\n", kernsize);
745 
746 	if (data_end - kernstart > kernsize) {
747 		kernsize += tlb1_mapin_region(kernstart + kernsize,
748 		    kernload + kernsize, (data_end - kernstart) - kernsize,
749 		    _TLB_ENTRY_MEM);
750 	}
751 	data_end = kernstart + kernsize;
752 	debugf(" updated data_end: 0x%"PRI0ptrX"\n", data_end);
753 
754 	/*
755 	 * Clear the structures - note we can only do it safely after the
756 	 * possible additional TLB1 translations are in place (above) so that
757 	 * all range up to the currently calculated 'data_end' is covered.
758 	 */
759 	bzero((void *)data_start, data_end - data_start);
760 	dpcpu_init(dpcpu, 0);
761 
762 	/*******************************************************/
763 	/* Set the start and end of kva. */
764 	/*******************************************************/
765 	virtual_avail = round_page(data_end);
766 	virtual_end = VM_MAX_KERNEL_ADDRESS;
767 
768 #ifndef __powerpc64__
769 	/* Allocate KVA space for page zero/copy operations. */
770 	zero_page_va = virtual_avail;
771 	virtual_avail += PAGE_SIZE;
772 	copy_page_src_va = virtual_avail;
773 	virtual_avail += PAGE_SIZE;
774 	copy_page_dst_va = virtual_avail;
775 	virtual_avail += PAGE_SIZE;
776 	debugf("zero_page_va = 0x%"PRI0ptrX"\n", zero_page_va);
777 	debugf("copy_page_src_va = 0x%"PRI0ptrX"\n", copy_page_src_va);
778 	debugf("copy_page_dst_va = 0x%"PRI0ptrX"\n", copy_page_dst_va);
779 
780 	/* Initialize page zero/copy mutexes. */
781 	mtx_init(&zero_page_mutex, "mmu_booke_zero_page", NULL, MTX_DEF);
782 	mtx_init(&copy_page_mutex, "mmu_booke_copy_page", NULL, MTX_DEF);
783 
784 	/* Allocate KVA space for ptbl bufs. */
785 	ptbl_buf_pool_vabase = virtual_avail;
786 	virtual_avail += PTBL_BUFS * PTBL_PAGES * PAGE_SIZE;
787 	debugf("ptbl_buf_pool_vabase = 0x%"PRI0ptrX" end = 0x%"PRI0ptrX"\n",
788 	    ptbl_buf_pool_vabase, virtual_avail);
789 #endif
790 #ifdef	__powerpc64__
791 	/* Allocate KVA space for crashdumpmap. */
792 	crashdumpmap = (caddr_t)virtual_avail;
793 	virtual_avail += MAXDUMPPGS * PAGE_SIZE;
794 #endif
795 
796 	/* Calculate corresponding physical addresses for the kernel region. */
797 	phys_kernelend = kernload + kernsize;
798 	debugf("kernel image and allocated data:\n");
799 	debugf(" kernload    = 0x%09jx\n", (uintmax_t)kernload);
800 	debugf(" kernstart   = 0x%"PRI0ptrX"\n", kernstart);
801 	debugf(" kernsize    = 0x%"PRI0ptrX"\n", kernsize);
802 
803 	/*
804 	 * Remove kernel physical address range from avail regions list. Page
805 	 * align all regions.  Non-page aligned memory isn't very interesting
806 	 * to us.  Also, sort the entries for ascending addresses.
807 	 */
808 
809 	sz = 0;
810 	cnt = availmem_regions_sz;
811 	debugf("processing avail regions:\n");
812 	for (mp = availmem_regions; mp->mr_size; mp++) {
813 		s = mp->mr_start;
814 		e = mp->mr_start + mp->mr_size;
815 		debugf(" %09jx-%09jx -> ", (uintmax_t)s, (uintmax_t)e);
816 		/* Check whether this region holds all of the kernel. */
817 		if (s < kernload && e > phys_kernelend) {
818 			availmem_regions[cnt].mr_start = phys_kernelend;
819 			availmem_regions[cnt++].mr_size = e - phys_kernelend;
820 			e = kernload;
821 		}
822 		/* Look whether this regions starts within the kernel. */
823 		if (s >= kernload && s < phys_kernelend) {
824 			if (e <= phys_kernelend)
825 				goto empty;
826 			s = phys_kernelend;
827 		}
828 		/* Now look whether this region ends within the kernel. */
829 		if (e > kernload && e <= phys_kernelend) {
830 			if (s >= kernload)
831 				goto empty;
832 			e = kernload;
833 		}
834 		/* Now page align the start and size of the region. */
835 		s = round_page(s);
836 		e = trunc_page(e);
837 		if (e < s)
838 			e = s;
839 		sz = e - s;
840 		debugf("%09jx-%09jx = %jx\n",
841 		    (uintmax_t)s, (uintmax_t)e, (uintmax_t)sz);
842 
843 		/* Check whether some memory is left here. */
844 		if (sz == 0) {
845 		empty:
846 			memmove(mp, mp + 1,
847 			    (cnt - (mp - availmem_regions)) * sizeof(*mp));
848 			cnt--;
849 			mp--;
850 			continue;
851 		}
852 
853 		/* Do an insertion sort. */
854 		for (mp1 = availmem_regions; mp1 < mp; mp1++)
855 			if (s < mp1->mr_start)
856 				break;
857 		if (mp1 < mp) {
858 			memmove(mp1 + 1, mp1, (char *)mp - (char *)mp1);
859 			mp1->mr_start = s;
860 			mp1->mr_size = sz;
861 		} else {
862 			mp->mr_start = s;
863 			mp->mr_size = sz;
864 		}
865 	}
866 	availmem_regions_sz = cnt;
867 
868 	/*******************************************************/
869 	/* Steal physical memory for kernel stack from the end */
870 	/* of the first avail region                           */
871 	/*******************************************************/
872 	kstack0_sz = kstack_pages * PAGE_SIZE;
873 	kstack0_phys = availmem_regions[0].mr_start +
874 	    availmem_regions[0].mr_size;
875 	kstack0_phys -= kstack0_sz;
876 	availmem_regions[0].mr_size -= kstack0_sz;
877 
878 	/*******************************************************/
879 	/* Fill in phys_avail table, based on availmem_regions */
880 	/*******************************************************/
881 	phys_avail_count = 0;
882 	physsz = 0;
883 	hwphyssz = 0;
884 	TUNABLE_ULONG_FETCH("hw.physmem", (u_long *) &hwphyssz);
885 
886 	debugf("fill in phys_avail:\n");
887 	for (i = 0, j = 0; i < availmem_regions_sz; i++, j += 2) {
888 		debugf(" region: 0x%jx - 0x%jx (0x%jx)\n",
889 		    (uintmax_t)availmem_regions[i].mr_start,
890 		    (uintmax_t)availmem_regions[i].mr_start +
891 		        availmem_regions[i].mr_size,
892 		    (uintmax_t)availmem_regions[i].mr_size);
893 
894 		if (hwphyssz != 0 &&
895 		    (physsz + availmem_regions[i].mr_size) >= hwphyssz) {
896 			debugf(" hw.physmem adjust\n");
897 			if (physsz < hwphyssz) {
898 				phys_avail[j] = availmem_regions[i].mr_start;
899 				phys_avail[j + 1] =
900 				    availmem_regions[i].mr_start +
901 				    hwphyssz - physsz;
902 				physsz = hwphyssz;
903 				phys_avail_count++;
904 				dump_avail[j] = phys_avail[j];
905 				dump_avail[j + 1] = phys_avail[j + 1];
906 			}
907 			break;
908 		}
909 
910 		phys_avail[j] = availmem_regions[i].mr_start;
911 		phys_avail[j + 1] = availmem_regions[i].mr_start +
912 		    availmem_regions[i].mr_size;
913 		phys_avail_count++;
914 		physsz += availmem_regions[i].mr_size;
915 		dump_avail[j] = phys_avail[j];
916 		dump_avail[j + 1] = phys_avail[j + 1];
917 	}
918 	physmem = btoc(physsz);
919 
920 	/* Calculate the last available physical address. */
921 	for (i = 0; phys_avail[i + 2] != 0; i += 2)
922 		;
923 	Maxmem = powerpc_btop(phys_avail[i + 1]);
924 
925 	debugf("Maxmem = 0x%08lx\n", Maxmem);
926 	debugf("phys_avail_count = %d\n", phys_avail_count);
927 	debugf("physsz = 0x%09jx physmem = %jd (0x%09jx)\n",
928 	    (uintmax_t)physsz, (uintmax_t)physmem, (uintmax_t)physmem);
929 
930 #ifdef __powerpc64__
931 	/*
932 	 * Map the physical memory contiguously in TLB1.
933 	 * Round so it fits into a single mapping.
934 	 */
935 	tlb1_mapin_region(DMAP_BASE_ADDRESS, 0,
936 	    phys_avail[i + 1], _TLB_ENTRY_MEM);
937 #endif
938 
939 	/*******************************************************/
940 	/* Initialize (statically allocated) kernel pmap. */
941 	/*******************************************************/
942 	mtx_init(&kernel_pmap->pm_mtx, "kernel pmap", NULL, MTX_DEF);
943 
944 	debugf("kernel_pmap = 0x%"PRI0ptrX"\n", (uintptr_t)kernel_pmap);
945 	kernel_pte_alloc(virtual_avail, kernstart);
946 	for (i = 0; i < MAXCPU; i++) {
947 		kernel_pmap->pm_tid[i] = TID_KERNEL;
948 
949 		/* Initialize each CPU's tidbusy entry 0 with kernel_pmap */
950 		tid_set_busy(i, TID_KERNEL, kernel_pmap);
951 	}
952 
953 	/* Mark kernel_pmap active on all CPUs */
954 	CPU_FILL(&kernel_pmap->pm_active);
955 
956  	/*
957 	 * Initialize the global pv list lock.
958 	 */
959 	rw_init(&pvh_global_lock, "pmap pv global");
960 
961 	/*******************************************************/
962 	/* Final setup */
963 	/*******************************************************/
964 
965 	/* Enter kstack0 into kernel map, provide guard page */
966 	kstack0 = virtual_avail + KSTACK_GUARD_PAGES * PAGE_SIZE;
967 	thread0.td_kstack = (char *)kstack0;
968 	thread0.td_kstack_pages = kstack_pages;
969 
970 	debugf("kstack_sz = 0x%08jx\n", (uintmax_t)kstack0_sz);
971 	debugf("kstack0_phys at 0x%09jx - 0x%09jx\n",
972 	    (uintmax_t)kstack0_phys, (uintmax_t)kstack0_phys + kstack0_sz);
973 	debugf("kstack0 at 0x%"PRI0ptrX" - 0x%"PRI0ptrX"\n",
974 	    kstack0, kstack0 + kstack0_sz);
975 
976 	virtual_avail += KSTACK_GUARD_PAGES * PAGE_SIZE + kstack0_sz;
977 	for (i = 0; i < kstack_pages; i++) {
978 		mmu_booke_kenter(kstack0, kstack0_phys);
979 		kstack0 += PAGE_SIZE;
980 		kstack0_phys += PAGE_SIZE;
981 	}
982 
983 	pmap_bootstrapped = 1;
984 
985 	debugf("virtual_avail = %"PRI0ptrX"\n", virtual_avail);
986 	debugf("virtual_end   = %"PRI0ptrX"\n", virtual_end);
987 
988 	debugf("mmu_booke_bootstrap: exit\n");
989 }
990 
991 #ifdef SMP
992 void
tlb1_ap_prep(void)993 tlb1_ap_prep(void)
994 {
995 	tlb_entry_t *e, tmp;
996 	unsigned int i;
997 
998 	/* Prepare TLB1 image for AP processors */
999 	e = __boot_tlb1;
1000 	for (i = 0; i < TLB1_ENTRIES; i++) {
1001 		tlb1_read_entry(&tmp, i);
1002 
1003 		if ((tmp.mas1 & MAS1_VALID) && (tmp.mas2 & _TLB_ENTRY_SHARED))
1004 			memcpy(e++, &tmp, sizeof(tmp));
1005 	}
1006 }
1007 
1008 void
pmap_bootstrap_ap(volatile uint32_t * trcp __unused)1009 pmap_bootstrap_ap(volatile uint32_t *trcp __unused)
1010 {
1011 	int i;
1012 
1013 	/*
1014 	 * Finish TLB1 configuration: the BSP already set up its TLB1 and we
1015 	 * have the snapshot of its contents in the s/w __boot_tlb1[] table
1016 	 * created by tlb1_ap_prep(), so use these values directly to
1017 	 * (re)program AP's TLB1 hardware.
1018 	 *
1019 	 * Start at index 1 because index 0 has the kernel map.
1020 	 */
1021 	for (i = 1; i < TLB1_ENTRIES; i++) {
1022 		if (__boot_tlb1[i].mas1 & MAS1_VALID)
1023 			tlb1_write_entry(&__boot_tlb1[i], i);
1024 	}
1025 
1026 	set_mas4_defaults();
1027 }
1028 #endif
1029 
1030 static void
booke_pmap_init_qpages(void)1031 booke_pmap_init_qpages(void)
1032 {
1033 	struct pcpu *pc;
1034 	int i;
1035 
1036 	CPU_FOREACH(i) {
1037 		pc = pcpu_find(i);
1038 		pc->pc_qmap_addr = kva_alloc(PAGE_SIZE);
1039 		if (pc->pc_qmap_addr == NULL)
1040 			panic("pmap_init_qpages: unable to allocate KVA");
1041 	}
1042 }
1043 
1044 SYSINIT(qpages_init, SI_SUB_CPU, SI_ORDER_ANY, booke_pmap_init_qpages, NULL);
1045 
1046 /*
1047  * Get the physical page address for the given pmap/virtual address.
1048  */
1049 static vm_paddr_t
mmu_booke_extract(pmap_t pmap,vm_offset_t va)1050 mmu_booke_extract(pmap_t pmap, vm_offset_t va)
1051 {
1052 	vm_paddr_t pa;
1053 
1054 	PMAP_LOCK(pmap);
1055 	pa = pte_vatopa(pmap, va);
1056 	PMAP_UNLOCK(pmap);
1057 
1058 	return (pa);
1059 }
1060 
1061 /*
1062  * Extract the physical page address associated with the given
1063  * kernel virtual address.
1064  */
1065 static vm_paddr_t
mmu_booke_kextract(vm_offset_t va)1066 mmu_booke_kextract(vm_offset_t va)
1067 {
1068 	tlb_entry_t e;
1069 	vm_paddr_t p = 0;
1070 	int i;
1071 
1072 #ifdef __powerpc64__
1073 	if (va >= DMAP_BASE_ADDRESS && va <= DMAP_MAX_ADDRESS)
1074 		return (DMAP_TO_PHYS(va));
1075 #endif
1076 
1077 	if (va >= VM_MIN_KERNEL_ADDRESS && va <= VM_MAX_KERNEL_ADDRESS)
1078 		p = pte_vatopa(kernel_pmap, va);
1079 
1080 	if (p == 0) {
1081 		/* Check TLB1 mappings */
1082 		for (i = 0; i < TLB1_ENTRIES; i++) {
1083 			tlb1_read_entry(&e, i);
1084 			if (!(e.mas1 & MAS1_VALID))
1085 				continue;
1086 			if (va >= e.virt && va < e.virt + e.size)
1087 				return (e.phys + (va - e.virt));
1088 		}
1089 	}
1090 
1091 	return (p);
1092 }
1093 
1094 /*
1095  * Initialize the pmap module.
1096  *
1097  * Called by vm_mem_init(), to initialize any structures that the pmap system
1098  * needs to map virtual memory.
1099  */
1100 static void
mmu_booke_init(void)1101 mmu_booke_init(void)
1102 {
1103 	int shpgperproc = PMAP_SHPGPERPROC;
1104 
1105 	/*
1106 	 * Initialize the address space (zone) for the pv entries.  Set a
1107 	 * high water mark so that the system can recover from excessive
1108 	 * numbers of pv entries.
1109 	 */
1110 	pvzone = uma_zcreate("PV ENTRY", sizeof(struct pv_entry), NULL, NULL,
1111 	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_VM | UMA_ZONE_NOFREE);
1112 
1113 	TUNABLE_INT_FETCH("vm.pmap.shpgperproc", &shpgperproc);
1114 	pv_entry_max = shpgperproc * maxproc + vm_cnt.v_page_count;
1115 
1116 	TUNABLE_INT_FETCH("vm.pmap.pv_entry_max", &pv_entry_max);
1117 	pv_entry_high_water = 9 * (pv_entry_max / 10);
1118 
1119 	uma_zone_reserve_kva(pvzone, pv_entry_max);
1120 
1121 	/* Pre-fill pvzone with initial number of pv entries. */
1122 	uma_prealloc(pvzone, PV_ENTRY_ZONE_MIN);
1123 
1124 	/* Initialize ptbl allocation, including the page table root zone. */
1125 	ptbl_init();
1126 }
1127 
1128 /*
1129  * Map a list of wired pages into kernel virtual address space.  This is
1130  * intended for temporary mappings which do not need page modification or
1131  * references recorded.  Existing mappings in the region are overwritten.
1132  */
1133 static void
mmu_booke_qenter(void * sva,vm_page_t * m,int count)1134 mmu_booke_qenter(void *sva, vm_page_t *m, int count)
1135 {
1136 	vm_offset_t va;
1137 
1138 	va = (vm_offset_t)sva;
1139 	while (count-- > 0) {
1140 		mmu_booke_kenter(va, VM_PAGE_TO_PHYS(*m));
1141 		va += PAGE_SIZE;
1142 		m++;
1143 	}
1144 }
1145 
1146 /*
1147  * Remove page mappings from kernel virtual address space.  Intended for
1148  * temporary mappings entered by mmu_booke_qenter.
1149  */
1150 static void
mmu_booke_qremove(void * sva,int count)1151 mmu_booke_qremove(void *sva, int count)
1152 {
1153 	vm_offset_t va;
1154 
1155 	va = (vm_offset_t)sva;
1156 	while (count-- > 0) {
1157 		mmu_booke_kremove(va);
1158 		va += PAGE_SIZE;
1159 	}
1160 }
1161 
1162 /*
1163  * Map a wired page into kernel virtual address space.
1164  */
1165 static void
mmu_booke_kenter(vm_offset_t va,vm_paddr_t pa)1166 mmu_booke_kenter(vm_offset_t va, vm_paddr_t pa)
1167 {
1168 
1169 	mmu_booke_kenter_attr(va, pa, VM_MEMATTR_DEFAULT);
1170 }
1171 
1172 static void
mmu_booke_kenter_attr(vm_offset_t va,vm_paddr_t pa,vm_memattr_t ma)1173 mmu_booke_kenter_attr(vm_offset_t va, vm_paddr_t pa, vm_memattr_t ma)
1174 {
1175 	uint32_t flags;
1176 	pte_t *pte;
1177 
1178 	KASSERT(((va >= VM_MIN_KERNEL_ADDRESS) &&
1179 	    (va <= VM_MAX_KERNEL_ADDRESS)), ("mmu_booke_kenter: invalid va"));
1180 
1181 	flags = PTE_SR | PTE_SW | PTE_SX | PTE_WIRED | PTE_VALID;
1182 	flags |= tlb_calc_wimg(pa, ma) << PTE_MAS2_SHIFT;
1183 	flags |= PTE_PS_4KB;
1184 
1185 	pte = pte_find(kernel_pmap, va);
1186 	KASSERT((pte != NULL), ("mmu_booke_kenter: invalid va.  NULL PTE"));
1187 
1188 	mtx_lock_spin(&tlbivax_mutex);
1189 	tlb_miss_lock();
1190 
1191 	if (PTE_ISVALID(pte)) {
1192 		CTR1(KTR_PMAP, "%s: replacing entry!", __func__);
1193 
1194 		/* Flush entry from TLB0 */
1195 		tlb0_flush_entry(va);
1196 	}
1197 
1198 	*pte = PTE_RPN_FROM_PA(pa) | flags;
1199 
1200 	//debugf("mmu_booke_kenter: pdir_idx = %d ptbl_idx = %d va=0x%08x "
1201 	//		"pa=0x%08x rpn=0x%08x flags=0x%08x\n",
1202 	//		pdir_idx, ptbl_idx, va, pa, pte->rpn, pte->flags);
1203 
1204 	/* Flush the real memory from the instruction cache. */
1205 	if ((flags & (PTE_I | PTE_G)) == 0)
1206 		__syncicache((void *)va, PAGE_SIZE);
1207 
1208 	tlb_miss_unlock();
1209 	mtx_unlock_spin(&tlbivax_mutex);
1210 }
1211 
1212 /*
1213  * Remove a page from kernel page table.
1214  */
1215 static void
mmu_booke_kremove(vm_offset_t va)1216 mmu_booke_kremove(vm_offset_t va)
1217 {
1218 	pte_t *pte;
1219 
1220 	CTR2(KTR_PMAP,"%s: s (va = 0x%"PRI0ptrX")\n", __func__, va);
1221 
1222 	KASSERT(((va >= VM_MIN_KERNEL_ADDRESS) &&
1223 	    (va <= VM_MAX_KERNEL_ADDRESS)),
1224 	    ("mmu_booke_kremove: invalid va"));
1225 
1226 	pte = pte_find(kernel_pmap, va);
1227 
1228 	if (pte == NULL || !PTE_ISVALID(pte)) {
1229 		CTR1(KTR_PMAP, "%s: invalid pte", __func__);
1230 
1231 		return;
1232 	}
1233 
1234 	mtx_lock_spin(&tlbivax_mutex);
1235 	tlb_miss_lock();
1236 
1237 	/* Invalidate entry in TLB0, update PTE. */
1238 	tlb0_flush_entry(va);
1239 	*pte = 0;
1240 
1241 	tlb_miss_unlock();
1242 	mtx_unlock_spin(&tlbivax_mutex);
1243 }
1244 
1245 /*
1246  * Figure out where a given kernel pointer (usually in a fault) points
1247  * to from the VM's perspective, potentially remapping into userland's
1248  * address space.
1249  */
1250 static int
mmu_booke_decode_kernel_ptr(vm_offset_t addr,int * is_user,vm_offset_t * decoded_addr)1251 mmu_booke_decode_kernel_ptr(vm_offset_t addr, int *is_user,
1252     vm_offset_t *decoded_addr)
1253 {
1254 
1255 	if (trunc_page(addr) <= VM_MAXUSER_ADDRESS)
1256 		*is_user = 1;
1257 	else
1258 		*is_user = 0;
1259 
1260 	*decoded_addr = addr;
1261 	return (0);
1262 }
1263 
1264 static bool
mmu_booke_page_is_mapped(vm_page_t m)1265 mmu_booke_page_is_mapped(vm_page_t m)
1266 {
1267 
1268 	return (!TAILQ_EMPTY(&(m)->md.pv_list));
1269 }
1270 
1271 static bool
mmu_booke_ps_enabled(pmap_t pmap __unused)1272 mmu_booke_ps_enabled(pmap_t pmap __unused)
1273 {
1274 	return (false);
1275 }
1276 
1277 /*
1278  * Initialize pmap associated with process 0.
1279  */
1280 static void
mmu_booke_pinit0(pmap_t pmap)1281 mmu_booke_pinit0(pmap_t pmap)
1282 {
1283 
1284 	PMAP_LOCK_INIT(pmap);
1285 	mmu_booke_pinit(pmap);
1286 	PCPU_SET(curpmap, pmap);
1287 }
1288 
1289 /*
1290  * Insert the given physical page at the specified virtual address in the
1291  * target physical map with the protection requested. If specified the page
1292  * will be wired down.
1293  */
1294 static int
mmu_booke_enter(pmap_t pmap,vm_offset_t va,vm_page_t m,vm_prot_t prot,u_int flags,int8_t psind)1295 mmu_booke_enter(pmap_t pmap, vm_offset_t va, vm_page_t m,
1296     vm_prot_t prot, u_int flags, int8_t psind)
1297 {
1298 	int error;
1299 
1300 	rw_wlock(&pvh_global_lock);
1301 	PMAP_LOCK(pmap);
1302 	error = mmu_booke_enter_locked(pmap, va, m, prot, flags, psind);
1303 	PMAP_UNLOCK(pmap);
1304 	rw_wunlock(&pvh_global_lock);
1305 	return (error);
1306 }
1307 
1308 static int
mmu_booke_enter_locked(pmap_t pmap,vm_offset_t va,vm_page_t m,vm_prot_t prot,u_int pmap_flags,int8_t psind __unused)1309 mmu_booke_enter_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
1310     vm_prot_t prot, u_int pmap_flags, int8_t psind __unused)
1311 {
1312 	pte_t *pte;
1313 	vm_paddr_t pa;
1314 	pte_t flags;
1315 	int error, su, sync;
1316 
1317 	pa = VM_PAGE_TO_PHYS(m);
1318 	su = (pmap == kernel_pmap);
1319 	sync = 0;
1320 
1321 	//debugf("mmu_booke_enter_locked: s (pmap=0x%08x su=%d tid=%d m=0x%08x va=0x%08x "
1322 	//		"pa=0x%08x prot=0x%08x flags=%#x)\n",
1323 	//		(u_int32_t)pmap, su, pmap->pm_tid,
1324 	//		(u_int32_t)m, va, pa, prot, flags);
1325 
1326 	if (su) {
1327 		KASSERT(((va >= virtual_avail) &&
1328 		    (va <= VM_MAX_KERNEL_ADDRESS)),
1329 		    ("mmu_booke_enter_locked: kernel pmap, non kernel va"));
1330 	} else {
1331 		KASSERT((va <= VM_MAXUSER_ADDRESS),
1332 		    ("mmu_booke_enter_locked: user pmap, non user va"));
1333 	}
1334 	if ((m->oflags & VPO_UNMANAGED) == 0) {
1335 		if ((pmap_flags & PMAP_ENTER_QUICK_LOCKED) == 0)
1336 			VM_PAGE_OBJECT_BUSY_ASSERT(m);
1337 		else
1338 			VM_OBJECT_ASSERT_LOCKED(m->object);
1339 	}
1340 
1341 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1342 
1343 	/*
1344 	 * If there is an existing mapping, and the physical address has not
1345 	 * changed, must be protection or wiring change.
1346 	 */
1347 	if (((pte = pte_find(pmap, va)) != NULL) &&
1348 	    (PTE_ISVALID(pte)) && (PTE_PA(pte) == pa)) {
1349 
1350 		/*
1351 		 * Before actually updating pte->flags we calculate and
1352 		 * prepare its new value in a helper var.
1353 		 */
1354 		flags = *pte;
1355 		flags &= ~(PTE_UW | PTE_UX | PTE_SW | PTE_SX | PTE_MODIFIED);
1356 
1357 		/* Wiring change, just update stats. */
1358 		if ((pmap_flags & PMAP_ENTER_WIRED) != 0) {
1359 			if (!PTE_ISWIRED(pte)) {
1360 				flags |= PTE_WIRED;
1361 				pmap->pm_stats.wired_count++;
1362 			}
1363 		} else {
1364 			if (PTE_ISWIRED(pte)) {
1365 				flags &= ~PTE_WIRED;
1366 				pmap->pm_stats.wired_count--;
1367 			}
1368 		}
1369 
1370 		if (prot & VM_PROT_WRITE) {
1371 			/* Add write permissions. */
1372 			flags |= PTE_SW;
1373 			if (!su)
1374 				flags |= PTE_UW;
1375 
1376 			if ((flags & PTE_MANAGED) != 0)
1377 				vm_page_aflag_set(m, PGA_WRITEABLE);
1378 		} else {
1379 			/* Handle modified pages, sense modify status. */
1380 
1381 			/*
1382 			 * The PTE_MODIFIED flag could be set by underlying
1383 			 * TLB misses since we last read it (above), possibly
1384 			 * other CPUs could update it so we check in the PTE
1385 			 * directly rather than rely on that saved local flags
1386 			 * copy.
1387 			 */
1388 			if (PTE_ISMODIFIED(pte))
1389 				vm_page_dirty(m);
1390 		}
1391 
1392 		if (prot & VM_PROT_EXECUTE) {
1393 			flags |= PTE_SX;
1394 			if (!su)
1395 				flags |= PTE_UX;
1396 
1397 			/*
1398 			 * Check existing flags for execute permissions: if we
1399 			 * are turning execute permissions on, icache should
1400 			 * be flushed.
1401 			 */
1402 			if ((*pte & (PTE_UX | PTE_SX)) == 0)
1403 				sync++;
1404 		}
1405 
1406 		flags &= ~PTE_REFERENCED;
1407 
1408 		/*
1409 		 * The new flags value is all calculated -- only now actually
1410 		 * update the PTE.
1411 		 */
1412 		mtx_lock_spin(&tlbivax_mutex);
1413 		tlb_miss_lock();
1414 
1415 		tlb0_flush_entry(va);
1416 		*pte &= ~PTE_FLAGS_MASK;
1417 		*pte |= flags;
1418 
1419 		tlb_miss_unlock();
1420 		mtx_unlock_spin(&tlbivax_mutex);
1421 
1422 	} else {
1423 		/*
1424 		 * If there is an existing mapping, but it's for a different
1425 		 * physical address, pte_enter() will delete the old mapping.
1426 		 */
1427 		//if ((pte != NULL) && PTE_ISVALID(pte))
1428 		//	debugf("mmu_booke_enter_locked: replace\n");
1429 		//else
1430 		//	debugf("mmu_booke_enter_locked: new\n");
1431 
1432 		/* Now set up the flags and install the new mapping. */
1433 		flags = (PTE_SR | PTE_VALID);
1434 		flags |= PTE_M;
1435 
1436 		if (!su)
1437 			flags |= PTE_UR;
1438 
1439 		if (prot & VM_PROT_WRITE) {
1440 			flags |= PTE_SW;
1441 			if (!su)
1442 				flags |= PTE_UW;
1443 
1444 			if ((m->oflags & VPO_UNMANAGED) == 0)
1445 				vm_page_aflag_set(m, PGA_WRITEABLE);
1446 		}
1447 
1448 		if (prot & VM_PROT_EXECUTE) {
1449 			flags |= PTE_SX;
1450 			if (!su)
1451 				flags |= PTE_UX;
1452 		}
1453 
1454 		/* If its wired update stats. */
1455 		if ((pmap_flags & PMAP_ENTER_WIRED) != 0)
1456 			flags |= PTE_WIRED;
1457 
1458 		error = pte_enter(pmap, m, va, flags,
1459 		    (pmap_flags & PMAP_ENTER_NOSLEEP) != 0);
1460 		if (error != 0)
1461 			return (KERN_RESOURCE_SHORTAGE);
1462 
1463 		if ((flags & PMAP_ENTER_WIRED) != 0)
1464 			pmap->pm_stats.wired_count++;
1465 
1466 		/* Flush the real memory from the instruction cache. */
1467 		if (prot & VM_PROT_EXECUTE)
1468 			sync++;
1469 	}
1470 
1471 	if (sync && (su || pmap == PCPU_GET(curpmap))) {
1472 		__syncicache((void *)va, PAGE_SIZE);
1473 		sync = 0;
1474 	}
1475 
1476 	return (KERN_SUCCESS);
1477 }
1478 
1479 /*
1480  * Maps a sequence of resident pages belonging to the same object.
1481  * The sequence begins with the given page m_start.  This page is
1482  * mapped at the given virtual address start.  Each subsequent page is
1483  * mapped at a virtual address that is offset from start by the same
1484  * amount as the page is offset from m_start within the object.  The
1485  * last page in the sequence is the page with the largest offset from
1486  * m_start that can be mapped at a virtual address less than the given
1487  * virtual address end.  Not every virtual page between start and end
1488  * is mapped; only those for which a resident page exists with the
1489  * corresponding offset from m_start are mapped.
1490  */
1491 static void
mmu_booke_enter_object(pmap_t pmap,vm_offset_t start,vm_offset_t end,vm_page_t m_start,vm_prot_t prot)1492 mmu_booke_enter_object(pmap_t pmap, vm_offset_t start,
1493     vm_offset_t end, vm_page_t m_start, vm_prot_t prot)
1494 {
1495 	struct pctrie_iter pages;
1496 	vm_offset_t va;
1497 	vm_page_t m;
1498 
1499 	VM_OBJECT_ASSERT_LOCKED(m_start->object);
1500 
1501 	vm_page_iter_limit_init(&pages, m_start->object,
1502 	    m_start->pindex + atop(end - start));
1503 	m = vm_radix_iter_lookup(&pages, m_start->pindex);
1504 	rw_wlock(&pvh_global_lock);
1505 	PMAP_LOCK(pmap);
1506 	while (m != NULL) {
1507 		va = start + ptoa(m->pindex - m_start->pindex);
1508 		mmu_booke_enter_locked(pmap, va, m,
1509 		    prot & (VM_PROT_READ | VM_PROT_EXECUTE),
1510 		    PMAP_ENTER_NOSLEEP | PMAP_ENTER_QUICK_LOCKED, 0);
1511 		m = vm_radix_iter_step(&pages);
1512 	}
1513 	PMAP_UNLOCK(pmap);
1514 	rw_wunlock(&pvh_global_lock);
1515 }
1516 
1517 static void
mmu_booke_enter_quick(pmap_t pmap,vm_offset_t va,vm_page_t m,vm_prot_t prot)1518 mmu_booke_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m,
1519     vm_prot_t prot)
1520 {
1521 
1522 	rw_wlock(&pvh_global_lock);
1523 	PMAP_LOCK(pmap);
1524 	mmu_booke_enter_locked(pmap, va, m,
1525 	    prot & (VM_PROT_READ | VM_PROT_EXECUTE), PMAP_ENTER_NOSLEEP |
1526 	    PMAP_ENTER_QUICK_LOCKED, 0);
1527 	PMAP_UNLOCK(pmap);
1528 	rw_wunlock(&pvh_global_lock);
1529 }
1530 
1531 /*
1532  * Remove the given range of addresses from the specified map.
1533  *
1534  * It is assumed that the start and end are properly rounded to the page size.
1535  */
1536 static void
mmu_booke_remove(pmap_t pmap,vm_offset_t va,vm_offset_t endva)1537 mmu_booke_remove(pmap_t pmap, vm_offset_t va, vm_offset_t endva)
1538 {
1539 	pte_t *pte;
1540 	uint8_t hold_flag;
1541 
1542 	int su = (pmap == kernel_pmap);
1543 
1544 	//debugf("mmu_booke_remove: s (su = %d pmap=0x%08x tid=%d va=0x%08x endva=0x%08x)\n",
1545 	//		su, (u_int32_t)pmap, pmap->pm_tid, va, endva);
1546 
1547 	if (su) {
1548 		KASSERT(((va >= virtual_avail) &&
1549 		    (va <= VM_MAX_KERNEL_ADDRESS)),
1550 		    ("mmu_booke_remove: kernel pmap, non kernel va"));
1551 	} else {
1552 		KASSERT((va <= VM_MAXUSER_ADDRESS),
1553 		    ("mmu_booke_remove: user pmap, non user va"));
1554 	}
1555 
1556 	if (PMAP_REMOVE_DONE(pmap)) {
1557 		//debugf("mmu_booke_remove: e (empty)\n");
1558 		return;
1559 	}
1560 
1561 	hold_flag = PTBL_HOLD_FLAG(pmap);
1562 	//debugf("mmu_booke_remove: hold_flag = %d\n", hold_flag);
1563 
1564 	rw_wlock(&pvh_global_lock);
1565 	PMAP_LOCK(pmap);
1566 	for (; va < endva; va += PAGE_SIZE) {
1567 		pte = pte_find_next(pmap, &va);
1568 		if ((pte == NULL) || !PTE_ISVALID(pte))
1569 			break;
1570 		if (va >= endva)
1571 			break;
1572 		pte_remove(pmap, va, hold_flag);
1573 	}
1574 	PMAP_UNLOCK(pmap);
1575 	rw_wunlock(&pvh_global_lock);
1576 
1577 	//debugf("mmu_booke_remove: e\n");
1578 }
1579 
1580 /*
1581  * Remove physical page from all pmaps in which it resides.
1582  */
1583 static void
mmu_booke_remove_all(vm_page_t m)1584 mmu_booke_remove_all(vm_page_t m)
1585 {
1586 	pv_entry_t pv, pvn;
1587 	uint8_t hold_flag;
1588 
1589 	rw_wlock(&pvh_global_lock);
1590 	TAILQ_FOREACH_SAFE(pv, &m->md.pv_list, pv_link, pvn) {
1591 		PMAP_LOCK(pv->pv_pmap);
1592 		hold_flag = PTBL_HOLD_FLAG(pv->pv_pmap);
1593 		pte_remove(pv->pv_pmap, pv->pv_va, hold_flag);
1594 		PMAP_UNLOCK(pv->pv_pmap);
1595 	}
1596 	vm_page_aflag_clear(m, PGA_WRITEABLE);
1597 	rw_wunlock(&pvh_global_lock);
1598 }
1599 
1600 /*
1601  * Map a range of physical addresses into kernel virtual address space.
1602  */
1603 static void *
mmu_booke_map(vm_offset_t * virt,vm_paddr_t pa_start,vm_paddr_t pa_end,int prot)1604 mmu_booke_map(vm_offset_t *virt, vm_paddr_t pa_start,
1605     vm_paddr_t pa_end, int prot)
1606 {
1607 	vm_offset_t sva = *virt;
1608 	vm_offset_t va = sva;
1609 
1610 #ifdef __powerpc64__
1611 	/* XXX: Handle memory not starting at 0x0. */
1612 	if (pa_end < ctob(Maxmem))
1613 		return (PHYS_TO_DMAP(pa_start));
1614 #endif
1615 
1616 	while (pa_start < pa_end) {
1617 		mmu_booke_kenter(va, pa_start);
1618 		va += PAGE_SIZE;
1619 		pa_start += PAGE_SIZE;
1620 	}
1621 	*virt = va;
1622 
1623 	return ((void *)sva);
1624 }
1625 
1626 /*
1627  * The pmap must be activated before it's address space can be accessed in any
1628  * way.
1629  */
1630 static void
mmu_booke_activate(struct thread * td)1631 mmu_booke_activate(struct thread *td)
1632 {
1633 	pmap_t pmap;
1634 	u_int cpuid;
1635 
1636 	pmap = &td->td_proc->p_vmspace->vm_pmap;
1637 
1638 	CTR5(KTR_PMAP, "%s: s (td = %p, proc = '%s', id = %d, pmap = 0x%"PRI0ptrX")",
1639 	    __func__, td, td->td_proc->p_comm, td->td_proc->p_pid, pmap);
1640 
1641 	KASSERT((pmap != kernel_pmap), ("mmu_booke_activate: kernel_pmap!"));
1642 
1643 	sched_pin();
1644 
1645 	cpuid = PCPU_GET(cpuid);
1646 	CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
1647 	PCPU_SET(curpmap, pmap);
1648 
1649 	/*
1650 	 * pm_tid is only a hint: another pmap may have stolen the TID since we
1651 	 * last ran here, in which case tidbusy[] no longer names us.
1652 	 */
1653 	if (pmap->pm_tid[cpuid] == TID_NONE ||
1654 	    tid_get_busy(cpuid, pmap->pm_tid[cpuid]) != pmap)
1655 		tid_alloc(pmap);
1656 
1657 	/* Load PID0 register with pmap tid value. */
1658 	mtspr(SPR_PID0, pmap->pm_tid[cpuid]);
1659 	__asm __volatile("isync");
1660 
1661 	mtspr(SPR_DBCR0, td->td_pcb->pcb_cpu.booke.dbcr0);
1662 
1663 	sched_unpin();
1664 
1665 	CTR3(KTR_PMAP, "%s: e (tid = %d for '%s')", __func__,
1666 	    pmap->pm_tid[PCPU_GET(cpuid)], td->td_proc->p_comm);
1667 }
1668 
1669 /*
1670  * Deactivate the specified process's address space.
1671  */
1672 static void
mmu_booke_deactivate(struct thread * td)1673 mmu_booke_deactivate(struct thread *td)
1674 {
1675 	pmap_t pmap;
1676 
1677 	pmap = &td->td_proc->p_vmspace->vm_pmap;
1678 
1679 	CTR5(KTR_PMAP, "%s: td=%p, proc = '%s', id = %d, pmap = 0x%"PRI0ptrX,
1680 	    __func__, td, td->td_proc->p_comm, td->td_proc->p_pid, pmap);
1681 
1682 	td->td_pcb->pcb_cpu.booke.dbcr0 = mfspr(SPR_DBCR0);
1683 
1684 	CPU_CLR_ATOMIC(PCPU_GET(cpuid), &pmap->pm_active);
1685 	PCPU_SET(curpmap, NULL);
1686 }
1687 
1688 /*
1689  * Copy the range specified by src_addr/len
1690  * from the source map to the range dst_addr/len
1691  * in the destination map.
1692  *
1693  * This routine is only advisory and need not do anything.
1694  */
1695 static void
mmu_booke_copy(pmap_t dst_pmap,pmap_t src_pmap,vm_offset_t dst_addr,vm_size_t len,vm_offset_t src_addr)1696 mmu_booke_copy(pmap_t dst_pmap, pmap_t src_pmap,
1697     vm_offset_t dst_addr, vm_size_t len, vm_offset_t src_addr)
1698 {
1699 
1700 }
1701 
1702 /*
1703  * Set the physical protection on the specified range of this map as requested.
1704  */
1705 static void
mmu_booke_protect(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,vm_prot_t prot)1706 mmu_booke_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
1707     vm_prot_t prot)
1708 {
1709 	vm_offset_t va;
1710 	vm_page_t m;
1711 	pte_t *pte;
1712 
1713 	if ((prot & VM_PROT_READ) == VM_PROT_NONE) {
1714 		mmu_booke_remove(pmap, sva, eva);
1715 		return;
1716 	}
1717 
1718 	if (prot & VM_PROT_WRITE)
1719 		return;
1720 
1721 	PMAP_LOCK(pmap);
1722 	for (va = sva; va < eva; va += PAGE_SIZE) {
1723 		if ((pte = pte_find(pmap, va)) != NULL) {
1724 			if (PTE_ISVALID(pte)) {
1725 				m = PHYS_TO_VM_PAGE(PTE_PA(pte));
1726 
1727 				mtx_lock_spin(&tlbivax_mutex);
1728 				tlb_miss_lock();
1729 
1730 				/* Handle modified pages. */
1731 				if (PTE_ISMODIFIED(pte) && PTE_ISMANAGED(pte))
1732 					vm_page_dirty(m);
1733 
1734 				tlb0_flush_entry(va);
1735 				*pte &= ~(PTE_UW | PTE_SW | PTE_MODIFIED);
1736 
1737 				tlb_miss_unlock();
1738 				mtx_unlock_spin(&tlbivax_mutex);
1739 			}
1740 		}
1741 	}
1742 	PMAP_UNLOCK(pmap);
1743 }
1744 
1745 /*
1746  * Clear the write and modified bits in each of the given page's mappings.
1747  */
1748 static void
mmu_booke_remove_write(vm_page_t m)1749 mmu_booke_remove_write(vm_page_t m)
1750 {
1751 	pv_entry_t pv;
1752 	pte_t *pte;
1753 
1754 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1755 	    ("mmu_booke_remove_write: page %p is not managed", m));
1756 	vm_page_assert_busied(m);
1757 
1758 	if (!pmap_page_is_write_mapped(m))
1759 	        return;
1760 	rw_wlock(&pvh_global_lock);
1761 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_link) {
1762 		PMAP_LOCK(pv->pv_pmap);
1763 		if ((pte = pte_find(pv->pv_pmap, pv->pv_va)) != NULL) {
1764 			if (PTE_ISVALID(pte)) {
1765 				m = PHYS_TO_VM_PAGE(PTE_PA(pte));
1766 
1767 				mtx_lock_spin(&tlbivax_mutex);
1768 				tlb_miss_lock();
1769 
1770 				/* Handle modified pages. */
1771 				if (PTE_ISMODIFIED(pte))
1772 					vm_page_dirty(m);
1773 
1774 				/* Flush mapping from TLB0. */
1775 				*pte &= ~(PTE_UW | PTE_SW | PTE_MODIFIED);
1776 
1777 				tlb_miss_unlock();
1778 				mtx_unlock_spin(&tlbivax_mutex);
1779 			}
1780 		}
1781 		PMAP_UNLOCK(pv->pv_pmap);
1782 	}
1783 	vm_page_aflag_clear(m, PGA_WRITEABLE);
1784 	rw_wunlock(&pvh_global_lock);
1785 }
1786 
1787 /*
1788  * Atomically extract and hold the physical page with the given
1789  * pmap and virtual address pair if that mapping permits the given
1790  * protection.
1791  */
1792 static vm_page_t
mmu_booke_extract_and_hold(pmap_t pmap,vm_offset_t va,vm_prot_t prot)1793 mmu_booke_extract_and_hold(pmap_t pmap, vm_offset_t va,
1794     vm_prot_t prot)
1795 {
1796 	pte_t *pte;
1797 	vm_page_t m;
1798 	uint32_t pte_wbit;
1799 
1800 	m = NULL;
1801 	PMAP_LOCK(pmap);
1802 	pte = pte_find(pmap, va);
1803 	if ((pte != NULL) && PTE_ISVALID(pte)) {
1804 		if (pmap == kernel_pmap)
1805 			pte_wbit = PTE_SW;
1806 		else
1807 			pte_wbit = PTE_UW;
1808 
1809 		if ((*pte & pte_wbit) != 0 || (prot & VM_PROT_WRITE) == 0) {
1810 			m = PHYS_TO_VM_PAGE(PTE_PA(pte));
1811 			if (!vm_page_wire_mapped(m))
1812 				m = NULL;
1813 		}
1814 	}
1815 	PMAP_UNLOCK(pmap);
1816 	return (m);
1817 }
1818 
1819 /*
1820  * Initialize a vm_page's machine-dependent fields.
1821  */
1822 static void
mmu_booke_page_init(vm_page_t m)1823 mmu_booke_page_init(vm_page_t m)
1824 {
1825 
1826 	m->md.pv_tracked = 0;
1827 	TAILQ_INIT(&m->md.pv_list);
1828 }
1829 
1830 /*
1831  * Return whether or not the specified physical page was modified
1832  * in any of physical maps.
1833  */
1834 static bool
mmu_booke_is_modified(vm_page_t m)1835 mmu_booke_is_modified(vm_page_t m)
1836 {
1837 	pte_t *pte;
1838 	pv_entry_t pv;
1839 	bool rv;
1840 
1841 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1842 	    ("mmu_booke_is_modified: page %p is not managed", m));
1843 	rv = false;
1844 
1845 	/*
1846 	 * If the page is not busied then this check is racy.
1847 	 */
1848 	if (!pmap_page_is_write_mapped(m))
1849 		return (false);
1850 
1851 	rw_wlock(&pvh_global_lock);
1852 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_link) {
1853 		PMAP_LOCK(pv->pv_pmap);
1854 		if ((pte = pte_find(pv->pv_pmap, pv->pv_va)) != NULL &&
1855 		    PTE_ISVALID(pte)) {
1856 			if (PTE_ISMODIFIED(pte))
1857 				rv = true;
1858 		}
1859 		PMAP_UNLOCK(pv->pv_pmap);
1860 		if (rv)
1861 			break;
1862 	}
1863 	rw_wunlock(&pvh_global_lock);
1864 	return (rv);
1865 }
1866 
1867 /*
1868  * Return whether or not the specified virtual address is eligible
1869  * for prefault.
1870  */
1871 static bool
mmu_booke_is_prefaultable(pmap_t pmap,vm_offset_t addr)1872 mmu_booke_is_prefaultable(pmap_t pmap, vm_offset_t addr)
1873 {
1874 
1875 	return (false);
1876 }
1877 
1878 /*
1879  * Return whether or not the specified physical page was referenced
1880  * in any physical maps.
1881  */
1882 static bool
mmu_booke_is_referenced(vm_page_t m)1883 mmu_booke_is_referenced(vm_page_t m)
1884 {
1885 	pte_t *pte;
1886 	pv_entry_t pv;
1887 	bool rv;
1888 
1889 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1890 	    ("mmu_booke_is_referenced: page %p is not managed", m));
1891 	rv = false;
1892 	rw_wlock(&pvh_global_lock);
1893 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_link) {
1894 		PMAP_LOCK(pv->pv_pmap);
1895 		if ((pte = pte_find(pv->pv_pmap, pv->pv_va)) != NULL &&
1896 		    PTE_ISVALID(pte)) {
1897 			if (PTE_ISREFERENCED(pte))
1898 				rv = true;
1899 		}
1900 		PMAP_UNLOCK(pv->pv_pmap);
1901 		if (rv)
1902 			break;
1903 	}
1904 	rw_wunlock(&pvh_global_lock);
1905 	return (rv);
1906 }
1907 
1908 /*
1909  * Clear the modify bits on the specified physical page.
1910  */
1911 static void
mmu_booke_clear_modify(vm_page_t m)1912 mmu_booke_clear_modify(vm_page_t m)
1913 {
1914 	pte_t *pte;
1915 	pv_entry_t pv;
1916 
1917 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1918 	    ("mmu_booke_clear_modify: page %p is not managed", m));
1919 	vm_page_assert_busied(m);
1920 
1921 	if (!pmap_page_is_write_mapped(m))
1922 	        return;
1923 
1924 	rw_wlock(&pvh_global_lock);
1925 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_link) {
1926 		PMAP_LOCK(pv->pv_pmap);
1927 		if ((pte = pte_find(pv->pv_pmap, pv->pv_va)) != NULL &&
1928 		    PTE_ISVALID(pte)) {
1929 			mtx_lock_spin(&tlbivax_mutex);
1930 			tlb_miss_lock();
1931 
1932 			if (*pte & (PTE_SW | PTE_UW | PTE_MODIFIED)) {
1933 				tlb0_flush_entry(pv->pv_va);
1934 				*pte &= ~(PTE_SW | PTE_UW | PTE_MODIFIED |
1935 				    PTE_REFERENCED);
1936 			}
1937 
1938 			tlb_miss_unlock();
1939 			mtx_unlock_spin(&tlbivax_mutex);
1940 		}
1941 		PMAP_UNLOCK(pv->pv_pmap);
1942 	}
1943 	rw_wunlock(&pvh_global_lock);
1944 }
1945 
1946 /*
1947  * Return a count of reference bits for a page, clearing those bits.
1948  * It is not necessary for every reference bit to be cleared, but it
1949  * is necessary that 0 only be returned when there are truly no
1950  * reference bits set.
1951  *
1952  * As an optimization, update the page's dirty field if a modified bit is
1953  * found while counting reference bits.  This opportunistic update can be
1954  * performed at low cost and can eliminate the need for some future calls
1955  * to pmap_is_modified().  However, since this function stops after
1956  * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
1957  * dirty pages.  Those dirty pages will only be detected by a future call
1958  * to pmap_is_modified().
1959  */
1960 static int
mmu_booke_ts_referenced(vm_page_t m)1961 mmu_booke_ts_referenced(vm_page_t m)
1962 {
1963 	pte_t *pte;
1964 	pv_entry_t pv;
1965 	int count;
1966 
1967 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1968 	    ("mmu_booke_ts_referenced: page %p is not managed", m));
1969 	count = 0;
1970 	rw_wlock(&pvh_global_lock);
1971 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_link) {
1972 		PMAP_LOCK(pv->pv_pmap);
1973 		if ((pte = pte_find(pv->pv_pmap, pv->pv_va)) != NULL &&
1974 		    PTE_ISVALID(pte)) {
1975 			if (PTE_ISMODIFIED(pte))
1976 				vm_page_dirty(m);
1977 			if (PTE_ISREFERENCED(pte)) {
1978 				mtx_lock_spin(&tlbivax_mutex);
1979 				tlb_miss_lock();
1980 
1981 				tlb0_flush_entry(pv->pv_va);
1982 				*pte &= ~PTE_REFERENCED;
1983 
1984 				tlb_miss_unlock();
1985 				mtx_unlock_spin(&tlbivax_mutex);
1986 
1987 				if (++count >= PMAP_TS_REFERENCED_MAX) {
1988 					PMAP_UNLOCK(pv->pv_pmap);
1989 					break;
1990 				}
1991 			}
1992 		}
1993 		PMAP_UNLOCK(pv->pv_pmap);
1994 	}
1995 	rw_wunlock(&pvh_global_lock);
1996 	return (count);
1997 }
1998 
1999 /*
2000  * Clear the wired attribute from the mappings for the specified range of
2001  * addresses in the given pmap.  Every valid mapping within that range must
2002  * have the wired attribute set.  In contrast, invalid mappings cannot have
2003  * the wired attribute set, so they are ignored.
2004  *
2005  * The wired attribute of the page table entry is not a hardware feature, so
2006  * there is no need to invalidate any TLB entries.
2007  */
2008 static void
mmu_booke_unwire(pmap_t pmap,vm_offset_t sva,vm_offset_t eva)2009 mmu_booke_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
2010 {
2011 	vm_offset_t va;
2012 	pte_t *pte;
2013 
2014 	PMAP_LOCK(pmap);
2015 	for (va = sva; va < eva; va += PAGE_SIZE) {
2016 		if ((pte = pte_find(pmap, va)) != NULL &&
2017 		    PTE_ISVALID(pte)) {
2018 			if (!PTE_ISWIRED(pte))
2019 				panic("mmu_booke_unwire: pte %p isn't wired",
2020 				    pte);
2021 			*pte &= ~PTE_WIRED;
2022 			pmap->pm_stats.wired_count--;
2023 		}
2024 	}
2025 	PMAP_UNLOCK(pmap);
2026 
2027 }
2028 
2029 /*
2030  * Return true if the pmap's pv is one of the first 16 pvs linked to from this
2031  * page.  This count may be changed upwards or downwards in the future; it is
2032  * only necessary that true be returned for a small subset of pmaps for proper
2033  * page aging.
2034  */
2035 static bool
mmu_booke_page_exists_quick(pmap_t pmap,vm_page_t m)2036 mmu_booke_page_exists_quick(pmap_t pmap, vm_page_t m)
2037 {
2038 	pv_entry_t pv;
2039 	int loops;
2040 	bool rv;
2041 
2042 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
2043 	    ("mmu_booke_page_exists_quick: page %p is not managed", m));
2044 	loops = 0;
2045 	rv = false;
2046 	rw_wlock(&pvh_global_lock);
2047 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_link) {
2048 		if (pv->pv_pmap == pmap) {
2049 			rv = true;
2050 			break;
2051 		}
2052 		if (++loops >= 16)
2053 			break;
2054 	}
2055 	rw_wunlock(&pvh_global_lock);
2056 	return (rv);
2057 }
2058 
2059 /*
2060  * Return the number of managed mappings to the given physical page that are
2061  * wired.
2062  */
2063 static int
mmu_booke_page_wired_mappings(vm_page_t m)2064 mmu_booke_page_wired_mappings(vm_page_t m)
2065 {
2066 	pv_entry_t pv;
2067 	pte_t *pte;
2068 	int count = 0;
2069 
2070 	if ((m->oflags & VPO_UNMANAGED) != 0)
2071 		return (count);
2072 	rw_wlock(&pvh_global_lock);
2073 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_link) {
2074 		PMAP_LOCK(pv->pv_pmap);
2075 		if ((pte = pte_find(pv->pv_pmap, pv->pv_va)) != NULL)
2076 			if (PTE_ISVALID(pte) && PTE_ISWIRED(pte))
2077 				count++;
2078 		PMAP_UNLOCK(pv->pv_pmap);
2079 	}
2080 	rw_wunlock(&pvh_global_lock);
2081 	return (count);
2082 }
2083 
2084 static int
mmu_booke_dev_direct_mapped(vm_paddr_t pa,vm_size_t size)2085 mmu_booke_dev_direct_mapped(vm_paddr_t pa, vm_size_t size)
2086 {
2087 	int i;
2088 	vm_offset_t va;
2089 
2090 	/*
2091 	 * This currently does not work for entries that
2092 	 * overlap TLB1 entries.
2093 	 */
2094 	for (i = 0; i < TLB1_ENTRIES; i ++) {
2095 		if (tlb1_iomapped(i, pa, size, &va) == 0)
2096 			return (0);
2097 	}
2098 
2099 	return (EFAULT);
2100 }
2101 
2102 void
mmu_booke_dumpsys_map(vm_paddr_t pa,size_t sz,void ** va)2103 mmu_booke_dumpsys_map(vm_paddr_t pa, size_t sz, void **va)
2104 {
2105 	vm_paddr_t ppa;
2106 	vm_offset_t ofs;
2107 	vm_size_t gran;
2108 
2109 	/* Minidumps are based on virtual memory addresses. */
2110 	if (do_minidump) {
2111 		*va = (void *)(vm_offset_t)pa;
2112 		return;
2113 	}
2114 
2115 	/* Raw physical memory dumps don't have a virtual address. */
2116 	/* We always map a 256MB page at 256M. */
2117 	gran = 256 * 1024 * 1024;
2118 	ppa = rounddown2(pa, gran);
2119 	ofs = pa - ppa;
2120 	*va = (void *)gran;
2121 	tlb1_set_entry((vm_offset_t)va, ppa, gran, _TLB_ENTRY_IO);
2122 
2123 	if (sz > (gran - ofs))
2124 		tlb1_set_entry((vm_offset_t)(va + gran), ppa + gran, gran,
2125 		    _TLB_ENTRY_IO);
2126 }
2127 
2128 void
mmu_booke_dumpsys_unmap(vm_paddr_t pa,size_t sz,void * va)2129 mmu_booke_dumpsys_unmap(vm_paddr_t pa, size_t sz, void *va)
2130 {
2131 	vm_paddr_t ppa;
2132 	vm_offset_t ofs;
2133 	vm_size_t gran;
2134 	tlb_entry_t e;
2135 	int i;
2136 
2137 	/* Minidumps are based on virtual memory addresses. */
2138 	/* Nothing to do... */
2139 	if (do_minidump)
2140 		return;
2141 
2142 	for (i = 0; i < TLB1_ENTRIES; i++) {
2143 		tlb1_read_entry(&e, i);
2144 		if (!(e.mas1 & MAS1_VALID))
2145 			break;
2146 	}
2147 
2148 	/* Raw physical memory dumps don't have a virtual address. */
2149 	i--;
2150 	e.mas1 = 0;
2151 	e.mas2 = 0;
2152 	e.mas3 = 0;
2153 	tlb1_write_entry(&e, i);
2154 
2155 	gran = 256 * 1024 * 1024;
2156 	ppa = rounddown2(pa, gran);
2157 	ofs = pa - ppa;
2158 	if (sz > (gran - ofs)) {
2159 		i--;
2160 		e.mas1 = 0;
2161 		e.mas2 = 0;
2162 		e.mas3 = 0;
2163 		tlb1_write_entry(&e, i);
2164 	}
2165 }
2166 
2167 extern struct dump_pa dump_map[PHYS_AVAIL_SZ + 1];
2168 
2169 void
mmu_booke_scan_init(void)2170 mmu_booke_scan_init(void)
2171 {
2172 	vm_offset_t va;
2173 	pte_t *pte;
2174 	int i;
2175 
2176 	if (!do_minidump) {
2177 		/* Initialize phys. segments for dumpsys(). */
2178 		memset(&dump_map, 0, sizeof(dump_map));
2179 		mem_regions(&physmem_regions, &physmem_regions_sz, &availmem_regions,
2180 		    &availmem_regions_sz);
2181 		for (i = 0; i < physmem_regions_sz; i++) {
2182 			dump_map[i].pa_start = physmem_regions[i].mr_start;
2183 			dump_map[i].pa_size = physmem_regions[i].mr_size;
2184 		}
2185 		return;
2186 	}
2187 
2188 	/* Virtual segments for minidumps: */
2189 	memset(&dump_map, 0, sizeof(dump_map));
2190 
2191 	/* 1st: kernel .data and .bss. */
2192 	dump_map[0].pa_start = trunc_page((uintptr_t)_etext);
2193 	dump_map[0].pa_size =
2194 	    round_page((uintptr_t)_end) - dump_map[0].pa_start;
2195 
2196 	/* 2nd: msgbuf and tables (see pmap_bootstrap()). */
2197 	dump_map[1].pa_start = data_start;
2198 	dump_map[1].pa_size = data_end - data_start;
2199 
2200 	/* 3rd: kernel VM. */
2201 	va = dump_map[1].pa_start + dump_map[1].pa_size;
2202 	/* Find start of next chunk (from va). */
2203 	while (va < virtual_end) {
2204 		/* Don't dump the buffer cache. */
2205 		if (va >= kmi.buffer_sva && va < kmi.buffer_eva) {
2206 			va = kmi.buffer_eva;
2207 			continue;
2208 		}
2209 		pte = pte_find(kernel_pmap, va);
2210 		if (pte != NULL && PTE_ISVALID(pte))
2211 			break;
2212 		va += PAGE_SIZE;
2213 	}
2214 	if (va < virtual_end) {
2215 		dump_map[2].pa_start = va;
2216 		va += PAGE_SIZE;
2217 		/* Find last page in chunk. */
2218 		while (va < virtual_end) {
2219 			/* Don't run into the buffer cache. */
2220 			if (va == kmi.buffer_sva)
2221 				break;
2222 			pte = pte_find(kernel_pmap, va);
2223 			if (pte == NULL || !PTE_ISVALID(pte))
2224 				break;
2225 			va += PAGE_SIZE;
2226 		}
2227 		dump_map[2].pa_size = va - dump_map[2].pa_start;
2228 	}
2229 }
2230 
2231 /*
2232  * Map a set of physical memory pages into the kernel virtual address space.
2233  * Return a pointer to where it is mapped. This routine is intended to be used
2234  * for mapping device memory, NOT real memory.
2235  */
2236 static void *
mmu_booke_mapdev(vm_paddr_t pa,vm_size_t size)2237 mmu_booke_mapdev(vm_paddr_t pa, vm_size_t size)
2238 {
2239 
2240 	return (mmu_booke_mapdev_attr(pa, size, VM_MEMATTR_DEFAULT));
2241 }
2242 
2243 static int
tlb1_find_pa(vm_paddr_t pa,tlb_entry_t * e)2244 tlb1_find_pa(vm_paddr_t pa, tlb_entry_t *e)
2245 {
2246 	int i;
2247 
2248 	for (i = 0; i < TLB1_ENTRIES; i++) {
2249 		tlb1_read_entry(e, i);
2250 		if ((e->mas1 & MAS1_VALID) == 0)
2251 			continue;
2252 		if (e->phys == pa)
2253 			return (i);
2254 	}
2255 	return (-1);
2256 }
2257 
2258 static void *
mmu_booke_mapdev_attr(vm_paddr_t pa,vm_size_t size,vm_memattr_t ma)2259 mmu_booke_mapdev_attr(vm_paddr_t pa, vm_size_t size, vm_memattr_t ma)
2260 {
2261 	tlb_entry_t e;
2262 	vm_paddr_t tmppa;
2263 #ifndef __powerpc64__
2264 	uintptr_t tmpva;
2265 #endif
2266 	uintptr_t va, retva;
2267 	vm_size_t sz;
2268 	int i;
2269 	int wimge;
2270 
2271 	/*
2272 	 * Check if this is premapped in TLB1.
2273 	 */
2274 	sz = size;
2275 	tmppa = pa;
2276 	va = ~0;
2277 	wimge = tlb_calc_wimg(pa, ma);
2278 	for (i = 0; i < TLB1_ENTRIES; i++) {
2279 		tlb1_read_entry(&e, i);
2280 		if (!(e.mas1 & MAS1_VALID))
2281 			continue;
2282 		if (wimge != (e.mas2 & (MAS2_WIMGE_MASK & ~_TLB_ENTRY_SHARED)))
2283 			continue;
2284 		if (tmppa >= e.phys && tmppa < e.phys + e.size) {
2285 			va = e.virt + (pa - e.phys);
2286 			tmppa = e.phys + e.size;
2287 			sz -= MIN(sz, e.size - (pa - e.phys));
2288 			while (sz > 0 && (i = tlb1_find_pa(tmppa, &e)) != -1) {
2289 				if (wimge != (e.mas2 & (MAS2_WIMGE_MASK & ~_TLB_ENTRY_SHARED)))
2290 					break;
2291 				sz -= MIN(sz, e.size);
2292 				tmppa = e.phys + e.size;
2293 			}
2294 			if (sz != 0)
2295 				break;
2296 			return ((void *)va);
2297 		}
2298 	}
2299 
2300 	size = roundup(size, PAGE_SIZE);
2301 
2302 #ifdef __powerpc64__
2303 	KASSERT(pa < VM_MAPDEV_PA_MAX,
2304 	    ("Unsupported physical address! %lx", pa));
2305 	va = VM_MAPDEV_BASE + pa;
2306 	retva = va;
2307 #ifdef POW2_MAPPINGS
2308 	/*
2309 	 * Align the mapping to a power of 2 size, taking into account that we
2310 	 * may need to increase the size multiple times to satisfy the size and
2311 	 * alignment requirements.
2312 	 *
2313 	 * This works in the general case because it's very rare (near never?)
2314 	 * to have different access properties (WIMG) within a single
2315 	 * power-of-two region.  If a design does call for that, POW2_MAPPINGS
2316 	 * can be undefined, and exact mappings will be used instead.
2317 	 */
2318 	sz = size;
2319 	size = roundup2(size, 1 << ilog2(size));
2320 	while (rounddown2(va, size) + size < va + sz)
2321 		size <<= 1;
2322 	va = rounddown2(va, size);
2323 	pa = rounddown2(pa, size);
2324 #endif
2325 #else
2326 	/*
2327 	 * The device mapping area is between VM_MAXUSER_ADDRESS and
2328 	 * VM_MIN_KERNEL_ADDRESS.  This gives 1GB of device addressing.
2329 	 */
2330 #ifdef SPARSE_MAPDEV
2331 	/*
2332 	 * With a sparse mapdev, align to the largest starting region.  This
2333 	 * could feasibly be optimized for a 'best-fit' alignment, but that
2334 	 * calculation could be very costly.
2335 	 * Align to the smaller of:
2336 	 * - first set bit in overlap of (pa & size mask)
2337 	 * - largest size envelope
2338 	 *
2339 	 * It's possible the device mapping may start at a PA that's not larger
2340 	 * than the size mask, so we need to offset in to maximize the TLB entry
2341 	 * range and minimize the number of used TLB entries.
2342 	 */
2343 	do {
2344 	    tmpva = tlb1_map_base;
2345 	    sz = ffsl((~((1 << flsl(size-1)) - 1)) & pa);
2346 	    sz = sz ? min(roundup(sz + 3, 4), flsl(size) - 1) : flsl(size) - 1;
2347 	    va = roundup(tlb1_map_base, 1 << sz) | (((1 << sz) - 1) & pa);
2348 	} while (!atomic_cmpset_int(&tlb1_map_base, tmpva, va + size));
2349 #endif
2350 	va = atomic_fetchadd_int(&tlb1_map_base, size);
2351 	retva = va;
2352 #endif
2353 
2354 	if (tlb1_mapin_region(va, pa, size, tlb_calc_wimg(pa, ma)) != size)
2355 		return (NULL);
2356 
2357 	return ((void *)retva);
2358 }
2359 
2360 /*
2361  * 'Unmap' a range mapped by mmu_booke_mapdev().
2362  */
2363 static void
mmu_booke_unmapdev(void * p,vm_size_t size)2364 mmu_booke_unmapdev(void *p, vm_size_t size)
2365 {
2366 #ifdef SUPPORTS_SHRINKING_TLB1
2367 	void *base;
2368 	vm_offset_t offset, va;
2369 
2370 	/*
2371 	 * Unmap only if this is inside kernel virtual space.
2372 	 */
2373 	va = (vm_offset_t)p;
2374 	if ((va >= VM_MIN_KERNEL_ADDRESS) && (va <= VM_MAX_KERNEL_ADDRESS)) {
2375 		base = trunc_page(va);
2376 		offset = va & PAGE_MASK;
2377 		size = roundup(offset + size, PAGE_SIZE);
2378 		mmu_booke_qremove(base, atop(size));
2379 		kva_free((vm_offset_t)base, size);
2380 	}
2381 #endif
2382 }
2383 
2384 /*
2385  * mmu_booke_object_init_pt preloads the ptes for a given object into the
2386  * specified pmap. This eliminates the blast of soft faults on process startup
2387  * and immediately after an mmap.
2388  */
2389 static void
mmu_booke_object_init_pt(pmap_t pmap,vm_offset_t addr,vm_object_t object,vm_pindex_t pindex,vm_size_t size)2390 mmu_booke_object_init_pt(pmap_t pmap, vm_offset_t addr,
2391     vm_object_t object, vm_pindex_t pindex, vm_size_t size)
2392 {
2393 
2394 	VM_OBJECT_ASSERT_WLOCKED(object);
2395 	KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
2396 	    ("mmu_booke_object_init_pt: non-device object"));
2397 }
2398 
2399 /*
2400  * Perform the pmap work for mincore.
2401  */
2402 static int
mmu_booke_mincore(pmap_t pmap,vm_offset_t addr,vm_paddr_t * pap)2403 mmu_booke_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *pap)
2404 {
2405 
2406 	/* XXX: this should be implemented at some point */
2407 	return (0);
2408 }
2409 
2410 static int
mmu_booke_change_attr(void * sva,vm_size_t sz,vm_memattr_t mode)2411 mmu_booke_change_attr(void *sva, vm_size_t sz, vm_memattr_t mode)
2412 {
2413 	vm_offset_t addr, va;
2414 	pte_t *pte;
2415 	int i, j;
2416 	tlb_entry_t e;
2417 
2418 	addr = (vm_offset_t)sva;
2419 	addr = trunc_page(addr);
2420 
2421 	/* Only allow changes to mapped kernel addresses.  This includes:
2422 	 * - KVA
2423 	 * - DMAP (powerpc64)
2424 	 * - Device mappings
2425 	 */
2426 	if (addr <= VM_MAXUSER_ADDRESS ||
2427 #ifdef __powerpc64__
2428 	    (addr >= tlb1_map_base && addr < DMAP_BASE_ADDRESS) ||
2429 	    (addr > DMAP_MAX_ADDRESS && addr < VM_MIN_KERNEL_ADDRESS) ||
2430 #else
2431 	    (addr >= tlb1_map_base && addr < VM_MIN_KERNEL_ADDRESS) ||
2432 #endif
2433 	    (addr > VM_MAX_KERNEL_ADDRESS))
2434 		return (EINVAL);
2435 
2436 	/* Check TLB1 mappings */
2437 	for (i = 0; i < TLB1_ENTRIES; i++) {
2438 		tlb1_read_entry(&e, i);
2439 		if (!(e.mas1 & MAS1_VALID))
2440 			continue;
2441 		if (addr >= e.virt && addr < e.virt + e.size)
2442 			break;
2443 	}
2444 	if (i < TLB1_ENTRIES) {
2445 		/* Only allow full mappings to be modified for now. */
2446 		/* Validate the range. */
2447 		for (j = i, va = addr; va < addr + sz; va += e.size, j++) {
2448 			tlb1_read_entry(&e, j);
2449 			if (va != e.virt || (sz - (va - addr) < e.size))
2450 				return (EINVAL);
2451 		}
2452 		for (va = addr; va < addr + sz; va += e.size, i++) {
2453 			tlb1_read_entry(&e, i);
2454 			e.mas2 &= ~MAS2_WIMGE_MASK;
2455 			e.mas2 |= tlb_calc_wimg(e.phys, mode);
2456 
2457 			/*
2458 			 * Write it out to the TLB.  Should really re-sync with other
2459 			 * cores.
2460 			 */
2461 			tlb1_write_entry(&e, i);
2462 		}
2463 		return (0);
2464 	}
2465 
2466 	/* Not in TLB1, try through pmap */
2467 	/* First validate the range. */
2468 	for (va = addr; va < addr + sz; va += PAGE_SIZE) {
2469 		pte = pte_find(kernel_pmap, va);
2470 		if (pte == NULL || !PTE_ISVALID(pte))
2471 			return (EINVAL);
2472 	}
2473 
2474 	mtx_lock_spin(&tlbivax_mutex);
2475 	tlb_miss_lock();
2476 	for (va = addr; va < addr + sz; va += PAGE_SIZE) {
2477 		pte = pte_find(kernel_pmap, va);
2478 		*pte &= ~(PTE_MAS2_MASK << PTE_MAS2_SHIFT);
2479 		*pte |= tlb_calc_wimg(PTE_PA(pte), mode) << PTE_MAS2_SHIFT;
2480 		tlb0_flush_entry(va);
2481 	}
2482 	tlb_miss_unlock();
2483 	mtx_unlock_spin(&tlbivax_mutex);
2484 
2485 	return (0);
2486 }
2487 
2488 static void
mmu_booke_page_array_startup(long pages)2489 mmu_booke_page_array_startup(long pages)
2490 {
2491 	vm_page_array_size = pages;
2492 }
2493 
2494 /**************************************************************************/
2495 /* TID handling */
2496 /**************************************************************************/
2497 
2498 /*
2499  * tidbusy[] is the authoritative record of TID ownership; pm_tid is only a
2500  * hint, validated against it by mmu_booke_activate().  Only the pointer
2501  * matters, it's never dereferenced.
2502  */
2503 static __inline void
tid_set_busy(int cpu,int tid,pmap_t pmap)2504 tid_set_busy(int cpu, int tid, pmap_t pmap)
2505 {
2506 	tidbusy[cpu * (tid_max + 1) + tid] = pmap;
2507 }
2508 
2509 static __inline pmap_t
tid_get_busy(int cpu,int tid)2510 tid_get_busy(int cpu, int tid)
2511 {
2512 	return (tidbusy[cpu * (tid_max + 1) + tid]);
2513 }
2514 
2515 /*
2516  * Allocate a TID. If necessary, steal one from someone else.
2517  * The new TID is flushed from the TLB before returning.
2518  */
2519 static tlbtid_t
tid_alloc(pmap_t pmap)2520 tid_alloc(pmap_t pmap)
2521 {
2522 	tlbtid_t tid;
2523 	int thiscpu;
2524 
2525 	KASSERT((pmap != kernel_pmap), ("tid_alloc: kernel pmap"));
2526 
2527 	CTR2(KTR_PMAP, "%s: s (pmap = %p)", __func__, pmap);
2528 
2529 	thiscpu = PCPU_GET(cpuid);
2530 
2531 	tid = PCPU_GET(booke.tid_next);
2532 	/* tid_max is always a power-of-2-minus-1, so check for overflow. */
2533 	if ((tid & ~tid_max) != 0)
2534 		tid = TID_MIN;
2535 	PCPU_SET(booke.tid_next, tid + 1);
2536 
2537 	/*
2538 	 * If we are stealing the TID, drop the previous owner's translations.
2539 	 */
2540 	if (tid_get_busy(thiscpu, tid) != NULL) {
2541 		CTR2(KTR_PMAP, "%s: warning: stealing tid %d", __func__, tid);
2542 
2543 		/* Flush all entries from TLB0 matching this TID. */
2544 		tid_flush(tid);
2545 	}
2546 
2547 	tid_set_busy(thiscpu, tid, pmap);
2548 	pmap->pm_tid[thiscpu] = tid;
2549 	__asm __volatile("msync; isync");
2550 
2551 	CTR3(KTR_PMAP, "%s: e (%02d next = %02d)", __func__, tid,
2552 	    PCPU_GET(booke.tid_next));
2553 
2554 	return (tid);
2555 }
2556 
2557 /**************************************************************************/
2558 /* TLB0 handling */
2559 /**************************************************************************/
2560 
2561 /* Convert TLB0 va and way number to tlb0[] table index. */
2562 static inline unsigned int
tlb0_tableidx(vm_offset_t va,unsigned int way)2563 tlb0_tableidx(vm_offset_t va, unsigned int way)
2564 {
2565 	unsigned int idx;
2566 
2567 	idx = (way * TLB0_ENTRIES_PER_WAY);
2568 	idx += (va & MAS2_TLB0_ENTRY_IDX_MASK) >> MAS2_TLB0_ENTRY_IDX_SHIFT;
2569 	return (idx);
2570 }
2571 
2572 /*
2573  * Invalidate TLB0 entry.
2574  */
2575 static inline void
tlb0_flush_entry(vm_offset_t va)2576 tlb0_flush_entry(vm_offset_t va)
2577 {
2578 
2579 	CTR2(KTR_PMAP, "%s: s va=0x%08x", __func__, va);
2580 
2581 	mtx_assert(&tlbivax_mutex, MA_OWNED);
2582 
2583 	__asm __volatile("tlbivax 0, %0" :: "r"(va & MAS2_EPN_MASK));
2584 	__asm __volatile("isync; msync");
2585 	__asm __volatile("tlbsync; msync");
2586 
2587 	CTR1(KTR_PMAP, "%s: e", __func__);
2588 }
2589 
2590 /**************************************************************************/
2591 /* TLB1 handling */
2592 /**************************************************************************/
2593 
2594 /*
2595  * TLB1 mapping notes:
2596  *
2597  * TLB1[0]	Kernel text and data.
2598  * TLB1[1-15]	Additional kernel text and data mappings (if required), PCI
2599  *		windows, other devices mappings.
2600  */
2601 
2602  /*
2603  * Read an entry from given TLB1 slot.
2604  */
2605 void
tlb1_read_entry(tlb_entry_t * entry,unsigned int slot)2606 tlb1_read_entry(tlb_entry_t *entry, unsigned int slot)
2607 {
2608 	register_t msr;
2609 	uint32_t mas0;
2610 
2611 	KASSERT((entry != NULL), ("%s(): Entry is NULL!", __func__));
2612 
2613 	msr = mfmsr();
2614 	__asm __volatile("wrteei 0");
2615 
2616 	mas0 = MAS0_TLBSEL(1) | MAS0_ESEL(slot);
2617 	mtspr(SPR_MAS0, mas0);
2618 	__asm __volatile("isync; tlbre");
2619 
2620 	entry->mas1 = mfspr(SPR_MAS1);
2621 	entry->mas2 = mfspr(SPR_MAS2);
2622 	entry->mas3 = mfspr(SPR_MAS3);
2623 
2624 	switch ((mfpvr() >> 16) & 0xFFFF) {
2625 	case FSL_E500v2:
2626 	case FSL_E500mc:
2627 	case FSL_E5500:
2628 	case FSL_E6500:
2629 		entry->mas7 = mfspr(SPR_MAS7);
2630 		break;
2631 	default:
2632 		entry->mas7 = 0;
2633 		break;
2634 	}
2635 	__asm __volatile("wrtee %0" :: "r"(msr));
2636 
2637 	entry->virt = entry->mas2 & MAS2_EPN_MASK;
2638 	entry->phys = ((vm_paddr_t)(entry->mas7 & MAS7_RPN) << 32) |
2639 	    (entry->mas3 & MAS3_RPN);
2640 	entry->size =
2641 	    tsize2size((entry->mas1 & MAS1_TSIZE_MASK) >> MAS1_TSIZE_SHIFT);
2642 }
2643 
2644 struct tlbwrite_args {
2645 	tlb_entry_t *e;
2646 	unsigned int idx;
2647 };
2648 
2649 static uint32_t
tlb1_find_free(void)2650 tlb1_find_free(void)
2651 {
2652 	tlb_entry_t e;
2653 	int i;
2654 
2655 	for (i = 0; i < TLB1_ENTRIES; i++) {
2656 		tlb1_read_entry(&e, i);
2657 		if ((e.mas1 & MAS1_VALID) == 0)
2658 			return (i);
2659 	}
2660 	return (-1);
2661 }
2662 
2663 static void
tlb1_purge_va_range(vm_offset_t va,vm_size_t size)2664 tlb1_purge_va_range(vm_offset_t va, vm_size_t size)
2665 {
2666 	tlb_entry_t e;
2667 	int i;
2668 
2669 	for (i = 0; i < TLB1_ENTRIES; i++) {
2670 		tlb1_read_entry(&e, i);
2671 		if ((e.mas1 & MAS1_VALID) == 0)
2672 			continue;
2673 		if ((e.mas2 & MAS2_EPN_MASK) >= va &&
2674 		    (e.mas2 & MAS2_EPN_MASK) < va + size) {
2675 			mtspr(SPR_MAS1, e.mas1 & ~MAS1_VALID);
2676 			__asm __volatile("isync; tlbwe; isync; msync");
2677 		}
2678 	}
2679 }
2680 
2681 static void
tlb1_write_entry_int(void * arg)2682 tlb1_write_entry_int(void *arg)
2683 {
2684 	struct tlbwrite_args *args = arg;
2685 	uint32_t idx, mas0;
2686 
2687 	idx = args->idx;
2688 	if (idx == -1) {
2689 		tlb1_purge_va_range(args->e->virt, args->e->size);
2690 		idx = tlb1_find_free();
2691 		if (idx == -1)
2692 			panic("No free TLB1 entries!\n");
2693 	}
2694 	/* Select entry */
2695 	mas0 = MAS0_TLBSEL(1) | MAS0_ESEL(idx);
2696 
2697 	mtspr(SPR_MAS0, mas0);
2698 	mtspr(SPR_MAS1, args->e->mas1);
2699 	mtspr(SPR_MAS2, args->e->mas2);
2700 	mtspr(SPR_MAS3, args->e->mas3);
2701 	switch ((mfpvr() >> 16) & 0xFFFF) {
2702 	case FSL_E500mc:
2703 	case FSL_E5500:
2704 	case FSL_E6500:
2705 		mtspr(SPR_MAS8, 0);
2706 		/* FALLTHROUGH */
2707 	case FSL_E500v2:
2708 		mtspr(SPR_MAS7, args->e->mas7);
2709 		break;
2710 	default:
2711 		break;
2712 	}
2713 
2714 	__asm __volatile("isync; tlbwe; isync; msync");
2715 
2716 }
2717 
2718 static void
tlb1_write_entry_sync(void * arg)2719 tlb1_write_entry_sync(void *arg)
2720 {
2721 	/* Empty synchronization point for smp_rendezvous(). */
2722 }
2723 
2724 /*
2725  * Write given entry to TLB1 hardware.
2726  */
2727 static void
tlb1_write_entry(tlb_entry_t * e,unsigned int idx)2728 tlb1_write_entry(tlb_entry_t *e, unsigned int idx)
2729 {
2730 	struct tlbwrite_args args;
2731 
2732 	args.e = e;
2733 	args.idx = idx;
2734 
2735 #ifdef SMP
2736 	if ((e->mas2 & _TLB_ENTRY_SHARED) && smp_started) {
2737 		mb();
2738 		smp_rendezvous(tlb1_write_entry_sync,
2739 		    tlb1_write_entry_int,
2740 		    tlb1_write_entry_sync, &args);
2741 	} else
2742 #endif
2743 	{
2744 		register_t msr;
2745 
2746 		msr = mfmsr();
2747 		__asm __volatile("wrteei 0");
2748 		tlb1_write_entry_int(&args);
2749 		__asm __volatile("wrtee %0" :: "r"(msr));
2750 	}
2751 }
2752 
2753 /*
2754  * Convert TLB TSIZE value to mapped region size.
2755  */
2756 static vm_size_t
tsize2size(unsigned int tsize)2757 tsize2size(unsigned int tsize)
2758 {
2759 
2760 	/*
2761 	 * size = 4^tsize KB
2762 	 * size = 4^tsize * 2^10 = 2^(2 * tsize - 10)
2763 	 */
2764 
2765 	return ((1UL << tsize) * 1024);
2766 }
2767 
2768 /*
2769  * Convert region size (must be power of 4) to TLB TSIZE value.
2770  */
2771 static unsigned int
size2tsize(vm_size_t size)2772 size2tsize(vm_size_t size)
2773 {
2774 
2775 	return (ilog2(size) - 10);
2776 }
2777 
2778 /*
2779  * Register permanent kernel mapping in TLB1.
2780  *
2781  * Entries are created starting from index 0 (current free entry is
2782  * kept in tlb1_idx) and are not supposed to be invalidated.
2783  */
2784 int
tlb1_set_entry(vm_offset_t va,vm_paddr_t pa,vm_size_t size,uint32_t flags)2785 tlb1_set_entry(vm_offset_t va, vm_paddr_t pa, vm_size_t size,
2786     uint32_t flags)
2787 {
2788 	tlb_entry_t e;
2789 	uint32_t ts, tid;
2790 	int tsize, index;
2791 
2792 	/* First try to update an existing entry. */
2793 	for (index = 0; index < TLB1_ENTRIES; index++) {
2794 		tlb1_read_entry(&e, index);
2795 		/* Check if we're just updating the flags, and update them. */
2796 		if (e.phys == pa && e.virt == va && e.size == size) {
2797 			e.mas2 = (va & MAS2_EPN_MASK) | flags;
2798 			tlb1_write_entry(&e, index);
2799 			return (0);
2800 		}
2801 	}
2802 
2803 	/* Convert size to TSIZE */
2804 	tsize = size2tsize(size);
2805 
2806 	tid = (TID_KERNEL << MAS1_TID_SHIFT) & MAS1_TID_MASK;
2807 	/* XXX TS is hard coded to 0 for now as we only use single address space */
2808 	ts = (0 << MAS1_TS_SHIFT) & MAS1_TS_MASK;
2809 
2810 	e.phys = pa;
2811 	e.virt = va;
2812 	e.size = size;
2813 	e.mas1 = MAS1_VALID | MAS1_IPROT | ts | tid;
2814 	e.mas1 |= ((tsize << MAS1_TSIZE_SHIFT) & MAS1_TSIZE_MASK);
2815 	e.mas2 = (va & MAS2_EPN_MASK) | flags;
2816 
2817 	/* Set supervisor RWX permission bits */
2818 	e.mas3 = (pa & MAS3_RPN) | MAS3_SR | MAS3_SW | MAS3_SX;
2819 	e.mas7 = (pa >> 32) & MAS7_RPN;
2820 
2821 	tlb1_write_entry(&e, -1);
2822 
2823 	return (0);
2824 }
2825 
2826 /*
2827  * Map in contiguous RAM region into the TLB1.
2828  */
2829 static vm_size_t
tlb1_mapin_region(vm_offset_t va,vm_paddr_t pa,vm_size_t size,int wimge)2830 tlb1_mapin_region(vm_offset_t va, vm_paddr_t pa, vm_size_t size, int wimge)
2831 {
2832 	vm_offset_t base;
2833 	vm_size_t mapped, sz, ssize;
2834 	int shift;
2835 
2836 	mapped = 0;
2837 	base = va;
2838 	ssize = size;
2839 
2840 	if (mmuv2)
2841 		shift = 1;
2842 	else
2843 		shift = 2;
2844 
2845 	while (size > 0) {
2846 		sz = 1UL << (ilog2(size) & ~(shift - 1));
2847 		/* Align size to PA */
2848 		if (pa % sz != 0) {
2849 			do {
2850 				sz >>= shift;
2851 			} while (pa % sz != 0);
2852 		}
2853 		/* Now align from there to VA */
2854 		if (va % sz != 0) {
2855 			do {
2856 				sz >>= shift;
2857 			} while (va % sz != 0);
2858 		}
2859 #ifdef __powerpc64__
2860 		/*
2861 		 * Clamp TLB1 entries to 4G.
2862 		 *
2863 		 * While the e6500 supports up to 1TB mappings, the e5500
2864 		 * only supports up to 4G mappings. (0b1011)
2865 		 *
2866 		 * If any e6500 machines capable of supporting a very
2867 		 * large amount of memory appear in the future, we can
2868 		 * revisit this.
2869 		 *
2870 		 * For now, though, since we have plenty of space in TLB1,
2871 		 * always avoid creating entries larger than 4GB.
2872 		 */
2873 		if (!mmuv2)
2874 			sz = MIN(sz, 1UL << 32);
2875 #endif
2876 		if (bootverbose)
2877 			printf("Wiring VA=%p to PA=%jx (size=%lx)\n",
2878 			    (void *)va, (uintmax_t)pa, (long)sz);
2879 		if (tlb1_set_entry(va, pa, sz,
2880 		    _TLB_ENTRY_SHARED | wimge) < 0)
2881 			return (mapped);
2882 		size -= sz;
2883 		pa += sz;
2884 		va += sz;
2885 	}
2886 
2887 	mapped = (va - base);
2888 	if (bootverbose)
2889 		printf("mapped size 0x%"PRIxPTR" (wasted space 0x%"PRIxPTR")\n",
2890 		    mapped, mapped - ssize);
2891 
2892 	return (mapped);
2893 }
2894 
2895 /*
2896  * TLB1 initialization routine, to be called after the very first
2897  * assembler level setup done in locore.S.
2898  */
2899 void
tlb1_init(void)2900 tlb1_init(void)
2901 {
2902 	vm_offset_t mas2;
2903 	uint32_t mas0, mas1, mas3, mas7;
2904 	uint32_t tsz;
2905 
2906 	tlb1_get_tlbconf();
2907 
2908 	mas0 = MAS0_TLBSEL(1) | MAS0_ESEL(0);
2909 	mtspr(SPR_MAS0, mas0);
2910 	__asm __volatile("isync; tlbre");
2911 
2912 	mas1 = mfspr(SPR_MAS1);
2913 	mas2 = mfspr(SPR_MAS2);
2914 	mas3 = mfspr(SPR_MAS3);
2915 	mas7 = mfspr(SPR_MAS7);
2916 
2917 	kernload =  ((vm_paddr_t)(mas7 & MAS7_RPN) << 32) |
2918 	    (mas3 & MAS3_RPN);
2919 
2920 	tsz = (mas1 & MAS1_TSIZE_MASK) >> MAS1_TSIZE_SHIFT;
2921 	kernsize += (tsz > 0) ? tsize2size(tsz) : 0;
2922 	kernstart = trunc_page(mas2);
2923 
2924 	/* Setup TLB miss defaults */
2925 	set_mas4_defaults();
2926 }
2927 
2928 /*
2929  * pmap_early_io_unmap() should be used in short conjunction with
2930  * pmap_early_io_map(), as in the following snippet:
2931  *
2932  * x = pmap_early_io_map(...);
2933  * <do something with x>
2934  * pmap_early_io_unmap(x, size);
2935  *
2936  * And avoiding more allocations between.
2937  */
2938 void
pmap_early_io_unmap(vm_offset_t va,vm_size_t size)2939 pmap_early_io_unmap(vm_offset_t va, vm_size_t size)
2940 {
2941 	int i;
2942 	tlb_entry_t e;
2943 	vm_size_t isize;
2944 
2945 	size = roundup(size, PAGE_SIZE);
2946 	isize = size;
2947 	for (i = 0; i < TLB1_ENTRIES && size > 0; i++) {
2948 		tlb1_read_entry(&e, i);
2949 		if (!(e.mas1 & MAS1_VALID))
2950 			continue;
2951 		if (va <= e.virt && (va + isize) >= (e.virt + e.size)) {
2952 			size -= e.size;
2953 			e.mas1 &= ~MAS1_VALID;
2954 			tlb1_write_entry(&e, i);
2955 		}
2956 	}
2957 	if (tlb1_map_base == va + isize)
2958 		tlb1_map_base -= isize;
2959 }
2960 
2961 vm_offset_t
pmap_early_io_map(vm_paddr_t pa,vm_size_t size)2962 pmap_early_io_map(vm_paddr_t pa, vm_size_t size)
2963 {
2964 	vm_paddr_t pa_base;
2965 	vm_offset_t va, sz;
2966 	int i;
2967 	tlb_entry_t e;
2968 
2969 	KASSERT(!pmap_bootstrapped, ("Do not use after PMAP is up!"));
2970 
2971 	for (i = 0; i < TLB1_ENTRIES; i++) {
2972 		tlb1_read_entry(&e, i);
2973 		if (!(e.mas1 & MAS1_VALID))
2974 			continue;
2975 		if (pa >= e.phys && (pa + size) <=
2976 		    (e.phys + e.size))
2977 			return (e.virt + (pa - e.phys));
2978 	}
2979 
2980 	pa_base = rounddown(pa, PAGE_SIZE);
2981 	size = roundup(size + (pa - pa_base), PAGE_SIZE);
2982 	tlb1_map_base = roundup2(tlb1_map_base, 1 << (ilog2(size) & ~1));
2983 	va = tlb1_map_base + (pa - pa_base);
2984 
2985 	do {
2986 		sz = 1 << (ilog2(size) & ~1);
2987 		tlb1_set_entry(tlb1_map_base, pa_base, sz,
2988 		    _TLB_ENTRY_SHARED | _TLB_ENTRY_IO);
2989 		size -= sz;
2990 		pa_base += sz;
2991 		tlb1_map_base += sz;
2992 	} while (size > 0);
2993 
2994 	return (va);
2995 }
2996 
2997 void
pmap_track_page(pmap_t pmap,vm_offset_t va)2998 pmap_track_page(pmap_t pmap, vm_offset_t va)
2999 {
3000 	vm_paddr_t pa;
3001 	vm_page_t page;
3002 	struct pv_entry *pve;
3003 
3004 	va = trunc_page(va);
3005 	pa = pmap_kextract(va);
3006 	page = PHYS_TO_VM_PAGE(pa);
3007 
3008 	rw_wlock(&pvh_global_lock);
3009 	PMAP_LOCK(pmap);
3010 
3011 	TAILQ_FOREACH(pve, &page->md.pv_list, pv_link) {
3012 		if ((pmap == pve->pv_pmap) && (va == pve->pv_va)) {
3013 			goto out;
3014 		}
3015 	}
3016 	page->md.pv_tracked = true;
3017 	pv_insert(pmap, va, page);
3018 out:
3019 	PMAP_UNLOCK(pmap);
3020 	rw_wunlock(&pvh_global_lock);
3021 }
3022 
3023 /*
3024  * Setup MAS4 defaults.
3025  * These values are loaded to MAS0-2 on a TLB miss.
3026  */
3027 static void
set_mas4_defaults(void)3028 set_mas4_defaults(void)
3029 {
3030 	uint32_t mas4;
3031 
3032 	/* Defaults: TLB0, PID0, TSIZED=4K */
3033 	mas4 = MAS4_TLBSELD0;
3034 	mas4 |= (TLB_SIZE_4K << MAS4_TSIZED_SHIFT) & MAS4_TSIZED_MASK;
3035 #ifdef SMP
3036 	mas4 |= MAS4_MD;
3037 #endif
3038 	mtspr(SPR_MAS4, mas4);
3039 	__asm __volatile("isync");
3040 }
3041 
3042 /*
3043  * Return 0 if the physical IO range is encompassed by one of the
3044  * the TLB1 entries, otherwise return related error code.
3045  */
3046 static int
tlb1_iomapped(int i,vm_paddr_t pa,vm_size_t size,vm_offset_t * va)3047 tlb1_iomapped(int i, vm_paddr_t pa, vm_size_t size, vm_offset_t *va)
3048 {
3049 	uint32_t prot;
3050 	vm_paddr_t pa_start;
3051 	vm_paddr_t pa_end;
3052 	unsigned int entry_tsize;
3053 	vm_size_t entry_size;
3054 	tlb_entry_t e;
3055 
3056 	*va = (vm_offset_t)NULL;
3057 
3058 	tlb1_read_entry(&e, i);
3059 	/* Skip invalid entries */
3060 	if (!(e.mas1 & MAS1_VALID))
3061 		return (EINVAL);
3062 
3063 	/*
3064 	 * The entry must be cache-inhibited, guarded, and r/w
3065 	 * so it can function as an i/o page
3066 	 */
3067 	prot = e.mas2 & (MAS2_I | MAS2_G);
3068 	if (prot != (MAS2_I | MAS2_G))
3069 		return (EPERM);
3070 
3071 	prot = e.mas3 & (MAS3_SR | MAS3_SW);
3072 	if (prot != (MAS3_SR | MAS3_SW))
3073 		return (EPERM);
3074 
3075 	/* The address should be within the entry range. */
3076 	entry_tsize = (e.mas1 & MAS1_TSIZE_MASK) >> MAS1_TSIZE_SHIFT;
3077 	KASSERT((entry_tsize), ("tlb1_iomapped: invalid entry tsize"));
3078 
3079 	entry_size = tsize2size(entry_tsize);
3080 	pa_start = (((vm_paddr_t)e.mas7 & MAS7_RPN) << 32) |
3081 	    (e.mas3 & MAS3_RPN);
3082 	pa_end = pa_start + entry_size;
3083 
3084 	if ((pa < pa_start) || ((pa + size) > pa_end))
3085 		return (ERANGE);
3086 
3087 	/* Return virtual address of this mapping. */
3088 	*va = (e.mas2 & MAS2_EPN_MASK) + (pa - pa_start);
3089 	return (0);
3090 }
3091 
3092 #ifdef DDB
3093 /* Print out contents of the MAS registers for each TLB0 entry */
3094 static void
3095 #ifdef __powerpc64__
tlb_print_entry(int i,uint32_t mas1,uint64_t mas2,uint32_t mas3,uint32_t mas7)3096 tlb_print_entry(int i, uint32_t mas1, uint64_t mas2, uint32_t mas3,
3097 #else
3098 tlb_print_entry(int i, uint32_t mas1, uint32_t mas2, uint32_t mas3,
3099 #endif
3100     uint32_t mas7)
3101 {
3102 	int as;
3103 	char desc[3];
3104 	tlbtid_t tid;
3105 	vm_size_t size;
3106 	unsigned int tsize;
3107 
3108 	desc[2] = '\0';
3109 	if (mas1 & MAS1_VALID)
3110 		desc[0] = 'V';
3111 	else
3112 		desc[0] = ' ';
3113 
3114 	if (mas1 & MAS1_IPROT)
3115 		desc[1] = 'P';
3116 	else
3117 		desc[1] = ' ';
3118 
3119 	as = (mas1 & MAS1_TS_MASK) ? 1 : 0;
3120 	tid = MAS1_GETTID(mas1);
3121 
3122 	tsize = (mas1 & MAS1_TSIZE_MASK) >> MAS1_TSIZE_SHIFT;
3123 	size = 0;
3124 	if (tsize)
3125 		size = tsize2size(tsize);
3126 
3127 	printf("%3d: (%s) [AS=%d] "
3128 	    "sz = 0x%jx tsz = %d tid = %d mas1 = 0x%08x "
3129 	    "mas2(va) = 0x%"PRI0ptrX" mas3(pa) = 0x%08x mas7 = 0x%08x\n",
3130 	    i, desc, as, (uintmax_t)size, tsize, tid, mas1, mas2, mas3, mas7);
3131 }
3132 
DB_SHOW_COMMAND(tlb0,tlb0_print_tlbentries)3133 DB_SHOW_COMMAND(tlb0, tlb0_print_tlbentries)
3134 {
3135 	uint32_t mas0, mas1, mas3, mas7;
3136 #ifdef __powerpc64__
3137 	uint64_t mas2;
3138 #else
3139 	uint32_t mas2;
3140 #endif
3141 	int entryidx, way, idx;
3142 
3143 	printf("TLB0 entries:\n");
3144 	for (way = 0; way < TLB0_WAYS; way ++)
3145 		for (entryidx = 0; entryidx < TLB0_ENTRIES_PER_WAY; entryidx++) {
3146 			mas0 = MAS0_TLBSEL(0) | MAS0_ESEL(way);
3147 			mtspr(SPR_MAS0, mas0);
3148 
3149 			mas2 = entryidx << MAS2_TLB0_ENTRY_IDX_SHIFT;
3150 			mtspr(SPR_MAS2, mas2);
3151 
3152 			__asm __volatile("isync; tlbre");
3153 
3154 			mas1 = mfspr(SPR_MAS1);
3155 			mas2 = mfspr(SPR_MAS2);
3156 			mas3 = mfspr(SPR_MAS3);
3157 			mas7 = mfspr(SPR_MAS7);
3158 
3159 			idx = tlb0_tableidx(mas2, way);
3160 			tlb_print_entry(idx, mas1, mas2, mas3, mas7);
3161 		}
3162 }
3163 
3164 /*
3165  * Print out contents of the MAS registers for each TLB1 entry
3166  */
DB_SHOW_COMMAND(tlb1,tlb1_print_tlbentries)3167 DB_SHOW_COMMAND(tlb1, tlb1_print_tlbentries)
3168 {
3169 	uint32_t mas0, mas1, mas3, mas7;
3170 #ifdef __powerpc64__
3171 	uint64_t mas2;
3172 #else
3173 	uint32_t mas2;
3174 #endif
3175 	int i;
3176 
3177 	printf("TLB1 entries:\n");
3178 	for (i = 0; i < TLB1_ENTRIES; i++) {
3179 		mas0 = MAS0_TLBSEL(1) | MAS0_ESEL(i);
3180 		mtspr(SPR_MAS0, mas0);
3181 
3182 		__asm __volatile("isync; tlbre");
3183 
3184 		mas1 = mfspr(SPR_MAS1);
3185 		mas2 = mfspr(SPR_MAS2);
3186 		mas3 = mfspr(SPR_MAS3);
3187 		mas7 = mfspr(SPR_MAS7);
3188 
3189 		tlb_print_entry(i, mas1, mas2, mas3, mas7);
3190 	}
3191 }
3192 #endif
3193