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