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