ccbfcc88758ca6bc09598c7ec4cfa45cdeebc84c
[linux-2.6-microblaze.git] / arch / powerpc / kernel / setup_64.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * 
4  * Common boot and setup code.
5  *
6  * Copyright (C) 2001 PPC64 Team, IBM Corp
7  */
8
9 #include <linux/export.h>
10 #include <linux/string.h>
11 #include <linux/sched.h>
12 #include <linux/init.h>
13 #include <linux/kernel.h>
14 #include <linux/reboot.h>
15 #include <linux/delay.h>
16 #include <linux/initrd.h>
17 #include <linux/seq_file.h>
18 #include <linux/ioport.h>
19 #include <linux/console.h>
20 #include <linux/utsname.h>
21 #include <linux/tty.h>
22 #include <linux/root_dev.h>
23 #include <linux/notifier.h>
24 #include <linux/cpu.h>
25 #include <linux/unistd.h>
26 #include <linux/serial.h>
27 #include <linux/serial_8250.h>
28 #include <linux/memblock.h>
29 #include <linux/pci.h>
30 #include <linux/lockdep.h>
31 #include <linux/memory.h>
32 #include <linux/nmi.h>
33 #include <linux/pgtable.h>
34
35 #include <asm/debugfs.h>
36 #include <asm/io.h>
37 #include <asm/kdump.h>
38 #include <asm/prom.h>
39 #include <asm/processor.h>
40 #include <asm/smp.h>
41 #include <asm/elf.h>
42 #include <asm/machdep.h>
43 #include <asm/paca.h>
44 #include <asm/time.h>
45 #include <asm/cputable.h>
46 #include <asm/dt_cpu_ftrs.h>
47 #include <asm/sections.h>
48 #include <asm/btext.h>
49 #include <asm/nvram.h>
50 #include <asm/setup.h>
51 #include <asm/rtas.h>
52 #include <asm/iommu.h>
53 #include <asm/serial.h>
54 #include <asm/cache.h>
55 #include <asm/page.h>
56 #include <asm/mmu.h>
57 #include <asm/firmware.h>
58 #include <asm/xmon.h>
59 #include <asm/udbg.h>
60 #include <asm/kexec.h>
61 #include <asm/code-patching.h>
62 #include <asm/livepatch.h>
63 #include <asm/opal.h>
64 #include <asm/cputhreads.h>
65 #include <asm/hw_irq.h>
66 #include <asm/feature-fixups.h>
67 #include <asm/kup.h>
68 #include <asm/early_ioremap.h>
69 #include <asm/pgalloc.h>
70 #include <asm/asm-prototypes.h>
71
72 #include "setup.h"
73
74 int spinning_secondaries;
75 u64 ppc64_pft_size;
76
77 struct ppc64_caches ppc64_caches = {
78         .l1d = {
79                 .block_size = 0x40,
80                 .log_block_size = 6,
81         },
82         .l1i = {
83                 .block_size = 0x40,
84                 .log_block_size = 6
85         },
86 };
87 EXPORT_SYMBOL_GPL(ppc64_caches);
88
89 #if defined(CONFIG_PPC_BOOK3E) && defined(CONFIG_SMP)
90 void __init setup_tlb_core_data(void)
91 {
92         int cpu;
93
94         BUILD_BUG_ON(offsetof(struct tlb_core_data, lock) != 0);
95
96         for_each_possible_cpu(cpu) {
97                 int first = cpu_first_thread_sibling(cpu);
98
99                 /*
100                  * If we boot via kdump on a non-primary thread,
101                  * make sure we point at the thread that actually
102                  * set up this TLB.
103                  */
104                 if (cpu_first_thread_sibling(boot_cpuid) == first)
105                         first = boot_cpuid;
106
107                 paca_ptrs[cpu]->tcd_ptr = &paca_ptrs[first]->tcd;
108
109                 /*
110                  * If we have threads, we need either tlbsrx.
111                  * or e6500 tablewalk mode, or else TLB handlers
112                  * will be racy and could produce duplicate entries.
113                  * Should we panic instead?
114                  */
115                 WARN_ONCE(smt_enabled_at_boot >= 2 &&
116                           !mmu_has_feature(MMU_FTR_USE_TLBRSRV) &&
117                           book3e_htw_mode != PPC_HTW_E6500,
118                           "%s: unsupported MMU configuration\n", __func__);
119         }
120 }
121 #endif
122
123 #ifdef CONFIG_SMP
124
125 static char *smt_enabled_cmdline;
126
127 /* Look for ibm,smt-enabled OF option */
128 void __init check_smt_enabled(void)
129 {
130         struct device_node *dn;
131         const char *smt_option;
132
133         /* Default to enabling all threads */
134         smt_enabled_at_boot = threads_per_core;
135
136         /* Allow the command line to overrule the OF option */
137         if (smt_enabled_cmdline) {
138                 if (!strcmp(smt_enabled_cmdline, "on"))
139                         smt_enabled_at_boot = threads_per_core;
140                 else if (!strcmp(smt_enabled_cmdline, "off"))
141                         smt_enabled_at_boot = 0;
142                 else {
143                         int smt;
144                         int rc;
145
146                         rc = kstrtoint(smt_enabled_cmdline, 10, &smt);
147                         if (!rc)
148                                 smt_enabled_at_boot =
149                                         min(threads_per_core, smt);
150                 }
151         } else {
152                 dn = of_find_node_by_path("/options");
153                 if (dn) {
154                         smt_option = of_get_property(dn, "ibm,smt-enabled",
155                                                      NULL);
156
157                         if (smt_option) {
158                                 if (!strcmp(smt_option, "on"))
159                                         smt_enabled_at_boot = threads_per_core;
160                                 else if (!strcmp(smt_option, "off"))
161                                         smt_enabled_at_boot = 0;
162                         }
163
164                         of_node_put(dn);
165                 }
166         }
167 }
168
169 /* Look for smt-enabled= cmdline option */
170 static int __init early_smt_enabled(char *p)
171 {
172         smt_enabled_cmdline = p;
173         return 0;
174 }
175 early_param("smt-enabled", early_smt_enabled);
176
177 #endif /* CONFIG_SMP */
178
179 /** Fix up paca fields required for the boot cpu */
180 static void __init fixup_boot_paca(void)
181 {
182         /* The boot cpu is started */
183         get_paca()->cpu_start = 1;
184         /* Allow percpu accesses to work until we setup percpu data */
185         get_paca()->data_offset = 0;
186         /* Mark interrupts disabled in PACA */
187         irq_soft_mask_set(IRQS_DISABLED);
188 }
189
190 static void __init configure_exceptions(void)
191 {
192         /*
193          * Setup the trampolines from the lowmem exception vectors
194          * to the kdump kernel when not using a relocatable kernel.
195          */
196         setup_kdump_trampoline();
197
198         /* Under a PAPR hypervisor, we need hypercalls */
199         if (firmware_has_feature(FW_FEATURE_SET_MODE)) {
200                 /* Enable AIL if possible */
201                 if (!pseries_enable_reloc_on_exc()) {
202                         init_task.thread.fscr &= ~FSCR_SCV;
203                         cur_cpu_spec->cpu_user_features2 &= ~PPC_FEATURE2_SCV;
204                 }
205
206                 /*
207                  * Tell the hypervisor that we want our exceptions to
208                  * be taken in little endian mode.
209                  *
210                  * We don't call this for big endian as our calling convention
211                  * makes us always enter in BE, and the call may fail under
212                  * some circumstances with kdump.
213                  */
214 #ifdef __LITTLE_ENDIAN__
215                 pseries_little_endian_exceptions();
216 #endif
217         } else {
218                 /* Set endian mode using OPAL */
219                 if (firmware_has_feature(FW_FEATURE_OPAL))
220                         opal_configure_cores();
221
222                 /* AIL on native is done in cpu_ready_for_interrupts() */
223         }
224 }
225
226 static void cpu_ready_for_interrupts(void)
227 {
228         /*
229          * Enable AIL if supported, and we are in hypervisor mode. This
230          * is called once for every processor.
231          *
232          * If we are not in hypervisor mode the job is done once for
233          * the whole partition in configure_exceptions().
234          */
235         if (cpu_has_feature(CPU_FTR_HVMODE) &&
236             cpu_has_feature(CPU_FTR_ARCH_207S)) {
237                 unsigned long lpcr = mfspr(SPRN_LPCR);
238                 mtspr(SPRN_LPCR, lpcr | LPCR_AIL_3);
239         }
240
241         /*
242          * Set HFSCR:TM based on CPU features:
243          * In the special case of TM no suspend (P9N DD2.1), Linux is
244          * told TM is off via the dt-ftrs but told to (partially) use
245          * it via OPAL_REINIT_CPUS_TM_SUSPEND_DISABLED. So HFSCR[TM]
246          * will be off from dt-ftrs but we need to turn it on for the
247          * no suspend case.
248          */
249         if (cpu_has_feature(CPU_FTR_HVMODE)) {
250                 if (cpu_has_feature(CPU_FTR_TM_COMP))
251                         mtspr(SPRN_HFSCR, mfspr(SPRN_HFSCR) | HFSCR_TM);
252                 else
253                         mtspr(SPRN_HFSCR, mfspr(SPRN_HFSCR) & ~HFSCR_TM);
254         }
255
256         /* Set IR and DR in PACA MSR */
257         get_paca()->kernel_msr = MSR_KERNEL;
258 }
259
260 unsigned long spr_default_dscr = 0;
261
262 static void __init record_spr_defaults(void)
263 {
264         if (early_cpu_has_feature(CPU_FTR_DSCR))
265                 spr_default_dscr = mfspr(SPRN_DSCR);
266 }
267
268 /*
269  * Early initialization entry point. This is called by head.S
270  * with MMU translation disabled. We rely on the "feature" of
271  * the CPU that ignores the top 2 bits of the address in real
272  * mode so we can access kernel globals normally provided we
273  * only toy with things in the RMO region. From here, we do
274  * some early parsing of the device-tree to setup out MEMBLOCK
275  * data structures, and allocate & initialize the hash table
276  * and segment tables so we can start running with translation
277  * enabled.
278  *
279  * It is this function which will call the probe() callback of
280  * the various platform types and copy the matching one to the
281  * global ppc_md structure. Your platform can eventually do
282  * some very early initializations from the probe() routine, but
283  * this is not recommended, be very careful as, for example, the
284  * device-tree is not accessible via normal means at this point.
285  */
286
287 void __init early_setup(unsigned long dt_ptr)
288 {
289         static __initdata struct paca_struct boot_paca;
290
291         /* -------- printk is _NOT_ safe to use here ! ------- */
292
293         /*
294          * Assume we're on cpu 0 for now.
295          *
296          * We need to load a PACA very early for a few reasons.
297          *
298          * The stack protector canary is stored in the paca, so as soon as we
299          * call any stack protected code we need r13 pointing somewhere valid.
300          *
301          * If we are using kcov it will call in_task() in its instrumentation,
302          * which relies on the current task from the PACA.
303          *
304          * dt_cpu_ftrs_init() calls into generic OF/fdt code, as well as
305          * printk(), which can trigger both stack protector and kcov.
306          *
307          * percpu variables and spin locks also use the paca.
308          *
309          * So set up a temporary paca. It will be replaced below once we know
310          * what CPU we are on.
311          */
312         initialise_paca(&boot_paca, 0);
313         setup_paca(&boot_paca);
314         fixup_boot_paca();
315
316         /* -------- printk is now safe to use ------- */
317
318         /* Try new device tree based feature discovery ... */
319         if (!dt_cpu_ftrs_init(__va(dt_ptr)))
320                 /* Otherwise use the old style CPU table */
321                 identify_cpu(0, mfspr(SPRN_PVR));
322
323         /* Enable early debugging if any specified (see udbg.h) */
324         udbg_early_init();
325
326         udbg_printf(" -> %s(), dt_ptr: 0x%lx\n", __func__, dt_ptr);
327
328         /*
329          * Do early initialization using the flattened device
330          * tree, such as retrieving the physical memory map or
331          * calculating/retrieving the hash table size.
332          */
333         early_init_devtree(__va(dt_ptr));
334
335         /* Now we know the logical id of our boot cpu, setup the paca. */
336         if (boot_cpuid != 0) {
337                 /* Poison paca_ptrs[0] again if it's not the boot cpu */
338                 memset(&paca_ptrs[0], 0x88, sizeof(paca_ptrs[0]));
339         }
340         setup_paca(paca_ptrs[boot_cpuid]);
341         fixup_boot_paca();
342
343         /*
344          * Configure exception handlers. This include setting up trampolines
345          * if needed, setting exception endian mode, etc...
346          */
347         configure_exceptions();
348
349         /*
350          * Configure Kernel Userspace Protection. This needs to happen before
351          * feature fixups for platforms that implement this using features.
352          */
353         setup_kup();
354
355         /* Apply all the dynamic patching */
356         apply_feature_fixups();
357         setup_feature_keys();
358
359         early_ioremap_setup();
360
361         /* Initialize the hash table or TLB handling */
362         early_init_mmu();
363
364         /*
365          * After firmware and early platform setup code has set things up,
366          * we note the SPR values for configurable control/performance
367          * registers, and use those as initial defaults.
368          */
369         record_spr_defaults();
370
371         /*
372          * At this point, we can let interrupts switch to virtual mode
373          * (the MMU has been setup), so adjust the MSR in the PACA to
374          * have IR and DR set and enable AIL if it exists
375          */
376         cpu_ready_for_interrupts();
377
378         /*
379          * We enable ftrace here, but since we only support DYNAMIC_FTRACE, it
380          * will only actually get enabled on the boot cpu much later once
381          * ftrace itself has been initialized.
382          */
383         this_cpu_enable_ftrace();
384
385         udbg_printf(" <- %s()\n", __func__);
386
387 #ifdef CONFIG_PPC_EARLY_DEBUG_BOOTX
388         /*
389          * This needs to be done *last* (after the above udbg_printf() even)
390          *
391          * Right after we return from this function, we turn on the MMU
392          * which means the real-mode access trick that btext does will
393          * no longer work, it needs to switch to using a real MMU
394          * mapping. This call will ensure that it does
395          */
396         btext_map();
397 #endif /* CONFIG_PPC_EARLY_DEBUG_BOOTX */
398 }
399
400 #ifdef CONFIG_SMP
401 void early_setup_secondary(void)
402 {
403         /* Mark interrupts disabled in PACA */
404         irq_soft_mask_set(IRQS_DISABLED);
405
406         /* Initialize the hash table or TLB handling */
407         early_init_mmu_secondary();
408
409         /* Perform any KUP setup that is per-cpu */
410         setup_kup();
411
412         /*
413          * At this point, we can let interrupts switch to virtual mode
414          * (the MMU has been setup), so adjust the MSR in the PACA to
415          * have IR and DR set.
416          */
417         cpu_ready_for_interrupts();
418 }
419
420 #endif /* CONFIG_SMP */
421
422 void panic_smp_self_stop(void)
423 {
424         hard_irq_disable();
425         spin_begin();
426         while (1)
427                 spin_cpu_relax();
428 }
429
430 #if defined(CONFIG_SMP) || defined(CONFIG_KEXEC_CORE)
431 static bool use_spinloop(void)
432 {
433         if (IS_ENABLED(CONFIG_PPC_BOOK3S)) {
434                 /*
435                  * See comments in head_64.S -- not all platforms insert
436                  * secondaries at __secondary_hold and wait at the spin
437                  * loop.
438                  */
439                 if (firmware_has_feature(FW_FEATURE_OPAL))
440                         return false;
441                 return true;
442         }
443
444         /*
445          * When book3e boots from kexec, the ePAPR spin table does
446          * not get used.
447          */
448         return of_property_read_bool(of_chosen, "linux,booted-from-kexec");
449 }
450
451 void smp_release_cpus(void)
452 {
453         unsigned long *ptr;
454         int i;
455
456         if (!use_spinloop())
457                 return;
458
459         /* All secondary cpus are spinning on a common spinloop, release them
460          * all now so they can start to spin on their individual paca
461          * spinloops. For non SMP kernels, the secondary cpus never get out
462          * of the common spinloop.
463          */
464
465         ptr  = (unsigned long *)((unsigned long)&__secondary_hold_spinloop
466                         - PHYSICAL_START);
467         *ptr = ppc_function_entry(generic_secondary_smp_init);
468
469         /* And wait a bit for them to catch up */
470         for (i = 0; i < 100000; i++) {
471                 mb();
472                 HMT_low();
473                 if (spinning_secondaries == 0)
474                         break;
475                 udelay(1);
476         }
477         pr_debug("spinning_secondaries = %d\n", spinning_secondaries);
478 }
479 #endif /* CONFIG_SMP || CONFIG_KEXEC_CORE */
480
481 /*
482  * Initialize some remaining members of the ppc64_caches and systemcfg
483  * structures
484  * (at least until we get rid of them completely). This is mostly some
485  * cache informations about the CPU that will be used by cache flush
486  * routines and/or provided to userland
487  */
488
489 static void init_cache_info(struct ppc_cache_info *info, u32 size, u32 lsize,
490                             u32 bsize, u32 sets)
491 {
492         info->size = size;
493         info->sets = sets;
494         info->line_size = lsize;
495         info->block_size = bsize;
496         info->log_block_size = __ilog2(bsize);
497         if (bsize)
498                 info->blocks_per_page = PAGE_SIZE / bsize;
499         else
500                 info->blocks_per_page = 0;
501
502         if (sets == 0)
503                 info->assoc = 0xffff;
504         else
505                 info->assoc = size / (sets * lsize);
506 }
507
508 static bool __init parse_cache_info(struct device_node *np,
509                                     bool icache,
510                                     struct ppc_cache_info *info)
511 {
512         static const char *ipropnames[] __initdata = {
513                 "i-cache-size",
514                 "i-cache-sets",
515                 "i-cache-block-size",
516                 "i-cache-line-size",
517         };
518         static const char *dpropnames[] __initdata = {
519                 "d-cache-size",
520                 "d-cache-sets",
521                 "d-cache-block-size",
522                 "d-cache-line-size",
523         };
524         const char **propnames = icache ? ipropnames : dpropnames;
525         const __be32 *sizep, *lsizep, *bsizep, *setsp;
526         u32 size, lsize, bsize, sets;
527         bool success = true;
528
529         size = 0;
530         sets = -1u;
531         lsize = bsize = cur_cpu_spec->dcache_bsize;
532         sizep = of_get_property(np, propnames[0], NULL);
533         if (sizep != NULL)
534                 size = be32_to_cpu(*sizep);
535         setsp = of_get_property(np, propnames[1], NULL);
536         if (setsp != NULL)
537                 sets = be32_to_cpu(*setsp);
538         bsizep = of_get_property(np, propnames[2], NULL);
539         lsizep = of_get_property(np, propnames[3], NULL);
540         if (bsizep == NULL)
541                 bsizep = lsizep;
542         if (lsizep == NULL)
543                 lsizep = bsizep;
544         if (lsizep != NULL)
545                 lsize = be32_to_cpu(*lsizep);
546         if (bsizep != NULL)
547                 bsize = be32_to_cpu(*bsizep);
548         if (sizep == NULL || bsizep == NULL || lsizep == NULL)
549                 success = false;
550
551         /*
552          * OF is weird .. it represents fully associative caches
553          * as "1 way" which doesn't make much sense and doesn't
554          * leave room for direct mapped. We'll assume that 0
555          * in OF means direct mapped for that reason.
556          */
557         if (sets == 1)
558                 sets = 0;
559         else if (sets == 0)
560                 sets = 1;
561
562         init_cache_info(info, size, lsize, bsize, sets);
563
564         return success;
565 }
566
567 void __init initialize_cache_info(void)
568 {
569         struct device_node *cpu = NULL, *l2, *l3 = NULL;
570         u32 pvr;
571
572         /*
573          * All shipping POWER8 machines have a firmware bug that
574          * puts incorrect information in the device-tree. This will
575          * be (hopefully) fixed for future chips but for now hard
576          * code the values if we are running on one of these
577          */
578         pvr = PVR_VER(mfspr(SPRN_PVR));
579         if (pvr == PVR_POWER8 || pvr == PVR_POWER8E ||
580             pvr == PVR_POWER8NVL) {
581                                                 /* size    lsize   blk  sets */
582                 init_cache_info(&ppc64_caches.l1i, 0x8000,   128,  128, 32);
583                 init_cache_info(&ppc64_caches.l1d, 0x10000,  128,  128, 64);
584                 init_cache_info(&ppc64_caches.l2,  0x80000,  128,  0,   512);
585                 init_cache_info(&ppc64_caches.l3,  0x800000, 128,  0,   8192);
586         } else
587                 cpu = of_find_node_by_type(NULL, "cpu");
588
589         /*
590          * We're assuming *all* of the CPUs have the same
591          * d-cache and i-cache sizes... -Peter
592          */
593         if (cpu) {
594                 if (!parse_cache_info(cpu, false, &ppc64_caches.l1d))
595                         pr_warn("Argh, can't find dcache properties !\n");
596
597                 if (!parse_cache_info(cpu, true, &ppc64_caches.l1i))
598                         pr_warn("Argh, can't find icache properties !\n");
599
600                 /*
601                  * Try to find the L2 and L3 if any. Assume they are
602                  * unified and use the D-side properties.
603                  */
604                 l2 = of_find_next_cache_node(cpu);
605                 of_node_put(cpu);
606                 if (l2) {
607                         parse_cache_info(l2, false, &ppc64_caches.l2);
608                         l3 = of_find_next_cache_node(l2);
609                         of_node_put(l2);
610                 }
611                 if (l3) {
612                         parse_cache_info(l3, false, &ppc64_caches.l3);
613                         of_node_put(l3);
614                 }
615         }
616
617         /* For use by binfmt_elf */
618         dcache_bsize = ppc64_caches.l1d.block_size;
619         icache_bsize = ppc64_caches.l1i.block_size;
620
621         cur_cpu_spec->dcache_bsize = dcache_bsize;
622         cur_cpu_spec->icache_bsize = icache_bsize;
623 }
624
625 /*
626  * This returns the limit below which memory accesses to the linear
627  * mapping are guarnateed not to cause an architectural exception (e.g.,
628  * TLB or SLB miss fault).
629  *
630  * This is used to allocate PACAs and various interrupt stacks that
631  * that are accessed early in interrupt handlers that must not cause
632  * re-entrant interrupts.
633  */
634 __init u64 ppc64_bolted_size(void)
635 {
636 #ifdef CONFIG_PPC_BOOK3E
637         /* Freescale BookE bolts the entire linear mapping */
638         /* XXX: BookE ppc64_rma_limit setup seems to disagree? */
639         if (early_mmu_has_feature(MMU_FTR_TYPE_FSL_E))
640                 return linear_map_top;
641         /* Other BookE, we assume the first GB is bolted */
642         return 1ul << 30;
643 #else
644         /* BookS radix, does not take faults on linear mapping */
645         if (early_radix_enabled())
646                 return ULONG_MAX;
647
648         /* BookS hash, the first segment is bolted */
649         if (early_mmu_has_feature(MMU_FTR_1T_SEGMENT))
650                 return 1UL << SID_SHIFT_1T;
651         return 1UL << SID_SHIFT;
652 #endif
653 }
654
655 static void *__init alloc_stack(unsigned long limit, int cpu)
656 {
657         void *ptr;
658
659         BUILD_BUG_ON(STACK_INT_FRAME_SIZE % 16);
660
661         ptr = memblock_alloc_try_nid(THREAD_SIZE, THREAD_ALIGN,
662                                      MEMBLOCK_LOW_LIMIT, limit,
663                                      early_cpu_to_node(cpu));
664         if (!ptr)
665                 panic("cannot allocate stacks");
666
667         return ptr;
668 }
669
670 void __init irqstack_early_init(void)
671 {
672         u64 limit = ppc64_bolted_size();
673         unsigned int i;
674
675         /*
676          * Interrupt stacks must be in the first segment since we
677          * cannot afford to take SLB misses on them. They are not
678          * accessed in realmode.
679          */
680         for_each_possible_cpu(i) {
681                 softirq_ctx[i] = alloc_stack(limit, i);
682                 hardirq_ctx[i] = alloc_stack(limit, i);
683         }
684 }
685
686 #ifdef CONFIG_PPC_BOOK3E
687 void __init exc_lvl_early_init(void)
688 {
689         unsigned int i;
690
691         for_each_possible_cpu(i) {
692                 void *sp;
693
694                 sp = alloc_stack(ULONG_MAX, i);
695                 critirq_ctx[i] = sp;
696                 paca_ptrs[i]->crit_kstack = sp + THREAD_SIZE;
697
698                 sp = alloc_stack(ULONG_MAX, i);
699                 dbgirq_ctx[i] = sp;
700                 paca_ptrs[i]->dbg_kstack = sp + THREAD_SIZE;
701
702                 sp = alloc_stack(ULONG_MAX, i);
703                 mcheckirq_ctx[i] = sp;
704                 paca_ptrs[i]->mc_kstack = sp + THREAD_SIZE;
705         }
706
707         if (cpu_has_feature(CPU_FTR_DEBUG_LVL_EXC))
708                 patch_exception(0x040, exc_debug_debug_book3e);
709 }
710 #endif
711
712 /*
713  * Stack space used when we detect a bad kernel stack pointer, and
714  * early in SMP boots before relocation is enabled. Exclusive emergency
715  * stack for machine checks.
716  */
717 void __init emergency_stack_init(void)
718 {
719         u64 limit, mce_limit;
720         unsigned int i;
721
722         /*
723          * Emergency stacks must be under 256MB, we cannot afford to take
724          * SLB misses on them. The ABI also requires them to be 128-byte
725          * aligned.
726          *
727          * Since we use these as temporary stacks during secondary CPU
728          * bringup, machine check, system reset, and HMI, we need to get
729          * at them in real mode. This means they must also be within the RMO
730          * region.
731          *
732          * The IRQ stacks allocated elsewhere in this file are zeroed and
733          * initialized in kernel/irq.c. These are initialized here in order
734          * to have emergency stacks available as early as possible.
735          */
736         limit = mce_limit = min(ppc64_bolted_size(), ppc64_rma_size);
737
738         /*
739          * Machine check on pseries calls rtas, but can't use the static
740          * rtas_args due to a machine check hitting while the lock is held.
741          * rtas args have to be under 4GB, so the machine check stack is
742          * limited to 4GB so args can be put on stack.
743          */
744         if (firmware_has_feature(FW_FEATURE_LPAR) && mce_limit > SZ_4G)
745                 mce_limit = SZ_4G;
746
747         for_each_possible_cpu(i) {
748                 paca_ptrs[i]->emergency_sp = alloc_stack(limit, i) + THREAD_SIZE;
749
750 #ifdef CONFIG_PPC_BOOK3S_64
751                 /* emergency stack for NMI exception handling. */
752                 paca_ptrs[i]->nmi_emergency_sp = alloc_stack(limit, i) + THREAD_SIZE;
753
754                 /* emergency stack for machine check exception handling. */
755                 paca_ptrs[i]->mc_emergency_sp = alloc_stack(mce_limit, i) + THREAD_SIZE;
756 #endif
757         }
758 }
759
760 #ifdef CONFIG_SMP
761 /**
762  * pcpu_alloc_bootmem - NUMA friendly alloc_bootmem wrapper for percpu
763  * @cpu: cpu to allocate for
764  * @size: size allocation in bytes
765  * @align: alignment
766  *
767  * Allocate @size bytes aligned at @align for cpu @cpu.  This wrapper
768  * does the right thing for NUMA regardless of the current
769  * configuration.
770  *
771  * RETURNS:
772  * Pointer to the allocated area on success, NULL on failure.
773  */
774 static void * __init pcpu_alloc_bootmem(unsigned int cpu, size_t size,
775                                         size_t align)
776 {
777         const unsigned long goal = __pa(MAX_DMA_ADDRESS);
778 #ifdef CONFIG_NEED_MULTIPLE_NODES
779         int node = early_cpu_to_node(cpu);
780         void *ptr;
781
782         if (!node_online(node) || !NODE_DATA(node)) {
783                 ptr = memblock_alloc_from(size, align, goal);
784                 pr_info("cpu %d has no node %d or node-local memory\n",
785                         cpu, node);
786                 pr_debug("per cpu data for cpu%d %lu bytes at %016lx\n",
787                          cpu, size, __pa(ptr));
788         } else {
789                 ptr = memblock_alloc_try_nid(size, align, goal,
790                                              MEMBLOCK_ALLOC_ACCESSIBLE, node);
791                 pr_debug("per cpu data for cpu%d %lu bytes on node%d at "
792                          "%016lx\n", cpu, size, node, __pa(ptr));
793         }
794         return ptr;
795 #else
796         return memblock_alloc_from(size, align, goal);
797 #endif
798 }
799
800 static void __init pcpu_free_bootmem(void *ptr, size_t size)
801 {
802         memblock_free(__pa(ptr), size);
803 }
804
805 static int pcpu_cpu_distance(unsigned int from, unsigned int to)
806 {
807         if (early_cpu_to_node(from) == early_cpu_to_node(to))
808                 return LOCAL_DISTANCE;
809         else
810                 return REMOTE_DISTANCE;
811 }
812
813 unsigned long __per_cpu_offset[NR_CPUS] __read_mostly;
814 EXPORT_SYMBOL(__per_cpu_offset);
815
816 static void __init pcpu_populate_pte(unsigned long addr)
817 {
818         pgd_t *pgd = pgd_offset_k(addr);
819         p4d_t *p4d;
820         pud_t *pud;
821         pmd_t *pmd;
822
823         p4d = p4d_offset(pgd, addr);
824         if (p4d_none(*p4d)) {
825                 pud_t *new;
826
827                 new = memblock_alloc(PUD_TABLE_SIZE, PUD_TABLE_SIZE);
828                 if (!new)
829                         goto err_alloc;
830                 p4d_populate(&init_mm, p4d, new);
831         }
832
833         pud = pud_offset(p4d, addr);
834         if (pud_none(*pud)) {
835                 pmd_t *new;
836
837                 new = memblock_alloc(PMD_TABLE_SIZE, PMD_TABLE_SIZE);
838                 if (!new)
839                         goto err_alloc;
840                 pud_populate(&init_mm, pud, new);
841         }
842
843         pmd = pmd_offset(pud, addr);
844         if (!pmd_present(*pmd)) {
845                 pte_t *new;
846
847                 new = memblock_alloc(PTE_TABLE_SIZE, PTE_TABLE_SIZE);
848                 if (!new)
849                         goto err_alloc;
850                 pmd_populate_kernel(&init_mm, pmd, new);
851         }
852
853         return;
854
855 err_alloc:
856         panic("%s: Failed to allocate %lu bytes align=%lx from=%lx\n",
857               __func__, PAGE_SIZE, PAGE_SIZE, PAGE_SIZE);
858 }
859
860
861 void __init setup_per_cpu_areas(void)
862 {
863         const size_t dyn_size = PERCPU_MODULE_RESERVE + PERCPU_DYNAMIC_RESERVE;
864         size_t atom_size;
865         unsigned long delta;
866         unsigned int cpu;
867         int rc = -EINVAL;
868
869         /*
870          * Linear mapping is one of 4K, 1M and 16M.  For 4K, no need
871          * to group units.  For larger mappings, use 1M atom which
872          * should be large enough to contain a number of units.
873          */
874         if (mmu_linear_psize == MMU_PAGE_4K)
875                 atom_size = PAGE_SIZE;
876         else
877                 atom_size = 1 << 20;
878
879         if (pcpu_chosen_fc != PCPU_FC_PAGE) {
880                 rc = pcpu_embed_first_chunk(0, dyn_size, atom_size, pcpu_cpu_distance,
881                                             pcpu_alloc_bootmem, pcpu_free_bootmem);
882                 if (rc)
883                         pr_warn("PERCPU: %s allocator failed (%d), "
884                                 "falling back to page size\n",
885                                 pcpu_fc_names[pcpu_chosen_fc], rc);
886         }
887
888         if (rc < 0)
889                 rc = pcpu_page_first_chunk(0, pcpu_alloc_bootmem, pcpu_free_bootmem,
890                                            pcpu_populate_pte);
891         if (rc < 0)
892                 panic("cannot initialize percpu area (err=%d)", rc);
893
894         delta = (unsigned long)pcpu_base_addr - (unsigned long)__per_cpu_start;
895         for_each_possible_cpu(cpu) {
896                 __per_cpu_offset[cpu] = delta + pcpu_unit_offsets[cpu];
897                 paca_ptrs[cpu]->data_offset = __per_cpu_offset[cpu];
898         }
899 }
900 #endif
901
902 #ifdef CONFIG_MEMORY_HOTPLUG_SPARSE
903 unsigned long memory_block_size_bytes(void)
904 {
905         if (ppc_md.memory_block_size)
906                 return ppc_md.memory_block_size();
907
908         return MIN_MEMORY_BLOCK_SIZE;
909 }
910 #endif
911
912 #if defined(CONFIG_PPC_INDIRECT_PIO) || defined(CONFIG_PPC_INDIRECT_MMIO)
913 struct ppc_pci_io ppc_pci_io;
914 EXPORT_SYMBOL(ppc_pci_io);
915 #endif
916
917 #ifdef CONFIG_HARDLOCKUP_DETECTOR_PERF
918 u64 hw_nmi_get_sample_period(int watchdog_thresh)
919 {
920         return ppc_proc_freq * watchdog_thresh;
921 }
922 #endif
923
924 /*
925  * The perf based hardlockup detector breaks PMU event based branches, so
926  * disable it by default. Book3S has a soft-nmi hardlockup detector based
927  * on the decrementer interrupt, so it does not suffer from this problem.
928  *
929  * It is likely to get false positives in VM guests, so disable it there
930  * by default too.
931  */
932 static int __init disable_hardlockup_detector(void)
933 {
934 #ifdef CONFIG_HARDLOCKUP_DETECTOR_PERF
935         hardlockup_detector_disable();
936 #else
937         if (firmware_has_feature(FW_FEATURE_LPAR))
938                 hardlockup_detector_disable();
939 #endif
940
941         return 0;
942 }
943 early_initcall(disable_hardlockup_detector);