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 
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  */
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 
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 
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 
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  */
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 
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 
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 __ro_after_init;
475 
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 
483 bool stress_hpt_enabled __initdata;
484 
485 static int __init parse_stress_hpt(char *p)
486 {
487 	stress_hpt_enabled = true;
488 	return 0;
489 }
490 early_param("stress_hpt", parse_stress_hpt);
491 
492 __ro_after_init DEFINE_STATIC_KEY_FALSE(stress_hpt_key);
493 
494 /*
495  * per-CPU array allocated if we enable stress_hpt.
496  */
497 #define STRESS_MAX_GROUPS 16
498 struct stress_hpt_struct {
499 	unsigned long last_group[STRESS_MAX_GROUPS];
500 };
501 
502 static inline int stress_nr_groups(void)
503 {
504 	/*
505 	 * LPAR H_REMOVE flushes TLB, so need some number > 1 of entries
506 	 * to allow practical forward progress. Bare metal returns 1, which
507 	 * seems to help uncover more bugs.
508 	 */
509 	if (firmware_has_feature(FW_FEATURE_LPAR))
510 		return STRESS_MAX_GROUPS;
511 	else
512 		return 1;
513 }
514 
515 static struct stress_hpt_struct *stress_hpt_struct;
516 
517 static int __init htab_dt_scan_seg_sizes(unsigned long node,
518 					 const char *uname, int depth,
519 					 void *data)
520 {
521 	const char *type = of_get_flat_dt_prop(node, "device_type", NULL);
522 	const __be32 *prop;
523 	int size = 0;
524 
525 	/* We are scanning "cpu" nodes only */
526 	if (type == NULL || strcmp(type, "cpu") != 0)
527 		return 0;
528 
529 	prop = of_get_flat_dt_prop(node, "ibm,processor-segment-sizes", &size);
530 	if (prop == NULL)
531 		return 0;
532 	for (; size >= 4; size -= 4, ++prop) {
533 		if (be32_to_cpu(prop[0]) == 40) {
534 			DBG("1T segment support detected\n");
535 
536 			if (disable_1tb_segments) {
537 				DBG("1T segments disabled by command line\n");
538 				break;
539 			}
540 
541 			cur_cpu_spec->mmu_features |= MMU_FTR_1T_SEGMENT;
542 			return 1;
543 		}
544 	}
545 	cur_cpu_spec->mmu_features &= ~MMU_FTR_NO_SLBIE_B;
546 	return 0;
547 }
548 
549 static int __init get_idx_from_shift(unsigned int shift)
550 {
551 	int idx = -1;
552 
553 	switch (shift) {
554 	case 0xc:
555 		idx = MMU_PAGE_4K;
556 		break;
557 	case 0x10:
558 		idx = MMU_PAGE_64K;
559 		break;
560 	case 0x14:
561 		idx = MMU_PAGE_1M;
562 		break;
563 	case 0x18:
564 		idx = MMU_PAGE_16M;
565 		break;
566 	case 0x22:
567 		idx = MMU_PAGE_16G;
568 		break;
569 	}
570 	return idx;
571 }
572 
573 static int __init htab_dt_scan_page_sizes(unsigned long node,
574 					  const char *uname, int depth,
575 					  void *data)
576 {
577 	const char *type = of_get_flat_dt_prop(node, "device_type", NULL);
578 	const __be32 *prop;
579 	int size = 0;
580 
581 	/* We are scanning "cpu" nodes only */
582 	if (type == NULL || strcmp(type, "cpu") != 0)
583 		return 0;
584 
585 	prop = of_get_flat_dt_prop(node, "ibm,segment-page-sizes", &size);
586 	if (!prop)
587 		return 0;
588 
589 	pr_info("Page sizes from device-tree:\n");
590 	size /= 4;
591 	cur_cpu_spec->mmu_features &= ~(MMU_FTR_16M_PAGE);
592 	while(size > 0) {
593 		unsigned int base_shift = be32_to_cpu(prop[0]);
594 		unsigned int slbenc = be32_to_cpu(prop[1]);
595 		unsigned int lpnum = be32_to_cpu(prop[2]);
596 		struct mmu_psize_def *def;
597 		int idx, base_idx;
598 
599 		size -= 3; prop += 3;
600 		base_idx = get_idx_from_shift(base_shift);
601 		if (base_idx < 0) {
602 			/* skip the pte encoding also */
603 			prop += lpnum * 2; size -= lpnum * 2;
604 			continue;
605 		}
606 		def = &mmu_psize_defs[base_idx];
607 		if (base_idx == MMU_PAGE_16M)
608 			cur_cpu_spec->mmu_features |= MMU_FTR_16M_PAGE;
609 
610 		def->shift = base_shift;
611 		if (base_shift <= 23)
612 			def->avpnm = 0;
613 		else
614 			def->avpnm = (1 << (base_shift - 23)) - 1;
615 		def->sllp = slbenc;
616 		/*
617 		 * We don't know for sure what's up with tlbiel, so
618 		 * for now we only set it for 4K and 64K pages
619 		 */
620 		if (base_idx == MMU_PAGE_4K || base_idx == MMU_PAGE_64K)
621 			def->tlbiel = 1;
622 		else
623 			def->tlbiel = 0;
624 
625 		while (size > 0 && lpnum) {
626 			unsigned int shift = be32_to_cpu(prop[0]);
627 			int penc  = be32_to_cpu(prop[1]);
628 
629 			prop += 2; size -= 2;
630 			lpnum--;
631 
632 			idx = get_idx_from_shift(shift);
633 			if (idx < 0)
634 				continue;
635 
636 			if (penc == -1)
637 				pr_err("Invalid penc for base_shift=%d "
638 				       "shift=%d\n", base_shift, shift);
639 
640 			def->penc[idx] = penc;
641 			pr_info("base_shift=%d: shift=%d, sllp=0x%04lx,"
642 				" avpnm=0x%08lx, tlbiel=%d, penc=%d\n",
643 				base_shift, shift, def->sllp,
644 				def->avpnm, def->tlbiel, def->penc[idx]);
645 		}
646 	}
647 
648 	return 1;
649 }
650 
651 #ifdef CONFIG_HUGETLB_PAGE
652 /*
653  * Scan for 16G memory blocks that have been set aside for huge pages
654  * and reserve those blocks for 16G huge pages.
655  */
656 static int __init htab_dt_scan_hugepage_blocks(unsigned long node,
657 					const char *uname, int depth,
658 					void *data) {
659 	const char *type = of_get_flat_dt_prop(node, "device_type", NULL);
660 	const __be64 *addr_prop;
661 	const __be32 *page_count_prop;
662 	unsigned int expected_pages;
663 	long unsigned int phys_addr;
664 	long unsigned int block_size;
665 
666 	/* We are scanning "memory" nodes only */
667 	if (type == NULL || strcmp(type, "memory") != 0)
668 		return 0;
669 
670 	/*
671 	 * This property is the log base 2 of the number of virtual pages that
672 	 * will represent this memory block.
673 	 */
674 	page_count_prop = of_get_flat_dt_prop(node, "ibm,expected#pages", NULL);
675 	if (page_count_prop == NULL)
676 		return 0;
677 	expected_pages = (1 << be32_to_cpu(page_count_prop[0]));
678 	addr_prop = of_get_flat_dt_prop(node, "reg", NULL);
679 	if (addr_prop == NULL)
680 		return 0;
681 	phys_addr = be64_to_cpu(addr_prop[0]);
682 	block_size = be64_to_cpu(addr_prop[1]);
683 	if (block_size != (16 * GB))
684 		return 0;
685 	printk(KERN_INFO "Huge page(16GB) memory: "
686 			"addr = 0x%lX size = 0x%lX pages = %d\n",
687 			phys_addr, block_size, expected_pages);
688 	if (phys_addr + block_size * expected_pages <= memblock_end_of_DRAM()) {
689 		memblock_reserve(phys_addr, block_size * expected_pages);
690 		pseries_add_gpage(phys_addr, block_size, expected_pages);
691 	}
692 	return 0;
693 }
694 #endif /* CONFIG_HUGETLB_PAGE */
695 
696 static void __init mmu_psize_set_default_penc(void)
697 {
698 	int bpsize, apsize;
699 	for (bpsize = 0; bpsize < MMU_PAGE_COUNT; bpsize++)
700 		for (apsize = 0; apsize < MMU_PAGE_COUNT; apsize++)
701 			mmu_psize_defs[bpsize].penc[apsize] = -1;
702 }
703 
704 #ifdef CONFIG_PPC_64K_PAGES
705 
706 static bool __init might_have_hea(void)
707 {
708 	/*
709 	 * The HEA ethernet adapter requires awareness of the
710 	 * GX bus. Without that awareness we can easily assume
711 	 * we will never see an HEA ethernet device.
712 	 */
713 #ifdef CONFIG_IBMEBUS
714 	return !cpu_has_feature(CPU_FTR_ARCH_207S) &&
715 		firmware_has_feature(FW_FEATURE_SPLPAR);
716 #else
717 	return false;
718 #endif
719 }
720 
721 #endif /* #ifdef CONFIG_PPC_64K_PAGES */
722 
723 static void __init htab_scan_page_sizes(void)
724 {
725 	int rc;
726 
727 	/* se the invalid penc to -1 */
728 	mmu_psize_set_default_penc();
729 
730 	/* Default to 4K pages only */
731 	memcpy(mmu_psize_defs, mmu_psize_defaults,
732 	       sizeof(mmu_psize_defaults));
733 
734 	/*
735 	 * Try to find the available page sizes in the device-tree
736 	 */
737 	rc = of_scan_flat_dt(htab_dt_scan_page_sizes, NULL);
738 	if (rc == 0 && early_mmu_has_feature(MMU_FTR_16M_PAGE)) {
739 		/*
740 		 * Nothing in the device-tree, but the CPU supports 16M pages,
741 		 * so let's fallback on a known size list for 16M capable CPUs.
742 		 */
743 		memcpy(mmu_psize_defs, mmu_psize_defaults_gp,
744 		       sizeof(mmu_psize_defaults_gp));
745 	}
746 
747 #ifdef CONFIG_HUGETLB_PAGE
748 	if (!hugetlb_disabled && !early_radix_enabled() ) {
749 		/* Reserve 16G huge page memory sections for huge pages */
750 		of_scan_flat_dt(htab_dt_scan_hugepage_blocks, NULL);
751 	}
752 #endif /* CONFIG_HUGETLB_PAGE */
753 }
754 
755 /*
756  * Fill in the hpte_page_sizes[] array.
757  * We go through the mmu_psize_defs[] array looking for all the
758  * supported base/actual page size combinations.  Each combination
759  * has a unique pagesize encoding (penc) value in the low bits of
760  * the LP field of the HPTE.  For actual page sizes less than 1MB,
761  * some of the upper LP bits are used for RPN bits, meaning that
762  * we need to fill in several entries in hpte_page_sizes[].
763  *
764  * In diagrammatic form, with r = RPN bits and z = page size bits:
765  *        PTE LP     actual page size
766  *    rrrr rrrz		>=8KB
767  *    rrrr rrzz		>=16KB
768  *    rrrr rzzz		>=32KB
769  *    rrrr zzzz		>=64KB
770  *    ...
771  *
772  * The zzzz bits are implementation-specific but are chosen so that
773  * no encoding for a larger page size uses the same value in its
774  * low-order N bits as the encoding for the 2^(12+N) byte page size
775  * (if it exists).
776  */
777 static void __init init_hpte_page_sizes(void)
778 {
779 	long int ap, bp;
780 	long int shift, penc;
781 
782 	for (bp = 0; bp < MMU_PAGE_COUNT; ++bp) {
783 		if (!mmu_psize_defs[bp].shift)
784 			continue;	/* not a supported page size */
785 		for (ap = bp; ap < MMU_PAGE_COUNT; ++ap) {
786 			penc = mmu_psize_defs[bp].penc[ap];
787 			if (penc == -1 || !mmu_psize_defs[ap].shift)
788 				continue;
789 			shift = mmu_psize_defs[ap].shift - LP_SHIFT;
790 			if (shift <= 0)
791 				continue;	/* should never happen */
792 			/*
793 			 * For page sizes less than 1MB, this loop
794 			 * replicates the entry for all possible values
795 			 * of the rrrr bits.
796 			 */
797 			while (penc < (1 << LP_BITS)) {
798 				hpte_page_sizes[penc] = (ap << 4) | bp;
799 				penc += 1 << shift;
800 			}
801 		}
802 	}
803 }
804 
805 static void __init htab_init_page_sizes(void)
806 {
807 	bool aligned = true;
808 	init_hpte_page_sizes();
809 
810 	if (!debug_pagealloc_enabled_or_kfence()) {
811 		/*
812 		 * Pick a size for the linear mapping. Currently, we only
813 		 * support 16M, 1M and 4K which is the default
814 		 */
815 		if (IS_ENABLED(CONFIG_STRICT_KERNEL_RWX) &&
816 		    (unsigned long)_stext % 0x1000000) {
817 			if (mmu_psize_defs[MMU_PAGE_16M].shift)
818 				pr_warn("Kernel not 16M aligned, disabling 16M linear map alignment\n");
819 			aligned = false;
820 		}
821 
822 		if (mmu_psize_defs[MMU_PAGE_16M].shift && aligned)
823 			mmu_linear_psize = MMU_PAGE_16M;
824 		else if (mmu_psize_defs[MMU_PAGE_1M].shift)
825 			mmu_linear_psize = MMU_PAGE_1M;
826 	}
827 
828 #ifdef CONFIG_PPC_64K_PAGES
829 	/*
830 	 * Pick a size for the ordinary pages. Default is 4K, we support
831 	 * 64K for user mappings and vmalloc if supported by the processor.
832 	 * We only use 64k for ioremap if the processor
833 	 * (and firmware) support cache-inhibited large pages.
834 	 * If not, we use 4k and set mmu_ci_restrictions so that
835 	 * hash_page knows to switch processes that use cache-inhibited
836 	 * mappings to 4k pages.
837 	 */
838 	if (mmu_psize_defs[MMU_PAGE_64K].shift) {
839 		mmu_virtual_psize = MMU_PAGE_64K;
840 		mmu_vmalloc_psize = MMU_PAGE_64K;
841 		if (mmu_linear_psize == MMU_PAGE_4K)
842 			mmu_linear_psize = MMU_PAGE_64K;
843 		if (mmu_has_feature(MMU_FTR_CI_LARGE_PAGE)) {
844 			/*
845 			 * When running on pSeries using 64k pages for ioremap
846 			 * would stop us accessing the HEA ethernet. So if we
847 			 * have the chance of ever seeing one, stay at 4k.
848 			 */
849 			if (!might_have_hea())
850 				mmu_io_psize = MMU_PAGE_64K;
851 		} else
852 			mmu_ci_restrictions = 1;
853 	}
854 #endif /* CONFIG_PPC_64K_PAGES */
855 
856 #ifdef CONFIG_SPARSEMEM_VMEMMAP
857 	/*
858 	 * We try to use 16M pages for vmemmap if that is supported
859 	 * and we have at least 1G of RAM at boot
860 	 */
861 	if (mmu_psize_defs[MMU_PAGE_16M].shift &&
862 	    memblock_phys_mem_size() >= 0x40000000)
863 		mmu_vmemmap_psize = MMU_PAGE_16M;
864 	else
865 		mmu_vmemmap_psize = mmu_virtual_psize;
866 #endif /* CONFIG_SPARSEMEM_VMEMMAP */
867 
868 	printk(KERN_DEBUG "Page orders: linear mapping = %d, "
869 	       "virtual = %d, io = %d"
870 #ifdef CONFIG_SPARSEMEM_VMEMMAP
871 	       ", vmemmap = %d"
872 #endif
873 	       "\n",
874 	       mmu_psize_defs[mmu_linear_psize].shift,
875 	       mmu_psize_defs[mmu_virtual_psize].shift,
876 	       mmu_psize_defs[mmu_io_psize].shift
877 #ifdef CONFIG_SPARSEMEM_VMEMMAP
878 	       ,mmu_psize_defs[mmu_vmemmap_psize].shift
879 #endif
880 	       );
881 }
882 
883 static int __init htab_dt_scan_pftsize(unsigned long node,
884 				       const char *uname, int depth,
885 				       void *data)
886 {
887 	const char *type = of_get_flat_dt_prop(node, "device_type", NULL);
888 	const __be32 *prop;
889 
890 	/* We are scanning "cpu" nodes only */
891 	if (type == NULL || strcmp(type, "cpu") != 0)
892 		return 0;
893 
894 	prop = of_get_flat_dt_prop(node, "ibm,pft-size", NULL);
895 	if (prop != NULL) {
896 		/* pft_size[0] is the NUMA CEC cookie */
897 		ppc64_pft_size = be32_to_cpu(prop[1]);
898 		return 1;
899 	}
900 	return 0;
901 }
902 
903 unsigned htab_shift_for_mem_size(unsigned long mem_size)
904 {
905 	unsigned memshift = __ilog2(mem_size);
906 	unsigned pshift = mmu_psize_defs[mmu_virtual_psize].shift;
907 	unsigned pteg_shift;
908 
909 	/* round mem_size up to next power of 2 */
910 	if ((1UL << memshift) < mem_size)
911 		memshift += 1;
912 
913 	/* aim for 2 pages / pteg */
914 	pteg_shift = memshift - (pshift + 1);
915 
916 	/*
917 	 * 2^11 PTEGS of 128 bytes each, ie. 2^18 bytes is the minimum htab
918 	 * size permitted by the architecture.
919 	 */
920 	return max(pteg_shift + 7, 18U);
921 }
922 
923 static unsigned long __init htab_get_table_size(void)
924 {
925 	/*
926 	 * If hash size isn't already provided by the platform, we try to
927 	 * retrieve it from the device-tree. If it's not there neither, we
928 	 * calculate it now based on the total RAM size
929 	 */
930 	if (ppc64_pft_size == 0)
931 		of_scan_flat_dt(htab_dt_scan_pftsize, NULL);
932 	if (ppc64_pft_size)
933 		return 1UL << ppc64_pft_size;
934 
935 	return 1UL << htab_shift_for_mem_size(memblock_phys_mem_size());
936 }
937 
938 #ifdef CONFIG_MEMORY_HOTPLUG
939 static int resize_hpt_for_hotplug(unsigned long new_mem_size)
940 {
941 	unsigned target_hpt_shift;
942 
943 	if (!mmu_hash_ops.resize_hpt)
944 		return 0;
945 
946 	target_hpt_shift = htab_shift_for_mem_size(new_mem_size);
947 
948 	/*
949 	 * To avoid lots of HPT resizes if memory size is fluctuating
950 	 * across a boundary, we deliberately have some hysterisis
951 	 * here: we immediately increase the HPT size if the target
952 	 * shift exceeds the current shift, but we won't attempt to
953 	 * reduce unless the target shift is at least 2 below the
954 	 * current shift
955 	 */
956 	if (target_hpt_shift > ppc64_pft_size ||
957 	    target_hpt_shift < ppc64_pft_size - 1)
958 		return mmu_hash_ops.resize_hpt(target_hpt_shift);
959 
960 	return 0;
961 }
962 
963 int hash__create_section_mapping(unsigned long start, unsigned long end,
964 				 int nid, pgprot_t prot)
965 {
966 	int rc;
967 
968 	if (end >= H_VMALLOC_START) {
969 		pr_warn("Outside the supported range\n");
970 		return -1;
971 	}
972 
973 	resize_hpt_for_hotplug(memblock_phys_mem_size());
974 
975 	rc = htab_bolt_mapping(start, end, __pa(start),
976 			       pgprot_val(prot), mmu_linear_psize,
977 			       mmu_kernel_ssize);
978 
979 	if (rc < 0) {
980 		int rc2 = htab_remove_mapping(start, end, mmu_linear_psize,
981 					      mmu_kernel_ssize);
982 		BUG_ON(rc2 && (rc2 != -ENOENT));
983 	}
984 	return rc;
985 }
986 
987 int hash__remove_section_mapping(unsigned long start, unsigned long end)
988 {
989 	int rc = htab_remove_mapping(start, end, mmu_linear_psize,
990 				     mmu_kernel_ssize);
991 
992 	if (resize_hpt_for_hotplug(memblock_phys_mem_size()) == -ENOSPC)
993 		pr_warn("Hash collision while resizing HPT\n");
994 
995 	return rc;
996 }
997 #endif /* CONFIG_MEMORY_HOTPLUG */
998 
999 static void __init hash_init_partition_table(phys_addr_t hash_table,
1000 					     unsigned long htab_size)
1001 {
1002 	mmu_partition_table_init();
1003 
1004 	/*
1005 	 * PS field (VRMA page size) is not used for LPID 0, hence set to 0.
1006 	 * For now, UPRT is 0 and we have no segment table.
1007 	 */
1008 	htab_size =  __ilog2(htab_size) - 18;
1009 	mmu_partition_table_set_entry(0, hash_table | htab_size, 0, false);
1010 	pr_info("Partition table %p\n", partition_tb);
1011 }
1012 
1013 void hpt_clear_stress(void);
1014 static struct timer_list stress_hpt_timer;
1015 static void stress_hpt_timer_fn(struct timer_list *timer)
1016 {
1017 	int next_cpu;
1018 
1019 	hpt_clear_stress();
1020 	if (!firmware_has_feature(FW_FEATURE_LPAR))
1021 		tlbiel_all();
1022 
1023 	next_cpu = cpumask_next(raw_smp_processor_id(), cpu_online_mask);
1024 	if (next_cpu >= nr_cpu_ids)
1025 		next_cpu = cpumask_first(cpu_online_mask);
1026 	stress_hpt_timer.expires = jiffies + msecs_to_jiffies(10);
1027 	add_timer_on(&stress_hpt_timer, next_cpu);
1028 }
1029 
1030 static void __init htab_initialize(void)
1031 {
1032 	unsigned long table;
1033 	unsigned long pteg_count;
1034 	unsigned long prot;
1035 	phys_addr_t base = 0, size = 0, end;
1036 	u64 i;
1037 
1038 	DBG(" -> htab_initialize()\n");
1039 
1040 	if (mmu_has_feature(MMU_FTR_1T_SEGMENT)) {
1041 		mmu_kernel_ssize = MMU_SEGSIZE_1T;
1042 		mmu_highuser_ssize = MMU_SEGSIZE_1T;
1043 		printk(KERN_INFO "Using 1TB segments\n");
1044 	}
1045 
1046 	if (stress_slb_enabled)
1047 		static_branch_enable(&stress_slb_key);
1048 
1049 	if (stress_hpt_enabled) {
1050 		unsigned long tmp;
1051 		static_branch_enable(&stress_hpt_key);
1052 		// Too early to use nr_cpu_ids, so use NR_CPUS
1053 		tmp = memblock_phys_alloc_range(sizeof(struct stress_hpt_struct) * NR_CPUS,
1054 						__alignof__(struct stress_hpt_struct),
1055 						0, MEMBLOCK_ALLOC_ANYWHERE);
1056 		memset((void *)tmp, 0xff, sizeof(struct stress_hpt_struct) * NR_CPUS);
1057 		stress_hpt_struct = __va(tmp);
1058 
1059 		timer_setup(&stress_hpt_timer, stress_hpt_timer_fn, 0);
1060 		stress_hpt_timer.expires = jiffies + msecs_to_jiffies(10);
1061 		add_timer(&stress_hpt_timer);
1062 	}
1063 
1064 	/*
1065 	 * Calculate the required size of the htab.  We want the number of
1066 	 * PTEGs to equal one half the number of real pages.
1067 	 */
1068 	htab_size_bytes = htab_get_table_size();
1069 	pteg_count = htab_size_bytes >> 7;
1070 
1071 	htab_hash_mask = pteg_count - 1;
1072 
1073 	if (firmware_has_feature(FW_FEATURE_LPAR) ||
1074 	    firmware_has_feature(FW_FEATURE_PS3_LV1)) {
1075 		/* Using a hypervisor which owns the htab */
1076 		htab_address = NULL;
1077 		_SDR1 = 0;
1078 #ifdef CONFIG_FA_DUMP
1079 		/*
1080 		 * If firmware assisted dump is active firmware preserves
1081 		 * the contents of htab along with entire partition memory.
1082 		 * Clear the htab if firmware assisted dump is active so
1083 		 * that we dont end up using old mappings.
1084 		 */
1085 		if (is_fadump_active() && mmu_hash_ops.hpte_clear_all)
1086 			mmu_hash_ops.hpte_clear_all();
1087 #endif
1088 	} else {
1089 		unsigned long limit = MEMBLOCK_ALLOC_ANYWHERE;
1090 
1091 #ifdef CONFIG_PPC_CELL
1092 		/*
1093 		 * Cell may require the hash table down low when using the
1094 		 * Axon IOMMU in order to fit the dynamic region over it, see
1095 		 * comments in cell/iommu.c
1096 		 */
1097 		if (fdt_subnode_offset(initial_boot_params, 0, "axon") > 0) {
1098 			limit = 0x80000000;
1099 			pr_info("Hash table forced below 2G for Axon IOMMU\n");
1100 		}
1101 #endif /* CONFIG_PPC_CELL */
1102 
1103 		table = memblock_phys_alloc_range(htab_size_bytes,
1104 						  htab_size_bytes,
1105 						  0, limit);
1106 		if (!table)
1107 			panic("ERROR: Failed to allocate %pa bytes below %pa\n",
1108 			      &htab_size_bytes, &limit);
1109 
1110 		DBG("Hash table allocated at %lx, size: %lx\n", table,
1111 		    htab_size_bytes);
1112 
1113 		htab_address = __va(table);
1114 
1115 		/* htab absolute addr + encoded htabsize */
1116 		_SDR1 = table + __ilog2(htab_size_bytes) - 18;
1117 
1118 		/* Initialize the HPT with no entries */
1119 		memset((void *)table, 0, htab_size_bytes);
1120 
1121 		if (!cpu_has_feature(CPU_FTR_ARCH_300))
1122 			/* Set SDR1 */
1123 			mtspr(SPRN_SDR1, _SDR1);
1124 		else
1125 			hash_init_partition_table(table, htab_size_bytes);
1126 	}
1127 
1128 	prot = pgprot_val(PAGE_KERNEL);
1129 
1130 	if (debug_pagealloc_enabled_or_kfence()) {
1131 		linear_map_hash_count = memblock_end_of_DRAM() >> PAGE_SHIFT;
1132 		linear_map_hash_slots = memblock_alloc_try_nid(
1133 				linear_map_hash_count, 1, MEMBLOCK_LOW_LIMIT,
1134 				ppc64_rma_size,	NUMA_NO_NODE);
1135 		if (!linear_map_hash_slots)
1136 			panic("%s: Failed to allocate %lu bytes max_addr=%pa\n",
1137 			      __func__, linear_map_hash_count, &ppc64_rma_size);
1138 	}
1139 
1140 	/* create bolted the linear mapping in the hash table */
1141 	for_each_mem_range(i, &base, &end) {
1142 		size = end - base;
1143 		base = (unsigned long)__va(base);
1144 
1145 		DBG("creating mapping for region: %lx..%lx (prot: %lx)\n",
1146 		    base, size, prot);
1147 
1148 		if ((base + size) >= H_VMALLOC_START) {
1149 			pr_warn("Outside the supported range\n");
1150 			continue;
1151 		}
1152 
1153 		BUG_ON(htab_bolt_mapping(base, base + size, __pa(base),
1154 				prot, mmu_linear_psize, mmu_kernel_ssize));
1155 	}
1156 	memblock_set_current_limit(MEMBLOCK_ALLOC_ANYWHERE);
1157 
1158 	/*
1159 	 * If we have a memory_limit and we've allocated TCEs then we need to
1160 	 * explicitly map the TCE area at the top of RAM. We also cope with the
1161 	 * case that the TCEs start below memory_limit.
1162 	 * tce_alloc_start/end are 16MB aligned so the mapping should work
1163 	 * for either 4K or 16MB pages.
1164 	 */
1165 	if (tce_alloc_start) {
1166 		tce_alloc_start = (unsigned long)__va(tce_alloc_start);
1167 		tce_alloc_end = (unsigned long)__va(tce_alloc_end);
1168 
1169 		if (base + size >= tce_alloc_start)
1170 			tce_alloc_start = base + size + 1;
1171 
1172 		BUG_ON(htab_bolt_mapping(tce_alloc_start, tce_alloc_end,
1173 					 __pa(tce_alloc_start), prot,
1174 					 mmu_linear_psize, mmu_kernel_ssize));
1175 	}
1176 
1177 
1178 	DBG(" <- htab_initialize()\n");
1179 }
1180 #undef KB
1181 #undef MB
1182 
1183 void __init hash__early_init_devtree(void)
1184 {
1185 	/* Initialize segment sizes */
1186 	of_scan_flat_dt(htab_dt_scan_seg_sizes, NULL);
1187 
1188 	/* Initialize page sizes */
1189 	htab_scan_page_sizes();
1190 }
1191 
1192 static struct hash_mm_context init_hash_mm_context;
1193 void __init hash__early_init_mmu(void)
1194 {
1195 #ifndef CONFIG_PPC_64K_PAGES
1196 	/*
1197 	 * We have code in __hash_page_4K() and elsewhere, which assumes it can
1198 	 * do the following:
1199 	 *   new_pte |= (slot << H_PAGE_F_GIX_SHIFT) & (H_PAGE_F_SECOND | H_PAGE_F_GIX);
1200 	 *
1201 	 * Where the slot number is between 0-15, and values of 8-15 indicate
1202 	 * the secondary bucket. For that code to work H_PAGE_F_SECOND and
1203 	 * H_PAGE_F_GIX must occupy four contiguous bits in the PTE, and
1204 	 * H_PAGE_F_SECOND must be placed above H_PAGE_F_GIX. Assert that here
1205 	 * with a BUILD_BUG_ON().
1206 	 */
1207 	BUILD_BUG_ON(H_PAGE_F_SECOND != (1ul  << (H_PAGE_F_GIX_SHIFT + 3)));
1208 #endif /* CONFIG_PPC_64K_PAGES */
1209 
1210 	htab_init_page_sizes();
1211 
1212 	/*
1213 	 * initialize page table size
1214 	 */
1215 	__pte_frag_nr = H_PTE_FRAG_NR;
1216 	__pte_frag_size_shift = H_PTE_FRAG_SIZE_SHIFT;
1217 	__pmd_frag_nr = H_PMD_FRAG_NR;
1218 	__pmd_frag_size_shift = H_PMD_FRAG_SIZE_SHIFT;
1219 
1220 	__pte_index_size = H_PTE_INDEX_SIZE;
1221 	__pmd_index_size = H_PMD_INDEX_SIZE;
1222 	__pud_index_size = H_PUD_INDEX_SIZE;
1223 	__pgd_index_size = H_PGD_INDEX_SIZE;
1224 	__pud_cache_index = H_PUD_CACHE_INDEX;
1225 	__pte_table_size = H_PTE_TABLE_SIZE;
1226 	__pmd_table_size = H_PMD_TABLE_SIZE;
1227 	__pud_table_size = H_PUD_TABLE_SIZE;
1228 	__pgd_table_size = H_PGD_TABLE_SIZE;
1229 	/*
1230 	 * 4k use hugepd format, so for hash set then to
1231 	 * zero
1232 	 */
1233 	__pmd_val_bits = HASH_PMD_VAL_BITS;
1234 	__pud_val_bits = HASH_PUD_VAL_BITS;
1235 	__pgd_val_bits = HASH_PGD_VAL_BITS;
1236 
1237 	__kernel_virt_start = H_KERN_VIRT_START;
1238 	__vmalloc_start = H_VMALLOC_START;
1239 	__vmalloc_end = H_VMALLOC_END;
1240 	__kernel_io_start = H_KERN_IO_START;
1241 	__kernel_io_end = H_KERN_IO_END;
1242 	vmemmap = (struct page *)H_VMEMMAP_START;
1243 	ioremap_bot = IOREMAP_BASE;
1244 
1245 #ifdef CONFIG_PCI
1246 	pci_io_base = ISA_IO_BASE;
1247 #endif
1248 
1249 	/* Select appropriate backend */
1250 	if (firmware_has_feature(FW_FEATURE_PS3_LV1))
1251 		ps3_early_mm_init();
1252 	else if (firmware_has_feature(FW_FEATURE_LPAR))
1253 		hpte_init_pseries();
1254 	else if (IS_ENABLED(CONFIG_PPC_HASH_MMU_NATIVE))
1255 		hpte_init_native();
1256 
1257 	if (!mmu_hash_ops.hpte_insert)
1258 		panic("hash__early_init_mmu: No MMU hash ops defined!\n");
1259 
1260 	/*
1261 	 * Initialize the MMU Hash table and create the linear mapping
1262 	 * of memory. Has to be done before SLB initialization as this is
1263 	 * currently where the page size encoding is obtained.
1264 	 */
1265 	htab_initialize();
1266 
1267 	init_mm.context.hash_context = &init_hash_mm_context;
1268 	mm_ctx_set_slb_addr_limit(&init_mm.context, SLB_ADDR_LIMIT_DEFAULT);
1269 
1270 	pr_info("Initializing hash mmu with SLB\n");
1271 	/* Initialize SLB management */
1272 	slb_initialize();
1273 
1274 	if (cpu_has_feature(CPU_FTR_ARCH_206)
1275 			&& cpu_has_feature(CPU_FTR_HVMODE))
1276 		tlbiel_all();
1277 }
1278 
1279 #ifdef CONFIG_SMP
1280 void hash__early_init_mmu_secondary(void)
1281 {
1282 	/* Initialize hash table for that CPU */
1283 	if (!firmware_has_feature(FW_FEATURE_LPAR)) {
1284 
1285 		if (!cpu_has_feature(CPU_FTR_ARCH_300))
1286 			mtspr(SPRN_SDR1, _SDR1);
1287 		else
1288 			set_ptcr_when_no_uv(__pa(partition_tb) |
1289 					    (PATB_SIZE_SHIFT - 12));
1290 	}
1291 	/* Initialize SLB */
1292 	slb_initialize();
1293 
1294 	if (cpu_has_feature(CPU_FTR_ARCH_206)
1295 			&& cpu_has_feature(CPU_FTR_HVMODE))
1296 		tlbiel_all();
1297 
1298 #ifdef CONFIG_PPC_MEM_KEYS
1299 	if (mmu_has_feature(MMU_FTR_PKEY))
1300 		mtspr(SPRN_UAMOR, default_uamor);
1301 #endif
1302 }
1303 #endif /* CONFIG_SMP */
1304 
1305 /*
1306  * Called by asm hashtable.S for doing lazy icache flush
1307  */
1308 unsigned int hash_page_do_lazy_icache(unsigned int pp, pte_t pte, int trap)
1309 {
1310 	struct page *page;
1311 
1312 	if (!pfn_valid(pte_pfn(pte)))
1313 		return pp;
1314 
1315 	page = pte_page(pte);
1316 
1317 	/* page is dirty */
1318 	if (!test_bit(PG_dcache_clean, &page->flags) && !PageReserved(page)) {
1319 		if (trap == INTERRUPT_INST_STORAGE) {
1320 			flush_dcache_icache_page(page);
1321 			set_bit(PG_dcache_clean, &page->flags);
1322 		} else
1323 			pp |= HPTE_R_N;
1324 	}
1325 	return pp;
1326 }
1327 
1328 static unsigned int get_paca_psize(unsigned long addr)
1329 {
1330 	unsigned char *psizes;
1331 	unsigned long index, mask_index;
1332 
1333 	if (addr < SLICE_LOW_TOP) {
1334 		psizes = get_paca()->mm_ctx_low_slices_psize;
1335 		index = GET_LOW_SLICE_INDEX(addr);
1336 	} else {
1337 		psizes = get_paca()->mm_ctx_high_slices_psize;
1338 		index = GET_HIGH_SLICE_INDEX(addr);
1339 	}
1340 	mask_index = index & 0x1;
1341 	return (psizes[index >> 1] >> (mask_index * 4)) & 0xF;
1342 }
1343 
1344 
1345 /*
1346  * Demote a segment to using 4k pages.
1347  * For now this makes the whole process use 4k pages.
1348  */
1349 #ifdef CONFIG_PPC_64K_PAGES
1350 void demote_segment_4k(struct mm_struct *mm, unsigned long addr)
1351 {
1352 	if (get_slice_psize(mm, addr) == MMU_PAGE_4K)
1353 		return;
1354 	slice_set_range_psize(mm, addr, 1, MMU_PAGE_4K);
1355 	copro_flush_all_slbs(mm);
1356 	if ((get_paca_psize(addr) != MMU_PAGE_4K) && (current->mm == mm)) {
1357 
1358 		copy_mm_to_paca(mm);
1359 		slb_flush_and_restore_bolted();
1360 	}
1361 }
1362 #endif /* CONFIG_PPC_64K_PAGES */
1363 
1364 #ifdef CONFIG_PPC_SUBPAGE_PROT
1365 /*
1366  * This looks up a 2-bit protection code for a 4k subpage of a 64k page.
1367  * Userspace sets the subpage permissions using the subpage_prot system call.
1368  *
1369  * Result is 0: full permissions, _PAGE_RW: read-only,
1370  * _PAGE_RWX: no access.
1371  */
1372 static int subpage_protection(struct mm_struct *mm, unsigned long ea)
1373 {
1374 	struct subpage_prot_table *spt = mm_ctx_subpage_prot(&mm->context);
1375 	u32 spp = 0;
1376 	u32 **sbpm, *sbpp;
1377 
1378 	if (!spt)
1379 		return 0;
1380 
1381 	if (ea >= spt->maxaddr)
1382 		return 0;
1383 	if (ea < 0x100000000UL) {
1384 		/* addresses below 4GB use spt->low_prot */
1385 		sbpm = spt->low_prot;
1386 	} else {
1387 		sbpm = spt->protptrs[ea >> SBP_L3_SHIFT];
1388 		if (!sbpm)
1389 			return 0;
1390 	}
1391 	sbpp = sbpm[(ea >> SBP_L2_SHIFT) & (SBP_L2_COUNT - 1)];
1392 	if (!sbpp)
1393 		return 0;
1394 	spp = sbpp[(ea >> PAGE_SHIFT) & (SBP_L1_COUNT - 1)];
1395 
1396 	/* extract 2-bit bitfield for this 4k subpage */
1397 	spp >>= 30 - 2 * ((ea >> 12) & 0xf);
1398 
1399 	/*
1400 	 * 0 -> full permission
1401 	 * 1 -> Read only
1402 	 * 2 -> no access.
1403 	 * We return the flag that need to be cleared.
1404 	 */
1405 	spp = ((spp & 2) ? _PAGE_RWX : 0) | ((spp & 1) ? _PAGE_WRITE : 0);
1406 	return spp;
1407 }
1408 
1409 #else /* CONFIG_PPC_SUBPAGE_PROT */
1410 static inline int subpage_protection(struct mm_struct *mm, unsigned long ea)
1411 {
1412 	return 0;
1413 }
1414 #endif
1415 
1416 void hash_failure_debug(unsigned long ea, unsigned long access,
1417 			unsigned long vsid, unsigned long trap,
1418 			int ssize, int psize, int lpsize, unsigned long pte)
1419 {
1420 	if (!printk_ratelimit())
1421 		return;
1422 	pr_info("mm: Hashing failure ! EA=0x%lx access=0x%lx current=%s\n",
1423 		ea, access, current->comm);
1424 	pr_info("    trap=0x%lx vsid=0x%lx ssize=%d base psize=%d psize %d pte=0x%lx\n",
1425 		trap, vsid, ssize, psize, lpsize, pte);
1426 }
1427 
1428 static void check_paca_psize(unsigned long ea, struct mm_struct *mm,
1429 			     int psize, bool user_region)
1430 {
1431 	if (user_region) {
1432 		if (psize != get_paca_psize(ea)) {
1433 			copy_mm_to_paca(mm);
1434 			slb_flush_and_restore_bolted();
1435 		}
1436 	} else if (get_paca()->vmalloc_sllp !=
1437 		   mmu_psize_defs[mmu_vmalloc_psize].sllp) {
1438 		get_paca()->vmalloc_sllp =
1439 			mmu_psize_defs[mmu_vmalloc_psize].sllp;
1440 		slb_vmalloc_update();
1441 	}
1442 }
1443 
1444 /*
1445  * Result code is:
1446  *  0 - handled
1447  *  1 - normal page fault
1448  * -1 - critical hash insertion error
1449  * -2 - access not permitted by subpage protection mechanism
1450  */
1451 int hash_page_mm(struct mm_struct *mm, unsigned long ea,
1452 		 unsigned long access, unsigned long trap,
1453 		 unsigned long flags)
1454 {
1455 	bool is_thp;
1456 	pgd_t *pgdir;
1457 	unsigned long vsid;
1458 	pte_t *ptep;
1459 	unsigned hugeshift;
1460 	int rc, user_region = 0;
1461 	int psize, ssize;
1462 
1463 	DBG_LOW("hash_page(ea=%016lx, access=%lx, trap=%lx\n",
1464 		ea, access, trap);
1465 	trace_hash_fault(ea, access, trap);
1466 
1467 	/* Get region & vsid */
1468 	switch (get_region_id(ea)) {
1469 	case USER_REGION_ID:
1470 		user_region = 1;
1471 		if (! mm) {
1472 			DBG_LOW(" user region with no mm !\n");
1473 			rc = 1;
1474 			goto bail;
1475 		}
1476 		psize = get_slice_psize(mm, ea);
1477 		ssize = user_segment_size(ea);
1478 		vsid = get_user_vsid(&mm->context, ea, ssize);
1479 		break;
1480 	case VMALLOC_REGION_ID:
1481 		vsid = get_kernel_vsid(ea, mmu_kernel_ssize);
1482 		psize = mmu_vmalloc_psize;
1483 		ssize = mmu_kernel_ssize;
1484 		flags |= HPTE_USE_KERNEL_KEY;
1485 		break;
1486 
1487 	case IO_REGION_ID:
1488 		vsid = get_kernel_vsid(ea, mmu_kernel_ssize);
1489 		psize = mmu_io_psize;
1490 		ssize = mmu_kernel_ssize;
1491 		flags |= HPTE_USE_KERNEL_KEY;
1492 		break;
1493 	default:
1494 		/*
1495 		 * Not a valid range
1496 		 * Send the problem up to do_page_fault()
1497 		 */
1498 		rc = 1;
1499 		goto bail;
1500 	}
1501 	DBG_LOW(" mm=%p, mm->pgdir=%p, vsid=%016lx\n", mm, mm->pgd, vsid);
1502 
1503 	/* Bad address. */
1504 	if (!vsid) {
1505 		DBG_LOW("Bad address!\n");
1506 		rc = 1;
1507 		goto bail;
1508 	}
1509 	/* Get pgdir */
1510 	pgdir = mm->pgd;
1511 	if (pgdir == NULL) {
1512 		rc = 1;
1513 		goto bail;
1514 	}
1515 
1516 	/* Check CPU locality */
1517 	if (user_region && mm_is_thread_local(mm))
1518 		flags |= HPTE_LOCAL_UPDATE;
1519 
1520 #ifndef CONFIG_PPC_64K_PAGES
1521 	/*
1522 	 * If we use 4K pages and our psize is not 4K, then we might
1523 	 * be hitting a special driver mapping, and need to align the
1524 	 * address before we fetch the PTE.
1525 	 *
1526 	 * It could also be a hugepage mapping, in which case this is
1527 	 * not necessary, but it's not harmful, either.
1528 	 */
1529 	if (psize != MMU_PAGE_4K)
1530 		ea &= ~((1ul << mmu_psize_defs[psize].shift) - 1);
1531 #endif /* CONFIG_PPC_64K_PAGES */
1532 
1533 	/* Get PTE and page size from page tables */
1534 	ptep = find_linux_pte(pgdir, ea, &is_thp, &hugeshift);
1535 	if (ptep == NULL || !pte_present(*ptep)) {
1536 		DBG_LOW(" no PTE !\n");
1537 		rc = 1;
1538 		goto bail;
1539 	}
1540 
1541 	/*
1542 	 * Add _PAGE_PRESENT to the required access perm. If there are parallel
1543 	 * updates to the pte that can possibly clear _PAGE_PTE, catch that too.
1544 	 *
1545 	 * We can safely use the return pte address in rest of the function
1546 	 * because we do set H_PAGE_BUSY which prevents further updates to pte
1547 	 * from generic code.
1548 	 */
1549 	access |= _PAGE_PRESENT | _PAGE_PTE;
1550 
1551 	/*
1552 	 * Pre-check access permissions (will be re-checked atomically
1553 	 * in __hash_page_XX but this pre-check is a fast path
1554 	 */
1555 	if (!check_pte_access(access, pte_val(*ptep))) {
1556 		DBG_LOW(" no access !\n");
1557 		rc = 1;
1558 		goto bail;
1559 	}
1560 
1561 	if (hugeshift) {
1562 		if (is_thp)
1563 			rc = __hash_page_thp(ea, access, vsid, (pmd_t *)ptep,
1564 					     trap, flags, ssize, psize);
1565 #ifdef CONFIG_HUGETLB_PAGE
1566 		else
1567 			rc = __hash_page_huge(ea, access, vsid, ptep, trap,
1568 					      flags, ssize, hugeshift, psize);
1569 #else
1570 		else {
1571 			/*
1572 			 * if we have hugeshift, and is not transhuge with
1573 			 * hugetlb disabled, something is really wrong.
1574 			 */
1575 			rc = 1;
1576 			WARN_ON(1);
1577 		}
1578 #endif
1579 		if (current->mm == mm)
1580 			check_paca_psize(ea, mm, psize, user_region);
1581 
1582 		goto bail;
1583 	}
1584 
1585 #ifndef CONFIG_PPC_64K_PAGES
1586 	DBG_LOW(" i-pte: %016lx\n", pte_val(*ptep));
1587 #else
1588 	DBG_LOW(" i-pte: %016lx %016lx\n", pte_val(*ptep),
1589 		pte_val(*(ptep + PTRS_PER_PTE)));
1590 #endif
1591 	/* Do actual hashing */
1592 #ifdef CONFIG_PPC_64K_PAGES
1593 	/* If H_PAGE_4K_PFN is set, make sure this is a 4k segment */
1594 	if ((pte_val(*ptep) & H_PAGE_4K_PFN) && psize == MMU_PAGE_64K) {
1595 		demote_segment_4k(mm, ea);
1596 		psize = MMU_PAGE_4K;
1597 	}
1598 
1599 	/*
1600 	 * If this PTE is non-cacheable and we have restrictions on
1601 	 * using non cacheable large pages, then we switch to 4k
1602 	 */
1603 	if (mmu_ci_restrictions && psize == MMU_PAGE_64K && pte_ci(*ptep)) {
1604 		if (user_region) {
1605 			demote_segment_4k(mm, ea);
1606 			psize = MMU_PAGE_4K;
1607 		} else if (ea < VMALLOC_END) {
1608 			/*
1609 			 * some driver did a non-cacheable mapping
1610 			 * in vmalloc space, so switch vmalloc
1611 			 * to 4k pages
1612 			 */
1613 			printk(KERN_ALERT "Reducing vmalloc segment "
1614 			       "to 4kB pages because of "
1615 			       "non-cacheable mapping\n");
1616 			psize = mmu_vmalloc_psize = MMU_PAGE_4K;
1617 			copro_flush_all_slbs(mm);
1618 		}
1619 	}
1620 
1621 #endif /* CONFIG_PPC_64K_PAGES */
1622 
1623 	if (current->mm == mm)
1624 		check_paca_psize(ea, mm, psize, user_region);
1625 
1626 #ifdef CONFIG_PPC_64K_PAGES
1627 	if (psize == MMU_PAGE_64K)
1628 		rc = __hash_page_64K(ea, access, vsid, ptep, trap,
1629 				     flags, ssize);
1630 	else
1631 #endif /* CONFIG_PPC_64K_PAGES */
1632 	{
1633 		int spp = subpage_protection(mm, ea);
1634 		if (access & spp)
1635 			rc = -2;
1636 		else
1637 			rc = __hash_page_4K(ea, access, vsid, ptep, trap,
1638 					    flags, ssize, spp);
1639 	}
1640 
1641 	/*
1642 	 * Dump some info in case of hash insertion failure, they should
1643 	 * never happen so it is really useful to know if/when they do
1644 	 */
1645 	if (rc == -1)
1646 		hash_failure_debug(ea, access, vsid, trap, ssize, psize,
1647 				   psize, pte_val(*ptep));
1648 #ifndef CONFIG_PPC_64K_PAGES
1649 	DBG_LOW(" o-pte: %016lx\n", pte_val(*ptep));
1650 #else
1651 	DBG_LOW(" o-pte: %016lx %016lx\n", pte_val(*ptep),
1652 		pte_val(*(ptep + PTRS_PER_PTE)));
1653 #endif
1654 	DBG_LOW(" -> rc=%d\n", rc);
1655 
1656 bail:
1657 	return rc;
1658 }
1659 EXPORT_SYMBOL_GPL(hash_page_mm);
1660 
1661 int hash_page(unsigned long ea, unsigned long access, unsigned long trap,
1662 	      unsigned long dsisr)
1663 {
1664 	unsigned long flags = 0;
1665 	struct mm_struct *mm = current->mm;
1666 
1667 	if ((get_region_id(ea) == VMALLOC_REGION_ID) ||
1668 	    (get_region_id(ea) == IO_REGION_ID))
1669 		mm = &init_mm;
1670 
1671 	if (dsisr & DSISR_NOHPTE)
1672 		flags |= HPTE_NOHPTE_UPDATE;
1673 
1674 	return hash_page_mm(mm, ea, access, trap, flags);
1675 }
1676 EXPORT_SYMBOL_GPL(hash_page);
1677 
1678 DEFINE_INTERRUPT_HANDLER(do_hash_fault)
1679 {
1680 	unsigned long ea = regs->dar;
1681 	unsigned long dsisr = regs->dsisr;
1682 	unsigned long access = _PAGE_PRESENT | _PAGE_READ;
1683 	unsigned long flags = 0;
1684 	struct mm_struct *mm;
1685 	unsigned int region_id;
1686 	long err;
1687 
1688 	if (unlikely(dsisr & (DSISR_BAD_FAULT_64S | DSISR_KEYFAULT))) {
1689 		hash__do_page_fault(regs);
1690 		return;
1691 	}
1692 
1693 	region_id = get_region_id(ea);
1694 	if ((region_id == VMALLOC_REGION_ID) || (region_id == IO_REGION_ID))
1695 		mm = &init_mm;
1696 	else
1697 		mm = current->mm;
1698 
1699 	if (dsisr & DSISR_NOHPTE)
1700 		flags |= HPTE_NOHPTE_UPDATE;
1701 
1702 	if (dsisr & DSISR_ISSTORE)
1703 		access |= _PAGE_WRITE;
1704 	/*
1705 	 * We set _PAGE_PRIVILEGED only when
1706 	 * kernel mode access kernel space.
1707 	 *
1708 	 * _PAGE_PRIVILEGED is NOT set
1709 	 * 1) when kernel mode access user space
1710 	 * 2) user space access kernel space.
1711 	 */
1712 	access |= _PAGE_PRIVILEGED;
1713 	if (user_mode(regs) || (region_id == USER_REGION_ID))
1714 		access &= ~_PAGE_PRIVILEGED;
1715 
1716 	if (TRAP(regs) == INTERRUPT_INST_STORAGE)
1717 		access |= _PAGE_EXEC;
1718 
1719 	err = hash_page_mm(mm, ea, access, TRAP(regs), flags);
1720 	if (unlikely(err < 0)) {
1721 		// failed to insert a hash PTE due to an hypervisor error
1722 		if (user_mode(regs)) {
1723 			if (IS_ENABLED(CONFIG_PPC_SUBPAGE_PROT) && err == -2)
1724 				_exception(SIGSEGV, regs, SEGV_ACCERR, ea);
1725 			else
1726 				_exception(SIGBUS, regs, BUS_ADRERR, ea);
1727 		} else {
1728 			bad_page_fault(regs, SIGBUS);
1729 		}
1730 		err = 0;
1731 
1732 	} else if (err) {
1733 		hash__do_page_fault(regs);
1734 	}
1735 }
1736 
1737 static bool should_hash_preload(struct mm_struct *mm, unsigned long ea)
1738 {
1739 	int psize = get_slice_psize(mm, ea);
1740 
1741 	/* We only prefault standard pages for now */
1742 	if (unlikely(psize != mm_ctx_user_psize(&mm->context)))
1743 		return false;
1744 
1745 	/*
1746 	 * Don't prefault if subpage protection is enabled for the EA.
1747 	 */
1748 	if (unlikely((psize == MMU_PAGE_4K) && subpage_protection(mm, ea)))
1749 		return false;
1750 
1751 	return true;
1752 }
1753 
1754 static void hash_preload(struct mm_struct *mm, pte_t *ptep, unsigned long ea,
1755 			 bool is_exec, unsigned long trap)
1756 {
1757 	unsigned long vsid;
1758 	pgd_t *pgdir;
1759 	int rc, ssize, update_flags = 0;
1760 	unsigned long access = _PAGE_PRESENT | _PAGE_READ | (is_exec ? _PAGE_EXEC : 0);
1761 	unsigned long flags;
1762 
1763 	BUG_ON(get_region_id(ea) != USER_REGION_ID);
1764 
1765 	if (!should_hash_preload(mm, ea))
1766 		return;
1767 
1768 	DBG_LOW("hash_preload(mm=%p, mm->pgdir=%p, ea=%016lx, access=%lx,"
1769 		" trap=%lx\n", mm, mm->pgd, ea, access, trap);
1770 
1771 	/* Get Linux PTE if available */
1772 	pgdir = mm->pgd;
1773 	if (pgdir == NULL)
1774 		return;
1775 
1776 	/* Get VSID */
1777 	ssize = user_segment_size(ea);
1778 	vsid = get_user_vsid(&mm->context, ea, ssize);
1779 	if (!vsid)
1780 		return;
1781 
1782 #ifdef CONFIG_PPC_64K_PAGES
1783 	/* If either H_PAGE_4K_PFN or cache inhibited is set (and we are on
1784 	 * a 64K kernel), then we don't preload, hash_page() will take
1785 	 * care of it once we actually try to access the page.
1786 	 * That way we don't have to duplicate all of the logic for segment
1787 	 * page size demotion here
1788 	 * Called with  PTL held, hence can be sure the value won't change in
1789 	 * between.
1790 	 */
1791 	if ((pte_val(*ptep) & H_PAGE_4K_PFN) || pte_ci(*ptep))
1792 		return;
1793 #endif /* CONFIG_PPC_64K_PAGES */
1794 
1795 	/*
1796 	 * __hash_page_* must run with interrupts off, including PMI interrupts
1797 	 * off, as it sets the H_PAGE_BUSY bit.
1798 	 *
1799 	 * It's otherwise possible for perf interrupts to hit at any time and
1800 	 * may take a hash fault reading the user stack, which could take a
1801 	 * hash miss and deadlock on the same H_PAGE_BUSY bit.
1802 	 *
1803 	 * Interrupts must also be off for the duration of the
1804 	 * mm_is_thread_local test and update, to prevent preempt running the
1805 	 * mm on another CPU (XXX: this may be racy vs kthread_use_mm).
1806 	 */
1807 	powerpc_local_irq_pmu_save(flags);
1808 
1809 	/* Is that local to this CPU ? */
1810 	if (mm_is_thread_local(mm))
1811 		update_flags |= HPTE_LOCAL_UPDATE;
1812 
1813 	/* Hash it in */
1814 #ifdef CONFIG_PPC_64K_PAGES
1815 	if (mm_ctx_user_psize(&mm->context) == MMU_PAGE_64K)
1816 		rc = __hash_page_64K(ea, access, vsid, ptep, trap,
1817 				     update_flags, ssize);
1818 	else
1819 #endif /* CONFIG_PPC_64K_PAGES */
1820 		rc = __hash_page_4K(ea, access, vsid, ptep, trap, update_flags,
1821 				    ssize, subpage_protection(mm, ea));
1822 
1823 	/* Dump some info in case of hash insertion failure, they should
1824 	 * never happen so it is really useful to know if/when they do
1825 	 */
1826 	if (rc == -1)
1827 		hash_failure_debug(ea, access, vsid, trap, ssize,
1828 				   mm_ctx_user_psize(&mm->context),
1829 				   mm_ctx_user_psize(&mm->context),
1830 				   pte_val(*ptep));
1831 
1832 	powerpc_local_irq_pmu_restore(flags);
1833 }
1834 
1835 /*
1836  * This is called at the end of handling a user page fault, when the
1837  * fault has been handled by updating a PTE in the linux page tables.
1838  * We use it to preload an HPTE into the hash table corresponding to
1839  * the updated linux PTE.
1840  *
1841  * This must always be called with the pte lock held.
1842  */
1843 void __update_mmu_cache(struct vm_area_struct *vma, unsigned long address,
1844 		      pte_t *ptep)
1845 {
1846 	/*
1847 	 * We don't need to worry about _PAGE_PRESENT here because we are
1848 	 * called with either mm->page_table_lock held or ptl lock held
1849 	 */
1850 	unsigned long trap;
1851 	bool is_exec;
1852 
1853 	/* We only want HPTEs for linux PTEs that have _PAGE_ACCESSED set */
1854 	if (!pte_young(*ptep) || address >= TASK_SIZE)
1855 		return;
1856 
1857 	/*
1858 	 * We try to figure out if we are coming from an instruction
1859 	 * access fault and pass that down to __hash_page so we avoid
1860 	 * double-faulting on execution of fresh text. We have to test
1861 	 * for regs NULL since init will get here first thing at boot.
1862 	 *
1863 	 * We also avoid filling the hash if not coming from a fault.
1864 	 */
1865 
1866 	trap = current->thread.regs ? TRAP(current->thread.regs) : 0UL;
1867 	switch (trap) {
1868 	case 0x300:
1869 		is_exec = false;
1870 		break;
1871 	case 0x400:
1872 		is_exec = true;
1873 		break;
1874 	default:
1875 		return;
1876 	}
1877 
1878 	hash_preload(vma->vm_mm, ptep, address, is_exec, trap);
1879 }
1880 
1881 #ifdef CONFIG_PPC_TRANSACTIONAL_MEM
1882 static inline void tm_flush_hash_page(int local)
1883 {
1884 	/*
1885 	 * Transactions are not aborted by tlbiel, only tlbie. Without, syncing a
1886 	 * page back to a block device w/PIO could pick up transactional data
1887 	 * (bad!) so we force an abort here. Before the sync the page will be
1888 	 * made read-only, which will flush_hash_page. BIG ISSUE here: if the
1889 	 * kernel uses a page from userspace without unmapping it first, it may
1890 	 * see the speculated version.
1891 	 */
1892 	if (local && cpu_has_feature(CPU_FTR_TM) && current->thread.regs &&
1893 	    MSR_TM_ACTIVE(current->thread.regs->msr)) {
1894 		tm_enable();
1895 		tm_abort(TM_CAUSE_TLBI);
1896 	}
1897 }
1898 #else
1899 static inline void tm_flush_hash_page(int local)
1900 {
1901 }
1902 #endif
1903 
1904 /*
1905  * Return the global hash slot, corresponding to the given PTE, which contains
1906  * the HPTE.
1907  */
1908 unsigned long pte_get_hash_gslot(unsigned long vpn, unsigned long shift,
1909 		int ssize, real_pte_t rpte, unsigned int subpg_index)
1910 {
1911 	unsigned long hash, gslot, hidx;
1912 
1913 	hash = hpt_hash(vpn, shift, ssize);
1914 	hidx = __rpte_to_hidx(rpte, subpg_index);
1915 	if (hidx & _PTEIDX_SECONDARY)
1916 		hash = ~hash;
1917 	gslot = (hash & htab_hash_mask) * HPTES_PER_GROUP;
1918 	gslot += hidx & _PTEIDX_GROUP_IX;
1919 	return gslot;
1920 }
1921 
1922 void flush_hash_page(unsigned long vpn, real_pte_t pte, int psize, int ssize,
1923 		     unsigned long flags)
1924 {
1925 	unsigned long index, shift, gslot;
1926 	int local = flags & HPTE_LOCAL_UPDATE;
1927 
1928 	DBG_LOW("flush_hash_page(vpn=%016lx)\n", vpn);
1929 	pte_iterate_hashed_subpages(pte, psize, vpn, index, shift) {
1930 		gslot = pte_get_hash_gslot(vpn, shift, ssize, pte, index);
1931 		DBG_LOW(" sub %ld: gslot=%lx\n", index, gslot);
1932 		/*
1933 		 * We use same base page size and actual psize, because we don't
1934 		 * use these functions for hugepage
1935 		 */
1936 		mmu_hash_ops.hpte_invalidate(gslot, vpn, psize, psize,
1937 					     ssize, local);
1938 	} pte_iterate_hashed_end();
1939 
1940 	tm_flush_hash_page(local);
1941 }
1942 
1943 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1944 void flush_hash_hugepage(unsigned long vsid, unsigned long addr,
1945 			 pmd_t *pmdp, unsigned int psize, int ssize,
1946 			 unsigned long flags)
1947 {
1948 	int i, max_hpte_count, valid;
1949 	unsigned long s_addr;
1950 	unsigned char *hpte_slot_array;
1951 	unsigned long hidx, shift, vpn, hash, slot;
1952 	int local = flags & HPTE_LOCAL_UPDATE;
1953 
1954 	s_addr = addr & HPAGE_PMD_MASK;
1955 	hpte_slot_array = get_hpte_slot_array(pmdp);
1956 	/*
1957 	 * IF we try to do a HUGE PTE update after a withdraw is done.
1958 	 * we will find the below NULL. This happens when we do
1959 	 * split_huge_pmd
1960 	 */
1961 	if (!hpte_slot_array)
1962 		return;
1963 
1964 	if (mmu_hash_ops.hugepage_invalidate) {
1965 		mmu_hash_ops.hugepage_invalidate(vsid, s_addr, hpte_slot_array,
1966 						 psize, ssize, local);
1967 		goto tm_abort;
1968 	}
1969 	/*
1970 	 * No bluk hpte removal support, invalidate each entry
1971 	 */
1972 	shift = mmu_psize_defs[psize].shift;
1973 	max_hpte_count = HPAGE_PMD_SIZE >> shift;
1974 	for (i = 0; i < max_hpte_count; i++) {
1975 		/*
1976 		 * 8 bits per each hpte entries
1977 		 * 000| [ secondary group (one bit) | hidx (3 bits) | valid bit]
1978 		 */
1979 		valid = hpte_valid(hpte_slot_array, i);
1980 		if (!valid)
1981 			continue;
1982 		hidx =  hpte_hash_index(hpte_slot_array, i);
1983 
1984 		/* get the vpn */
1985 		addr = s_addr + (i * (1ul << shift));
1986 		vpn = hpt_vpn(addr, vsid, ssize);
1987 		hash = hpt_hash(vpn, shift, ssize);
1988 		if (hidx & _PTEIDX_SECONDARY)
1989 			hash = ~hash;
1990 
1991 		slot = (hash & htab_hash_mask) * HPTES_PER_GROUP;
1992 		slot += hidx & _PTEIDX_GROUP_IX;
1993 		mmu_hash_ops.hpte_invalidate(slot, vpn, psize,
1994 					     MMU_PAGE_16M, ssize, local);
1995 	}
1996 tm_abort:
1997 	tm_flush_hash_page(local);
1998 }
1999 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
2000 
2001 void flush_hash_range(unsigned long number, int local)
2002 {
2003 	if (mmu_hash_ops.flush_hash_range)
2004 		mmu_hash_ops.flush_hash_range(number, local);
2005 	else {
2006 		int i;
2007 		struct ppc64_tlb_batch *batch =
2008 			this_cpu_ptr(&ppc64_tlb_batch);
2009 
2010 		for (i = 0; i < number; i++)
2011 			flush_hash_page(batch->vpn[i], batch->pte[i],
2012 					batch->psize, batch->ssize, local);
2013 	}
2014 }
2015 
2016 long hpte_insert_repeating(unsigned long hash, unsigned long vpn,
2017 			   unsigned long pa, unsigned long rflags,
2018 			   unsigned long vflags, int psize, int ssize)
2019 {
2020 	unsigned long hpte_group;
2021 	long slot;
2022 
2023 repeat:
2024 	hpte_group = (hash & htab_hash_mask) * HPTES_PER_GROUP;
2025 
2026 	/* Insert into the hash table, primary slot */
2027 	slot = mmu_hash_ops.hpte_insert(hpte_group, vpn, pa, rflags, vflags,
2028 					psize, psize, ssize);
2029 
2030 	/* Primary is full, try the secondary */
2031 	if (unlikely(slot == -1)) {
2032 		hpte_group = (~hash & htab_hash_mask) * HPTES_PER_GROUP;
2033 		slot = mmu_hash_ops.hpte_insert(hpte_group, vpn, pa, rflags,
2034 						vflags | HPTE_V_SECONDARY,
2035 						psize, psize, ssize);
2036 		if (slot == -1) {
2037 			if (mftb() & 0x1)
2038 				hpte_group = (hash & htab_hash_mask) *
2039 						HPTES_PER_GROUP;
2040 
2041 			mmu_hash_ops.hpte_remove(hpte_group);
2042 			goto repeat;
2043 		}
2044 	}
2045 
2046 	return slot;
2047 }
2048 
2049 void hpt_clear_stress(void)
2050 {
2051 	int cpu = raw_smp_processor_id();
2052 	int g;
2053 
2054 	for (g = 0; g < stress_nr_groups(); g++) {
2055 		unsigned long last_group;
2056 		last_group = stress_hpt_struct[cpu].last_group[g];
2057 
2058 		if (last_group != -1UL) {
2059 			int i;
2060 			for (i = 0; i < HPTES_PER_GROUP; i++) {
2061 				if (mmu_hash_ops.hpte_remove(last_group) == -1)
2062 					break;
2063 			}
2064 			stress_hpt_struct[cpu].last_group[g] = -1;
2065 		}
2066 	}
2067 }
2068 
2069 void hpt_do_stress(unsigned long ea, unsigned long hpte_group)
2070 {
2071 	unsigned long last_group;
2072 	int cpu = raw_smp_processor_id();
2073 
2074 	last_group = stress_hpt_struct[cpu].last_group[stress_nr_groups() - 1];
2075 	if (hpte_group == last_group)
2076 		return;
2077 
2078 	if (last_group != -1UL) {
2079 		int i;
2080 		/*
2081 		 * Concurrent CPUs might be inserting into this group, so
2082 		 * give up after a number of iterations, to prevent a live
2083 		 * lock.
2084 		 */
2085 		for (i = 0; i < HPTES_PER_GROUP; i++) {
2086 			if (mmu_hash_ops.hpte_remove(last_group) == -1)
2087 				break;
2088 		}
2089 		stress_hpt_struct[cpu].last_group[stress_nr_groups() - 1] = -1;
2090 	}
2091 
2092 	if (ea >= PAGE_OFFSET) {
2093 		/*
2094 		 * We would really like to prefetch to get the TLB loaded, then
2095 		 * remove the PTE before returning from fault interrupt, to
2096 		 * increase the hash fault rate.
2097 		 *
2098 		 * Unfortunately QEMU TCG does not model the TLB in a way that
2099 		 * makes this possible, and systemsim (mambo) emulator does not
2100 		 * bring in TLBs with prefetches (although loads/stores do
2101 		 * work for non-CI PTEs).
2102 		 *
2103 		 * So remember this PTE and clear it on the next hash fault.
2104 		 */
2105 		memmove(&stress_hpt_struct[cpu].last_group[1],
2106 			&stress_hpt_struct[cpu].last_group[0],
2107 			(stress_nr_groups() - 1) * sizeof(unsigned long));
2108 		stress_hpt_struct[cpu].last_group[0] = hpte_group;
2109 	}
2110 }
2111 
2112 #if defined(CONFIG_DEBUG_PAGEALLOC) || defined(CONFIG_KFENCE)
2113 static DEFINE_RAW_SPINLOCK(linear_map_hash_lock);
2114 
2115 static void kernel_map_linear_page(unsigned long vaddr, unsigned long lmi)
2116 {
2117 	unsigned long hash;
2118 	unsigned long vsid = get_kernel_vsid(vaddr, mmu_kernel_ssize);
2119 	unsigned long vpn = hpt_vpn(vaddr, vsid, mmu_kernel_ssize);
2120 	unsigned long mode = htab_convert_pte_flags(pgprot_val(PAGE_KERNEL), HPTE_USE_KERNEL_KEY);
2121 	long ret;
2122 
2123 	hash = hpt_hash(vpn, PAGE_SHIFT, mmu_kernel_ssize);
2124 
2125 	/* Don't create HPTE entries for bad address */
2126 	if (!vsid)
2127 		return;
2128 
2129 	if (linear_map_hash_slots[lmi] & 0x80)
2130 		return;
2131 
2132 	ret = hpte_insert_repeating(hash, vpn, __pa(vaddr), mode,
2133 				    HPTE_V_BOLTED,
2134 				    mmu_linear_psize, mmu_kernel_ssize);
2135 
2136 	BUG_ON (ret < 0);
2137 	raw_spin_lock(&linear_map_hash_lock);
2138 	BUG_ON(linear_map_hash_slots[lmi] & 0x80);
2139 	linear_map_hash_slots[lmi] = ret | 0x80;
2140 	raw_spin_unlock(&linear_map_hash_lock);
2141 }
2142 
2143 static void kernel_unmap_linear_page(unsigned long vaddr, unsigned long lmi)
2144 {
2145 	unsigned long hash, hidx, slot;
2146 	unsigned long vsid = get_kernel_vsid(vaddr, mmu_kernel_ssize);
2147 	unsigned long vpn = hpt_vpn(vaddr, vsid, mmu_kernel_ssize);
2148 
2149 	hash = hpt_hash(vpn, PAGE_SHIFT, mmu_kernel_ssize);
2150 	raw_spin_lock(&linear_map_hash_lock);
2151 	if (!(linear_map_hash_slots[lmi] & 0x80)) {
2152 		raw_spin_unlock(&linear_map_hash_lock);
2153 		return;
2154 	}
2155 	hidx = linear_map_hash_slots[lmi] & 0x7f;
2156 	linear_map_hash_slots[lmi] = 0;
2157 	raw_spin_unlock(&linear_map_hash_lock);
2158 	if (hidx & _PTEIDX_SECONDARY)
2159 		hash = ~hash;
2160 	slot = (hash & htab_hash_mask) * HPTES_PER_GROUP;
2161 	slot += hidx & _PTEIDX_GROUP_IX;
2162 	mmu_hash_ops.hpte_invalidate(slot, vpn, mmu_linear_psize,
2163 				     mmu_linear_psize,
2164 				     mmu_kernel_ssize, 0);
2165 }
2166 
2167 void hash__kernel_map_pages(struct page *page, int numpages, int enable)
2168 {
2169 	unsigned long flags, vaddr, lmi;
2170 	int i;
2171 
2172 	local_irq_save(flags);
2173 	for (i = 0; i < numpages; i++, page++) {
2174 		vaddr = (unsigned long)page_address(page);
2175 		lmi = __pa(vaddr) >> PAGE_SHIFT;
2176 		if (lmi >= linear_map_hash_count)
2177 			continue;
2178 		if (enable)
2179 			kernel_map_linear_page(vaddr, lmi);
2180 		else
2181 			kernel_unmap_linear_page(vaddr, lmi);
2182 	}
2183 	local_irq_restore(flags);
2184 }
2185 #endif /* CONFIG_DEBUG_PAGEALLOC || CONFIG_KFENCE */
2186 
2187 void hash__setup_initial_memory_limit(phys_addr_t first_memblock_base,
2188 				phys_addr_t first_memblock_size)
2189 {
2190 	/*
2191 	 * We don't currently support the first MEMBLOCK not mapping 0
2192 	 * physical on those processors
2193 	 */
2194 	BUG_ON(first_memblock_base != 0);
2195 
2196 	/*
2197 	 * On virtualized systems the first entry is our RMA region aka VRMA,
2198 	 * non-virtualized 64-bit hash MMU systems don't have a limitation
2199 	 * on real mode access.
2200 	 *
2201 	 * For guests on platforms before POWER9, we clamp the it limit to 1G
2202 	 * to avoid some funky things such as RTAS bugs etc...
2203 	 *
2204 	 * On POWER9 we limit to 1TB in case the host erroneously told us that
2205 	 * the RMA was >1TB. Effective address bits 0:23 are treated as zero
2206 	 * (meaning the access is aliased to zero i.e. addr = addr % 1TB)
2207 	 * for virtual real mode addressing and so it doesn't make sense to
2208 	 * have an area larger than 1TB as it can't be addressed.
2209 	 */
2210 	if (!early_cpu_has_feature(CPU_FTR_HVMODE)) {
2211 		ppc64_rma_size = first_memblock_size;
2212 		if (!early_cpu_has_feature(CPU_FTR_ARCH_300))
2213 			ppc64_rma_size = min_t(u64, ppc64_rma_size, 0x40000000);
2214 		else
2215 			ppc64_rma_size = min_t(u64, ppc64_rma_size,
2216 					       1UL << SID_SHIFT_1T);
2217 
2218 		/* Finally limit subsequent allocations */
2219 		memblock_set_current_limit(ppc64_rma_size);
2220 	} else {
2221 		ppc64_rma_size = ULONG_MAX;
2222 	}
2223 }
2224 
2225 #ifdef CONFIG_DEBUG_FS
2226 
2227 static int hpt_order_get(void *data, u64 *val)
2228 {
2229 	*val = ppc64_pft_size;
2230 	return 0;
2231 }
2232 
2233 static int hpt_order_set(void *data, u64 val)
2234 {
2235 	int ret;
2236 
2237 	if (!mmu_hash_ops.resize_hpt)
2238 		return -ENODEV;
2239 
2240 	cpus_read_lock();
2241 	ret = mmu_hash_ops.resize_hpt(val);
2242 	cpus_read_unlock();
2243 
2244 	return ret;
2245 }
2246 
2247 DEFINE_DEBUGFS_ATTRIBUTE(fops_hpt_order, hpt_order_get, hpt_order_set, "%llu\n");
2248 
2249 static int __init hash64_debugfs(void)
2250 {
2251 	debugfs_create_file("hpt_order", 0600, arch_debugfs_dir, NULL,
2252 			    &fops_hpt_order);
2253 	return 0;
2254 }
2255 machine_device_initcall(pseries, hash64_debugfs);
2256 #endif /* CONFIG_DEBUG_FS */
2257 
2258 void __init print_system_hash_info(void)
2259 {
2260 	pr_info("ppc64_pft_size    = 0x%llx\n", ppc64_pft_size);
2261 
2262 	if (htab_hash_mask)
2263 		pr_info("htab_hash_mask    = 0x%lx\n", htab_hash_mask);
2264 }
2265 
2266 unsigned long arch_randomize_brk(struct mm_struct *mm)
2267 {
2268 	/*
2269 	 * If we are using 1TB segments and we are allowed to randomise
2270 	 * the heap, we can put it above 1TB so it is backed by a 1TB
2271 	 * segment. Otherwise the heap will be in the bottom 1TB
2272 	 * which always uses 256MB segments and this may result in a
2273 	 * performance penalty.
2274 	 */
2275 	if (is_32bit_task())
2276 		return randomize_page(mm->brk, SZ_32M);
2277 	else if (!radix_enabled() && mmu_highuser_ssize == MMU_SEGSIZE_1T)
2278 		return randomize_page(max_t(unsigned long, mm->brk, SZ_1T), SZ_1G);
2279 	else
2280 		return randomize_page(mm->brk, SZ_1G);
2281 }
2282