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