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