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