• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * PowerPC64 port by Mike Corrigan and Dave Engebretsen
4  *   {mikejc|engebret}@us.ibm.com
5  *
6  *    Copyright (c) 2000 Mike Corrigan <mikejc@us.ibm.com>
7  *
8  * SMP scalability work:
9  *    Copyright (C) 2001 Anton Blanchard <anton@au.ibm.com>, IBM
10  *
11  *    Module name: htab.c
12  *
13  *    Description:
14  *      PowerPC Hashed Page Table functions
15  */
16 
17 #undef DEBUG
18 #undef DEBUG_LOW
19 
20 #define pr_fmt(fmt) "hash-mmu: " fmt
21 #include <linux/spinlock.h>
22 #include <linux/errno.h>
23 #include <linux/sched/mm.h>
24 #include <linux/proc_fs.h>
25 #include <linux/stat.h>
26 #include <linux/sysctl.h>
27 #include <linux/export.h>
28 #include <linux/ctype.h>
29 #include <linux/cache.h>
30 #include <linux/init.h>
31 #include <linux/signal.h>
32 #include <linux/memblock.h>
33 #include <linux/context_tracking.h>
34 #include <linux/libfdt.h>
35 #include <linux/pkeys.h>
36 #include <linux/hugetlb.h>
37 #include <linux/cpu.h>
38 #include <linux/pgtable.h>
39 
40 #include <asm/debugfs.h>
41 #include <asm/processor.h>
42 #include <asm/mmu.h>
43 #include <asm/mmu_context.h>
44 #include <asm/page.h>
45 #include <asm/types.h>
46 #include <linux/uaccess.h>
47 #include <asm/machdep.h>
48 #include <asm/prom.h>
49 #include <asm/io.h>
50 #include <asm/eeh.h>
51 #include <asm/tlb.h>
52 #include <asm/cacheflush.h>
53 #include <asm/cputable.h>
54 #include <asm/sections.h>
55 #include <asm/copro.h>
56 #include <asm/udbg.h>
57 #include <asm/code-patching.h>
58 #include <asm/fadump.h>
59 #include <asm/firmware.h>
60 #include <asm/tm.h>
61 #include <asm/trace.h>
62 #include <asm/ps3.h>
63 #include <asm/pte-walk.h>
64 #include <asm/asm-prototypes.h>
65 #include <asm/ultravisor.h>
66 
67 #include <mm/mmu_decl.h>
68 
69 #include "internal.h"
70 
71 
72 #ifdef DEBUG
73 #define DBG(fmt...) udbg_printf(fmt)
74 #else
75 #define DBG(fmt...)
76 #endif
77 
78 #ifdef DEBUG_LOW
79 #define DBG_LOW(fmt...) udbg_printf(fmt)
80 #else
81 #define DBG_LOW(fmt...)
82 #endif
83 
84 #define KB (1024)
85 #define MB (1024*KB)
86 #define GB (1024L*MB)
87 
88 /*
89  * Note:  pte   --> Linux PTE
90  *        HPTE  --> PowerPC Hashed Page Table Entry
91  *
92  * Execution context:
93  *   htab_initialize is called with the MMU off (of course), but
94  *   the kernel has been copied down to zero so it can directly
95  *   reference global data.  At this point it is very difficult
96  *   to print debug info.
97  *
98  */
99 
100 static unsigned long _SDR1;
101 struct mmu_psize_def mmu_psize_defs[MMU_PAGE_COUNT];
102 EXPORT_SYMBOL_GPL(mmu_psize_defs);
103 
104 u8 hpte_page_sizes[1 << LP_BITS];
105 EXPORT_SYMBOL_GPL(hpte_page_sizes);
106 
107 struct hash_pte *htab_address;
108 unsigned long htab_size_bytes;
109 unsigned long htab_hash_mask;
110 EXPORT_SYMBOL_GPL(htab_hash_mask);
111 int mmu_linear_psize = MMU_PAGE_4K;
112 EXPORT_SYMBOL_GPL(mmu_linear_psize);
113 int mmu_virtual_psize = MMU_PAGE_4K;
114 int mmu_vmalloc_psize = MMU_PAGE_4K;
115 #ifdef CONFIG_SPARSEMEM_VMEMMAP
116 int mmu_vmemmap_psize = MMU_PAGE_4K;
117 #endif
118 int mmu_io_psize = MMU_PAGE_4K;
119 int mmu_kernel_ssize = MMU_SEGSIZE_256M;
120 EXPORT_SYMBOL_GPL(mmu_kernel_ssize);
121 int mmu_highuser_ssize = MMU_SEGSIZE_256M;
122 u16 mmu_slb_size = 64;
123 EXPORT_SYMBOL_GPL(mmu_slb_size);
124 #ifdef CONFIG_PPC_64K_PAGES
125 int mmu_ci_restrictions;
126 #endif
127 #ifdef CONFIG_DEBUG_PAGEALLOC
128 static u8 *linear_map_hash_slots;
129 static unsigned long linear_map_hash_count;
130 static DEFINE_SPINLOCK(linear_map_hash_lock);
131 #endif /* CONFIG_DEBUG_PAGEALLOC */
132 struct mmu_hash_ops mmu_hash_ops;
133 EXPORT_SYMBOL(mmu_hash_ops);
134 
135 /*
136  * These are definitions of page sizes arrays to be used when none
137  * is provided by the firmware.
138  */
139 
140 /*
141  * Fallback (4k pages only)
142  */
143 static struct mmu_psize_def mmu_psize_defaults[] = {
144 	[MMU_PAGE_4K] = {
145 		.shift	= 12,
146 		.sllp	= 0,
147 		.penc   = {[MMU_PAGE_4K] = 0, [1 ... MMU_PAGE_COUNT - 1] = -1},
148 		.avpnm	= 0,
149 		.tlbiel = 0,
150 	},
151 };
152 
153 /*
154  * POWER4, GPUL, POWER5
155  *
156  * Support for 16Mb large pages
157  */
158 static struct mmu_psize_def mmu_psize_defaults_gp[] = {
159 	[MMU_PAGE_4K] = {
160 		.shift	= 12,
161 		.sllp	= 0,
162 		.penc   = {[MMU_PAGE_4K] = 0, [1 ... MMU_PAGE_COUNT - 1] = -1},
163 		.avpnm	= 0,
164 		.tlbiel = 1,
165 	},
166 	[MMU_PAGE_16M] = {
167 		.shift	= 24,
168 		.sllp	= SLB_VSID_L,
169 		.penc   = {[0 ... MMU_PAGE_16M - 1] = -1, [MMU_PAGE_16M] = 0,
170 			    [MMU_PAGE_16M + 1 ... MMU_PAGE_COUNT - 1] = -1 },
171 		.avpnm	= 0x1UL,
172 		.tlbiel = 0,
173 	},
174 };
175 
176 /*
177  * 'R' and 'C' update notes:
178  *  - Under pHyp or KVM, the updatepp path will not set C, thus it *will*
179  *     create writeable HPTEs without C set, because the hcall H_PROTECT
180  *     that we use in that case will not update C
181  *  - The above is however not a problem, because we also don't do that
182  *     fancy "no flush" variant of eviction and we use H_REMOVE which will
183  *     do the right thing and thus we don't have the race I described earlier
184  *
185  *    - Under bare metal,  we do have the race, so we need R and C set
186  *    - We make sure R is always set and never lost
187  *    - C is _PAGE_DIRTY, and *should* always be set for a writeable mapping
188  */
htab_convert_pte_flags(unsigned long pteflags)189 unsigned long htab_convert_pte_flags(unsigned long pteflags)
190 {
191 	unsigned long rflags = 0;
192 
193 	/* _PAGE_EXEC -> NOEXEC */
194 	if ((pteflags & _PAGE_EXEC) == 0)
195 		rflags |= HPTE_R_N;
196 	/*
197 	 * PPP bits:
198 	 * Linux uses slb key 0 for kernel and 1 for user.
199 	 * kernel RW areas are mapped with PPP=0b000
200 	 * User area is mapped with PPP=0b010 for read/write
201 	 * or PPP=0b011 for read-only (including writeable but clean pages).
202 	 */
203 	if (pteflags & _PAGE_PRIVILEGED) {
204 		/*
205 		 * Kernel read only mapped with ppp bits 0b110
206 		 */
207 		if (!(pteflags & _PAGE_WRITE)) {
208 			if (mmu_has_feature(MMU_FTR_KERNEL_RO))
209 				rflags |= (HPTE_R_PP0 | 0x2);
210 			else
211 				rflags |= 0x3;
212 		}
213 	} else {
214 		if (pteflags & _PAGE_RWX)
215 			rflags |= 0x2;
216 		if (!((pteflags & _PAGE_WRITE) && (pteflags & _PAGE_DIRTY)))
217 			rflags |= 0x1;
218 	}
219 	/*
220 	 * We can't allow hardware to update hpte bits. Hence always
221 	 * set 'R' bit and set 'C' if it is a write fault
222 	 */
223 	rflags |=  HPTE_R_R;
224 
225 	if (pteflags & _PAGE_DIRTY)
226 		rflags |= HPTE_R_C;
227 	/*
228 	 * Add in WIG bits
229 	 */
230 
231 	if ((pteflags & _PAGE_CACHE_CTL) == _PAGE_TOLERANT)
232 		rflags |= HPTE_R_I;
233 	else if ((pteflags & _PAGE_CACHE_CTL) == _PAGE_NON_IDEMPOTENT)
234 		rflags |= (HPTE_R_I | HPTE_R_G);
235 	else if ((pteflags & _PAGE_CACHE_CTL) == _PAGE_SAO)
236 		rflags |= (HPTE_R_W | HPTE_R_I | HPTE_R_M);
237 	else
238 		/*
239 		 * Add memory coherence if cache inhibited is not set
240 		 */
241 		rflags |= HPTE_R_M;
242 
243 	rflags |= pte_to_hpte_pkey_bits(pteflags);
244 	return rflags;
245 }
246 
htab_bolt_mapping(unsigned long vstart,unsigned long vend,unsigned long pstart,unsigned long prot,int psize,int ssize)247 int htab_bolt_mapping(unsigned long vstart, unsigned long vend,
248 		      unsigned long pstart, unsigned long prot,
249 		      int psize, int ssize)
250 {
251 	unsigned long vaddr, paddr;
252 	unsigned int step, shift;
253 	int ret = 0;
254 
255 	shift = mmu_psize_defs[psize].shift;
256 	step = 1 << shift;
257 
258 	prot = htab_convert_pte_flags(prot);
259 
260 	DBG("htab_bolt_mapping(%lx..%lx -> %lx (%lx,%d,%d)\n",
261 	    vstart, vend, pstart, prot, psize, ssize);
262 
263 	/* Carefully map only the possible range */
264 	vaddr = ALIGN(vstart, step);
265 	paddr = ALIGN(pstart, step);
266 	vend  = ALIGN_DOWN(vend, step);
267 
268 	for (; vaddr < vend; vaddr += step, paddr += step) {
269 		unsigned long hash, hpteg;
270 		unsigned long vsid = get_kernel_vsid(vaddr, ssize);
271 		unsigned long vpn  = hpt_vpn(vaddr, vsid, ssize);
272 		unsigned long tprot = prot;
273 		bool secondary_hash = false;
274 
275 		/*
276 		 * If we hit a bad address return error.
277 		 */
278 		if (!vsid)
279 			return -1;
280 		/* Make kernel text executable */
281 		if (overlaps_kernel_text(vaddr, vaddr + step))
282 			tprot &= ~HPTE_R_N;
283 
284 		/*
285 		 * If relocatable, check if it overlaps interrupt vectors that
286 		 * are copied down to real 0. For relocatable kernel
287 		 * (e.g. kdump case) we copy interrupt vectors down to real
288 		 * address 0. Mark that region as executable. This is
289 		 * because on p8 system with relocation on exception feature
290 		 * enabled, exceptions are raised with MMU (IR=DR=1) ON. Hence
291 		 * in order to execute the interrupt handlers in virtual
292 		 * mode the vector region need to be marked as executable.
293 		 */
294 		if ((PHYSICAL_START > MEMORY_START) &&
295 			overlaps_interrupt_vector_text(vaddr, vaddr + step))
296 				tprot &= ~HPTE_R_N;
297 
298 		hash = hpt_hash(vpn, shift, ssize);
299 		hpteg = ((hash & htab_hash_mask) * HPTES_PER_GROUP);
300 
301 		BUG_ON(!mmu_hash_ops.hpte_insert);
302 repeat:
303 		ret = mmu_hash_ops.hpte_insert(hpteg, vpn, paddr, tprot,
304 					       HPTE_V_BOLTED, psize, psize,
305 					       ssize);
306 		if (ret == -1) {
307 			/*
308 			 * Try to to keep bolted entries in primary.
309 			 * Remove non bolted entries and try insert again
310 			 */
311 			ret = mmu_hash_ops.hpte_remove(hpteg);
312 			if (ret != -1)
313 				ret = mmu_hash_ops.hpte_insert(hpteg, vpn, paddr, tprot,
314 							       HPTE_V_BOLTED, psize, psize,
315 							       ssize);
316 			if (ret == -1 && !secondary_hash) {
317 				secondary_hash = true;
318 				hpteg = ((~hash & htab_hash_mask) * HPTES_PER_GROUP);
319 				goto repeat;
320 			}
321 		}
322 
323 		if (ret < 0)
324 			break;
325 
326 		cond_resched();
327 #ifdef CONFIG_DEBUG_PAGEALLOC
328 		if (debug_pagealloc_enabled() &&
329 			(paddr >> PAGE_SHIFT) < linear_map_hash_count)
330 			linear_map_hash_slots[paddr >> PAGE_SHIFT] = ret | 0x80;
331 #endif /* CONFIG_DEBUG_PAGEALLOC */
332 	}
333 	return ret < 0 ? ret : 0;
334 }
335 
htab_remove_mapping(unsigned long vstart,unsigned long vend,int psize,int ssize)336 int htab_remove_mapping(unsigned long vstart, unsigned long vend,
337 		      int psize, int ssize)
338 {
339 	unsigned long vaddr, time_limit;
340 	unsigned int step, shift;
341 	int rc;
342 	int ret = 0;
343 
344 	shift = mmu_psize_defs[psize].shift;
345 	step = 1 << shift;
346 
347 	if (!mmu_hash_ops.hpte_removebolted)
348 		return -ENODEV;
349 
350 	/* Unmap the full range specificied */
351 	vaddr = ALIGN_DOWN(vstart, step);
352 	time_limit = jiffies + HZ;
353 
354 	for (;vaddr < vend; vaddr += step) {
355 		rc = mmu_hash_ops.hpte_removebolted(vaddr, psize, ssize);
356 
357 		/*
358 		 * For large number of mappings introduce a cond_resched()
359 		 * to prevent softlockup warnings.
360 		 */
361 		if (time_after(jiffies, time_limit)) {
362 			cond_resched();
363 			time_limit = jiffies + HZ;
364 		}
365 		if (rc == -ENOENT) {
366 			ret = -ENOENT;
367 			continue;
368 		}
369 		if (rc < 0)
370 			return rc;
371 	}
372 
373 	return ret;
374 }
375 
376 static bool disable_1tb_segments = false;
377 
parse_disable_1tb_segments(char * p)378 static int __init parse_disable_1tb_segments(char *p)
379 {
380 	disable_1tb_segments = true;
381 	return 0;
382 }
383 early_param("disable_1tb_segments", parse_disable_1tb_segments);
384 
htab_dt_scan_seg_sizes(unsigned long node,const char * uname,int depth,void * data)385 static int __init htab_dt_scan_seg_sizes(unsigned long node,
386 					 const char *uname, int depth,
387 					 void *data)
388 {
389 	const char *type = of_get_flat_dt_prop(node, "device_type", NULL);
390 	const __be32 *prop;
391 	int size = 0;
392 
393 	/* We are scanning "cpu" nodes only */
394 	if (type == NULL || strcmp(type, "cpu") != 0)
395 		return 0;
396 
397 	prop = of_get_flat_dt_prop(node, "ibm,processor-segment-sizes", &size);
398 	if (prop == NULL)
399 		return 0;
400 	for (; size >= 4; size -= 4, ++prop) {
401 		if (be32_to_cpu(prop[0]) == 40) {
402 			DBG("1T segment support detected\n");
403 
404 			if (disable_1tb_segments) {
405 				DBG("1T segments disabled by command line\n");
406 				break;
407 			}
408 
409 			cur_cpu_spec->mmu_features |= MMU_FTR_1T_SEGMENT;
410 			return 1;
411 		}
412 	}
413 	cur_cpu_spec->mmu_features &= ~MMU_FTR_NO_SLBIE_B;
414 	return 0;
415 }
416 
get_idx_from_shift(unsigned int shift)417 static int __init get_idx_from_shift(unsigned int shift)
418 {
419 	int idx = -1;
420 
421 	switch (shift) {
422 	case 0xc:
423 		idx = MMU_PAGE_4K;
424 		break;
425 	case 0x10:
426 		idx = MMU_PAGE_64K;
427 		break;
428 	case 0x14:
429 		idx = MMU_PAGE_1M;
430 		break;
431 	case 0x18:
432 		idx = MMU_PAGE_16M;
433 		break;
434 	case 0x22:
435 		idx = MMU_PAGE_16G;
436 		break;
437 	}
438 	return idx;
439 }
440 
htab_dt_scan_page_sizes(unsigned long node,const char * uname,int depth,void * data)441 static int __init htab_dt_scan_page_sizes(unsigned long node,
442 					  const char *uname, int depth,
443 					  void *data)
444 {
445 	const char *type = of_get_flat_dt_prop(node, "device_type", NULL);
446 	const __be32 *prop;
447 	int size = 0;
448 
449 	/* We are scanning "cpu" nodes only */
450 	if (type == NULL || strcmp(type, "cpu") != 0)
451 		return 0;
452 
453 	prop = of_get_flat_dt_prop(node, "ibm,segment-page-sizes", &size);
454 	if (!prop)
455 		return 0;
456 
457 	pr_info("Page sizes from device-tree:\n");
458 	size /= 4;
459 	cur_cpu_spec->mmu_features &= ~(MMU_FTR_16M_PAGE);
460 	while(size > 0) {
461 		unsigned int base_shift = be32_to_cpu(prop[0]);
462 		unsigned int slbenc = be32_to_cpu(prop[1]);
463 		unsigned int lpnum = be32_to_cpu(prop[2]);
464 		struct mmu_psize_def *def;
465 		int idx, base_idx;
466 
467 		size -= 3; prop += 3;
468 		base_idx = get_idx_from_shift(base_shift);
469 		if (base_idx < 0) {
470 			/* skip the pte encoding also */
471 			prop += lpnum * 2; size -= lpnum * 2;
472 			continue;
473 		}
474 		def = &mmu_psize_defs[base_idx];
475 		if (base_idx == MMU_PAGE_16M)
476 			cur_cpu_spec->mmu_features |= MMU_FTR_16M_PAGE;
477 
478 		def->shift = base_shift;
479 		if (base_shift <= 23)
480 			def->avpnm = 0;
481 		else
482 			def->avpnm = (1 << (base_shift - 23)) - 1;
483 		def->sllp = slbenc;
484 		/*
485 		 * We don't know for sure what's up with tlbiel, so
486 		 * for now we only set it for 4K and 64K pages
487 		 */
488 		if (base_idx == MMU_PAGE_4K || base_idx == MMU_PAGE_64K)
489 			def->tlbiel = 1;
490 		else
491 			def->tlbiel = 0;
492 
493 		while (size > 0 && lpnum) {
494 			unsigned int shift = be32_to_cpu(prop[0]);
495 			int penc  = be32_to_cpu(prop[1]);
496 
497 			prop += 2; size -= 2;
498 			lpnum--;
499 
500 			idx = get_idx_from_shift(shift);
501 			if (idx < 0)
502 				continue;
503 
504 			if (penc == -1)
505 				pr_err("Invalid penc for base_shift=%d "
506 				       "shift=%d\n", base_shift, shift);
507 
508 			def->penc[idx] = penc;
509 			pr_info("base_shift=%d: shift=%d, sllp=0x%04lx,"
510 				" avpnm=0x%08lx, tlbiel=%d, penc=%d\n",
511 				base_shift, shift, def->sllp,
512 				def->avpnm, def->tlbiel, def->penc[idx]);
513 		}
514 	}
515 
516 	return 1;
517 }
518 
519 #ifdef CONFIG_HUGETLB_PAGE
520 /*
521  * Scan for 16G memory blocks that have been set aside for huge pages
522  * and reserve those blocks for 16G huge pages.
523  */
htab_dt_scan_hugepage_blocks(unsigned long node,const char * uname,int depth,void * data)524 static int __init htab_dt_scan_hugepage_blocks(unsigned long node,
525 					const char *uname, int depth,
526 					void *data) {
527 	const char *type = of_get_flat_dt_prop(node, "device_type", NULL);
528 	const __be64 *addr_prop;
529 	const __be32 *page_count_prop;
530 	unsigned int expected_pages;
531 	long unsigned int phys_addr;
532 	long unsigned int block_size;
533 
534 	/* We are scanning "memory" nodes only */
535 	if (type == NULL || strcmp(type, "memory") != 0)
536 		return 0;
537 
538 	/*
539 	 * This property is the log base 2 of the number of virtual pages that
540 	 * will represent this memory block.
541 	 */
542 	page_count_prop = of_get_flat_dt_prop(node, "ibm,expected#pages", NULL);
543 	if (page_count_prop == NULL)
544 		return 0;
545 	expected_pages = (1 << be32_to_cpu(page_count_prop[0]));
546 	addr_prop = of_get_flat_dt_prop(node, "reg", NULL);
547 	if (addr_prop == NULL)
548 		return 0;
549 	phys_addr = be64_to_cpu(addr_prop[0]);
550 	block_size = be64_to_cpu(addr_prop[1]);
551 	if (block_size != (16 * GB))
552 		return 0;
553 	printk(KERN_INFO "Huge page(16GB) memory: "
554 			"addr = 0x%lX size = 0x%lX pages = %d\n",
555 			phys_addr, block_size, expected_pages);
556 	if (phys_addr + block_size * expected_pages <= memblock_end_of_DRAM()) {
557 		memblock_reserve(phys_addr, block_size * expected_pages);
558 		pseries_add_gpage(phys_addr, block_size, expected_pages);
559 	}
560 	return 0;
561 }
562 #endif /* CONFIG_HUGETLB_PAGE */
563 
mmu_psize_set_default_penc(void)564 static void mmu_psize_set_default_penc(void)
565 {
566 	int bpsize, apsize;
567 	for (bpsize = 0; bpsize < MMU_PAGE_COUNT; bpsize++)
568 		for (apsize = 0; apsize < MMU_PAGE_COUNT; apsize++)
569 			mmu_psize_defs[bpsize].penc[apsize] = -1;
570 }
571 
572 #ifdef CONFIG_PPC_64K_PAGES
573 
might_have_hea(void)574 static bool might_have_hea(void)
575 {
576 	/*
577 	 * The HEA ethernet adapter requires awareness of the
578 	 * GX bus. Without that awareness we can easily assume
579 	 * we will never see an HEA ethernet device.
580 	 */
581 #ifdef CONFIG_IBMEBUS
582 	return !cpu_has_feature(CPU_FTR_ARCH_207S) &&
583 		firmware_has_feature(FW_FEATURE_SPLPAR);
584 #else
585 	return false;
586 #endif
587 }
588 
589 #endif /* #ifdef CONFIG_PPC_64K_PAGES */
590 
htab_scan_page_sizes(void)591 static void __init htab_scan_page_sizes(void)
592 {
593 	int rc;
594 
595 	/* se the invalid penc to -1 */
596 	mmu_psize_set_default_penc();
597 
598 	/* Default to 4K pages only */
599 	memcpy(mmu_psize_defs, mmu_psize_defaults,
600 	       sizeof(mmu_psize_defaults));
601 
602 	/*
603 	 * Try to find the available page sizes in the device-tree
604 	 */
605 	rc = of_scan_flat_dt(htab_dt_scan_page_sizes, NULL);
606 	if (rc == 0 && early_mmu_has_feature(MMU_FTR_16M_PAGE)) {
607 		/*
608 		 * Nothing in the device-tree, but the CPU supports 16M pages,
609 		 * so let's fallback on a known size list for 16M capable CPUs.
610 		 */
611 		memcpy(mmu_psize_defs, mmu_psize_defaults_gp,
612 		       sizeof(mmu_psize_defaults_gp));
613 	}
614 
615 #ifdef CONFIG_HUGETLB_PAGE
616 	if (!hugetlb_disabled && !early_radix_enabled() ) {
617 		/* Reserve 16G huge page memory sections for huge pages */
618 		of_scan_flat_dt(htab_dt_scan_hugepage_blocks, NULL);
619 	}
620 #endif /* CONFIG_HUGETLB_PAGE */
621 }
622 
623 /*
624  * Fill in the hpte_page_sizes[] array.
625  * We go through the mmu_psize_defs[] array looking for all the
626  * supported base/actual page size combinations.  Each combination
627  * has a unique pagesize encoding (penc) value in the low bits of
628  * the LP field of the HPTE.  For actual page sizes less than 1MB,
629  * some of the upper LP bits are used for RPN bits, meaning that
630  * we need to fill in several entries in hpte_page_sizes[].
631  *
632  * In diagrammatic form, with r = RPN bits and z = page size bits:
633  *        PTE LP     actual page size
634  *    rrrr rrrz		>=8KB
635  *    rrrr rrzz		>=16KB
636  *    rrrr rzzz		>=32KB
637  *    rrrr zzzz		>=64KB
638  *    ...
639  *
640  * The zzzz bits are implementation-specific but are chosen so that
641  * no encoding for a larger page size uses the same value in its
642  * low-order N bits as the encoding for the 2^(12+N) byte page size
643  * (if it exists).
644  */
init_hpte_page_sizes(void)645 static void init_hpte_page_sizes(void)
646 {
647 	long int ap, bp;
648 	long int shift, penc;
649 
650 	for (bp = 0; bp < MMU_PAGE_COUNT; ++bp) {
651 		if (!mmu_psize_defs[bp].shift)
652 			continue;	/* not a supported page size */
653 		for (ap = bp; ap < MMU_PAGE_COUNT; ++ap) {
654 			penc = mmu_psize_defs[bp].penc[ap];
655 			if (penc == -1 || !mmu_psize_defs[ap].shift)
656 				continue;
657 			shift = mmu_psize_defs[ap].shift - LP_SHIFT;
658 			if (shift <= 0)
659 				continue;	/* should never happen */
660 			/*
661 			 * For page sizes less than 1MB, this loop
662 			 * replicates the entry for all possible values
663 			 * of the rrrr bits.
664 			 */
665 			while (penc < (1 << LP_BITS)) {
666 				hpte_page_sizes[penc] = (ap << 4) | bp;
667 				penc += 1 << shift;
668 			}
669 		}
670 	}
671 }
672 
htab_init_page_sizes(void)673 static void __init htab_init_page_sizes(void)
674 {
675 	bool aligned = true;
676 	init_hpte_page_sizes();
677 
678 	if (!debug_pagealloc_enabled()) {
679 		/*
680 		 * Pick a size for the linear mapping. Currently, we only
681 		 * support 16M, 1M and 4K which is the default
682 		 */
683 		if (IS_ENABLED(CONFIG_STRICT_KERNEL_RWX) &&
684 		    (unsigned long)_stext % 0x1000000) {
685 			if (mmu_psize_defs[MMU_PAGE_16M].shift)
686 				pr_warn("Kernel not 16M aligned, disabling 16M linear map alignment\n");
687 			aligned = false;
688 		}
689 
690 		if (mmu_psize_defs[MMU_PAGE_16M].shift && aligned)
691 			mmu_linear_psize = MMU_PAGE_16M;
692 		else if (mmu_psize_defs[MMU_PAGE_1M].shift)
693 			mmu_linear_psize = MMU_PAGE_1M;
694 	}
695 
696 #ifdef CONFIG_PPC_64K_PAGES
697 	/*
698 	 * Pick a size for the ordinary pages. Default is 4K, we support
699 	 * 64K for user mappings and vmalloc if supported by the processor.
700 	 * We only use 64k for ioremap if the processor
701 	 * (and firmware) support cache-inhibited large pages.
702 	 * If not, we use 4k and set mmu_ci_restrictions so that
703 	 * hash_page knows to switch processes that use cache-inhibited
704 	 * mappings to 4k pages.
705 	 */
706 	if (mmu_psize_defs[MMU_PAGE_64K].shift) {
707 		mmu_virtual_psize = MMU_PAGE_64K;
708 		mmu_vmalloc_psize = MMU_PAGE_64K;
709 		if (mmu_linear_psize == MMU_PAGE_4K)
710 			mmu_linear_psize = MMU_PAGE_64K;
711 		if (mmu_has_feature(MMU_FTR_CI_LARGE_PAGE)) {
712 			/*
713 			 * When running on pSeries using 64k pages for ioremap
714 			 * would stop us accessing the HEA ethernet. So if we
715 			 * have the chance of ever seeing one, stay at 4k.
716 			 */
717 			if (!might_have_hea())
718 				mmu_io_psize = MMU_PAGE_64K;
719 		} else
720 			mmu_ci_restrictions = 1;
721 	}
722 #endif /* CONFIG_PPC_64K_PAGES */
723 
724 #ifdef CONFIG_SPARSEMEM_VMEMMAP
725 	/*
726 	 * We try to use 16M pages for vmemmap if that is supported
727 	 * and we have at least 1G of RAM at boot
728 	 */
729 	if (mmu_psize_defs[MMU_PAGE_16M].shift &&
730 	    memblock_phys_mem_size() >= 0x40000000)
731 		mmu_vmemmap_psize = MMU_PAGE_16M;
732 	else
733 		mmu_vmemmap_psize = mmu_virtual_psize;
734 #endif /* CONFIG_SPARSEMEM_VMEMMAP */
735 
736 	printk(KERN_DEBUG "Page orders: linear mapping = %d, "
737 	       "virtual = %d, io = %d"
738 #ifdef CONFIG_SPARSEMEM_VMEMMAP
739 	       ", vmemmap = %d"
740 #endif
741 	       "\n",
742 	       mmu_psize_defs[mmu_linear_psize].shift,
743 	       mmu_psize_defs[mmu_virtual_psize].shift,
744 	       mmu_psize_defs[mmu_io_psize].shift
745 #ifdef CONFIG_SPARSEMEM_VMEMMAP
746 	       ,mmu_psize_defs[mmu_vmemmap_psize].shift
747 #endif
748 	       );
749 }
750 
htab_dt_scan_pftsize(unsigned long node,const char * uname,int depth,void * data)751 static int __init htab_dt_scan_pftsize(unsigned long node,
752 				       const char *uname, int depth,
753 				       void *data)
754 {
755 	const char *type = of_get_flat_dt_prop(node, "device_type", NULL);
756 	const __be32 *prop;
757 
758 	/* We are scanning "cpu" nodes only */
759 	if (type == NULL || strcmp(type, "cpu") != 0)
760 		return 0;
761 
762 	prop = of_get_flat_dt_prop(node, "ibm,pft-size", NULL);
763 	if (prop != NULL) {
764 		/* pft_size[0] is the NUMA CEC cookie */
765 		ppc64_pft_size = be32_to_cpu(prop[1]);
766 		return 1;
767 	}
768 	return 0;
769 }
770 
htab_shift_for_mem_size(unsigned long mem_size)771 unsigned htab_shift_for_mem_size(unsigned long mem_size)
772 {
773 	unsigned memshift = __ilog2(mem_size);
774 	unsigned pshift = mmu_psize_defs[mmu_virtual_psize].shift;
775 	unsigned pteg_shift;
776 
777 	/* round mem_size up to next power of 2 */
778 	if ((1UL << memshift) < mem_size)
779 		memshift += 1;
780 
781 	/* aim for 2 pages / pteg */
782 	pteg_shift = memshift - (pshift + 1);
783 
784 	/*
785 	 * 2^11 PTEGS of 128 bytes each, ie. 2^18 bytes is the minimum htab
786 	 * size permitted by the architecture.
787 	 */
788 	return max(pteg_shift + 7, 18U);
789 }
790 
htab_get_table_size(void)791 static unsigned long __init htab_get_table_size(void)
792 {
793 	/*
794 	 * If hash size isn't already provided by the platform, we try to
795 	 * retrieve it from the device-tree. If it's not there neither, we
796 	 * calculate it now based on the total RAM size
797 	 */
798 	if (ppc64_pft_size == 0)
799 		of_scan_flat_dt(htab_dt_scan_pftsize, NULL);
800 	if (ppc64_pft_size)
801 		return 1UL << ppc64_pft_size;
802 
803 	return 1UL << htab_shift_for_mem_size(memblock_phys_mem_size());
804 }
805 
806 #ifdef CONFIG_MEMORY_HOTPLUG
resize_hpt_for_hotplug(unsigned long new_mem_size)807 static int resize_hpt_for_hotplug(unsigned long new_mem_size)
808 {
809 	unsigned target_hpt_shift;
810 
811 	if (!mmu_hash_ops.resize_hpt)
812 		return 0;
813 
814 	target_hpt_shift = htab_shift_for_mem_size(new_mem_size);
815 
816 	/*
817 	 * To avoid lots of HPT resizes if memory size is fluctuating
818 	 * across a boundary, we deliberately have some hysterisis
819 	 * here: we immediately increase the HPT size if the target
820 	 * shift exceeds the current shift, but we won't attempt to
821 	 * reduce unless the target shift is at least 2 below the
822 	 * current shift
823 	 */
824 	if (target_hpt_shift > ppc64_pft_size ||
825 	    target_hpt_shift < ppc64_pft_size - 1)
826 		return mmu_hash_ops.resize_hpt(target_hpt_shift);
827 
828 	return 0;
829 }
830 
hash__create_section_mapping(unsigned long start,unsigned long end,int nid,pgprot_t prot)831 int hash__create_section_mapping(unsigned long start, unsigned long end,
832 				 int nid, pgprot_t prot)
833 {
834 	int rc;
835 
836 	if (end >= H_VMALLOC_START) {
837 		pr_warn("Outside the supported range\n");
838 		return -1;
839 	}
840 
841 	resize_hpt_for_hotplug(memblock_phys_mem_size());
842 
843 	rc = htab_bolt_mapping(start, end, __pa(start),
844 			       pgprot_val(prot), mmu_linear_psize,
845 			       mmu_kernel_ssize);
846 
847 	if (rc < 0) {
848 		int rc2 = htab_remove_mapping(start, end, mmu_linear_psize,
849 					      mmu_kernel_ssize);
850 		BUG_ON(rc2 && (rc2 != -ENOENT));
851 	}
852 	return rc;
853 }
854 
hash__remove_section_mapping(unsigned long start,unsigned long end)855 int hash__remove_section_mapping(unsigned long start, unsigned long end)
856 {
857 	int rc = htab_remove_mapping(start, end, mmu_linear_psize,
858 				     mmu_kernel_ssize);
859 	WARN_ON(rc < 0);
860 
861 	if (resize_hpt_for_hotplug(memblock_phys_mem_size()) == -ENOSPC)
862 		pr_warn("Hash collision while resizing HPT\n");
863 
864 	return rc;
865 }
866 #endif /* CONFIG_MEMORY_HOTPLUG */
867 
hash_init_partition_table(phys_addr_t hash_table,unsigned long htab_size)868 static void __init hash_init_partition_table(phys_addr_t hash_table,
869 					     unsigned long htab_size)
870 {
871 	mmu_partition_table_init();
872 
873 	/*
874 	 * PS field (VRMA page size) is not used for LPID 0, hence set to 0.
875 	 * For now, UPRT is 0 and we have no segment table.
876 	 */
877 	htab_size =  __ilog2(htab_size) - 18;
878 	mmu_partition_table_set_entry(0, hash_table | htab_size, 0, false);
879 	pr_info("Partition table %p\n", partition_tb);
880 }
881 
htab_initialize(void)882 static void __init htab_initialize(void)
883 {
884 	unsigned long table;
885 	unsigned long pteg_count;
886 	unsigned long prot;
887 	phys_addr_t base = 0, size = 0, end;
888 	u64 i;
889 
890 	DBG(" -> htab_initialize()\n");
891 
892 	if (mmu_has_feature(MMU_FTR_1T_SEGMENT)) {
893 		mmu_kernel_ssize = MMU_SEGSIZE_1T;
894 		mmu_highuser_ssize = MMU_SEGSIZE_1T;
895 		printk(KERN_INFO "Using 1TB segments\n");
896 	}
897 
898 	if (stress_slb_enabled)
899 		static_branch_enable(&stress_slb_key);
900 
901 	/*
902 	 * Calculate the required size of the htab.  We want the number of
903 	 * PTEGs to equal one half the number of real pages.
904 	 */
905 	htab_size_bytes = htab_get_table_size();
906 	pteg_count = htab_size_bytes >> 7;
907 
908 	htab_hash_mask = pteg_count - 1;
909 
910 	if (firmware_has_feature(FW_FEATURE_LPAR) ||
911 	    firmware_has_feature(FW_FEATURE_PS3_LV1)) {
912 		/* Using a hypervisor which owns the htab */
913 		htab_address = NULL;
914 		_SDR1 = 0;
915 #ifdef CONFIG_FA_DUMP
916 		/*
917 		 * If firmware assisted dump is active firmware preserves
918 		 * the contents of htab along with entire partition memory.
919 		 * Clear the htab if firmware assisted dump is active so
920 		 * that we dont end up using old mappings.
921 		 */
922 		if (is_fadump_active() && mmu_hash_ops.hpte_clear_all)
923 			mmu_hash_ops.hpte_clear_all();
924 #endif
925 	} else {
926 		unsigned long limit = MEMBLOCK_ALLOC_ANYWHERE;
927 
928 #ifdef CONFIG_PPC_CELL
929 		/*
930 		 * Cell may require the hash table down low when using the
931 		 * Axon IOMMU in order to fit the dynamic region over it, see
932 		 * comments in cell/iommu.c
933 		 */
934 		if (fdt_subnode_offset(initial_boot_params, 0, "axon") > 0) {
935 			limit = 0x80000000;
936 			pr_info("Hash table forced below 2G for Axon IOMMU\n");
937 		}
938 #endif /* CONFIG_PPC_CELL */
939 
940 		table = memblock_phys_alloc_range(htab_size_bytes,
941 						  htab_size_bytes,
942 						  0, limit);
943 		if (!table)
944 			panic("ERROR: Failed to allocate %pa bytes below %pa\n",
945 			      &htab_size_bytes, &limit);
946 
947 		DBG("Hash table allocated at %lx, size: %lx\n", table,
948 		    htab_size_bytes);
949 
950 		htab_address = __va(table);
951 
952 		/* htab absolute addr + encoded htabsize */
953 		_SDR1 = table + __ilog2(htab_size_bytes) - 18;
954 
955 		/* Initialize the HPT with no entries */
956 		memset((void *)table, 0, htab_size_bytes);
957 
958 		if (!cpu_has_feature(CPU_FTR_ARCH_300))
959 			/* Set SDR1 */
960 			mtspr(SPRN_SDR1, _SDR1);
961 		else
962 			hash_init_partition_table(table, htab_size_bytes);
963 	}
964 
965 	prot = pgprot_val(PAGE_KERNEL);
966 
967 #ifdef CONFIG_DEBUG_PAGEALLOC
968 	if (debug_pagealloc_enabled()) {
969 		linear_map_hash_count = memblock_end_of_DRAM() >> PAGE_SHIFT;
970 		linear_map_hash_slots = memblock_alloc_try_nid(
971 				linear_map_hash_count, 1, MEMBLOCK_LOW_LIMIT,
972 				ppc64_rma_size,	NUMA_NO_NODE);
973 		if (!linear_map_hash_slots)
974 			panic("%s: Failed to allocate %lu bytes max_addr=%pa\n",
975 			      __func__, linear_map_hash_count, &ppc64_rma_size);
976 	}
977 #endif /* CONFIG_DEBUG_PAGEALLOC */
978 
979 	/* create bolted the linear mapping in the hash table */
980 	for_each_mem_range(i, &base, &end) {
981 		size = end - base;
982 		base = (unsigned long)__va(base);
983 
984 		DBG("creating mapping for region: %lx..%lx (prot: %lx)\n",
985 		    base, size, prot);
986 
987 		if ((base + size) >= H_VMALLOC_START) {
988 			pr_warn("Outside the supported range\n");
989 			continue;
990 		}
991 
992 		BUG_ON(htab_bolt_mapping(base, base + size, __pa(base),
993 				prot, mmu_linear_psize, mmu_kernel_ssize));
994 	}
995 	memblock_set_current_limit(MEMBLOCK_ALLOC_ANYWHERE);
996 
997 	/*
998 	 * If we have a memory_limit and we've allocated TCEs then we need to
999 	 * explicitly map the TCE area at the top of RAM. We also cope with the
1000 	 * case that the TCEs start below memory_limit.
1001 	 * tce_alloc_start/end are 16MB aligned so the mapping should work
1002 	 * for either 4K or 16MB pages.
1003 	 */
1004 	if (tce_alloc_start) {
1005 		tce_alloc_start = (unsigned long)__va(tce_alloc_start);
1006 		tce_alloc_end = (unsigned long)__va(tce_alloc_end);
1007 
1008 		if (base + size >= tce_alloc_start)
1009 			tce_alloc_start = base + size + 1;
1010 
1011 		BUG_ON(htab_bolt_mapping(tce_alloc_start, tce_alloc_end,
1012 					 __pa(tce_alloc_start), prot,
1013 					 mmu_linear_psize, mmu_kernel_ssize));
1014 	}
1015 
1016 
1017 	DBG(" <- htab_initialize()\n");
1018 }
1019 #undef KB
1020 #undef MB
1021 
hash__early_init_devtree(void)1022 void __init hash__early_init_devtree(void)
1023 {
1024 	/* Initialize segment sizes */
1025 	of_scan_flat_dt(htab_dt_scan_seg_sizes, NULL);
1026 
1027 	/* Initialize page sizes */
1028 	htab_scan_page_sizes();
1029 }
1030 
1031 static struct hash_mm_context init_hash_mm_context;
hash__early_init_mmu(void)1032 void __init hash__early_init_mmu(void)
1033 {
1034 #ifndef CONFIG_PPC_64K_PAGES
1035 	/*
1036 	 * We have code in __hash_page_4K() and elsewhere, which assumes it can
1037 	 * do the following:
1038 	 *   new_pte |= (slot << H_PAGE_F_GIX_SHIFT) & (H_PAGE_F_SECOND | H_PAGE_F_GIX);
1039 	 *
1040 	 * Where the slot number is between 0-15, and values of 8-15 indicate
1041 	 * the secondary bucket. For that code to work H_PAGE_F_SECOND and
1042 	 * H_PAGE_F_GIX must occupy four contiguous bits in the PTE, and
1043 	 * H_PAGE_F_SECOND must be placed above H_PAGE_F_GIX. Assert that here
1044 	 * with a BUILD_BUG_ON().
1045 	 */
1046 	BUILD_BUG_ON(H_PAGE_F_SECOND != (1ul  << (H_PAGE_F_GIX_SHIFT + 3)));
1047 #endif /* CONFIG_PPC_64K_PAGES */
1048 
1049 	htab_init_page_sizes();
1050 
1051 	/*
1052 	 * initialize page table size
1053 	 */
1054 	__pte_frag_nr = H_PTE_FRAG_NR;
1055 	__pte_frag_size_shift = H_PTE_FRAG_SIZE_SHIFT;
1056 	__pmd_frag_nr = H_PMD_FRAG_NR;
1057 	__pmd_frag_size_shift = H_PMD_FRAG_SIZE_SHIFT;
1058 
1059 	__pte_index_size = H_PTE_INDEX_SIZE;
1060 	__pmd_index_size = H_PMD_INDEX_SIZE;
1061 	__pud_index_size = H_PUD_INDEX_SIZE;
1062 	__pgd_index_size = H_PGD_INDEX_SIZE;
1063 	__pud_cache_index = H_PUD_CACHE_INDEX;
1064 	__pte_table_size = H_PTE_TABLE_SIZE;
1065 	__pmd_table_size = H_PMD_TABLE_SIZE;
1066 	__pud_table_size = H_PUD_TABLE_SIZE;
1067 	__pgd_table_size = H_PGD_TABLE_SIZE;
1068 	/*
1069 	 * 4k use hugepd format, so for hash set then to
1070 	 * zero
1071 	 */
1072 	__pmd_val_bits = HASH_PMD_VAL_BITS;
1073 	__pud_val_bits = HASH_PUD_VAL_BITS;
1074 	__pgd_val_bits = HASH_PGD_VAL_BITS;
1075 
1076 	__kernel_virt_start = H_KERN_VIRT_START;
1077 	__vmalloc_start = H_VMALLOC_START;
1078 	__vmalloc_end = H_VMALLOC_END;
1079 	__kernel_io_start = H_KERN_IO_START;
1080 	__kernel_io_end = H_KERN_IO_END;
1081 	vmemmap = (struct page *)H_VMEMMAP_START;
1082 	ioremap_bot = IOREMAP_BASE;
1083 
1084 #ifdef CONFIG_PCI
1085 	pci_io_base = ISA_IO_BASE;
1086 #endif
1087 
1088 	/* Select appropriate backend */
1089 	if (firmware_has_feature(FW_FEATURE_PS3_LV1))
1090 		ps3_early_mm_init();
1091 	else if (firmware_has_feature(FW_FEATURE_LPAR))
1092 		hpte_init_pseries();
1093 	else if (IS_ENABLED(CONFIG_PPC_NATIVE))
1094 		hpte_init_native();
1095 
1096 	if (!mmu_hash_ops.hpte_insert)
1097 		panic("hash__early_init_mmu: No MMU hash ops defined!\n");
1098 
1099 	/*
1100 	 * Initialize the MMU Hash table and create the linear mapping
1101 	 * of memory. Has to be done before SLB initialization as this is
1102 	 * currently where the page size encoding is obtained.
1103 	 */
1104 	htab_initialize();
1105 
1106 	init_mm.context.hash_context = &init_hash_mm_context;
1107 	mm_ctx_set_slb_addr_limit(&init_mm.context, SLB_ADDR_LIMIT_DEFAULT);
1108 
1109 	pr_info("Initializing hash mmu with SLB\n");
1110 	/* Initialize SLB management */
1111 	slb_initialize();
1112 
1113 	if (cpu_has_feature(CPU_FTR_ARCH_206)
1114 			&& cpu_has_feature(CPU_FTR_HVMODE))
1115 		tlbiel_all();
1116 }
1117 
1118 #ifdef CONFIG_SMP
hash__early_init_mmu_secondary(void)1119 void hash__early_init_mmu_secondary(void)
1120 {
1121 	/* Initialize hash table for that CPU */
1122 	if (!firmware_has_feature(FW_FEATURE_LPAR)) {
1123 
1124 		if (!cpu_has_feature(CPU_FTR_ARCH_300))
1125 			mtspr(SPRN_SDR1, _SDR1);
1126 		else
1127 			set_ptcr_when_no_uv(__pa(partition_tb) |
1128 					    (PATB_SIZE_SHIFT - 12));
1129 	}
1130 	/* Initialize SLB */
1131 	slb_initialize();
1132 
1133 	if (cpu_has_feature(CPU_FTR_ARCH_206)
1134 			&& cpu_has_feature(CPU_FTR_HVMODE))
1135 		tlbiel_all();
1136 
1137 #ifdef CONFIG_PPC_MEM_KEYS
1138 	if (mmu_has_feature(MMU_FTR_PKEY))
1139 		mtspr(SPRN_UAMOR, default_uamor);
1140 #endif
1141 }
1142 #endif /* CONFIG_SMP */
1143 
1144 /*
1145  * Called by asm hashtable.S for doing lazy icache flush
1146  */
hash_page_do_lazy_icache(unsigned int pp,pte_t pte,int trap)1147 unsigned int hash_page_do_lazy_icache(unsigned int pp, pte_t pte, int trap)
1148 {
1149 	struct page *page;
1150 
1151 	if (!pfn_valid(pte_pfn(pte)))
1152 		return pp;
1153 
1154 	page = pte_page(pte);
1155 
1156 	/* page is dirty */
1157 	if (!test_bit(PG_arch_1, &page->flags) && !PageReserved(page)) {
1158 		if (trap == 0x400) {
1159 			flush_dcache_icache_page(page);
1160 			set_bit(PG_arch_1, &page->flags);
1161 		} else
1162 			pp |= HPTE_R_N;
1163 	}
1164 	return pp;
1165 }
1166 
1167 #ifdef CONFIG_PPC_MM_SLICES
get_paca_psize(unsigned long addr)1168 static unsigned int get_paca_psize(unsigned long addr)
1169 {
1170 	unsigned char *psizes;
1171 	unsigned long index, mask_index;
1172 
1173 	if (addr < SLICE_LOW_TOP) {
1174 		psizes = get_paca()->mm_ctx_low_slices_psize;
1175 		index = GET_LOW_SLICE_INDEX(addr);
1176 	} else {
1177 		psizes = get_paca()->mm_ctx_high_slices_psize;
1178 		index = GET_HIGH_SLICE_INDEX(addr);
1179 	}
1180 	mask_index = index & 0x1;
1181 	return (psizes[index >> 1] >> (mask_index * 4)) & 0xF;
1182 }
1183 
1184 #else
get_paca_psize(unsigned long addr)1185 unsigned int get_paca_psize(unsigned long addr)
1186 {
1187 	return get_paca()->mm_ctx_user_psize;
1188 }
1189 #endif
1190 
1191 /*
1192  * Demote a segment to using 4k pages.
1193  * For now this makes the whole process use 4k pages.
1194  */
1195 #ifdef CONFIG_PPC_64K_PAGES
demote_segment_4k(struct mm_struct * mm,unsigned long addr)1196 void demote_segment_4k(struct mm_struct *mm, unsigned long addr)
1197 {
1198 	if (get_slice_psize(mm, addr) == MMU_PAGE_4K)
1199 		return;
1200 	slice_set_range_psize(mm, addr, 1, MMU_PAGE_4K);
1201 	copro_flush_all_slbs(mm);
1202 	if ((get_paca_psize(addr) != MMU_PAGE_4K) && (current->mm == mm)) {
1203 
1204 		copy_mm_to_paca(mm);
1205 		slb_flush_and_restore_bolted();
1206 	}
1207 }
1208 #endif /* CONFIG_PPC_64K_PAGES */
1209 
1210 #ifdef CONFIG_PPC_SUBPAGE_PROT
1211 /*
1212  * This looks up a 2-bit protection code for a 4k subpage of a 64k page.
1213  * Userspace sets the subpage permissions using the subpage_prot system call.
1214  *
1215  * Result is 0: full permissions, _PAGE_RW: read-only,
1216  * _PAGE_RWX: no access.
1217  */
subpage_protection(struct mm_struct * mm,unsigned long ea)1218 static int subpage_protection(struct mm_struct *mm, unsigned long ea)
1219 {
1220 	struct subpage_prot_table *spt = mm_ctx_subpage_prot(&mm->context);
1221 	u32 spp = 0;
1222 	u32 **sbpm, *sbpp;
1223 
1224 	if (!spt)
1225 		return 0;
1226 
1227 	if (ea >= spt->maxaddr)
1228 		return 0;
1229 	if (ea < 0x100000000UL) {
1230 		/* addresses below 4GB use spt->low_prot */
1231 		sbpm = spt->low_prot;
1232 	} else {
1233 		sbpm = spt->protptrs[ea >> SBP_L3_SHIFT];
1234 		if (!sbpm)
1235 			return 0;
1236 	}
1237 	sbpp = sbpm[(ea >> SBP_L2_SHIFT) & (SBP_L2_COUNT - 1)];
1238 	if (!sbpp)
1239 		return 0;
1240 	spp = sbpp[(ea >> PAGE_SHIFT) & (SBP_L1_COUNT - 1)];
1241 
1242 	/* extract 2-bit bitfield for this 4k subpage */
1243 	spp >>= 30 - 2 * ((ea >> 12) & 0xf);
1244 
1245 	/*
1246 	 * 0 -> full premission
1247 	 * 1 -> Read only
1248 	 * 2 -> no access.
1249 	 * We return the flag that need to be cleared.
1250 	 */
1251 	spp = ((spp & 2) ? _PAGE_RWX : 0) | ((spp & 1) ? _PAGE_WRITE : 0);
1252 	return spp;
1253 }
1254 
1255 #else /* CONFIG_PPC_SUBPAGE_PROT */
subpage_protection(struct mm_struct * mm,unsigned long ea)1256 static inline int subpage_protection(struct mm_struct *mm, unsigned long ea)
1257 {
1258 	return 0;
1259 }
1260 #endif
1261 
hash_failure_debug(unsigned long ea,unsigned long access,unsigned long vsid,unsigned long trap,int ssize,int psize,int lpsize,unsigned long pte)1262 void hash_failure_debug(unsigned long ea, unsigned long access,
1263 			unsigned long vsid, unsigned long trap,
1264 			int ssize, int psize, int lpsize, unsigned long pte)
1265 {
1266 	if (!printk_ratelimit())
1267 		return;
1268 	pr_info("mm: Hashing failure ! EA=0x%lx access=0x%lx current=%s\n",
1269 		ea, access, current->comm);
1270 	pr_info("    trap=0x%lx vsid=0x%lx ssize=%d base psize=%d psize %d pte=0x%lx\n",
1271 		trap, vsid, ssize, psize, lpsize, pte);
1272 }
1273 
check_paca_psize(unsigned long ea,struct mm_struct * mm,int psize,bool user_region)1274 static void check_paca_psize(unsigned long ea, struct mm_struct *mm,
1275 			     int psize, bool user_region)
1276 {
1277 	if (user_region) {
1278 		if (psize != get_paca_psize(ea)) {
1279 			copy_mm_to_paca(mm);
1280 			slb_flush_and_restore_bolted();
1281 		}
1282 	} else if (get_paca()->vmalloc_sllp !=
1283 		   mmu_psize_defs[mmu_vmalloc_psize].sllp) {
1284 		get_paca()->vmalloc_sllp =
1285 			mmu_psize_defs[mmu_vmalloc_psize].sllp;
1286 		slb_vmalloc_update();
1287 	}
1288 }
1289 
1290 /*
1291  * Result code is:
1292  *  0 - handled
1293  *  1 - normal page fault
1294  * -1 - critical hash insertion error
1295  * -2 - access not permitted by subpage protection mechanism
1296  */
hash_page_mm(struct mm_struct * mm,unsigned long ea,unsigned long access,unsigned long trap,unsigned long flags)1297 int hash_page_mm(struct mm_struct *mm, unsigned long ea,
1298 		 unsigned long access, unsigned long trap,
1299 		 unsigned long flags)
1300 {
1301 	bool is_thp;
1302 	enum ctx_state prev_state = exception_enter();
1303 	pgd_t *pgdir;
1304 	unsigned long vsid;
1305 	pte_t *ptep;
1306 	unsigned hugeshift;
1307 	int rc, user_region = 0;
1308 	int psize, ssize;
1309 
1310 	DBG_LOW("hash_page(ea=%016lx, access=%lx, trap=%lx\n",
1311 		ea, access, trap);
1312 	trace_hash_fault(ea, access, trap);
1313 
1314 	/* Get region & vsid */
1315 	switch (get_region_id(ea)) {
1316 	case USER_REGION_ID:
1317 		user_region = 1;
1318 		if (! mm) {
1319 			DBG_LOW(" user region with no mm !\n");
1320 			rc = 1;
1321 			goto bail;
1322 		}
1323 		psize = get_slice_psize(mm, ea);
1324 		ssize = user_segment_size(ea);
1325 		vsid = get_user_vsid(&mm->context, ea, ssize);
1326 		break;
1327 	case VMALLOC_REGION_ID:
1328 		vsid = get_kernel_vsid(ea, mmu_kernel_ssize);
1329 		psize = mmu_vmalloc_psize;
1330 		ssize = mmu_kernel_ssize;
1331 		break;
1332 
1333 	case IO_REGION_ID:
1334 		vsid = get_kernel_vsid(ea, mmu_kernel_ssize);
1335 		psize = mmu_io_psize;
1336 		ssize = mmu_kernel_ssize;
1337 		break;
1338 	default:
1339 		/*
1340 		 * Not a valid range
1341 		 * Send the problem up to do_page_fault()
1342 		 */
1343 		rc = 1;
1344 		goto bail;
1345 	}
1346 	DBG_LOW(" mm=%p, mm->pgdir=%p, vsid=%016lx\n", mm, mm->pgd, vsid);
1347 
1348 	/* Bad address. */
1349 	if (!vsid) {
1350 		DBG_LOW("Bad address!\n");
1351 		rc = 1;
1352 		goto bail;
1353 	}
1354 	/* Get pgdir */
1355 	pgdir = mm->pgd;
1356 	if (pgdir == NULL) {
1357 		rc = 1;
1358 		goto bail;
1359 	}
1360 
1361 	/* Check CPU locality */
1362 	if (user_region && mm_is_thread_local(mm))
1363 		flags |= HPTE_LOCAL_UPDATE;
1364 
1365 #ifndef CONFIG_PPC_64K_PAGES
1366 	/*
1367 	 * If we use 4K pages and our psize is not 4K, then we might
1368 	 * be hitting a special driver mapping, and need to align the
1369 	 * address before we fetch the PTE.
1370 	 *
1371 	 * It could also be a hugepage mapping, in which case this is
1372 	 * not necessary, but it's not harmful, either.
1373 	 */
1374 	if (psize != MMU_PAGE_4K)
1375 		ea &= ~((1ul << mmu_psize_defs[psize].shift) - 1);
1376 #endif /* CONFIG_PPC_64K_PAGES */
1377 
1378 	/* Get PTE and page size from page tables */
1379 	ptep = find_linux_pte(pgdir, ea, &is_thp, &hugeshift);
1380 	if (ptep == NULL || !pte_present(*ptep)) {
1381 		DBG_LOW(" no PTE !\n");
1382 		rc = 1;
1383 		goto bail;
1384 	}
1385 
1386 	/*
1387 	 * Add _PAGE_PRESENT to the required access perm. If there are parallel
1388 	 * updates to the pte that can possibly clear _PAGE_PTE, catch that too.
1389 	 *
1390 	 * We can safely use the return pte address in rest of the function
1391 	 * because we do set H_PAGE_BUSY which prevents further updates to pte
1392 	 * from generic code.
1393 	 */
1394 	access |= _PAGE_PRESENT | _PAGE_PTE;
1395 
1396 	/*
1397 	 * Pre-check access permissions (will be re-checked atomically
1398 	 * in __hash_page_XX but this pre-check is a fast path
1399 	 */
1400 	if (!check_pte_access(access, pte_val(*ptep))) {
1401 		DBG_LOW(" no access !\n");
1402 		rc = 1;
1403 		goto bail;
1404 	}
1405 
1406 	if (hugeshift) {
1407 		if (is_thp)
1408 			rc = __hash_page_thp(ea, access, vsid, (pmd_t *)ptep,
1409 					     trap, flags, ssize, psize);
1410 #ifdef CONFIG_HUGETLB_PAGE
1411 		else
1412 			rc = __hash_page_huge(ea, access, vsid, ptep, trap,
1413 					      flags, ssize, hugeshift, psize);
1414 #else
1415 		else {
1416 			/*
1417 			 * if we have hugeshift, and is not transhuge with
1418 			 * hugetlb disabled, something is really wrong.
1419 			 */
1420 			rc = 1;
1421 			WARN_ON(1);
1422 		}
1423 #endif
1424 		if (current->mm == mm)
1425 			check_paca_psize(ea, mm, psize, user_region);
1426 
1427 		goto bail;
1428 	}
1429 
1430 #ifndef CONFIG_PPC_64K_PAGES
1431 	DBG_LOW(" i-pte: %016lx\n", pte_val(*ptep));
1432 #else
1433 	DBG_LOW(" i-pte: %016lx %016lx\n", pte_val(*ptep),
1434 		pte_val(*(ptep + PTRS_PER_PTE)));
1435 #endif
1436 	/* Do actual hashing */
1437 #ifdef CONFIG_PPC_64K_PAGES
1438 	/* If H_PAGE_4K_PFN is set, make sure this is a 4k segment */
1439 	if ((pte_val(*ptep) & H_PAGE_4K_PFN) && psize == MMU_PAGE_64K) {
1440 		demote_segment_4k(mm, ea);
1441 		psize = MMU_PAGE_4K;
1442 	}
1443 
1444 	/*
1445 	 * If this PTE is non-cacheable and we have restrictions on
1446 	 * using non cacheable large pages, then we switch to 4k
1447 	 */
1448 	if (mmu_ci_restrictions && psize == MMU_PAGE_64K && pte_ci(*ptep)) {
1449 		if (user_region) {
1450 			demote_segment_4k(mm, ea);
1451 			psize = MMU_PAGE_4K;
1452 		} else if (ea < VMALLOC_END) {
1453 			/*
1454 			 * some driver did a non-cacheable mapping
1455 			 * in vmalloc space, so switch vmalloc
1456 			 * to 4k pages
1457 			 */
1458 			printk(KERN_ALERT "Reducing vmalloc segment "
1459 			       "to 4kB pages because of "
1460 			       "non-cacheable mapping\n");
1461 			psize = mmu_vmalloc_psize = MMU_PAGE_4K;
1462 			copro_flush_all_slbs(mm);
1463 		}
1464 	}
1465 
1466 #endif /* CONFIG_PPC_64K_PAGES */
1467 
1468 	if (current->mm == mm)
1469 		check_paca_psize(ea, mm, psize, user_region);
1470 
1471 #ifdef CONFIG_PPC_64K_PAGES
1472 	if (psize == MMU_PAGE_64K)
1473 		rc = __hash_page_64K(ea, access, vsid, ptep, trap,
1474 				     flags, ssize);
1475 	else
1476 #endif /* CONFIG_PPC_64K_PAGES */
1477 	{
1478 		int spp = subpage_protection(mm, ea);
1479 		if (access & spp)
1480 			rc = -2;
1481 		else
1482 			rc = __hash_page_4K(ea, access, vsid, ptep, trap,
1483 					    flags, ssize, spp);
1484 	}
1485 
1486 	/*
1487 	 * Dump some info in case of hash insertion failure, they should
1488 	 * never happen so it is really useful to know if/when they do
1489 	 */
1490 	if (rc == -1)
1491 		hash_failure_debug(ea, access, vsid, trap, ssize, psize,
1492 				   psize, pte_val(*ptep));
1493 #ifndef CONFIG_PPC_64K_PAGES
1494 	DBG_LOW(" o-pte: %016lx\n", pte_val(*ptep));
1495 #else
1496 	DBG_LOW(" o-pte: %016lx %016lx\n", pte_val(*ptep),
1497 		pte_val(*(ptep + PTRS_PER_PTE)));
1498 #endif
1499 	DBG_LOW(" -> rc=%d\n", rc);
1500 
1501 bail:
1502 	exception_exit(prev_state);
1503 	return rc;
1504 }
1505 EXPORT_SYMBOL_GPL(hash_page_mm);
1506 
hash_page(unsigned long ea,unsigned long access,unsigned long trap,unsigned long dsisr)1507 int hash_page(unsigned long ea, unsigned long access, unsigned long trap,
1508 	      unsigned long dsisr)
1509 {
1510 	unsigned long flags = 0;
1511 	struct mm_struct *mm = current->mm;
1512 
1513 	if ((get_region_id(ea) == VMALLOC_REGION_ID) ||
1514 	    (get_region_id(ea) == IO_REGION_ID))
1515 		mm = &init_mm;
1516 
1517 	if (dsisr & DSISR_NOHPTE)
1518 		flags |= HPTE_NOHPTE_UPDATE;
1519 
1520 	return hash_page_mm(mm, ea, access, trap, flags);
1521 }
1522 EXPORT_SYMBOL_GPL(hash_page);
1523 
__hash_page(unsigned long trap,unsigned long ea,unsigned long dsisr,unsigned long msr)1524 int __hash_page(unsigned long trap, unsigned long ea, unsigned long dsisr,
1525 		unsigned long msr)
1526 {
1527 	unsigned long access = _PAGE_PRESENT | _PAGE_READ;
1528 	unsigned long flags = 0;
1529 	struct mm_struct *mm = current->mm;
1530 	unsigned int region_id = get_region_id(ea);
1531 
1532 	if ((region_id == VMALLOC_REGION_ID) || (region_id == IO_REGION_ID))
1533 		mm = &init_mm;
1534 
1535 	if (dsisr & DSISR_NOHPTE)
1536 		flags |= HPTE_NOHPTE_UPDATE;
1537 
1538 	if (dsisr & DSISR_ISSTORE)
1539 		access |= _PAGE_WRITE;
1540 	/*
1541 	 * We set _PAGE_PRIVILEGED only when
1542 	 * kernel mode access kernel space.
1543 	 *
1544 	 * _PAGE_PRIVILEGED is NOT set
1545 	 * 1) when kernel mode access user space
1546 	 * 2) user space access kernel space.
1547 	 */
1548 	access |= _PAGE_PRIVILEGED;
1549 	if ((msr & MSR_PR) || (region_id == USER_REGION_ID))
1550 		access &= ~_PAGE_PRIVILEGED;
1551 
1552 	if (trap == 0x400)
1553 		access |= _PAGE_EXEC;
1554 
1555 	return hash_page_mm(mm, ea, access, trap, flags);
1556 }
1557 
1558 #ifdef CONFIG_PPC_MM_SLICES
should_hash_preload(struct mm_struct * mm,unsigned long ea)1559 static bool should_hash_preload(struct mm_struct *mm, unsigned long ea)
1560 {
1561 	int psize = get_slice_psize(mm, ea);
1562 
1563 	/* We only prefault standard pages for now */
1564 	if (unlikely(psize != mm_ctx_user_psize(&mm->context)))
1565 		return false;
1566 
1567 	/*
1568 	 * Don't prefault if subpage protection is enabled for the EA.
1569 	 */
1570 	if (unlikely((psize == MMU_PAGE_4K) && subpage_protection(mm, ea)))
1571 		return false;
1572 
1573 	return true;
1574 }
1575 #else
should_hash_preload(struct mm_struct * mm,unsigned long ea)1576 static bool should_hash_preload(struct mm_struct *mm, unsigned long ea)
1577 {
1578 	return true;
1579 }
1580 #endif
1581 
hash_preload(struct mm_struct * mm,pte_t * ptep,unsigned long ea,bool is_exec,unsigned long trap)1582 static void hash_preload(struct mm_struct *mm, pte_t *ptep, unsigned long ea,
1583 			 bool is_exec, unsigned long trap)
1584 {
1585 	unsigned long vsid;
1586 	pgd_t *pgdir;
1587 	int rc, ssize, update_flags = 0;
1588 	unsigned long access = _PAGE_PRESENT | _PAGE_READ | (is_exec ? _PAGE_EXEC : 0);
1589 	unsigned long flags;
1590 
1591 	BUG_ON(get_region_id(ea) != USER_REGION_ID);
1592 
1593 	if (!should_hash_preload(mm, ea))
1594 		return;
1595 
1596 	DBG_LOW("hash_preload(mm=%p, mm->pgdir=%p, ea=%016lx, access=%lx,"
1597 		" trap=%lx\n", mm, mm->pgd, ea, access, trap);
1598 
1599 	/* Get Linux PTE if available */
1600 	pgdir = mm->pgd;
1601 	if (pgdir == NULL)
1602 		return;
1603 
1604 	/* Get VSID */
1605 	ssize = user_segment_size(ea);
1606 	vsid = get_user_vsid(&mm->context, ea, ssize);
1607 	if (!vsid)
1608 		return;
1609 
1610 #ifdef CONFIG_PPC_64K_PAGES
1611 	/* If either H_PAGE_4K_PFN or cache inhibited is set (and we are on
1612 	 * a 64K kernel), then we don't preload, hash_page() will take
1613 	 * care of it once we actually try to access the page.
1614 	 * That way we don't have to duplicate all of the logic for segment
1615 	 * page size demotion here
1616 	 * Called with  PTL held, hence can be sure the value won't change in
1617 	 * between.
1618 	 */
1619 	if ((pte_val(*ptep) & H_PAGE_4K_PFN) || pte_ci(*ptep))
1620 		return;
1621 #endif /* CONFIG_PPC_64K_PAGES */
1622 
1623 	/*
1624 	 * __hash_page_* must run with interrupts off, as it sets the
1625 	 * H_PAGE_BUSY bit. It's possible for perf interrupts to hit at any
1626 	 * time and may take a hash fault reading the user stack, see
1627 	 * read_user_stack_slow() in the powerpc/perf code.
1628 	 *
1629 	 * If that takes a hash fault on the same page as we lock here, it
1630 	 * will bail out when seeing H_PAGE_BUSY set, and retry the access
1631 	 * leading to an infinite loop.
1632 	 *
1633 	 * Disabling interrupts here does not prevent perf interrupts, but it
1634 	 * will prevent them taking hash faults (see the NMI test in
1635 	 * do_hash_page), then read_user_stack's copy_from_user_nofault will
1636 	 * fail and perf will fall back to read_user_stack_slow(), which
1637 	 * walks the Linux page tables.
1638 	 *
1639 	 * Interrupts must also be off for the duration of the
1640 	 * mm_is_thread_local test and update, to prevent preempt running the
1641 	 * mm on another CPU (XXX: this may be racy vs kthread_use_mm).
1642 	 */
1643 	local_irq_save(flags);
1644 
1645 	/* Is that local to this CPU ? */
1646 	if (mm_is_thread_local(mm))
1647 		update_flags |= HPTE_LOCAL_UPDATE;
1648 
1649 	/* Hash it in */
1650 #ifdef CONFIG_PPC_64K_PAGES
1651 	if (mm_ctx_user_psize(&mm->context) == MMU_PAGE_64K)
1652 		rc = __hash_page_64K(ea, access, vsid, ptep, trap,
1653 				     update_flags, ssize);
1654 	else
1655 #endif /* CONFIG_PPC_64K_PAGES */
1656 		rc = __hash_page_4K(ea, access, vsid, ptep, trap, update_flags,
1657 				    ssize, subpage_protection(mm, ea));
1658 
1659 	/* Dump some info in case of hash insertion failure, they should
1660 	 * never happen so it is really useful to know if/when they do
1661 	 */
1662 	if (rc == -1)
1663 		hash_failure_debug(ea, access, vsid, trap, ssize,
1664 				   mm_ctx_user_psize(&mm->context),
1665 				   mm_ctx_user_psize(&mm->context),
1666 				   pte_val(*ptep));
1667 
1668 	local_irq_restore(flags);
1669 }
1670 
1671 /*
1672  * This is called at the end of handling a user page fault, when the
1673  * fault has been handled by updating a PTE in the linux page tables.
1674  * We use it to preload an HPTE into the hash table corresponding to
1675  * the updated linux PTE.
1676  *
1677  * This must always be called with the pte lock held.
1678  */
update_mmu_cache(struct vm_area_struct * vma,unsigned long address,pte_t * ptep)1679 void update_mmu_cache(struct vm_area_struct *vma, unsigned long address,
1680 		      pte_t *ptep)
1681 {
1682 	/*
1683 	 * We don't need to worry about _PAGE_PRESENT here because we are
1684 	 * called with either mm->page_table_lock held or ptl lock held
1685 	 */
1686 	unsigned long trap;
1687 	bool is_exec;
1688 
1689 	if (radix_enabled())
1690 		return;
1691 
1692 	/* We only want HPTEs for linux PTEs that have _PAGE_ACCESSED set */
1693 	if (!pte_young(*ptep) || address >= TASK_SIZE)
1694 		return;
1695 
1696 	/*
1697 	 * We try to figure out if we are coming from an instruction
1698 	 * access fault and pass that down to __hash_page so we avoid
1699 	 * double-faulting on execution of fresh text. We have to test
1700 	 * for regs NULL since init will get here first thing at boot.
1701 	 *
1702 	 * We also avoid filling the hash if not coming from a fault.
1703 	 */
1704 
1705 	trap = current->thread.regs ? TRAP(current->thread.regs) : 0UL;
1706 	switch (trap) {
1707 	case 0x300:
1708 		is_exec = false;
1709 		break;
1710 	case 0x400:
1711 		is_exec = true;
1712 		break;
1713 	default:
1714 		return;
1715 	}
1716 
1717 	hash_preload(vma->vm_mm, ptep, address, is_exec, trap);
1718 }
1719 
1720 #ifdef CONFIG_PPC_TRANSACTIONAL_MEM
tm_flush_hash_page(int local)1721 static inline void tm_flush_hash_page(int local)
1722 {
1723 	/*
1724 	 * Transactions are not aborted by tlbiel, only tlbie. Without, syncing a
1725 	 * page back to a block device w/PIO could pick up transactional data
1726 	 * (bad!) so we force an abort here. Before the sync the page will be
1727 	 * made read-only, which will flush_hash_page. BIG ISSUE here: if the
1728 	 * kernel uses a page from userspace without unmapping it first, it may
1729 	 * see the speculated version.
1730 	 */
1731 	if (local && cpu_has_feature(CPU_FTR_TM) && current->thread.regs &&
1732 	    MSR_TM_ACTIVE(current->thread.regs->msr)) {
1733 		tm_enable();
1734 		tm_abort(TM_CAUSE_TLBI);
1735 	}
1736 }
1737 #else
tm_flush_hash_page(int local)1738 static inline void tm_flush_hash_page(int local)
1739 {
1740 }
1741 #endif
1742 
1743 /*
1744  * Return the global hash slot, corresponding to the given PTE, which contains
1745  * the HPTE.
1746  */
pte_get_hash_gslot(unsigned long vpn,unsigned long shift,int ssize,real_pte_t rpte,unsigned int subpg_index)1747 unsigned long pte_get_hash_gslot(unsigned long vpn, unsigned long shift,
1748 		int ssize, real_pte_t rpte, unsigned int subpg_index)
1749 {
1750 	unsigned long hash, gslot, hidx;
1751 
1752 	hash = hpt_hash(vpn, shift, ssize);
1753 	hidx = __rpte_to_hidx(rpte, subpg_index);
1754 	if (hidx & _PTEIDX_SECONDARY)
1755 		hash = ~hash;
1756 	gslot = (hash & htab_hash_mask) * HPTES_PER_GROUP;
1757 	gslot += hidx & _PTEIDX_GROUP_IX;
1758 	return gslot;
1759 }
1760 
flush_hash_page(unsigned long vpn,real_pte_t pte,int psize,int ssize,unsigned long flags)1761 void flush_hash_page(unsigned long vpn, real_pte_t pte, int psize, int ssize,
1762 		     unsigned long flags)
1763 {
1764 	unsigned long index, shift, gslot;
1765 	int local = flags & HPTE_LOCAL_UPDATE;
1766 
1767 	DBG_LOW("flush_hash_page(vpn=%016lx)\n", vpn);
1768 	pte_iterate_hashed_subpages(pte, psize, vpn, index, shift) {
1769 		gslot = pte_get_hash_gslot(vpn, shift, ssize, pte, index);
1770 		DBG_LOW(" sub %ld: gslot=%lx\n", index, gslot);
1771 		/*
1772 		 * We use same base page size and actual psize, because we don't
1773 		 * use these functions for hugepage
1774 		 */
1775 		mmu_hash_ops.hpte_invalidate(gslot, vpn, psize, psize,
1776 					     ssize, local);
1777 	} pte_iterate_hashed_end();
1778 
1779 	tm_flush_hash_page(local);
1780 }
1781 
1782 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
flush_hash_hugepage(unsigned long vsid,unsigned long addr,pmd_t * pmdp,unsigned int psize,int ssize,unsigned long flags)1783 void flush_hash_hugepage(unsigned long vsid, unsigned long addr,
1784 			 pmd_t *pmdp, unsigned int psize, int ssize,
1785 			 unsigned long flags)
1786 {
1787 	int i, max_hpte_count, valid;
1788 	unsigned long s_addr;
1789 	unsigned char *hpte_slot_array;
1790 	unsigned long hidx, shift, vpn, hash, slot;
1791 	int local = flags & HPTE_LOCAL_UPDATE;
1792 
1793 	s_addr = addr & HPAGE_PMD_MASK;
1794 	hpte_slot_array = get_hpte_slot_array(pmdp);
1795 	/*
1796 	 * IF we try to do a HUGE PTE update after a withdraw is done.
1797 	 * we will find the below NULL. This happens when we do
1798 	 * split_huge_pmd
1799 	 */
1800 	if (!hpte_slot_array)
1801 		return;
1802 
1803 	if (mmu_hash_ops.hugepage_invalidate) {
1804 		mmu_hash_ops.hugepage_invalidate(vsid, s_addr, hpte_slot_array,
1805 						 psize, ssize, local);
1806 		goto tm_abort;
1807 	}
1808 	/*
1809 	 * No bluk hpte removal support, invalidate each entry
1810 	 */
1811 	shift = mmu_psize_defs[psize].shift;
1812 	max_hpte_count = HPAGE_PMD_SIZE >> shift;
1813 	for (i = 0; i < max_hpte_count; i++) {
1814 		/*
1815 		 * 8 bits per each hpte entries
1816 		 * 000| [ secondary group (one bit) | hidx (3 bits) | valid bit]
1817 		 */
1818 		valid = hpte_valid(hpte_slot_array, i);
1819 		if (!valid)
1820 			continue;
1821 		hidx =  hpte_hash_index(hpte_slot_array, i);
1822 
1823 		/* get the vpn */
1824 		addr = s_addr + (i * (1ul << shift));
1825 		vpn = hpt_vpn(addr, vsid, ssize);
1826 		hash = hpt_hash(vpn, shift, ssize);
1827 		if (hidx & _PTEIDX_SECONDARY)
1828 			hash = ~hash;
1829 
1830 		slot = (hash & htab_hash_mask) * HPTES_PER_GROUP;
1831 		slot += hidx & _PTEIDX_GROUP_IX;
1832 		mmu_hash_ops.hpte_invalidate(slot, vpn, psize,
1833 					     MMU_PAGE_16M, ssize, local);
1834 	}
1835 tm_abort:
1836 	tm_flush_hash_page(local);
1837 }
1838 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
1839 
flush_hash_range(unsigned long number,int local)1840 void flush_hash_range(unsigned long number, int local)
1841 {
1842 	if (mmu_hash_ops.flush_hash_range)
1843 		mmu_hash_ops.flush_hash_range(number, local);
1844 	else {
1845 		int i;
1846 		struct ppc64_tlb_batch *batch =
1847 			this_cpu_ptr(&ppc64_tlb_batch);
1848 
1849 		for (i = 0; i < number; i++)
1850 			flush_hash_page(batch->vpn[i], batch->pte[i],
1851 					batch->psize, batch->ssize, local);
1852 	}
1853 }
1854 
1855 /*
1856  * low_hash_fault is called when we the low level hash code failed
1857  * to instert a PTE due to an hypervisor error
1858  */
low_hash_fault(struct pt_regs * regs,unsigned long address,int rc)1859 void low_hash_fault(struct pt_regs *regs, unsigned long address, int rc)
1860 {
1861 	enum ctx_state prev_state = exception_enter();
1862 
1863 	if (user_mode(regs)) {
1864 #ifdef CONFIG_PPC_SUBPAGE_PROT
1865 		if (rc == -2)
1866 			_exception(SIGSEGV, regs, SEGV_ACCERR, address);
1867 		else
1868 #endif
1869 			_exception(SIGBUS, regs, BUS_ADRERR, address);
1870 	} else
1871 		bad_page_fault(regs, address, SIGBUS);
1872 
1873 	exception_exit(prev_state);
1874 }
1875 
hpte_insert_repeating(unsigned long hash,unsigned long vpn,unsigned long pa,unsigned long rflags,unsigned long vflags,int psize,int ssize)1876 long hpte_insert_repeating(unsigned long hash, unsigned long vpn,
1877 			   unsigned long pa, unsigned long rflags,
1878 			   unsigned long vflags, int psize, int ssize)
1879 {
1880 	unsigned long hpte_group;
1881 	long slot;
1882 
1883 repeat:
1884 	hpte_group = (hash & htab_hash_mask) * HPTES_PER_GROUP;
1885 
1886 	/* Insert into the hash table, primary slot */
1887 	slot = mmu_hash_ops.hpte_insert(hpte_group, vpn, pa, rflags, vflags,
1888 					psize, psize, ssize);
1889 
1890 	/* Primary is full, try the secondary */
1891 	if (unlikely(slot == -1)) {
1892 		hpte_group = (~hash & htab_hash_mask) * HPTES_PER_GROUP;
1893 		slot = mmu_hash_ops.hpte_insert(hpte_group, vpn, pa, rflags,
1894 						vflags | HPTE_V_SECONDARY,
1895 						psize, psize, ssize);
1896 		if (slot == -1) {
1897 			if (mftb() & 0x1)
1898 				hpte_group = (hash & htab_hash_mask) *
1899 						HPTES_PER_GROUP;
1900 
1901 			mmu_hash_ops.hpte_remove(hpte_group);
1902 			goto repeat;
1903 		}
1904 	}
1905 
1906 	return slot;
1907 }
1908 
1909 #ifdef CONFIG_DEBUG_PAGEALLOC
kernel_map_linear_page(unsigned long vaddr,unsigned long lmi)1910 static void kernel_map_linear_page(unsigned long vaddr, unsigned long lmi)
1911 {
1912 	unsigned long hash;
1913 	unsigned long vsid = get_kernel_vsid(vaddr, mmu_kernel_ssize);
1914 	unsigned long vpn = hpt_vpn(vaddr, vsid, mmu_kernel_ssize);
1915 	unsigned long mode = htab_convert_pte_flags(pgprot_val(PAGE_KERNEL));
1916 	long ret;
1917 
1918 	hash = hpt_hash(vpn, PAGE_SHIFT, mmu_kernel_ssize);
1919 
1920 	/* Don't create HPTE entries for bad address */
1921 	if (!vsid)
1922 		return;
1923 
1924 	ret = hpte_insert_repeating(hash, vpn, __pa(vaddr), mode,
1925 				    HPTE_V_BOLTED,
1926 				    mmu_linear_psize, mmu_kernel_ssize);
1927 
1928 	BUG_ON (ret < 0);
1929 	spin_lock(&linear_map_hash_lock);
1930 	BUG_ON(linear_map_hash_slots[lmi] & 0x80);
1931 	linear_map_hash_slots[lmi] = ret | 0x80;
1932 	spin_unlock(&linear_map_hash_lock);
1933 }
1934 
kernel_unmap_linear_page(unsigned long vaddr,unsigned long lmi)1935 static void kernel_unmap_linear_page(unsigned long vaddr, unsigned long lmi)
1936 {
1937 	unsigned long hash, hidx, slot;
1938 	unsigned long vsid = get_kernel_vsid(vaddr, mmu_kernel_ssize);
1939 	unsigned long vpn = hpt_vpn(vaddr, vsid, mmu_kernel_ssize);
1940 
1941 	hash = hpt_hash(vpn, PAGE_SHIFT, mmu_kernel_ssize);
1942 	spin_lock(&linear_map_hash_lock);
1943 	BUG_ON(!(linear_map_hash_slots[lmi] & 0x80));
1944 	hidx = linear_map_hash_slots[lmi] & 0x7f;
1945 	linear_map_hash_slots[lmi] = 0;
1946 	spin_unlock(&linear_map_hash_lock);
1947 	if (hidx & _PTEIDX_SECONDARY)
1948 		hash = ~hash;
1949 	slot = (hash & htab_hash_mask) * HPTES_PER_GROUP;
1950 	slot += hidx & _PTEIDX_GROUP_IX;
1951 	mmu_hash_ops.hpte_invalidate(slot, vpn, mmu_linear_psize,
1952 				     mmu_linear_psize,
1953 				     mmu_kernel_ssize, 0);
1954 }
1955 
__kernel_map_pages(struct page * page,int numpages,int enable)1956 void __kernel_map_pages(struct page *page, int numpages, int enable)
1957 {
1958 	unsigned long flags, vaddr, lmi;
1959 	int i;
1960 
1961 	local_irq_save(flags);
1962 	for (i = 0; i < numpages; i++, page++) {
1963 		vaddr = (unsigned long)page_address(page);
1964 		lmi = __pa(vaddr) >> PAGE_SHIFT;
1965 		if (lmi >= linear_map_hash_count)
1966 			continue;
1967 		if (enable)
1968 			kernel_map_linear_page(vaddr, lmi);
1969 		else
1970 			kernel_unmap_linear_page(vaddr, lmi);
1971 	}
1972 	local_irq_restore(flags);
1973 }
1974 #endif /* CONFIG_DEBUG_PAGEALLOC */
1975 
hash__setup_initial_memory_limit(phys_addr_t first_memblock_base,phys_addr_t first_memblock_size)1976 void hash__setup_initial_memory_limit(phys_addr_t first_memblock_base,
1977 				phys_addr_t first_memblock_size)
1978 {
1979 	/*
1980 	 * We don't currently support the first MEMBLOCK not mapping 0
1981 	 * physical on those processors
1982 	 */
1983 	BUG_ON(first_memblock_base != 0);
1984 
1985 	/*
1986 	 * On virtualized systems the first entry is our RMA region aka VRMA,
1987 	 * non-virtualized 64-bit hash MMU systems don't have a limitation
1988 	 * on real mode access.
1989 	 *
1990 	 * For guests on platforms before POWER9, we clamp the it limit to 1G
1991 	 * to avoid some funky things such as RTAS bugs etc...
1992 	 *
1993 	 * On POWER9 we limit to 1TB in case the host erroneously told us that
1994 	 * the RMA was >1TB. Effective address bits 0:23 are treated as zero
1995 	 * (meaning the access is aliased to zero i.e. addr = addr % 1TB)
1996 	 * for virtual real mode addressing and so it doesn't make sense to
1997 	 * have an area larger than 1TB as it can't be addressed.
1998 	 */
1999 	if (!early_cpu_has_feature(CPU_FTR_HVMODE)) {
2000 		ppc64_rma_size = first_memblock_size;
2001 		if (!early_cpu_has_feature(CPU_FTR_ARCH_300))
2002 			ppc64_rma_size = min_t(u64, ppc64_rma_size, 0x40000000);
2003 		else
2004 			ppc64_rma_size = min_t(u64, ppc64_rma_size,
2005 					       1UL << SID_SHIFT_1T);
2006 
2007 		/* Finally limit subsequent allocations */
2008 		memblock_set_current_limit(ppc64_rma_size);
2009 	} else {
2010 		ppc64_rma_size = ULONG_MAX;
2011 	}
2012 }
2013 
2014 #ifdef CONFIG_DEBUG_FS
2015 
hpt_order_get(void * data,u64 * val)2016 static int hpt_order_get(void *data, u64 *val)
2017 {
2018 	*val = ppc64_pft_size;
2019 	return 0;
2020 }
2021 
hpt_order_set(void * data,u64 val)2022 static int hpt_order_set(void *data, u64 val)
2023 {
2024 	int ret;
2025 
2026 	if (!mmu_hash_ops.resize_hpt)
2027 		return -ENODEV;
2028 
2029 	cpus_read_lock();
2030 	ret = mmu_hash_ops.resize_hpt(val);
2031 	cpus_read_unlock();
2032 
2033 	return ret;
2034 }
2035 
2036 DEFINE_DEBUGFS_ATTRIBUTE(fops_hpt_order, hpt_order_get, hpt_order_set, "%llu\n");
2037 
hash64_debugfs(void)2038 static int __init hash64_debugfs(void)
2039 {
2040 	debugfs_create_file("hpt_order", 0600, powerpc_debugfs_root, NULL,
2041 			    &fops_hpt_order);
2042 	return 0;
2043 }
2044 machine_device_initcall(pseries, hash64_debugfs);
2045 #endif /* CONFIG_DEBUG_FS */
2046 
print_system_hash_info(void)2047 void __init print_system_hash_info(void)
2048 {
2049 	pr_info("ppc64_pft_size    = 0x%llx\n", ppc64_pft_size);
2050 
2051 	if (htab_hash_mask)
2052 		pr_info("htab_hash_mask    = 0x%lx\n", htab_hash_mask);
2053 }
2054