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