xref: /openbmc/linux/kernel/kexec_file.c (revision 22d55f02)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * kexec: kexec_file_load system call
4  *
5  * Copyright (C) 2014 Red Hat Inc.
6  * Authors:
7  *      Vivek Goyal <vgoyal@redhat.com>
8  */
9 
10 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
11 
12 #include <linux/capability.h>
13 #include <linux/mm.h>
14 #include <linux/file.h>
15 #include <linux/slab.h>
16 #include <linux/kexec.h>
17 #include <linux/memblock.h>
18 #include <linux/mutex.h>
19 #include <linux/list.h>
20 #include <linux/fs.h>
21 #include <linux/ima.h>
22 #include <crypto/hash.h>
23 #include <crypto/sha.h>
24 #include <linux/elf.h>
25 #include <linux/elfcore.h>
26 #include <linux/kernel.h>
27 #include <linux/syscalls.h>
28 #include <linux/vmalloc.h>
29 #include "kexec_internal.h"
30 
31 static int kexec_calculate_store_digests(struct kimage *image);
32 
33 /*
34  * Currently this is the only default function that is exported as some
35  * architectures need it to do additional handlings.
36  * In the future, other default functions may be exported too if required.
37  */
38 int kexec_image_probe_default(struct kimage *image, void *buf,
39 			      unsigned long buf_len)
40 {
41 	const struct kexec_file_ops * const *fops;
42 	int ret = -ENOEXEC;
43 
44 	for (fops = &kexec_file_loaders[0]; *fops && (*fops)->probe; ++fops) {
45 		ret = (*fops)->probe(buf, buf_len);
46 		if (!ret) {
47 			image->fops = *fops;
48 			return ret;
49 		}
50 	}
51 
52 	return ret;
53 }
54 
55 /* Architectures can provide this probe function */
56 int __weak arch_kexec_kernel_image_probe(struct kimage *image, void *buf,
57 					 unsigned long buf_len)
58 {
59 	return kexec_image_probe_default(image, buf, buf_len);
60 }
61 
62 static void *kexec_image_load_default(struct kimage *image)
63 {
64 	if (!image->fops || !image->fops->load)
65 		return ERR_PTR(-ENOEXEC);
66 
67 	return image->fops->load(image, image->kernel_buf,
68 				 image->kernel_buf_len, image->initrd_buf,
69 				 image->initrd_buf_len, image->cmdline_buf,
70 				 image->cmdline_buf_len);
71 }
72 
73 void * __weak arch_kexec_kernel_image_load(struct kimage *image)
74 {
75 	return kexec_image_load_default(image);
76 }
77 
78 int kexec_image_post_load_cleanup_default(struct kimage *image)
79 {
80 	if (!image->fops || !image->fops->cleanup)
81 		return 0;
82 
83 	return image->fops->cleanup(image->image_loader_data);
84 }
85 
86 int __weak arch_kimage_file_post_load_cleanup(struct kimage *image)
87 {
88 	return kexec_image_post_load_cleanup_default(image);
89 }
90 
91 #ifdef CONFIG_KEXEC_VERIFY_SIG
92 static int kexec_image_verify_sig_default(struct kimage *image, void *buf,
93 					  unsigned long buf_len)
94 {
95 	if (!image->fops || !image->fops->verify_sig) {
96 		pr_debug("kernel loader does not support signature verification.\n");
97 		return -EKEYREJECTED;
98 	}
99 
100 	return image->fops->verify_sig(buf, buf_len);
101 }
102 
103 int __weak arch_kexec_kernel_verify_sig(struct kimage *image, void *buf,
104 					unsigned long buf_len)
105 {
106 	return kexec_image_verify_sig_default(image, buf, buf_len);
107 }
108 #endif
109 
110 /*
111  * arch_kexec_apply_relocations_add - apply relocations of type RELA
112  * @pi:		Purgatory to be relocated.
113  * @section:	Section relocations applying to.
114  * @relsec:	Section containing RELAs.
115  * @symtab:	Corresponding symtab.
116  *
117  * Return: 0 on success, negative errno on error.
118  */
119 int __weak
120 arch_kexec_apply_relocations_add(struct purgatory_info *pi, Elf_Shdr *section,
121 				 const Elf_Shdr *relsec, const Elf_Shdr *symtab)
122 {
123 	pr_err("RELA relocation unsupported.\n");
124 	return -ENOEXEC;
125 }
126 
127 /*
128  * arch_kexec_apply_relocations - apply relocations of type REL
129  * @pi:		Purgatory to be relocated.
130  * @section:	Section relocations applying to.
131  * @relsec:	Section containing RELs.
132  * @symtab:	Corresponding symtab.
133  *
134  * Return: 0 on success, negative errno on error.
135  */
136 int __weak
137 arch_kexec_apply_relocations(struct purgatory_info *pi, Elf_Shdr *section,
138 			     const Elf_Shdr *relsec, const Elf_Shdr *symtab)
139 {
140 	pr_err("REL relocation unsupported.\n");
141 	return -ENOEXEC;
142 }
143 
144 /*
145  * Free up memory used by kernel, initrd, and command line. This is temporary
146  * memory allocation which is not needed any more after these buffers have
147  * been loaded into separate segments and have been copied elsewhere.
148  */
149 void kimage_file_post_load_cleanup(struct kimage *image)
150 {
151 	struct purgatory_info *pi = &image->purgatory_info;
152 
153 	vfree(image->kernel_buf);
154 	image->kernel_buf = NULL;
155 
156 	vfree(image->initrd_buf);
157 	image->initrd_buf = NULL;
158 
159 	kfree(image->cmdline_buf);
160 	image->cmdline_buf = NULL;
161 
162 	vfree(pi->purgatory_buf);
163 	pi->purgatory_buf = NULL;
164 
165 	vfree(pi->sechdrs);
166 	pi->sechdrs = NULL;
167 
168 	/* See if architecture has anything to cleanup post load */
169 	arch_kimage_file_post_load_cleanup(image);
170 
171 	/*
172 	 * Above call should have called into bootloader to free up
173 	 * any data stored in kimage->image_loader_data. It should
174 	 * be ok now to free it up.
175 	 */
176 	kfree(image->image_loader_data);
177 	image->image_loader_data = NULL;
178 }
179 
180 /*
181  * In file mode list of segments is prepared by kernel. Copy relevant
182  * data from user space, do error checking, prepare segment list
183  */
184 static int
185 kimage_file_prepare_segments(struct kimage *image, int kernel_fd, int initrd_fd,
186 			     const char __user *cmdline_ptr,
187 			     unsigned long cmdline_len, unsigned flags)
188 {
189 	int ret = 0;
190 	void *ldata;
191 	loff_t size;
192 
193 	ret = kernel_read_file_from_fd(kernel_fd, &image->kernel_buf,
194 				       &size, INT_MAX, READING_KEXEC_IMAGE);
195 	if (ret)
196 		return ret;
197 	image->kernel_buf_len = size;
198 
199 	/* IMA needs to pass the measurement list to the next kernel. */
200 	ima_add_kexec_buffer(image);
201 
202 	/* Call arch image probe handlers */
203 	ret = arch_kexec_kernel_image_probe(image, image->kernel_buf,
204 					    image->kernel_buf_len);
205 	if (ret)
206 		goto out;
207 
208 #ifdef CONFIG_KEXEC_VERIFY_SIG
209 	ret = arch_kexec_kernel_verify_sig(image, image->kernel_buf,
210 					   image->kernel_buf_len);
211 	if (ret) {
212 		pr_debug("kernel signature verification failed.\n");
213 		goto out;
214 	}
215 	pr_debug("kernel signature verification successful.\n");
216 #endif
217 	/* It is possible that there no initramfs is being loaded */
218 	if (!(flags & KEXEC_FILE_NO_INITRAMFS)) {
219 		ret = kernel_read_file_from_fd(initrd_fd, &image->initrd_buf,
220 					       &size, INT_MAX,
221 					       READING_KEXEC_INITRAMFS);
222 		if (ret)
223 			goto out;
224 		image->initrd_buf_len = size;
225 	}
226 
227 	if (cmdline_len) {
228 		image->cmdline_buf = memdup_user(cmdline_ptr, cmdline_len);
229 		if (IS_ERR(image->cmdline_buf)) {
230 			ret = PTR_ERR(image->cmdline_buf);
231 			image->cmdline_buf = NULL;
232 			goto out;
233 		}
234 
235 		image->cmdline_buf_len = cmdline_len;
236 
237 		/* command line should be a string with last byte null */
238 		if (image->cmdline_buf[cmdline_len - 1] != '\0') {
239 			ret = -EINVAL;
240 			goto out;
241 		}
242 	}
243 
244 	/* Call arch image load handlers */
245 	ldata = arch_kexec_kernel_image_load(image);
246 
247 	if (IS_ERR(ldata)) {
248 		ret = PTR_ERR(ldata);
249 		goto out;
250 	}
251 
252 	image->image_loader_data = ldata;
253 out:
254 	/* In case of error, free up all allocated memory in this function */
255 	if (ret)
256 		kimage_file_post_load_cleanup(image);
257 	return ret;
258 }
259 
260 static int
261 kimage_file_alloc_init(struct kimage **rimage, int kernel_fd,
262 		       int initrd_fd, const char __user *cmdline_ptr,
263 		       unsigned long cmdline_len, unsigned long flags)
264 {
265 	int ret;
266 	struct kimage *image;
267 	bool kexec_on_panic = flags & KEXEC_FILE_ON_CRASH;
268 
269 	image = do_kimage_alloc_init();
270 	if (!image)
271 		return -ENOMEM;
272 
273 	image->file_mode = 1;
274 
275 	if (kexec_on_panic) {
276 		/* Enable special crash kernel control page alloc policy. */
277 		image->control_page = crashk_res.start;
278 		image->type = KEXEC_TYPE_CRASH;
279 	}
280 
281 	ret = kimage_file_prepare_segments(image, kernel_fd, initrd_fd,
282 					   cmdline_ptr, cmdline_len, flags);
283 	if (ret)
284 		goto out_free_image;
285 
286 	ret = sanity_check_segment_list(image);
287 	if (ret)
288 		goto out_free_post_load_bufs;
289 
290 	ret = -ENOMEM;
291 	image->control_code_page = kimage_alloc_control_pages(image,
292 					   get_order(KEXEC_CONTROL_PAGE_SIZE));
293 	if (!image->control_code_page) {
294 		pr_err("Could not allocate control_code_buffer\n");
295 		goto out_free_post_load_bufs;
296 	}
297 
298 	if (!kexec_on_panic) {
299 		image->swap_page = kimage_alloc_control_pages(image, 0);
300 		if (!image->swap_page) {
301 			pr_err("Could not allocate swap buffer\n");
302 			goto out_free_control_pages;
303 		}
304 	}
305 
306 	*rimage = image;
307 	return 0;
308 out_free_control_pages:
309 	kimage_free_page_list(&image->control_pages);
310 out_free_post_load_bufs:
311 	kimage_file_post_load_cleanup(image);
312 out_free_image:
313 	kfree(image);
314 	return ret;
315 }
316 
317 SYSCALL_DEFINE5(kexec_file_load, int, kernel_fd, int, initrd_fd,
318 		unsigned long, cmdline_len, const char __user *, cmdline_ptr,
319 		unsigned long, flags)
320 {
321 	int ret = 0, i;
322 	struct kimage **dest_image, *image;
323 
324 	/* We only trust the superuser with rebooting the system. */
325 	if (!capable(CAP_SYS_BOOT) || kexec_load_disabled)
326 		return -EPERM;
327 
328 	/* Make sure we have a legal set of flags */
329 	if (flags != (flags & KEXEC_FILE_FLAGS))
330 		return -EINVAL;
331 
332 	image = NULL;
333 
334 	if (!mutex_trylock(&kexec_mutex))
335 		return -EBUSY;
336 
337 	dest_image = &kexec_image;
338 	if (flags & KEXEC_FILE_ON_CRASH) {
339 		dest_image = &kexec_crash_image;
340 		if (kexec_crash_image)
341 			arch_kexec_unprotect_crashkres();
342 	}
343 
344 	if (flags & KEXEC_FILE_UNLOAD)
345 		goto exchange;
346 
347 	/*
348 	 * In case of crash, new kernel gets loaded in reserved region. It is
349 	 * same memory where old crash kernel might be loaded. Free any
350 	 * current crash dump kernel before we corrupt it.
351 	 */
352 	if (flags & KEXEC_FILE_ON_CRASH)
353 		kimage_free(xchg(&kexec_crash_image, NULL));
354 
355 	ret = kimage_file_alloc_init(&image, kernel_fd, initrd_fd, cmdline_ptr,
356 				     cmdline_len, flags);
357 	if (ret)
358 		goto out;
359 
360 	ret = machine_kexec_prepare(image);
361 	if (ret)
362 		goto out;
363 
364 	/*
365 	 * Some architecture(like S390) may touch the crash memory before
366 	 * machine_kexec_prepare(), we must copy vmcoreinfo data after it.
367 	 */
368 	ret = kimage_crash_copy_vmcoreinfo(image);
369 	if (ret)
370 		goto out;
371 
372 	ret = kexec_calculate_store_digests(image);
373 	if (ret)
374 		goto out;
375 
376 	for (i = 0; i < image->nr_segments; i++) {
377 		struct kexec_segment *ksegment;
378 
379 		ksegment = &image->segment[i];
380 		pr_debug("Loading segment %d: buf=0x%p bufsz=0x%zx mem=0x%lx memsz=0x%zx\n",
381 			 i, ksegment->buf, ksegment->bufsz, ksegment->mem,
382 			 ksegment->memsz);
383 
384 		ret = kimage_load_segment(image, &image->segment[i]);
385 		if (ret)
386 			goto out;
387 	}
388 
389 	kimage_terminate(image);
390 
391 	/*
392 	 * Free up any temporary buffers allocated which are not needed
393 	 * after image has been loaded
394 	 */
395 	kimage_file_post_load_cleanup(image);
396 exchange:
397 	image = xchg(dest_image, image);
398 out:
399 	if ((flags & KEXEC_FILE_ON_CRASH) && kexec_crash_image)
400 		arch_kexec_protect_crashkres();
401 
402 	mutex_unlock(&kexec_mutex);
403 	kimage_free(image);
404 	return ret;
405 }
406 
407 static int locate_mem_hole_top_down(unsigned long start, unsigned long end,
408 				    struct kexec_buf *kbuf)
409 {
410 	struct kimage *image = kbuf->image;
411 	unsigned long temp_start, temp_end;
412 
413 	temp_end = min(end, kbuf->buf_max);
414 	temp_start = temp_end - kbuf->memsz;
415 
416 	do {
417 		/* align down start */
418 		temp_start = temp_start & (~(kbuf->buf_align - 1));
419 
420 		if (temp_start < start || temp_start < kbuf->buf_min)
421 			return 0;
422 
423 		temp_end = temp_start + kbuf->memsz - 1;
424 
425 		/*
426 		 * Make sure this does not conflict with any of existing
427 		 * segments
428 		 */
429 		if (kimage_is_destination_range(image, temp_start, temp_end)) {
430 			temp_start = temp_start - PAGE_SIZE;
431 			continue;
432 		}
433 
434 		/* We found a suitable memory range */
435 		break;
436 	} while (1);
437 
438 	/* If we are here, we found a suitable memory range */
439 	kbuf->mem = temp_start;
440 
441 	/* Success, stop navigating through remaining System RAM ranges */
442 	return 1;
443 }
444 
445 static int locate_mem_hole_bottom_up(unsigned long start, unsigned long end,
446 				     struct kexec_buf *kbuf)
447 {
448 	struct kimage *image = kbuf->image;
449 	unsigned long temp_start, temp_end;
450 
451 	temp_start = max(start, kbuf->buf_min);
452 
453 	do {
454 		temp_start = ALIGN(temp_start, kbuf->buf_align);
455 		temp_end = temp_start + kbuf->memsz - 1;
456 
457 		if (temp_end > end || temp_end > kbuf->buf_max)
458 			return 0;
459 		/*
460 		 * Make sure this does not conflict with any of existing
461 		 * segments
462 		 */
463 		if (kimage_is_destination_range(image, temp_start, temp_end)) {
464 			temp_start = temp_start + PAGE_SIZE;
465 			continue;
466 		}
467 
468 		/* We found a suitable memory range */
469 		break;
470 	} while (1);
471 
472 	/* If we are here, we found a suitable memory range */
473 	kbuf->mem = temp_start;
474 
475 	/* Success, stop navigating through remaining System RAM ranges */
476 	return 1;
477 }
478 
479 static int locate_mem_hole_callback(struct resource *res, void *arg)
480 {
481 	struct kexec_buf *kbuf = (struct kexec_buf *)arg;
482 	u64 start = res->start, end = res->end;
483 	unsigned long sz = end - start + 1;
484 
485 	/* Returning 0 will take to next memory range */
486 	if (sz < kbuf->memsz)
487 		return 0;
488 
489 	if (end < kbuf->buf_min || start > kbuf->buf_max)
490 		return 0;
491 
492 	/*
493 	 * Allocate memory top down with-in ram range. Otherwise bottom up
494 	 * allocation.
495 	 */
496 	if (kbuf->top_down)
497 		return locate_mem_hole_top_down(start, end, kbuf);
498 	return locate_mem_hole_bottom_up(start, end, kbuf);
499 }
500 
501 #ifdef CONFIG_ARCH_KEEP_MEMBLOCK
502 static int kexec_walk_memblock(struct kexec_buf *kbuf,
503 			       int (*func)(struct resource *, void *))
504 {
505 	int ret = 0;
506 	u64 i;
507 	phys_addr_t mstart, mend;
508 	struct resource res = { };
509 
510 	if (kbuf->image->type == KEXEC_TYPE_CRASH)
511 		return func(&crashk_res, kbuf);
512 
513 	if (kbuf->top_down) {
514 		for_each_free_mem_range_reverse(i, NUMA_NO_NODE, MEMBLOCK_NONE,
515 						&mstart, &mend, NULL) {
516 			/*
517 			 * In memblock, end points to the first byte after the
518 			 * range while in kexec, end points to the last byte
519 			 * in the range.
520 			 */
521 			res.start = mstart;
522 			res.end = mend - 1;
523 			ret = func(&res, kbuf);
524 			if (ret)
525 				break;
526 		}
527 	} else {
528 		for_each_free_mem_range(i, NUMA_NO_NODE, MEMBLOCK_NONE,
529 					&mstart, &mend, NULL) {
530 			/*
531 			 * In memblock, end points to the first byte after the
532 			 * range while in kexec, end points to the last byte
533 			 * in the range.
534 			 */
535 			res.start = mstart;
536 			res.end = mend - 1;
537 			ret = func(&res, kbuf);
538 			if (ret)
539 				break;
540 		}
541 	}
542 
543 	return ret;
544 }
545 #else
546 static int kexec_walk_memblock(struct kexec_buf *kbuf,
547 			       int (*func)(struct resource *, void *))
548 {
549 	return 0;
550 }
551 #endif
552 
553 /**
554  * kexec_walk_resources - call func(data) on free memory regions
555  * @kbuf:	Context info for the search. Also passed to @func.
556  * @func:	Function to call for each memory region.
557  *
558  * Return: The memory walk will stop when func returns a non-zero value
559  * and that value will be returned. If all free regions are visited without
560  * func returning non-zero, then zero will be returned.
561  */
562 static int kexec_walk_resources(struct kexec_buf *kbuf,
563 				int (*func)(struct resource *, void *))
564 {
565 	if (kbuf->image->type == KEXEC_TYPE_CRASH)
566 		return walk_iomem_res_desc(crashk_res.desc,
567 					   IORESOURCE_SYSTEM_RAM | IORESOURCE_BUSY,
568 					   crashk_res.start, crashk_res.end,
569 					   kbuf, func);
570 	else
571 		return walk_system_ram_res(0, ULONG_MAX, kbuf, func);
572 }
573 
574 /**
575  * kexec_locate_mem_hole - find free memory for the purgatory or the next kernel
576  * @kbuf:	Parameters for the memory search.
577  *
578  * On success, kbuf->mem will have the start address of the memory region found.
579  *
580  * Return: 0 on success, negative errno on error.
581  */
582 int kexec_locate_mem_hole(struct kexec_buf *kbuf)
583 {
584 	int ret;
585 
586 	/* Arch knows where to place */
587 	if (kbuf->mem != KEXEC_BUF_MEM_UNKNOWN)
588 		return 0;
589 
590 	if (!IS_ENABLED(CONFIG_ARCH_KEEP_MEMBLOCK))
591 		ret = kexec_walk_resources(kbuf, locate_mem_hole_callback);
592 	else
593 		ret = kexec_walk_memblock(kbuf, locate_mem_hole_callback);
594 
595 	return ret == 1 ? 0 : -EADDRNOTAVAIL;
596 }
597 
598 /**
599  * kexec_add_buffer - place a buffer in a kexec segment
600  * @kbuf:	Buffer contents and memory parameters.
601  *
602  * This function assumes that kexec_mutex is held.
603  * On successful return, @kbuf->mem will have the physical address of
604  * the buffer in memory.
605  *
606  * Return: 0 on success, negative errno on error.
607  */
608 int kexec_add_buffer(struct kexec_buf *kbuf)
609 {
610 
611 	struct kexec_segment *ksegment;
612 	int ret;
613 
614 	/* Currently adding segment this way is allowed only in file mode */
615 	if (!kbuf->image->file_mode)
616 		return -EINVAL;
617 
618 	if (kbuf->image->nr_segments >= KEXEC_SEGMENT_MAX)
619 		return -EINVAL;
620 
621 	/*
622 	 * Make sure we are not trying to add buffer after allocating
623 	 * control pages. All segments need to be placed first before
624 	 * any control pages are allocated. As control page allocation
625 	 * logic goes through list of segments to make sure there are
626 	 * no destination overlaps.
627 	 */
628 	if (!list_empty(&kbuf->image->control_pages)) {
629 		WARN_ON(1);
630 		return -EINVAL;
631 	}
632 
633 	/* Ensure minimum alignment needed for segments. */
634 	kbuf->memsz = ALIGN(kbuf->memsz, PAGE_SIZE);
635 	kbuf->buf_align = max(kbuf->buf_align, PAGE_SIZE);
636 
637 	/* Walk the RAM ranges and allocate a suitable range for the buffer */
638 	ret = kexec_locate_mem_hole(kbuf);
639 	if (ret)
640 		return ret;
641 
642 	/* Found a suitable memory range */
643 	ksegment = &kbuf->image->segment[kbuf->image->nr_segments];
644 	ksegment->kbuf = kbuf->buffer;
645 	ksegment->bufsz = kbuf->bufsz;
646 	ksegment->mem = kbuf->mem;
647 	ksegment->memsz = kbuf->memsz;
648 	kbuf->image->nr_segments++;
649 	return 0;
650 }
651 
652 /* Calculate and store the digest of segments */
653 static int kexec_calculate_store_digests(struct kimage *image)
654 {
655 	struct crypto_shash *tfm;
656 	struct shash_desc *desc;
657 	int ret = 0, i, j, zero_buf_sz, sha_region_sz;
658 	size_t desc_size, nullsz;
659 	char *digest;
660 	void *zero_buf;
661 	struct kexec_sha_region *sha_regions;
662 	struct purgatory_info *pi = &image->purgatory_info;
663 
664 	if (!IS_ENABLED(CONFIG_ARCH_HAS_KEXEC_PURGATORY))
665 		return 0;
666 
667 	zero_buf = __va(page_to_pfn(ZERO_PAGE(0)) << PAGE_SHIFT);
668 	zero_buf_sz = PAGE_SIZE;
669 
670 	tfm = crypto_alloc_shash("sha256", 0, 0);
671 	if (IS_ERR(tfm)) {
672 		ret = PTR_ERR(tfm);
673 		goto out;
674 	}
675 
676 	desc_size = crypto_shash_descsize(tfm) + sizeof(*desc);
677 	desc = kzalloc(desc_size, GFP_KERNEL);
678 	if (!desc) {
679 		ret = -ENOMEM;
680 		goto out_free_tfm;
681 	}
682 
683 	sha_region_sz = KEXEC_SEGMENT_MAX * sizeof(struct kexec_sha_region);
684 	sha_regions = vzalloc(sha_region_sz);
685 	if (!sha_regions)
686 		goto out_free_desc;
687 
688 	desc->tfm   = tfm;
689 
690 	ret = crypto_shash_init(desc);
691 	if (ret < 0)
692 		goto out_free_sha_regions;
693 
694 	digest = kzalloc(SHA256_DIGEST_SIZE, GFP_KERNEL);
695 	if (!digest) {
696 		ret = -ENOMEM;
697 		goto out_free_sha_regions;
698 	}
699 
700 	for (j = i = 0; i < image->nr_segments; i++) {
701 		struct kexec_segment *ksegment;
702 
703 		ksegment = &image->segment[i];
704 		/*
705 		 * Skip purgatory as it will be modified once we put digest
706 		 * info in purgatory.
707 		 */
708 		if (ksegment->kbuf == pi->purgatory_buf)
709 			continue;
710 
711 		ret = crypto_shash_update(desc, ksegment->kbuf,
712 					  ksegment->bufsz);
713 		if (ret)
714 			break;
715 
716 		/*
717 		 * Assume rest of the buffer is filled with zero and
718 		 * update digest accordingly.
719 		 */
720 		nullsz = ksegment->memsz - ksegment->bufsz;
721 		while (nullsz) {
722 			unsigned long bytes = nullsz;
723 
724 			if (bytes > zero_buf_sz)
725 				bytes = zero_buf_sz;
726 			ret = crypto_shash_update(desc, zero_buf, bytes);
727 			if (ret)
728 				break;
729 			nullsz -= bytes;
730 		}
731 
732 		if (ret)
733 			break;
734 
735 		sha_regions[j].start = ksegment->mem;
736 		sha_regions[j].len = ksegment->memsz;
737 		j++;
738 	}
739 
740 	if (!ret) {
741 		ret = crypto_shash_final(desc, digest);
742 		if (ret)
743 			goto out_free_digest;
744 		ret = kexec_purgatory_get_set_symbol(image, "purgatory_sha_regions",
745 						     sha_regions, sha_region_sz, 0);
746 		if (ret)
747 			goto out_free_digest;
748 
749 		ret = kexec_purgatory_get_set_symbol(image, "purgatory_sha256_digest",
750 						     digest, SHA256_DIGEST_SIZE, 0);
751 		if (ret)
752 			goto out_free_digest;
753 	}
754 
755 out_free_digest:
756 	kfree(digest);
757 out_free_sha_regions:
758 	vfree(sha_regions);
759 out_free_desc:
760 	kfree(desc);
761 out_free_tfm:
762 	kfree(tfm);
763 out:
764 	return ret;
765 }
766 
767 #ifdef CONFIG_ARCH_HAS_KEXEC_PURGATORY
768 /*
769  * kexec_purgatory_setup_kbuf - prepare buffer to load purgatory.
770  * @pi:		Purgatory to be loaded.
771  * @kbuf:	Buffer to setup.
772  *
773  * Allocates the memory needed for the buffer. Caller is responsible to free
774  * the memory after use.
775  *
776  * Return: 0 on success, negative errno on error.
777  */
778 static int kexec_purgatory_setup_kbuf(struct purgatory_info *pi,
779 				      struct kexec_buf *kbuf)
780 {
781 	const Elf_Shdr *sechdrs;
782 	unsigned long bss_align;
783 	unsigned long bss_sz;
784 	unsigned long align;
785 	int i, ret;
786 
787 	sechdrs = (void *)pi->ehdr + pi->ehdr->e_shoff;
788 	kbuf->buf_align = bss_align = 1;
789 	kbuf->bufsz = bss_sz = 0;
790 
791 	for (i = 0; i < pi->ehdr->e_shnum; i++) {
792 		if (!(sechdrs[i].sh_flags & SHF_ALLOC))
793 			continue;
794 
795 		align = sechdrs[i].sh_addralign;
796 		if (sechdrs[i].sh_type != SHT_NOBITS) {
797 			if (kbuf->buf_align < align)
798 				kbuf->buf_align = align;
799 			kbuf->bufsz = ALIGN(kbuf->bufsz, align);
800 			kbuf->bufsz += sechdrs[i].sh_size;
801 		} else {
802 			if (bss_align < align)
803 				bss_align = align;
804 			bss_sz = ALIGN(bss_sz, align);
805 			bss_sz += sechdrs[i].sh_size;
806 		}
807 	}
808 	kbuf->bufsz = ALIGN(kbuf->bufsz, bss_align);
809 	kbuf->memsz = kbuf->bufsz + bss_sz;
810 	if (kbuf->buf_align < bss_align)
811 		kbuf->buf_align = bss_align;
812 
813 	kbuf->buffer = vzalloc(kbuf->bufsz);
814 	if (!kbuf->buffer)
815 		return -ENOMEM;
816 	pi->purgatory_buf = kbuf->buffer;
817 
818 	ret = kexec_add_buffer(kbuf);
819 	if (ret)
820 		goto out;
821 
822 	return 0;
823 out:
824 	vfree(pi->purgatory_buf);
825 	pi->purgatory_buf = NULL;
826 	return ret;
827 }
828 
829 /*
830  * kexec_purgatory_setup_sechdrs - prepares the pi->sechdrs buffer.
831  * @pi:		Purgatory to be loaded.
832  * @kbuf:	Buffer prepared to store purgatory.
833  *
834  * Allocates the memory needed for the buffer. Caller is responsible to free
835  * the memory after use.
836  *
837  * Return: 0 on success, negative errno on error.
838  */
839 static int kexec_purgatory_setup_sechdrs(struct purgatory_info *pi,
840 					 struct kexec_buf *kbuf)
841 {
842 	unsigned long bss_addr;
843 	unsigned long offset;
844 	Elf_Shdr *sechdrs;
845 	int i;
846 
847 	/*
848 	 * The section headers in kexec_purgatory are read-only. In order to
849 	 * have them modifiable make a temporary copy.
850 	 */
851 	sechdrs = vzalloc(array_size(sizeof(Elf_Shdr), pi->ehdr->e_shnum));
852 	if (!sechdrs)
853 		return -ENOMEM;
854 	memcpy(sechdrs, (void *)pi->ehdr + pi->ehdr->e_shoff,
855 	       pi->ehdr->e_shnum * sizeof(Elf_Shdr));
856 	pi->sechdrs = sechdrs;
857 
858 	offset = 0;
859 	bss_addr = kbuf->mem + kbuf->bufsz;
860 	kbuf->image->start = pi->ehdr->e_entry;
861 
862 	for (i = 0; i < pi->ehdr->e_shnum; i++) {
863 		unsigned long align;
864 		void *src, *dst;
865 
866 		if (!(sechdrs[i].sh_flags & SHF_ALLOC))
867 			continue;
868 
869 		align = sechdrs[i].sh_addralign;
870 		if (sechdrs[i].sh_type == SHT_NOBITS) {
871 			bss_addr = ALIGN(bss_addr, align);
872 			sechdrs[i].sh_addr = bss_addr;
873 			bss_addr += sechdrs[i].sh_size;
874 			continue;
875 		}
876 
877 		offset = ALIGN(offset, align);
878 		if (sechdrs[i].sh_flags & SHF_EXECINSTR &&
879 		    pi->ehdr->e_entry >= sechdrs[i].sh_addr &&
880 		    pi->ehdr->e_entry < (sechdrs[i].sh_addr
881 					 + sechdrs[i].sh_size)) {
882 			kbuf->image->start -= sechdrs[i].sh_addr;
883 			kbuf->image->start += kbuf->mem + offset;
884 		}
885 
886 		src = (void *)pi->ehdr + sechdrs[i].sh_offset;
887 		dst = pi->purgatory_buf + offset;
888 		memcpy(dst, src, sechdrs[i].sh_size);
889 
890 		sechdrs[i].sh_addr = kbuf->mem + offset;
891 		sechdrs[i].sh_offset = offset;
892 		offset += sechdrs[i].sh_size;
893 	}
894 
895 	return 0;
896 }
897 
898 static int kexec_apply_relocations(struct kimage *image)
899 {
900 	int i, ret;
901 	struct purgatory_info *pi = &image->purgatory_info;
902 	const Elf_Shdr *sechdrs;
903 
904 	sechdrs = (void *)pi->ehdr + pi->ehdr->e_shoff;
905 
906 	for (i = 0; i < pi->ehdr->e_shnum; i++) {
907 		const Elf_Shdr *relsec;
908 		const Elf_Shdr *symtab;
909 		Elf_Shdr *section;
910 
911 		relsec = sechdrs + i;
912 
913 		if (relsec->sh_type != SHT_RELA &&
914 		    relsec->sh_type != SHT_REL)
915 			continue;
916 
917 		/*
918 		 * For section of type SHT_RELA/SHT_REL,
919 		 * ->sh_link contains section header index of associated
920 		 * symbol table. And ->sh_info contains section header
921 		 * index of section to which relocations apply.
922 		 */
923 		if (relsec->sh_info >= pi->ehdr->e_shnum ||
924 		    relsec->sh_link >= pi->ehdr->e_shnum)
925 			return -ENOEXEC;
926 
927 		section = pi->sechdrs + relsec->sh_info;
928 		symtab = sechdrs + relsec->sh_link;
929 
930 		if (!(section->sh_flags & SHF_ALLOC))
931 			continue;
932 
933 		/*
934 		 * symtab->sh_link contain section header index of associated
935 		 * string table.
936 		 */
937 		if (symtab->sh_link >= pi->ehdr->e_shnum)
938 			/* Invalid section number? */
939 			continue;
940 
941 		/*
942 		 * Respective architecture needs to provide support for applying
943 		 * relocations of type SHT_RELA/SHT_REL.
944 		 */
945 		if (relsec->sh_type == SHT_RELA)
946 			ret = arch_kexec_apply_relocations_add(pi, section,
947 							       relsec, symtab);
948 		else if (relsec->sh_type == SHT_REL)
949 			ret = arch_kexec_apply_relocations(pi, section,
950 							   relsec, symtab);
951 		if (ret)
952 			return ret;
953 	}
954 
955 	return 0;
956 }
957 
958 /*
959  * kexec_load_purgatory - Load and relocate the purgatory object.
960  * @image:	Image to add the purgatory to.
961  * @kbuf:	Memory parameters to use.
962  *
963  * Allocates the memory needed for image->purgatory_info.sechdrs and
964  * image->purgatory_info.purgatory_buf/kbuf->buffer. Caller is responsible
965  * to free the memory after use.
966  *
967  * Return: 0 on success, negative errno on error.
968  */
969 int kexec_load_purgatory(struct kimage *image, struct kexec_buf *kbuf)
970 {
971 	struct purgatory_info *pi = &image->purgatory_info;
972 	int ret;
973 
974 	if (kexec_purgatory_size <= 0)
975 		return -EINVAL;
976 
977 	pi->ehdr = (const Elf_Ehdr *)kexec_purgatory;
978 
979 	ret = kexec_purgatory_setup_kbuf(pi, kbuf);
980 	if (ret)
981 		return ret;
982 
983 	ret = kexec_purgatory_setup_sechdrs(pi, kbuf);
984 	if (ret)
985 		goto out_free_kbuf;
986 
987 	ret = kexec_apply_relocations(image);
988 	if (ret)
989 		goto out;
990 
991 	return 0;
992 out:
993 	vfree(pi->sechdrs);
994 	pi->sechdrs = NULL;
995 out_free_kbuf:
996 	vfree(pi->purgatory_buf);
997 	pi->purgatory_buf = NULL;
998 	return ret;
999 }
1000 
1001 /*
1002  * kexec_purgatory_find_symbol - find a symbol in the purgatory
1003  * @pi:		Purgatory to search in.
1004  * @name:	Name of the symbol.
1005  *
1006  * Return: pointer to symbol in read-only symtab on success, NULL on error.
1007  */
1008 static const Elf_Sym *kexec_purgatory_find_symbol(struct purgatory_info *pi,
1009 						  const char *name)
1010 {
1011 	const Elf_Shdr *sechdrs;
1012 	const Elf_Ehdr *ehdr;
1013 	const Elf_Sym *syms;
1014 	const char *strtab;
1015 	int i, k;
1016 
1017 	if (!pi->ehdr)
1018 		return NULL;
1019 
1020 	ehdr = pi->ehdr;
1021 	sechdrs = (void *)ehdr + ehdr->e_shoff;
1022 
1023 	for (i = 0; i < ehdr->e_shnum; i++) {
1024 		if (sechdrs[i].sh_type != SHT_SYMTAB)
1025 			continue;
1026 
1027 		if (sechdrs[i].sh_link >= ehdr->e_shnum)
1028 			/* Invalid strtab section number */
1029 			continue;
1030 		strtab = (void *)ehdr + sechdrs[sechdrs[i].sh_link].sh_offset;
1031 		syms = (void *)ehdr + sechdrs[i].sh_offset;
1032 
1033 		/* Go through symbols for a match */
1034 		for (k = 0; k < sechdrs[i].sh_size/sizeof(Elf_Sym); k++) {
1035 			if (ELF_ST_BIND(syms[k].st_info) != STB_GLOBAL)
1036 				continue;
1037 
1038 			if (strcmp(strtab + syms[k].st_name, name) != 0)
1039 				continue;
1040 
1041 			if (syms[k].st_shndx == SHN_UNDEF ||
1042 			    syms[k].st_shndx >= ehdr->e_shnum) {
1043 				pr_debug("Symbol: %s has bad section index %d.\n",
1044 						name, syms[k].st_shndx);
1045 				return NULL;
1046 			}
1047 
1048 			/* Found the symbol we are looking for */
1049 			return &syms[k];
1050 		}
1051 	}
1052 
1053 	return NULL;
1054 }
1055 
1056 void *kexec_purgatory_get_symbol_addr(struct kimage *image, const char *name)
1057 {
1058 	struct purgatory_info *pi = &image->purgatory_info;
1059 	const Elf_Sym *sym;
1060 	Elf_Shdr *sechdr;
1061 
1062 	sym = kexec_purgatory_find_symbol(pi, name);
1063 	if (!sym)
1064 		return ERR_PTR(-EINVAL);
1065 
1066 	sechdr = &pi->sechdrs[sym->st_shndx];
1067 
1068 	/*
1069 	 * Returns the address where symbol will finally be loaded after
1070 	 * kexec_load_segment()
1071 	 */
1072 	return (void *)(sechdr->sh_addr + sym->st_value);
1073 }
1074 
1075 /*
1076  * Get or set value of a symbol. If "get_value" is true, symbol value is
1077  * returned in buf otherwise symbol value is set based on value in buf.
1078  */
1079 int kexec_purgatory_get_set_symbol(struct kimage *image, const char *name,
1080 				   void *buf, unsigned int size, bool get_value)
1081 {
1082 	struct purgatory_info *pi = &image->purgatory_info;
1083 	const Elf_Sym *sym;
1084 	Elf_Shdr *sec;
1085 	char *sym_buf;
1086 
1087 	sym = kexec_purgatory_find_symbol(pi, name);
1088 	if (!sym)
1089 		return -EINVAL;
1090 
1091 	if (sym->st_size != size) {
1092 		pr_err("symbol %s size mismatch: expected %lu actual %u\n",
1093 		       name, (unsigned long)sym->st_size, size);
1094 		return -EINVAL;
1095 	}
1096 
1097 	sec = pi->sechdrs + sym->st_shndx;
1098 
1099 	if (sec->sh_type == SHT_NOBITS) {
1100 		pr_err("symbol %s is in a bss section. Cannot %s\n", name,
1101 		       get_value ? "get" : "set");
1102 		return -EINVAL;
1103 	}
1104 
1105 	sym_buf = (char *)pi->purgatory_buf + sec->sh_offset + sym->st_value;
1106 
1107 	if (get_value)
1108 		memcpy((void *)buf, sym_buf, size);
1109 	else
1110 		memcpy((void *)sym_buf, buf, size);
1111 
1112 	return 0;
1113 }
1114 #endif /* CONFIG_ARCH_HAS_KEXEC_PURGATORY */
1115 
1116 int crash_exclude_mem_range(struct crash_mem *mem,
1117 			    unsigned long long mstart, unsigned long long mend)
1118 {
1119 	int i, j;
1120 	unsigned long long start, end;
1121 	struct crash_mem_range temp_range = {0, 0};
1122 
1123 	for (i = 0; i < mem->nr_ranges; i++) {
1124 		start = mem->ranges[i].start;
1125 		end = mem->ranges[i].end;
1126 
1127 		if (mstart > end || mend < start)
1128 			continue;
1129 
1130 		/* Truncate any area outside of range */
1131 		if (mstart < start)
1132 			mstart = start;
1133 		if (mend > end)
1134 			mend = end;
1135 
1136 		/* Found completely overlapping range */
1137 		if (mstart == start && mend == end) {
1138 			mem->ranges[i].start = 0;
1139 			mem->ranges[i].end = 0;
1140 			if (i < mem->nr_ranges - 1) {
1141 				/* Shift rest of the ranges to left */
1142 				for (j = i; j < mem->nr_ranges - 1; j++) {
1143 					mem->ranges[j].start =
1144 						mem->ranges[j+1].start;
1145 					mem->ranges[j].end =
1146 							mem->ranges[j+1].end;
1147 				}
1148 			}
1149 			mem->nr_ranges--;
1150 			return 0;
1151 		}
1152 
1153 		if (mstart > start && mend < end) {
1154 			/* Split original range */
1155 			mem->ranges[i].end = mstart - 1;
1156 			temp_range.start = mend + 1;
1157 			temp_range.end = end;
1158 		} else if (mstart != start)
1159 			mem->ranges[i].end = mstart - 1;
1160 		else
1161 			mem->ranges[i].start = mend + 1;
1162 		break;
1163 	}
1164 
1165 	/* If a split happened, add the split to array */
1166 	if (!temp_range.end)
1167 		return 0;
1168 
1169 	/* Split happened */
1170 	if (i == mem->max_nr_ranges - 1)
1171 		return -ENOMEM;
1172 
1173 	/* Location where new range should go */
1174 	j = i + 1;
1175 	if (j < mem->nr_ranges) {
1176 		/* Move over all ranges one slot towards the end */
1177 		for (i = mem->nr_ranges - 1; i >= j; i--)
1178 			mem->ranges[i + 1] = mem->ranges[i];
1179 	}
1180 
1181 	mem->ranges[j].start = temp_range.start;
1182 	mem->ranges[j].end = temp_range.end;
1183 	mem->nr_ranges++;
1184 	return 0;
1185 }
1186 
1187 int crash_prepare_elf64_headers(struct crash_mem *mem, int kernel_map,
1188 			  void **addr, unsigned long *sz)
1189 {
1190 	Elf64_Ehdr *ehdr;
1191 	Elf64_Phdr *phdr;
1192 	unsigned long nr_cpus = num_possible_cpus(), nr_phdr, elf_sz;
1193 	unsigned char *buf;
1194 	unsigned int cpu, i;
1195 	unsigned long long notes_addr;
1196 	unsigned long mstart, mend;
1197 
1198 	/* extra phdr for vmcoreinfo elf note */
1199 	nr_phdr = nr_cpus + 1;
1200 	nr_phdr += mem->nr_ranges;
1201 
1202 	/*
1203 	 * kexec-tools creates an extra PT_LOAD phdr for kernel text mapping
1204 	 * area (for example, ffffffff80000000 - ffffffffa0000000 on x86_64).
1205 	 * I think this is required by tools like gdb. So same physical
1206 	 * memory will be mapped in two elf headers. One will contain kernel
1207 	 * text virtual addresses and other will have __va(physical) addresses.
1208 	 */
1209 
1210 	nr_phdr++;
1211 	elf_sz = sizeof(Elf64_Ehdr) + nr_phdr * sizeof(Elf64_Phdr);
1212 	elf_sz = ALIGN(elf_sz, ELF_CORE_HEADER_ALIGN);
1213 
1214 	buf = vzalloc(elf_sz);
1215 	if (!buf)
1216 		return -ENOMEM;
1217 
1218 	ehdr = (Elf64_Ehdr *)buf;
1219 	phdr = (Elf64_Phdr *)(ehdr + 1);
1220 	memcpy(ehdr->e_ident, ELFMAG, SELFMAG);
1221 	ehdr->e_ident[EI_CLASS] = ELFCLASS64;
1222 	ehdr->e_ident[EI_DATA] = ELFDATA2LSB;
1223 	ehdr->e_ident[EI_VERSION] = EV_CURRENT;
1224 	ehdr->e_ident[EI_OSABI] = ELF_OSABI;
1225 	memset(ehdr->e_ident + EI_PAD, 0, EI_NIDENT - EI_PAD);
1226 	ehdr->e_type = ET_CORE;
1227 	ehdr->e_machine = ELF_ARCH;
1228 	ehdr->e_version = EV_CURRENT;
1229 	ehdr->e_phoff = sizeof(Elf64_Ehdr);
1230 	ehdr->e_ehsize = sizeof(Elf64_Ehdr);
1231 	ehdr->e_phentsize = sizeof(Elf64_Phdr);
1232 
1233 	/* Prepare one phdr of type PT_NOTE for each present cpu */
1234 	for_each_present_cpu(cpu) {
1235 		phdr->p_type = PT_NOTE;
1236 		notes_addr = per_cpu_ptr_to_phys(per_cpu_ptr(crash_notes, cpu));
1237 		phdr->p_offset = phdr->p_paddr = notes_addr;
1238 		phdr->p_filesz = phdr->p_memsz = sizeof(note_buf_t);
1239 		(ehdr->e_phnum)++;
1240 		phdr++;
1241 	}
1242 
1243 	/* Prepare one PT_NOTE header for vmcoreinfo */
1244 	phdr->p_type = PT_NOTE;
1245 	phdr->p_offset = phdr->p_paddr = paddr_vmcoreinfo_note();
1246 	phdr->p_filesz = phdr->p_memsz = VMCOREINFO_NOTE_SIZE;
1247 	(ehdr->e_phnum)++;
1248 	phdr++;
1249 
1250 	/* Prepare PT_LOAD type program header for kernel text region */
1251 	if (kernel_map) {
1252 		phdr->p_type = PT_LOAD;
1253 		phdr->p_flags = PF_R|PF_W|PF_X;
1254 		phdr->p_vaddr = (Elf64_Addr)_text;
1255 		phdr->p_filesz = phdr->p_memsz = _end - _text;
1256 		phdr->p_offset = phdr->p_paddr = __pa_symbol(_text);
1257 		ehdr->e_phnum++;
1258 		phdr++;
1259 	}
1260 
1261 	/* Go through all the ranges in mem->ranges[] and prepare phdr */
1262 	for (i = 0; i < mem->nr_ranges; i++) {
1263 		mstart = mem->ranges[i].start;
1264 		mend = mem->ranges[i].end;
1265 
1266 		phdr->p_type = PT_LOAD;
1267 		phdr->p_flags = PF_R|PF_W|PF_X;
1268 		phdr->p_offset  = mstart;
1269 
1270 		phdr->p_paddr = mstart;
1271 		phdr->p_vaddr = (unsigned long long) __va(mstart);
1272 		phdr->p_filesz = phdr->p_memsz = mend - mstart + 1;
1273 		phdr->p_align = 0;
1274 		ehdr->e_phnum++;
1275 		phdr++;
1276 		pr_debug("Crash PT_LOAD elf header. phdr=%p vaddr=0x%llx, paddr=0x%llx, sz=0x%llx e_phnum=%d p_offset=0x%llx\n",
1277 			phdr, phdr->p_vaddr, phdr->p_paddr, phdr->p_filesz,
1278 			ehdr->e_phnum, phdr->p_offset);
1279 	}
1280 
1281 	*addr = buf;
1282 	*sz = elf_sz;
1283 	return 0;
1284 }
1285