GNU Linux-libre 4.4.283-gnu1
[releases.git] / arch / sparc / mm / init_64.c
1 /*
2  *  arch/sparc64/mm/init.c
3  *
4  *  Copyright (C) 1996-1999 David S. Miller (davem@caip.rutgers.edu)
5  *  Copyright (C) 1997-1999 Jakub Jelinek (jj@sunsite.mff.cuni.cz)
6  */
7  
8 #include <linux/module.h>
9 #include <linux/kernel.h>
10 #include <linux/sched.h>
11 #include <linux/string.h>
12 #include <linux/init.h>
13 #include <linux/bootmem.h>
14 #include <linux/mm.h>
15 #include <linux/hugetlb.h>
16 #include <linux/initrd.h>
17 #include <linux/swap.h>
18 #include <linux/pagemap.h>
19 #include <linux/poison.h>
20 #include <linux/fs.h>
21 #include <linux/seq_file.h>
22 #include <linux/kprobes.h>
23 #include <linux/cache.h>
24 #include <linux/sort.h>
25 #include <linux/ioport.h>
26 #include <linux/percpu.h>
27 #include <linux/memblock.h>
28 #include <linux/mmzone.h>
29 #include <linux/gfp.h>
30
31 #include <asm/head.h>
32 #include <asm/page.h>
33 #include <asm/pgalloc.h>
34 #include <asm/pgtable.h>
35 #include <asm/oplib.h>
36 #include <asm/iommu.h>
37 #include <asm/io.h>
38 #include <asm/uaccess.h>
39 #include <asm/mmu_context.h>
40 #include <asm/tlbflush.h>
41 #include <asm/dma.h>
42 #include <asm/starfire.h>
43 #include <asm/tlb.h>
44 #include <asm/spitfire.h>
45 #include <asm/sections.h>
46 #include <asm/tsb.h>
47 #include <asm/hypervisor.h>
48 #include <asm/prom.h>
49 #include <asm/mdesc.h>
50 #include <asm/cpudata.h>
51 #include <asm/setup.h>
52 #include <asm/irq.h>
53
54 #include "init_64.h"
55
56 unsigned long kern_linear_pte_xor[4] __read_mostly;
57 static unsigned long page_cache4v_flag;
58
59 /* A bitmap, two bits for every 256MB of physical memory.  These two
60  * bits determine what page size we use for kernel linear
61  * translations.  They form an index into kern_linear_pte_xor[].  The
62  * value in the indexed slot is XOR'd with the TLB miss virtual
63  * address to form the resulting TTE.  The mapping is:
64  *
65  *      0       ==>     4MB
66  *      1       ==>     256MB
67  *      2       ==>     2GB
68  *      3       ==>     16GB
69  *
70  * All sun4v chips support 256MB pages.  Only SPARC-T4 and later
71  * support 2GB pages, and hopefully future cpus will support the 16GB
72  * pages as well.  For slots 2 and 3, we encode a 256MB TTE xor there
73  * if these larger page sizes are not supported by the cpu.
74  *
75  * It would be nice to determine this from the machine description
76  * 'cpu' properties, but we need to have this table setup before the
77  * MDESC is initialized.
78  */
79
80 #ifndef CONFIG_DEBUG_PAGEALLOC
81 /* A special kernel TSB for 4MB, 256MB, 2GB and 16GB linear mappings.
82  * Space is allocated for this right after the trap table in
83  * arch/sparc64/kernel/head.S
84  */
85 extern struct tsb swapper_4m_tsb[KERNEL_TSB4M_NENTRIES];
86 #endif
87 extern struct tsb swapper_tsb[KERNEL_TSB_NENTRIES];
88
89 static unsigned long cpu_pgsz_mask;
90
91 #define MAX_BANKS       1024
92
93 static struct linux_prom64_registers pavail[MAX_BANKS];
94 static int pavail_ents;
95
96 u64 numa_latency[MAX_NUMNODES][MAX_NUMNODES];
97
98 static int cmp_p64(const void *a, const void *b)
99 {
100         const struct linux_prom64_registers *x = a, *y = b;
101
102         if (x->phys_addr > y->phys_addr)
103                 return 1;
104         if (x->phys_addr < y->phys_addr)
105                 return -1;
106         return 0;
107 }
108
109 static void __init read_obp_memory(const char *property,
110                                    struct linux_prom64_registers *regs,
111                                    int *num_ents)
112 {
113         phandle node = prom_finddevice("/memory");
114         int prop_size = prom_getproplen(node, property);
115         int ents, ret, i;
116
117         ents = prop_size / sizeof(struct linux_prom64_registers);
118         if (ents > MAX_BANKS) {
119                 prom_printf("The machine has more %s property entries than "
120                             "this kernel can support (%d).\n",
121                             property, MAX_BANKS);
122                 prom_halt();
123         }
124
125         ret = prom_getproperty(node, property, (char *) regs, prop_size);
126         if (ret == -1) {
127                 prom_printf("Couldn't get %s property from /memory.\n",
128                                 property);
129                 prom_halt();
130         }
131
132         /* Sanitize what we got from the firmware, by page aligning
133          * everything.
134          */
135         for (i = 0; i < ents; i++) {
136                 unsigned long base, size;
137
138                 base = regs[i].phys_addr;
139                 size = regs[i].reg_size;
140
141                 size &= PAGE_MASK;
142                 if (base & ~PAGE_MASK) {
143                         unsigned long new_base = PAGE_ALIGN(base);
144
145                         size -= new_base - base;
146                         if ((long) size < 0L)
147                                 size = 0UL;
148                         base = new_base;
149                 }
150                 if (size == 0UL) {
151                         /* If it is empty, simply get rid of it.
152                          * This simplifies the logic of the other
153                          * functions that process these arrays.
154                          */
155                         memmove(&regs[i], &regs[i + 1],
156                                 (ents - i - 1) * sizeof(regs[0]));
157                         i--;
158                         ents--;
159                         continue;
160                 }
161                 regs[i].phys_addr = base;
162                 regs[i].reg_size = size;
163         }
164
165         *num_ents = ents;
166
167         sort(regs, ents, sizeof(struct linux_prom64_registers),
168              cmp_p64, NULL);
169 }
170
171 /* Kernel physical address base and size in bytes.  */
172 unsigned long kern_base __read_mostly;
173 unsigned long kern_size __read_mostly;
174
175 /* Initial ramdisk setup */
176 extern unsigned long sparc_ramdisk_image64;
177 extern unsigned int sparc_ramdisk_image;
178 extern unsigned int sparc_ramdisk_size;
179
180 struct page *mem_map_zero __read_mostly;
181 EXPORT_SYMBOL(mem_map_zero);
182
183 unsigned int sparc64_highest_unlocked_tlb_ent __read_mostly;
184
185 unsigned long sparc64_kern_pri_context __read_mostly;
186 unsigned long sparc64_kern_pri_nuc_bits __read_mostly;
187 unsigned long sparc64_kern_sec_context __read_mostly;
188
189 int num_kernel_image_mappings;
190
191 #ifdef CONFIG_DEBUG_DCFLUSH
192 atomic_t dcpage_flushes = ATOMIC_INIT(0);
193 #ifdef CONFIG_SMP
194 atomic_t dcpage_flushes_xcall = ATOMIC_INIT(0);
195 #endif
196 #endif
197
198 inline void flush_dcache_page_impl(struct page *page)
199 {
200         BUG_ON(tlb_type == hypervisor);
201 #ifdef CONFIG_DEBUG_DCFLUSH
202         atomic_inc(&dcpage_flushes);
203 #endif
204
205 #ifdef DCACHE_ALIASING_POSSIBLE
206         __flush_dcache_page(page_address(page),
207                             ((tlb_type == spitfire) &&
208                              page_mapping(page) != NULL));
209 #else
210         if (page_mapping(page) != NULL &&
211             tlb_type == spitfire)
212                 __flush_icache_page(__pa(page_address(page)));
213 #endif
214 }
215
216 #define PG_dcache_dirty         PG_arch_1
217 #define PG_dcache_cpu_shift     32UL
218 #define PG_dcache_cpu_mask      \
219         ((1UL<<ilog2(roundup_pow_of_two(NR_CPUS)))-1UL)
220
221 #define dcache_dirty_cpu(page) \
222         (((page)->flags >> PG_dcache_cpu_shift) & PG_dcache_cpu_mask)
223
224 static inline void set_dcache_dirty(struct page *page, int this_cpu)
225 {
226         unsigned long mask = this_cpu;
227         unsigned long non_cpu_bits;
228
229         non_cpu_bits = ~(PG_dcache_cpu_mask << PG_dcache_cpu_shift);
230         mask = (mask << PG_dcache_cpu_shift) | (1UL << PG_dcache_dirty);
231
232         __asm__ __volatile__("1:\n\t"
233                              "ldx       [%2], %%g7\n\t"
234                              "and       %%g7, %1, %%g1\n\t"
235                              "or        %%g1, %0, %%g1\n\t"
236                              "casx      [%2], %%g7, %%g1\n\t"
237                              "cmp       %%g7, %%g1\n\t"
238                              "bne,pn    %%xcc, 1b\n\t"
239                              " nop"
240                              : /* no outputs */
241                              : "r" (mask), "r" (non_cpu_bits), "r" (&page->flags)
242                              : "g1", "g7");
243 }
244
245 static inline void clear_dcache_dirty_cpu(struct page *page, unsigned long cpu)
246 {
247         unsigned long mask = (1UL << PG_dcache_dirty);
248
249         __asm__ __volatile__("! test_and_clear_dcache_dirty\n"
250                              "1:\n\t"
251                              "ldx       [%2], %%g7\n\t"
252                              "srlx      %%g7, %4, %%g1\n\t"
253                              "and       %%g1, %3, %%g1\n\t"
254                              "cmp       %%g1, %0\n\t"
255                              "bne,pn    %%icc, 2f\n\t"
256                              " andn     %%g7, %1, %%g1\n\t"
257                              "casx      [%2], %%g7, %%g1\n\t"
258                              "cmp       %%g7, %%g1\n\t"
259                              "bne,pn    %%xcc, 1b\n\t"
260                              " nop\n"
261                              "2:"
262                              : /* no outputs */
263                              : "r" (cpu), "r" (mask), "r" (&page->flags),
264                                "i" (PG_dcache_cpu_mask),
265                                "i" (PG_dcache_cpu_shift)
266                              : "g1", "g7");
267 }
268
269 static inline void tsb_insert(struct tsb *ent, unsigned long tag, unsigned long pte)
270 {
271         unsigned long tsb_addr = (unsigned long) ent;
272
273         if (tlb_type == cheetah_plus || tlb_type == hypervisor)
274                 tsb_addr = __pa(tsb_addr);
275
276         __tsb_insert(tsb_addr, tag, pte);
277 }
278
279 unsigned long _PAGE_ALL_SZ_BITS __read_mostly;
280
281 static void flush_dcache(unsigned long pfn)
282 {
283         struct page *page;
284
285         page = pfn_to_page(pfn);
286         if (page) {
287                 unsigned long pg_flags;
288
289                 pg_flags = page->flags;
290                 if (pg_flags & (1UL << PG_dcache_dirty)) {
291                         int cpu = ((pg_flags >> PG_dcache_cpu_shift) &
292                                    PG_dcache_cpu_mask);
293                         int this_cpu = get_cpu();
294
295                         /* This is just to optimize away some function calls
296                          * in the SMP case.
297                          */
298                         if (cpu == this_cpu)
299                                 flush_dcache_page_impl(page);
300                         else
301                                 smp_flush_dcache_page_impl(page, cpu);
302
303                         clear_dcache_dirty_cpu(page, cpu);
304
305                         put_cpu();
306                 }
307         }
308 }
309
310 /* mm->context.lock must be held */
311 static void __update_mmu_tsb_insert(struct mm_struct *mm, unsigned long tsb_index,
312                                     unsigned long tsb_hash_shift, unsigned long address,
313                                     unsigned long tte)
314 {
315         struct tsb *tsb = mm->context.tsb_block[tsb_index].tsb;
316         unsigned long tag;
317
318         if (unlikely(!tsb))
319                 return;
320
321         tsb += ((address >> tsb_hash_shift) &
322                 (mm->context.tsb_block[tsb_index].tsb_nentries - 1UL));
323         tag = (address >> 22UL);
324         tsb_insert(tsb, tag, tte);
325 }
326
327 void update_mmu_cache(struct vm_area_struct *vma, unsigned long address, pte_t *ptep)
328 {
329         struct mm_struct *mm;
330         unsigned long flags;
331         pte_t pte = *ptep;
332
333         if (tlb_type != hypervisor) {
334                 unsigned long pfn = pte_pfn(pte);
335
336                 if (pfn_valid(pfn))
337                         flush_dcache(pfn);
338         }
339
340         mm = vma->vm_mm;
341
342         /* Don't insert a non-valid PTE into the TSB, we'll deadlock.  */
343         if (!pte_accessible(mm, pte))
344                 return;
345
346         spin_lock_irqsave(&mm->context.lock, flags);
347
348 #if defined(CONFIG_HUGETLB_PAGE) || defined(CONFIG_TRANSPARENT_HUGEPAGE)
349         if ((mm->context.hugetlb_pte_count || mm->context.thp_pte_count) &&
350             is_hugetlb_pte(pte))
351                 __update_mmu_tsb_insert(mm, MM_TSB_HUGE, REAL_HPAGE_SHIFT,
352                                         address, pte_val(pte));
353         else
354 #endif
355                 __update_mmu_tsb_insert(mm, MM_TSB_BASE, PAGE_SHIFT,
356                                         address, pte_val(pte));
357
358         spin_unlock_irqrestore(&mm->context.lock, flags);
359 }
360
361 void flush_dcache_page(struct page *page)
362 {
363         struct address_space *mapping;
364         int this_cpu;
365
366         if (tlb_type == hypervisor)
367                 return;
368
369         /* Do not bother with the expensive D-cache flush if it
370          * is merely the zero page.  The 'bigcore' testcase in GDB
371          * causes this case to run millions of times.
372          */
373         if (page == ZERO_PAGE(0))
374                 return;
375
376         this_cpu = get_cpu();
377
378         mapping = page_mapping(page);
379         if (mapping && !mapping_mapped(mapping)) {
380                 int dirty = test_bit(PG_dcache_dirty, &page->flags);
381                 if (dirty) {
382                         int dirty_cpu = dcache_dirty_cpu(page);
383
384                         if (dirty_cpu == this_cpu)
385                                 goto out;
386                         smp_flush_dcache_page_impl(page, dirty_cpu);
387                 }
388                 set_dcache_dirty(page, this_cpu);
389         } else {
390                 /* We could delay the flush for the !page_mapping
391                  * case too.  But that case is for exec env/arg
392                  * pages and those are %99 certainly going to get
393                  * faulted into the tlb (and thus flushed) anyways.
394                  */
395                 flush_dcache_page_impl(page);
396         }
397
398 out:
399         put_cpu();
400 }
401 EXPORT_SYMBOL(flush_dcache_page);
402
403 void __kprobes flush_icache_range(unsigned long start, unsigned long end)
404 {
405         /* Cheetah and Hypervisor platform cpus have coherent I-cache. */
406         if (tlb_type == spitfire) {
407                 unsigned long kaddr;
408
409                 /* This code only runs on Spitfire cpus so this is
410                  * why we can assume _PAGE_PADDR_4U.
411                  */
412                 for (kaddr = start; kaddr < end; kaddr += PAGE_SIZE) {
413                         unsigned long paddr, mask = _PAGE_PADDR_4U;
414
415                         if (kaddr >= PAGE_OFFSET)
416                                 paddr = kaddr & mask;
417                         else {
418                                 pgd_t *pgdp = pgd_offset_k(kaddr);
419                                 pud_t *pudp = pud_offset(pgdp, kaddr);
420                                 pmd_t *pmdp = pmd_offset(pudp, kaddr);
421                                 pte_t *ptep = pte_offset_kernel(pmdp, kaddr);
422
423                                 paddr = pte_val(*ptep) & mask;
424                         }
425                         __flush_icache_page(paddr);
426                 }
427         }
428 }
429 EXPORT_SYMBOL(flush_icache_range);
430
431 void mmu_info(struct seq_file *m)
432 {
433         static const char *pgsz_strings[] = {
434                 "8K", "64K", "512K", "4MB", "32MB",
435                 "256MB", "2GB", "16GB",
436         };
437         int i, printed;
438
439         if (tlb_type == cheetah)
440                 seq_printf(m, "MMU Type\t: Cheetah\n");
441         else if (tlb_type == cheetah_plus)
442                 seq_printf(m, "MMU Type\t: Cheetah+\n");
443         else if (tlb_type == spitfire)
444                 seq_printf(m, "MMU Type\t: Spitfire\n");
445         else if (tlb_type == hypervisor)
446                 seq_printf(m, "MMU Type\t: Hypervisor (sun4v)\n");
447         else
448                 seq_printf(m, "MMU Type\t: ???\n");
449
450         seq_printf(m, "MMU PGSZs\t: ");
451         printed = 0;
452         for (i = 0; i < ARRAY_SIZE(pgsz_strings); i++) {
453                 if (cpu_pgsz_mask & (1UL << i)) {
454                         seq_printf(m, "%s%s",
455                                    printed ? "," : "", pgsz_strings[i]);
456                         printed++;
457                 }
458         }
459         seq_putc(m, '\n');
460
461 #ifdef CONFIG_DEBUG_DCFLUSH
462         seq_printf(m, "DCPageFlushes\t: %d\n",
463                    atomic_read(&dcpage_flushes));
464 #ifdef CONFIG_SMP
465         seq_printf(m, "DCPageFlushesXC\t: %d\n",
466                    atomic_read(&dcpage_flushes_xcall));
467 #endif /* CONFIG_SMP */
468 #endif /* CONFIG_DEBUG_DCFLUSH */
469 }
470
471 struct linux_prom_translation prom_trans[512] __read_mostly;
472 unsigned int prom_trans_ents __read_mostly;
473
474 unsigned long kern_locked_tte_data;
475
476 /* The obp translations are saved based on 8k pagesize, since obp can
477  * use a mixture of pagesizes. Misses to the LOW_OBP_ADDRESS ->
478  * HI_OBP_ADDRESS range are handled in ktlb.S.
479  */
480 static inline int in_obp_range(unsigned long vaddr)
481 {
482         return (vaddr >= LOW_OBP_ADDRESS &&
483                 vaddr < HI_OBP_ADDRESS);
484 }
485
486 static int cmp_ptrans(const void *a, const void *b)
487 {
488         const struct linux_prom_translation *x = a, *y = b;
489
490         if (x->virt > y->virt)
491                 return 1;
492         if (x->virt < y->virt)
493                 return -1;
494         return 0;
495 }
496
497 /* Read OBP translations property into 'prom_trans[]'.  */
498 static void __init read_obp_translations(void)
499 {
500         int n, node, ents, first, last, i;
501
502         node = prom_finddevice("/virtual-memory");
503         n = prom_getproplen(node, "translations");
504         if (unlikely(n == 0 || n == -1)) {
505                 prom_printf("prom_mappings: Couldn't get size.\n");
506                 prom_halt();
507         }
508         if (unlikely(n > sizeof(prom_trans))) {
509                 prom_printf("prom_mappings: Size %d is too big.\n", n);
510                 prom_halt();
511         }
512
513         if ((n = prom_getproperty(node, "translations",
514                                   (char *)&prom_trans[0],
515                                   sizeof(prom_trans))) == -1) {
516                 prom_printf("prom_mappings: Couldn't get property.\n");
517                 prom_halt();
518         }
519
520         n = n / sizeof(struct linux_prom_translation);
521
522         ents = n;
523
524         sort(prom_trans, ents, sizeof(struct linux_prom_translation),
525              cmp_ptrans, NULL);
526
527         /* Now kick out all the non-OBP entries.  */
528         for (i = 0; i < ents; i++) {
529                 if (in_obp_range(prom_trans[i].virt))
530                         break;
531         }
532         first = i;
533         for (; i < ents; i++) {
534                 if (!in_obp_range(prom_trans[i].virt))
535                         break;
536         }
537         last = i;
538
539         for (i = 0; i < (last - first); i++) {
540                 struct linux_prom_translation *src = &prom_trans[i + first];
541                 struct linux_prom_translation *dest = &prom_trans[i];
542
543                 *dest = *src;
544         }
545         for (; i < ents; i++) {
546                 struct linux_prom_translation *dest = &prom_trans[i];
547                 dest->virt = dest->size = dest->data = 0x0UL;
548         }
549
550         prom_trans_ents = last - first;
551
552         if (tlb_type == spitfire) {
553                 /* Clear diag TTE bits. */
554                 for (i = 0; i < prom_trans_ents; i++)
555                         prom_trans[i].data &= ~0x0003fe0000000000UL;
556         }
557
558         /* Force execute bit on.  */
559         for (i = 0; i < prom_trans_ents; i++)
560                 prom_trans[i].data |= (tlb_type == hypervisor ?
561                                        _PAGE_EXEC_4V : _PAGE_EXEC_4U);
562 }
563
564 static void __init hypervisor_tlb_lock(unsigned long vaddr,
565                                        unsigned long pte,
566                                        unsigned long mmu)
567 {
568         unsigned long ret = sun4v_mmu_map_perm_addr(vaddr, 0, pte, mmu);
569
570         if (ret != 0) {
571                 prom_printf("hypervisor_tlb_lock[%lx:%x:%lx:%lx]: "
572                             "errors with %lx\n", vaddr, 0, pte, mmu, ret);
573                 prom_halt();
574         }
575 }
576
577 static unsigned long kern_large_tte(unsigned long paddr);
578
579 static void __init remap_kernel(void)
580 {
581         unsigned long phys_page, tte_vaddr, tte_data;
582         int i, tlb_ent = sparc64_highest_locked_tlbent();
583
584         tte_vaddr = (unsigned long) KERNBASE;
585         phys_page = (prom_boot_mapping_phys_low >> ILOG2_4MB) << ILOG2_4MB;
586         tte_data = kern_large_tte(phys_page);
587
588         kern_locked_tte_data = tte_data;
589
590         /* Now lock us into the TLBs via Hypervisor or OBP. */
591         if (tlb_type == hypervisor) {
592                 for (i = 0; i < num_kernel_image_mappings; i++) {
593                         hypervisor_tlb_lock(tte_vaddr, tte_data, HV_MMU_DMMU);
594                         hypervisor_tlb_lock(tte_vaddr, tte_data, HV_MMU_IMMU);
595                         tte_vaddr += 0x400000;
596                         tte_data += 0x400000;
597                 }
598         } else {
599                 for (i = 0; i < num_kernel_image_mappings; i++) {
600                         prom_dtlb_load(tlb_ent - i, tte_data, tte_vaddr);
601                         prom_itlb_load(tlb_ent - i, tte_data, tte_vaddr);
602                         tte_vaddr += 0x400000;
603                         tte_data += 0x400000;
604                 }
605                 sparc64_highest_unlocked_tlb_ent = tlb_ent - i;
606         }
607         if (tlb_type == cheetah_plus) {
608                 sparc64_kern_pri_context = (CTX_CHEETAH_PLUS_CTX0 |
609                                             CTX_CHEETAH_PLUS_NUC);
610                 sparc64_kern_pri_nuc_bits = CTX_CHEETAH_PLUS_NUC;
611                 sparc64_kern_sec_context = CTX_CHEETAH_PLUS_CTX0;
612         }
613 }
614
615
616 static void __init inherit_prom_mappings(void)
617 {
618         /* Now fixup OBP's idea about where we really are mapped. */
619         printk("Remapping the kernel... ");
620         remap_kernel();
621         printk("done.\n");
622 }
623
624 void prom_world(int enter)
625 {
626         if (!enter)
627                 set_fs(get_fs());
628
629         __asm__ __volatile__("flushw");
630 }
631
632 void __flush_dcache_range(unsigned long start, unsigned long end)
633 {
634         unsigned long va;
635
636         if (tlb_type == spitfire) {
637                 int n = 0;
638
639                 for (va = start; va < end; va += 32) {
640                         spitfire_put_dcache_tag(va & 0x3fe0, 0x0);
641                         if (++n >= 512)
642                                 break;
643                 }
644         } else if (tlb_type == cheetah || tlb_type == cheetah_plus) {
645                 start = __pa(start);
646                 end = __pa(end);
647                 for (va = start; va < end; va += 32)
648                         __asm__ __volatile__("stxa %%g0, [%0] %1\n\t"
649                                              "membar #Sync"
650                                              : /* no outputs */
651                                              : "r" (va),
652                                                "i" (ASI_DCACHE_INVALIDATE));
653         }
654 }
655 EXPORT_SYMBOL(__flush_dcache_range);
656
657 /* get_new_mmu_context() uses "cache + 1".  */
658 DEFINE_SPINLOCK(ctx_alloc_lock);
659 unsigned long tlb_context_cache = CTX_FIRST_VERSION;
660 #define MAX_CTX_NR      (1UL << CTX_NR_BITS)
661 #define CTX_BMAP_SLOTS  BITS_TO_LONGS(MAX_CTX_NR)
662 DECLARE_BITMAP(mmu_context_bmap, MAX_CTX_NR);
663 DEFINE_PER_CPU(struct mm_struct *, per_cpu_secondary_mm) = {0};
664
665 static void mmu_context_wrap(void)
666 {
667         unsigned long old_ver = tlb_context_cache & CTX_VERSION_MASK;
668         unsigned long new_ver, new_ctx, old_ctx;
669         struct mm_struct *mm;
670         int cpu;
671
672         bitmap_zero(mmu_context_bmap, 1 << CTX_NR_BITS);
673
674         /* Reserve kernel context */
675         set_bit(0, mmu_context_bmap);
676
677         new_ver = (tlb_context_cache & CTX_VERSION_MASK) + CTX_FIRST_VERSION;
678         if (unlikely(new_ver == 0))
679                 new_ver = CTX_FIRST_VERSION;
680         tlb_context_cache = new_ver;
681
682         /*
683          * Make sure that any new mm that are added into per_cpu_secondary_mm,
684          * are going to go through get_new_mmu_context() path.
685          */
686         mb();
687
688         /*
689          * Updated versions to current on those CPUs that had valid secondary
690          * contexts
691          */
692         for_each_online_cpu(cpu) {
693                 /*
694                  * If a new mm is stored after we took this mm from the array,
695                  * it will go into get_new_mmu_context() path, because we
696                  * already bumped the version in tlb_context_cache.
697                  */
698                 mm = per_cpu(per_cpu_secondary_mm, cpu);
699
700                 if (unlikely(!mm || mm == &init_mm))
701                         continue;
702
703                 old_ctx = mm->context.sparc64_ctx_val;
704                 if (likely((old_ctx & CTX_VERSION_MASK) == old_ver)) {
705                         new_ctx = (old_ctx & ~CTX_VERSION_MASK) | new_ver;
706                         set_bit(new_ctx & CTX_NR_MASK, mmu_context_bmap);
707                         mm->context.sparc64_ctx_val = new_ctx;
708                 }
709         }
710 }
711
712 /* Caller does TLB context flushing on local CPU if necessary.
713  * The caller also ensures that CTX_VALID(mm->context) is false.
714  *
715  * We must be careful about boundary cases so that we never
716  * let the user have CTX 0 (nucleus) or we ever use a CTX
717  * version of zero (and thus NO_CONTEXT would not be caught
718  * by version mis-match tests in mmu_context.h).
719  *
720  * Always invoked with interrupts disabled.
721  */
722 void get_new_mmu_context(struct mm_struct *mm)
723 {
724         unsigned long ctx, new_ctx;
725         unsigned long orig_pgsz_bits;
726
727         spin_lock(&ctx_alloc_lock);
728 retry:
729         /* wrap might have happened, test again if our context became valid */
730         if (unlikely(CTX_VALID(mm->context)))
731                 goto out;
732         orig_pgsz_bits = (mm->context.sparc64_ctx_val & CTX_PGSZ_MASK);
733         ctx = (tlb_context_cache + 1) & CTX_NR_MASK;
734         new_ctx = find_next_zero_bit(mmu_context_bmap, 1 << CTX_NR_BITS, ctx);
735         if (new_ctx >= (1 << CTX_NR_BITS)) {
736                 new_ctx = find_next_zero_bit(mmu_context_bmap, ctx, 1);
737                 if (new_ctx >= ctx) {
738                         mmu_context_wrap();
739                         goto retry;
740                 }
741         }
742         if (mm->context.sparc64_ctx_val)
743                 cpumask_clear(mm_cpumask(mm));
744         mmu_context_bmap[new_ctx>>6] |= (1UL << (new_ctx & 63));
745         new_ctx |= (tlb_context_cache & CTX_VERSION_MASK);
746         tlb_context_cache = new_ctx;
747         mm->context.sparc64_ctx_val = new_ctx | orig_pgsz_bits;
748 out:
749         spin_unlock(&ctx_alloc_lock);
750 }
751
752 static int numa_enabled = 1;
753 static int numa_debug;
754
755 static int __init early_numa(char *p)
756 {
757         if (!p)
758                 return 0;
759
760         if (strstr(p, "off"))
761                 numa_enabled = 0;
762
763         if (strstr(p, "debug"))
764                 numa_debug = 1;
765
766         return 0;
767 }
768 early_param("numa", early_numa);
769
770 #define numadbg(f, a...) \
771 do {    if (numa_debug) \
772                 printk(KERN_INFO f, ## a); \
773 } while (0)
774
775 static void __init find_ramdisk(unsigned long phys_base)
776 {
777 #ifdef CONFIG_BLK_DEV_INITRD
778         if (sparc_ramdisk_image || sparc_ramdisk_image64) {
779                 unsigned long ramdisk_image;
780
781                 /* Older versions of the bootloader only supported a
782                  * 32-bit physical address for the ramdisk image
783                  * location, stored at sparc_ramdisk_image.  Newer
784                  * SILO versions set sparc_ramdisk_image to zero and
785                  * provide a full 64-bit physical address at
786                  * sparc_ramdisk_image64.
787                  */
788                 ramdisk_image = sparc_ramdisk_image;
789                 if (!ramdisk_image)
790                         ramdisk_image = sparc_ramdisk_image64;
791
792                 /* Another bootloader quirk.  The bootloader normalizes
793                  * the physical address to KERNBASE, so we have to
794                  * factor that back out and add in the lowest valid
795                  * physical page address to get the true physical address.
796                  */
797                 ramdisk_image -= KERNBASE;
798                 ramdisk_image += phys_base;
799
800                 numadbg("Found ramdisk at physical address 0x%lx, size %u\n",
801                         ramdisk_image, sparc_ramdisk_size);
802
803                 initrd_start = ramdisk_image;
804                 initrd_end = ramdisk_image + sparc_ramdisk_size;
805
806                 memblock_reserve(initrd_start, sparc_ramdisk_size);
807
808                 initrd_start += PAGE_OFFSET;
809                 initrd_end += PAGE_OFFSET;
810         }
811 #endif
812 }
813
814 struct node_mem_mask {
815         unsigned long mask;
816         unsigned long val;
817 };
818 static struct node_mem_mask node_masks[MAX_NUMNODES];
819 static int num_node_masks;
820
821 #ifdef CONFIG_NEED_MULTIPLE_NODES
822
823 int numa_cpu_lookup_table[NR_CPUS];
824 cpumask_t numa_cpumask_lookup_table[MAX_NUMNODES];
825
826 struct mdesc_mblock {
827         u64     base;
828         u64     size;
829         u64     offset; /* RA-to-PA */
830 };
831 static struct mdesc_mblock *mblocks;
832 static int num_mblocks;
833 static int find_numa_node_for_addr(unsigned long pa,
834                                    struct node_mem_mask *pnode_mask);
835
836 static unsigned long __init ra_to_pa(unsigned long addr)
837 {
838         int i;
839
840         for (i = 0; i < num_mblocks; i++) {
841                 struct mdesc_mblock *m = &mblocks[i];
842
843                 if (addr >= m->base &&
844                     addr < (m->base + m->size)) {
845                         addr += m->offset;
846                         break;
847                 }
848         }
849         return addr;
850 }
851
852 static int __init find_node(unsigned long addr)
853 {
854         static bool search_mdesc = true;
855         static struct node_mem_mask last_mem_mask = { ~0UL, ~0UL };
856         static int last_index;
857         int i;
858
859         addr = ra_to_pa(addr);
860         for (i = 0; i < num_node_masks; i++) {
861                 struct node_mem_mask *p = &node_masks[i];
862
863                 if ((addr & p->mask) == p->val)
864                         return i;
865         }
866         /* The following condition has been observed on LDOM guests because
867          * node_masks only contains the best latency mask and value.
868          * LDOM guest's mdesc can contain a single latency group to
869          * cover multiple address range. Print warning message only if the
870          * address cannot be found in node_masks nor mdesc.
871          */
872         if ((search_mdesc) &&
873             ((addr & last_mem_mask.mask) != last_mem_mask.val)) {
874                 /* find the available node in the mdesc */
875                 last_index = find_numa_node_for_addr(addr, &last_mem_mask);
876                 numadbg("find_node: latency group for address 0x%lx is %d\n",
877                         addr, last_index);
878                 if ((last_index < 0) || (last_index >= num_node_masks)) {
879                         /* WARN_ONCE() and use default group 0 */
880                         WARN_ONCE(1, "find_node: A physical address doesn't match a NUMA node rule. Some physical memory will be owned by node 0.");
881                         search_mdesc = false;
882                         last_index = 0;
883                 }
884         }
885
886         return last_index;
887 }
888
889 static u64 __init memblock_nid_range(u64 start, u64 end, int *nid)
890 {
891         *nid = find_node(start);
892         start += PAGE_SIZE;
893         while (start < end) {
894                 int n = find_node(start);
895
896                 if (n != *nid)
897                         break;
898                 start += PAGE_SIZE;
899         }
900
901         if (start > end)
902                 start = end;
903
904         return start;
905 }
906 #endif
907
908 /* This must be invoked after performing all of the necessary
909  * memblock_set_node() calls for 'nid'.  We need to be able to get
910  * correct data from get_pfn_range_for_nid().
911  */
912 static void __init allocate_node_data(int nid)
913 {
914         struct pglist_data *p;
915         unsigned long start_pfn, end_pfn;
916 #ifdef CONFIG_NEED_MULTIPLE_NODES
917         unsigned long paddr;
918
919         paddr = memblock_alloc_try_nid(sizeof(struct pglist_data), SMP_CACHE_BYTES, nid);
920         if (!paddr) {
921                 prom_printf("Cannot allocate pglist_data for nid[%d]\n", nid);
922                 prom_halt();
923         }
924         NODE_DATA(nid) = __va(paddr);
925         memset(NODE_DATA(nid), 0, sizeof(struct pglist_data));
926
927         NODE_DATA(nid)->node_id = nid;
928 #endif
929
930         p = NODE_DATA(nid);
931
932         get_pfn_range_for_nid(nid, &start_pfn, &end_pfn);
933         p->node_start_pfn = start_pfn;
934         p->node_spanned_pages = end_pfn - start_pfn;
935 }
936
937 static void init_node_masks_nonnuma(void)
938 {
939 #ifdef CONFIG_NEED_MULTIPLE_NODES
940         int i;
941 #endif
942
943         numadbg("Initializing tables for non-numa.\n");
944
945         node_masks[0].mask = node_masks[0].val = 0;
946         num_node_masks = 1;
947
948 #ifdef CONFIG_NEED_MULTIPLE_NODES
949         for (i = 0; i < NR_CPUS; i++)
950                 numa_cpu_lookup_table[i] = 0;
951
952         cpumask_setall(&numa_cpumask_lookup_table[0]);
953 #endif
954 }
955
956 #ifdef CONFIG_NEED_MULTIPLE_NODES
957 struct pglist_data *node_data[MAX_NUMNODES];
958
959 EXPORT_SYMBOL(numa_cpu_lookup_table);
960 EXPORT_SYMBOL(numa_cpumask_lookup_table);
961 EXPORT_SYMBOL(node_data);
962
963 struct mdesc_mlgroup {
964         u64     node;
965         u64     latency;
966         u64     match;
967         u64     mask;
968 };
969 static struct mdesc_mlgroup *mlgroups;
970 static int num_mlgroups;
971
972 static int scan_pio_for_cfg_handle(struct mdesc_handle *md, u64 pio,
973                                    u32 cfg_handle)
974 {
975         u64 arc;
976
977         mdesc_for_each_arc(arc, md, pio, MDESC_ARC_TYPE_FWD) {
978                 u64 target = mdesc_arc_target(md, arc);
979                 const u64 *val;
980
981                 val = mdesc_get_property(md, target,
982                                          "cfg-handle", NULL);
983                 if (val && *val == cfg_handle)
984                         return 0;
985         }
986         return -ENODEV;
987 }
988
989 static int scan_arcs_for_cfg_handle(struct mdesc_handle *md, u64 grp,
990                                     u32 cfg_handle)
991 {
992         u64 arc, candidate, best_latency = ~(u64)0;
993
994         candidate = MDESC_NODE_NULL;
995         mdesc_for_each_arc(arc, md, grp, MDESC_ARC_TYPE_FWD) {
996                 u64 target = mdesc_arc_target(md, arc);
997                 const char *name = mdesc_node_name(md, target);
998                 const u64 *val;
999
1000                 if (strcmp(name, "pio-latency-group"))
1001                         continue;
1002
1003                 val = mdesc_get_property(md, target, "latency", NULL);
1004                 if (!val)
1005                         continue;
1006
1007                 if (*val < best_latency) {
1008                         candidate = target;
1009                         best_latency = *val;
1010                 }
1011         }
1012
1013         if (candidate == MDESC_NODE_NULL)
1014                 return -ENODEV;
1015
1016         return scan_pio_for_cfg_handle(md, candidate, cfg_handle);
1017 }
1018
1019 int of_node_to_nid(struct device_node *dp)
1020 {
1021         const struct linux_prom64_registers *regs;
1022         struct mdesc_handle *md;
1023         u32 cfg_handle;
1024         int count, nid;
1025         u64 grp;
1026
1027         /* This is the right thing to do on currently supported
1028          * SUN4U NUMA platforms as well, as the PCI controller does
1029          * not sit behind any particular memory controller.
1030          */
1031         if (!mlgroups)
1032                 return -1;
1033
1034         regs = of_get_property(dp, "reg", NULL);
1035         if (!regs)
1036                 return -1;
1037
1038         cfg_handle = (regs->phys_addr >> 32UL) & 0x0fffffff;
1039
1040         md = mdesc_grab();
1041
1042         count = 0;
1043         nid = -1;
1044         mdesc_for_each_node_by_name(md, grp, "group") {
1045                 if (!scan_arcs_for_cfg_handle(md, grp, cfg_handle)) {
1046                         nid = count;
1047                         break;
1048                 }
1049                 count++;
1050         }
1051
1052         mdesc_release(md);
1053
1054         return nid;
1055 }
1056
1057 static void __init add_node_ranges(void)
1058 {
1059         struct memblock_region *reg;
1060
1061         for_each_memblock(memory, reg) {
1062                 unsigned long size = reg->size;
1063                 unsigned long start, end;
1064
1065                 start = reg->base;
1066                 end = start + size;
1067                 while (start < end) {
1068                         unsigned long this_end;
1069                         int nid;
1070
1071                         this_end = memblock_nid_range(start, end, &nid);
1072
1073                         numadbg("Setting memblock NUMA node nid[%d] "
1074                                 "start[%lx] end[%lx]\n",
1075                                 nid, start, this_end);
1076
1077                         memblock_set_node(start, this_end - start,
1078                                           &memblock.memory, nid);
1079                         start = this_end;
1080                 }
1081         }
1082 }
1083
1084 static int __init grab_mlgroups(struct mdesc_handle *md)
1085 {
1086         unsigned long paddr;
1087         int count = 0;
1088         u64 node;
1089
1090         mdesc_for_each_node_by_name(md, node, "memory-latency-group")
1091                 count++;
1092         if (!count)
1093                 return -ENOENT;
1094
1095         paddr = memblock_alloc(count * sizeof(struct mdesc_mlgroup),
1096                           SMP_CACHE_BYTES);
1097         if (!paddr)
1098                 return -ENOMEM;
1099
1100         mlgroups = __va(paddr);
1101         num_mlgroups = count;
1102
1103         count = 0;
1104         mdesc_for_each_node_by_name(md, node, "memory-latency-group") {
1105                 struct mdesc_mlgroup *m = &mlgroups[count++];
1106                 const u64 *val;
1107
1108                 m->node = node;
1109
1110                 val = mdesc_get_property(md, node, "latency", NULL);
1111                 m->latency = *val;
1112                 val = mdesc_get_property(md, node, "address-match", NULL);
1113                 m->match = *val;
1114                 val = mdesc_get_property(md, node, "address-mask", NULL);
1115                 m->mask = *val;
1116
1117                 numadbg("MLGROUP[%d]: node[%llx] latency[%llx] "
1118                         "match[%llx] mask[%llx]\n",
1119                         count - 1, m->node, m->latency, m->match, m->mask);
1120         }
1121
1122         return 0;
1123 }
1124
1125 static int __init grab_mblocks(struct mdesc_handle *md)
1126 {
1127         unsigned long paddr;
1128         int count = 0;
1129         u64 node;
1130
1131         mdesc_for_each_node_by_name(md, node, "mblock")
1132                 count++;
1133         if (!count)
1134                 return -ENOENT;
1135
1136         paddr = memblock_alloc(count * sizeof(struct mdesc_mblock),
1137                           SMP_CACHE_BYTES);
1138         if (!paddr)
1139                 return -ENOMEM;
1140
1141         mblocks = __va(paddr);
1142         num_mblocks = count;
1143
1144         count = 0;
1145         mdesc_for_each_node_by_name(md, node, "mblock") {
1146                 struct mdesc_mblock *m = &mblocks[count++];
1147                 const u64 *val;
1148
1149                 val = mdesc_get_property(md, node, "base", NULL);
1150                 m->base = *val;
1151                 val = mdesc_get_property(md, node, "size", NULL);
1152                 m->size = *val;
1153                 val = mdesc_get_property(md, node,
1154                                          "address-congruence-offset", NULL);
1155
1156                 /* The address-congruence-offset property is optional.
1157                  * Explicity zero it be identifty this.
1158                  */
1159                 if (val)
1160                         m->offset = *val;
1161                 else
1162                         m->offset = 0UL;
1163
1164                 numadbg("MBLOCK[%d]: base[%llx] size[%llx] offset[%llx]\n",
1165                         count - 1, m->base, m->size, m->offset);
1166         }
1167
1168         return 0;
1169 }
1170
1171 static void __init numa_parse_mdesc_group_cpus(struct mdesc_handle *md,
1172                                                u64 grp, cpumask_t *mask)
1173 {
1174         u64 arc;
1175
1176         cpumask_clear(mask);
1177
1178         mdesc_for_each_arc(arc, md, grp, MDESC_ARC_TYPE_BACK) {
1179                 u64 target = mdesc_arc_target(md, arc);
1180                 const char *name = mdesc_node_name(md, target);
1181                 const u64 *id;
1182
1183                 if (strcmp(name, "cpu"))
1184                         continue;
1185                 id = mdesc_get_property(md, target, "id", NULL);
1186                 if (*id < nr_cpu_ids)
1187                         cpumask_set_cpu(*id, mask);
1188         }
1189 }
1190
1191 static struct mdesc_mlgroup * __init find_mlgroup(u64 node)
1192 {
1193         int i;
1194
1195         for (i = 0; i < num_mlgroups; i++) {
1196                 struct mdesc_mlgroup *m = &mlgroups[i];
1197                 if (m->node == node)
1198                         return m;
1199         }
1200         return NULL;
1201 }
1202
1203 int __node_distance(int from, int to)
1204 {
1205         if ((from >= MAX_NUMNODES) || (to >= MAX_NUMNODES)) {
1206                 pr_warn("Returning default NUMA distance value for %d->%d\n",
1207                         from, to);
1208                 return (from == to) ? LOCAL_DISTANCE : REMOTE_DISTANCE;
1209         }
1210         return numa_latency[from][to];
1211 }
1212
1213 static int find_numa_node_for_addr(unsigned long pa,
1214                                    struct node_mem_mask *pnode_mask)
1215 {
1216         struct mdesc_handle *md = mdesc_grab();
1217         u64 node, arc;
1218         int i = 0;
1219
1220         node = mdesc_node_by_name(md, MDESC_NODE_NULL, "latency-groups");
1221         if (node == MDESC_NODE_NULL)
1222                 goto out;
1223
1224         mdesc_for_each_node_by_name(md, node, "group") {
1225                 mdesc_for_each_arc(arc, md, node, MDESC_ARC_TYPE_FWD) {
1226                         u64 target = mdesc_arc_target(md, arc);
1227                         struct mdesc_mlgroup *m = find_mlgroup(target);
1228
1229                         if (!m)
1230                                 continue;
1231                         if ((pa & m->mask) == m->match) {
1232                                 if (pnode_mask) {
1233                                         pnode_mask->mask = m->mask;
1234                                         pnode_mask->val = m->match;
1235                                 }
1236                                 mdesc_release(md);
1237                                 return i;
1238                         }
1239                 }
1240                 i++;
1241         }
1242
1243 out:
1244         mdesc_release(md);
1245         return -1;
1246 }
1247
1248 static int find_best_numa_node_for_mlgroup(struct mdesc_mlgroup *grp)
1249 {
1250         int i;
1251
1252         for (i = 0; i < MAX_NUMNODES; i++) {
1253                 struct node_mem_mask *n = &node_masks[i];
1254
1255                 if ((grp->mask == n->mask) && (grp->match == n->val))
1256                         break;
1257         }
1258         return i;
1259 }
1260
1261 static void find_numa_latencies_for_group(struct mdesc_handle *md, u64 grp,
1262                                           int index)
1263 {
1264         u64 arc;
1265
1266         mdesc_for_each_arc(arc, md, grp, MDESC_ARC_TYPE_FWD) {
1267                 int tnode;
1268                 u64 target = mdesc_arc_target(md, arc);
1269                 struct mdesc_mlgroup *m = find_mlgroup(target);
1270
1271                 if (!m)
1272                         continue;
1273                 tnode = find_best_numa_node_for_mlgroup(m);
1274                 if (tnode == MAX_NUMNODES)
1275                         continue;
1276                 numa_latency[index][tnode] = m->latency;
1277         }
1278 }
1279
1280 static int __init numa_attach_mlgroup(struct mdesc_handle *md, u64 grp,
1281                                       int index)
1282 {
1283         struct mdesc_mlgroup *candidate = NULL;
1284         u64 arc, best_latency = ~(u64)0;
1285         struct node_mem_mask *n;
1286
1287         mdesc_for_each_arc(arc, md, grp, MDESC_ARC_TYPE_FWD) {
1288                 u64 target = mdesc_arc_target(md, arc);
1289                 struct mdesc_mlgroup *m = find_mlgroup(target);
1290                 if (!m)
1291                         continue;
1292                 if (m->latency < best_latency) {
1293                         candidate = m;
1294                         best_latency = m->latency;
1295                 }
1296         }
1297         if (!candidate)
1298                 return -ENOENT;
1299
1300         if (num_node_masks != index) {
1301                 printk(KERN_ERR "Inconsistent NUMA state, "
1302                        "index[%d] != num_node_masks[%d]\n",
1303                        index, num_node_masks);
1304                 return -EINVAL;
1305         }
1306
1307         n = &node_masks[num_node_masks++];
1308
1309         n->mask = candidate->mask;
1310         n->val = candidate->match;
1311
1312         numadbg("NUMA NODE[%d]: mask[%lx] val[%lx] (latency[%llx])\n",
1313                 index, n->mask, n->val, candidate->latency);
1314
1315         return 0;
1316 }
1317
1318 static int __init numa_parse_mdesc_group(struct mdesc_handle *md, u64 grp,
1319                                          int index)
1320 {
1321         cpumask_t mask;
1322         int cpu;
1323
1324         numa_parse_mdesc_group_cpus(md, grp, &mask);
1325
1326         for_each_cpu(cpu, &mask)
1327                 numa_cpu_lookup_table[cpu] = index;
1328         cpumask_copy(&numa_cpumask_lookup_table[index], &mask);
1329
1330         if (numa_debug) {
1331                 printk(KERN_INFO "NUMA GROUP[%d]: cpus [ ", index);
1332                 for_each_cpu(cpu, &mask)
1333                         printk("%d ", cpu);
1334                 printk("]\n");
1335         }
1336
1337         return numa_attach_mlgroup(md, grp, index);
1338 }
1339
1340 static int __init numa_parse_mdesc(void)
1341 {
1342         struct mdesc_handle *md = mdesc_grab();
1343         int i, j, err, count;
1344         u64 node;
1345
1346         node = mdesc_node_by_name(md, MDESC_NODE_NULL, "latency-groups");
1347         if (node == MDESC_NODE_NULL) {
1348                 mdesc_release(md);
1349                 return -ENOENT;
1350         }
1351
1352         err = grab_mblocks(md);
1353         if (err < 0)
1354                 goto out;
1355
1356         err = grab_mlgroups(md);
1357         if (err < 0)
1358                 goto out;
1359
1360         count = 0;
1361         mdesc_for_each_node_by_name(md, node, "group") {
1362                 err = numa_parse_mdesc_group(md, node, count);
1363                 if (err < 0)
1364                         break;
1365                 count++;
1366         }
1367
1368         count = 0;
1369         mdesc_for_each_node_by_name(md, node, "group") {
1370                 find_numa_latencies_for_group(md, node, count);
1371                 count++;
1372         }
1373
1374         /* Normalize numa latency matrix according to ACPI SLIT spec. */
1375         for (i = 0; i < MAX_NUMNODES; i++) {
1376                 u64 self_latency = numa_latency[i][i];
1377
1378                 for (j = 0; j < MAX_NUMNODES; j++) {
1379                         numa_latency[i][j] =
1380                                 (numa_latency[i][j] * LOCAL_DISTANCE) /
1381                                 self_latency;
1382                 }
1383         }
1384
1385         add_node_ranges();
1386
1387         for (i = 0; i < num_node_masks; i++) {
1388                 allocate_node_data(i);
1389                 node_set_online(i);
1390         }
1391
1392         err = 0;
1393 out:
1394         mdesc_release(md);
1395         return err;
1396 }
1397
1398 static int __init numa_parse_jbus(void)
1399 {
1400         unsigned long cpu, index;
1401
1402         /* NUMA node id is encoded in bits 36 and higher, and there is
1403          * a 1-to-1 mapping from CPU ID to NUMA node ID.
1404          */
1405         index = 0;
1406         for_each_present_cpu(cpu) {
1407                 numa_cpu_lookup_table[cpu] = index;
1408                 cpumask_copy(&numa_cpumask_lookup_table[index], cpumask_of(cpu));
1409                 node_masks[index].mask = ~((1UL << 36UL) - 1UL);
1410                 node_masks[index].val = cpu << 36UL;
1411
1412                 index++;
1413         }
1414         num_node_masks = index;
1415
1416         add_node_ranges();
1417
1418         for (index = 0; index < num_node_masks; index++) {
1419                 allocate_node_data(index);
1420                 node_set_online(index);
1421         }
1422
1423         return 0;
1424 }
1425
1426 static int __init numa_parse_sun4u(void)
1427 {
1428         if (tlb_type == cheetah || tlb_type == cheetah_plus) {
1429                 unsigned long ver;
1430
1431                 __asm__ ("rdpr %%ver, %0" : "=r" (ver));
1432                 if ((ver >> 32UL) == __JALAPENO_ID ||
1433                     (ver >> 32UL) == __SERRANO_ID)
1434                         return numa_parse_jbus();
1435         }
1436         return -1;
1437 }
1438
1439 static int __init bootmem_init_numa(void)
1440 {
1441         int i, j;
1442         int err = -1;
1443
1444         numadbg("bootmem_init_numa()\n");
1445
1446         /* Some sane defaults for numa latency values */
1447         for (i = 0; i < MAX_NUMNODES; i++) {
1448                 for (j = 0; j < MAX_NUMNODES; j++)
1449                         numa_latency[i][j] = (i == j) ?
1450                                 LOCAL_DISTANCE : REMOTE_DISTANCE;
1451         }
1452
1453         if (numa_enabled) {
1454                 if (tlb_type == hypervisor)
1455                         err = numa_parse_mdesc();
1456                 else
1457                         err = numa_parse_sun4u();
1458         }
1459         return err;
1460 }
1461
1462 #else
1463
1464 static int bootmem_init_numa(void)
1465 {
1466         return -1;
1467 }
1468
1469 #endif
1470
1471 static void __init bootmem_init_nonnuma(void)
1472 {
1473         unsigned long top_of_ram = memblock_end_of_DRAM();
1474         unsigned long total_ram = memblock_phys_mem_size();
1475
1476         numadbg("bootmem_init_nonnuma()\n");
1477
1478         printk(KERN_INFO "Top of RAM: 0x%lx, Total RAM: 0x%lx\n",
1479                top_of_ram, total_ram);
1480         printk(KERN_INFO "Memory hole size: %ldMB\n",
1481                (top_of_ram - total_ram) >> 20);
1482
1483         init_node_masks_nonnuma();
1484         memblock_set_node(0, (phys_addr_t)ULLONG_MAX, &memblock.memory, 0);
1485         allocate_node_data(0);
1486         node_set_online(0);
1487 }
1488
1489 static unsigned long __init bootmem_init(unsigned long phys_base)
1490 {
1491         unsigned long end_pfn;
1492
1493         end_pfn = memblock_end_of_DRAM() >> PAGE_SHIFT;
1494         max_pfn = max_low_pfn = end_pfn;
1495         min_low_pfn = (phys_base >> PAGE_SHIFT);
1496
1497         if (bootmem_init_numa() < 0)
1498                 bootmem_init_nonnuma();
1499
1500         /* Dump memblock with node info. */
1501         memblock_dump_all();
1502
1503         /* XXX cpu notifier XXX */
1504
1505         sparse_memory_present_with_active_regions(MAX_NUMNODES);
1506         sparse_init();
1507
1508         return end_pfn;
1509 }
1510
1511 static struct linux_prom64_registers pall[MAX_BANKS] __initdata;
1512 static int pall_ents __initdata;
1513
1514 static unsigned long max_phys_bits = 40;
1515
1516 bool kern_addr_valid(unsigned long addr)
1517 {
1518         pgd_t *pgd;
1519         pud_t *pud;
1520         pmd_t *pmd;
1521         pte_t *pte;
1522
1523         if ((long)addr < 0L) {
1524                 unsigned long pa = __pa(addr);
1525
1526                 if ((pa >> max_phys_bits) != 0UL)
1527                         return false;
1528
1529                 return pfn_valid(pa >> PAGE_SHIFT);
1530         }
1531
1532         if (addr >= (unsigned long) KERNBASE &&
1533             addr < (unsigned long)&_end)
1534                 return true;
1535
1536         pgd = pgd_offset_k(addr);
1537         if (pgd_none(*pgd))
1538                 return 0;
1539
1540         pud = pud_offset(pgd, addr);
1541         if (pud_none(*pud))
1542                 return 0;
1543
1544         if (pud_large(*pud))
1545                 return pfn_valid(pud_pfn(*pud));
1546
1547         pmd = pmd_offset(pud, addr);
1548         if (pmd_none(*pmd))
1549                 return 0;
1550
1551         if (pmd_large(*pmd))
1552                 return pfn_valid(pmd_pfn(*pmd));
1553
1554         pte = pte_offset_kernel(pmd, addr);
1555         if (pte_none(*pte))
1556                 return 0;
1557
1558         return pfn_valid(pte_pfn(*pte));
1559 }
1560 EXPORT_SYMBOL(kern_addr_valid);
1561
1562 static unsigned long __ref kernel_map_hugepud(unsigned long vstart,
1563                                               unsigned long vend,
1564                                               pud_t *pud)
1565 {
1566         const unsigned long mask16gb = (1UL << 34) - 1UL;
1567         u64 pte_val = vstart;
1568
1569         /* Each PUD is 8GB */
1570         if ((vstart & mask16gb) ||
1571             (vend - vstart <= mask16gb)) {
1572                 pte_val ^= kern_linear_pte_xor[2];
1573                 pud_val(*pud) = pte_val | _PAGE_PUD_HUGE;
1574
1575                 return vstart + PUD_SIZE;
1576         }
1577
1578         pte_val ^= kern_linear_pte_xor[3];
1579         pte_val |= _PAGE_PUD_HUGE;
1580
1581         vend = vstart + mask16gb + 1UL;
1582         while (vstart < vend) {
1583                 pud_val(*pud) = pte_val;
1584
1585                 pte_val += PUD_SIZE;
1586                 vstart += PUD_SIZE;
1587                 pud++;
1588         }
1589         return vstart;
1590 }
1591
1592 static bool kernel_can_map_hugepud(unsigned long vstart, unsigned long vend,
1593                                    bool guard)
1594 {
1595         if (guard && !(vstart & ~PUD_MASK) && (vend - vstart) >= PUD_SIZE)
1596                 return true;
1597
1598         return false;
1599 }
1600
1601 static unsigned long __ref kernel_map_hugepmd(unsigned long vstart,
1602                                               unsigned long vend,
1603                                               pmd_t *pmd)
1604 {
1605         const unsigned long mask256mb = (1UL << 28) - 1UL;
1606         const unsigned long mask2gb = (1UL << 31) - 1UL;
1607         u64 pte_val = vstart;
1608
1609         /* Each PMD is 8MB */
1610         if ((vstart & mask256mb) ||
1611             (vend - vstart <= mask256mb)) {
1612                 pte_val ^= kern_linear_pte_xor[0];
1613                 pmd_val(*pmd) = pte_val | _PAGE_PMD_HUGE;
1614
1615                 return vstart + PMD_SIZE;
1616         }
1617
1618         if ((vstart & mask2gb) ||
1619             (vend - vstart <= mask2gb)) {
1620                 pte_val ^= kern_linear_pte_xor[1];
1621                 pte_val |= _PAGE_PMD_HUGE;
1622                 vend = vstart + mask256mb + 1UL;
1623         } else {
1624                 pte_val ^= kern_linear_pte_xor[2];
1625                 pte_val |= _PAGE_PMD_HUGE;
1626                 vend = vstart + mask2gb + 1UL;
1627         }
1628
1629         while (vstart < vend) {
1630                 pmd_val(*pmd) = pte_val;
1631
1632                 pte_val += PMD_SIZE;
1633                 vstart += PMD_SIZE;
1634                 pmd++;
1635         }
1636
1637         return vstart;
1638 }
1639
1640 static bool kernel_can_map_hugepmd(unsigned long vstart, unsigned long vend,
1641                                    bool guard)
1642 {
1643         if (guard && !(vstart & ~PMD_MASK) && (vend - vstart) >= PMD_SIZE)
1644                 return true;
1645
1646         return false;
1647 }
1648
1649 static unsigned long __ref kernel_map_range(unsigned long pstart,
1650                                             unsigned long pend, pgprot_t prot,
1651                                             bool use_huge)
1652 {
1653         unsigned long vstart = PAGE_OFFSET + pstart;
1654         unsigned long vend = PAGE_OFFSET + pend;
1655         unsigned long alloc_bytes = 0UL;
1656
1657         if ((vstart & ~PAGE_MASK) || (vend & ~PAGE_MASK)) {
1658                 prom_printf("kernel_map: Unaligned physmem[%lx:%lx]\n",
1659                             vstart, vend);
1660                 prom_halt();
1661         }
1662
1663         while (vstart < vend) {
1664                 unsigned long this_end, paddr = __pa(vstart);
1665                 pgd_t *pgd = pgd_offset_k(vstart);
1666                 pud_t *pud;
1667                 pmd_t *pmd;
1668                 pte_t *pte;
1669
1670                 if (pgd_none(*pgd)) {
1671                         pud_t *new;
1672
1673                         new = __alloc_bootmem(PAGE_SIZE, PAGE_SIZE, PAGE_SIZE);
1674                         alloc_bytes += PAGE_SIZE;
1675                         pgd_populate(&init_mm, pgd, new);
1676                 }
1677                 pud = pud_offset(pgd, vstart);
1678                 if (pud_none(*pud)) {
1679                         pmd_t *new;
1680
1681                         if (kernel_can_map_hugepud(vstart, vend, use_huge)) {
1682                                 vstart = kernel_map_hugepud(vstart, vend, pud);
1683                                 continue;
1684                         }
1685                         new = __alloc_bootmem(PAGE_SIZE, PAGE_SIZE, PAGE_SIZE);
1686                         alloc_bytes += PAGE_SIZE;
1687                         pud_populate(&init_mm, pud, new);
1688                 }
1689
1690                 pmd = pmd_offset(pud, vstart);
1691                 if (pmd_none(*pmd)) {
1692                         pte_t *new;
1693
1694                         if (kernel_can_map_hugepmd(vstart, vend, use_huge)) {
1695                                 vstart = kernel_map_hugepmd(vstart, vend, pmd);
1696                                 continue;
1697                         }
1698                         new = __alloc_bootmem(PAGE_SIZE, PAGE_SIZE, PAGE_SIZE);
1699                         alloc_bytes += PAGE_SIZE;
1700                         pmd_populate_kernel(&init_mm, pmd, new);
1701                 }
1702
1703                 pte = pte_offset_kernel(pmd, vstart);
1704                 this_end = (vstart + PMD_SIZE) & PMD_MASK;
1705                 if (this_end > vend)
1706                         this_end = vend;
1707
1708                 while (vstart < this_end) {
1709                         pte_val(*pte) = (paddr | pgprot_val(prot));
1710
1711                         vstart += PAGE_SIZE;
1712                         paddr += PAGE_SIZE;
1713                         pte++;
1714                 }
1715         }
1716
1717         return alloc_bytes;
1718 }
1719
1720 static void __init flush_all_kernel_tsbs(void)
1721 {
1722         int i;
1723
1724         for (i = 0; i < KERNEL_TSB_NENTRIES; i++) {
1725                 struct tsb *ent = &swapper_tsb[i];
1726
1727                 ent->tag = (1UL << TSB_TAG_INVALID_BIT);
1728         }
1729 #ifndef CONFIG_DEBUG_PAGEALLOC
1730         for (i = 0; i < KERNEL_TSB4M_NENTRIES; i++) {
1731                 struct tsb *ent = &swapper_4m_tsb[i];
1732
1733                 ent->tag = (1UL << TSB_TAG_INVALID_BIT);
1734         }
1735 #endif
1736 }
1737
1738 extern unsigned int kvmap_linear_patch[1];
1739
1740 static void __init kernel_physical_mapping_init(void)
1741 {
1742         unsigned long i, mem_alloced = 0UL;
1743         bool use_huge = true;
1744
1745 #ifdef CONFIG_DEBUG_PAGEALLOC
1746         use_huge = false;
1747 #endif
1748         for (i = 0; i < pall_ents; i++) {
1749                 unsigned long phys_start, phys_end;
1750
1751                 phys_start = pall[i].phys_addr;
1752                 phys_end = phys_start + pall[i].reg_size;
1753
1754                 mem_alloced += kernel_map_range(phys_start, phys_end,
1755                                                 PAGE_KERNEL, use_huge);
1756         }
1757
1758         printk("Allocated %ld bytes for kernel page tables.\n",
1759                mem_alloced);
1760
1761         kvmap_linear_patch[0] = 0x01000000; /* nop */
1762         flushi(&kvmap_linear_patch[0]);
1763
1764         flush_all_kernel_tsbs();
1765
1766         __flush_tlb_all();
1767 }
1768
1769 #ifdef CONFIG_DEBUG_PAGEALLOC
1770 void __kernel_map_pages(struct page *page, int numpages, int enable)
1771 {
1772         unsigned long phys_start = page_to_pfn(page) << PAGE_SHIFT;
1773         unsigned long phys_end = phys_start + (numpages * PAGE_SIZE);
1774
1775         kernel_map_range(phys_start, phys_end,
1776                          (enable ? PAGE_KERNEL : __pgprot(0)), false);
1777
1778         flush_tsb_kernel_range(PAGE_OFFSET + phys_start,
1779                                PAGE_OFFSET + phys_end);
1780
1781         /* we should perform an IPI and flush all tlbs,
1782          * but that can deadlock->flush only current cpu.
1783          */
1784         __flush_tlb_kernel_range(PAGE_OFFSET + phys_start,
1785                                  PAGE_OFFSET + phys_end);
1786 }
1787 #endif
1788
1789 unsigned long __init find_ecache_flush_span(unsigned long size)
1790 {
1791         int i;
1792
1793         for (i = 0; i < pavail_ents; i++) {
1794                 if (pavail[i].reg_size >= size)
1795                         return pavail[i].phys_addr;
1796         }
1797
1798         return ~0UL;
1799 }
1800
1801 unsigned long PAGE_OFFSET;
1802 EXPORT_SYMBOL(PAGE_OFFSET);
1803
1804 unsigned long VMALLOC_END   = 0x0000010000000000UL;
1805 EXPORT_SYMBOL(VMALLOC_END);
1806
1807 unsigned long sparc64_va_hole_top =    0xfffff80000000000UL;
1808 unsigned long sparc64_va_hole_bottom = 0x0000080000000000UL;
1809
1810 static void __init setup_page_offset(void)
1811 {
1812         if (tlb_type == cheetah || tlb_type == cheetah_plus) {
1813                 /* Cheetah/Panther support a full 64-bit virtual
1814                  * address, so we can use all that our page tables
1815                  * support.
1816                  */
1817                 sparc64_va_hole_top =    0xfff0000000000000UL;
1818                 sparc64_va_hole_bottom = 0x0010000000000000UL;
1819
1820                 max_phys_bits = 42;
1821         } else if (tlb_type == hypervisor) {
1822                 switch (sun4v_chip_type) {
1823                 case SUN4V_CHIP_NIAGARA1:
1824                 case SUN4V_CHIP_NIAGARA2:
1825                         /* T1 and T2 support 48-bit virtual addresses.  */
1826                         sparc64_va_hole_top =    0xffff800000000000UL;
1827                         sparc64_va_hole_bottom = 0x0000800000000000UL;
1828
1829                         max_phys_bits = 39;
1830                         break;
1831                 case SUN4V_CHIP_NIAGARA3:
1832                         /* T3 supports 48-bit virtual addresses.  */
1833                         sparc64_va_hole_top =    0xffff800000000000UL;
1834                         sparc64_va_hole_bottom = 0x0000800000000000UL;
1835
1836                         max_phys_bits = 43;
1837                         break;
1838                 case SUN4V_CHIP_NIAGARA4:
1839                 case SUN4V_CHIP_NIAGARA5:
1840                 case SUN4V_CHIP_SPARC64X:
1841                 case SUN4V_CHIP_SPARC_M6:
1842                         /* T4 and later support 52-bit virtual addresses.  */
1843                         sparc64_va_hole_top =    0xfff8000000000000UL;
1844                         sparc64_va_hole_bottom = 0x0008000000000000UL;
1845                         max_phys_bits = 47;
1846                         break;
1847                 case SUN4V_CHIP_SPARC_M7:
1848                 default:
1849                         /* M7 and later support 52-bit virtual addresses.  */
1850                         sparc64_va_hole_top =    0xfff8000000000000UL;
1851                         sparc64_va_hole_bottom = 0x0008000000000000UL;
1852                         max_phys_bits = 49;
1853                         break;
1854                 }
1855         }
1856
1857         if (max_phys_bits > MAX_PHYS_ADDRESS_BITS) {
1858                 prom_printf("MAX_PHYS_ADDRESS_BITS is too small, need %lu\n",
1859                             max_phys_bits);
1860                 prom_halt();
1861         }
1862
1863         PAGE_OFFSET = sparc64_va_hole_top;
1864         VMALLOC_END = ((sparc64_va_hole_bottom >> 1) +
1865                        (sparc64_va_hole_bottom >> 2));
1866
1867         pr_info("MM: PAGE_OFFSET is 0x%016lx (max_phys_bits == %lu)\n",
1868                 PAGE_OFFSET, max_phys_bits);
1869         pr_info("MM: VMALLOC [0x%016lx --> 0x%016lx]\n",
1870                 VMALLOC_START, VMALLOC_END);
1871         pr_info("MM: VMEMMAP [0x%016lx --> 0x%016lx]\n",
1872                 VMEMMAP_BASE, VMEMMAP_BASE << 1);
1873 }
1874
1875 static void __init tsb_phys_patch(void)
1876 {
1877         struct tsb_ldquad_phys_patch_entry *pquad;
1878         struct tsb_phys_patch_entry *p;
1879
1880         pquad = &__tsb_ldquad_phys_patch;
1881         while (pquad < &__tsb_ldquad_phys_patch_end) {
1882                 unsigned long addr = pquad->addr;
1883
1884                 if (tlb_type == hypervisor)
1885                         *(unsigned int *) addr = pquad->sun4v_insn;
1886                 else
1887                         *(unsigned int *) addr = pquad->sun4u_insn;
1888                 wmb();
1889                 __asm__ __volatile__("flush     %0"
1890                                      : /* no outputs */
1891                                      : "r" (addr));
1892
1893                 pquad++;
1894         }
1895
1896         p = &__tsb_phys_patch;
1897         while (p < &__tsb_phys_patch_end) {
1898                 unsigned long addr = p->addr;
1899
1900                 *(unsigned int *) addr = p->insn;
1901                 wmb();
1902                 __asm__ __volatile__("flush     %0"
1903                                      : /* no outputs */
1904                                      : "r" (addr));
1905
1906                 p++;
1907         }
1908 }
1909
1910 /* Don't mark as init, we give this to the Hypervisor.  */
1911 #ifndef CONFIG_DEBUG_PAGEALLOC
1912 #define NUM_KTSB_DESCR  2
1913 #else
1914 #define NUM_KTSB_DESCR  1
1915 #endif
1916 static struct hv_tsb_descr ktsb_descr[NUM_KTSB_DESCR];
1917
1918 /* The swapper TSBs are loaded with a base sequence of:
1919  *
1920  *      sethi   %uhi(SYMBOL), REG1
1921  *      sethi   %hi(SYMBOL), REG2
1922  *      or      REG1, %ulo(SYMBOL), REG1
1923  *      or      REG2, %lo(SYMBOL), REG2
1924  *      sllx    REG1, 32, REG1
1925  *      or      REG1, REG2, REG1
1926  *
1927  * When we use physical addressing for the TSB accesses, we patch the
1928  * first four instructions in the above sequence.
1929  */
1930
1931 static void patch_one_ktsb_phys(unsigned int *start, unsigned int *end, unsigned long pa)
1932 {
1933         unsigned long high_bits, low_bits;
1934
1935         high_bits = (pa >> 32) & 0xffffffff;
1936         low_bits = (pa >> 0) & 0xffffffff;
1937
1938         while (start < end) {
1939                 unsigned int *ia = (unsigned int *)(unsigned long)*start;
1940
1941                 ia[0] = (ia[0] & ~0x3fffff) | (high_bits >> 10);
1942                 __asm__ __volatile__("flush     %0" : : "r" (ia));
1943
1944                 ia[1] = (ia[1] & ~0x3fffff) | (low_bits >> 10);
1945                 __asm__ __volatile__("flush     %0" : : "r" (ia + 1));
1946
1947                 ia[2] = (ia[2] & ~0x1fff) | (high_bits & 0x3ff);
1948                 __asm__ __volatile__("flush     %0" : : "r" (ia + 2));
1949
1950                 ia[3] = (ia[3] & ~0x1fff) | (low_bits & 0x3ff);
1951                 __asm__ __volatile__("flush     %0" : : "r" (ia + 3));
1952
1953                 start++;
1954         }
1955 }
1956
1957 static void ktsb_phys_patch(void)
1958 {
1959         extern unsigned int __swapper_tsb_phys_patch;
1960         extern unsigned int __swapper_tsb_phys_patch_end;
1961         unsigned long ktsb_pa;
1962
1963         ktsb_pa = kern_base + ((unsigned long)&swapper_tsb[0] - KERNBASE);
1964         patch_one_ktsb_phys(&__swapper_tsb_phys_patch,
1965                             &__swapper_tsb_phys_patch_end, ktsb_pa);
1966 #ifndef CONFIG_DEBUG_PAGEALLOC
1967         {
1968         extern unsigned int __swapper_4m_tsb_phys_patch;
1969         extern unsigned int __swapper_4m_tsb_phys_patch_end;
1970         ktsb_pa = (kern_base +
1971                    ((unsigned long)&swapper_4m_tsb[0] - KERNBASE));
1972         patch_one_ktsb_phys(&__swapper_4m_tsb_phys_patch,
1973                             &__swapper_4m_tsb_phys_patch_end, ktsb_pa);
1974         }
1975 #endif
1976 }
1977
1978 static void __init sun4v_ktsb_init(void)
1979 {
1980         unsigned long ktsb_pa;
1981
1982         /* First KTSB for PAGE_SIZE mappings.  */
1983         ktsb_pa = kern_base + ((unsigned long)&swapper_tsb[0] - KERNBASE);
1984
1985         switch (PAGE_SIZE) {
1986         case 8 * 1024:
1987         default:
1988                 ktsb_descr[0].pgsz_idx = HV_PGSZ_IDX_8K;
1989                 ktsb_descr[0].pgsz_mask = HV_PGSZ_MASK_8K;
1990                 break;
1991
1992         case 64 * 1024:
1993                 ktsb_descr[0].pgsz_idx = HV_PGSZ_IDX_64K;
1994                 ktsb_descr[0].pgsz_mask = HV_PGSZ_MASK_64K;
1995                 break;
1996
1997         case 512 * 1024:
1998                 ktsb_descr[0].pgsz_idx = HV_PGSZ_IDX_512K;
1999                 ktsb_descr[0].pgsz_mask = HV_PGSZ_MASK_512K;
2000                 break;
2001
2002         case 4 * 1024 * 1024:
2003                 ktsb_descr[0].pgsz_idx = HV_PGSZ_IDX_4MB;
2004                 ktsb_descr[0].pgsz_mask = HV_PGSZ_MASK_4MB;
2005                 break;
2006         }
2007
2008         ktsb_descr[0].assoc = 1;
2009         ktsb_descr[0].num_ttes = KERNEL_TSB_NENTRIES;
2010         ktsb_descr[0].ctx_idx = 0;
2011         ktsb_descr[0].tsb_base = ktsb_pa;
2012         ktsb_descr[0].resv = 0;
2013
2014 #ifndef CONFIG_DEBUG_PAGEALLOC
2015         /* Second KTSB for 4MB/256MB/2GB/16GB mappings.  */
2016         ktsb_pa = (kern_base +
2017                    ((unsigned long)&swapper_4m_tsb[0] - KERNBASE));
2018
2019         ktsb_descr[1].pgsz_idx = HV_PGSZ_IDX_4MB;
2020         ktsb_descr[1].pgsz_mask = ((HV_PGSZ_MASK_4MB |
2021                                     HV_PGSZ_MASK_256MB |
2022                                     HV_PGSZ_MASK_2GB |
2023                                     HV_PGSZ_MASK_16GB) &
2024                                    cpu_pgsz_mask);
2025         ktsb_descr[1].assoc = 1;
2026         ktsb_descr[1].num_ttes = KERNEL_TSB4M_NENTRIES;
2027         ktsb_descr[1].ctx_idx = 0;
2028         ktsb_descr[1].tsb_base = ktsb_pa;
2029         ktsb_descr[1].resv = 0;
2030 #endif
2031 }
2032
2033 void sun4v_ktsb_register(void)
2034 {
2035         unsigned long pa, ret;
2036
2037         pa = kern_base + ((unsigned long)&ktsb_descr[0] - KERNBASE);
2038
2039         ret = sun4v_mmu_tsb_ctx0(NUM_KTSB_DESCR, pa);
2040         if (ret != 0) {
2041                 prom_printf("hypervisor_mmu_tsb_ctx0[%lx]: "
2042                             "errors with %lx\n", pa, ret);
2043                 prom_halt();
2044         }
2045 }
2046
2047 static void __init sun4u_linear_pte_xor_finalize(void)
2048 {
2049 #ifndef CONFIG_DEBUG_PAGEALLOC
2050         /* This is where we would add Panther support for
2051          * 32MB and 256MB pages.
2052          */
2053 #endif
2054 }
2055
2056 static void __init sun4v_linear_pte_xor_finalize(void)
2057 {
2058         unsigned long pagecv_flag;
2059
2060         /* Bit 9 of TTE is no longer CV bit on M7 processor and it instead
2061          * enables MCD error. Do not set bit 9 on M7 processor.
2062          */
2063         switch (sun4v_chip_type) {
2064         case SUN4V_CHIP_SPARC_M7:
2065                 pagecv_flag = 0x00;
2066                 break;
2067         default:
2068                 pagecv_flag = _PAGE_CV_4V;
2069                 break;
2070         }
2071 #ifndef CONFIG_DEBUG_PAGEALLOC
2072         if (cpu_pgsz_mask & HV_PGSZ_MASK_256MB) {
2073                 kern_linear_pte_xor[1] = (_PAGE_VALID | _PAGE_SZ256MB_4V) ^
2074                         PAGE_OFFSET;
2075                 kern_linear_pte_xor[1] |= (_PAGE_CP_4V | pagecv_flag |
2076                                            _PAGE_P_4V | _PAGE_W_4V);
2077         } else {
2078                 kern_linear_pte_xor[1] = kern_linear_pte_xor[0];
2079         }
2080
2081         if (cpu_pgsz_mask & HV_PGSZ_MASK_2GB) {
2082                 kern_linear_pte_xor[2] = (_PAGE_VALID | _PAGE_SZ2GB_4V) ^
2083                         PAGE_OFFSET;
2084                 kern_linear_pte_xor[2] |= (_PAGE_CP_4V | pagecv_flag |
2085                                            _PAGE_P_4V | _PAGE_W_4V);
2086         } else {
2087                 kern_linear_pte_xor[2] = kern_linear_pte_xor[1];
2088         }
2089
2090         if (cpu_pgsz_mask & HV_PGSZ_MASK_16GB) {
2091                 kern_linear_pte_xor[3] = (_PAGE_VALID | _PAGE_SZ16GB_4V) ^
2092                         PAGE_OFFSET;
2093                 kern_linear_pte_xor[3] |= (_PAGE_CP_4V | pagecv_flag |
2094                                            _PAGE_P_4V | _PAGE_W_4V);
2095         } else {
2096                 kern_linear_pte_xor[3] = kern_linear_pte_xor[2];
2097         }
2098 #endif
2099 }
2100
2101 /* paging_init() sets up the page tables */
2102
2103 static unsigned long last_valid_pfn;
2104
2105 static void sun4u_pgprot_init(void);
2106 static void sun4v_pgprot_init(void);
2107
2108 static phys_addr_t __init available_memory(void)
2109 {
2110         phys_addr_t available = 0ULL;
2111         phys_addr_t pa_start, pa_end;
2112         u64 i;
2113
2114         for_each_free_mem_range(i, NUMA_NO_NODE, MEMBLOCK_NONE, &pa_start,
2115                                 &pa_end, NULL)
2116                 available = available + (pa_end  - pa_start);
2117
2118         return available;
2119 }
2120
2121 #define _PAGE_CACHE_4U  (_PAGE_CP_4U | _PAGE_CV_4U)
2122 #define _PAGE_CACHE_4V  (_PAGE_CP_4V | _PAGE_CV_4V)
2123 #define __DIRTY_BITS_4U  (_PAGE_MODIFIED_4U | _PAGE_WRITE_4U | _PAGE_W_4U)
2124 #define __DIRTY_BITS_4V  (_PAGE_MODIFIED_4V | _PAGE_WRITE_4V | _PAGE_W_4V)
2125 #define __ACCESS_BITS_4U (_PAGE_ACCESSED_4U | _PAGE_READ_4U | _PAGE_R)
2126 #define __ACCESS_BITS_4V (_PAGE_ACCESSED_4V | _PAGE_READ_4V | _PAGE_R)
2127
2128 /* We need to exclude reserved regions. This exclusion will include
2129  * vmlinux and initrd. To be more precise the initrd size could be used to
2130  * compute a new lower limit because it is freed later during initialization.
2131  */
2132 static void __init reduce_memory(phys_addr_t limit_ram)
2133 {
2134         phys_addr_t avail_ram = available_memory();
2135         phys_addr_t pa_start, pa_end;
2136         u64 i;
2137
2138         if (limit_ram >= avail_ram)
2139                 return;
2140
2141         for_each_free_mem_range(i, NUMA_NO_NODE, MEMBLOCK_NONE, &pa_start,
2142                                 &pa_end, NULL) {
2143                 phys_addr_t region_size = pa_end - pa_start;
2144                 phys_addr_t clip_start = pa_start;
2145
2146                 avail_ram = avail_ram - region_size;
2147                 /* Are we consuming too much? */
2148                 if (avail_ram < limit_ram) {
2149                         phys_addr_t give_back = limit_ram - avail_ram;
2150
2151                         region_size = region_size - give_back;
2152                         clip_start = clip_start + give_back;
2153                 }
2154
2155                 memblock_remove(clip_start, region_size);
2156
2157                 if (avail_ram <= limit_ram)
2158                         break;
2159                 i = 0UL;
2160         }
2161 }
2162
2163 void __init paging_init(void)
2164 {
2165         unsigned long end_pfn, shift, phys_base;
2166         unsigned long real_end, i;
2167         int node;
2168
2169         setup_page_offset();
2170
2171         /* These build time checkes make sure that the dcache_dirty_cpu()
2172          * page->flags usage will work.
2173          *
2174          * When a page gets marked as dcache-dirty, we store the
2175          * cpu number starting at bit 32 in the page->flags.  Also,
2176          * functions like clear_dcache_dirty_cpu use the cpu mask
2177          * in 13-bit signed-immediate instruction fields.
2178          */
2179
2180         /*
2181          * Page flags must not reach into upper 32 bits that are used
2182          * for the cpu number
2183          */
2184         BUILD_BUG_ON(NR_PAGEFLAGS > 32);
2185
2186         /*
2187          * The bit fields placed in the high range must not reach below
2188          * the 32 bit boundary. Otherwise we cannot place the cpu field
2189          * at the 32 bit boundary.
2190          */
2191         BUILD_BUG_ON(SECTIONS_WIDTH + NODES_WIDTH + ZONES_WIDTH +
2192                 ilog2(roundup_pow_of_two(NR_CPUS)) > 32);
2193
2194         BUILD_BUG_ON(NR_CPUS > 4096);
2195
2196         kern_base = (prom_boot_mapping_phys_low >> ILOG2_4MB) << ILOG2_4MB;
2197         kern_size = (unsigned long)&_end - (unsigned long)KERNBASE;
2198
2199         /* Invalidate both kernel TSBs.  */
2200         memset(swapper_tsb, 0x40, sizeof(swapper_tsb));
2201 #ifndef CONFIG_DEBUG_PAGEALLOC
2202         memset(swapper_4m_tsb, 0x40, sizeof(swapper_4m_tsb));
2203 #endif
2204
2205         /* TTE.cv bit on sparc v9 occupies the same position as TTE.mcde
2206          * bit on M7 processor. This is a conflicting usage of the same
2207          * bit. Enabling TTE.cv on M7 would turn on Memory Corruption
2208          * Detection error on all pages and this will lead to problems
2209          * later. Kernel does not run with MCD enabled and hence rest
2210          * of the required steps to fully configure memory corruption
2211          * detection are not taken. We need to ensure TTE.mcde is not
2212          * set on M7 processor. Compute the value of cacheability
2213          * flag for use later taking this into consideration.
2214          */
2215         switch (sun4v_chip_type) {
2216         case SUN4V_CHIP_SPARC_M7:
2217                 page_cache4v_flag = _PAGE_CP_4V;
2218                 break;
2219         default:
2220                 page_cache4v_flag = _PAGE_CACHE_4V;
2221                 break;
2222         }
2223
2224         if (tlb_type == hypervisor)
2225                 sun4v_pgprot_init();
2226         else
2227                 sun4u_pgprot_init();
2228
2229         if (tlb_type == cheetah_plus ||
2230             tlb_type == hypervisor) {
2231                 tsb_phys_patch();
2232                 ktsb_phys_patch();
2233         }
2234
2235         if (tlb_type == hypervisor)
2236                 sun4v_patch_tlb_handlers();
2237
2238         /* Find available physical memory...
2239          *
2240          * Read it twice in order to work around a bug in openfirmware.
2241          * The call to grab this table itself can cause openfirmware to
2242          * allocate memory, which in turn can take away some space from
2243          * the list of available memory.  Reading it twice makes sure
2244          * we really do get the final value.
2245          */
2246         read_obp_translations();
2247         read_obp_memory("reg", &pall[0], &pall_ents);
2248         read_obp_memory("available", &pavail[0], &pavail_ents);
2249         read_obp_memory("available", &pavail[0], &pavail_ents);
2250
2251         phys_base = 0xffffffffffffffffUL;
2252         for (i = 0; i < pavail_ents; i++) {
2253                 phys_base = min(phys_base, pavail[i].phys_addr);
2254                 memblock_add(pavail[i].phys_addr, pavail[i].reg_size);
2255         }
2256
2257         memblock_reserve(kern_base, kern_size);
2258
2259         find_ramdisk(phys_base);
2260
2261         if (cmdline_memory_size)
2262                 reduce_memory(cmdline_memory_size);
2263
2264         memblock_allow_resize();
2265         memblock_dump_all();
2266
2267         set_bit(0, mmu_context_bmap);
2268
2269         shift = kern_base + PAGE_OFFSET - ((unsigned long)KERNBASE);
2270
2271         real_end = (unsigned long)_end;
2272         num_kernel_image_mappings = DIV_ROUND_UP(real_end - KERNBASE, 1 << ILOG2_4MB);
2273         printk("Kernel: Using %d locked TLB entries for main kernel image.\n",
2274                num_kernel_image_mappings);
2275
2276         /* Set kernel pgd to upper alias so physical page computations
2277          * work.
2278          */
2279         init_mm.pgd += ((shift) / (sizeof(pgd_t)));
2280         
2281         memset(swapper_pg_dir, 0, sizeof(swapper_pg_dir));
2282
2283         inherit_prom_mappings();
2284         
2285         /* Ok, we can use our TLB miss and window trap handlers safely.  */
2286         setup_tba();
2287
2288         __flush_tlb_all();
2289
2290         prom_build_devicetree();
2291         of_populate_present_mask();
2292 #ifndef CONFIG_SMP
2293         of_fill_in_cpu_data();
2294 #endif
2295
2296         if (tlb_type == hypervisor) {
2297                 sun4v_mdesc_init();
2298                 mdesc_populate_present_mask(cpu_all_mask);
2299 #ifndef CONFIG_SMP
2300                 mdesc_fill_in_cpu_data(cpu_all_mask);
2301 #endif
2302                 mdesc_get_page_sizes(cpu_all_mask, &cpu_pgsz_mask);
2303
2304                 sun4v_linear_pte_xor_finalize();
2305
2306                 sun4v_ktsb_init();
2307                 sun4v_ktsb_register();
2308         } else {
2309                 unsigned long impl, ver;
2310
2311                 cpu_pgsz_mask = (HV_PGSZ_MASK_8K | HV_PGSZ_MASK_64K |
2312                                  HV_PGSZ_MASK_512K | HV_PGSZ_MASK_4MB);
2313
2314                 __asm__ __volatile__("rdpr %%ver, %0" : "=r" (ver));
2315                 impl = ((ver >> 32) & 0xffff);
2316                 if (impl == PANTHER_IMPL)
2317                         cpu_pgsz_mask |= (HV_PGSZ_MASK_32MB |
2318                                           HV_PGSZ_MASK_256MB);
2319
2320                 sun4u_linear_pte_xor_finalize();
2321         }
2322
2323         /* Flush the TLBs and the 4M TSB so that the updated linear
2324          * pte XOR settings are realized for all mappings.
2325          */
2326         __flush_tlb_all();
2327 #ifndef CONFIG_DEBUG_PAGEALLOC
2328         memset(swapper_4m_tsb, 0x40, sizeof(swapper_4m_tsb));
2329 #endif
2330         __flush_tlb_all();
2331
2332         /* Setup bootmem... */
2333         last_valid_pfn = end_pfn = bootmem_init(phys_base);
2334
2335         /* Once the OF device tree and MDESC have been setup, we know
2336          * the list of possible cpus.  Therefore we can allocate the
2337          * IRQ stacks.
2338          */
2339         for_each_possible_cpu(i) {
2340                 node = cpu_to_node(i);
2341
2342                 softirq_stack[i] = __alloc_bootmem_node(NODE_DATA(node),
2343                                                         THREAD_SIZE,
2344                                                         THREAD_SIZE, 0);
2345                 hardirq_stack[i] = __alloc_bootmem_node(NODE_DATA(node),
2346                                                         THREAD_SIZE,
2347                                                         THREAD_SIZE, 0);
2348         }
2349
2350         kernel_physical_mapping_init();
2351
2352         {
2353                 unsigned long max_zone_pfns[MAX_NR_ZONES];
2354
2355                 memset(max_zone_pfns, 0, sizeof(max_zone_pfns));
2356
2357                 max_zone_pfns[ZONE_NORMAL] = end_pfn;
2358
2359                 free_area_init_nodes(max_zone_pfns);
2360         }
2361
2362         printk("Booting Linux...\n");
2363 }
2364
2365 int page_in_phys_avail(unsigned long paddr)
2366 {
2367         int i;
2368
2369         paddr &= PAGE_MASK;
2370
2371         for (i = 0; i < pavail_ents; i++) {
2372                 unsigned long start, end;
2373
2374                 start = pavail[i].phys_addr;
2375                 end = start + pavail[i].reg_size;
2376
2377                 if (paddr >= start && paddr < end)
2378                         return 1;
2379         }
2380         if (paddr >= kern_base && paddr < (kern_base + kern_size))
2381                 return 1;
2382 #ifdef CONFIG_BLK_DEV_INITRD
2383         if (paddr >= __pa(initrd_start) &&
2384             paddr < __pa(PAGE_ALIGN(initrd_end)))
2385                 return 1;
2386 #endif
2387
2388         return 0;
2389 }
2390
2391 static void __init register_page_bootmem_info(void)
2392 {
2393 #ifdef CONFIG_NEED_MULTIPLE_NODES
2394         int i;
2395
2396         for_each_online_node(i)
2397                 if (NODE_DATA(i)->node_spanned_pages)
2398                         register_page_bootmem_info_node(NODE_DATA(i));
2399 #endif
2400 }
2401 void __init mem_init(void)
2402 {
2403         high_memory = __va(last_valid_pfn << PAGE_SHIFT);
2404
2405         free_all_bootmem();
2406
2407         /*
2408          * Must be done after boot memory is put on freelist, because here we
2409          * might set fields in deferred struct pages that have not yet been
2410          * initialized, and free_all_bootmem() initializes all the reserved
2411          * deferred pages for us.
2412          */
2413         register_page_bootmem_info();
2414
2415         /*
2416          * Set up the zero page, mark it reserved, so that page count
2417          * is not manipulated when freeing the page from user ptes.
2418          */
2419         mem_map_zero = alloc_pages(GFP_KERNEL|__GFP_ZERO, 0);
2420         if (mem_map_zero == NULL) {
2421                 prom_printf("paging_init: Cannot alloc zero page.\n");
2422                 prom_halt();
2423         }
2424         mark_page_reserved(mem_map_zero);
2425
2426         mem_init_print_info(NULL);
2427
2428         if (tlb_type == cheetah || tlb_type == cheetah_plus)
2429                 cheetah_ecache_flush_init();
2430 }
2431
2432 void free_initmem(void)
2433 {
2434         unsigned long addr, initend;
2435         int do_free = 1;
2436
2437         /* If the physical memory maps were trimmed by kernel command
2438          * line options, don't even try freeing this initmem stuff up.
2439          * The kernel image could have been in the trimmed out region
2440          * and if so the freeing below will free invalid page structs.
2441          */
2442         if (cmdline_memory_size)
2443                 do_free = 0;
2444
2445         /*
2446          * The init section is aligned to 8k in vmlinux.lds. Page align for >8k pagesizes.
2447          */
2448         addr = PAGE_ALIGN((unsigned long)(__init_begin));
2449         initend = (unsigned long)(__init_end) & PAGE_MASK;
2450         for (; addr < initend; addr += PAGE_SIZE) {
2451                 unsigned long page;
2452
2453                 page = (addr +
2454                         ((unsigned long) __va(kern_base)) -
2455                         ((unsigned long) KERNBASE));
2456                 memset((void *)addr, POISON_FREE_INITMEM, PAGE_SIZE);
2457
2458                 if (do_free)
2459                         free_reserved_page(virt_to_page(page));
2460         }
2461 }
2462
2463 #ifdef CONFIG_BLK_DEV_INITRD
2464 void free_initrd_mem(unsigned long start, unsigned long end)
2465 {
2466         free_reserved_area((void *)start, (void *)end, POISON_FREE_INITMEM,
2467                            "initrd");
2468 }
2469 #endif
2470
2471 pgprot_t PAGE_KERNEL __read_mostly;
2472 EXPORT_SYMBOL(PAGE_KERNEL);
2473
2474 pgprot_t PAGE_KERNEL_LOCKED __read_mostly;
2475 pgprot_t PAGE_COPY __read_mostly;
2476
2477 pgprot_t PAGE_SHARED __read_mostly;
2478 EXPORT_SYMBOL(PAGE_SHARED);
2479
2480 unsigned long pg_iobits __read_mostly;
2481
2482 unsigned long _PAGE_IE __read_mostly;
2483 EXPORT_SYMBOL(_PAGE_IE);
2484
2485 unsigned long _PAGE_E __read_mostly;
2486 EXPORT_SYMBOL(_PAGE_E);
2487
2488 unsigned long _PAGE_CACHE __read_mostly;
2489 EXPORT_SYMBOL(_PAGE_CACHE);
2490
2491 #ifdef CONFIG_SPARSEMEM_VMEMMAP
2492 int __meminit vmemmap_populate(unsigned long vstart, unsigned long vend,
2493                                int node)
2494 {
2495         unsigned long pte_base;
2496
2497         pte_base = (_PAGE_VALID | _PAGE_SZ4MB_4U |
2498                     _PAGE_CP_4U | _PAGE_CV_4U |
2499                     _PAGE_P_4U | _PAGE_W_4U);
2500         if (tlb_type == hypervisor)
2501                 pte_base = (_PAGE_VALID | _PAGE_SZ4MB_4V |
2502                             page_cache4v_flag | _PAGE_P_4V | _PAGE_W_4V);
2503
2504         pte_base |= _PAGE_PMD_HUGE;
2505
2506         vstart = vstart & PMD_MASK;
2507         vend = ALIGN(vend, PMD_SIZE);
2508         for (; vstart < vend; vstart += PMD_SIZE) {
2509                 pgd_t *pgd = pgd_offset_k(vstart);
2510                 unsigned long pte;
2511                 pud_t *pud;
2512                 pmd_t *pmd;
2513
2514                 if (pgd_none(*pgd)) {
2515                         pud_t *new = vmemmap_alloc_block(PAGE_SIZE, node);
2516
2517                         if (!new)
2518                                 return -ENOMEM;
2519                         pgd_populate(&init_mm, pgd, new);
2520                 }
2521
2522                 pud = pud_offset(pgd, vstart);
2523                 if (pud_none(*pud)) {
2524                         pmd_t *new = vmemmap_alloc_block(PAGE_SIZE, node);
2525
2526                         if (!new)
2527                                 return -ENOMEM;
2528                         pud_populate(&init_mm, pud, new);
2529                 }
2530
2531                 pmd = pmd_offset(pud, vstart);
2532
2533                 pte = pmd_val(*pmd);
2534                 if (!(pte & _PAGE_VALID)) {
2535                         void *block = vmemmap_alloc_block(PMD_SIZE, node);
2536
2537                         if (!block)
2538                                 return -ENOMEM;
2539
2540                         pmd_val(*pmd) = pte_base | __pa(block);
2541                 }
2542         }
2543
2544         return 0;
2545 }
2546
2547 void vmemmap_free(unsigned long start, unsigned long end)
2548 {
2549 }
2550 #endif /* CONFIG_SPARSEMEM_VMEMMAP */
2551
2552 static void prot_init_common(unsigned long page_none,
2553                              unsigned long page_shared,
2554                              unsigned long page_copy,
2555                              unsigned long page_readonly,
2556                              unsigned long page_exec_bit)
2557 {
2558         PAGE_COPY = __pgprot(page_copy);
2559         PAGE_SHARED = __pgprot(page_shared);
2560
2561         protection_map[0x0] = __pgprot(page_none);
2562         protection_map[0x1] = __pgprot(page_readonly & ~page_exec_bit);
2563         protection_map[0x2] = __pgprot(page_copy & ~page_exec_bit);
2564         protection_map[0x3] = __pgprot(page_copy & ~page_exec_bit);
2565         protection_map[0x4] = __pgprot(page_readonly);
2566         protection_map[0x5] = __pgprot(page_readonly);
2567         protection_map[0x6] = __pgprot(page_copy);
2568         protection_map[0x7] = __pgprot(page_copy);
2569         protection_map[0x8] = __pgprot(page_none);
2570         protection_map[0x9] = __pgprot(page_readonly & ~page_exec_bit);
2571         protection_map[0xa] = __pgprot(page_shared & ~page_exec_bit);
2572         protection_map[0xb] = __pgprot(page_shared & ~page_exec_bit);
2573         protection_map[0xc] = __pgprot(page_readonly);
2574         protection_map[0xd] = __pgprot(page_readonly);
2575         protection_map[0xe] = __pgprot(page_shared);
2576         protection_map[0xf] = __pgprot(page_shared);
2577 }
2578
2579 static void __init sun4u_pgprot_init(void)
2580 {
2581         unsigned long page_none, page_shared, page_copy, page_readonly;
2582         unsigned long page_exec_bit;
2583         int i;
2584
2585         PAGE_KERNEL = __pgprot (_PAGE_PRESENT_4U | _PAGE_VALID |
2586                                 _PAGE_CACHE_4U | _PAGE_P_4U |
2587                                 __ACCESS_BITS_4U | __DIRTY_BITS_4U |
2588                                 _PAGE_EXEC_4U);
2589         PAGE_KERNEL_LOCKED = __pgprot (_PAGE_PRESENT_4U | _PAGE_VALID |
2590                                        _PAGE_CACHE_4U | _PAGE_P_4U |
2591                                        __ACCESS_BITS_4U | __DIRTY_BITS_4U |
2592                                        _PAGE_EXEC_4U | _PAGE_L_4U);
2593
2594         _PAGE_IE = _PAGE_IE_4U;
2595         _PAGE_E = _PAGE_E_4U;
2596         _PAGE_CACHE = _PAGE_CACHE_4U;
2597
2598         pg_iobits = (_PAGE_VALID | _PAGE_PRESENT_4U | __DIRTY_BITS_4U |
2599                      __ACCESS_BITS_4U | _PAGE_E_4U);
2600
2601 #ifdef CONFIG_DEBUG_PAGEALLOC
2602         kern_linear_pte_xor[0] = _PAGE_VALID ^ PAGE_OFFSET;
2603 #else
2604         kern_linear_pte_xor[0] = (_PAGE_VALID | _PAGE_SZ4MB_4U) ^
2605                 PAGE_OFFSET;
2606 #endif
2607         kern_linear_pte_xor[0] |= (_PAGE_CP_4U | _PAGE_CV_4U |
2608                                    _PAGE_P_4U | _PAGE_W_4U);
2609
2610         for (i = 1; i < 4; i++)
2611                 kern_linear_pte_xor[i] = kern_linear_pte_xor[0];
2612
2613         _PAGE_ALL_SZ_BITS =  (_PAGE_SZ4MB_4U | _PAGE_SZ512K_4U |
2614                               _PAGE_SZ64K_4U | _PAGE_SZ8K_4U |
2615                               _PAGE_SZ32MB_4U | _PAGE_SZ256MB_4U);
2616
2617
2618         page_none = _PAGE_PRESENT_4U | _PAGE_ACCESSED_4U | _PAGE_CACHE_4U;
2619         page_shared = (_PAGE_VALID | _PAGE_PRESENT_4U | _PAGE_CACHE_4U |
2620                        __ACCESS_BITS_4U | _PAGE_WRITE_4U | _PAGE_EXEC_4U);
2621         page_copy   = (_PAGE_VALID | _PAGE_PRESENT_4U | _PAGE_CACHE_4U |
2622                        __ACCESS_BITS_4U | _PAGE_EXEC_4U);
2623         page_readonly   = (_PAGE_VALID | _PAGE_PRESENT_4U | _PAGE_CACHE_4U |
2624                            __ACCESS_BITS_4U | _PAGE_EXEC_4U);
2625
2626         page_exec_bit = _PAGE_EXEC_4U;
2627
2628         prot_init_common(page_none, page_shared, page_copy, page_readonly,
2629                          page_exec_bit);
2630 }
2631
2632 static void __init sun4v_pgprot_init(void)
2633 {
2634         unsigned long page_none, page_shared, page_copy, page_readonly;
2635         unsigned long page_exec_bit;
2636         int i;
2637
2638         PAGE_KERNEL = __pgprot (_PAGE_PRESENT_4V | _PAGE_VALID |
2639                                 page_cache4v_flag | _PAGE_P_4V |
2640                                 __ACCESS_BITS_4V | __DIRTY_BITS_4V |
2641                                 _PAGE_EXEC_4V);
2642         PAGE_KERNEL_LOCKED = PAGE_KERNEL;
2643
2644         _PAGE_IE = _PAGE_IE_4V;
2645         _PAGE_E = _PAGE_E_4V;
2646         _PAGE_CACHE = page_cache4v_flag;
2647
2648 #ifdef CONFIG_DEBUG_PAGEALLOC
2649         kern_linear_pte_xor[0] = _PAGE_VALID ^ PAGE_OFFSET;
2650 #else
2651         kern_linear_pte_xor[0] = (_PAGE_VALID | _PAGE_SZ4MB_4V) ^
2652                 PAGE_OFFSET;
2653 #endif
2654         kern_linear_pte_xor[0] |= (page_cache4v_flag | _PAGE_P_4V |
2655                                    _PAGE_W_4V);
2656
2657         for (i = 1; i < 4; i++)
2658                 kern_linear_pte_xor[i] = kern_linear_pte_xor[0];
2659
2660         pg_iobits = (_PAGE_VALID | _PAGE_PRESENT_4V | __DIRTY_BITS_4V |
2661                      __ACCESS_BITS_4V | _PAGE_E_4V);
2662
2663         _PAGE_ALL_SZ_BITS = (_PAGE_SZ16GB_4V | _PAGE_SZ2GB_4V |
2664                              _PAGE_SZ256MB_4V | _PAGE_SZ32MB_4V |
2665                              _PAGE_SZ4MB_4V | _PAGE_SZ512K_4V |
2666                              _PAGE_SZ64K_4V | _PAGE_SZ8K_4V);
2667
2668         page_none = _PAGE_PRESENT_4V | _PAGE_ACCESSED_4V | page_cache4v_flag;
2669         page_shared = (_PAGE_VALID | _PAGE_PRESENT_4V | page_cache4v_flag |
2670                        __ACCESS_BITS_4V | _PAGE_WRITE_4V | _PAGE_EXEC_4V);
2671         page_copy   = (_PAGE_VALID | _PAGE_PRESENT_4V | page_cache4v_flag |
2672                        __ACCESS_BITS_4V | _PAGE_EXEC_4V);
2673         page_readonly = (_PAGE_VALID | _PAGE_PRESENT_4V | page_cache4v_flag |
2674                          __ACCESS_BITS_4V | _PAGE_EXEC_4V);
2675
2676         page_exec_bit = _PAGE_EXEC_4V;
2677
2678         prot_init_common(page_none, page_shared, page_copy, page_readonly,
2679                          page_exec_bit);
2680 }
2681
2682 unsigned long pte_sz_bits(unsigned long sz)
2683 {
2684         if (tlb_type == hypervisor) {
2685                 switch (sz) {
2686                 case 8 * 1024:
2687                 default:
2688                         return _PAGE_SZ8K_4V;
2689                 case 64 * 1024:
2690                         return _PAGE_SZ64K_4V;
2691                 case 512 * 1024:
2692                         return _PAGE_SZ512K_4V;
2693                 case 4 * 1024 * 1024:
2694                         return _PAGE_SZ4MB_4V;
2695                 }
2696         } else {
2697                 switch (sz) {
2698                 case 8 * 1024:
2699                 default:
2700                         return _PAGE_SZ8K_4U;
2701                 case 64 * 1024:
2702                         return _PAGE_SZ64K_4U;
2703                 case 512 * 1024:
2704                         return _PAGE_SZ512K_4U;
2705                 case 4 * 1024 * 1024:
2706                         return _PAGE_SZ4MB_4U;
2707                 }
2708         }
2709 }
2710
2711 pte_t mk_pte_io(unsigned long page, pgprot_t prot, int space, unsigned long page_size)
2712 {
2713         pte_t pte;
2714
2715         pte_val(pte)  = page | pgprot_val(pgprot_noncached(prot));
2716         pte_val(pte) |= (((unsigned long)space) << 32);
2717         pte_val(pte) |= pte_sz_bits(page_size);
2718
2719         return pte;
2720 }
2721
2722 static unsigned long kern_large_tte(unsigned long paddr)
2723 {
2724         unsigned long val;
2725
2726         val = (_PAGE_VALID | _PAGE_SZ4MB_4U |
2727                _PAGE_CP_4U | _PAGE_CV_4U | _PAGE_P_4U |
2728                _PAGE_EXEC_4U | _PAGE_L_4U | _PAGE_W_4U);
2729         if (tlb_type == hypervisor)
2730                 val = (_PAGE_VALID | _PAGE_SZ4MB_4V |
2731                        page_cache4v_flag | _PAGE_P_4V |
2732                        _PAGE_EXEC_4V | _PAGE_W_4V);
2733
2734         return val | paddr;
2735 }
2736
2737 /* If not locked, zap it. */
2738 void __flush_tlb_all(void)
2739 {
2740         unsigned long pstate;
2741         int i;
2742
2743         __asm__ __volatile__("flushw\n\t"
2744                              "rdpr      %%pstate, %0\n\t"
2745                              "wrpr      %0, %1, %%pstate"
2746                              : "=r" (pstate)
2747                              : "i" (PSTATE_IE));
2748         if (tlb_type == hypervisor) {
2749                 sun4v_mmu_demap_all();
2750         } else if (tlb_type == spitfire) {
2751                 for (i = 0; i < 64; i++) {
2752                         /* Spitfire Errata #32 workaround */
2753                         /* NOTE: Always runs on spitfire, so no
2754                          *       cheetah+ page size encodings.
2755                          */
2756                         __asm__ __volatile__("stxa      %0, [%1] %2\n\t"
2757                                              "flush     %%g6"
2758                                              : /* No outputs */
2759                                              : "r" (0),
2760                                              "r" (PRIMARY_CONTEXT), "i" (ASI_DMMU));
2761
2762                         if (!(spitfire_get_dtlb_data(i) & _PAGE_L_4U)) {
2763                                 __asm__ __volatile__("stxa %%g0, [%0] %1\n\t"
2764                                                      "membar #Sync"
2765                                                      : /* no outputs */
2766                                                      : "r" (TLB_TAG_ACCESS), "i" (ASI_DMMU));
2767                                 spitfire_put_dtlb_data(i, 0x0UL);
2768                         }
2769
2770                         /* Spitfire Errata #32 workaround */
2771                         /* NOTE: Always runs on spitfire, so no
2772                          *       cheetah+ page size encodings.
2773                          */
2774                         __asm__ __volatile__("stxa      %0, [%1] %2\n\t"
2775                                              "flush     %%g6"
2776                                              : /* No outputs */
2777                                              : "r" (0),
2778                                              "r" (PRIMARY_CONTEXT), "i" (ASI_DMMU));
2779
2780                         if (!(spitfire_get_itlb_data(i) & _PAGE_L_4U)) {
2781                                 __asm__ __volatile__("stxa %%g0, [%0] %1\n\t"
2782                                                      "membar #Sync"
2783                                                      : /* no outputs */
2784                                                      : "r" (TLB_TAG_ACCESS), "i" (ASI_IMMU));
2785                                 spitfire_put_itlb_data(i, 0x0UL);
2786                         }
2787                 }
2788         } else if (tlb_type == cheetah || tlb_type == cheetah_plus) {
2789                 cheetah_flush_dtlb_all();
2790                 cheetah_flush_itlb_all();
2791         }
2792         __asm__ __volatile__("wrpr      %0, 0, %%pstate"
2793                              : : "r" (pstate));
2794 }
2795
2796 pte_t *pte_alloc_one_kernel(struct mm_struct *mm,
2797                             unsigned long address)
2798 {
2799         struct page *page = alloc_page(GFP_KERNEL | __GFP_NOTRACK |
2800                                        __GFP_REPEAT | __GFP_ZERO);
2801         pte_t *pte = NULL;
2802
2803         if (page)
2804                 pte = (pte_t *) page_address(page);
2805
2806         return pte;
2807 }
2808
2809 pgtable_t pte_alloc_one(struct mm_struct *mm,
2810                         unsigned long address)
2811 {
2812         struct page *page = alloc_page(GFP_KERNEL | __GFP_NOTRACK |
2813                                        __GFP_REPEAT | __GFP_ZERO);
2814         if (!page)
2815                 return NULL;
2816         if (!pgtable_page_ctor(page)) {
2817                 free_hot_cold_page(page, 0);
2818                 return NULL;
2819         }
2820         return (pte_t *) page_address(page);
2821 }
2822
2823 void pte_free_kernel(struct mm_struct *mm, pte_t *pte)
2824 {
2825         free_page((unsigned long)pte);
2826 }
2827
2828 static void __pte_free(pgtable_t pte)
2829 {
2830         struct page *page = virt_to_page(pte);
2831
2832         pgtable_page_dtor(page);
2833         __free_page(page);
2834 }
2835
2836 void pte_free(struct mm_struct *mm, pgtable_t pte)
2837 {
2838         __pte_free(pte);
2839 }
2840
2841 void pgtable_free(void *table, bool is_page)
2842 {
2843         if (is_page)
2844                 __pte_free(table);
2845         else
2846                 kmem_cache_free(pgtable_cache, table);
2847 }
2848
2849 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2850 void update_mmu_cache_pmd(struct vm_area_struct *vma, unsigned long addr,
2851                           pmd_t *pmd)
2852 {
2853         unsigned long pte, flags;
2854         struct mm_struct *mm;
2855         pmd_t entry = *pmd;
2856
2857         if (!pmd_large(entry) || !pmd_young(entry))
2858                 return;
2859
2860         pte = pmd_val(entry);
2861
2862         /* Don't insert a non-valid PMD into the TSB, we'll deadlock.  */
2863         if (!(pte & _PAGE_VALID))
2864                 return;
2865
2866         /* We are fabricating 8MB pages using 4MB real hw pages.  */
2867         pte |= (addr & (1UL << REAL_HPAGE_SHIFT));
2868
2869         mm = vma->vm_mm;
2870
2871         spin_lock_irqsave(&mm->context.lock, flags);
2872
2873         if (mm->context.tsb_block[MM_TSB_HUGE].tsb != NULL)
2874                 __update_mmu_tsb_insert(mm, MM_TSB_HUGE, REAL_HPAGE_SHIFT,
2875                                         addr, pte);
2876
2877         spin_unlock_irqrestore(&mm->context.lock, flags);
2878 }
2879 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
2880
2881 #if defined(CONFIG_HUGETLB_PAGE) || defined(CONFIG_TRANSPARENT_HUGEPAGE)
2882 static void context_reload(void *__data)
2883 {
2884         struct mm_struct *mm = __data;
2885
2886         if (mm == current->mm)
2887                 load_secondary_context(mm);
2888 }
2889
2890 void hugetlb_setup(struct pt_regs *regs)
2891 {
2892         struct mm_struct *mm = current->mm;
2893         struct tsb_config *tp;
2894
2895         if (faulthandler_disabled() || !mm) {
2896                 const struct exception_table_entry *entry;
2897
2898                 entry = search_exception_tables(regs->tpc);
2899                 if (entry) {
2900                         regs->tpc = entry->fixup;
2901                         regs->tnpc = regs->tpc + 4;
2902                         return;
2903                 }
2904                 pr_alert("Unexpected HugeTLB setup in atomic context.\n");
2905                 die_if_kernel("HugeTSB in atomic", regs);
2906         }
2907
2908         tp = &mm->context.tsb_block[MM_TSB_HUGE];
2909         if (likely(tp->tsb == NULL))
2910                 tsb_grow(mm, MM_TSB_HUGE, 0);
2911
2912         tsb_context_switch(mm);
2913         smp_tsb_sync(mm);
2914
2915         /* On UltraSPARC-III+ and later, configure the second half of
2916          * the Data-TLB for huge pages.
2917          */
2918         if (tlb_type == cheetah_plus) {
2919                 bool need_context_reload = false;
2920                 unsigned long ctx;
2921
2922                 spin_lock_irq(&ctx_alloc_lock);
2923                 ctx = mm->context.sparc64_ctx_val;
2924                 ctx &= ~CTX_PGSZ_MASK;
2925                 ctx |= CTX_PGSZ_BASE << CTX_PGSZ0_SHIFT;
2926                 ctx |= CTX_PGSZ_HUGE << CTX_PGSZ1_SHIFT;
2927
2928                 if (ctx != mm->context.sparc64_ctx_val) {
2929                         /* When changing the page size fields, we
2930                          * must perform a context flush so that no
2931                          * stale entries match.  This flush must
2932                          * occur with the original context register
2933                          * settings.
2934                          */
2935                         do_flush_tlb_mm(mm);
2936
2937                         /* Reload the context register of all processors
2938                          * also executing in this address space.
2939                          */
2940                         mm->context.sparc64_ctx_val = ctx;
2941                         need_context_reload = true;
2942                 }
2943                 spin_unlock_irq(&ctx_alloc_lock);
2944
2945                 if (need_context_reload)
2946                         on_each_cpu(context_reload, mm, 0);
2947         }
2948 }
2949 #endif
2950
2951 static struct resource code_resource = {
2952         .name   = "Kernel code",
2953         .flags  = IORESOURCE_BUSY | IORESOURCE_MEM
2954 };
2955
2956 static struct resource data_resource = {
2957         .name   = "Kernel data",
2958         .flags  = IORESOURCE_BUSY | IORESOURCE_MEM
2959 };
2960
2961 static struct resource bss_resource = {
2962         .name   = "Kernel bss",
2963         .flags  = IORESOURCE_BUSY | IORESOURCE_MEM
2964 };
2965
2966 static inline resource_size_t compute_kern_paddr(void *addr)
2967 {
2968         return (resource_size_t) (addr - KERNBASE + kern_base);
2969 }
2970
2971 static void __init kernel_lds_init(void)
2972 {
2973         code_resource.start = compute_kern_paddr(_text);
2974         code_resource.end   = compute_kern_paddr(_etext - 1);
2975         data_resource.start = compute_kern_paddr(_etext);
2976         data_resource.end   = compute_kern_paddr(_edata - 1);
2977         bss_resource.start  = compute_kern_paddr(__bss_start);
2978         bss_resource.end    = compute_kern_paddr(_end - 1);
2979 }
2980
2981 static int __init report_memory(void)
2982 {
2983         int i;
2984         struct resource *res;
2985
2986         kernel_lds_init();
2987
2988         for (i = 0; i < pavail_ents; i++) {
2989                 res = kzalloc(sizeof(struct resource), GFP_KERNEL);
2990
2991                 if (!res) {
2992                         pr_warn("Failed to allocate source.\n");
2993                         break;
2994                 }
2995
2996                 res->name = "System RAM";
2997                 res->start = pavail[i].phys_addr;
2998                 res->end = pavail[i].phys_addr + pavail[i].reg_size - 1;
2999                 res->flags = IORESOURCE_BUSY | IORESOURCE_MEM;
3000
3001                 if (insert_resource(&iomem_resource, res) < 0) {
3002                         pr_warn("Resource insertion failed.\n");
3003                         break;
3004                 }
3005
3006                 insert_resource(res, &code_resource);
3007                 insert_resource(res, &data_resource);
3008                 insert_resource(res, &bss_resource);
3009         }
3010
3011         return 0;
3012 }
3013 arch_initcall(report_memory);
3014
3015 #ifdef CONFIG_SMP
3016 #define do_flush_tlb_kernel_range       smp_flush_tlb_kernel_range
3017 #else
3018 #define do_flush_tlb_kernel_range       __flush_tlb_kernel_range
3019 #endif
3020
3021 void flush_tlb_kernel_range(unsigned long start, unsigned long end)
3022 {
3023         if (start < HI_OBP_ADDRESS && end > LOW_OBP_ADDRESS) {
3024                 if (start < LOW_OBP_ADDRESS) {
3025                         flush_tsb_kernel_range(start, LOW_OBP_ADDRESS);
3026                         do_flush_tlb_kernel_range(start, LOW_OBP_ADDRESS);
3027                 }
3028                 if (end > HI_OBP_ADDRESS) {
3029                         flush_tsb_kernel_range(HI_OBP_ADDRESS, end);
3030                         do_flush_tlb_kernel_range(HI_OBP_ADDRESS, end);
3031                 }
3032         } else {
3033                 flush_tsb_kernel_range(start, end);
3034                 do_flush_tlb_kernel_range(start, end);
3035         }
3036 }