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