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