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