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