1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * ppc64 code to implement the kexec_file_load syscall
4  *
5  * Copyright (C) 2004  Adam Litke (agl@us.ibm.com)
6  * Copyright (C) 2004  IBM Corp.
7  * Copyright (C) 2004,2005  Milton D Miller II, IBM Corporation
8  * Copyright (C) 2005  R Sharada (sharada@in.ibm.com)
9  * Copyright (C) 2006  Mohan Kumar M (mohan@in.ibm.com)
10  * Copyright (C) 2020  IBM Corporation
11  *
12  * Based on kexec-tools' kexec-ppc64.c, kexec-elf-rel-ppc64.c, fs2dt.c.
13  * Heavily modified for the kernel by
14  * Hari Bathini, IBM Corporation.
15  */
16 
17 #include <linux/kexec.h>
18 #include <linux/of_fdt.h>
19 #include <linux/libfdt.h>
20 #include <linux/of_device.h>
21 #include <linux/memblock.h>
22 #include <linux/slab.h>
23 #include <linux/vmalloc.h>
24 #include <asm/drmem.h>
25 #include <asm/kexec_ranges.h>
26 #include <asm/crashdump-ppc64.h>
27 
28 struct umem_info {
29 	u64 *buf;		/* data buffer for usable-memory property */
30 	u32 size;		/* size allocated for the data buffer */
31 	u32 max_entries;	/* maximum no. of entries */
32 	u32 idx;		/* index of current entry */
33 
34 	/* usable memory ranges to look up */
35 	unsigned int nr_ranges;
36 	const struct crash_mem_range *ranges;
37 };
38 
39 const struct kexec_file_ops * const kexec_file_loaders[] = {
40 	&kexec_elf64_ops,
41 	NULL
42 };
43 
44 /**
45  * get_exclude_memory_ranges - Get exclude memory ranges. This list includes
46  *                             regions like opal/rtas, tce-table, initrd,
47  *                             kernel, htab which should be avoided while
48  *                             setting up kexec load segments.
49  * @mem_ranges:                Range list to add the memory ranges to.
50  *
51  * Returns 0 on success, negative errno on error.
52  */
53 static int get_exclude_memory_ranges(struct crash_mem **mem_ranges)
54 {
55 	int ret;
56 
57 	ret = add_tce_mem_ranges(mem_ranges);
58 	if (ret)
59 		goto out;
60 
61 	ret = add_initrd_mem_range(mem_ranges);
62 	if (ret)
63 		goto out;
64 
65 	ret = add_htab_mem_range(mem_ranges);
66 	if (ret)
67 		goto out;
68 
69 	ret = add_kernel_mem_range(mem_ranges);
70 	if (ret)
71 		goto out;
72 
73 	ret = add_rtas_mem_range(mem_ranges);
74 	if (ret)
75 		goto out;
76 
77 	ret = add_opal_mem_range(mem_ranges);
78 	if (ret)
79 		goto out;
80 
81 	ret = add_reserved_mem_ranges(mem_ranges);
82 	if (ret)
83 		goto out;
84 
85 	/* exclude memory ranges should be sorted for easy lookup */
86 	sort_memory_ranges(*mem_ranges, true);
87 out:
88 	if (ret)
89 		pr_err("Failed to setup exclude memory ranges\n");
90 	return ret;
91 }
92 
93 /**
94  * get_usable_memory_ranges - Get usable memory ranges. This list includes
95  *                            regions like crashkernel, opal/rtas & tce-table,
96  *                            that kdump kernel could use.
97  * @mem_ranges:               Range list to add the memory ranges to.
98  *
99  * Returns 0 on success, negative errno on error.
100  */
101 static int get_usable_memory_ranges(struct crash_mem **mem_ranges)
102 {
103 	int ret;
104 
105 	/*
106 	 * Early boot failure observed on guests when low memory (first memory
107 	 * block?) is not added to usable memory. So, add [0, crashk_res.end]
108 	 * instead of [crashk_res.start, crashk_res.end] to workaround it.
109 	 * Also, crashed kernel's memory must be added to reserve map to
110 	 * avoid kdump kernel from using it.
111 	 */
112 	ret = add_mem_range(mem_ranges, 0, crashk_res.end + 1);
113 	if (ret)
114 		goto out;
115 
116 	ret = add_rtas_mem_range(mem_ranges);
117 	if (ret)
118 		goto out;
119 
120 	ret = add_opal_mem_range(mem_ranges);
121 	if (ret)
122 		goto out;
123 
124 	ret = add_tce_mem_ranges(mem_ranges);
125 out:
126 	if (ret)
127 		pr_err("Failed to setup usable memory ranges\n");
128 	return ret;
129 }
130 
131 /**
132  * get_crash_memory_ranges - Get crash memory ranges. This list includes
133  *                           first/crashing kernel's memory regions that
134  *                           would be exported via an elfcore.
135  * @mem_ranges:              Range list to add the memory ranges to.
136  *
137  * Returns 0 on success, negative errno on error.
138  */
139 static int get_crash_memory_ranges(struct crash_mem **mem_ranges)
140 {
141 	struct memblock_region *reg;
142 	struct crash_mem *tmem;
143 	int ret;
144 
145 	for_each_memblock(memory, reg) {
146 		u64 base, size;
147 
148 		base = (u64)reg->base;
149 		size = (u64)reg->size;
150 
151 		/* Skip backup memory region, which needs a separate entry */
152 		if (base == BACKUP_SRC_START) {
153 			if (size > BACKUP_SRC_SIZE) {
154 				base = BACKUP_SRC_END + 1;
155 				size -= BACKUP_SRC_SIZE;
156 			} else
157 				continue;
158 		}
159 
160 		ret = add_mem_range(mem_ranges, base, size);
161 		if (ret)
162 			goto out;
163 
164 		/* Try merging adjacent ranges before reallocation attempt */
165 		if ((*mem_ranges)->nr_ranges == (*mem_ranges)->max_nr_ranges)
166 			sort_memory_ranges(*mem_ranges, true);
167 	}
168 
169 	/* Reallocate memory ranges if there is no space to split ranges */
170 	tmem = *mem_ranges;
171 	if (tmem && (tmem->nr_ranges == tmem->max_nr_ranges)) {
172 		tmem = realloc_mem_ranges(mem_ranges);
173 		if (!tmem)
174 			goto out;
175 	}
176 
177 	/* Exclude crashkernel region */
178 	ret = crash_exclude_mem_range(tmem, crashk_res.start, crashk_res.end);
179 	if (ret)
180 		goto out;
181 
182 	/*
183 	 * FIXME: For now, stay in parity with kexec-tools but if RTAS/OPAL
184 	 *        regions are exported to save their context at the time of
185 	 *        crash, they should actually be backed up just like the
186 	 *        first 64K bytes of memory.
187 	 */
188 	ret = add_rtas_mem_range(mem_ranges);
189 	if (ret)
190 		goto out;
191 
192 	ret = add_opal_mem_range(mem_ranges);
193 	if (ret)
194 		goto out;
195 
196 	/* create a separate program header for the backup region */
197 	ret = add_mem_range(mem_ranges, BACKUP_SRC_START, BACKUP_SRC_SIZE);
198 	if (ret)
199 		goto out;
200 
201 	sort_memory_ranges(*mem_ranges, false);
202 out:
203 	if (ret)
204 		pr_err("Failed to setup crash memory ranges\n");
205 	return ret;
206 }
207 
208 /**
209  * get_reserved_memory_ranges - Get reserve memory ranges. This list includes
210  *                              memory regions that should be added to the
211  *                              memory reserve map to ensure the region is
212  *                              protected from any mischief.
213  * @mem_ranges:                 Range list to add the memory ranges to.
214  *
215  * Returns 0 on success, negative errno on error.
216  */
217 static int get_reserved_memory_ranges(struct crash_mem **mem_ranges)
218 {
219 	int ret;
220 
221 	ret = add_rtas_mem_range(mem_ranges);
222 	if (ret)
223 		goto out;
224 
225 	ret = add_tce_mem_ranges(mem_ranges);
226 	if (ret)
227 		goto out;
228 
229 	ret = add_reserved_mem_ranges(mem_ranges);
230 out:
231 	if (ret)
232 		pr_err("Failed to setup reserved memory ranges\n");
233 	return ret;
234 }
235 
236 /**
237  * __locate_mem_hole_top_down - Looks top down for a large enough memory hole
238  *                              in the memory regions between buf_min & buf_max
239  *                              for the buffer. If found, sets kbuf->mem.
240  * @kbuf:                       Buffer contents and memory parameters.
241  * @buf_min:                    Minimum address for the buffer.
242  * @buf_max:                    Maximum address for the buffer.
243  *
244  * Returns 0 on success, negative errno on error.
245  */
246 static int __locate_mem_hole_top_down(struct kexec_buf *kbuf,
247 				      u64 buf_min, u64 buf_max)
248 {
249 	int ret = -EADDRNOTAVAIL;
250 	phys_addr_t start, end;
251 	u64 i;
252 
253 	for_each_mem_range_rev(i, &start, &end) {
254 		/*
255 		 * memblock uses [start, end) convention while it is
256 		 * [start, end] here. Fix the off-by-one to have the
257 		 * same convention.
258 		 */
259 		end -= 1;
260 
261 		if (start > buf_max)
262 			continue;
263 
264 		/* Memory hole not found */
265 		if (end < buf_min)
266 			break;
267 
268 		/* Adjust memory region based on the given range */
269 		if (start < buf_min)
270 			start = buf_min;
271 		if (end > buf_max)
272 			end = buf_max;
273 
274 		start = ALIGN(start, kbuf->buf_align);
275 		if (start < end && (end - start + 1) >= kbuf->memsz) {
276 			/* Suitable memory range found. Set kbuf->mem */
277 			kbuf->mem = ALIGN_DOWN(end - kbuf->memsz + 1,
278 					       kbuf->buf_align);
279 			ret = 0;
280 			break;
281 		}
282 	}
283 
284 	return ret;
285 }
286 
287 /**
288  * locate_mem_hole_top_down_ppc64 - Skip special memory regions to find a
289  *                                  suitable buffer with top down approach.
290  * @kbuf:                           Buffer contents and memory parameters.
291  * @buf_min:                        Minimum address for the buffer.
292  * @buf_max:                        Maximum address for the buffer.
293  * @emem:                           Exclude memory ranges.
294  *
295  * Returns 0 on success, negative errno on error.
296  */
297 static int locate_mem_hole_top_down_ppc64(struct kexec_buf *kbuf,
298 					  u64 buf_min, u64 buf_max,
299 					  const struct crash_mem *emem)
300 {
301 	int i, ret = 0, err = -EADDRNOTAVAIL;
302 	u64 start, end, tmin, tmax;
303 
304 	tmax = buf_max;
305 	for (i = (emem->nr_ranges - 1); i >= 0; i--) {
306 		start = emem->ranges[i].start;
307 		end = emem->ranges[i].end;
308 
309 		if (start > tmax)
310 			continue;
311 
312 		if (end < tmax) {
313 			tmin = (end < buf_min ? buf_min : end + 1);
314 			ret = __locate_mem_hole_top_down(kbuf, tmin, tmax);
315 			if (!ret)
316 				return 0;
317 		}
318 
319 		tmax = start - 1;
320 
321 		if (tmax < buf_min) {
322 			ret = err;
323 			break;
324 		}
325 		ret = 0;
326 	}
327 
328 	if (!ret) {
329 		tmin = buf_min;
330 		ret = __locate_mem_hole_top_down(kbuf, tmin, tmax);
331 	}
332 	return ret;
333 }
334 
335 /**
336  * __locate_mem_hole_bottom_up - Looks bottom up for a large enough memory hole
337  *                               in the memory regions between buf_min & buf_max
338  *                               for the buffer. If found, sets kbuf->mem.
339  * @kbuf:                        Buffer contents and memory parameters.
340  * @buf_min:                     Minimum address for the buffer.
341  * @buf_max:                     Maximum address for the buffer.
342  *
343  * Returns 0 on success, negative errno on error.
344  */
345 static int __locate_mem_hole_bottom_up(struct kexec_buf *kbuf,
346 				       u64 buf_min, u64 buf_max)
347 {
348 	int ret = -EADDRNOTAVAIL;
349 	phys_addr_t start, end;
350 	u64 i;
351 
352 	for_each_mem_range(i, &start, &end) {
353 		/*
354 		 * memblock uses [start, end) convention while it is
355 		 * [start, end] here. Fix the off-by-one to have the
356 		 * same convention.
357 		 */
358 		end -= 1;
359 
360 		if (end < buf_min)
361 			continue;
362 
363 		/* Memory hole not found */
364 		if (start > buf_max)
365 			break;
366 
367 		/* Adjust memory region based on the given range */
368 		if (start < buf_min)
369 			start = buf_min;
370 		if (end > buf_max)
371 			end = buf_max;
372 
373 		start = ALIGN(start, kbuf->buf_align);
374 		if (start < end && (end - start + 1) >= kbuf->memsz) {
375 			/* Suitable memory range found. Set kbuf->mem */
376 			kbuf->mem = start;
377 			ret = 0;
378 			break;
379 		}
380 	}
381 
382 	return ret;
383 }
384 
385 /**
386  * locate_mem_hole_bottom_up_ppc64 - Skip special memory regions to find a
387  *                                   suitable buffer with bottom up approach.
388  * @kbuf:                            Buffer contents and memory parameters.
389  * @buf_min:                         Minimum address for the buffer.
390  * @buf_max:                         Maximum address for the buffer.
391  * @emem:                            Exclude memory ranges.
392  *
393  * Returns 0 on success, negative errno on error.
394  */
395 static int locate_mem_hole_bottom_up_ppc64(struct kexec_buf *kbuf,
396 					   u64 buf_min, u64 buf_max,
397 					   const struct crash_mem *emem)
398 {
399 	int i, ret = 0, err = -EADDRNOTAVAIL;
400 	u64 start, end, tmin, tmax;
401 
402 	tmin = buf_min;
403 	for (i = 0; i < emem->nr_ranges; i++) {
404 		start = emem->ranges[i].start;
405 		end = emem->ranges[i].end;
406 
407 		if (end < tmin)
408 			continue;
409 
410 		if (start > tmin) {
411 			tmax = (start > buf_max ? buf_max : start - 1);
412 			ret = __locate_mem_hole_bottom_up(kbuf, tmin, tmax);
413 			if (!ret)
414 				return 0;
415 		}
416 
417 		tmin = end + 1;
418 
419 		if (tmin > buf_max) {
420 			ret = err;
421 			break;
422 		}
423 		ret = 0;
424 	}
425 
426 	if (!ret) {
427 		tmax = buf_max;
428 		ret = __locate_mem_hole_bottom_up(kbuf, tmin, tmax);
429 	}
430 	return ret;
431 }
432 
433 /**
434  * check_realloc_usable_mem - Reallocate buffer if it can't accommodate entries
435  * @um_info:                  Usable memory buffer and ranges info.
436  * @cnt:                      No. of entries to accommodate.
437  *
438  * Frees up the old buffer if memory reallocation fails.
439  *
440  * Returns buffer on success, NULL on error.
441  */
442 static u64 *check_realloc_usable_mem(struct umem_info *um_info, int cnt)
443 {
444 	u32 new_size;
445 	u64 *tbuf;
446 
447 	if ((um_info->idx + cnt) <= um_info->max_entries)
448 		return um_info->buf;
449 
450 	new_size = um_info->size + MEM_RANGE_CHUNK_SZ;
451 	tbuf = krealloc(um_info->buf, new_size, GFP_KERNEL);
452 	if (tbuf) {
453 		um_info->buf = tbuf;
454 		um_info->size = new_size;
455 		um_info->max_entries = (um_info->size / sizeof(u64));
456 	}
457 
458 	return tbuf;
459 }
460 
461 /**
462  * add_usable_mem - Add the usable memory ranges within the given memory range
463  *                  to the buffer
464  * @um_info:        Usable memory buffer and ranges info.
465  * @base:           Base address of memory range to look for.
466  * @end:            End address of memory range to look for.
467  *
468  * Returns 0 on success, negative errno on error.
469  */
470 static int add_usable_mem(struct umem_info *um_info, u64 base, u64 end)
471 {
472 	u64 loc_base, loc_end;
473 	bool add;
474 	int i;
475 
476 	for (i = 0; i < um_info->nr_ranges; i++) {
477 		add = false;
478 		loc_base = um_info->ranges[i].start;
479 		loc_end = um_info->ranges[i].end;
480 		if (loc_base >= base && loc_end <= end)
481 			add = true;
482 		else if (base < loc_end && end > loc_base) {
483 			if (loc_base < base)
484 				loc_base = base;
485 			if (loc_end > end)
486 				loc_end = end;
487 			add = true;
488 		}
489 
490 		if (add) {
491 			if (!check_realloc_usable_mem(um_info, 2))
492 				return -ENOMEM;
493 
494 			um_info->buf[um_info->idx++] = cpu_to_be64(loc_base);
495 			um_info->buf[um_info->idx++] =
496 					cpu_to_be64(loc_end - loc_base + 1);
497 		}
498 	}
499 
500 	return 0;
501 }
502 
503 /**
504  * kdump_setup_usable_lmb - This is a callback function that gets called by
505  *                          walk_drmem_lmbs for every LMB to set its
506  *                          usable memory ranges.
507  * @lmb:                    LMB info.
508  * @usm:                    linux,drconf-usable-memory property value.
509  * @data:                   Pointer to usable memory buffer and ranges info.
510  *
511  * Returns 0 on success, negative errno on error.
512  */
513 static int kdump_setup_usable_lmb(struct drmem_lmb *lmb, const __be32 **usm,
514 				  void *data)
515 {
516 	struct umem_info *um_info;
517 	int tmp_idx, ret;
518 	u64 base, end;
519 
520 	/*
521 	 * kdump load isn't supported on kernels already booted with
522 	 * linux,drconf-usable-memory property.
523 	 */
524 	if (*usm) {
525 		pr_err("linux,drconf-usable-memory property already exists!");
526 		return -EINVAL;
527 	}
528 
529 	um_info = data;
530 	tmp_idx = um_info->idx;
531 	if (!check_realloc_usable_mem(um_info, 1))
532 		return -ENOMEM;
533 
534 	um_info->idx++;
535 	base = lmb->base_addr;
536 	end = base + drmem_lmb_size() - 1;
537 	ret = add_usable_mem(um_info, base, end);
538 	if (!ret) {
539 		/*
540 		 * Update the no. of ranges added. Two entries (base & size)
541 		 * for every range added.
542 		 */
543 		um_info->buf[tmp_idx] =
544 				cpu_to_be64((um_info->idx - tmp_idx - 1) / 2);
545 	}
546 
547 	return ret;
548 }
549 
550 #define NODE_PATH_LEN		256
551 /**
552  * add_usable_mem_property - Add usable memory property for the given
553  *                           memory node.
554  * @fdt:                     Flattened device tree for the kdump kernel.
555  * @dn:                      Memory node.
556  * @um_info:                 Usable memory buffer and ranges info.
557  *
558  * Returns 0 on success, negative errno on error.
559  */
560 static int add_usable_mem_property(void *fdt, struct device_node *dn,
561 				   struct umem_info *um_info)
562 {
563 	int n_mem_addr_cells, n_mem_size_cells, node;
564 	char path[NODE_PATH_LEN];
565 	int i, len, ranges, ret;
566 	const __be32 *prop;
567 	u64 base, end;
568 
569 	of_node_get(dn);
570 
571 	if (snprintf(path, NODE_PATH_LEN, "%pOF", dn) > (NODE_PATH_LEN - 1)) {
572 		pr_err("Buffer (%d) too small for memory node: %pOF\n",
573 		       NODE_PATH_LEN, dn);
574 		return -EOVERFLOW;
575 	}
576 	pr_debug("Memory node path: %s\n", path);
577 
578 	/* Now that we know the path, find its offset in kdump kernel's fdt */
579 	node = fdt_path_offset(fdt, path);
580 	if (node < 0) {
581 		pr_err("Malformed device tree: error reading %s\n", path);
582 		ret = -EINVAL;
583 		goto out;
584 	}
585 
586 	/* Get the address & size cells */
587 	n_mem_addr_cells = of_n_addr_cells(dn);
588 	n_mem_size_cells = of_n_size_cells(dn);
589 	pr_debug("address cells: %d, size cells: %d\n", n_mem_addr_cells,
590 		 n_mem_size_cells);
591 
592 	um_info->idx  = 0;
593 	if (!check_realloc_usable_mem(um_info, 2)) {
594 		ret = -ENOMEM;
595 		goto out;
596 	}
597 
598 	prop = of_get_property(dn, "reg", &len);
599 	if (!prop || len <= 0) {
600 		ret = 0;
601 		goto out;
602 	}
603 
604 	/*
605 	 * "reg" property represents sequence of (addr,size) tuples
606 	 * each representing a memory range.
607 	 */
608 	ranges = (len >> 2) / (n_mem_addr_cells + n_mem_size_cells);
609 
610 	for (i = 0; i < ranges; i++) {
611 		base = of_read_number(prop, n_mem_addr_cells);
612 		prop += n_mem_addr_cells;
613 		end = base + of_read_number(prop, n_mem_size_cells) - 1;
614 		prop += n_mem_size_cells;
615 
616 		ret = add_usable_mem(um_info, base, end);
617 		if (ret)
618 			goto out;
619 	}
620 
621 	/*
622 	 * No kdump kernel usable memory found in this memory node.
623 	 * Write (0,0) tuple in linux,usable-memory property for
624 	 * this region to be ignored.
625 	 */
626 	if (um_info->idx == 0) {
627 		um_info->buf[0] = 0;
628 		um_info->buf[1] = 0;
629 		um_info->idx = 2;
630 	}
631 
632 	ret = fdt_setprop(fdt, node, "linux,usable-memory", um_info->buf,
633 			  (um_info->idx * sizeof(u64)));
634 
635 out:
636 	of_node_put(dn);
637 	return ret;
638 }
639 
640 
641 /**
642  * update_usable_mem_fdt - Updates kdump kernel's fdt with linux,usable-memory
643  *                         and linux,drconf-usable-memory DT properties as
644  *                         appropriate to restrict its memory usage.
645  * @fdt:                   Flattened device tree for the kdump kernel.
646  * @usable_mem:            Usable memory ranges for kdump kernel.
647  *
648  * Returns 0 on success, negative errno on error.
649  */
650 static int update_usable_mem_fdt(void *fdt, struct crash_mem *usable_mem)
651 {
652 	struct umem_info um_info;
653 	struct device_node *dn;
654 	int node, ret = 0;
655 
656 	if (!usable_mem) {
657 		pr_err("Usable memory ranges for kdump kernel not found\n");
658 		return -ENOENT;
659 	}
660 
661 	node = fdt_path_offset(fdt, "/ibm,dynamic-reconfiguration-memory");
662 	if (node == -FDT_ERR_NOTFOUND)
663 		pr_debug("No dynamic reconfiguration memory found\n");
664 	else if (node < 0) {
665 		pr_err("Malformed device tree: error reading /ibm,dynamic-reconfiguration-memory.\n");
666 		return -EINVAL;
667 	}
668 
669 	um_info.buf  = NULL;
670 	um_info.size = 0;
671 	um_info.max_entries = 0;
672 	um_info.idx  = 0;
673 	/* Memory ranges to look up */
674 	um_info.ranges = &(usable_mem->ranges[0]);
675 	um_info.nr_ranges = usable_mem->nr_ranges;
676 
677 	dn = of_find_node_by_path("/ibm,dynamic-reconfiguration-memory");
678 	if (dn) {
679 		ret = walk_drmem_lmbs(dn, &um_info, kdump_setup_usable_lmb);
680 		of_node_put(dn);
681 
682 		if (ret) {
683 			pr_err("Could not setup linux,drconf-usable-memory property for kdump\n");
684 			goto out;
685 		}
686 
687 		ret = fdt_setprop(fdt, node, "linux,drconf-usable-memory",
688 				  um_info.buf, (um_info.idx * sizeof(u64)));
689 		if (ret) {
690 			pr_err("Failed to update fdt with linux,drconf-usable-memory property");
691 			goto out;
692 		}
693 	}
694 
695 	/*
696 	 * Walk through each memory node and set linux,usable-memory property
697 	 * for the corresponding node in kdump kernel's fdt.
698 	 */
699 	for_each_node_by_type(dn, "memory") {
700 		ret = add_usable_mem_property(fdt, dn, &um_info);
701 		if (ret) {
702 			pr_err("Failed to set linux,usable-memory property for %s node",
703 			       dn->full_name);
704 			goto out;
705 		}
706 	}
707 
708 out:
709 	kfree(um_info.buf);
710 	return ret;
711 }
712 
713 /**
714  * load_backup_segment - Locate a memory hole to place the backup region.
715  * @image:               Kexec image.
716  * @kbuf:                Buffer contents and memory parameters.
717  *
718  * Returns 0 on success, negative errno on error.
719  */
720 static int load_backup_segment(struct kimage *image, struct kexec_buf *kbuf)
721 {
722 	void *buf;
723 	int ret;
724 
725 	/*
726 	 * Setup a source buffer for backup segment.
727 	 *
728 	 * A source buffer has no meaning for backup region as data will
729 	 * be copied from backup source, after crash, in the purgatory.
730 	 * But as load segment code doesn't recognize such segments,
731 	 * setup a dummy source buffer to keep it happy for now.
732 	 */
733 	buf = vzalloc(BACKUP_SRC_SIZE);
734 	if (!buf)
735 		return -ENOMEM;
736 
737 	kbuf->buffer = buf;
738 	kbuf->mem = KEXEC_BUF_MEM_UNKNOWN;
739 	kbuf->bufsz = kbuf->memsz = BACKUP_SRC_SIZE;
740 	kbuf->top_down = false;
741 
742 	ret = kexec_add_buffer(kbuf);
743 	if (ret) {
744 		vfree(buf);
745 		return ret;
746 	}
747 
748 	image->arch.backup_buf = buf;
749 	image->arch.backup_start = kbuf->mem;
750 	return 0;
751 }
752 
753 /**
754  * update_backup_region_phdr - Update backup region's offset for the core to
755  *                             export the region appropriately.
756  * @image:                     Kexec image.
757  * @ehdr:                      ELF core header.
758  *
759  * Assumes an exclusive program header is setup for the backup region
760  * in the ELF headers
761  *
762  * Returns nothing.
763  */
764 static void update_backup_region_phdr(struct kimage *image, Elf64_Ehdr *ehdr)
765 {
766 	Elf64_Phdr *phdr;
767 	unsigned int i;
768 
769 	phdr = (Elf64_Phdr *)(ehdr + 1);
770 	for (i = 0; i < ehdr->e_phnum; i++) {
771 		if (phdr->p_paddr == BACKUP_SRC_START) {
772 			phdr->p_offset = image->arch.backup_start;
773 			pr_debug("Backup region offset updated to 0x%lx\n",
774 				 image->arch.backup_start);
775 			return;
776 		}
777 	}
778 }
779 
780 /**
781  * load_elfcorehdr_segment - Setup crash memory ranges and initialize elfcorehdr
782  *                           segment needed to load kdump kernel.
783  * @image:                   Kexec image.
784  * @kbuf:                    Buffer contents and memory parameters.
785  *
786  * Returns 0 on success, negative errno on error.
787  */
788 static int load_elfcorehdr_segment(struct kimage *image, struct kexec_buf *kbuf)
789 {
790 	struct crash_mem *cmem = NULL;
791 	unsigned long headers_sz;
792 	void *headers = NULL;
793 	int ret;
794 
795 	ret = get_crash_memory_ranges(&cmem);
796 	if (ret)
797 		goto out;
798 
799 	/* Setup elfcorehdr segment */
800 	ret = crash_prepare_elf64_headers(cmem, false, &headers, &headers_sz);
801 	if (ret) {
802 		pr_err("Failed to prepare elf headers for the core\n");
803 		goto out;
804 	}
805 
806 	/* Fix the offset for backup region in the ELF header */
807 	update_backup_region_phdr(image, headers);
808 
809 	kbuf->buffer = headers;
810 	kbuf->mem = KEXEC_BUF_MEM_UNKNOWN;
811 	kbuf->bufsz = kbuf->memsz = headers_sz;
812 	kbuf->top_down = false;
813 
814 	ret = kexec_add_buffer(kbuf);
815 	if (ret) {
816 		vfree(headers);
817 		goto out;
818 	}
819 
820 	image->arch.elfcorehdr_addr = kbuf->mem;
821 	image->arch.elf_headers_sz = headers_sz;
822 	image->arch.elf_headers = headers;
823 out:
824 	kfree(cmem);
825 	return ret;
826 }
827 
828 /**
829  * load_crashdump_segments_ppc64 - Initialize the additional segements needed
830  *                                 to load kdump kernel.
831  * @image:                         Kexec image.
832  * @kbuf:                          Buffer contents and memory parameters.
833  *
834  * Returns 0 on success, negative errno on error.
835  */
836 int load_crashdump_segments_ppc64(struct kimage *image,
837 				  struct kexec_buf *kbuf)
838 {
839 	int ret;
840 
841 	/* Load backup segment - first 64K bytes of the crashing kernel */
842 	ret = load_backup_segment(image, kbuf);
843 	if (ret) {
844 		pr_err("Failed to load backup segment\n");
845 		return ret;
846 	}
847 	pr_debug("Loaded the backup region at 0x%lx\n", kbuf->mem);
848 
849 	/* Load elfcorehdr segment - to export crashing kernel's vmcore */
850 	ret = load_elfcorehdr_segment(image, kbuf);
851 	if (ret) {
852 		pr_err("Failed to load elfcorehdr segment\n");
853 		return ret;
854 	}
855 	pr_debug("Loaded elf core header at 0x%lx, bufsz=0x%lx memsz=0x%lx\n",
856 		 image->arch.elfcorehdr_addr, kbuf->bufsz, kbuf->memsz);
857 
858 	return 0;
859 }
860 
861 /**
862  * setup_purgatory_ppc64 - initialize PPC64 specific purgatory's global
863  *                         variables and call setup_purgatory() to initialize
864  *                         common global variable.
865  * @image:                 kexec image.
866  * @slave_code:            Slave code for the purgatory.
867  * @fdt:                   Flattened device tree for the next kernel.
868  * @kernel_load_addr:      Address where the kernel is loaded.
869  * @fdt_load_addr:         Address where the flattened device tree is loaded.
870  *
871  * Returns 0 on success, negative errno on error.
872  */
873 int setup_purgatory_ppc64(struct kimage *image, const void *slave_code,
874 			  const void *fdt, unsigned long kernel_load_addr,
875 			  unsigned long fdt_load_addr)
876 {
877 	struct device_node *dn = NULL;
878 	int ret;
879 
880 	ret = setup_purgatory(image, slave_code, fdt, kernel_load_addr,
881 			      fdt_load_addr);
882 	if (ret)
883 		goto out;
884 
885 	if (image->type == KEXEC_TYPE_CRASH) {
886 		u32 my_run_at_load = 1;
887 
888 		/*
889 		 * Tell relocatable kernel to run at load address
890 		 * via the word meant for that at 0x5c.
891 		 */
892 		ret = kexec_purgatory_get_set_symbol(image, "run_at_load",
893 						     &my_run_at_load,
894 						     sizeof(my_run_at_load),
895 						     false);
896 		if (ret)
897 			goto out;
898 	}
899 
900 	/* Tell purgatory where to look for backup region */
901 	ret = kexec_purgatory_get_set_symbol(image, "backup_start",
902 					     &image->arch.backup_start,
903 					     sizeof(image->arch.backup_start),
904 					     false);
905 	if (ret)
906 		goto out;
907 
908 	/* Setup OPAL base & entry values */
909 	dn = of_find_node_by_path("/ibm,opal");
910 	if (dn) {
911 		u64 val;
912 
913 		of_property_read_u64(dn, "opal-base-address", &val);
914 		ret = kexec_purgatory_get_set_symbol(image, "opal_base", &val,
915 						     sizeof(val), false);
916 		if (ret)
917 			goto out;
918 
919 		of_property_read_u64(dn, "opal-entry-address", &val);
920 		ret = kexec_purgatory_get_set_symbol(image, "opal_entry", &val,
921 						     sizeof(val), false);
922 	}
923 out:
924 	if (ret)
925 		pr_err("Failed to setup purgatory symbols");
926 	of_node_put(dn);
927 	return ret;
928 }
929 
930 /**
931  * setup_new_fdt_ppc64 - Update the flattend device-tree of the kernel
932  *                       being loaded.
933  * @image:               kexec image being loaded.
934  * @fdt:                 Flattened device tree for the next kernel.
935  * @initrd_load_addr:    Address where the next initrd will be loaded.
936  * @initrd_len:          Size of the next initrd, or 0 if there will be none.
937  * @cmdline:             Command line for the next kernel, or NULL if there will
938  *                       be none.
939  *
940  * Returns 0 on success, negative errno on error.
941  */
942 int setup_new_fdt_ppc64(const struct kimage *image, void *fdt,
943 			unsigned long initrd_load_addr,
944 			unsigned long initrd_len, const char *cmdline)
945 {
946 	struct crash_mem *umem = NULL, *rmem = NULL;
947 	int i, nr_ranges, ret;
948 
949 	ret = setup_new_fdt(image, fdt, initrd_load_addr, initrd_len, cmdline);
950 	if (ret)
951 		goto out;
952 
953 	/*
954 	 * Restrict memory usage for kdump kernel by setting up
955 	 * usable memory ranges and memory reserve map.
956 	 */
957 	if (image->type == KEXEC_TYPE_CRASH) {
958 		ret = get_usable_memory_ranges(&umem);
959 		if (ret)
960 			goto out;
961 
962 		ret = update_usable_mem_fdt(fdt, umem);
963 		if (ret) {
964 			pr_err("Error setting up usable-memory property for kdump kernel\n");
965 			goto out;
966 		}
967 
968 		/*
969 		 * Ensure we don't touch crashed kernel's memory except the
970 		 * first 64K of RAM, which will be backed up.
971 		 */
972 		ret = fdt_add_mem_rsv(fdt, BACKUP_SRC_END + 1,
973 				      crashk_res.start - BACKUP_SRC_SIZE);
974 		if (ret) {
975 			pr_err("Error reserving crash memory: %s\n",
976 			       fdt_strerror(ret));
977 			goto out;
978 		}
979 
980 		/* Ensure backup region is not used by kdump/capture kernel */
981 		ret = fdt_add_mem_rsv(fdt, image->arch.backup_start,
982 				      BACKUP_SRC_SIZE);
983 		if (ret) {
984 			pr_err("Error reserving memory for backup: %s\n",
985 			       fdt_strerror(ret));
986 			goto out;
987 		}
988 	}
989 
990 	/* Update memory reserve map */
991 	ret = get_reserved_memory_ranges(&rmem);
992 	if (ret)
993 		goto out;
994 
995 	nr_ranges = rmem ? rmem->nr_ranges : 0;
996 	for (i = 0; i < nr_ranges; i++) {
997 		u64 base, size;
998 
999 		base = rmem->ranges[i].start;
1000 		size = rmem->ranges[i].end - base + 1;
1001 		ret = fdt_add_mem_rsv(fdt, base, size);
1002 		if (ret) {
1003 			pr_err("Error updating memory reserve map: %s\n",
1004 			       fdt_strerror(ret));
1005 			goto out;
1006 		}
1007 	}
1008 
1009 out:
1010 	kfree(rmem);
1011 	kfree(umem);
1012 	return ret;
1013 }
1014 
1015 /**
1016  * arch_kexec_locate_mem_hole - Skip special memory regions like rtas, opal,
1017  *                              tce-table, reserved-ranges & such (exclude
1018  *                              memory ranges) as they can't be used for kexec
1019  *                              segment buffer. Sets kbuf->mem when a suitable
1020  *                              memory hole is found.
1021  * @kbuf:                       Buffer contents and memory parameters.
1022  *
1023  * Assumes minimum of PAGE_SIZE alignment for kbuf->memsz & kbuf->buf_align.
1024  *
1025  * Returns 0 on success, negative errno on error.
1026  */
1027 int arch_kexec_locate_mem_hole(struct kexec_buf *kbuf)
1028 {
1029 	struct crash_mem **emem;
1030 	u64 buf_min, buf_max;
1031 	int ret;
1032 
1033 	/* Look up the exclude ranges list while locating the memory hole */
1034 	emem = &(kbuf->image->arch.exclude_ranges);
1035 	if (!(*emem) || ((*emem)->nr_ranges == 0)) {
1036 		pr_warn("No exclude range list. Using the default locate mem hole method\n");
1037 		return kexec_locate_mem_hole(kbuf);
1038 	}
1039 
1040 	buf_min = kbuf->buf_min;
1041 	buf_max = kbuf->buf_max;
1042 	/* Segments for kdump kernel should be within crashkernel region */
1043 	if (kbuf->image->type == KEXEC_TYPE_CRASH) {
1044 		buf_min = (buf_min < crashk_res.start ?
1045 			   crashk_res.start : buf_min);
1046 		buf_max = (buf_max > crashk_res.end ?
1047 			   crashk_res.end : buf_max);
1048 	}
1049 
1050 	if (buf_min > buf_max) {
1051 		pr_err("Invalid buffer min and/or max values\n");
1052 		return -EINVAL;
1053 	}
1054 
1055 	if (kbuf->top_down)
1056 		ret = locate_mem_hole_top_down_ppc64(kbuf, buf_min, buf_max,
1057 						     *emem);
1058 	else
1059 		ret = locate_mem_hole_bottom_up_ppc64(kbuf, buf_min, buf_max,
1060 						      *emem);
1061 
1062 	/* Add the buffer allocated to the exclude list for the next lookup */
1063 	if (!ret) {
1064 		add_mem_range(emem, kbuf->mem, kbuf->memsz);
1065 		sort_memory_ranges(*emem, true);
1066 	} else {
1067 		pr_err("Failed to locate memory buffer of size %lu\n",
1068 		       kbuf->memsz);
1069 	}
1070 	return ret;
1071 }
1072 
1073 /**
1074  * arch_kexec_kernel_image_probe - Does additional handling needed to setup
1075  *                                 kexec segments.
1076  * @image:                         kexec image being loaded.
1077  * @buf:                           Buffer pointing to elf data.
1078  * @buf_len:                       Length of the buffer.
1079  *
1080  * Returns 0 on success, negative errno on error.
1081  */
1082 int arch_kexec_kernel_image_probe(struct kimage *image, void *buf,
1083 				  unsigned long buf_len)
1084 {
1085 	int ret;
1086 
1087 	/* Get exclude memory ranges needed for setting up kexec segments */
1088 	ret = get_exclude_memory_ranges(&(image->arch.exclude_ranges));
1089 	if (ret) {
1090 		pr_err("Failed to setup exclude memory ranges for buffer lookup\n");
1091 		return ret;
1092 	}
1093 
1094 	return kexec_image_probe_default(image, buf, buf_len);
1095 }
1096 
1097 /**
1098  * arch_kimage_file_post_load_cleanup - Frees up all the allocations done
1099  *                                      while loading the image.
1100  * @image:                              kexec image being loaded.
1101  *
1102  * Returns 0 on success, negative errno on error.
1103  */
1104 int arch_kimage_file_post_load_cleanup(struct kimage *image)
1105 {
1106 	kfree(image->arch.exclude_ranges);
1107 	image->arch.exclude_ranges = NULL;
1108 
1109 	vfree(image->arch.backup_buf);
1110 	image->arch.backup_buf = NULL;
1111 
1112 	vfree(image->arch.elf_headers);
1113 	image->arch.elf_headers = NULL;
1114 	image->arch.elf_headers_sz = 0;
1115 
1116 	return kexec_image_post_load_cleanup_default(image);
1117 }
1118