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