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