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