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