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