xref: /openbmc/linux/arch/powerpc/kernel/fadump.c (revision 887f56a07f0eee41f60ef3d165facaa348b3e3af)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Firmware Assisted dump: A robust mechanism to get reliable kernel crash
4  * dump with assistance from firmware. This approach does not use kexec,
5  * instead firmware assists in booting the kdump kernel while preserving
6  * memory contents. The most of the code implementation has been adapted
7  * from phyp assisted dump implementation written by Linas Vepstas and
8  * Manish Ahuja
9  *
10  * Copyright 2011 IBM Corporation
11  * Author: Mahesh Salgaonkar <mahesh@linux.vnet.ibm.com>
12  */
13 
14 #undef DEBUG
15 #define pr_fmt(fmt) "fadump: " fmt
16 
17 #include <linux/string.h>
18 #include <linux/memblock.h>
19 #include <linux/delay.h>
20 #include <linux/seq_file.h>
21 #include <linux/crash_dump.h>
22 #include <linux/kobject.h>
23 #include <linux/sysfs.h>
24 #include <linux/slab.h>
25 #include <linux/cma.h>
26 #include <linux/hugetlb.h>
27 #include <linux/debugfs.h>
28 
29 #include <asm/page.h>
30 #include <asm/prom.h>
31 #include <asm/fadump.h>
32 #include <asm/fadump-internal.h>
33 #include <asm/setup.h>
34 #include <asm/interrupt.h>
35 
36 /*
37  * The CPU who acquired the lock to trigger the fadump crash should
38  * wait for other CPUs to enter.
39  *
40  * The timeout is in milliseconds.
41  */
42 #define CRASH_TIMEOUT		500
43 
44 static struct fw_dump fw_dump;
45 
46 static void __init fadump_reserve_crash_area(u64 base);
47 
48 #ifndef CONFIG_PRESERVE_FA_DUMP
49 
50 static struct kobject *fadump_kobj;
51 
52 static atomic_t cpus_in_fadump;
53 static DEFINE_MUTEX(fadump_mutex);
54 
55 static struct fadump_mrange_info crash_mrange_info = { "crash", NULL, 0, 0, 0, false };
56 
57 #define RESERVED_RNGS_SZ	16384 /* 16K - 128 entries */
58 #define RESERVED_RNGS_CNT	(RESERVED_RNGS_SZ / \
59 				 sizeof(struct fadump_memory_range))
60 static struct fadump_memory_range rngs[RESERVED_RNGS_CNT];
61 static struct fadump_mrange_info
62 reserved_mrange_info = { "reserved", rngs, RESERVED_RNGS_SZ, 0, RESERVED_RNGS_CNT, true };
63 
64 static void __init early_init_dt_scan_reserved_ranges(unsigned long node);
65 
66 #ifdef CONFIG_CMA
67 static struct cma *fadump_cma;
68 
69 /*
70  * fadump_cma_init() - Initialize CMA area from a fadump reserved memory
71  *
72  * This function initializes CMA area from fadump reserved memory.
73  * The total size of fadump reserved memory covers for boot memory size
74  * + cpu data size + hpte size and metadata.
75  * Initialize only the area equivalent to boot memory size for CMA use.
76  * The remaining portion of fadump reserved memory will be not given
77  * to CMA and pages for those will stay reserved. boot memory size is
78  * aligned per CMA requirement to satisy cma_init_reserved_mem() call.
79  * But for some reason even if it fails we still have the memory reservation
80  * with us and we can still continue doing fadump.
81  */
82 static int __init fadump_cma_init(void)
83 {
84 	unsigned long long base, size;
85 	int rc;
86 
87 	if (!fw_dump.fadump_enabled)
88 		return 0;
89 
90 	/*
91 	 * Do not use CMA if user has provided fadump=nocma kernel parameter.
92 	 * Return 1 to continue with fadump old behaviour.
93 	 */
94 	if (fw_dump.nocma)
95 		return 1;
96 
97 	base = fw_dump.reserve_dump_area_start;
98 	size = fw_dump.boot_memory_size;
99 
100 	if (!size)
101 		return 0;
102 
103 	rc = cma_init_reserved_mem(base, size, 0, "fadump_cma", &fadump_cma);
104 	if (rc) {
105 		pr_err("Failed to init cma area for firmware-assisted dump,%d\n", rc);
106 		/*
107 		 * Though the CMA init has failed we still have memory
108 		 * reservation with us. The reserved memory will be
109 		 * blocked from production system usage.  Hence return 1,
110 		 * so that we can continue with fadump.
111 		 */
112 		return 1;
113 	}
114 
115 	/*
116 	 *  If CMA activation fails, keep the pages reserved, instead of
117 	 *  exposing them to buddy allocator. Same as 'fadump=nocma' case.
118 	 */
119 	cma_reserve_pages_on_error(fadump_cma);
120 
121 	/*
122 	 * So we now have successfully initialized cma area for fadump.
123 	 */
124 	pr_info("Initialized 0x%lx bytes cma area at %ldMB from 0x%lx "
125 		"bytes of memory reserved for firmware-assisted dump\n",
126 		cma_get_size(fadump_cma),
127 		(unsigned long)cma_get_base(fadump_cma) >> 20,
128 		fw_dump.reserve_dump_area_size);
129 	return 1;
130 }
131 #else
132 static int __init fadump_cma_init(void) { return 1; }
133 #endif /* CONFIG_CMA */
134 
135 /* Scan the Firmware Assisted dump configuration details. */
136 int __init early_init_dt_scan_fw_dump(unsigned long node, const char *uname,
137 				      int depth, void *data)
138 {
139 	if (depth == 0) {
140 		early_init_dt_scan_reserved_ranges(node);
141 		return 0;
142 	}
143 
144 	if (depth != 1)
145 		return 0;
146 
147 	if (strcmp(uname, "rtas") == 0) {
148 		rtas_fadump_dt_scan(&fw_dump, node);
149 		return 1;
150 	}
151 
152 	if (strcmp(uname, "ibm,opal") == 0) {
153 		opal_fadump_dt_scan(&fw_dump, node);
154 		return 1;
155 	}
156 
157 	return 0;
158 }
159 
160 /*
161  * If fadump is registered, check if the memory provided
162  * falls within boot memory area and reserved memory area.
163  */
164 int is_fadump_memory_area(u64 addr, unsigned long size)
165 {
166 	u64 d_start, d_end;
167 
168 	if (!fw_dump.dump_registered)
169 		return 0;
170 
171 	if (!size)
172 		return 0;
173 
174 	d_start = fw_dump.reserve_dump_area_start;
175 	d_end = d_start + fw_dump.reserve_dump_area_size;
176 	if (((addr + size) > d_start) && (addr <= d_end))
177 		return 1;
178 
179 	return (addr <= fw_dump.boot_mem_top);
180 }
181 
182 int should_fadump_crash(void)
183 {
184 	if (!fw_dump.dump_registered || !fw_dump.fadumphdr_addr)
185 		return 0;
186 	return 1;
187 }
188 
189 int is_fadump_active(void)
190 {
191 	return fw_dump.dump_active;
192 }
193 
194 /*
195  * Returns true, if there are no holes in memory area between d_start to d_end,
196  * false otherwise.
197  */
198 static bool is_fadump_mem_area_contiguous(u64 d_start, u64 d_end)
199 {
200 	phys_addr_t reg_start, reg_end;
201 	bool ret = false;
202 	u64 i, start, end;
203 
204 	for_each_mem_range(i, &reg_start, &reg_end) {
205 		start = max_t(u64, d_start, reg_start);
206 		end = min_t(u64, d_end, reg_end);
207 		if (d_start < end) {
208 			/* Memory hole from d_start to start */
209 			if (start > d_start)
210 				break;
211 
212 			if (end == d_end) {
213 				ret = true;
214 				break;
215 			}
216 
217 			d_start = end + 1;
218 		}
219 	}
220 
221 	return ret;
222 }
223 
224 /*
225  * Returns true, if there are no holes in boot memory area,
226  * false otherwise.
227  */
228 bool is_fadump_boot_mem_contiguous(void)
229 {
230 	unsigned long d_start, d_end;
231 	bool ret = false;
232 	int i;
233 
234 	for (i = 0; i < fw_dump.boot_mem_regs_cnt; i++) {
235 		d_start = fw_dump.boot_mem_addr[i];
236 		d_end   = d_start + fw_dump.boot_mem_sz[i];
237 
238 		ret = is_fadump_mem_area_contiguous(d_start, d_end);
239 		if (!ret)
240 			break;
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 bool is_fadump_reserved_mem_contiguous(void)
251 {
252 	u64 d_start, d_end;
253 
254 	d_start	= fw_dump.reserve_dump_area_start;
255 	d_end	= d_start + fw_dump.reserve_dump_area_size;
256 	return is_fadump_mem_area_contiguous(d_start, d_end);
257 }
258 
259 /* Print firmware assisted dump configurations for debugging purpose. */
260 static void __init fadump_show_config(void)
261 {
262 	int i;
263 
264 	pr_debug("Support for firmware-assisted dump (fadump): %s\n",
265 			(fw_dump.fadump_supported ? "present" : "no support"));
266 
267 	if (!fw_dump.fadump_supported)
268 		return;
269 
270 	pr_debug("Fadump enabled    : %s\n",
271 				(fw_dump.fadump_enabled ? "yes" : "no"));
272 	pr_debug("Dump Active       : %s\n",
273 				(fw_dump.dump_active ? "yes" : "no"));
274 	pr_debug("Dump section sizes:\n");
275 	pr_debug("    CPU state data size: %lx\n", fw_dump.cpu_state_data_size);
276 	pr_debug("    HPTE region size   : %lx\n", fw_dump.hpte_region_size);
277 	pr_debug("    Boot memory size   : %lx\n", fw_dump.boot_memory_size);
278 	pr_debug("    Boot memory top    : %llx\n", fw_dump.boot_mem_top);
279 	pr_debug("Boot memory regions cnt: %llx\n", fw_dump.boot_mem_regs_cnt);
280 	for (i = 0; i < fw_dump.boot_mem_regs_cnt; i++) {
281 		pr_debug("[%03d] base = %llx, size = %llx\n", i,
282 			 fw_dump.boot_mem_addr[i], fw_dump.boot_mem_sz[i]);
283 	}
284 }
285 
286 /**
287  * fadump_calculate_reserve_size(): reserve variable boot area 5% of System RAM
288  *
289  * Function to find the largest memory size we need to reserve during early
290  * boot process. This will be the size of the memory that is required for a
291  * kernel to boot successfully.
292  *
293  * This function has been taken from phyp-assisted dump feature implementation.
294  *
295  * returns larger of 256MB or 5% rounded down to multiples of 256MB.
296  *
297  * TODO: Come up with better approach to find out more accurate memory size
298  * that is required for a kernel to boot successfully.
299  *
300  */
301 static __init u64 fadump_calculate_reserve_size(void)
302 {
303 	u64 base, size, bootmem_min;
304 	int ret;
305 
306 	if (fw_dump.reserve_bootvar)
307 		pr_warn("'fadump_reserve_mem=' parameter is deprecated in favor of 'crashkernel=' parameter.\n");
308 
309 	/*
310 	 * Check if the size is specified through crashkernel= cmdline
311 	 * option. If yes, then use that but ignore base as fadump reserves
312 	 * memory at a predefined offset.
313 	 */
314 	ret = parse_crashkernel(boot_command_line, memblock_phys_mem_size(),
315 				&size, &base);
316 	if (ret == 0 && size > 0) {
317 		unsigned long max_size;
318 
319 		if (fw_dump.reserve_bootvar)
320 			pr_info("Using 'crashkernel=' parameter for memory reservation.\n");
321 
322 		fw_dump.reserve_bootvar = (unsigned long)size;
323 
324 		/*
325 		 * Adjust if the boot memory size specified is above
326 		 * the upper limit.
327 		 */
328 		max_size = memblock_phys_mem_size() / MAX_BOOT_MEM_RATIO;
329 		if (fw_dump.reserve_bootvar > max_size) {
330 			fw_dump.reserve_bootvar = max_size;
331 			pr_info("Adjusted boot memory size to %luMB\n",
332 				(fw_dump.reserve_bootvar >> 20));
333 		}
334 
335 		return fw_dump.reserve_bootvar;
336 	} else if (fw_dump.reserve_bootvar) {
337 		/*
338 		 * 'fadump_reserve_mem=' is being used to reserve memory
339 		 * for firmware-assisted dump.
340 		 */
341 		return fw_dump.reserve_bootvar;
342 	}
343 
344 	/* divide by 20 to get 5% of value */
345 	size = memblock_phys_mem_size() / 20;
346 
347 	/* round it down in multiples of 256 */
348 	size = size & ~0x0FFFFFFFUL;
349 
350 	/* Truncate to memory_limit. We don't want to over reserve the memory.*/
351 	if (memory_limit && size > memory_limit)
352 		size = memory_limit;
353 
354 	bootmem_min = fw_dump.ops->fadump_get_bootmem_min();
355 	return (size > bootmem_min ? size : bootmem_min);
356 }
357 
358 /*
359  * Calculate the total memory size required to be reserved for
360  * firmware-assisted dump registration.
361  */
362 static unsigned long __init get_fadump_area_size(void)
363 {
364 	unsigned long size = 0;
365 
366 	size += fw_dump.cpu_state_data_size;
367 	size += fw_dump.hpte_region_size;
368 	/*
369 	 * Account for pagesize alignment of boot memory area destination address.
370 	 * This faciliates in mmap reading of first kernel's memory.
371 	 */
372 	size = PAGE_ALIGN(size);
373 	size += fw_dump.boot_memory_size;
374 	size += sizeof(struct fadump_crash_info_header);
375 	size += sizeof(struct elfhdr); /* ELF core header.*/
376 	size += sizeof(struct elf_phdr); /* place holder for cpu notes */
377 	/* Program headers for crash memory regions. */
378 	size += sizeof(struct elf_phdr) * (memblock_num_regions(memory) + 2);
379 
380 	size = PAGE_ALIGN(size);
381 
382 	/* This is to hold kernel metadata on platforms that support it */
383 	size += (fw_dump.ops->fadump_get_metadata_size ?
384 		 fw_dump.ops->fadump_get_metadata_size() : 0);
385 	return size;
386 }
387 
388 static int __init add_boot_mem_region(unsigned long rstart,
389 				      unsigned long rsize)
390 {
391 	int i = fw_dump.boot_mem_regs_cnt++;
392 
393 	if (fw_dump.boot_mem_regs_cnt > FADUMP_MAX_MEM_REGS) {
394 		fw_dump.boot_mem_regs_cnt = FADUMP_MAX_MEM_REGS;
395 		return 0;
396 	}
397 
398 	pr_debug("Added boot memory range[%d] [%#016lx-%#016lx)\n",
399 		 i, rstart, (rstart + rsize));
400 	fw_dump.boot_mem_addr[i] = rstart;
401 	fw_dump.boot_mem_sz[i] = rsize;
402 	return 1;
403 }
404 
405 /*
406  * Firmware usually has a hard limit on the data it can copy per region.
407  * Honour that by splitting a memory range into multiple regions.
408  */
409 static int __init add_boot_mem_regions(unsigned long mstart,
410 				       unsigned long msize)
411 {
412 	unsigned long rstart, rsize, max_size;
413 	int ret = 1;
414 
415 	rstart = mstart;
416 	max_size = fw_dump.max_copy_size ? fw_dump.max_copy_size : msize;
417 	while (msize) {
418 		if (msize > max_size)
419 			rsize = max_size;
420 		else
421 			rsize = msize;
422 
423 		ret = add_boot_mem_region(rstart, rsize);
424 		if (!ret)
425 			break;
426 
427 		msize -= rsize;
428 		rstart += rsize;
429 	}
430 
431 	return ret;
432 }
433 
434 static int __init fadump_get_boot_mem_regions(void)
435 {
436 	unsigned long size, cur_size, hole_size, last_end;
437 	unsigned long mem_size = fw_dump.boot_memory_size;
438 	phys_addr_t reg_start, reg_end;
439 	int ret = 1;
440 	u64 i;
441 
442 	fw_dump.boot_mem_regs_cnt = 0;
443 
444 	last_end = 0;
445 	hole_size = 0;
446 	cur_size = 0;
447 	for_each_mem_range(i, &reg_start, &reg_end) {
448 		size = reg_end - reg_start;
449 		hole_size += (reg_start - last_end);
450 
451 		if ((cur_size + size) >= mem_size) {
452 			size = (mem_size - cur_size);
453 			ret = add_boot_mem_regions(reg_start, size);
454 			break;
455 		}
456 
457 		mem_size -= size;
458 		cur_size += size;
459 		ret = add_boot_mem_regions(reg_start, size);
460 		if (!ret)
461 			break;
462 
463 		last_end = reg_end;
464 	}
465 	fw_dump.boot_mem_top = PAGE_ALIGN(fw_dump.boot_memory_size + hole_size);
466 
467 	return ret;
468 }
469 
470 /*
471  * Returns true, if the given range overlaps with reserved memory ranges
472  * starting at idx. Also, updates idx to index of overlapping memory range
473  * with the given memory range.
474  * False, otherwise.
475  */
476 static bool __init overlaps_reserved_ranges(u64 base, u64 end, int *idx)
477 {
478 	bool ret = false;
479 	int i;
480 
481 	for (i = *idx; i < reserved_mrange_info.mem_range_cnt; i++) {
482 		u64 rbase = reserved_mrange_info.mem_ranges[i].base;
483 		u64 rend = rbase + reserved_mrange_info.mem_ranges[i].size;
484 
485 		if (end <= rbase)
486 			break;
487 
488 		if ((end > rbase) &&  (base < rend)) {
489 			*idx = i;
490 			ret = true;
491 			break;
492 		}
493 	}
494 
495 	return ret;
496 }
497 
498 /*
499  * Locate a suitable memory area to reserve memory for FADump. While at it,
500  * lookup reserved-ranges & avoid overlap with them, as they are used by F/W.
501  */
502 static u64 __init fadump_locate_reserve_mem(u64 base, u64 size)
503 {
504 	struct fadump_memory_range *mrngs;
505 	phys_addr_t mstart, mend;
506 	int idx = 0;
507 	u64 i, ret = 0;
508 
509 	mrngs = reserved_mrange_info.mem_ranges;
510 	for_each_free_mem_range(i, NUMA_NO_NODE, MEMBLOCK_NONE,
511 				&mstart, &mend, NULL) {
512 		pr_debug("%llu) mstart: %llx, mend: %llx, base: %llx\n",
513 			 i, mstart, mend, base);
514 
515 		if (mstart > base)
516 			base = PAGE_ALIGN(mstart);
517 
518 		while ((mend > base) && ((mend - base) >= size)) {
519 			if (!overlaps_reserved_ranges(base, base+size, &idx)) {
520 				ret = base;
521 				goto out;
522 			}
523 
524 			base = mrngs[idx].base + mrngs[idx].size;
525 			base = PAGE_ALIGN(base);
526 		}
527 	}
528 
529 out:
530 	return ret;
531 }
532 
533 int __init fadump_reserve_mem(void)
534 {
535 	u64 base, size, mem_boundary, bootmem_min;
536 	int ret = 1;
537 
538 	if (!fw_dump.fadump_enabled)
539 		return 0;
540 
541 	if (!fw_dump.fadump_supported) {
542 		pr_info("Firmware-Assisted Dump is not supported on this hardware\n");
543 		goto error_out;
544 	}
545 
546 	/*
547 	 * Initialize boot memory size
548 	 * If dump is active then we have already calculated the size during
549 	 * first kernel.
550 	 */
551 	if (!fw_dump.dump_active) {
552 		fw_dump.boot_memory_size =
553 			PAGE_ALIGN(fadump_calculate_reserve_size());
554 #ifdef CONFIG_CMA
555 		if (!fw_dump.nocma) {
556 			fw_dump.boot_memory_size =
557 				ALIGN(fw_dump.boot_memory_size,
558 				      CMA_MIN_ALIGNMENT_BYTES);
559 		}
560 #endif
561 
562 		bootmem_min = fw_dump.ops->fadump_get_bootmem_min();
563 		if (fw_dump.boot_memory_size < bootmem_min) {
564 			pr_err("Can't enable fadump with boot memory size (0x%lx) less than 0x%llx\n",
565 			       fw_dump.boot_memory_size, bootmem_min);
566 			goto error_out;
567 		}
568 
569 		if (!fadump_get_boot_mem_regions()) {
570 			pr_err("Too many holes in boot memory area to enable fadump\n");
571 			goto error_out;
572 		}
573 	}
574 
575 	/*
576 	 * Calculate the memory boundary.
577 	 * If memory_limit is less than actual memory boundary then reserve
578 	 * the memory for fadump beyond the memory_limit and adjust the
579 	 * memory_limit accordingly, so that the running kernel can run with
580 	 * specified memory_limit.
581 	 */
582 	if (memory_limit && memory_limit < memblock_end_of_DRAM()) {
583 		size = get_fadump_area_size();
584 		if ((memory_limit + size) < memblock_end_of_DRAM())
585 			memory_limit += size;
586 		else
587 			memory_limit = memblock_end_of_DRAM();
588 		printk(KERN_INFO "Adjusted memory_limit for firmware-assisted"
589 				" dump, now %#016llx\n", memory_limit);
590 	}
591 	if (memory_limit)
592 		mem_boundary = memory_limit;
593 	else
594 		mem_boundary = memblock_end_of_DRAM();
595 
596 	base = fw_dump.boot_mem_top;
597 	size = get_fadump_area_size();
598 	fw_dump.reserve_dump_area_size = size;
599 	if (fw_dump.dump_active) {
600 		pr_info("Firmware-assisted dump is active.\n");
601 
602 #ifdef CONFIG_HUGETLB_PAGE
603 		/*
604 		 * FADump capture kernel doesn't care much about hugepages.
605 		 * In fact, handling hugepages in capture kernel is asking for
606 		 * trouble. So, disable HugeTLB support when fadump is active.
607 		 */
608 		hugetlb_disabled = true;
609 #endif
610 		/*
611 		 * If last boot has crashed then reserve all the memory
612 		 * above boot memory size so that we don't touch it until
613 		 * dump is written to disk by userspace tool. This memory
614 		 * can be released for general use by invalidating fadump.
615 		 */
616 		fadump_reserve_crash_area(base);
617 
618 		pr_debug("fadumphdr_addr = %#016lx\n", fw_dump.fadumphdr_addr);
619 		pr_debug("Reserve dump area start address: 0x%lx\n",
620 			 fw_dump.reserve_dump_area_start);
621 	} else {
622 		/*
623 		 * Reserve memory at an offset closer to bottom of the RAM to
624 		 * minimize the impact of memory hot-remove operation.
625 		 */
626 		base = fadump_locate_reserve_mem(base, size);
627 
628 		if (!base || (base + size > mem_boundary)) {
629 			pr_err("Failed to find memory chunk for reservation!\n");
630 			goto error_out;
631 		}
632 		fw_dump.reserve_dump_area_start = base;
633 
634 		/*
635 		 * Calculate the kernel metadata address and register it with
636 		 * f/w if the platform supports.
637 		 */
638 		if (fw_dump.ops->fadump_setup_metadata &&
639 		    (fw_dump.ops->fadump_setup_metadata(&fw_dump) < 0))
640 			goto error_out;
641 
642 		if (memblock_reserve(base, size)) {
643 			pr_err("Failed to reserve memory!\n");
644 			goto error_out;
645 		}
646 
647 		pr_info("Reserved %lldMB of memory at %#016llx (System RAM: %lldMB)\n",
648 			(size >> 20), base, (memblock_phys_mem_size() >> 20));
649 
650 		ret = fadump_cma_init();
651 	}
652 
653 	return ret;
654 error_out:
655 	fw_dump.fadump_enabled = 0;
656 	return 0;
657 }
658 
659 /* Look for fadump= cmdline option. */
660 static int __init early_fadump_param(char *p)
661 {
662 	if (!p)
663 		return 1;
664 
665 	if (strncmp(p, "on", 2) == 0)
666 		fw_dump.fadump_enabled = 1;
667 	else if (strncmp(p, "off", 3) == 0)
668 		fw_dump.fadump_enabled = 0;
669 	else if (strncmp(p, "nocma", 5) == 0) {
670 		fw_dump.fadump_enabled = 1;
671 		fw_dump.nocma = 1;
672 	}
673 
674 	return 0;
675 }
676 early_param("fadump", early_fadump_param);
677 
678 /*
679  * Look for fadump_reserve_mem= cmdline option
680  * TODO: Remove references to 'fadump_reserve_mem=' parameter,
681  *       the sooner 'crashkernel=' parameter is accustomed to.
682  */
683 static int __init early_fadump_reserve_mem(char *p)
684 {
685 	if (p)
686 		fw_dump.reserve_bootvar = memparse(p, &p);
687 	return 0;
688 }
689 early_param("fadump_reserve_mem", early_fadump_reserve_mem);
690 
691 void crash_fadump(struct pt_regs *regs, const char *str)
692 {
693 	unsigned int msecs;
694 	struct fadump_crash_info_header *fdh = NULL;
695 	int old_cpu, this_cpu;
696 	/* Do not include first CPU */
697 	unsigned int ncpus = num_online_cpus() - 1;
698 
699 	if (!should_fadump_crash())
700 		return;
701 
702 	/*
703 	 * old_cpu == -1 means this is the first CPU which has come here,
704 	 * go ahead and trigger fadump.
705 	 *
706 	 * old_cpu != -1 means some other CPU has already on it's way
707 	 * to trigger fadump, just keep looping here.
708 	 */
709 	this_cpu = smp_processor_id();
710 	old_cpu = cmpxchg(&crashing_cpu, -1, this_cpu);
711 
712 	if (old_cpu != -1) {
713 		atomic_inc(&cpus_in_fadump);
714 
715 		/*
716 		 * We can't loop here indefinitely. Wait as long as fadump
717 		 * is in force. If we race with fadump un-registration this
718 		 * loop will break and then we go down to normal panic path
719 		 * and reboot. If fadump is in force the first crashing
720 		 * cpu will definitely trigger fadump.
721 		 */
722 		while (fw_dump.dump_registered)
723 			cpu_relax();
724 		return;
725 	}
726 
727 	fdh = __va(fw_dump.fadumphdr_addr);
728 	fdh->crashing_cpu = crashing_cpu;
729 	crash_save_vmcoreinfo();
730 
731 	if (regs)
732 		fdh->regs = *regs;
733 	else
734 		ppc_save_regs(&fdh->regs);
735 
736 	fdh->cpu_mask = *cpu_online_mask;
737 
738 	/*
739 	 * If we came in via system reset, wait a while for the secondary
740 	 * CPUs to enter.
741 	 */
742 	if (TRAP(&(fdh->regs)) == INTERRUPT_SYSTEM_RESET) {
743 		msecs = CRASH_TIMEOUT;
744 		while ((atomic_read(&cpus_in_fadump) < ncpus) && (--msecs > 0))
745 			mdelay(1);
746 	}
747 
748 	fw_dump.ops->fadump_trigger(fdh, str);
749 }
750 
751 u32 *__init fadump_regs_to_elf_notes(u32 *buf, struct pt_regs *regs)
752 {
753 	struct elf_prstatus prstatus;
754 
755 	memset(&prstatus, 0, sizeof(prstatus));
756 	/*
757 	 * FIXME: How do i get PID? Do I really need it?
758 	 * prstatus.pr_pid = ????
759 	 */
760 	elf_core_copy_kernel_regs(&prstatus.pr_reg, regs);
761 	buf = append_elf_note(buf, CRASH_CORE_NOTE_NAME, NT_PRSTATUS,
762 			      &prstatus, sizeof(prstatus));
763 	return buf;
764 }
765 
766 void __init fadump_update_elfcore_header(char *bufp)
767 {
768 	struct elf_phdr *phdr;
769 
770 	bufp += sizeof(struct elfhdr);
771 
772 	/* First note is a place holder for cpu notes info. */
773 	phdr = (struct elf_phdr *)bufp;
774 
775 	if (phdr->p_type == PT_NOTE) {
776 		phdr->p_paddr	= __pa(fw_dump.cpu_notes_buf_vaddr);
777 		phdr->p_offset	= phdr->p_paddr;
778 		phdr->p_filesz	= fw_dump.cpu_notes_buf_size;
779 		phdr->p_memsz = fw_dump.cpu_notes_buf_size;
780 	}
781 	return;
782 }
783 
784 static void *__init fadump_alloc_buffer(unsigned long size)
785 {
786 	unsigned long count, i;
787 	struct page *page;
788 	void *vaddr;
789 
790 	vaddr = alloc_pages_exact(size, GFP_KERNEL | __GFP_ZERO);
791 	if (!vaddr)
792 		return NULL;
793 
794 	count = PAGE_ALIGN(size) / PAGE_SIZE;
795 	page = virt_to_page(vaddr);
796 	for (i = 0; i < count; i++)
797 		mark_page_reserved(page + i);
798 	return vaddr;
799 }
800 
801 static void fadump_free_buffer(unsigned long vaddr, unsigned long size)
802 {
803 	free_reserved_area((void *)vaddr, (void *)(vaddr + size), -1, NULL);
804 }
805 
806 s32 __init fadump_setup_cpu_notes_buf(u32 num_cpus)
807 {
808 	/* Allocate buffer to hold cpu crash notes. */
809 	fw_dump.cpu_notes_buf_size = num_cpus * sizeof(note_buf_t);
810 	fw_dump.cpu_notes_buf_size = PAGE_ALIGN(fw_dump.cpu_notes_buf_size);
811 	fw_dump.cpu_notes_buf_vaddr =
812 		(unsigned long)fadump_alloc_buffer(fw_dump.cpu_notes_buf_size);
813 	if (!fw_dump.cpu_notes_buf_vaddr) {
814 		pr_err("Failed to allocate %ld bytes for CPU notes buffer\n",
815 		       fw_dump.cpu_notes_buf_size);
816 		return -ENOMEM;
817 	}
818 
819 	pr_debug("Allocated buffer for cpu notes of size %ld at 0x%lx\n",
820 		 fw_dump.cpu_notes_buf_size,
821 		 fw_dump.cpu_notes_buf_vaddr);
822 	return 0;
823 }
824 
825 void fadump_free_cpu_notes_buf(void)
826 {
827 	if (!fw_dump.cpu_notes_buf_vaddr)
828 		return;
829 
830 	fadump_free_buffer(fw_dump.cpu_notes_buf_vaddr,
831 			   fw_dump.cpu_notes_buf_size);
832 	fw_dump.cpu_notes_buf_vaddr = 0;
833 	fw_dump.cpu_notes_buf_size = 0;
834 }
835 
836 static void fadump_free_mem_ranges(struct fadump_mrange_info *mrange_info)
837 {
838 	if (mrange_info->is_static) {
839 		mrange_info->mem_range_cnt = 0;
840 		return;
841 	}
842 
843 	kfree(mrange_info->mem_ranges);
844 	memset((void *)((u64)mrange_info + RNG_NAME_SZ), 0,
845 	       (sizeof(struct fadump_mrange_info) - RNG_NAME_SZ));
846 }
847 
848 /*
849  * Allocate or reallocate mem_ranges array in incremental units
850  * of PAGE_SIZE.
851  */
852 static int fadump_alloc_mem_ranges(struct fadump_mrange_info *mrange_info)
853 {
854 	struct fadump_memory_range *new_array;
855 	u64 new_size;
856 
857 	new_size = mrange_info->mem_ranges_sz + PAGE_SIZE;
858 	pr_debug("Allocating %llu bytes of memory for %s memory ranges\n",
859 		 new_size, mrange_info->name);
860 
861 	new_array = krealloc(mrange_info->mem_ranges, new_size, GFP_KERNEL);
862 	if (new_array == NULL) {
863 		pr_err("Insufficient memory for setting up %s memory ranges\n",
864 		       mrange_info->name);
865 		fadump_free_mem_ranges(mrange_info);
866 		return -ENOMEM;
867 	}
868 
869 	mrange_info->mem_ranges = new_array;
870 	mrange_info->mem_ranges_sz = new_size;
871 	mrange_info->max_mem_ranges = (new_size /
872 				       sizeof(struct fadump_memory_range));
873 	return 0;
874 }
875 static inline int fadump_add_mem_range(struct fadump_mrange_info *mrange_info,
876 				       u64 base, u64 end)
877 {
878 	struct fadump_memory_range *mem_ranges = mrange_info->mem_ranges;
879 	bool is_adjacent = false;
880 	u64 start, size;
881 
882 	if (base == end)
883 		return 0;
884 
885 	/*
886 	 * Fold adjacent memory ranges to bring down the memory ranges/
887 	 * PT_LOAD segments count.
888 	 */
889 	if (mrange_info->mem_range_cnt) {
890 		start = mem_ranges[mrange_info->mem_range_cnt - 1].base;
891 		size  = mem_ranges[mrange_info->mem_range_cnt - 1].size;
892 
893 		/*
894 		 * Boot memory area needs separate PT_LOAD segment(s) as it
895 		 * is moved to a different location at the time of crash.
896 		 * So, fold only if the region is not boot memory area.
897 		 */
898 		if ((start + size) == base && start >= fw_dump.boot_mem_top)
899 			is_adjacent = true;
900 	}
901 	if (!is_adjacent) {
902 		/* resize the array on reaching the limit */
903 		if (mrange_info->mem_range_cnt == mrange_info->max_mem_ranges) {
904 			int ret;
905 
906 			if (mrange_info->is_static) {
907 				pr_err("Reached array size limit for %s memory ranges\n",
908 				       mrange_info->name);
909 				return -ENOSPC;
910 			}
911 
912 			ret = fadump_alloc_mem_ranges(mrange_info);
913 			if (ret)
914 				return ret;
915 
916 			/* Update to the new resized array */
917 			mem_ranges = mrange_info->mem_ranges;
918 		}
919 
920 		start = base;
921 		mem_ranges[mrange_info->mem_range_cnt].base = start;
922 		mrange_info->mem_range_cnt++;
923 	}
924 
925 	mem_ranges[mrange_info->mem_range_cnt - 1].size = (end - start);
926 	pr_debug("%s_memory_range[%d] [%#016llx-%#016llx], %#llx bytes\n",
927 		 mrange_info->name, (mrange_info->mem_range_cnt - 1),
928 		 start, end - 1, (end - start));
929 	return 0;
930 }
931 
932 static int fadump_exclude_reserved_area(u64 start, u64 end)
933 {
934 	u64 ra_start, ra_end;
935 	int ret = 0;
936 
937 	ra_start = fw_dump.reserve_dump_area_start;
938 	ra_end = ra_start + fw_dump.reserve_dump_area_size;
939 
940 	if ((ra_start < end) && (ra_end > start)) {
941 		if ((start < ra_start) && (end > ra_end)) {
942 			ret = fadump_add_mem_range(&crash_mrange_info,
943 						   start, ra_start);
944 			if (ret)
945 				return ret;
946 
947 			ret = fadump_add_mem_range(&crash_mrange_info,
948 						   ra_end, end);
949 		} else if (start < ra_start) {
950 			ret = fadump_add_mem_range(&crash_mrange_info,
951 						   start, ra_start);
952 		} else if (ra_end < end) {
953 			ret = fadump_add_mem_range(&crash_mrange_info,
954 						   ra_end, end);
955 		}
956 	} else
957 		ret = fadump_add_mem_range(&crash_mrange_info, start, end);
958 
959 	return ret;
960 }
961 
962 static int fadump_init_elfcore_header(char *bufp)
963 {
964 	struct elfhdr *elf;
965 
966 	elf = (struct elfhdr *) bufp;
967 	bufp += sizeof(struct elfhdr);
968 	memcpy(elf->e_ident, ELFMAG, SELFMAG);
969 	elf->e_ident[EI_CLASS] = ELF_CLASS;
970 	elf->e_ident[EI_DATA] = ELF_DATA;
971 	elf->e_ident[EI_VERSION] = EV_CURRENT;
972 	elf->e_ident[EI_OSABI] = ELF_OSABI;
973 	memset(elf->e_ident+EI_PAD, 0, EI_NIDENT-EI_PAD);
974 	elf->e_type = ET_CORE;
975 	elf->e_machine = ELF_ARCH;
976 	elf->e_version = EV_CURRENT;
977 	elf->e_entry = 0;
978 	elf->e_phoff = sizeof(struct elfhdr);
979 	elf->e_shoff = 0;
980 #if defined(_CALL_ELF)
981 	elf->e_flags = _CALL_ELF;
982 #else
983 	elf->e_flags = 0;
984 #endif
985 	elf->e_ehsize = sizeof(struct elfhdr);
986 	elf->e_phentsize = sizeof(struct elf_phdr);
987 	elf->e_phnum = 0;
988 	elf->e_shentsize = 0;
989 	elf->e_shnum = 0;
990 	elf->e_shstrndx = 0;
991 
992 	return 0;
993 }
994 
995 /*
996  * Traverse through memblock structure and setup crash memory ranges. These
997  * ranges will be used create PT_LOAD program headers in elfcore header.
998  */
999 static int fadump_setup_crash_memory_ranges(void)
1000 {
1001 	u64 i, start, end;
1002 	int ret;
1003 
1004 	pr_debug("Setup crash memory ranges.\n");
1005 	crash_mrange_info.mem_range_cnt = 0;
1006 
1007 	/*
1008 	 * Boot memory region(s) registered with firmware are moved to
1009 	 * different location at the time of crash. Create separate program
1010 	 * header(s) for this memory chunk(s) with the correct offset.
1011 	 */
1012 	for (i = 0; i < fw_dump.boot_mem_regs_cnt; i++) {
1013 		start = fw_dump.boot_mem_addr[i];
1014 		end = start + fw_dump.boot_mem_sz[i];
1015 		ret = fadump_add_mem_range(&crash_mrange_info, start, end);
1016 		if (ret)
1017 			return ret;
1018 	}
1019 
1020 	for_each_mem_range(i, &start, &end) {
1021 		/*
1022 		 * skip the memory chunk that is already added
1023 		 * (0 through boot_memory_top).
1024 		 */
1025 		if (start < fw_dump.boot_mem_top) {
1026 			if (end > fw_dump.boot_mem_top)
1027 				start = fw_dump.boot_mem_top;
1028 			else
1029 				continue;
1030 		}
1031 
1032 		/* add this range excluding the reserved dump area. */
1033 		ret = fadump_exclude_reserved_area(start, end);
1034 		if (ret)
1035 			return ret;
1036 	}
1037 
1038 	return 0;
1039 }
1040 
1041 /*
1042  * If the given physical address falls within the boot memory region then
1043  * return the relocated address that points to the dump region reserved
1044  * for saving initial boot memory contents.
1045  */
1046 static inline unsigned long fadump_relocate(unsigned long paddr)
1047 {
1048 	unsigned long raddr, rstart, rend, rlast, hole_size;
1049 	int i;
1050 
1051 	hole_size = 0;
1052 	rlast = 0;
1053 	raddr = paddr;
1054 	for (i = 0; i < fw_dump.boot_mem_regs_cnt; i++) {
1055 		rstart = fw_dump.boot_mem_addr[i];
1056 		rend = rstart + fw_dump.boot_mem_sz[i];
1057 		hole_size += (rstart - rlast);
1058 
1059 		if (paddr >= rstart && paddr < rend) {
1060 			raddr += fw_dump.boot_mem_dest_addr - hole_size;
1061 			break;
1062 		}
1063 
1064 		rlast = rend;
1065 	}
1066 
1067 	pr_debug("vmcoreinfo: paddr = 0x%lx, raddr = 0x%lx\n", paddr, raddr);
1068 	return raddr;
1069 }
1070 
1071 static int fadump_create_elfcore_headers(char *bufp)
1072 {
1073 	unsigned long long raddr, offset;
1074 	struct elf_phdr *phdr;
1075 	struct elfhdr *elf;
1076 	int i, j;
1077 
1078 	fadump_init_elfcore_header(bufp);
1079 	elf = (struct elfhdr *)bufp;
1080 	bufp += sizeof(struct elfhdr);
1081 
1082 	/*
1083 	 * setup ELF PT_NOTE, place holder for cpu notes info. The notes info
1084 	 * will be populated during second kernel boot after crash. Hence
1085 	 * this PT_NOTE will always be the first elf note.
1086 	 *
1087 	 * NOTE: Any new ELF note addition should be placed after this note.
1088 	 */
1089 	phdr = (struct elf_phdr *)bufp;
1090 	bufp += sizeof(struct elf_phdr);
1091 	phdr->p_type = PT_NOTE;
1092 	phdr->p_flags = 0;
1093 	phdr->p_vaddr = 0;
1094 	phdr->p_align = 0;
1095 
1096 	phdr->p_offset = 0;
1097 	phdr->p_paddr = 0;
1098 	phdr->p_filesz = 0;
1099 	phdr->p_memsz = 0;
1100 
1101 	(elf->e_phnum)++;
1102 
1103 	/* setup ELF PT_NOTE for vmcoreinfo */
1104 	phdr = (struct elf_phdr *)bufp;
1105 	bufp += sizeof(struct elf_phdr);
1106 	phdr->p_type	= PT_NOTE;
1107 	phdr->p_flags	= 0;
1108 	phdr->p_vaddr	= 0;
1109 	phdr->p_align	= 0;
1110 
1111 	phdr->p_paddr	= fadump_relocate(paddr_vmcoreinfo_note());
1112 	phdr->p_offset	= phdr->p_paddr;
1113 	phdr->p_memsz	= phdr->p_filesz = VMCOREINFO_NOTE_SIZE;
1114 
1115 	/* Increment number of program headers. */
1116 	(elf->e_phnum)++;
1117 
1118 	/* setup PT_LOAD sections. */
1119 	j = 0;
1120 	offset = 0;
1121 	raddr = fw_dump.boot_mem_addr[0];
1122 	for (i = 0; i < crash_mrange_info.mem_range_cnt; i++) {
1123 		u64 mbase, msize;
1124 
1125 		mbase = crash_mrange_info.mem_ranges[i].base;
1126 		msize = crash_mrange_info.mem_ranges[i].size;
1127 		if (!msize)
1128 			continue;
1129 
1130 		phdr = (struct elf_phdr *)bufp;
1131 		bufp += sizeof(struct elf_phdr);
1132 		phdr->p_type	= PT_LOAD;
1133 		phdr->p_flags	= PF_R|PF_W|PF_X;
1134 		phdr->p_offset	= mbase;
1135 
1136 		if (mbase == raddr) {
1137 			/*
1138 			 * The entire real memory region will be moved by
1139 			 * firmware to the specified destination_address.
1140 			 * Hence set the correct offset.
1141 			 */
1142 			phdr->p_offset = fw_dump.boot_mem_dest_addr + offset;
1143 			if (j < (fw_dump.boot_mem_regs_cnt - 1)) {
1144 				offset += fw_dump.boot_mem_sz[j];
1145 				raddr = fw_dump.boot_mem_addr[++j];
1146 			}
1147 		}
1148 
1149 		phdr->p_paddr = mbase;
1150 		phdr->p_vaddr = (unsigned long)__va(mbase);
1151 		phdr->p_filesz = msize;
1152 		phdr->p_memsz = msize;
1153 		phdr->p_align = 0;
1154 
1155 		/* Increment number of program headers. */
1156 		(elf->e_phnum)++;
1157 	}
1158 	return 0;
1159 }
1160 
1161 static unsigned long init_fadump_header(unsigned long addr)
1162 {
1163 	struct fadump_crash_info_header *fdh;
1164 
1165 	if (!addr)
1166 		return 0;
1167 
1168 	fdh = __va(addr);
1169 	addr += sizeof(struct fadump_crash_info_header);
1170 
1171 	memset(fdh, 0, sizeof(struct fadump_crash_info_header));
1172 	fdh->magic_number = FADUMP_CRASH_INFO_MAGIC;
1173 	fdh->elfcorehdr_addr = addr;
1174 	/* We will set the crashing cpu id in crash_fadump() during crash. */
1175 	fdh->crashing_cpu = FADUMP_CPU_UNKNOWN;
1176 	/*
1177 	 * When LPAR is terminated by PYHP, ensure all possible CPUs'
1178 	 * register data is processed while exporting the vmcore.
1179 	 */
1180 	fdh->cpu_mask = *cpu_possible_mask;
1181 
1182 	return addr;
1183 }
1184 
1185 static int register_fadump(void)
1186 {
1187 	unsigned long addr;
1188 	void *vaddr;
1189 	int ret;
1190 
1191 	/*
1192 	 * If no memory is reserved then we can not register for firmware-
1193 	 * assisted dump.
1194 	 */
1195 	if (!fw_dump.reserve_dump_area_size)
1196 		return -ENODEV;
1197 
1198 	ret = fadump_setup_crash_memory_ranges();
1199 	if (ret)
1200 		return ret;
1201 
1202 	addr = fw_dump.fadumphdr_addr;
1203 
1204 	/* Initialize fadump crash info header. */
1205 	addr = init_fadump_header(addr);
1206 	vaddr = __va(addr);
1207 
1208 	pr_debug("Creating ELF core headers at %#016lx\n", addr);
1209 	fadump_create_elfcore_headers(vaddr);
1210 
1211 	/* register the future kernel dump with firmware. */
1212 	pr_debug("Registering for firmware-assisted kernel dump...\n");
1213 	return fw_dump.ops->fadump_register(&fw_dump);
1214 }
1215 
1216 void fadump_cleanup(void)
1217 {
1218 	if (!fw_dump.fadump_supported)
1219 		return;
1220 
1221 	/* Invalidate the registration only if dump is active. */
1222 	if (fw_dump.dump_active) {
1223 		pr_debug("Invalidating firmware-assisted dump registration\n");
1224 		fw_dump.ops->fadump_invalidate(&fw_dump);
1225 	} else if (fw_dump.dump_registered) {
1226 		/* Un-register Firmware-assisted dump if it was registered. */
1227 		fw_dump.ops->fadump_unregister(&fw_dump);
1228 		fadump_free_mem_ranges(&crash_mrange_info);
1229 	}
1230 
1231 	if (fw_dump.ops->fadump_cleanup)
1232 		fw_dump.ops->fadump_cleanup(&fw_dump);
1233 }
1234 
1235 static void fadump_free_reserved_memory(unsigned long start_pfn,
1236 					unsigned long end_pfn)
1237 {
1238 	unsigned long pfn;
1239 	unsigned long time_limit = jiffies + HZ;
1240 
1241 	pr_info("freeing reserved memory (0x%llx - 0x%llx)\n",
1242 		PFN_PHYS(start_pfn), PFN_PHYS(end_pfn));
1243 
1244 	for (pfn = start_pfn; pfn < end_pfn; pfn++) {
1245 		free_reserved_page(pfn_to_page(pfn));
1246 
1247 		if (time_after(jiffies, time_limit)) {
1248 			cond_resched();
1249 			time_limit = jiffies + HZ;
1250 		}
1251 	}
1252 }
1253 
1254 /*
1255  * Skip memory holes and free memory that was actually reserved.
1256  */
1257 static void fadump_release_reserved_area(u64 start, u64 end)
1258 {
1259 	unsigned long reg_spfn, reg_epfn;
1260 	u64 tstart, tend, spfn, epfn;
1261 	int i;
1262 
1263 	spfn = PHYS_PFN(start);
1264 	epfn = PHYS_PFN(end);
1265 
1266 	for_each_mem_pfn_range(i, MAX_NUMNODES, &reg_spfn, &reg_epfn, NULL) {
1267 		tstart = max_t(u64, spfn, reg_spfn);
1268 		tend   = min_t(u64, epfn, reg_epfn);
1269 
1270 		if (tstart < tend) {
1271 			fadump_free_reserved_memory(tstart, tend);
1272 
1273 			if (tend == epfn)
1274 				break;
1275 
1276 			spfn = tend;
1277 		}
1278 	}
1279 }
1280 
1281 /*
1282  * Sort the mem ranges in-place and merge adjacent ranges
1283  * to minimize the memory ranges count.
1284  */
1285 static void sort_and_merge_mem_ranges(struct fadump_mrange_info *mrange_info)
1286 {
1287 	struct fadump_memory_range *mem_ranges;
1288 	struct fadump_memory_range tmp_range;
1289 	u64 base, size;
1290 	int i, j, idx;
1291 
1292 	if (!reserved_mrange_info.mem_range_cnt)
1293 		return;
1294 
1295 	/* Sort the memory ranges */
1296 	mem_ranges = mrange_info->mem_ranges;
1297 	for (i = 0; i < mrange_info->mem_range_cnt; i++) {
1298 		idx = i;
1299 		for (j = (i + 1); j < mrange_info->mem_range_cnt; j++) {
1300 			if (mem_ranges[idx].base > mem_ranges[j].base)
1301 				idx = j;
1302 		}
1303 		if (idx != i) {
1304 			tmp_range = mem_ranges[idx];
1305 			mem_ranges[idx] = mem_ranges[i];
1306 			mem_ranges[i] = tmp_range;
1307 		}
1308 	}
1309 
1310 	/* Merge adjacent reserved ranges */
1311 	idx = 0;
1312 	for (i = 1; i < mrange_info->mem_range_cnt; i++) {
1313 		base = mem_ranges[i-1].base;
1314 		size = mem_ranges[i-1].size;
1315 		if (mem_ranges[i].base == (base + size))
1316 			mem_ranges[idx].size += mem_ranges[i].size;
1317 		else {
1318 			idx++;
1319 			if (i == idx)
1320 				continue;
1321 
1322 			mem_ranges[idx] = mem_ranges[i];
1323 		}
1324 	}
1325 	mrange_info->mem_range_cnt = idx + 1;
1326 }
1327 
1328 /*
1329  * Scan reserved-ranges to consider them while reserving/releasing
1330  * memory for FADump.
1331  */
1332 static void __init early_init_dt_scan_reserved_ranges(unsigned long node)
1333 {
1334 	const __be32 *prop;
1335 	int len, ret = -1;
1336 	unsigned long i;
1337 
1338 	/* reserved-ranges already scanned */
1339 	if (reserved_mrange_info.mem_range_cnt != 0)
1340 		return;
1341 
1342 	prop = of_get_flat_dt_prop(node, "reserved-ranges", &len);
1343 	if (!prop)
1344 		return;
1345 
1346 	/*
1347 	 * Each reserved range is an (address,size) pair, 2 cells each,
1348 	 * totalling 4 cells per range.
1349 	 */
1350 	for (i = 0; i < len / (sizeof(*prop) * 4); i++) {
1351 		u64 base, size;
1352 
1353 		base = of_read_number(prop + (i * 4) + 0, 2);
1354 		size = of_read_number(prop + (i * 4) + 2, 2);
1355 
1356 		if (size) {
1357 			ret = fadump_add_mem_range(&reserved_mrange_info,
1358 						   base, base + size);
1359 			if (ret < 0) {
1360 				pr_warn("some reserved ranges are ignored!\n");
1361 				break;
1362 			}
1363 		}
1364 	}
1365 
1366 	/* Compact reserved ranges */
1367 	sort_and_merge_mem_ranges(&reserved_mrange_info);
1368 }
1369 
1370 /*
1371  * Release the memory that was reserved during early boot to preserve the
1372  * crash'ed kernel's memory contents except reserved dump area (permanent
1373  * reservation) and reserved ranges used by F/W. The released memory will
1374  * be available for general use.
1375  */
1376 static void fadump_release_memory(u64 begin, u64 end)
1377 {
1378 	u64 ra_start, ra_end, tstart;
1379 	int i, ret;
1380 
1381 	ra_start = fw_dump.reserve_dump_area_start;
1382 	ra_end = ra_start + fw_dump.reserve_dump_area_size;
1383 
1384 	/*
1385 	 * If reserved ranges array limit is hit, overwrite the last reserved
1386 	 * memory range with reserved dump area to ensure it is excluded from
1387 	 * the memory being released (reused for next FADump registration).
1388 	 */
1389 	if (reserved_mrange_info.mem_range_cnt ==
1390 	    reserved_mrange_info.max_mem_ranges)
1391 		reserved_mrange_info.mem_range_cnt--;
1392 
1393 	ret = fadump_add_mem_range(&reserved_mrange_info, ra_start, ra_end);
1394 	if (ret != 0)
1395 		return;
1396 
1397 	/* Get the reserved ranges list in order first. */
1398 	sort_and_merge_mem_ranges(&reserved_mrange_info);
1399 
1400 	/* Exclude reserved ranges and release remaining memory */
1401 	tstart = begin;
1402 	for (i = 0; i < reserved_mrange_info.mem_range_cnt; i++) {
1403 		ra_start = reserved_mrange_info.mem_ranges[i].base;
1404 		ra_end = ra_start + reserved_mrange_info.mem_ranges[i].size;
1405 
1406 		if (tstart >= ra_end)
1407 			continue;
1408 
1409 		if (tstart < ra_start)
1410 			fadump_release_reserved_area(tstart, ra_start);
1411 		tstart = ra_end;
1412 	}
1413 
1414 	if (tstart < end)
1415 		fadump_release_reserved_area(tstart, end);
1416 }
1417 
1418 static void fadump_invalidate_release_mem(void)
1419 {
1420 	mutex_lock(&fadump_mutex);
1421 	if (!fw_dump.dump_active) {
1422 		mutex_unlock(&fadump_mutex);
1423 		return;
1424 	}
1425 
1426 	fadump_cleanup();
1427 	mutex_unlock(&fadump_mutex);
1428 
1429 	fadump_release_memory(fw_dump.boot_mem_top, memblock_end_of_DRAM());
1430 	fadump_free_cpu_notes_buf();
1431 
1432 	/*
1433 	 * Setup kernel metadata and initialize the kernel dump
1434 	 * memory structure for FADump re-registration.
1435 	 */
1436 	if (fw_dump.ops->fadump_setup_metadata &&
1437 	    (fw_dump.ops->fadump_setup_metadata(&fw_dump) < 0))
1438 		pr_warn("Failed to setup kernel metadata!\n");
1439 	fw_dump.ops->fadump_init_mem_struct(&fw_dump);
1440 }
1441 
1442 static ssize_t release_mem_store(struct kobject *kobj,
1443 				 struct kobj_attribute *attr,
1444 				 const char *buf, size_t count)
1445 {
1446 	int input = -1;
1447 
1448 	if (!fw_dump.dump_active)
1449 		return -EPERM;
1450 
1451 	if (kstrtoint(buf, 0, &input))
1452 		return -EINVAL;
1453 
1454 	if (input == 1) {
1455 		/*
1456 		 * Take away the '/proc/vmcore'. We are releasing the dump
1457 		 * memory, hence it will not be valid anymore.
1458 		 */
1459 #ifdef CONFIG_PROC_VMCORE
1460 		vmcore_cleanup();
1461 #endif
1462 		fadump_invalidate_release_mem();
1463 
1464 	} else
1465 		return -EINVAL;
1466 	return count;
1467 }
1468 
1469 /* Release the reserved memory and disable the FADump */
1470 static void __init unregister_fadump(void)
1471 {
1472 	fadump_cleanup();
1473 	fadump_release_memory(fw_dump.reserve_dump_area_start,
1474 			      fw_dump.reserve_dump_area_size);
1475 	fw_dump.fadump_enabled = 0;
1476 	kobject_put(fadump_kobj);
1477 }
1478 
1479 static ssize_t enabled_show(struct kobject *kobj,
1480 			    struct kobj_attribute *attr,
1481 			    char *buf)
1482 {
1483 	return sprintf(buf, "%d\n", fw_dump.fadump_enabled);
1484 }
1485 
1486 static ssize_t mem_reserved_show(struct kobject *kobj,
1487 				 struct kobj_attribute *attr,
1488 				 char *buf)
1489 {
1490 	return sprintf(buf, "%ld\n", fw_dump.reserve_dump_area_size);
1491 }
1492 
1493 static ssize_t registered_show(struct kobject *kobj,
1494 			       struct kobj_attribute *attr,
1495 			       char *buf)
1496 {
1497 	return sprintf(buf, "%d\n", fw_dump.dump_registered);
1498 }
1499 
1500 static ssize_t registered_store(struct kobject *kobj,
1501 				struct kobj_attribute *attr,
1502 				const char *buf, size_t count)
1503 {
1504 	int ret = 0;
1505 	int input = -1;
1506 
1507 	if (!fw_dump.fadump_enabled || fw_dump.dump_active)
1508 		return -EPERM;
1509 
1510 	if (kstrtoint(buf, 0, &input))
1511 		return -EINVAL;
1512 
1513 	mutex_lock(&fadump_mutex);
1514 
1515 	switch (input) {
1516 	case 0:
1517 		if (fw_dump.dump_registered == 0) {
1518 			goto unlock_out;
1519 		}
1520 
1521 		/* Un-register Firmware-assisted dump */
1522 		pr_debug("Un-register firmware-assisted dump\n");
1523 		fw_dump.ops->fadump_unregister(&fw_dump);
1524 		break;
1525 	case 1:
1526 		if (fw_dump.dump_registered == 1) {
1527 			/* Un-register Firmware-assisted dump */
1528 			fw_dump.ops->fadump_unregister(&fw_dump);
1529 		}
1530 		/* Register Firmware-assisted dump */
1531 		ret = register_fadump();
1532 		break;
1533 	default:
1534 		ret = -EINVAL;
1535 		break;
1536 	}
1537 
1538 unlock_out:
1539 	mutex_unlock(&fadump_mutex);
1540 	return ret < 0 ? ret : count;
1541 }
1542 
1543 static int fadump_region_show(struct seq_file *m, void *private)
1544 {
1545 	if (!fw_dump.fadump_enabled)
1546 		return 0;
1547 
1548 	mutex_lock(&fadump_mutex);
1549 	fw_dump.ops->fadump_region_show(&fw_dump, m);
1550 	mutex_unlock(&fadump_mutex);
1551 	return 0;
1552 }
1553 
1554 static struct kobj_attribute release_attr = __ATTR_WO(release_mem);
1555 static struct kobj_attribute enable_attr = __ATTR_RO(enabled);
1556 static struct kobj_attribute register_attr = __ATTR_RW(registered);
1557 static struct kobj_attribute mem_reserved_attr = __ATTR_RO(mem_reserved);
1558 
1559 static struct attribute *fadump_attrs[] = {
1560 	&enable_attr.attr,
1561 	&register_attr.attr,
1562 	&mem_reserved_attr.attr,
1563 	NULL,
1564 };
1565 
1566 ATTRIBUTE_GROUPS(fadump);
1567 
1568 DEFINE_SHOW_ATTRIBUTE(fadump_region);
1569 
1570 static void __init fadump_init_files(void)
1571 {
1572 	int rc = 0;
1573 
1574 	fadump_kobj = kobject_create_and_add("fadump", kernel_kobj);
1575 	if (!fadump_kobj) {
1576 		pr_err("failed to create fadump kobject\n");
1577 		return;
1578 	}
1579 
1580 	debugfs_create_file("fadump_region", 0444, arch_debugfs_dir, NULL,
1581 			    &fadump_region_fops);
1582 
1583 	if (fw_dump.dump_active) {
1584 		rc = sysfs_create_file(fadump_kobj, &release_attr.attr);
1585 		if (rc)
1586 			pr_err("unable to create release_mem sysfs file (%d)\n",
1587 			       rc);
1588 	}
1589 
1590 	rc = sysfs_create_groups(fadump_kobj, fadump_groups);
1591 	if (rc) {
1592 		pr_err("sysfs group creation failed (%d), unregistering FADump",
1593 		       rc);
1594 		unregister_fadump();
1595 		return;
1596 	}
1597 
1598 	/*
1599 	 * The FADump sysfs are moved from kernel_kobj to fadump_kobj need to
1600 	 * create symlink at old location to maintain backward compatibility.
1601 	 *
1602 	 *      - fadump_enabled -> fadump/enabled
1603 	 *      - fadump_registered -> fadump/registered
1604 	 *      - fadump_release_mem -> fadump/release_mem
1605 	 */
1606 	rc = compat_only_sysfs_link_entry_to_kobj(kernel_kobj, fadump_kobj,
1607 						  "enabled", "fadump_enabled");
1608 	if (rc) {
1609 		pr_err("unable to create fadump_enabled symlink (%d)", rc);
1610 		return;
1611 	}
1612 
1613 	rc = compat_only_sysfs_link_entry_to_kobj(kernel_kobj, fadump_kobj,
1614 						  "registered",
1615 						  "fadump_registered");
1616 	if (rc) {
1617 		pr_err("unable to create fadump_registered symlink (%d)", rc);
1618 		sysfs_remove_link(kernel_kobj, "fadump_enabled");
1619 		return;
1620 	}
1621 
1622 	if (fw_dump.dump_active) {
1623 		rc = compat_only_sysfs_link_entry_to_kobj(kernel_kobj,
1624 							  fadump_kobj,
1625 							  "release_mem",
1626 							  "fadump_release_mem");
1627 		if (rc)
1628 			pr_err("unable to create fadump_release_mem symlink (%d)",
1629 			       rc);
1630 	}
1631 	return;
1632 }
1633 
1634 /*
1635  * Prepare for firmware-assisted dump.
1636  */
1637 int __init setup_fadump(void)
1638 {
1639 	if (!fw_dump.fadump_supported)
1640 		return 0;
1641 
1642 	fadump_init_files();
1643 	fadump_show_config();
1644 
1645 	if (!fw_dump.fadump_enabled)
1646 		return 1;
1647 
1648 	/*
1649 	 * If dump data is available then see if it is valid and prepare for
1650 	 * saving it to the disk.
1651 	 */
1652 	if (fw_dump.dump_active) {
1653 		/*
1654 		 * if dump process fails then invalidate the registration
1655 		 * and release memory before proceeding for re-registration.
1656 		 */
1657 		if (fw_dump.ops->fadump_process(&fw_dump) < 0)
1658 			fadump_invalidate_release_mem();
1659 	}
1660 	/* Initialize the kernel dump memory structure and register with f/w */
1661 	else if (fw_dump.reserve_dump_area_size) {
1662 		fw_dump.ops->fadump_init_mem_struct(&fw_dump);
1663 		register_fadump();
1664 	}
1665 
1666 	/*
1667 	 * In case of panic, fadump is triggered via ppc_panic_event()
1668 	 * panic notifier. Setting crash_kexec_post_notifiers to 'true'
1669 	 * lets panic() function take crash friendly path before panic
1670 	 * notifiers are invoked.
1671 	 */
1672 	crash_kexec_post_notifiers = true;
1673 
1674 	return 1;
1675 }
1676 /*
1677  * Use subsys_initcall_sync() here because there is dependency with
1678  * crash_save_vmcoreinfo_init(), which mush run first to ensure vmcoreinfo initialization
1679  * is done before regisering with f/w.
1680  */
1681 subsys_initcall_sync(setup_fadump);
1682 #else /* !CONFIG_PRESERVE_FA_DUMP */
1683 
1684 /* Scan the Firmware Assisted dump configuration details. */
1685 int __init early_init_dt_scan_fw_dump(unsigned long node, const char *uname,
1686 				      int depth, void *data)
1687 {
1688 	if ((depth != 1) || (strcmp(uname, "ibm,opal") != 0))
1689 		return 0;
1690 
1691 	opal_fadump_dt_scan(&fw_dump, node);
1692 	return 1;
1693 }
1694 
1695 /*
1696  * When dump is active but PRESERVE_FA_DUMP is enabled on the kernel,
1697  * preserve crash data. The subsequent memory preserving kernel boot
1698  * is likely to process this crash data.
1699  */
1700 int __init fadump_reserve_mem(void)
1701 {
1702 	if (fw_dump.dump_active) {
1703 		/*
1704 		 * If last boot has crashed then reserve all the memory
1705 		 * above boot memory to preserve crash data.
1706 		 */
1707 		pr_info("Preserving crash data for processing in next boot.\n");
1708 		fadump_reserve_crash_area(fw_dump.boot_mem_top);
1709 	} else
1710 		pr_debug("FADump-aware kernel..\n");
1711 
1712 	return 1;
1713 }
1714 #endif /* CONFIG_PRESERVE_FA_DUMP */
1715 
1716 /* Preserve everything above the base address */
1717 static void __init fadump_reserve_crash_area(u64 base)
1718 {
1719 	u64 i, mstart, mend, msize;
1720 
1721 	for_each_mem_range(i, &mstart, &mend) {
1722 		msize  = mend - mstart;
1723 
1724 		if ((mstart + msize) < base)
1725 			continue;
1726 
1727 		if (mstart < base) {
1728 			msize -= (base - mstart);
1729 			mstart = base;
1730 		}
1731 
1732 		pr_info("Reserving %lluMB of memory at %#016llx for preserving crash data",
1733 			(msize >> 20), mstart);
1734 		memblock_reserve(mstart, msize);
1735 	}
1736 }
1737 
1738 unsigned long __init arch_reserved_kernel_pages(void)
1739 {
1740 	return memblock_reserved_size() / PAGE_SIZE;
1741 }
1742