Linux-libre 4.19.116-gnu
[librecmc/linux-libre.git] / arch / powerpc / kernel / fadump.c
1 /*
2  * Firmware Assisted dump: A robust mechanism to get reliable kernel crash
3  * dump with assistance from firmware. This approach does not use kexec,
4  * instead firmware assists in booting the kdump kernel while preserving
5  * memory contents. The most of the code implementation has been adapted
6  * from phyp assisted dump implementation written by Linas Vepstas and
7  * Manish Ahuja
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
22  *
23  * Copyright 2011 IBM Corporation
24  * Author: Mahesh Salgaonkar <mahesh@linux.vnet.ibm.com>
25  */
26
27 #undef DEBUG
28 #define pr_fmt(fmt) "fadump: " fmt
29
30 #include <linux/string.h>
31 #include <linux/memblock.h>
32 #include <linux/delay.h>
33 #include <linux/seq_file.h>
34 #include <linux/crash_dump.h>
35 #include <linux/kobject.h>
36 #include <linux/sysfs.h>
37 #include <linux/slab.h>
38
39 #include <asm/debugfs.h>
40 #include <asm/page.h>
41 #include <asm/prom.h>
42 #include <asm/rtas.h>
43 #include <asm/fadump.h>
44 #include <asm/setup.h>
45
46 static struct fw_dump fw_dump;
47 static struct fadump_mem_struct fdm;
48 static const struct fadump_mem_struct *fdm_active;
49
50 static DEFINE_MUTEX(fadump_mutex);
51 struct fad_crash_memory_ranges *crash_memory_ranges;
52 int crash_memory_ranges_size;
53 int crash_mem_ranges;
54 int max_crash_mem_ranges;
55
56 /* Scan the Firmware Assisted dump configuration details. */
57 int __init early_init_dt_scan_fw_dump(unsigned long node,
58                         const char *uname, int depth, void *data)
59 {
60         const __be32 *sections;
61         int i, num_sections;
62         int size;
63         const __be32 *token;
64
65         if (depth != 1 || strcmp(uname, "rtas") != 0)
66                 return 0;
67
68         /*
69          * Check if Firmware Assisted dump is supported. if yes, check
70          * if dump has been initiated on last reboot.
71          */
72         token = of_get_flat_dt_prop(node, "ibm,configure-kernel-dump", NULL);
73         if (!token)
74                 return 1;
75
76         fw_dump.fadump_supported = 1;
77         fw_dump.ibm_configure_kernel_dump = be32_to_cpu(*token);
78
79         /*
80          * The 'ibm,kernel-dump' rtas node is present only if there is
81          * dump data waiting for us.
82          */
83         fdm_active = of_get_flat_dt_prop(node, "ibm,kernel-dump", NULL);
84         if (fdm_active)
85                 fw_dump.dump_active = 1;
86
87         /* Get the sizes required to store dump data for the firmware provided
88          * dump sections.
89          * For each dump section type supported, a 32bit cell which defines
90          * the ID of a supported section followed by two 32 bit cells which
91          * gives teh size of the section in bytes.
92          */
93         sections = of_get_flat_dt_prop(node, "ibm,configure-kernel-dump-sizes",
94                                         &size);
95
96         if (!sections)
97                 return 1;
98
99         num_sections = size / (3 * sizeof(u32));
100
101         for (i = 0; i < num_sections; i++, sections += 3) {
102                 u32 type = (u32)of_read_number(sections, 1);
103
104                 switch (type) {
105                 case FADUMP_CPU_STATE_DATA:
106                         fw_dump.cpu_state_data_size =
107                                         of_read_ulong(&sections[1], 2);
108                         break;
109                 case FADUMP_HPTE_REGION:
110                         fw_dump.hpte_region_size =
111                                         of_read_ulong(&sections[1], 2);
112                         break;
113                 }
114         }
115
116         return 1;
117 }
118
119 /*
120  * If fadump is registered, check if the memory provided
121  * falls within boot memory area and reserved memory area.
122  */
123 int is_fadump_memory_area(u64 addr, ulong size)
124 {
125         u64 d_start = fw_dump.reserve_dump_area_start;
126         u64 d_end = d_start + fw_dump.reserve_dump_area_size;
127
128         if (!fw_dump.dump_registered)
129                 return 0;
130
131         if (((addr + size) > d_start) && (addr <= d_end))
132                 return 1;
133
134         return (addr + size) > RMA_START && addr <= fw_dump.boot_memory_size;
135 }
136
137 int should_fadump_crash(void)
138 {
139         if (!fw_dump.dump_registered || !fw_dump.fadumphdr_addr)
140                 return 0;
141         return 1;
142 }
143
144 int is_fadump_active(void)
145 {
146         return fw_dump.dump_active;
147 }
148
149 /*
150  * Returns 1, if there are no holes in boot memory area,
151  * 0 otherwise.
152  */
153 static int is_boot_memory_area_contiguous(void)
154 {
155         struct memblock_region *reg;
156         unsigned long tstart, tend;
157         unsigned long start_pfn = PHYS_PFN(RMA_START);
158         unsigned long end_pfn = PHYS_PFN(RMA_START + fw_dump.boot_memory_size);
159         unsigned int ret = 0;
160
161         for_each_memblock(memory, reg) {
162                 tstart = max(start_pfn, memblock_region_memory_base_pfn(reg));
163                 tend = min(end_pfn, memblock_region_memory_end_pfn(reg));
164                 if (tstart < tend) {
165                         /* Memory hole from start_pfn to tstart */
166                         if (tstart > start_pfn)
167                                 break;
168
169                         if (tend == end_pfn) {
170                                 ret = 1;
171                                 break;
172                         }
173
174                         start_pfn = tend + 1;
175                 }
176         }
177
178         return ret;
179 }
180
181 /* Print firmware assisted dump configurations for debugging purpose. */
182 static void fadump_show_config(void)
183 {
184         pr_debug("Support for firmware-assisted dump (fadump): %s\n",
185                         (fw_dump.fadump_supported ? "present" : "no support"));
186
187         if (!fw_dump.fadump_supported)
188                 return;
189
190         pr_debug("Fadump enabled    : %s\n",
191                                 (fw_dump.fadump_enabled ? "yes" : "no"));
192         pr_debug("Dump Active       : %s\n",
193                                 (fw_dump.dump_active ? "yes" : "no"));
194         pr_debug("Dump section sizes:\n");
195         pr_debug("    CPU state data size: %lx\n", fw_dump.cpu_state_data_size);
196         pr_debug("    HPTE region size   : %lx\n", fw_dump.hpte_region_size);
197         pr_debug("Boot memory size  : %lx\n", fw_dump.boot_memory_size);
198 }
199
200 static unsigned long init_fadump_mem_struct(struct fadump_mem_struct *fdm,
201                                 unsigned long addr)
202 {
203         if (!fdm)
204                 return 0;
205
206         memset(fdm, 0, sizeof(struct fadump_mem_struct));
207         addr = addr & PAGE_MASK;
208
209         fdm->header.dump_format_version = cpu_to_be32(0x00000001);
210         fdm->header.dump_num_sections = cpu_to_be16(3);
211         fdm->header.dump_status_flag = 0;
212         fdm->header.offset_first_dump_section =
213                 cpu_to_be32((u32)offsetof(struct fadump_mem_struct, cpu_state_data));
214
215         /*
216          * Fields for disk dump option.
217          * We are not using disk dump option, hence set these fields to 0.
218          */
219         fdm->header.dd_block_size = 0;
220         fdm->header.dd_block_offset = 0;
221         fdm->header.dd_num_blocks = 0;
222         fdm->header.dd_offset_disk_path = 0;
223
224         /* set 0 to disable an automatic dump-reboot. */
225         fdm->header.max_time_auto = 0;
226
227         /* Kernel dump sections */
228         /* cpu state data section. */
229         fdm->cpu_state_data.request_flag = cpu_to_be32(FADUMP_REQUEST_FLAG);
230         fdm->cpu_state_data.source_data_type = cpu_to_be16(FADUMP_CPU_STATE_DATA);
231         fdm->cpu_state_data.source_address = 0;
232         fdm->cpu_state_data.source_len = cpu_to_be64(fw_dump.cpu_state_data_size);
233         fdm->cpu_state_data.destination_address = cpu_to_be64(addr);
234         addr += fw_dump.cpu_state_data_size;
235
236         /* hpte region section */
237         fdm->hpte_region.request_flag = cpu_to_be32(FADUMP_REQUEST_FLAG);
238         fdm->hpte_region.source_data_type = cpu_to_be16(FADUMP_HPTE_REGION);
239         fdm->hpte_region.source_address = 0;
240         fdm->hpte_region.source_len = cpu_to_be64(fw_dump.hpte_region_size);
241         fdm->hpte_region.destination_address = cpu_to_be64(addr);
242         addr += fw_dump.hpte_region_size;
243
244         /* RMA region section */
245         fdm->rmr_region.request_flag = cpu_to_be32(FADUMP_REQUEST_FLAG);
246         fdm->rmr_region.source_data_type = cpu_to_be16(FADUMP_REAL_MODE_REGION);
247         fdm->rmr_region.source_address = cpu_to_be64(RMA_START);
248         fdm->rmr_region.source_len = cpu_to_be64(fw_dump.boot_memory_size);
249         fdm->rmr_region.destination_address = cpu_to_be64(addr);
250         addr += fw_dump.boot_memory_size;
251
252         return addr;
253 }
254
255 /**
256  * fadump_calculate_reserve_size(): reserve variable boot area 5% of System RAM
257  *
258  * Function to find the largest memory size we need to reserve during early
259  * boot process. This will be the size of the memory that is required for a
260  * kernel to boot successfully.
261  *
262  * This function has been taken from phyp-assisted dump feature implementation.
263  *
264  * returns larger of 256MB or 5% rounded down to multiples of 256MB.
265  *
266  * TODO: Come up with better approach to find out more accurate memory size
267  * that is required for a kernel to boot successfully.
268  *
269  */
270 static inline unsigned long fadump_calculate_reserve_size(void)
271 {
272         int ret;
273         unsigned long long base, size;
274
275         if (fw_dump.reserve_bootvar)
276                 pr_warn("'fadump_reserve_mem=' parameter is deprecated in favor of 'crashkernel=' parameter.\n");
277
278         /*
279          * Check if the size is specified through crashkernel= cmdline
280          * option. If yes, then use that but ignore base as fadump reserves
281          * memory at a predefined offset.
282          */
283         ret = parse_crashkernel(boot_command_line, memblock_phys_mem_size(),
284                                 &size, &base);
285         if (ret == 0 && size > 0) {
286                 unsigned long max_size;
287
288                 if (fw_dump.reserve_bootvar)
289                         pr_info("Using 'crashkernel=' parameter for memory reservation.\n");
290
291                 fw_dump.reserve_bootvar = (unsigned long)size;
292
293                 /*
294                  * Adjust if the boot memory size specified is above
295                  * the upper limit.
296                  */
297                 max_size = memblock_phys_mem_size() / MAX_BOOT_MEM_RATIO;
298                 if (fw_dump.reserve_bootvar > max_size) {
299                         fw_dump.reserve_bootvar = max_size;
300                         pr_info("Adjusted boot memory size to %luMB\n",
301                                 (fw_dump.reserve_bootvar >> 20));
302                 }
303
304                 return fw_dump.reserve_bootvar;
305         } else if (fw_dump.reserve_bootvar) {
306                 /*
307                  * 'fadump_reserve_mem=' is being used to reserve memory
308                  * for firmware-assisted dump.
309                  */
310                 return fw_dump.reserve_bootvar;
311         }
312
313         /* divide by 20 to get 5% of value */
314         size = memblock_phys_mem_size() / 20;
315
316         /* round it down in multiples of 256 */
317         size = size & ~0x0FFFFFFFUL;
318
319         /* Truncate to memory_limit. We don't want to over reserve the memory.*/
320         if (memory_limit && size > memory_limit)
321                 size = memory_limit;
322
323         return (size > MIN_BOOT_MEM ? size : MIN_BOOT_MEM);
324 }
325
326 /*
327  * Calculate the total memory size required to be reserved for
328  * firmware-assisted dump registration.
329  */
330 static unsigned long get_fadump_area_size(void)
331 {
332         unsigned long size = 0;
333
334         size += fw_dump.cpu_state_data_size;
335         size += fw_dump.hpte_region_size;
336         size += fw_dump.boot_memory_size;
337         size += sizeof(struct fadump_crash_info_header);
338         size += sizeof(struct elfhdr); /* ELF core header.*/
339         size += sizeof(struct elf_phdr); /* place holder for cpu notes */
340         /* Program headers for crash memory regions. */
341         size += sizeof(struct elf_phdr) * (memblock_num_regions(memory) + 2);
342
343         size = PAGE_ALIGN(size);
344         return size;
345 }
346
347 static void __init fadump_reserve_crash_area(unsigned long base,
348                                              unsigned long size)
349 {
350         struct memblock_region *reg;
351         unsigned long mstart, mend, msize;
352
353         for_each_memblock(memory, reg) {
354                 mstart = max_t(unsigned long, base, reg->base);
355                 mend = reg->base + reg->size;
356                 mend = min(base + size, mend);
357
358                 if (mstart < mend) {
359                         msize = mend - mstart;
360                         memblock_reserve(mstart, msize);
361                         pr_info("Reserved %ldMB of memory at %#016lx for saving crash dump\n",
362                                 (msize >> 20), mstart);
363                 }
364         }
365 }
366
367 int __init fadump_reserve_mem(void)
368 {
369         unsigned long base, size, memory_boundary;
370
371         if (!fw_dump.fadump_enabled)
372                 return 0;
373
374         if (!fw_dump.fadump_supported) {
375                 printk(KERN_INFO "Firmware-assisted dump is not supported on"
376                                 " this hardware\n");
377                 fw_dump.fadump_enabled = 0;
378                 return 0;
379         }
380         /*
381          * Initialize boot memory size
382          * If dump is active then we have already calculated the size during
383          * first kernel.
384          */
385         if (fdm_active)
386                 fw_dump.boot_memory_size = be64_to_cpu(fdm_active->rmr_region.source_len);
387         else
388                 fw_dump.boot_memory_size = fadump_calculate_reserve_size();
389
390         /*
391          * Calculate the memory boundary.
392          * If memory_limit is less than actual memory boundary then reserve
393          * the memory for fadump beyond the memory_limit and adjust the
394          * memory_limit accordingly, so that the running kernel can run with
395          * specified memory_limit.
396          */
397         if (memory_limit && memory_limit < memblock_end_of_DRAM()) {
398                 size = get_fadump_area_size();
399                 if ((memory_limit + size) < memblock_end_of_DRAM())
400                         memory_limit += size;
401                 else
402                         memory_limit = memblock_end_of_DRAM();
403                 printk(KERN_INFO "Adjusted memory_limit for firmware-assisted"
404                                 " dump, now %#016llx\n", memory_limit);
405         }
406         if (memory_limit)
407                 memory_boundary = memory_limit;
408         else
409                 memory_boundary = memblock_end_of_DRAM();
410
411         if (fw_dump.dump_active) {
412                 pr_info("Firmware-assisted dump is active.\n");
413
414 #ifdef CONFIG_HUGETLB_PAGE
415                 /*
416                  * FADump capture kernel doesn't care much about hugepages.
417                  * In fact, handling hugepages in capture kernel is asking for
418                  * trouble. So, disable HugeTLB support when fadump is active.
419                  */
420                 hugetlb_disabled = true;
421 #endif
422                 /*
423                  * If last boot has crashed then reserve all the memory
424                  * above boot_memory_size so that we don't touch it until
425                  * dump is written to disk by userspace tool. This memory
426                  * will be released for general use once the dump is saved.
427                  */
428                 base = fw_dump.boot_memory_size;
429                 size = memory_boundary - base;
430                 fadump_reserve_crash_area(base, size);
431
432                 fw_dump.fadumphdr_addr =
433                                 be64_to_cpu(fdm_active->rmr_region.destination_address) +
434                                 be64_to_cpu(fdm_active->rmr_region.source_len);
435                 pr_debug("fadumphdr_addr = %p\n",
436                                 (void *) fw_dump.fadumphdr_addr);
437         } else {
438                 size = get_fadump_area_size();
439
440                 /*
441                  * Reserve memory at an offset closer to bottom of the RAM to
442                  * minimize the impact of memory hot-remove operation. We can't
443                  * use memblock_find_in_range() here since it doesn't allocate
444                  * from bottom to top.
445                  */
446                 for (base = fw_dump.boot_memory_size;
447                      base <= (memory_boundary - size);
448                      base += size) {
449                         if (memblock_is_region_memory(base, size) &&
450                             !memblock_is_region_reserved(base, size))
451                                 break;
452                 }
453                 if ((base > (memory_boundary - size)) ||
454                     memblock_reserve(base, size)) {
455                         pr_err("Failed to reserve memory\n");
456                         return 0;
457                 }
458
459                 pr_info("Reserved %ldMB of memory at %ldMB for firmware-"
460                         "assisted dump (System RAM: %ldMB)\n",
461                         (unsigned long)(size >> 20),
462                         (unsigned long)(base >> 20),
463                         (unsigned long)(memblock_phys_mem_size() >> 20));
464         }
465
466         fw_dump.reserve_dump_area_start = base;
467         fw_dump.reserve_dump_area_size = size;
468         return 1;
469 }
470
471 unsigned long __init arch_reserved_kernel_pages(void)
472 {
473         return memblock_reserved_size() / PAGE_SIZE;
474 }
475
476 /* Look for fadump= cmdline option. */
477 static int __init early_fadump_param(char *p)
478 {
479         if (!p)
480                 return 1;
481
482         if (strncmp(p, "on", 2) == 0)
483                 fw_dump.fadump_enabled = 1;
484         else if (strncmp(p, "off", 3) == 0)
485                 fw_dump.fadump_enabled = 0;
486
487         return 0;
488 }
489 early_param("fadump", early_fadump_param);
490
491 /*
492  * Look for fadump_reserve_mem= cmdline option
493  * TODO: Remove references to 'fadump_reserve_mem=' parameter,
494  *       the sooner 'crashkernel=' parameter is accustomed to.
495  */
496 static int __init early_fadump_reserve_mem(char *p)
497 {
498         if (p)
499                 fw_dump.reserve_bootvar = memparse(p, &p);
500         return 0;
501 }
502 early_param("fadump_reserve_mem", early_fadump_reserve_mem);
503
504 static int register_fw_dump(struct fadump_mem_struct *fdm)
505 {
506         int rc, err;
507         unsigned int wait_time;
508
509         pr_debug("Registering for firmware-assisted kernel dump...\n");
510
511         /* TODO: Add upper time limit for the delay */
512         do {
513                 rc = rtas_call(fw_dump.ibm_configure_kernel_dump, 3, 1, NULL,
514                         FADUMP_REGISTER, fdm,
515                         sizeof(struct fadump_mem_struct));
516
517                 wait_time = rtas_busy_delay_time(rc);
518                 if (wait_time)
519                         mdelay(wait_time);
520
521         } while (wait_time);
522
523         err = -EIO;
524         switch (rc) {
525         default:
526                 pr_err("Failed to register. Unknown Error(%d).\n", rc);
527                 break;
528         case -1:
529                 printk(KERN_ERR "Failed to register firmware-assisted kernel"
530                         " dump. Hardware Error(%d).\n", rc);
531                 break;
532         case -3:
533                 if (!is_boot_memory_area_contiguous())
534                         pr_err("Can't have holes in boot memory area while "
535                                "registering fadump\n");
536
537                 printk(KERN_ERR "Failed to register firmware-assisted kernel"
538                         " dump. Parameter Error(%d).\n", rc);
539                 err = -EINVAL;
540                 break;
541         case -9:
542                 printk(KERN_ERR "firmware-assisted kernel dump is already "
543                         " registered.");
544                 fw_dump.dump_registered = 1;
545                 err = -EEXIST;
546                 break;
547         case 0:
548                 printk(KERN_INFO "firmware-assisted kernel dump registration"
549                         " is successful\n");
550                 fw_dump.dump_registered = 1;
551                 err = 0;
552                 break;
553         }
554         return err;
555 }
556
557 void crash_fadump(struct pt_regs *regs, const char *str)
558 {
559         struct fadump_crash_info_header *fdh = NULL;
560         int old_cpu, this_cpu;
561
562         if (!should_fadump_crash())
563                 return;
564
565         /*
566          * old_cpu == -1 means this is the first CPU which has come here,
567          * go ahead and trigger fadump.
568          *
569          * old_cpu != -1 means some other CPU has already on it's way
570          * to trigger fadump, just keep looping here.
571          */
572         this_cpu = smp_processor_id();
573         old_cpu = cmpxchg(&crashing_cpu, -1, this_cpu);
574
575         if (old_cpu != -1) {
576                 /*
577                  * We can't loop here indefinitely. Wait as long as fadump
578                  * is in force. If we race with fadump un-registration this
579                  * loop will break and then we go down to normal panic path
580                  * and reboot. If fadump is in force the first crashing
581                  * cpu will definitely trigger fadump.
582                  */
583                 while (fw_dump.dump_registered)
584                         cpu_relax();
585                 return;
586         }
587
588         fdh = __va(fw_dump.fadumphdr_addr);
589         fdh->crashing_cpu = crashing_cpu;
590         crash_save_vmcoreinfo();
591
592         if (regs)
593                 fdh->regs = *regs;
594         else
595                 ppc_save_regs(&fdh->regs);
596
597         fdh->online_mask = *cpu_online_mask;
598
599         /* Call ibm,os-term rtas call to trigger firmware assisted dump */
600         rtas_os_term((char *)str);
601 }
602
603 #define GPR_MASK        0xffffff0000000000
604 static inline int fadump_gpr_index(u64 id)
605 {
606         int i = -1;
607         char str[3];
608
609         if ((id & GPR_MASK) == REG_ID("GPR")) {
610                 /* get the digits at the end */
611                 id &= ~GPR_MASK;
612                 id >>= 24;
613                 str[2] = '\0';
614                 str[1] = id & 0xff;
615                 str[0] = (id >> 8) & 0xff;
616                 sscanf(str, "%d", &i);
617                 if (i > 31)
618                         i = -1;
619         }
620         return i;
621 }
622
623 static inline void fadump_set_regval(struct pt_regs *regs, u64 reg_id,
624                                                                 u64 reg_val)
625 {
626         int i;
627
628         i = fadump_gpr_index(reg_id);
629         if (i >= 0)
630                 regs->gpr[i] = (unsigned long)reg_val;
631         else if (reg_id == REG_ID("NIA"))
632                 regs->nip = (unsigned long)reg_val;
633         else if (reg_id == REG_ID("MSR"))
634                 regs->msr = (unsigned long)reg_val;
635         else if (reg_id == REG_ID("CTR"))
636                 regs->ctr = (unsigned long)reg_val;
637         else if (reg_id == REG_ID("LR"))
638                 regs->link = (unsigned long)reg_val;
639         else if (reg_id == REG_ID("XER"))
640                 regs->xer = (unsigned long)reg_val;
641         else if (reg_id == REG_ID("CR"))
642                 regs->ccr = (unsigned long)reg_val;
643         else if (reg_id == REG_ID("DAR"))
644                 regs->dar = (unsigned long)reg_val;
645         else if (reg_id == REG_ID("DSISR"))
646                 regs->dsisr = (unsigned long)reg_val;
647 }
648
649 static struct fadump_reg_entry*
650 fadump_read_registers(struct fadump_reg_entry *reg_entry, struct pt_regs *regs)
651 {
652         memset(regs, 0, sizeof(struct pt_regs));
653
654         while (be64_to_cpu(reg_entry->reg_id) != REG_ID("CPUEND")) {
655                 fadump_set_regval(regs, be64_to_cpu(reg_entry->reg_id),
656                                         be64_to_cpu(reg_entry->reg_value));
657                 reg_entry++;
658         }
659         reg_entry++;
660         return reg_entry;
661 }
662
663 static u32 *fadump_regs_to_elf_notes(u32 *buf, struct pt_regs *regs)
664 {
665         struct elf_prstatus prstatus;
666
667         memset(&prstatus, 0, sizeof(prstatus));
668         /*
669          * FIXME: How do i get PID? Do I really need it?
670          * prstatus.pr_pid = ????
671          */
672         elf_core_copy_kernel_regs(&prstatus.pr_reg, regs);
673         buf = append_elf_note(buf, CRASH_CORE_NOTE_NAME, NT_PRSTATUS,
674                               &prstatus, sizeof(prstatus));
675         return buf;
676 }
677
678 static void fadump_update_elfcore_header(char *bufp)
679 {
680         struct elfhdr *elf;
681         struct elf_phdr *phdr;
682
683         elf = (struct elfhdr *)bufp;
684         bufp += sizeof(struct elfhdr);
685
686         /* First note is a place holder for cpu notes info. */
687         phdr = (struct elf_phdr *)bufp;
688
689         if (phdr->p_type == PT_NOTE) {
690                 phdr->p_paddr = fw_dump.cpu_notes_buf;
691                 phdr->p_offset  = phdr->p_paddr;
692                 phdr->p_filesz  = fw_dump.cpu_notes_buf_size;
693                 phdr->p_memsz = fw_dump.cpu_notes_buf_size;
694         }
695         return;
696 }
697
698 static void *fadump_cpu_notes_buf_alloc(unsigned long size)
699 {
700         void *vaddr;
701         struct page *page;
702         unsigned long order, count, i;
703
704         order = get_order(size);
705         vaddr = (void *)__get_free_pages(GFP_KERNEL|__GFP_ZERO, order);
706         if (!vaddr)
707                 return NULL;
708
709         count = 1 << order;
710         page = virt_to_page(vaddr);
711         for (i = 0; i < count; i++)
712                 SetPageReserved(page + i);
713         return vaddr;
714 }
715
716 static void fadump_cpu_notes_buf_free(unsigned long vaddr, unsigned long size)
717 {
718         struct page *page;
719         unsigned long order, count, i;
720
721         order = get_order(size);
722         count = 1 << order;
723         page = virt_to_page(vaddr);
724         for (i = 0; i < count; i++)
725                 ClearPageReserved(page + i);
726         __free_pages(page, order);
727 }
728
729 /*
730  * Read CPU state dump data and convert it into ELF notes.
731  * The CPU dump starts with magic number "REGSAVE". NumCpusOffset should be
732  * used to access the data to allow for additional fields to be added without
733  * affecting compatibility. Each list of registers for a CPU starts with
734  * "CPUSTRT" and ends with "CPUEND". Each register entry is of 16 bytes,
735  * 8 Byte ASCII identifier and 8 Byte register value. The register entry
736  * with identifier "CPUSTRT" and "CPUEND" contains 4 byte cpu id as part
737  * of register value. For more details refer to PAPR document.
738  *
739  * Only for the crashing cpu we ignore the CPU dump data and get exact
740  * state from fadump crash info structure populated by first kernel at the
741  * time of crash.
742  */
743 static int __init fadump_build_cpu_notes(const struct fadump_mem_struct *fdm)
744 {
745         struct fadump_reg_save_area_header *reg_header;
746         struct fadump_reg_entry *reg_entry;
747         struct fadump_crash_info_header *fdh = NULL;
748         void *vaddr;
749         unsigned long addr;
750         u32 num_cpus, *note_buf;
751         struct pt_regs regs;
752         int i, rc = 0, cpu = 0;
753
754         if (!fdm->cpu_state_data.bytes_dumped)
755                 return -EINVAL;
756
757         addr = be64_to_cpu(fdm->cpu_state_data.destination_address);
758         vaddr = __va(addr);
759
760         reg_header = vaddr;
761         if (be64_to_cpu(reg_header->magic_number) != REGSAVE_AREA_MAGIC) {
762                 printk(KERN_ERR "Unable to read register save area.\n");
763                 return -ENOENT;
764         }
765         pr_debug("--------CPU State Data------------\n");
766         pr_debug("Magic Number: %llx\n", be64_to_cpu(reg_header->magic_number));
767         pr_debug("NumCpuOffset: %x\n", be32_to_cpu(reg_header->num_cpu_offset));
768
769         vaddr += be32_to_cpu(reg_header->num_cpu_offset);
770         num_cpus = be32_to_cpu(*((__be32 *)(vaddr)));
771         pr_debug("NumCpus     : %u\n", num_cpus);
772         vaddr += sizeof(u32);
773         reg_entry = (struct fadump_reg_entry *)vaddr;
774
775         /* Allocate buffer to hold cpu crash notes. */
776         fw_dump.cpu_notes_buf_size = num_cpus * sizeof(note_buf_t);
777         fw_dump.cpu_notes_buf_size = PAGE_ALIGN(fw_dump.cpu_notes_buf_size);
778         note_buf = fadump_cpu_notes_buf_alloc(fw_dump.cpu_notes_buf_size);
779         if (!note_buf) {
780                 printk(KERN_ERR "Failed to allocate 0x%lx bytes for "
781                         "cpu notes buffer\n", fw_dump.cpu_notes_buf_size);
782                 return -ENOMEM;
783         }
784         fw_dump.cpu_notes_buf = __pa(note_buf);
785
786         pr_debug("Allocated buffer for cpu notes of size %ld at %p\n",
787                         (num_cpus * sizeof(note_buf_t)), note_buf);
788
789         if (fw_dump.fadumphdr_addr)
790                 fdh = __va(fw_dump.fadumphdr_addr);
791
792         for (i = 0; i < num_cpus; i++) {
793                 if (be64_to_cpu(reg_entry->reg_id) != REG_ID("CPUSTRT")) {
794                         printk(KERN_ERR "Unable to read CPU state data\n");
795                         rc = -ENOENT;
796                         goto error_out;
797                 }
798                 /* Lower 4 bytes of reg_value contains logical cpu id */
799                 cpu = be64_to_cpu(reg_entry->reg_value) & FADUMP_CPU_ID_MASK;
800                 if (fdh && !cpumask_test_cpu(cpu, &fdh->online_mask)) {
801                         SKIP_TO_NEXT_CPU(reg_entry);
802                         continue;
803                 }
804                 pr_debug("Reading register data for cpu %d...\n", cpu);
805                 if (fdh && fdh->crashing_cpu == cpu) {
806                         regs = fdh->regs;
807                         note_buf = fadump_regs_to_elf_notes(note_buf, &regs);
808                         SKIP_TO_NEXT_CPU(reg_entry);
809                 } else {
810                         reg_entry++;
811                         reg_entry = fadump_read_registers(reg_entry, &regs);
812                         note_buf = fadump_regs_to_elf_notes(note_buf, &regs);
813                 }
814         }
815         final_note(note_buf);
816
817         if (fdh) {
818                 pr_debug("Updating elfcore header (%llx) with cpu notes\n",
819                                                         fdh->elfcorehdr_addr);
820                 fadump_update_elfcore_header((char *)__va(fdh->elfcorehdr_addr));
821         }
822         return 0;
823
824 error_out:
825         fadump_cpu_notes_buf_free((unsigned long)__va(fw_dump.cpu_notes_buf),
826                                         fw_dump.cpu_notes_buf_size);
827         fw_dump.cpu_notes_buf = 0;
828         fw_dump.cpu_notes_buf_size = 0;
829         return rc;
830
831 }
832
833 /*
834  * Validate and process the dump data stored by firmware before exporting
835  * it through '/proc/vmcore'.
836  */
837 static int __init process_fadump(const struct fadump_mem_struct *fdm_active)
838 {
839         struct fadump_crash_info_header *fdh;
840         int rc = 0;
841
842         if (!fdm_active || !fw_dump.fadumphdr_addr)
843                 return -EINVAL;
844
845         /* Check if the dump data is valid. */
846         if ((be16_to_cpu(fdm_active->header.dump_status_flag) == FADUMP_ERROR_FLAG) ||
847                         (fdm_active->cpu_state_data.error_flags != 0) ||
848                         (fdm_active->rmr_region.error_flags != 0)) {
849                 printk(KERN_ERR "Dump taken by platform is not valid\n");
850                 return -EINVAL;
851         }
852         if ((fdm_active->rmr_region.bytes_dumped !=
853                         fdm_active->rmr_region.source_len) ||
854                         !fdm_active->cpu_state_data.bytes_dumped) {
855                 printk(KERN_ERR "Dump taken by platform is incomplete\n");
856                 return -EINVAL;
857         }
858
859         /* Validate the fadump crash info header */
860         fdh = __va(fw_dump.fadumphdr_addr);
861         if (fdh->magic_number != FADUMP_CRASH_INFO_MAGIC) {
862                 printk(KERN_ERR "Crash info header is not valid.\n");
863                 return -EINVAL;
864         }
865
866         rc = fadump_build_cpu_notes(fdm_active);
867         if (rc)
868                 return rc;
869
870         /*
871          * We are done validating dump info and elfcore header is now ready
872          * to be exported. set elfcorehdr_addr so that vmcore module will
873          * export the elfcore header through '/proc/vmcore'.
874          */
875         elfcorehdr_addr = fdh->elfcorehdr_addr;
876
877         return 0;
878 }
879
880 static void free_crash_memory_ranges(void)
881 {
882         kfree(crash_memory_ranges);
883         crash_memory_ranges = NULL;
884         crash_memory_ranges_size = 0;
885         max_crash_mem_ranges = 0;
886 }
887
888 /*
889  * Allocate or reallocate crash memory ranges array in incremental units
890  * of PAGE_SIZE.
891  */
892 static int allocate_crash_memory_ranges(void)
893 {
894         struct fad_crash_memory_ranges *new_array;
895         u64 new_size;
896
897         new_size = crash_memory_ranges_size + PAGE_SIZE;
898         pr_debug("Allocating %llu bytes of memory for crash memory ranges\n",
899                  new_size);
900
901         new_array = krealloc(crash_memory_ranges, new_size, GFP_KERNEL);
902         if (new_array == NULL) {
903                 pr_err("Insufficient memory for setting up crash memory ranges\n");
904                 free_crash_memory_ranges();
905                 return -ENOMEM;
906         }
907
908         crash_memory_ranges = new_array;
909         crash_memory_ranges_size = new_size;
910         max_crash_mem_ranges = (new_size /
911                                 sizeof(struct fad_crash_memory_ranges));
912         return 0;
913 }
914
915 static inline int fadump_add_crash_memory(unsigned long long base,
916                                           unsigned long long end)
917 {
918         u64  start, size;
919         bool is_adjacent = false;
920
921         if (base == end)
922                 return 0;
923
924         /*
925          * Fold adjacent memory ranges to bring down the memory ranges/
926          * PT_LOAD segments count.
927          */
928         if (crash_mem_ranges) {
929                 start = crash_memory_ranges[crash_mem_ranges - 1].base;
930                 size = crash_memory_ranges[crash_mem_ranges - 1].size;
931
932                 if ((start + size) == base)
933                         is_adjacent = true;
934         }
935         if (!is_adjacent) {
936                 /* resize the array on reaching the limit */
937                 if (crash_mem_ranges == max_crash_mem_ranges) {
938                         int ret;
939
940                         ret = allocate_crash_memory_ranges();
941                         if (ret)
942                                 return ret;
943                 }
944
945                 start = base;
946                 crash_memory_ranges[crash_mem_ranges].base = start;
947                 crash_mem_ranges++;
948         }
949
950         crash_memory_ranges[crash_mem_ranges - 1].size = (end - start);
951         pr_debug("crash_memory_range[%d] [%#016llx-%#016llx], %#llx bytes\n",
952                 (crash_mem_ranges - 1), start, end - 1, (end - start));
953         return 0;
954 }
955
956 static int fadump_exclude_reserved_area(unsigned long long start,
957                                         unsigned long long end)
958 {
959         unsigned long long ra_start, ra_end;
960         int ret = 0;
961
962         ra_start = fw_dump.reserve_dump_area_start;
963         ra_end = ra_start + fw_dump.reserve_dump_area_size;
964
965         if ((ra_start < end) && (ra_end > start)) {
966                 if ((start < ra_start) && (end > ra_end)) {
967                         ret = fadump_add_crash_memory(start, ra_start);
968                         if (ret)
969                                 return ret;
970
971                         ret = fadump_add_crash_memory(ra_end, end);
972                 } else if (start < ra_start) {
973                         ret = fadump_add_crash_memory(start, ra_start);
974                 } else if (ra_end < end) {
975                         ret = fadump_add_crash_memory(ra_end, end);
976                 }
977         } else
978                 ret = fadump_add_crash_memory(start, end);
979
980         return ret;
981 }
982
983 static int fadump_init_elfcore_header(char *bufp)
984 {
985         struct elfhdr *elf;
986
987         elf = (struct elfhdr *) bufp;
988         bufp += sizeof(struct elfhdr);
989         memcpy(elf->e_ident, ELFMAG, SELFMAG);
990         elf->e_ident[EI_CLASS] = ELF_CLASS;
991         elf->e_ident[EI_DATA] = ELF_DATA;
992         elf->e_ident[EI_VERSION] = EV_CURRENT;
993         elf->e_ident[EI_OSABI] = ELF_OSABI;
994         memset(elf->e_ident+EI_PAD, 0, EI_NIDENT-EI_PAD);
995         elf->e_type = ET_CORE;
996         elf->e_machine = ELF_ARCH;
997         elf->e_version = EV_CURRENT;
998         elf->e_entry = 0;
999         elf->e_phoff = sizeof(struct elfhdr);
1000         elf->e_shoff = 0;
1001 #if defined(_CALL_ELF)
1002         elf->e_flags = _CALL_ELF;
1003 #else
1004         elf->e_flags = 0;
1005 #endif
1006         elf->e_ehsize = sizeof(struct elfhdr);
1007         elf->e_phentsize = sizeof(struct elf_phdr);
1008         elf->e_phnum = 0;
1009         elf->e_shentsize = 0;
1010         elf->e_shnum = 0;
1011         elf->e_shstrndx = 0;
1012
1013         return 0;
1014 }
1015
1016 /*
1017  * Traverse through memblock structure and setup crash memory ranges. These
1018  * ranges will be used create PT_LOAD program headers in elfcore header.
1019  */
1020 static int fadump_setup_crash_memory_ranges(void)
1021 {
1022         struct memblock_region *reg;
1023         unsigned long long start, end;
1024         int ret;
1025
1026         pr_debug("Setup crash memory ranges.\n");
1027         crash_mem_ranges = 0;
1028
1029         /*
1030          * add the first memory chunk (RMA_START through boot_memory_size) as
1031          * a separate memory chunk. The reason is, at the time crash firmware
1032          * will move the content of this memory chunk to different location
1033          * specified during fadump registration. We need to create a separate
1034          * program header for this chunk with the correct offset.
1035          */
1036         ret = fadump_add_crash_memory(RMA_START, fw_dump.boot_memory_size);
1037         if (ret)
1038                 return ret;
1039
1040         for_each_memblock(memory, reg) {
1041                 start = (unsigned long long)reg->base;
1042                 end = start + (unsigned long long)reg->size;
1043
1044                 /*
1045                  * skip the first memory chunk that is already added (RMA_START
1046                  * through boot_memory_size). This logic needs a relook if and
1047                  * when RMA_START changes to a non-zero value.
1048                  */
1049                 BUILD_BUG_ON(RMA_START != 0);
1050                 if (start < fw_dump.boot_memory_size) {
1051                         if (end > fw_dump.boot_memory_size)
1052                                 start = fw_dump.boot_memory_size;
1053                         else
1054                                 continue;
1055                 }
1056
1057                 /* add this range excluding the reserved dump area. */
1058                 ret = fadump_exclude_reserved_area(start, end);
1059                 if (ret)
1060                         return ret;
1061         }
1062
1063         return 0;
1064 }
1065
1066 /*
1067  * If the given physical address falls within the boot memory region then
1068  * return the relocated address that points to the dump region reserved
1069  * for saving initial boot memory contents.
1070  */
1071 static inline unsigned long fadump_relocate(unsigned long paddr)
1072 {
1073         if (paddr > RMA_START && paddr < fw_dump.boot_memory_size)
1074                 return be64_to_cpu(fdm.rmr_region.destination_address) + paddr;
1075         else
1076                 return paddr;
1077 }
1078
1079 static int fadump_create_elfcore_headers(char *bufp)
1080 {
1081         struct elfhdr *elf;
1082         struct elf_phdr *phdr;
1083         int i;
1084
1085         fadump_init_elfcore_header(bufp);
1086         elf = (struct elfhdr *)bufp;
1087         bufp += sizeof(struct elfhdr);
1088
1089         /*
1090          * setup ELF PT_NOTE, place holder for cpu notes info. The notes info
1091          * will be populated during second kernel boot after crash. Hence
1092          * this PT_NOTE will always be the first elf note.
1093          *
1094          * NOTE: Any new ELF note addition should be placed after this note.
1095          */
1096         phdr = (struct elf_phdr *)bufp;
1097         bufp += sizeof(struct elf_phdr);
1098         phdr->p_type = PT_NOTE;
1099         phdr->p_flags = 0;
1100         phdr->p_vaddr = 0;
1101         phdr->p_align = 0;
1102
1103         phdr->p_offset = 0;
1104         phdr->p_paddr = 0;
1105         phdr->p_filesz = 0;
1106         phdr->p_memsz = 0;
1107
1108         (elf->e_phnum)++;
1109
1110         /* setup ELF PT_NOTE for vmcoreinfo */
1111         phdr = (struct elf_phdr *)bufp;
1112         bufp += sizeof(struct elf_phdr);
1113         phdr->p_type    = PT_NOTE;
1114         phdr->p_flags   = 0;
1115         phdr->p_vaddr   = 0;
1116         phdr->p_align   = 0;
1117
1118         phdr->p_paddr   = fadump_relocate(paddr_vmcoreinfo_note());
1119         phdr->p_offset  = phdr->p_paddr;
1120         phdr->p_memsz   = phdr->p_filesz = VMCOREINFO_NOTE_SIZE;
1121
1122         /* Increment number of program headers. */
1123         (elf->e_phnum)++;
1124
1125         /* setup PT_LOAD sections. */
1126
1127         for (i = 0; i < crash_mem_ranges; i++) {
1128                 unsigned long long mbase, msize;
1129                 mbase = crash_memory_ranges[i].base;
1130                 msize = crash_memory_ranges[i].size;
1131
1132                 if (!msize)
1133                         continue;
1134
1135                 phdr = (struct elf_phdr *)bufp;
1136                 bufp += sizeof(struct elf_phdr);
1137                 phdr->p_type    = PT_LOAD;
1138                 phdr->p_flags   = PF_R|PF_W|PF_X;
1139                 phdr->p_offset  = mbase;
1140
1141                 if (mbase == RMA_START) {
1142                         /*
1143                          * The entire RMA region will be moved by firmware
1144                          * to the specified destination_address. Hence set
1145                          * the correct offset.
1146                          */
1147                         phdr->p_offset = be64_to_cpu(fdm.rmr_region.destination_address);
1148                 }
1149
1150                 phdr->p_paddr = mbase;
1151                 phdr->p_vaddr = (unsigned long)__va(mbase);
1152                 phdr->p_filesz = msize;
1153                 phdr->p_memsz = msize;
1154                 phdr->p_align = 0;
1155
1156                 /* Increment number of program headers. */
1157                 (elf->e_phnum)++;
1158         }
1159         return 0;
1160 }
1161
1162 static unsigned long init_fadump_header(unsigned long addr)
1163 {
1164         struct fadump_crash_info_header *fdh;
1165
1166         if (!addr)
1167                 return 0;
1168
1169         fw_dump.fadumphdr_addr = addr;
1170         fdh = __va(addr);
1171         addr += sizeof(struct fadump_crash_info_header);
1172
1173         memset(fdh, 0, sizeof(struct fadump_crash_info_header));
1174         fdh->magic_number = FADUMP_CRASH_INFO_MAGIC;
1175         fdh->elfcorehdr_addr = addr;
1176         /* We will set the crashing cpu id in crash_fadump() during crash. */
1177         fdh->crashing_cpu = CPU_UNKNOWN;
1178
1179         return addr;
1180 }
1181
1182 static int register_fadump(void)
1183 {
1184         unsigned long addr;
1185         void *vaddr;
1186         int ret;
1187
1188         /*
1189          * If no memory is reserved then we can not register for firmware-
1190          * assisted dump.
1191          */
1192         if (!fw_dump.reserve_dump_area_size)
1193                 return -ENODEV;
1194
1195         ret = fadump_setup_crash_memory_ranges();
1196         if (ret)
1197                 return ret;
1198
1199         addr = be64_to_cpu(fdm.rmr_region.destination_address) + be64_to_cpu(fdm.rmr_region.source_len);
1200         /* Initialize fadump crash info header. */
1201         addr = init_fadump_header(addr);
1202         vaddr = __va(addr);
1203
1204         pr_debug("Creating ELF core headers at %#016lx\n", addr);
1205         fadump_create_elfcore_headers(vaddr);
1206
1207         /* register the future kernel dump with firmware. */
1208         return register_fw_dump(&fdm);
1209 }
1210
1211 static int fadump_unregister_dump(struct fadump_mem_struct *fdm)
1212 {
1213         int rc = 0;
1214         unsigned int wait_time;
1215
1216         pr_debug("Un-register firmware-assisted dump\n");
1217
1218         /* TODO: Add upper time limit for the delay */
1219         do {
1220                 rc = rtas_call(fw_dump.ibm_configure_kernel_dump, 3, 1, NULL,
1221                         FADUMP_UNREGISTER, fdm,
1222                         sizeof(struct fadump_mem_struct));
1223
1224                 wait_time = rtas_busy_delay_time(rc);
1225                 if (wait_time)
1226                         mdelay(wait_time);
1227         } while (wait_time);
1228
1229         if (rc) {
1230                 printk(KERN_ERR "Failed to un-register firmware-assisted dump."
1231                         " unexpected error(%d).\n", rc);
1232                 return rc;
1233         }
1234         fw_dump.dump_registered = 0;
1235         return 0;
1236 }
1237
1238 static int fadump_invalidate_dump(struct fadump_mem_struct *fdm)
1239 {
1240         int rc = 0;
1241         unsigned int wait_time;
1242
1243         pr_debug("Invalidating firmware-assisted dump registration\n");
1244
1245         /* TODO: Add upper time limit for the delay */
1246         do {
1247                 rc = rtas_call(fw_dump.ibm_configure_kernel_dump, 3, 1, NULL,
1248                         FADUMP_INVALIDATE, fdm,
1249                         sizeof(struct fadump_mem_struct));
1250
1251                 wait_time = rtas_busy_delay_time(rc);
1252                 if (wait_time)
1253                         mdelay(wait_time);
1254         } while (wait_time);
1255
1256         if (rc) {
1257                 pr_err("Failed to invalidate firmware-assisted dump registration. Unexpected error (%d).\n", rc);
1258                 return rc;
1259         }
1260         fw_dump.dump_active = 0;
1261         fdm_active = NULL;
1262         return 0;
1263 }
1264
1265 void fadump_cleanup(void)
1266 {
1267         /* Invalidate the registration only if dump is active. */
1268         if (fw_dump.dump_active) {
1269                 init_fadump_mem_struct(&fdm,
1270                         be64_to_cpu(fdm_active->cpu_state_data.destination_address));
1271                 fadump_invalidate_dump(&fdm);
1272         } else if (fw_dump.dump_registered) {
1273                 /* Un-register Firmware-assisted dump if it was registered. */
1274                 fadump_unregister_dump(&fdm);
1275                 free_crash_memory_ranges();
1276         }
1277 }
1278
1279 static void fadump_free_reserved_memory(unsigned long start_pfn,
1280                                         unsigned long end_pfn)
1281 {
1282         unsigned long pfn;
1283         unsigned long time_limit = jiffies + HZ;
1284
1285         pr_info("freeing reserved memory (0x%llx - 0x%llx)\n",
1286                 PFN_PHYS(start_pfn), PFN_PHYS(end_pfn));
1287
1288         for (pfn = start_pfn; pfn < end_pfn; pfn++) {
1289                 free_reserved_page(pfn_to_page(pfn));
1290
1291                 if (time_after(jiffies, time_limit)) {
1292                         cond_resched();
1293                         time_limit = jiffies + HZ;
1294                 }
1295         }
1296 }
1297
1298 /*
1299  * Skip memory holes and free memory that was actually reserved.
1300  */
1301 static void fadump_release_reserved_area(unsigned long start, unsigned long end)
1302 {
1303         struct memblock_region *reg;
1304         unsigned long tstart, tend;
1305         unsigned long start_pfn = PHYS_PFN(start);
1306         unsigned long end_pfn = PHYS_PFN(end);
1307
1308         for_each_memblock(memory, reg) {
1309                 tstart = max(start_pfn, memblock_region_memory_base_pfn(reg));
1310                 tend = min(end_pfn, memblock_region_memory_end_pfn(reg));
1311                 if (tstart < tend) {
1312                         fadump_free_reserved_memory(tstart, tend);
1313
1314                         if (tend == end_pfn)
1315                                 break;
1316
1317                         start_pfn = tend + 1;
1318                 }
1319         }
1320 }
1321
1322 /*
1323  * Release the memory that was reserved in early boot to preserve the memory
1324  * contents. The released memory will be available for general use.
1325  */
1326 static void fadump_release_memory(unsigned long begin, unsigned long end)
1327 {
1328         unsigned long ra_start, ra_end;
1329
1330         ra_start = fw_dump.reserve_dump_area_start;
1331         ra_end = ra_start + fw_dump.reserve_dump_area_size;
1332
1333         /*
1334          * exclude the dump reserve area. Will reuse it for next
1335          * fadump registration.
1336          */
1337         if (begin < ra_end && end > ra_start) {
1338                 if (begin < ra_start)
1339                         fadump_release_reserved_area(begin, ra_start);
1340                 if (end > ra_end)
1341                         fadump_release_reserved_area(ra_end, end);
1342         } else
1343                 fadump_release_reserved_area(begin, end);
1344 }
1345
1346 static void fadump_invalidate_release_mem(void)
1347 {
1348         unsigned long reserved_area_start, reserved_area_end;
1349         unsigned long destination_address;
1350
1351         mutex_lock(&fadump_mutex);
1352         if (!fw_dump.dump_active) {
1353                 mutex_unlock(&fadump_mutex);
1354                 return;
1355         }
1356
1357         destination_address = be64_to_cpu(fdm_active->cpu_state_data.destination_address);
1358         fadump_cleanup();
1359         mutex_unlock(&fadump_mutex);
1360
1361         /*
1362          * Save the current reserved memory bounds we will require them
1363          * later for releasing the memory for general use.
1364          */
1365         reserved_area_start = fw_dump.reserve_dump_area_start;
1366         reserved_area_end = reserved_area_start +
1367                         fw_dump.reserve_dump_area_size;
1368         /*
1369          * Setup reserve_dump_area_start and its size so that we can
1370          * reuse this reserved memory for Re-registration.
1371          */
1372         fw_dump.reserve_dump_area_start = destination_address;
1373         fw_dump.reserve_dump_area_size = get_fadump_area_size();
1374
1375         fadump_release_memory(reserved_area_start, reserved_area_end);
1376         if (fw_dump.cpu_notes_buf) {
1377                 fadump_cpu_notes_buf_free(
1378                                 (unsigned long)__va(fw_dump.cpu_notes_buf),
1379                                 fw_dump.cpu_notes_buf_size);
1380                 fw_dump.cpu_notes_buf = 0;
1381                 fw_dump.cpu_notes_buf_size = 0;
1382         }
1383         /* Initialize the kernel dump memory structure for FAD registration. */
1384         init_fadump_mem_struct(&fdm, fw_dump.reserve_dump_area_start);
1385 }
1386
1387 static ssize_t fadump_release_memory_store(struct kobject *kobj,
1388                                         struct kobj_attribute *attr,
1389                                         const char *buf, size_t count)
1390 {
1391         int input = -1;
1392
1393         if (!fw_dump.dump_active)
1394                 return -EPERM;
1395
1396         if (kstrtoint(buf, 0, &input))
1397                 return -EINVAL;
1398
1399         if (input == 1) {
1400                 /*
1401                  * Take away the '/proc/vmcore'. We are releasing the dump
1402                  * memory, hence it will not be valid anymore.
1403                  */
1404 #ifdef CONFIG_PROC_VMCORE
1405                 vmcore_cleanup();
1406 #endif
1407                 fadump_invalidate_release_mem();
1408
1409         } else
1410                 return -EINVAL;
1411         return count;
1412 }
1413
1414 static ssize_t fadump_enabled_show(struct kobject *kobj,
1415                                         struct kobj_attribute *attr,
1416                                         char *buf)
1417 {
1418         return sprintf(buf, "%d\n", fw_dump.fadump_enabled);
1419 }
1420
1421 static ssize_t fadump_register_show(struct kobject *kobj,
1422                                         struct kobj_attribute *attr,
1423                                         char *buf)
1424 {
1425         return sprintf(buf, "%d\n", fw_dump.dump_registered);
1426 }
1427
1428 static ssize_t fadump_register_store(struct kobject *kobj,
1429                                         struct kobj_attribute *attr,
1430                                         const char *buf, size_t count)
1431 {
1432         int ret = 0;
1433         int input = -1;
1434
1435         if (!fw_dump.fadump_enabled || fdm_active)
1436                 return -EPERM;
1437
1438         if (kstrtoint(buf, 0, &input))
1439                 return -EINVAL;
1440
1441         mutex_lock(&fadump_mutex);
1442
1443         switch (input) {
1444         case 0:
1445                 if (fw_dump.dump_registered == 0) {
1446                         goto unlock_out;
1447                 }
1448                 /* Un-register Firmware-assisted dump */
1449                 fadump_unregister_dump(&fdm);
1450                 break;
1451         case 1:
1452                 if (fw_dump.dump_registered == 1) {
1453                         ret = -EEXIST;
1454                         goto unlock_out;
1455                 }
1456                 /* Register Firmware-assisted dump */
1457                 ret = register_fadump();
1458                 break;
1459         default:
1460                 ret = -EINVAL;
1461                 break;
1462         }
1463
1464 unlock_out:
1465         mutex_unlock(&fadump_mutex);
1466         return ret < 0 ? ret : count;
1467 }
1468
1469 static int fadump_region_show(struct seq_file *m, void *private)
1470 {
1471         const struct fadump_mem_struct *fdm_ptr;
1472
1473         if (!fw_dump.fadump_enabled)
1474                 return 0;
1475
1476         mutex_lock(&fadump_mutex);
1477         if (fdm_active)
1478                 fdm_ptr = fdm_active;
1479         else {
1480                 mutex_unlock(&fadump_mutex);
1481                 fdm_ptr = &fdm;
1482         }
1483
1484         seq_printf(m,
1485                         "CPU : [%#016llx-%#016llx] %#llx bytes, "
1486                         "Dumped: %#llx\n",
1487                         be64_to_cpu(fdm_ptr->cpu_state_data.destination_address),
1488                         be64_to_cpu(fdm_ptr->cpu_state_data.destination_address) +
1489                         be64_to_cpu(fdm_ptr->cpu_state_data.source_len) - 1,
1490                         be64_to_cpu(fdm_ptr->cpu_state_data.source_len),
1491                         be64_to_cpu(fdm_ptr->cpu_state_data.bytes_dumped));
1492         seq_printf(m,
1493                         "HPTE: [%#016llx-%#016llx] %#llx bytes, "
1494                         "Dumped: %#llx\n",
1495                         be64_to_cpu(fdm_ptr->hpte_region.destination_address),
1496                         be64_to_cpu(fdm_ptr->hpte_region.destination_address) +
1497                         be64_to_cpu(fdm_ptr->hpte_region.source_len) - 1,
1498                         be64_to_cpu(fdm_ptr->hpte_region.source_len),
1499                         be64_to_cpu(fdm_ptr->hpte_region.bytes_dumped));
1500         seq_printf(m,
1501                         "DUMP: [%#016llx-%#016llx] %#llx bytes, "
1502                         "Dumped: %#llx\n",
1503                         be64_to_cpu(fdm_ptr->rmr_region.destination_address),
1504                         be64_to_cpu(fdm_ptr->rmr_region.destination_address) +
1505                         be64_to_cpu(fdm_ptr->rmr_region.source_len) - 1,
1506                         be64_to_cpu(fdm_ptr->rmr_region.source_len),
1507                         be64_to_cpu(fdm_ptr->rmr_region.bytes_dumped));
1508
1509         if (!fdm_active ||
1510                 (fw_dump.reserve_dump_area_start ==
1511                 be64_to_cpu(fdm_ptr->cpu_state_data.destination_address)))
1512                 goto out;
1513
1514         /* Dump is active. Show reserved memory region. */
1515         seq_printf(m,
1516                         "    : [%#016llx-%#016llx] %#llx bytes, "
1517                         "Dumped: %#llx\n",
1518                         (unsigned long long)fw_dump.reserve_dump_area_start,
1519                         be64_to_cpu(fdm_ptr->cpu_state_data.destination_address) - 1,
1520                         be64_to_cpu(fdm_ptr->cpu_state_data.destination_address) -
1521                         fw_dump.reserve_dump_area_start,
1522                         be64_to_cpu(fdm_ptr->cpu_state_data.destination_address) -
1523                         fw_dump.reserve_dump_area_start);
1524 out:
1525         if (fdm_active)
1526                 mutex_unlock(&fadump_mutex);
1527         return 0;
1528 }
1529
1530 static struct kobj_attribute fadump_release_attr = __ATTR(fadump_release_mem,
1531                                                 0200, NULL,
1532                                                 fadump_release_memory_store);
1533 static struct kobj_attribute fadump_attr = __ATTR(fadump_enabled,
1534                                                 0444, fadump_enabled_show,
1535                                                 NULL);
1536 static struct kobj_attribute fadump_register_attr = __ATTR(fadump_registered,
1537                                                 0644, fadump_register_show,
1538                                                 fadump_register_store);
1539
1540 static int fadump_region_open(struct inode *inode, struct file *file)
1541 {
1542         return single_open(file, fadump_region_show, inode->i_private);
1543 }
1544
1545 static const struct file_operations fadump_region_fops = {
1546         .open    = fadump_region_open,
1547         .read    = seq_read,
1548         .llseek  = seq_lseek,
1549         .release = single_release,
1550 };
1551
1552 static void fadump_init_files(void)
1553 {
1554         struct dentry *debugfs_file;
1555         int rc = 0;
1556
1557         rc = sysfs_create_file(kernel_kobj, &fadump_attr.attr);
1558         if (rc)
1559                 printk(KERN_ERR "fadump: unable to create sysfs file"
1560                         " fadump_enabled (%d)\n", rc);
1561
1562         rc = sysfs_create_file(kernel_kobj, &fadump_register_attr.attr);
1563         if (rc)
1564                 printk(KERN_ERR "fadump: unable to create sysfs file"
1565                         " fadump_registered (%d)\n", rc);
1566
1567         debugfs_file = debugfs_create_file("fadump_region", 0444,
1568                                         powerpc_debugfs_root, NULL,
1569                                         &fadump_region_fops);
1570         if (!debugfs_file)
1571                 printk(KERN_ERR "fadump: unable to create debugfs file"
1572                                 " fadump_region\n");
1573
1574         if (fw_dump.dump_active) {
1575                 rc = sysfs_create_file(kernel_kobj, &fadump_release_attr.attr);
1576                 if (rc)
1577                         printk(KERN_ERR "fadump: unable to create sysfs file"
1578                                 " fadump_release_mem (%d)\n", rc);
1579         }
1580         return;
1581 }
1582
1583 /*
1584  * Prepare for firmware-assisted dump.
1585  */
1586 int __init setup_fadump(void)
1587 {
1588         if (!fw_dump.fadump_enabled)
1589                 return 0;
1590
1591         if (!fw_dump.fadump_supported) {
1592                 printk(KERN_ERR "Firmware-assisted dump is not supported on"
1593                         " this hardware\n");
1594                 return 0;
1595         }
1596
1597         fadump_show_config();
1598         /*
1599          * If dump data is available then see if it is valid and prepare for
1600          * saving it to the disk.
1601          */
1602         if (fw_dump.dump_active) {
1603                 /*
1604                  * if dump process fails then invalidate the registration
1605                  * and release memory before proceeding for re-registration.
1606                  */
1607                 if (process_fadump(fdm_active) < 0)
1608                         fadump_invalidate_release_mem();
1609         }
1610         /* Initialize the kernel dump memory structure for FAD registration. */
1611         else if (fw_dump.reserve_dump_area_size)
1612                 init_fadump_mem_struct(&fdm, fw_dump.reserve_dump_area_start);
1613         fadump_init_files();
1614
1615         return 1;
1616 }
1617 subsys_initcall(setup_fadump);