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