xref: /openbmc/linux/arch/powerpc/kernel/fadump.c (revision 41df5928721ff4b5f83767cd5e8b77862fc62bb3)
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 DEFINE_MUTEX(fadump_mutex);
38 struct fad_crash_memory_ranges *crash_memory_ranges;
39 int crash_memory_ranges_size;
40 int crash_mem_ranges;
41 int max_crash_mem_ranges;
42 
43 #ifdef CONFIG_CMA
44 static struct cma *fadump_cma;
45 
46 /*
47  * fadump_cma_init() - Initialize CMA area from a fadump reserved memory
48  *
49  * This function initializes CMA area from fadump reserved memory.
50  * The total size of fadump reserved memory covers for boot memory size
51  * + cpu data size + hpte size and metadata.
52  * Initialize only the area equivalent to boot memory size for CMA use.
53  * The reamining portion of fadump reserved memory will be not given
54  * to CMA and pages for thoes will stay reserved. boot memory size is
55  * aligned per CMA requirement to satisy cma_init_reserved_mem() call.
56  * But for some reason even if it fails we still have the memory reservation
57  * with us and we can still continue doing fadump.
58  */
59 int __init fadump_cma_init(void)
60 {
61 	unsigned long long base, size;
62 	int rc;
63 
64 	if (!fw_dump.fadump_enabled)
65 		return 0;
66 
67 	/*
68 	 * Do not use CMA if user has provided fadump=nocma kernel parameter.
69 	 * Return 1 to continue with fadump old behaviour.
70 	 */
71 	if (fw_dump.nocma)
72 		return 1;
73 
74 	base = fw_dump.reserve_dump_area_start;
75 	size = fw_dump.boot_memory_size;
76 
77 	if (!size)
78 		return 0;
79 
80 	rc = cma_init_reserved_mem(base, size, 0, "fadump_cma", &fadump_cma);
81 	if (rc) {
82 		pr_err("Failed to init cma area for firmware-assisted dump,%d\n", rc);
83 		/*
84 		 * Though the CMA init has failed we still have memory
85 		 * reservation with us. The reserved memory will be
86 		 * blocked from production system usage.  Hence return 1,
87 		 * so that we can continue with fadump.
88 		 */
89 		return 1;
90 	}
91 
92 	/*
93 	 * So we now have successfully initialized cma area for fadump.
94 	 */
95 	pr_info("Initialized 0x%lx bytes cma area at %ldMB from 0x%lx "
96 		"bytes of memory reserved for firmware-assisted dump\n",
97 		cma_get_size(fadump_cma),
98 		(unsigned long)cma_get_base(fadump_cma) >> 20,
99 		fw_dump.reserve_dump_area_size);
100 	return 1;
101 }
102 #else
103 static int __init fadump_cma_init(void) { return 1; }
104 #endif /* CONFIG_CMA */
105 
106 /* Scan the Firmware Assisted dump configuration details. */
107 int __init early_init_dt_scan_fw_dump(unsigned long node, const char *uname,
108 				      int depth, void *data)
109 {
110 	if (depth != 1)
111 		return 0;
112 
113 	if (strcmp(uname, "rtas") == 0) {
114 		rtas_fadump_dt_scan(&fw_dump, node);
115 		return 1;
116 	}
117 
118 	if (strcmp(uname, "ibm,opal") == 0) {
119 		opal_fadump_dt_scan(&fw_dump, node);
120 		return 1;
121 	}
122 
123 	return 0;
124 }
125 
126 /*
127  * If fadump is registered, check if the memory provided
128  * falls within boot memory area and reserved memory area.
129  */
130 int is_fadump_memory_area(u64 addr, ulong size)
131 {
132 	u64 d_start = fw_dump.reserve_dump_area_start;
133 	u64 d_end = d_start + fw_dump.reserve_dump_area_size;
134 
135 	if (!fw_dump.dump_registered)
136 		return 0;
137 
138 	if (((addr + size) > d_start) && (addr <= d_end))
139 		return 1;
140 
141 	return (addr + size) > RMA_START && addr <= fw_dump.boot_memory_size;
142 }
143 
144 int should_fadump_crash(void)
145 {
146 	if (!fw_dump.dump_registered || !fw_dump.fadumphdr_addr)
147 		return 0;
148 	return 1;
149 }
150 
151 int is_fadump_active(void)
152 {
153 	return fw_dump.dump_active;
154 }
155 
156 /*
157  * Returns true, if there are no holes in memory area between d_start to d_end,
158  * false otherwise.
159  */
160 static bool is_fadump_mem_area_contiguous(u64 d_start, u64 d_end)
161 {
162 	struct memblock_region *reg;
163 	bool ret = false;
164 	u64 start, end;
165 
166 	for_each_memblock(memory, reg) {
167 		start = max_t(u64, d_start, reg->base);
168 		end = min_t(u64, d_end, (reg->base + reg->size));
169 		if (d_start < end) {
170 			/* Memory hole from d_start to start */
171 			if (start > d_start)
172 				break;
173 
174 			if (end == d_end) {
175 				ret = true;
176 				break;
177 			}
178 
179 			d_start = end + 1;
180 		}
181 	}
182 
183 	return ret;
184 }
185 
186 /*
187  * Returns true, if there are no holes in boot memory area,
188  * false otherwise.
189  */
190 bool is_fadump_boot_mem_contiguous(void)
191 {
192 	return is_fadump_mem_area_contiguous(0, fw_dump.boot_memory_size);
193 }
194 
195 /*
196  * Returns true, if there are no holes in reserved memory area,
197  * false otherwise.
198  */
199 bool is_fadump_reserved_mem_contiguous(void)
200 {
201 	u64 d_start, d_end;
202 
203 	d_start	= fw_dump.reserve_dump_area_start;
204 	d_end	= d_start + fw_dump.reserve_dump_area_size;
205 	return is_fadump_mem_area_contiguous(d_start, d_end);
206 }
207 
208 /* Print firmware assisted dump configurations for debugging purpose. */
209 static void fadump_show_config(void)
210 {
211 	pr_debug("Support for firmware-assisted dump (fadump): %s\n",
212 			(fw_dump.fadump_supported ? "present" : "no support"));
213 
214 	if (!fw_dump.fadump_supported)
215 		return;
216 
217 	pr_debug("Fadump enabled    : %s\n",
218 				(fw_dump.fadump_enabled ? "yes" : "no"));
219 	pr_debug("Dump Active       : %s\n",
220 				(fw_dump.dump_active ? "yes" : "no"));
221 	pr_debug("Dump section sizes:\n");
222 	pr_debug("    CPU state data size: %lx\n", fw_dump.cpu_state_data_size);
223 	pr_debug("    HPTE region size   : %lx\n", fw_dump.hpte_region_size);
224 	pr_debug("Boot memory size  : %lx\n", fw_dump.boot_memory_size);
225 }
226 
227 /**
228  * fadump_calculate_reserve_size(): reserve variable boot area 5% of System RAM
229  *
230  * Function to find the largest memory size we need to reserve during early
231  * boot process. This will be the size of the memory that is required for a
232  * kernel to boot successfully.
233  *
234  * This function has been taken from phyp-assisted dump feature implementation.
235  *
236  * returns larger of 256MB or 5% rounded down to multiples of 256MB.
237  *
238  * TODO: Come up with better approach to find out more accurate memory size
239  * that is required for a kernel to boot successfully.
240  *
241  */
242 static inline unsigned long fadump_calculate_reserve_size(void)
243 {
244 	int ret;
245 	unsigned long long base, size;
246 
247 	if (fw_dump.reserve_bootvar)
248 		pr_warn("'fadump_reserve_mem=' parameter is deprecated in favor of 'crashkernel=' parameter.\n");
249 
250 	/*
251 	 * Check if the size is specified through crashkernel= cmdline
252 	 * option. If yes, then use that but ignore base as fadump reserves
253 	 * memory at a predefined offset.
254 	 */
255 	ret = parse_crashkernel(boot_command_line, memblock_phys_mem_size(),
256 				&size, &base);
257 	if (ret == 0 && size > 0) {
258 		unsigned long max_size;
259 
260 		if (fw_dump.reserve_bootvar)
261 			pr_info("Using 'crashkernel=' parameter for memory reservation.\n");
262 
263 		fw_dump.reserve_bootvar = (unsigned long)size;
264 
265 		/*
266 		 * Adjust if the boot memory size specified is above
267 		 * the upper limit.
268 		 */
269 		max_size = memblock_phys_mem_size() / MAX_BOOT_MEM_RATIO;
270 		if (fw_dump.reserve_bootvar > max_size) {
271 			fw_dump.reserve_bootvar = max_size;
272 			pr_info("Adjusted boot memory size to %luMB\n",
273 				(fw_dump.reserve_bootvar >> 20));
274 		}
275 
276 		return fw_dump.reserve_bootvar;
277 	} else if (fw_dump.reserve_bootvar) {
278 		/*
279 		 * 'fadump_reserve_mem=' is being used to reserve memory
280 		 * for firmware-assisted dump.
281 		 */
282 		return fw_dump.reserve_bootvar;
283 	}
284 
285 	/* divide by 20 to get 5% of value */
286 	size = memblock_phys_mem_size() / 20;
287 
288 	/* round it down in multiples of 256 */
289 	size = size & ~0x0FFFFFFFUL;
290 
291 	/* Truncate to memory_limit. We don't want to over reserve the memory.*/
292 	if (memory_limit && size > memory_limit)
293 		size = memory_limit;
294 
295 	return (size > MIN_BOOT_MEM ? size : MIN_BOOT_MEM);
296 }
297 
298 /*
299  * Calculate the total memory size required to be reserved for
300  * firmware-assisted dump registration.
301  */
302 static unsigned long get_fadump_area_size(void)
303 {
304 	unsigned long size = 0;
305 
306 	size += fw_dump.cpu_state_data_size;
307 	size += fw_dump.hpte_region_size;
308 	size += fw_dump.boot_memory_size;
309 	size += sizeof(struct fadump_crash_info_header);
310 	size += sizeof(struct elfhdr); /* ELF core header.*/
311 	size += sizeof(struct elf_phdr); /* place holder for cpu notes */
312 	/* Program headers for crash memory regions. */
313 	size += sizeof(struct elf_phdr) * (memblock_num_regions(memory) + 2);
314 
315 	size = PAGE_ALIGN(size);
316 	return size;
317 }
318 
319 static void __init fadump_reserve_crash_area(unsigned long base,
320 					     unsigned long size)
321 {
322 	struct memblock_region *reg;
323 	unsigned long mstart, mend, msize;
324 
325 	for_each_memblock(memory, reg) {
326 		mstart = max_t(unsigned long, base, reg->base);
327 		mend = reg->base + reg->size;
328 		mend = min(base + size, mend);
329 
330 		if (mstart < mend) {
331 			msize = mend - mstart;
332 			memblock_reserve(mstart, msize);
333 			pr_info("Reserved %ldMB of memory at %#016lx for saving crash dump\n",
334 				(msize >> 20), mstart);
335 		}
336 	}
337 }
338 
339 int __init fadump_reserve_mem(void)
340 {
341 	unsigned long base, size, memory_boundary;
342 
343 	if (!fw_dump.fadump_enabled)
344 		return 0;
345 
346 	if (!fw_dump.fadump_supported) {
347 		printk(KERN_INFO "Firmware-assisted dump is not supported on"
348 				" this hardware\n");
349 		fw_dump.fadump_enabled = 0;
350 		return 0;
351 	}
352 	/*
353 	 * Initialize boot memory size
354 	 * If dump is active then we have already calculated the size during
355 	 * first kernel.
356 	 */
357 	if (!fw_dump.dump_active) {
358 		fw_dump.boot_memory_size = fadump_calculate_reserve_size();
359 #ifdef CONFIG_CMA
360 		if (!fw_dump.nocma)
361 			fw_dump.boot_memory_size =
362 				ALIGN(fw_dump.boot_memory_size,
363 							FADUMP_CMA_ALIGNMENT);
364 #endif
365 	}
366 
367 	/*
368 	 * Calculate the memory boundary.
369 	 * If memory_limit is less than actual memory boundary then reserve
370 	 * the memory for fadump beyond the memory_limit and adjust the
371 	 * memory_limit accordingly, so that the running kernel can run with
372 	 * specified memory_limit.
373 	 */
374 	if (memory_limit && memory_limit < memblock_end_of_DRAM()) {
375 		size = get_fadump_area_size();
376 		if ((memory_limit + size) < memblock_end_of_DRAM())
377 			memory_limit += size;
378 		else
379 			memory_limit = memblock_end_of_DRAM();
380 		printk(KERN_INFO "Adjusted memory_limit for firmware-assisted"
381 				" dump, now %#016llx\n", memory_limit);
382 	}
383 	if (memory_limit)
384 		memory_boundary = memory_limit;
385 	else
386 		memory_boundary = memblock_end_of_DRAM();
387 
388 	size = get_fadump_area_size();
389 	fw_dump.reserve_dump_area_size = size;
390 	if (fw_dump.dump_active) {
391 		pr_info("Firmware-assisted dump is active.\n");
392 
393 #ifdef CONFIG_HUGETLB_PAGE
394 		/*
395 		 * FADump capture kernel doesn't care much about hugepages.
396 		 * In fact, handling hugepages in capture kernel is asking for
397 		 * trouble. So, disable HugeTLB support when fadump is active.
398 		 */
399 		hugetlb_disabled = true;
400 #endif
401 		/*
402 		 * If last boot has crashed then reserve all the memory
403 		 * above boot_memory_size so that we don't touch it until
404 		 * dump is written to disk by userspace tool. This memory
405 		 * will be released for general use once the dump is saved.
406 		 */
407 		base = fw_dump.boot_memory_size;
408 		size = memory_boundary - base;
409 		fadump_reserve_crash_area(base, size);
410 
411 		pr_debug("fadumphdr_addr = %#016lx\n", fw_dump.fadumphdr_addr);
412 		pr_debug("Reserve dump area start address: 0x%lx\n",
413 			 fw_dump.reserve_dump_area_start);
414 	} else {
415 		/*
416 		 * Reserve memory at an offset closer to bottom of the RAM to
417 		 * minimize the impact of memory hot-remove operation. We can't
418 		 * use memblock_find_in_range() here since it doesn't allocate
419 		 * from bottom to top.
420 		 */
421 		for (base = fw_dump.boot_memory_size;
422 		     base <= (memory_boundary - size);
423 		     base += size) {
424 			if (memblock_is_region_memory(base, size) &&
425 			    !memblock_is_region_reserved(base, size))
426 				break;
427 		}
428 		if ((base > (memory_boundary - size)) ||
429 		    memblock_reserve(base, size)) {
430 			pr_err("Failed to reserve memory\n");
431 			return 0;
432 		}
433 
434 		pr_info("Reserved %ldMB of memory at %ldMB for firmware-"
435 			"assisted dump (System RAM: %ldMB)\n",
436 			(unsigned long)(size >> 20),
437 			(unsigned long)(base >> 20),
438 			(unsigned long)(memblock_phys_mem_size() >> 20));
439 
440 		fw_dump.reserve_dump_area_start = base;
441 		return fadump_cma_init();
442 	}
443 	return 1;
444 }
445 
446 unsigned long __init arch_reserved_kernel_pages(void)
447 {
448 	return memblock_reserved_size() / PAGE_SIZE;
449 }
450 
451 /* Look for fadump= cmdline option. */
452 static int __init early_fadump_param(char *p)
453 {
454 	if (!p)
455 		return 1;
456 
457 	if (strncmp(p, "on", 2) == 0)
458 		fw_dump.fadump_enabled = 1;
459 	else if (strncmp(p, "off", 3) == 0)
460 		fw_dump.fadump_enabled = 0;
461 	else if (strncmp(p, "nocma", 5) == 0) {
462 		fw_dump.fadump_enabled = 1;
463 		fw_dump.nocma = 1;
464 	}
465 
466 	return 0;
467 }
468 early_param("fadump", early_fadump_param);
469 
470 /*
471  * Look for fadump_reserve_mem= cmdline option
472  * TODO: Remove references to 'fadump_reserve_mem=' parameter,
473  *       the sooner 'crashkernel=' parameter is accustomed to.
474  */
475 static int __init early_fadump_reserve_mem(char *p)
476 {
477 	if (p)
478 		fw_dump.reserve_bootvar = memparse(p, &p);
479 	return 0;
480 }
481 early_param("fadump_reserve_mem", early_fadump_reserve_mem);
482 
483 void crash_fadump(struct pt_regs *regs, const char *str)
484 {
485 	struct fadump_crash_info_header *fdh = NULL;
486 	int old_cpu, this_cpu;
487 
488 	if (!should_fadump_crash())
489 		return;
490 
491 	/*
492 	 * old_cpu == -1 means this is the first CPU which has come here,
493 	 * go ahead and trigger fadump.
494 	 *
495 	 * old_cpu != -1 means some other CPU has already on it's way
496 	 * to trigger fadump, just keep looping here.
497 	 */
498 	this_cpu = smp_processor_id();
499 	old_cpu = cmpxchg(&crashing_cpu, -1, this_cpu);
500 
501 	if (old_cpu != -1) {
502 		/*
503 		 * We can't loop here indefinitely. Wait as long as fadump
504 		 * is in force. If we race with fadump un-registration this
505 		 * loop will break and then we go down to normal panic path
506 		 * and reboot. If fadump is in force the first crashing
507 		 * cpu will definitely trigger fadump.
508 		 */
509 		while (fw_dump.dump_registered)
510 			cpu_relax();
511 		return;
512 	}
513 
514 	fdh = __va(fw_dump.fadumphdr_addr);
515 	fdh->crashing_cpu = crashing_cpu;
516 	crash_save_vmcoreinfo();
517 
518 	if (regs)
519 		fdh->regs = *regs;
520 	else
521 		ppc_save_regs(&fdh->regs);
522 
523 	fdh->online_mask = *cpu_online_mask;
524 
525 	fw_dump.ops->fadump_trigger(fdh, str);
526 }
527 
528 u32 *fadump_regs_to_elf_notes(u32 *buf, struct pt_regs *regs)
529 {
530 	struct elf_prstatus prstatus;
531 
532 	memset(&prstatus, 0, sizeof(prstatus));
533 	/*
534 	 * FIXME: How do i get PID? Do I really need it?
535 	 * prstatus.pr_pid = ????
536 	 */
537 	elf_core_copy_kernel_regs(&prstatus.pr_reg, regs);
538 	buf = append_elf_note(buf, CRASH_CORE_NOTE_NAME, NT_PRSTATUS,
539 			      &prstatus, sizeof(prstatus));
540 	return buf;
541 }
542 
543 void fadump_update_elfcore_header(char *bufp)
544 {
545 	struct elfhdr *elf;
546 	struct elf_phdr *phdr;
547 
548 	elf = (struct elfhdr *)bufp;
549 	bufp += sizeof(struct elfhdr);
550 
551 	/* First note is a place holder for cpu notes info. */
552 	phdr = (struct elf_phdr *)bufp;
553 
554 	if (phdr->p_type == PT_NOTE) {
555 		phdr->p_paddr	= __pa(fw_dump.cpu_notes_buf_vaddr);
556 		phdr->p_offset	= phdr->p_paddr;
557 		phdr->p_filesz	= fw_dump.cpu_notes_buf_size;
558 		phdr->p_memsz = fw_dump.cpu_notes_buf_size;
559 	}
560 	return;
561 }
562 
563 static void *fadump_alloc_buffer(unsigned long size)
564 {
565 	unsigned long count, i;
566 	struct page *page;
567 	void *vaddr;
568 
569 	vaddr = alloc_pages_exact(size, GFP_KERNEL | __GFP_ZERO);
570 	if (!vaddr)
571 		return NULL;
572 
573 	count = PAGE_ALIGN(size) / PAGE_SIZE;
574 	page = virt_to_page(vaddr);
575 	for (i = 0; i < count; i++)
576 		mark_page_reserved(page + i);
577 	return vaddr;
578 }
579 
580 static void fadump_free_buffer(unsigned long vaddr, unsigned long size)
581 {
582 	free_reserved_area((void *)vaddr, (void *)(vaddr + size), -1, NULL);
583 }
584 
585 s32 fadump_setup_cpu_notes_buf(u32 num_cpus)
586 {
587 	/* Allocate buffer to hold cpu crash notes. */
588 	fw_dump.cpu_notes_buf_size = num_cpus * sizeof(note_buf_t);
589 	fw_dump.cpu_notes_buf_size = PAGE_ALIGN(fw_dump.cpu_notes_buf_size);
590 	fw_dump.cpu_notes_buf_vaddr =
591 		(unsigned long)fadump_alloc_buffer(fw_dump.cpu_notes_buf_size);
592 	if (!fw_dump.cpu_notes_buf_vaddr) {
593 		pr_err("Failed to allocate %ld bytes for CPU notes buffer\n",
594 		       fw_dump.cpu_notes_buf_size);
595 		return -ENOMEM;
596 	}
597 
598 	pr_debug("Allocated buffer for cpu notes of size %ld at 0x%lx\n",
599 		 fw_dump.cpu_notes_buf_size,
600 		 fw_dump.cpu_notes_buf_vaddr);
601 	return 0;
602 }
603 
604 void fadump_free_cpu_notes_buf(void)
605 {
606 	if (!fw_dump.cpu_notes_buf_vaddr)
607 		return;
608 
609 	fadump_free_buffer(fw_dump.cpu_notes_buf_vaddr,
610 			   fw_dump.cpu_notes_buf_size);
611 	fw_dump.cpu_notes_buf_vaddr = 0;
612 	fw_dump.cpu_notes_buf_size = 0;
613 }
614 
615 static void free_crash_memory_ranges(void)
616 {
617 	kfree(crash_memory_ranges);
618 	crash_memory_ranges = NULL;
619 	crash_memory_ranges_size = 0;
620 	max_crash_mem_ranges = 0;
621 }
622 
623 /*
624  * Allocate or reallocate crash memory ranges array in incremental units
625  * of PAGE_SIZE.
626  */
627 static int allocate_crash_memory_ranges(void)
628 {
629 	struct fad_crash_memory_ranges *new_array;
630 	u64 new_size;
631 
632 	new_size = crash_memory_ranges_size + PAGE_SIZE;
633 	pr_debug("Allocating %llu bytes of memory for crash memory ranges\n",
634 		 new_size);
635 
636 	new_array = krealloc(crash_memory_ranges, new_size, GFP_KERNEL);
637 	if (new_array == NULL) {
638 		pr_err("Insufficient memory for setting up crash memory ranges\n");
639 		free_crash_memory_ranges();
640 		return -ENOMEM;
641 	}
642 
643 	crash_memory_ranges = new_array;
644 	crash_memory_ranges_size = new_size;
645 	max_crash_mem_ranges = (new_size /
646 				sizeof(struct fad_crash_memory_ranges));
647 	return 0;
648 }
649 
650 static inline int fadump_add_crash_memory(unsigned long long base,
651 					  unsigned long long end)
652 {
653 	u64  start, size;
654 	bool is_adjacent = false;
655 
656 	if (base == end)
657 		return 0;
658 
659 	/*
660 	 * Fold adjacent memory ranges to bring down the memory ranges/
661 	 * PT_LOAD segments count.
662 	 */
663 	if (crash_mem_ranges) {
664 		start = crash_memory_ranges[crash_mem_ranges - 1].base;
665 		size = crash_memory_ranges[crash_mem_ranges - 1].size;
666 
667 		if ((start + size) == base)
668 			is_adjacent = true;
669 	}
670 	if (!is_adjacent) {
671 		/* resize the array on reaching the limit */
672 		if (crash_mem_ranges == max_crash_mem_ranges) {
673 			int ret;
674 
675 			ret = allocate_crash_memory_ranges();
676 			if (ret)
677 				return ret;
678 		}
679 
680 		start = base;
681 		crash_memory_ranges[crash_mem_ranges].base = start;
682 		crash_mem_ranges++;
683 	}
684 
685 	crash_memory_ranges[crash_mem_ranges - 1].size = (end - start);
686 	pr_debug("crash_memory_range[%d] [%#016llx-%#016llx], %#llx bytes\n",
687 		(crash_mem_ranges - 1), start, end - 1, (end - start));
688 	return 0;
689 }
690 
691 static int fadump_exclude_reserved_area(unsigned long long start,
692 					unsigned long long end)
693 {
694 	unsigned long long ra_start, ra_end;
695 	int ret = 0;
696 
697 	ra_start = fw_dump.reserve_dump_area_start;
698 	ra_end = ra_start + fw_dump.reserve_dump_area_size;
699 
700 	if ((ra_start < end) && (ra_end > start)) {
701 		if ((start < ra_start) && (end > ra_end)) {
702 			ret = fadump_add_crash_memory(start, ra_start);
703 			if (ret)
704 				return ret;
705 
706 			ret = fadump_add_crash_memory(ra_end, end);
707 		} else if (start < ra_start) {
708 			ret = fadump_add_crash_memory(start, ra_start);
709 		} else if (ra_end < end) {
710 			ret = fadump_add_crash_memory(ra_end, end);
711 		}
712 	} else
713 		ret = fadump_add_crash_memory(start, end);
714 
715 	return ret;
716 }
717 
718 static int fadump_init_elfcore_header(char *bufp)
719 {
720 	struct elfhdr *elf;
721 
722 	elf = (struct elfhdr *) bufp;
723 	bufp += sizeof(struct elfhdr);
724 	memcpy(elf->e_ident, ELFMAG, SELFMAG);
725 	elf->e_ident[EI_CLASS] = ELF_CLASS;
726 	elf->e_ident[EI_DATA] = ELF_DATA;
727 	elf->e_ident[EI_VERSION] = EV_CURRENT;
728 	elf->e_ident[EI_OSABI] = ELF_OSABI;
729 	memset(elf->e_ident+EI_PAD, 0, EI_NIDENT-EI_PAD);
730 	elf->e_type = ET_CORE;
731 	elf->e_machine = ELF_ARCH;
732 	elf->e_version = EV_CURRENT;
733 	elf->e_entry = 0;
734 	elf->e_phoff = sizeof(struct elfhdr);
735 	elf->e_shoff = 0;
736 #if defined(_CALL_ELF)
737 	elf->e_flags = _CALL_ELF;
738 #else
739 	elf->e_flags = 0;
740 #endif
741 	elf->e_ehsize = sizeof(struct elfhdr);
742 	elf->e_phentsize = sizeof(struct elf_phdr);
743 	elf->e_phnum = 0;
744 	elf->e_shentsize = 0;
745 	elf->e_shnum = 0;
746 	elf->e_shstrndx = 0;
747 
748 	return 0;
749 }
750 
751 /*
752  * Traverse through memblock structure and setup crash memory ranges. These
753  * ranges will be used create PT_LOAD program headers in elfcore header.
754  */
755 static int fadump_setup_crash_memory_ranges(void)
756 {
757 	struct memblock_region *reg;
758 	unsigned long long start, end;
759 	int ret;
760 
761 	pr_debug("Setup crash memory ranges.\n");
762 	crash_mem_ranges = 0;
763 
764 	/*
765 	 * add the first memory chunk (RMA_START through boot_memory_size) as
766 	 * a separate memory chunk. The reason is, at the time crash firmware
767 	 * will move the content of this memory chunk to different location
768 	 * specified during fadump registration. We need to create a separate
769 	 * program header for this chunk with the correct offset.
770 	 */
771 	ret = fadump_add_crash_memory(RMA_START, fw_dump.boot_memory_size);
772 	if (ret)
773 		return ret;
774 
775 	for_each_memblock(memory, reg) {
776 		start = (unsigned long long)reg->base;
777 		end = start + (unsigned long long)reg->size;
778 
779 		/*
780 		 * skip the first memory chunk that is already added (RMA_START
781 		 * through boot_memory_size). This logic needs a relook if and
782 		 * when RMA_START changes to a non-zero value.
783 		 */
784 		BUILD_BUG_ON(RMA_START != 0);
785 		if (start < fw_dump.boot_memory_size) {
786 			if (end > fw_dump.boot_memory_size)
787 				start = fw_dump.boot_memory_size;
788 			else
789 				continue;
790 		}
791 
792 		/* add this range excluding the reserved dump area. */
793 		ret = fadump_exclude_reserved_area(start, end);
794 		if (ret)
795 			return ret;
796 	}
797 
798 	return 0;
799 }
800 
801 /*
802  * If the given physical address falls within the boot memory region then
803  * return the relocated address that points to the dump region reserved
804  * for saving initial boot memory contents.
805  */
806 static inline unsigned long fadump_relocate(unsigned long paddr)
807 {
808 	if (paddr > RMA_START && paddr < fw_dump.boot_memory_size)
809 		return fw_dump.boot_mem_dest_addr + paddr;
810 	else
811 		return paddr;
812 }
813 
814 static int fadump_create_elfcore_headers(char *bufp)
815 {
816 	struct elfhdr *elf;
817 	struct elf_phdr *phdr;
818 	int i;
819 
820 	fadump_init_elfcore_header(bufp);
821 	elf = (struct elfhdr *)bufp;
822 	bufp += sizeof(struct elfhdr);
823 
824 	/*
825 	 * setup ELF PT_NOTE, place holder for cpu notes info. The notes info
826 	 * will be populated during second kernel boot after crash. Hence
827 	 * this PT_NOTE will always be the first elf note.
828 	 *
829 	 * NOTE: Any new ELF note addition should be placed after this note.
830 	 */
831 	phdr = (struct elf_phdr *)bufp;
832 	bufp += sizeof(struct elf_phdr);
833 	phdr->p_type = PT_NOTE;
834 	phdr->p_flags = 0;
835 	phdr->p_vaddr = 0;
836 	phdr->p_align = 0;
837 
838 	phdr->p_offset = 0;
839 	phdr->p_paddr = 0;
840 	phdr->p_filesz = 0;
841 	phdr->p_memsz = 0;
842 
843 	(elf->e_phnum)++;
844 
845 	/* setup ELF PT_NOTE for vmcoreinfo */
846 	phdr = (struct elf_phdr *)bufp;
847 	bufp += sizeof(struct elf_phdr);
848 	phdr->p_type	= PT_NOTE;
849 	phdr->p_flags	= 0;
850 	phdr->p_vaddr	= 0;
851 	phdr->p_align	= 0;
852 
853 	phdr->p_paddr	= fadump_relocate(paddr_vmcoreinfo_note());
854 	phdr->p_offset	= phdr->p_paddr;
855 	phdr->p_memsz	= phdr->p_filesz = VMCOREINFO_NOTE_SIZE;
856 
857 	/* Increment number of program headers. */
858 	(elf->e_phnum)++;
859 
860 	/* setup PT_LOAD sections. */
861 
862 	for (i = 0; i < crash_mem_ranges; i++) {
863 		unsigned long long mbase, msize;
864 		mbase = crash_memory_ranges[i].base;
865 		msize = crash_memory_ranges[i].size;
866 
867 		if (!msize)
868 			continue;
869 
870 		phdr = (struct elf_phdr *)bufp;
871 		bufp += sizeof(struct elf_phdr);
872 		phdr->p_type	= PT_LOAD;
873 		phdr->p_flags	= PF_R|PF_W|PF_X;
874 		phdr->p_offset	= mbase;
875 
876 		if (mbase == RMA_START) {
877 			/*
878 			 * The entire RMA region will be moved by firmware
879 			 * to the specified destination_address. Hence set
880 			 * the correct offset.
881 			 */
882 			phdr->p_offset = fw_dump.boot_mem_dest_addr;
883 		}
884 
885 		phdr->p_paddr = mbase;
886 		phdr->p_vaddr = (unsigned long)__va(mbase);
887 		phdr->p_filesz = msize;
888 		phdr->p_memsz = msize;
889 		phdr->p_align = 0;
890 
891 		/* Increment number of program headers. */
892 		(elf->e_phnum)++;
893 	}
894 	return 0;
895 }
896 
897 static unsigned long init_fadump_header(unsigned long addr)
898 {
899 	struct fadump_crash_info_header *fdh;
900 
901 	if (!addr)
902 		return 0;
903 
904 	fdh = __va(addr);
905 	addr += sizeof(struct fadump_crash_info_header);
906 
907 	memset(fdh, 0, sizeof(struct fadump_crash_info_header));
908 	fdh->magic_number = FADUMP_CRASH_INFO_MAGIC;
909 	fdh->elfcorehdr_addr = addr;
910 	/* We will set the crashing cpu id in crash_fadump() during crash. */
911 	fdh->crashing_cpu = FADUMP_CPU_UNKNOWN;
912 
913 	return addr;
914 }
915 
916 static int register_fadump(void)
917 {
918 	unsigned long addr;
919 	void *vaddr;
920 	int ret;
921 
922 	/*
923 	 * If no memory is reserved then we can not register for firmware-
924 	 * assisted dump.
925 	 */
926 	if (!fw_dump.reserve_dump_area_size)
927 		return -ENODEV;
928 
929 	ret = fadump_setup_crash_memory_ranges();
930 	if (ret)
931 		return ret;
932 
933 	addr = fw_dump.fadumphdr_addr;
934 
935 	/* Initialize fadump crash info header. */
936 	addr = init_fadump_header(addr);
937 	vaddr = __va(addr);
938 
939 	pr_debug("Creating ELF core headers at %#016lx\n", addr);
940 	fadump_create_elfcore_headers(vaddr);
941 
942 	/* register the future kernel dump with firmware. */
943 	pr_debug("Registering for firmware-assisted kernel dump...\n");
944 	return fw_dump.ops->fadump_register(&fw_dump);
945 }
946 
947 void fadump_cleanup(void)
948 {
949 	/* Invalidate the registration only if dump is active. */
950 	if (fw_dump.dump_active) {
951 		pr_debug("Invalidating firmware-assisted dump registration\n");
952 		fw_dump.ops->fadump_invalidate(&fw_dump);
953 	} else if (fw_dump.dump_registered) {
954 		/* Un-register Firmware-assisted dump if it was registered. */
955 		fw_dump.ops->fadump_unregister(&fw_dump);
956 		free_crash_memory_ranges();
957 	}
958 }
959 
960 static void fadump_free_reserved_memory(unsigned long start_pfn,
961 					unsigned long end_pfn)
962 {
963 	unsigned long pfn;
964 	unsigned long time_limit = jiffies + HZ;
965 
966 	pr_info("freeing reserved memory (0x%llx - 0x%llx)\n",
967 		PFN_PHYS(start_pfn), PFN_PHYS(end_pfn));
968 
969 	for (pfn = start_pfn; pfn < end_pfn; pfn++) {
970 		free_reserved_page(pfn_to_page(pfn));
971 
972 		if (time_after(jiffies, time_limit)) {
973 			cond_resched();
974 			time_limit = jiffies + HZ;
975 		}
976 	}
977 }
978 
979 /*
980  * Skip memory holes and free memory that was actually reserved.
981  */
982 static void fadump_release_reserved_area(unsigned long start, unsigned long end)
983 {
984 	struct memblock_region *reg;
985 	unsigned long tstart, tend;
986 	unsigned long start_pfn = PHYS_PFN(start);
987 	unsigned long end_pfn = PHYS_PFN(end);
988 
989 	for_each_memblock(memory, reg) {
990 		tstart = max(start_pfn, memblock_region_memory_base_pfn(reg));
991 		tend = min(end_pfn, memblock_region_memory_end_pfn(reg));
992 		if (tstart < tend) {
993 			fadump_free_reserved_memory(tstart, tend);
994 
995 			if (tend == end_pfn)
996 				break;
997 
998 			start_pfn = tend + 1;
999 		}
1000 	}
1001 }
1002 
1003 /*
1004  * Release the memory that was reserved in early boot to preserve the memory
1005  * contents. The released memory will be available for general use.
1006  */
1007 static void fadump_release_memory(unsigned long begin, unsigned long end)
1008 {
1009 	unsigned long ra_start, ra_end;
1010 
1011 	ra_start = fw_dump.reserve_dump_area_start;
1012 	ra_end = ra_start + fw_dump.reserve_dump_area_size;
1013 
1014 	/*
1015 	 * exclude the dump reserve area. Will reuse it for next
1016 	 * fadump registration.
1017 	 */
1018 	if (begin < ra_end && end > ra_start) {
1019 		if (begin < ra_start)
1020 			fadump_release_reserved_area(begin, ra_start);
1021 		if (end > ra_end)
1022 			fadump_release_reserved_area(ra_end, end);
1023 	} else
1024 		fadump_release_reserved_area(begin, end);
1025 }
1026 
1027 static void fadump_invalidate_release_mem(void)
1028 {
1029 	mutex_lock(&fadump_mutex);
1030 	if (!fw_dump.dump_active) {
1031 		mutex_unlock(&fadump_mutex);
1032 		return;
1033 	}
1034 
1035 	fadump_cleanup();
1036 	mutex_unlock(&fadump_mutex);
1037 
1038 	fadump_release_memory(fw_dump.boot_memory_size, memblock_end_of_DRAM());
1039 	fadump_free_cpu_notes_buf();
1040 
1041 	/* Initialize the kernel dump memory structure for FAD registration. */
1042 	fw_dump.ops->fadump_init_mem_struct(&fw_dump);
1043 }
1044 
1045 static ssize_t fadump_release_memory_store(struct kobject *kobj,
1046 					struct kobj_attribute *attr,
1047 					const char *buf, size_t count)
1048 {
1049 	int input = -1;
1050 
1051 	if (!fw_dump.dump_active)
1052 		return -EPERM;
1053 
1054 	if (kstrtoint(buf, 0, &input))
1055 		return -EINVAL;
1056 
1057 	if (input == 1) {
1058 		/*
1059 		 * Take away the '/proc/vmcore'. We are releasing the dump
1060 		 * memory, hence it will not be valid anymore.
1061 		 */
1062 #ifdef CONFIG_PROC_VMCORE
1063 		vmcore_cleanup();
1064 #endif
1065 		fadump_invalidate_release_mem();
1066 
1067 	} else
1068 		return -EINVAL;
1069 	return count;
1070 }
1071 
1072 static ssize_t fadump_enabled_show(struct kobject *kobj,
1073 					struct kobj_attribute *attr,
1074 					char *buf)
1075 {
1076 	return sprintf(buf, "%d\n", fw_dump.fadump_enabled);
1077 }
1078 
1079 static ssize_t fadump_register_show(struct kobject *kobj,
1080 					struct kobj_attribute *attr,
1081 					char *buf)
1082 {
1083 	return sprintf(buf, "%d\n", fw_dump.dump_registered);
1084 }
1085 
1086 static ssize_t fadump_register_store(struct kobject *kobj,
1087 					struct kobj_attribute *attr,
1088 					const char *buf, size_t count)
1089 {
1090 	int ret = 0;
1091 	int input = -1;
1092 
1093 	if (!fw_dump.fadump_enabled || fw_dump.dump_active)
1094 		return -EPERM;
1095 
1096 	if (kstrtoint(buf, 0, &input))
1097 		return -EINVAL;
1098 
1099 	mutex_lock(&fadump_mutex);
1100 
1101 	switch (input) {
1102 	case 0:
1103 		if (fw_dump.dump_registered == 0) {
1104 			goto unlock_out;
1105 		}
1106 
1107 		/* Un-register Firmware-assisted dump */
1108 		pr_debug("Un-register firmware-assisted dump\n");
1109 		fw_dump.ops->fadump_unregister(&fw_dump);
1110 		break;
1111 	case 1:
1112 		if (fw_dump.dump_registered == 1) {
1113 			/* Un-register Firmware-assisted dump */
1114 			fw_dump.ops->fadump_unregister(&fw_dump);
1115 		}
1116 		/* Register Firmware-assisted dump */
1117 		ret = register_fadump();
1118 		break;
1119 	default:
1120 		ret = -EINVAL;
1121 		break;
1122 	}
1123 
1124 unlock_out:
1125 	mutex_unlock(&fadump_mutex);
1126 	return ret < 0 ? ret : count;
1127 }
1128 
1129 static int fadump_region_show(struct seq_file *m, void *private)
1130 {
1131 	if (!fw_dump.fadump_enabled)
1132 		return 0;
1133 
1134 	mutex_lock(&fadump_mutex);
1135 	fw_dump.ops->fadump_region_show(&fw_dump, m);
1136 	mutex_unlock(&fadump_mutex);
1137 	return 0;
1138 }
1139 
1140 static struct kobj_attribute fadump_release_attr = __ATTR(fadump_release_mem,
1141 						0200, NULL,
1142 						fadump_release_memory_store);
1143 static struct kobj_attribute fadump_attr = __ATTR(fadump_enabled,
1144 						0444, fadump_enabled_show,
1145 						NULL);
1146 static struct kobj_attribute fadump_register_attr = __ATTR(fadump_registered,
1147 						0644, fadump_register_show,
1148 						fadump_register_store);
1149 
1150 DEFINE_SHOW_ATTRIBUTE(fadump_region);
1151 
1152 static void fadump_init_files(void)
1153 {
1154 	struct dentry *debugfs_file;
1155 	int rc = 0;
1156 
1157 	rc = sysfs_create_file(kernel_kobj, &fadump_attr.attr);
1158 	if (rc)
1159 		printk(KERN_ERR "fadump: unable to create sysfs file"
1160 			" fadump_enabled (%d)\n", rc);
1161 
1162 	rc = sysfs_create_file(kernel_kobj, &fadump_register_attr.attr);
1163 	if (rc)
1164 		printk(KERN_ERR "fadump: unable to create sysfs file"
1165 			" fadump_registered (%d)\n", rc);
1166 
1167 	debugfs_file = debugfs_create_file("fadump_region", 0444,
1168 					powerpc_debugfs_root, NULL,
1169 					&fadump_region_fops);
1170 	if (!debugfs_file)
1171 		printk(KERN_ERR "fadump: unable to create debugfs file"
1172 				" fadump_region\n");
1173 
1174 	if (fw_dump.dump_active) {
1175 		rc = sysfs_create_file(kernel_kobj, &fadump_release_attr.attr);
1176 		if (rc)
1177 			printk(KERN_ERR "fadump: unable to create sysfs file"
1178 				" fadump_release_mem (%d)\n", rc);
1179 	}
1180 	return;
1181 }
1182 
1183 /*
1184  * Prepare for firmware-assisted dump.
1185  */
1186 int __init setup_fadump(void)
1187 {
1188 	if (!fw_dump.fadump_enabled)
1189 		return 0;
1190 
1191 	if (!fw_dump.fadump_supported) {
1192 		printk(KERN_ERR "Firmware-assisted dump is not supported on"
1193 			" this hardware\n");
1194 		return 0;
1195 	}
1196 
1197 	fadump_show_config();
1198 	/*
1199 	 * If dump data is available then see if it is valid and prepare for
1200 	 * saving it to the disk.
1201 	 */
1202 	if (fw_dump.dump_active) {
1203 		/*
1204 		 * if dump process fails then invalidate the registration
1205 		 * and release memory before proceeding for re-registration.
1206 		 */
1207 		if (fw_dump.ops->fadump_process(&fw_dump) < 0)
1208 			fadump_invalidate_release_mem();
1209 	}
1210 	/* Initialize the kernel dump memory structure for FAD registration. */
1211 	else if (fw_dump.reserve_dump_area_size)
1212 		fw_dump.ops->fadump_init_mem_struct(&fw_dump);
1213 
1214 	fadump_init_files();
1215 
1216 	return 1;
1217 }
1218 subsys_initcall(setup_fadump);
1219