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