powerpc/fadump: make crash memory ranges array allocation generic
[platform/kernel/linux-starfive.git] / arch / powerpc / kernel / fadump.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Firmware Assisted dump: A robust mechanism to get reliable kernel crash
4  * dump with assistance from firmware. This approach does not use kexec,
5  * instead firmware assists in booting the kdump kernel while preserving
6  * memory contents. The most of the code implementation has been adapted
7  * from phyp assisted dump implementation written by Linas Vepstas and
8  * Manish Ahuja
9  *
10  * Copyright 2011 IBM Corporation
11  * Author: Mahesh Salgaonkar <mahesh@linux.vnet.ibm.com>
12  */
13
14 #undef DEBUG
15 #define pr_fmt(fmt) "fadump: " fmt
16
17 #include <linux/string.h>
18 #include <linux/memblock.h>
19 #include <linux/delay.h>
20 #include <linux/seq_file.h>
21 #include <linux/crash_dump.h>
22 #include <linux/kobject.h>
23 #include <linux/sysfs.h>
24 #include <linux/slab.h>
25 #include <linux/cma.h>
26 #include <linux/hugetlb.h>
27
28 #include <asm/debugfs.h>
29 #include <asm/page.h>
30 #include <asm/prom.h>
31 #include <asm/fadump.h>
32 #include <asm/fadump-internal.h>
33 #include <asm/setup.h>
34
35 static struct fw_dump fw_dump;
36
37 static DEFINE_MUTEX(fadump_mutex);
38 struct fadump_mrange_info crash_mrange_info = { "crash", NULL, 0, 0, 0 };
39
40 #ifdef CONFIG_CMA
41 static struct cma *fadump_cma;
42
43 /*
44  * fadump_cma_init() - Initialize CMA area from a fadump reserved memory
45  *
46  * This function initializes CMA area from fadump reserved memory.
47  * The total size of fadump reserved memory covers for boot memory size
48  * + cpu data size + hpte size and metadata.
49  * Initialize only the area equivalent to boot memory size for CMA use.
50  * The reamining portion of fadump reserved memory will be not given
51  * to CMA and pages for thoes will stay reserved. boot memory size is
52  * aligned per CMA requirement to satisy cma_init_reserved_mem() call.
53  * But for some reason even if it fails we still have the memory reservation
54  * with us and we can still continue doing fadump.
55  */
56 int __init fadump_cma_init(void)
57 {
58         unsigned long long base, size;
59         int rc;
60
61         if (!fw_dump.fadump_enabled)
62                 return 0;
63
64         /*
65          * Do not use CMA if user has provided fadump=nocma kernel parameter.
66          * Return 1 to continue with fadump old behaviour.
67          */
68         if (fw_dump.nocma)
69                 return 1;
70
71         base = fw_dump.reserve_dump_area_start;
72         size = fw_dump.boot_memory_size;
73
74         if (!size)
75                 return 0;
76
77         rc = cma_init_reserved_mem(base, size, 0, "fadump_cma", &fadump_cma);
78         if (rc) {
79                 pr_err("Failed to init cma area for firmware-assisted dump,%d\n", rc);
80                 /*
81                  * Though the CMA init has failed we still have memory
82                  * reservation with us. The reserved memory will be
83                  * blocked from production system usage.  Hence return 1,
84                  * so that we can continue with fadump.
85                  */
86                 return 1;
87         }
88
89         /*
90          * So we now have successfully initialized cma area for fadump.
91          */
92         pr_info("Initialized 0x%lx bytes cma area at %ldMB from 0x%lx "
93                 "bytes of memory reserved for firmware-assisted dump\n",
94                 cma_get_size(fadump_cma),
95                 (unsigned long)cma_get_base(fadump_cma) >> 20,
96                 fw_dump.reserve_dump_area_size);
97         return 1;
98 }
99 #else
100 static int __init fadump_cma_init(void) { return 1; }
101 #endif /* CONFIG_CMA */
102
103 /* Scan the Firmware Assisted dump configuration details. */
104 int __init early_init_dt_scan_fw_dump(unsigned long node, const char *uname,
105                                       int depth, void *data)
106 {
107         if (depth != 1)
108                 return 0;
109
110         if (strcmp(uname, "rtas") == 0) {
111                 rtas_fadump_dt_scan(&fw_dump, node);
112                 return 1;
113         }
114
115         if (strcmp(uname, "ibm,opal") == 0) {
116                 opal_fadump_dt_scan(&fw_dump, node);
117                 return 1;
118         }
119
120         return 0;
121 }
122
123 /*
124  * If fadump is registered, check if the memory provided
125  * falls within boot memory area and reserved memory area.
126  */
127 int is_fadump_memory_area(u64 addr, ulong size)
128 {
129         u64 d_start = fw_dump.reserve_dump_area_start;
130         u64 d_end = d_start + fw_dump.reserve_dump_area_size;
131
132         if (!fw_dump.dump_registered)
133                 return 0;
134
135         if (((addr + size) > d_start) && (addr <= d_end))
136                 return 1;
137
138         return (addr + size) > RMA_START && addr <= fw_dump.boot_memory_size;
139 }
140
141 int should_fadump_crash(void)
142 {
143         if (!fw_dump.dump_registered || !fw_dump.fadumphdr_addr)
144                 return 0;
145         return 1;
146 }
147
148 int is_fadump_active(void)
149 {
150         return fw_dump.dump_active;
151 }
152
153 /*
154  * Returns true, if there are no holes in memory area between d_start to d_end,
155  * false otherwise.
156  */
157 static bool is_fadump_mem_area_contiguous(u64 d_start, u64 d_end)
158 {
159         struct memblock_region *reg;
160         bool ret = false;
161         u64 start, end;
162
163         for_each_memblock(memory, reg) {
164                 start = max_t(u64, d_start, reg->base);
165                 end = min_t(u64, d_end, (reg->base + reg->size));
166                 if (d_start < end) {
167                         /* Memory hole from d_start to start */
168                         if (start > d_start)
169                                 break;
170
171                         if (end == d_end) {
172                                 ret = true;
173                                 break;
174                         }
175
176                         d_start = end + 1;
177                 }
178         }
179
180         return ret;
181 }
182
183 /*
184  * Returns true, if there are no holes in boot memory area,
185  * false otherwise.
186  */
187 bool is_fadump_boot_mem_contiguous(void)
188 {
189         return is_fadump_mem_area_contiguous(0, fw_dump.boot_memory_size);
190 }
191
192 /*
193  * Returns true, if there are no holes in reserved memory area,
194  * false otherwise.
195  */
196 bool is_fadump_reserved_mem_contiguous(void)
197 {
198         u64 d_start, d_end;
199
200         d_start = fw_dump.reserve_dump_area_start;
201         d_end   = d_start + fw_dump.reserve_dump_area_size;
202         return is_fadump_mem_area_contiguous(d_start, d_end);
203 }
204
205 /* Print firmware assisted dump configurations for debugging purpose. */
206 static void fadump_show_config(void)
207 {
208         pr_debug("Support for firmware-assisted dump (fadump): %s\n",
209                         (fw_dump.fadump_supported ? "present" : "no support"));
210
211         if (!fw_dump.fadump_supported)
212                 return;
213
214         pr_debug("Fadump enabled    : %s\n",
215                                 (fw_dump.fadump_enabled ? "yes" : "no"));
216         pr_debug("Dump Active       : %s\n",
217                                 (fw_dump.dump_active ? "yes" : "no"));
218         pr_debug("Dump section sizes:\n");
219         pr_debug("    CPU state data size: %lx\n", fw_dump.cpu_state_data_size);
220         pr_debug("    HPTE region size   : %lx\n", fw_dump.hpte_region_size);
221         pr_debug("Boot memory size  : %lx\n", fw_dump.boot_memory_size);
222 }
223
224 /**
225  * fadump_calculate_reserve_size(): reserve variable boot area 5% of System RAM
226  *
227  * Function to find the largest memory size we need to reserve during early
228  * boot process. This will be the size of the memory that is required for a
229  * kernel to boot successfully.
230  *
231  * This function has been taken from phyp-assisted dump feature implementation.
232  *
233  * returns larger of 256MB or 5% rounded down to multiples of 256MB.
234  *
235  * TODO: Come up with better approach to find out more accurate memory size
236  * that is required for a kernel to boot successfully.
237  *
238  */
239 static inline unsigned long fadump_calculate_reserve_size(void)
240 {
241         int ret;
242         unsigned long long base, size;
243
244         if (fw_dump.reserve_bootvar)
245                 pr_warn("'fadump_reserve_mem=' parameter is deprecated in favor of 'crashkernel=' parameter.\n");
246
247         /*
248          * Check if the size is specified through crashkernel= cmdline
249          * option. If yes, then use that but ignore base as fadump reserves
250          * memory at a predefined offset.
251          */
252         ret = parse_crashkernel(boot_command_line, memblock_phys_mem_size(),
253                                 &size, &base);
254         if (ret == 0 && size > 0) {
255                 unsigned long max_size;
256
257                 if (fw_dump.reserve_bootvar)
258                         pr_info("Using 'crashkernel=' parameter for memory reservation.\n");
259
260                 fw_dump.reserve_bootvar = (unsigned long)size;
261
262                 /*
263                  * Adjust if the boot memory size specified is above
264                  * the upper limit.
265                  */
266                 max_size = memblock_phys_mem_size() / MAX_BOOT_MEM_RATIO;
267                 if (fw_dump.reserve_bootvar > max_size) {
268                         fw_dump.reserve_bootvar = max_size;
269                         pr_info("Adjusted boot memory size to %luMB\n",
270                                 (fw_dump.reserve_bootvar >> 20));
271                 }
272
273                 return fw_dump.reserve_bootvar;
274         } else if (fw_dump.reserve_bootvar) {
275                 /*
276                  * 'fadump_reserve_mem=' is being used to reserve memory
277                  * for firmware-assisted dump.
278                  */
279                 return fw_dump.reserve_bootvar;
280         }
281
282         /* divide by 20 to get 5% of value */
283         size = memblock_phys_mem_size() / 20;
284
285         /* round it down in multiples of 256 */
286         size = size & ~0x0FFFFFFFUL;
287
288         /* Truncate to memory_limit. We don't want to over reserve the memory.*/
289         if (memory_limit && size > memory_limit)
290                 size = memory_limit;
291
292         return (size > MIN_BOOT_MEM ? size : MIN_BOOT_MEM);
293 }
294
295 /*
296  * Calculate the total memory size required to be reserved for
297  * firmware-assisted dump registration.
298  */
299 static unsigned long get_fadump_area_size(void)
300 {
301         unsigned long size = 0;
302
303         size += fw_dump.cpu_state_data_size;
304         size += fw_dump.hpte_region_size;
305         size += fw_dump.boot_memory_size;
306         size += sizeof(struct fadump_crash_info_header);
307         size += sizeof(struct elfhdr); /* ELF core header.*/
308         size += sizeof(struct elf_phdr); /* place holder for cpu notes */
309         /* Program headers for crash memory regions. */
310         size += sizeof(struct elf_phdr) * (memblock_num_regions(memory) + 2);
311
312         size = PAGE_ALIGN(size);
313
314         /* This is to hold kernel metadata on platforms that support it */
315         size += (fw_dump.ops->fadump_get_metadata_size ?
316                  fw_dump.ops->fadump_get_metadata_size() : 0);
317         return size;
318 }
319
320 static void __init fadump_reserve_crash_area(unsigned long base,
321                                              unsigned long size)
322 {
323         struct memblock_region *reg;
324         unsigned long mstart, mend, msize;
325
326         for_each_memblock(memory, reg) {
327                 mstart = max_t(unsigned long, base, reg->base);
328                 mend = reg->base + reg->size;
329                 mend = min(base + size, mend);
330
331                 if (mstart < mend) {
332                         msize = mend - mstart;
333                         memblock_reserve(mstart, msize);
334                         pr_info("Reserved %ldMB of memory at %#016lx for saving crash dump\n",
335                                 (msize >> 20), mstart);
336                 }
337         }
338 }
339
340 int __init fadump_reserve_mem(void)
341 {
342         bool is_memblock_bottom_up = memblock_bottom_up();
343         u64 base, size, mem_boundary, align = PAGE_SIZE;
344         int ret = 1;
345
346         if (!fw_dump.fadump_enabled)
347                 return 0;
348
349         if (!fw_dump.fadump_supported) {
350                 pr_info("Firmware-Assisted Dump is not supported on this hardware\n");
351                 goto error_out;
352         }
353
354         /*
355          * Initialize boot memory size
356          * If dump is active then we have already calculated the size during
357          * first kernel.
358          */
359         if (!fw_dump.dump_active) {
360                 fw_dump.boot_memory_size =
361                         PAGE_ALIGN(fadump_calculate_reserve_size());
362 #ifdef CONFIG_CMA
363                 if (!fw_dump.nocma) {
364                         align = FADUMP_CMA_ALIGNMENT;
365                         fw_dump.boot_memory_size =
366                                 ALIGN(fw_dump.boot_memory_size, align);
367                 }
368 #endif
369         }
370
371         /*
372          * Calculate the memory boundary.
373          * If memory_limit is less than actual memory boundary then reserve
374          * the memory for fadump beyond the memory_limit and adjust the
375          * memory_limit accordingly, so that the running kernel can run with
376          * specified memory_limit.
377          */
378         if (memory_limit && memory_limit < memblock_end_of_DRAM()) {
379                 size = get_fadump_area_size();
380                 if ((memory_limit + size) < memblock_end_of_DRAM())
381                         memory_limit += size;
382                 else
383                         memory_limit = memblock_end_of_DRAM();
384                 printk(KERN_INFO "Adjusted memory_limit for firmware-assisted"
385                                 " dump, now %#016llx\n", memory_limit);
386         }
387         if (memory_limit)
388                 mem_boundary = memory_limit;
389         else
390                 mem_boundary = memblock_end_of_DRAM();
391
392         base = fw_dump.boot_memory_size;
393         size = get_fadump_area_size();
394         fw_dump.reserve_dump_area_size = size;
395         if (fw_dump.dump_active) {
396                 pr_info("Firmware-assisted dump is active.\n");
397
398 #ifdef CONFIG_HUGETLB_PAGE
399                 /*
400                  * FADump capture kernel doesn't care much about hugepages.
401                  * In fact, handling hugepages in capture kernel is asking for
402                  * trouble. So, disable HugeTLB support when fadump is active.
403                  */
404                 hugetlb_disabled = true;
405 #endif
406                 /*
407                  * If last boot has crashed then reserve all the memory
408                  * above boot_memory_size so that we don't touch it until
409                  * dump is written to disk by userspace tool. This memory
410                  * will be released for general use once the dump is saved.
411                  */
412                 size = mem_boundary - base;
413                 fadump_reserve_crash_area(base, size);
414
415                 pr_debug("fadumphdr_addr = %#016lx\n", fw_dump.fadumphdr_addr);
416                 pr_debug("Reserve dump area start address: 0x%lx\n",
417                          fw_dump.reserve_dump_area_start);
418         } else {
419                 /*
420                  * Reserve memory at an offset closer to bottom of the RAM to
421                  * minimize the impact of memory hot-remove operation.
422                  */
423                 memblock_set_bottom_up(true);
424                 base = memblock_find_in_range(base, mem_boundary, size, align);
425
426                 /* Restore the previous allocation mode */
427                 memblock_set_bottom_up(is_memblock_bottom_up);
428
429                 if (!base) {
430                         pr_err("Failed to find memory chunk for reservation!\n");
431                         goto error_out;
432                 }
433                 fw_dump.reserve_dump_area_start = base;
434
435                 /*
436                  * Calculate the kernel metadata address and register it with
437                  * f/w if the platform supports.
438                  */
439                 if (fw_dump.ops->fadump_setup_metadata &&
440                     (fw_dump.ops->fadump_setup_metadata(&fw_dump) < 0))
441                         goto error_out;
442
443                 if (memblock_reserve(base, size)) {
444                         pr_err("Failed to reserve memory!\n");
445                         goto error_out;
446                 }
447
448                 pr_info("Reserved %lldMB of memory at %#016llx (System RAM: %lldMB)\n",
449                         (size >> 20), base, (memblock_phys_mem_size() >> 20));
450
451                 ret = fadump_cma_init();
452         }
453
454         return ret;
455 error_out:
456         fw_dump.fadump_enabled = 0;
457         return 0;
458 }
459
460 unsigned long __init arch_reserved_kernel_pages(void)
461 {
462         return memblock_reserved_size() / PAGE_SIZE;
463 }
464
465 /* Look for fadump= cmdline option. */
466 static int __init early_fadump_param(char *p)
467 {
468         if (!p)
469                 return 1;
470
471         if (strncmp(p, "on", 2) == 0)
472                 fw_dump.fadump_enabled = 1;
473         else if (strncmp(p, "off", 3) == 0)
474                 fw_dump.fadump_enabled = 0;
475         else if (strncmp(p, "nocma", 5) == 0) {
476                 fw_dump.fadump_enabled = 1;
477                 fw_dump.nocma = 1;
478         }
479
480         return 0;
481 }
482 early_param("fadump", early_fadump_param);
483
484 /*
485  * Look for fadump_reserve_mem= cmdline option
486  * TODO: Remove references to 'fadump_reserve_mem=' parameter,
487  *       the sooner 'crashkernel=' parameter is accustomed to.
488  */
489 static int __init early_fadump_reserve_mem(char *p)
490 {
491         if (p)
492                 fw_dump.reserve_bootvar = memparse(p, &p);
493         return 0;
494 }
495 early_param("fadump_reserve_mem", early_fadump_reserve_mem);
496
497 void crash_fadump(struct pt_regs *regs, const char *str)
498 {
499         struct fadump_crash_info_header *fdh = NULL;
500         int old_cpu, this_cpu;
501
502         if (!should_fadump_crash())
503                 return;
504
505         /*
506          * old_cpu == -1 means this is the first CPU which has come here,
507          * go ahead and trigger fadump.
508          *
509          * old_cpu != -1 means some other CPU has already on it's way
510          * to trigger fadump, just keep looping here.
511          */
512         this_cpu = smp_processor_id();
513         old_cpu = cmpxchg(&crashing_cpu, -1, this_cpu);
514
515         if (old_cpu != -1) {
516                 /*
517                  * We can't loop here indefinitely. Wait as long as fadump
518                  * is in force. If we race with fadump un-registration this
519                  * loop will break and then we go down to normal panic path
520                  * and reboot. If fadump is in force the first crashing
521                  * cpu will definitely trigger fadump.
522                  */
523                 while (fw_dump.dump_registered)
524                         cpu_relax();
525                 return;
526         }
527
528         fdh = __va(fw_dump.fadumphdr_addr);
529         fdh->crashing_cpu = crashing_cpu;
530         crash_save_vmcoreinfo();
531
532         if (regs)
533                 fdh->regs = *regs;
534         else
535                 ppc_save_regs(&fdh->regs);
536
537         fdh->online_mask = *cpu_online_mask;
538
539         fw_dump.ops->fadump_trigger(fdh, str);
540 }
541
542 u32 *fadump_regs_to_elf_notes(u32 *buf, struct pt_regs *regs)
543 {
544         struct elf_prstatus prstatus;
545
546         memset(&prstatus, 0, sizeof(prstatus));
547         /*
548          * FIXME: How do i get PID? Do I really need it?
549          * prstatus.pr_pid = ????
550          */
551         elf_core_copy_kernel_regs(&prstatus.pr_reg, regs);
552         buf = append_elf_note(buf, CRASH_CORE_NOTE_NAME, NT_PRSTATUS,
553                               &prstatus, sizeof(prstatus));
554         return buf;
555 }
556
557 void fadump_update_elfcore_header(char *bufp)
558 {
559         struct elfhdr *elf;
560         struct elf_phdr *phdr;
561
562         elf = (struct elfhdr *)bufp;
563         bufp += sizeof(struct elfhdr);
564
565         /* First note is a place holder for cpu notes info. */
566         phdr = (struct elf_phdr *)bufp;
567
568         if (phdr->p_type == PT_NOTE) {
569                 phdr->p_paddr   = __pa(fw_dump.cpu_notes_buf_vaddr);
570                 phdr->p_offset  = phdr->p_paddr;
571                 phdr->p_filesz  = fw_dump.cpu_notes_buf_size;
572                 phdr->p_memsz = fw_dump.cpu_notes_buf_size;
573         }
574         return;
575 }
576
577 static void *fadump_alloc_buffer(unsigned long size)
578 {
579         unsigned long count, i;
580         struct page *page;
581         void *vaddr;
582
583         vaddr = alloc_pages_exact(size, GFP_KERNEL | __GFP_ZERO);
584         if (!vaddr)
585                 return NULL;
586
587         count = PAGE_ALIGN(size) / PAGE_SIZE;
588         page = virt_to_page(vaddr);
589         for (i = 0; i < count; i++)
590                 mark_page_reserved(page + i);
591         return vaddr;
592 }
593
594 static void fadump_free_buffer(unsigned long vaddr, unsigned long size)
595 {
596         free_reserved_area((void *)vaddr, (void *)(vaddr + size), -1, NULL);
597 }
598
599 s32 fadump_setup_cpu_notes_buf(u32 num_cpus)
600 {
601         /* Allocate buffer to hold cpu crash notes. */
602         fw_dump.cpu_notes_buf_size = num_cpus * sizeof(note_buf_t);
603         fw_dump.cpu_notes_buf_size = PAGE_ALIGN(fw_dump.cpu_notes_buf_size);
604         fw_dump.cpu_notes_buf_vaddr =
605                 (unsigned long)fadump_alloc_buffer(fw_dump.cpu_notes_buf_size);
606         if (!fw_dump.cpu_notes_buf_vaddr) {
607                 pr_err("Failed to allocate %ld bytes for CPU notes buffer\n",
608                        fw_dump.cpu_notes_buf_size);
609                 return -ENOMEM;
610         }
611
612         pr_debug("Allocated buffer for cpu notes of size %ld at 0x%lx\n",
613                  fw_dump.cpu_notes_buf_size,
614                  fw_dump.cpu_notes_buf_vaddr);
615         return 0;
616 }
617
618 void fadump_free_cpu_notes_buf(void)
619 {
620         if (!fw_dump.cpu_notes_buf_vaddr)
621                 return;
622
623         fadump_free_buffer(fw_dump.cpu_notes_buf_vaddr,
624                            fw_dump.cpu_notes_buf_size);
625         fw_dump.cpu_notes_buf_vaddr = 0;
626         fw_dump.cpu_notes_buf_size = 0;
627 }
628
629 static void fadump_free_mem_ranges(struct fadump_mrange_info *mrange_info)
630 {
631         kfree(mrange_info->mem_ranges);
632         mrange_info->mem_ranges = NULL;
633         mrange_info->mem_ranges_sz = 0;
634         mrange_info->max_mem_ranges = 0;
635 }
636
637 /*
638  * Allocate or reallocate mem_ranges array in incremental units
639  * of PAGE_SIZE.
640  */
641 static int fadump_alloc_mem_ranges(struct fadump_mrange_info *mrange_info)
642 {
643         struct fadump_memory_range *new_array;
644         u64 new_size;
645
646         new_size = mrange_info->mem_ranges_sz + PAGE_SIZE;
647         pr_debug("Allocating %llu bytes of memory for %s memory ranges\n",
648                  new_size, mrange_info->name);
649
650         new_array = krealloc(mrange_info->mem_ranges, new_size, GFP_KERNEL);
651         if (new_array == NULL) {
652                 pr_err("Insufficient memory for setting up %s memory ranges\n",
653                        mrange_info->name);
654                 fadump_free_mem_ranges(mrange_info);
655                 return -ENOMEM;
656         }
657
658         mrange_info->mem_ranges = new_array;
659         mrange_info->mem_ranges_sz = new_size;
660         mrange_info->max_mem_ranges = (new_size /
661                                        sizeof(struct fadump_memory_range));
662         return 0;
663 }
664
665 static inline int fadump_add_mem_range(struct fadump_mrange_info *mrange_info,
666                                        u64 base, u64 end)
667 {
668         struct fadump_memory_range *mem_ranges = mrange_info->mem_ranges;
669         bool is_adjacent = false;
670         u64 start, size;
671
672         if (base == end)
673                 return 0;
674
675         /*
676          * Fold adjacent memory ranges to bring down the memory ranges/
677          * PT_LOAD segments count.
678          */
679         if (mrange_info->mem_range_cnt) {
680                 start = mem_ranges[mrange_info->mem_range_cnt - 1].base;
681                 size  = mem_ranges[mrange_info->mem_range_cnt - 1].size;
682
683                 if ((start + size) == base)
684                         is_adjacent = true;
685         }
686         if (!is_adjacent) {
687                 /* resize the array on reaching the limit */
688                 if (mrange_info->mem_range_cnt == mrange_info->max_mem_ranges) {
689                         int ret;
690
691                         ret = fadump_alloc_mem_ranges(mrange_info);
692                         if (ret)
693                                 return ret;
694
695                         /* Update to the new resized array */
696                         mem_ranges = mrange_info->mem_ranges;
697                 }
698
699                 start = base;
700                 mem_ranges[mrange_info->mem_range_cnt].base = start;
701                 mrange_info->mem_range_cnt++;
702         }
703
704         mem_ranges[mrange_info->mem_range_cnt - 1].size = (end - start);
705         pr_debug("%s_memory_range[%d] [%#016llx-%#016llx], %#llx bytes\n",
706                  mrange_info->name, (mrange_info->mem_range_cnt - 1),
707                  start, end - 1, (end - start));
708         return 0;
709 }
710
711 static int fadump_exclude_reserved_area(u64 start, u64 end)
712 {
713         u64 ra_start, ra_end;
714         int ret = 0;
715
716         ra_start = fw_dump.reserve_dump_area_start;
717         ra_end = ra_start + fw_dump.reserve_dump_area_size;
718
719         if ((ra_start < end) && (ra_end > start)) {
720                 if ((start < ra_start) && (end > ra_end)) {
721                         ret = fadump_add_mem_range(&crash_mrange_info,
722                                                    start, ra_start);
723                         if (ret)
724                                 return ret;
725
726                         ret = fadump_add_mem_range(&crash_mrange_info,
727                                                    ra_end, end);
728                 } else if (start < ra_start) {
729                         ret = fadump_add_mem_range(&crash_mrange_info,
730                                                    start, ra_start);
731                 } else if (ra_end < end) {
732                         ret = fadump_add_mem_range(&crash_mrange_info,
733                                                    ra_end, end);
734                 }
735         } else
736                 ret = fadump_add_mem_range(&crash_mrange_info, start, end);
737
738         return ret;
739 }
740
741 static int fadump_init_elfcore_header(char *bufp)
742 {
743         struct elfhdr *elf;
744
745         elf = (struct elfhdr *) bufp;
746         bufp += sizeof(struct elfhdr);
747         memcpy(elf->e_ident, ELFMAG, SELFMAG);
748         elf->e_ident[EI_CLASS] = ELF_CLASS;
749         elf->e_ident[EI_DATA] = ELF_DATA;
750         elf->e_ident[EI_VERSION] = EV_CURRENT;
751         elf->e_ident[EI_OSABI] = ELF_OSABI;
752         memset(elf->e_ident+EI_PAD, 0, EI_NIDENT-EI_PAD);
753         elf->e_type = ET_CORE;
754         elf->e_machine = ELF_ARCH;
755         elf->e_version = EV_CURRENT;
756         elf->e_entry = 0;
757         elf->e_phoff = sizeof(struct elfhdr);
758         elf->e_shoff = 0;
759 #if defined(_CALL_ELF)
760         elf->e_flags = _CALL_ELF;
761 #else
762         elf->e_flags = 0;
763 #endif
764         elf->e_ehsize = sizeof(struct elfhdr);
765         elf->e_phentsize = sizeof(struct elf_phdr);
766         elf->e_phnum = 0;
767         elf->e_shentsize = 0;
768         elf->e_shnum = 0;
769         elf->e_shstrndx = 0;
770
771         return 0;
772 }
773
774 /*
775  * Traverse through memblock structure and setup crash memory ranges. These
776  * ranges will be used create PT_LOAD program headers in elfcore header.
777  */
778 static int fadump_setup_crash_memory_ranges(void)
779 {
780         struct memblock_region *reg;
781         u64 start, end;
782         int ret;
783
784         pr_debug("Setup crash memory ranges.\n");
785         crash_mrange_info.mem_range_cnt = 0;
786
787         /*
788          * add the first memory chunk (RMA_START through boot_memory_size) as
789          * a separate memory chunk. The reason is, at the time crash firmware
790          * will move the content of this memory chunk to different location
791          * specified during fadump registration. We need to create a separate
792          * program header for this chunk with the correct offset.
793          */
794         ret = fadump_add_mem_range(&crash_mrange_info,
795                                    RMA_START, fw_dump.boot_memory_size);
796         if (ret)
797                 return ret;
798
799         for_each_memblock(memory, reg) {
800                 start = (u64)reg->base;
801                 end = start + (u64)reg->size;
802
803                 /*
804                  * skip the first memory chunk that is already added (RMA_START
805                  * through boot_memory_size). This logic needs a relook if and
806                  * when RMA_START changes to a non-zero value.
807                  */
808                 BUILD_BUG_ON(RMA_START != 0);
809                 if (start < fw_dump.boot_memory_size) {
810                         if (end > fw_dump.boot_memory_size)
811                                 start = fw_dump.boot_memory_size;
812                         else
813                                 continue;
814                 }
815
816                 /* add this range excluding the reserved dump area. */
817                 ret = fadump_exclude_reserved_area(start, end);
818                 if (ret)
819                         return ret;
820         }
821
822         return 0;
823 }
824
825 /*
826  * If the given physical address falls within the boot memory region then
827  * return the relocated address that points to the dump region reserved
828  * for saving initial boot memory contents.
829  */
830 static inline unsigned long fadump_relocate(unsigned long paddr)
831 {
832         if (paddr > RMA_START && paddr < fw_dump.boot_memory_size)
833                 return fw_dump.boot_mem_dest_addr + paddr;
834         else
835                 return paddr;
836 }
837
838 static int fadump_create_elfcore_headers(char *bufp)
839 {
840         struct elfhdr *elf;
841         struct elf_phdr *phdr;
842         int i;
843
844         fadump_init_elfcore_header(bufp);
845         elf = (struct elfhdr *)bufp;
846         bufp += sizeof(struct elfhdr);
847
848         /*
849          * setup ELF PT_NOTE, place holder for cpu notes info. The notes info
850          * will be populated during second kernel boot after crash. Hence
851          * this PT_NOTE will always be the first elf note.
852          *
853          * NOTE: Any new ELF note addition should be placed after this note.
854          */
855         phdr = (struct elf_phdr *)bufp;
856         bufp += sizeof(struct elf_phdr);
857         phdr->p_type = PT_NOTE;
858         phdr->p_flags = 0;
859         phdr->p_vaddr = 0;
860         phdr->p_align = 0;
861
862         phdr->p_offset = 0;
863         phdr->p_paddr = 0;
864         phdr->p_filesz = 0;
865         phdr->p_memsz = 0;
866
867         (elf->e_phnum)++;
868
869         /* setup ELF PT_NOTE for vmcoreinfo */
870         phdr = (struct elf_phdr *)bufp;
871         bufp += sizeof(struct elf_phdr);
872         phdr->p_type    = PT_NOTE;
873         phdr->p_flags   = 0;
874         phdr->p_vaddr   = 0;
875         phdr->p_align   = 0;
876
877         phdr->p_paddr   = fadump_relocate(paddr_vmcoreinfo_note());
878         phdr->p_offset  = phdr->p_paddr;
879         phdr->p_memsz   = phdr->p_filesz = VMCOREINFO_NOTE_SIZE;
880
881         /* Increment number of program headers. */
882         (elf->e_phnum)++;
883
884         /* setup PT_LOAD sections. */
885
886         for (i = 0; i < crash_mrange_info.mem_range_cnt; i++) {
887                 u64 mbase, msize;
888
889                 mbase = crash_mrange_info.mem_ranges[i].base;
890                 msize = crash_mrange_info.mem_ranges[i].size;
891                 if (!msize)
892                         continue;
893
894                 phdr = (struct elf_phdr *)bufp;
895                 bufp += sizeof(struct elf_phdr);
896                 phdr->p_type    = PT_LOAD;
897                 phdr->p_flags   = PF_R|PF_W|PF_X;
898                 phdr->p_offset  = mbase;
899
900                 if (mbase == RMA_START) {
901                         /*
902                          * The entire RMA region will be moved by firmware
903                          * to the specified destination_address. Hence set
904                          * the correct offset.
905                          */
906                         phdr->p_offset = fw_dump.boot_mem_dest_addr;
907                 }
908
909                 phdr->p_paddr = mbase;
910                 phdr->p_vaddr = (unsigned long)__va(mbase);
911                 phdr->p_filesz = msize;
912                 phdr->p_memsz = msize;
913                 phdr->p_align = 0;
914
915                 /* Increment number of program headers. */
916                 (elf->e_phnum)++;
917         }
918         return 0;
919 }
920
921 static unsigned long init_fadump_header(unsigned long addr)
922 {
923         struct fadump_crash_info_header *fdh;
924
925         if (!addr)
926                 return 0;
927
928         fdh = __va(addr);
929         addr += sizeof(struct fadump_crash_info_header);
930
931         memset(fdh, 0, sizeof(struct fadump_crash_info_header));
932         fdh->magic_number = FADUMP_CRASH_INFO_MAGIC;
933         fdh->elfcorehdr_addr = addr;
934         /* We will set the crashing cpu id in crash_fadump() during crash. */
935         fdh->crashing_cpu = FADUMP_CPU_UNKNOWN;
936
937         return addr;
938 }
939
940 static int register_fadump(void)
941 {
942         unsigned long addr;
943         void *vaddr;
944         int ret;
945
946         /*
947          * If no memory is reserved then we can not register for firmware-
948          * assisted dump.
949          */
950         if (!fw_dump.reserve_dump_area_size)
951                 return -ENODEV;
952
953         ret = fadump_setup_crash_memory_ranges();
954         if (ret)
955                 return ret;
956
957         addr = fw_dump.fadumphdr_addr;
958
959         /* Initialize fadump crash info header. */
960         addr = init_fadump_header(addr);
961         vaddr = __va(addr);
962
963         pr_debug("Creating ELF core headers at %#016lx\n", addr);
964         fadump_create_elfcore_headers(vaddr);
965
966         /* register the future kernel dump with firmware. */
967         pr_debug("Registering for firmware-assisted kernel dump...\n");
968         return fw_dump.ops->fadump_register(&fw_dump);
969 }
970
971 void fadump_cleanup(void)
972 {
973         if (!fw_dump.fadump_supported)
974                 return;
975
976         /* Invalidate the registration only if dump is active. */
977         if (fw_dump.dump_active) {
978                 pr_debug("Invalidating firmware-assisted dump registration\n");
979                 fw_dump.ops->fadump_invalidate(&fw_dump);
980         } else if (fw_dump.dump_registered) {
981                 /* Un-register Firmware-assisted dump if it was registered. */
982                 fw_dump.ops->fadump_unregister(&fw_dump);
983                 fadump_free_mem_ranges(&crash_mrange_info);
984         }
985
986         if (fw_dump.ops->fadump_cleanup)
987                 fw_dump.ops->fadump_cleanup(&fw_dump);
988 }
989
990 static void fadump_free_reserved_memory(unsigned long start_pfn,
991                                         unsigned long end_pfn)
992 {
993         unsigned long pfn;
994         unsigned long time_limit = jiffies + HZ;
995
996         pr_info("freeing reserved memory (0x%llx - 0x%llx)\n",
997                 PFN_PHYS(start_pfn), PFN_PHYS(end_pfn));
998
999         for (pfn = start_pfn; pfn < end_pfn; pfn++) {
1000                 free_reserved_page(pfn_to_page(pfn));
1001
1002                 if (time_after(jiffies, time_limit)) {
1003                         cond_resched();
1004                         time_limit = jiffies + HZ;
1005                 }
1006         }
1007 }
1008
1009 /*
1010  * Skip memory holes and free memory that was actually reserved.
1011  */
1012 static void fadump_release_reserved_area(unsigned long start, unsigned long end)
1013 {
1014         struct memblock_region *reg;
1015         unsigned long tstart, tend;
1016         unsigned long start_pfn = PHYS_PFN(start);
1017         unsigned long end_pfn = PHYS_PFN(end);
1018
1019         for_each_memblock(memory, reg) {
1020                 tstart = max(start_pfn, memblock_region_memory_base_pfn(reg));
1021                 tend = min(end_pfn, memblock_region_memory_end_pfn(reg));
1022                 if (tstart < tend) {
1023                         fadump_free_reserved_memory(tstart, tend);
1024
1025                         if (tend == end_pfn)
1026                                 break;
1027
1028                         start_pfn = tend + 1;
1029                 }
1030         }
1031 }
1032
1033 /*
1034  * Release the memory that was reserved in early boot to preserve the memory
1035  * contents. The released memory will be available for general use.
1036  */
1037 static void fadump_release_memory(unsigned long begin, unsigned long end)
1038 {
1039         unsigned long ra_start, ra_end;
1040
1041         ra_start = fw_dump.reserve_dump_area_start;
1042         ra_end = ra_start + fw_dump.reserve_dump_area_size;
1043
1044         /*
1045          * exclude the dump reserve area. Will reuse it for next
1046          * fadump registration.
1047          */
1048         if (begin < ra_end && end > ra_start) {
1049                 if (begin < ra_start)
1050                         fadump_release_reserved_area(begin, ra_start);
1051                 if (end > ra_end)
1052                         fadump_release_reserved_area(ra_end, end);
1053         } else
1054                 fadump_release_reserved_area(begin, end);
1055 }
1056
1057 static void fadump_invalidate_release_mem(void)
1058 {
1059         mutex_lock(&fadump_mutex);
1060         if (!fw_dump.dump_active) {
1061                 mutex_unlock(&fadump_mutex);
1062                 return;
1063         }
1064
1065         fadump_cleanup();
1066         mutex_unlock(&fadump_mutex);
1067
1068         fadump_release_memory(fw_dump.boot_memory_size, memblock_end_of_DRAM());
1069         fadump_free_cpu_notes_buf();
1070
1071         /*
1072          * Setup kernel metadata and initialize the kernel dump
1073          * memory structure for FADump re-registration.
1074          */
1075         if (fw_dump.ops->fadump_setup_metadata &&
1076             (fw_dump.ops->fadump_setup_metadata(&fw_dump) < 0))
1077                 pr_warn("Failed to setup kernel metadata!\n");
1078         fw_dump.ops->fadump_init_mem_struct(&fw_dump);
1079 }
1080
1081 static ssize_t fadump_release_memory_store(struct kobject *kobj,
1082                                         struct kobj_attribute *attr,
1083                                         const char *buf, size_t count)
1084 {
1085         int input = -1;
1086
1087         if (!fw_dump.dump_active)
1088                 return -EPERM;
1089
1090         if (kstrtoint(buf, 0, &input))
1091                 return -EINVAL;
1092
1093         if (input == 1) {
1094                 /*
1095                  * Take away the '/proc/vmcore'. We are releasing the dump
1096                  * memory, hence it will not be valid anymore.
1097                  */
1098 #ifdef CONFIG_PROC_VMCORE
1099                 vmcore_cleanup();
1100 #endif
1101                 fadump_invalidate_release_mem();
1102
1103         } else
1104                 return -EINVAL;
1105         return count;
1106 }
1107
1108 static ssize_t fadump_enabled_show(struct kobject *kobj,
1109                                         struct kobj_attribute *attr,
1110                                         char *buf)
1111 {
1112         return sprintf(buf, "%d\n", fw_dump.fadump_enabled);
1113 }
1114
1115 static ssize_t fadump_register_show(struct kobject *kobj,
1116                                         struct kobj_attribute *attr,
1117                                         char *buf)
1118 {
1119         return sprintf(buf, "%d\n", fw_dump.dump_registered);
1120 }
1121
1122 static ssize_t fadump_register_store(struct kobject *kobj,
1123                                         struct kobj_attribute *attr,
1124                                         const char *buf, size_t count)
1125 {
1126         int ret = 0;
1127         int input = -1;
1128
1129         if (!fw_dump.fadump_enabled || fw_dump.dump_active)
1130                 return -EPERM;
1131
1132         if (kstrtoint(buf, 0, &input))
1133                 return -EINVAL;
1134
1135         mutex_lock(&fadump_mutex);
1136
1137         switch (input) {
1138         case 0:
1139                 if (fw_dump.dump_registered == 0) {
1140                         goto unlock_out;
1141                 }
1142
1143                 /* Un-register Firmware-assisted dump */
1144                 pr_debug("Un-register firmware-assisted dump\n");
1145                 fw_dump.ops->fadump_unregister(&fw_dump);
1146                 break;
1147         case 1:
1148                 if (fw_dump.dump_registered == 1) {
1149                         /* Un-register Firmware-assisted dump */
1150                         fw_dump.ops->fadump_unregister(&fw_dump);
1151                 }
1152                 /* Register Firmware-assisted dump */
1153                 ret = register_fadump();
1154                 break;
1155         default:
1156                 ret = -EINVAL;
1157                 break;
1158         }
1159
1160 unlock_out:
1161         mutex_unlock(&fadump_mutex);
1162         return ret < 0 ? ret : count;
1163 }
1164
1165 static int fadump_region_show(struct seq_file *m, void *private)
1166 {
1167         if (!fw_dump.fadump_enabled)
1168                 return 0;
1169
1170         mutex_lock(&fadump_mutex);
1171         fw_dump.ops->fadump_region_show(&fw_dump, m);
1172         mutex_unlock(&fadump_mutex);
1173         return 0;
1174 }
1175
1176 static struct kobj_attribute fadump_release_attr = __ATTR(fadump_release_mem,
1177                                                 0200, NULL,
1178                                                 fadump_release_memory_store);
1179 static struct kobj_attribute fadump_attr = __ATTR(fadump_enabled,
1180                                                 0444, fadump_enabled_show,
1181                                                 NULL);
1182 static struct kobj_attribute fadump_register_attr = __ATTR(fadump_registered,
1183                                                 0644, fadump_register_show,
1184                                                 fadump_register_store);
1185
1186 DEFINE_SHOW_ATTRIBUTE(fadump_region);
1187
1188 static void fadump_init_files(void)
1189 {
1190         struct dentry *debugfs_file;
1191         int rc = 0;
1192
1193         rc = sysfs_create_file(kernel_kobj, &fadump_attr.attr);
1194         if (rc)
1195                 printk(KERN_ERR "fadump: unable to create sysfs file"
1196                         " fadump_enabled (%d)\n", rc);
1197
1198         rc = sysfs_create_file(kernel_kobj, &fadump_register_attr.attr);
1199         if (rc)
1200                 printk(KERN_ERR "fadump: unable to create sysfs file"
1201                         " fadump_registered (%d)\n", rc);
1202
1203         debugfs_file = debugfs_create_file("fadump_region", 0444,
1204                                         powerpc_debugfs_root, NULL,
1205                                         &fadump_region_fops);
1206         if (!debugfs_file)
1207                 printk(KERN_ERR "fadump: unable to create debugfs file"
1208                                 " fadump_region\n");
1209
1210         if (fw_dump.dump_active) {
1211                 rc = sysfs_create_file(kernel_kobj, &fadump_release_attr.attr);
1212                 if (rc)
1213                         printk(KERN_ERR "fadump: unable to create sysfs file"
1214                                 " fadump_release_mem (%d)\n", rc);
1215         }
1216         return;
1217 }
1218
1219 /*
1220  * Prepare for firmware-assisted dump.
1221  */
1222 int __init setup_fadump(void)
1223 {
1224         if (!fw_dump.fadump_enabled)
1225                 return 0;
1226
1227         if (!fw_dump.fadump_supported) {
1228                 printk(KERN_ERR "Firmware-assisted dump is not supported on"
1229                         " this hardware\n");
1230                 return 0;
1231         }
1232
1233         fadump_show_config();
1234         /*
1235          * If dump data is available then see if it is valid and prepare for
1236          * saving it to the disk.
1237          */
1238         if (fw_dump.dump_active) {
1239                 /*
1240                  * if dump process fails then invalidate the registration
1241                  * and release memory before proceeding for re-registration.
1242                  */
1243                 if (fw_dump.ops->fadump_process(&fw_dump) < 0)
1244                         fadump_invalidate_release_mem();
1245         }
1246         /* Initialize the kernel dump memory structure for FAD registration. */
1247         else if (fw_dump.reserve_dump_area_size)
1248                 fw_dump.ops->fadump_init_mem_struct(&fw_dump);
1249
1250         fadump_init_files();
1251
1252         return 1;
1253 }
1254 subsys_initcall(setup_fadump);