xref: /linux/kernel/kexec_file.c (revision f11c1efe46ad84555a0948401c7bdb63d711088d)
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 
448 	do {
449 		/* align down start */
450 		temp_start = ALIGN_DOWN(temp_start, kbuf->buf_align);
451 
452 		if (temp_start < start || temp_start < kbuf->buf_min)
453 			return 0;
454 
455 		temp_end = temp_start + kbuf->memsz - 1;
456 
457 		/*
458 		 * Make sure this does not conflict with any of existing
459 		 * segments
460 		 */
461 		if (kimage_is_destination_range(image, temp_start, temp_end)) {
462 			temp_start = temp_start - PAGE_SIZE;
463 			continue;
464 		}
465 
466 		/* Make sure this does not conflict with exclude range */
467 		if (arch_check_excluded_range(image, temp_start, temp_end)) {
468 			temp_start = temp_start - PAGE_SIZE;
469 			continue;
470 		}
471 
472 		/* We found a suitable memory range */
473 		break;
474 	} while (1);
475 
476 	/* If we are here, we found a suitable memory range */
477 	kbuf->mem = temp_start;
478 
479 	/* Success, stop navigating through remaining System RAM ranges */
480 	return 1;
481 }
482 
483 static int locate_mem_hole_bottom_up(unsigned long start, unsigned long end,
484 				     struct kexec_buf *kbuf)
485 {
486 	struct kimage *image = kbuf->image;
487 	unsigned long temp_start, temp_end;
488 
489 	temp_start = max(start, kbuf->buf_min);
490 
491 	do {
492 		temp_start = ALIGN(temp_start, kbuf->buf_align);
493 		temp_end = temp_start + kbuf->memsz - 1;
494 
495 		if (temp_end > end || temp_end > kbuf->buf_max)
496 			return 0;
497 		/*
498 		 * Make sure this does not conflict with any of existing
499 		 * segments
500 		 */
501 		if (kimage_is_destination_range(image, temp_start, temp_end)) {
502 			temp_start = temp_start + PAGE_SIZE;
503 			continue;
504 		}
505 
506 		/* Make sure this does not conflict with exclude range */
507 		if (arch_check_excluded_range(image, temp_start, temp_end)) {
508 			temp_start = temp_start + PAGE_SIZE;
509 			continue;
510 		}
511 
512 		/* We found a suitable memory range */
513 		break;
514 	} while (1);
515 
516 	/* If we are here, we found a suitable memory range */
517 	kbuf->mem = temp_start;
518 
519 	/* Success, stop navigating through remaining System RAM ranges */
520 	return 1;
521 }
522 
523 static int locate_mem_hole_callback(struct resource *res, void *arg)
524 {
525 	struct kexec_buf *kbuf = (struct kexec_buf *)arg;
526 	u64 start = res->start, end = res->end;
527 	unsigned long sz = end - start + 1;
528 
529 	/* Returning 0 will take to next memory range */
530 
531 	/* Don't use memory that will be detected and handled by a driver. */
532 	if (res->flags & IORESOURCE_SYSRAM_DRIVER_MANAGED)
533 		return 0;
534 
535 	if (sz < kbuf->memsz)
536 		return 0;
537 
538 	if (end < kbuf->buf_min || start > kbuf->buf_max)
539 		return 0;
540 
541 	/*
542 	 * Allocate memory top down with-in ram range. Otherwise bottom up
543 	 * allocation.
544 	 */
545 	if (kbuf->top_down)
546 		return locate_mem_hole_top_down(start, end, kbuf);
547 	return locate_mem_hole_bottom_up(start, end, kbuf);
548 }
549 
550 #ifdef CONFIG_ARCH_KEEP_MEMBLOCK
551 static int kexec_walk_memblock(struct kexec_buf *kbuf,
552 			       int (*func)(struct resource *, void *))
553 {
554 	int ret = 0;
555 	u64 i;
556 	phys_addr_t mstart, mend;
557 	struct resource res = { };
558 
559 #ifdef CONFIG_CRASH_DUMP
560 	if (kbuf->image->type == KEXEC_TYPE_CRASH)
561 		return func(&crashk_res, kbuf);
562 #endif
563 
564 	/*
565 	 * Using MEMBLOCK_NONE will properly skip MEMBLOCK_DRIVER_MANAGED. See
566 	 * IORESOURCE_SYSRAM_DRIVER_MANAGED handling in
567 	 * locate_mem_hole_callback().
568 	 */
569 	if (kbuf->top_down) {
570 		for_each_free_mem_range_reverse(i, NUMA_NO_NODE, MEMBLOCK_NONE,
571 						&mstart, &mend, NULL) {
572 			/*
573 			 * In memblock, end points to the first byte after the
574 			 * range while in kexec, end points to the last byte
575 			 * in the range.
576 			 */
577 			res.start = mstart;
578 			res.end = mend - 1;
579 			ret = func(&res, kbuf);
580 			if (ret)
581 				break;
582 		}
583 	} else {
584 		for_each_free_mem_range(i, NUMA_NO_NODE, MEMBLOCK_NONE,
585 					&mstart, &mend, NULL) {
586 			/*
587 			 * In memblock, end points to the first byte after the
588 			 * range while in kexec, end points to the last byte
589 			 * in the range.
590 			 */
591 			res.start = mstart;
592 			res.end = mend - 1;
593 			ret = func(&res, kbuf);
594 			if (ret)
595 				break;
596 		}
597 	}
598 
599 	return ret;
600 }
601 #else
602 static int kexec_walk_memblock(struct kexec_buf *kbuf,
603 			       int (*func)(struct resource *, void *))
604 {
605 	return 0;
606 }
607 #endif
608 
609 /**
610  * kexec_walk_resources - call func(data) on free memory regions
611  * @kbuf:	Context info for the search. Also passed to @func.
612  * @func:	Function to call for each memory region.
613  *
614  * Return: The memory walk will stop when func returns a non-zero value
615  * and that value will be returned. If all free regions are visited without
616  * func returning non-zero, then zero will be returned.
617  */
618 static int kexec_walk_resources(struct kexec_buf *kbuf,
619 				int (*func)(struct resource *, void *))
620 {
621 #ifdef CONFIG_CRASH_DUMP
622 	if (kbuf->image->type == KEXEC_TYPE_CRASH)
623 		return walk_iomem_res_desc(crashk_res.desc,
624 					   IORESOURCE_SYSTEM_RAM | IORESOURCE_BUSY,
625 					   crashk_res.start, crashk_res.end,
626 					   kbuf, func);
627 #endif
628 	if (kbuf->top_down)
629 		return walk_system_ram_res_rev(0, ULONG_MAX, kbuf, func);
630 	else
631 		return walk_system_ram_res(0, ULONG_MAX, kbuf, func);
632 }
633 
634 /**
635  * kexec_locate_mem_hole - find free memory for the purgatory or the next kernel
636  * @kbuf:	Parameters for the memory search.
637  *
638  * On success, kbuf->mem will have the start address of the memory region found.
639  *
640  * Return: 0 on success, negative errno on error.
641  */
642 int kexec_locate_mem_hole(struct kexec_buf *kbuf)
643 {
644 	int ret;
645 
646 	/* Arch knows where to place */
647 	if (kbuf->mem != KEXEC_BUF_MEM_UNKNOWN)
648 		return 0;
649 
650 	if (!IS_ENABLED(CONFIG_ARCH_KEEP_MEMBLOCK))
651 		ret = kexec_walk_resources(kbuf, locate_mem_hole_callback);
652 	else
653 		ret = kexec_walk_memblock(kbuf, locate_mem_hole_callback);
654 
655 	return ret == 1 ? 0 : -EADDRNOTAVAIL;
656 }
657 
658 /**
659  * kexec_add_buffer - place a buffer in a kexec segment
660  * @kbuf:	Buffer contents and memory parameters.
661  *
662  * This function assumes that kexec_lock is held.
663  * On successful return, @kbuf->mem will have the physical address of
664  * the buffer in memory.
665  *
666  * Return: 0 on success, negative errno on error.
667  */
668 int kexec_add_buffer(struct kexec_buf *kbuf)
669 {
670 	struct kexec_segment *ksegment;
671 	int ret;
672 
673 	/* Currently adding segment this way is allowed only in file mode */
674 	if (!kbuf->image->file_mode)
675 		return -EINVAL;
676 
677 	if (kbuf->image->nr_segments >= KEXEC_SEGMENT_MAX)
678 		return -EINVAL;
679 
680 	/*
681 	 * Make sure we are not trying to add buffer after allocating
682 	 * control pages. All segments need to be placed first before
683 	 * any control pages are allocated. As control page allocation
684 	 * logic goes through list of segments to make sure there are
685 	 * no destination overlaps.
686 	 */
687 	if (!list_empty(&kbuf->image->control_pages)) {
688 		WARN_ON(1);
689 		return -EINVAL;
690 	}
691 
692 	/* Ensure minimum alignment needed for segments. */
693 	kbuf->memsz = ALIGN(kbuf->memsz, PAGE_SIZE);
694 	kbuf->buf_align = max(kbuf->buf_align, PAGE_SIZE);
695 
696 	/* Walk the RAM ranges and allocate a suitable range for the buffer */
697 	ret = arch_kexec_locate_mem_hole(kbuf);
698 	if (ret)
699 		return ret;
700 
701 	/* Found a suitable memory range */
702 	ksegment = &kbuf->image->segment[kbuf->image->nr_segments];
703 	ksegment->kbuf = kbuf->buffer;
704 	ksegment->bufsz = kbuf->bufsz;
705 	ksegment->mem = kbuf->mem;
706 	ksegment->memsz = kbuf->memsz;
707 	kbuf->image->nr_segments++;
708 	return 0;
709 }
710 
711 /* Calculate and store the digest of segments */
712 static int kexec_calculate_store_digests(struct kimage *image)
713 {
714 	struct sha256_state state;
715 	int ret = 0, i, j, zero_buf_sz, sha_region_sz;
716 	size_t nullsz;
717 	u8 digest[SHA256_DIGEST_SIZE];
718 	void *zero_buf;
719 	struct kexec_sha_region *sha_regions;
720 	struct purgatory_info *pi = &image->purgatory_info;
721 
722 	if (!IS_ENABLED(CONFIG_ARCH_SUPPORTS_KEXEC_PURGATORY))
723 		return 0;
724 
725 	zero_buf = __va(page_to_pfn(ZERO_PAGE(0)) << PAGE_SHIFT);
726 	zero_buf_sz = PAGE_SIZE;
727 
728 	sha_region_sz = KEXEC_SEGMENT_MAX * sizeof(struct kexec_sha_region);
729 	sha_regions = vzalloc(sha_region_sz);
730 	if (!sha_regions)
731 		return -ENOMEM;
732 
733 	sha256_init(&state);
734 
735 	for (j = i = 0; i < image->nr_segments; i++) {
736 		struct kexec_segment *ksegment;
737 
738 #ifdef CONFIG_CRASH_HOTPLUG
739 		/* Exclude elfcorehdr segment to allow future changes via hotplug */
740 		if (i == image->elfcorehdr_index)
741 			continue;
742 #endif
743 
744 		ksegment = &image->segment[i];
745 		/*
746 		 * Skip purgatory as it will be modified once we put digest
747 		 * info in purgatory.
748 		 */
749 		if (ksegment->kbuf == pi->purgatory_buf)
750 			continue;
751 
752 		sha256_update(&state, ksegment->kbuf, ksegment->bufsz);
753 
754 		/*
755 		 * Assume rest of the buffer is filled with zero and
756 		 * update digest accordingly.
757 		 */
758 		nullsz = ksegment->memsz - ksegment->bufsz;
759 		while (nullsz) {
760 			unsigned long bytes = nullsz;
761 
762 			if (bytes > zero_buf_sz)
763 				bytes = zero_buf_sz;
764 			sha256_update(&state, zero_buf, bytes);
765 			nullsz -= bytes;
766 		}
767 
768 		sha_regions[j].start = ksegment->mem;
769 		sha_regions[j].len = ksegment->memsz;
770 		j++;
771 	}
772 
773 	sha256_final(&state, digest);
774 
775 	ret = kexec_purgatory_get_set_symbol(image, "purgatory_sha_regions",
776 					     sha_regions, sha_region_sz, 0);
777 	if (ret)
778 		goto out_free_sha_regions;
779 
780 	ret = kexec_purgatory_get_set_symbol(image, "purgatory_sha256_digest",
781 					     digest, SHA256_DIGEST_SIZE, 0);
782 out_free_sha_regions:
783 	vfree(sha_regions);
784 	return ret;
785 }
786 
787 #ifdef CONFIG_ARCH_SUPPORTS_KEXEC_PURGATORY
788 /*
789  * kexec_purgatory_setup_kbuf - prepare buffer to load purgatory.
790  * @pi:		Purgatory to be loaded.
791  * @kbuf:	Buffer to setup.
792  *
793  * Allocates the memory needed for the buffer. Caller is responsible to free
794  * the memory after use.
795  *
796  * Return: 0 on success, negative errno on error.
797  */
798 static int kexec_purgatory_setup_kbuf(struct purgatory_info *pi,
799 				      struct kexec_buf *kbuf)
800 {
801 	const Elf_Shdr *sechdrs;
802 	unsigned long bss_align;
803 	unsigned long bss_sz;
804 	unsigned long align;
805 	int i, ret;
806 
807 	sechdrs = (void *)pi->ehdr + pi->ehdr->e_shoff;
808 	kbuf->buf_align = bss_align = 1;
809 	kbuf->bufsz = bss_sz = 0;
810 
811 	for (i = 0; i < pi->ehdr->e_shnum; i++) {
812 		if (!(sechdrs[i].sh_flags & SHF_ALLOC))
813 			continue;
814 
815 		align = sechdrs[i].sh_addralign;
816 		if (sechdrs[i].sh_type != SHT_NOBITS) {
817 			if (kbuf->buf_align < align)
818 				kbuf->buf_align = align;
819 			kbuf->bufsz = ALIGN(kbuf->bufsz, align);
820 			kbuf->bufsz += sechdrs[i].sh_size;
821 		} else {
822 			if (bss_align < align)
823 				bss_align = align;
824 			bss_sz = ALIGN(bss_sz, align);
825 			bss_sz += sechdrs[i].sh_size;
826 		}
827 	}
828 	kbuf->bufsz = ALIGN(kbuf->bufsz, bss_align);
829 	kbuf->memsz = kbuf->bufsz + bss_sz;
830 	if (kbuf->buf_align < bss_align)
831 		kbuf->buf_align = bss_align;
832 
833 	kbuf->buffer = vzalloc(kbuf->bufsz);
834 	if (!kbuf->buffer)
835 		return -ENOMEM;
836 	pi->purgatory_buf = kbuf->buffer;
837 
838 	ret = kexec_add_buffer(kbuf);
839 	if (ret)
840 		goto out;
841 
842 	return 0;
843 out:
844 	vfree(pi->purgatory_buf);
845 	pi->purgatory_buf = NULL;
846 	return ret;
847 }
848 
849 /*
850  * kexec_purgatory_setup_sechdrs - prepares the pi->sechdrs buffer.
851  * @pi:		Purgatory to be loaded.
852  * @kbuf:	Buffer prepared to store purgatory.
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_sechdrs(struct purgatory_info *pi,
860 					 struct kexec_buf *kbuf)
861 {
862 	unsigned long bss_addr;
863 	unsigned long offset;
864 	size_t sechdrs_size;
865 	Elf_Shdr *sechdrs;
866 	int i;
867 
868 	/*
869 	 * The section headers in kexec_purgatory are read-only. In order to
870 	 * have them modifiable make a temporary copy.
871 	 */
872 	sechdrs_size = array_size(sizeof(Elf_Shdr), pi->ehdr->e_shnum);
873 	sechdrs = vzalloc(sechdrs_size);
874 	if (!sechdrs)
875 		return -ENOMEM;
876 	memcpy(sechdrs, (void *)pi->ehdr + pi->ehdr->e_shoff, sechdrs_size);
877 	pi->sechdrs = sechdrs;
878 
879 	offset = 0;
880 	bss_addr = kbuf->mem + kbuf->bufsz;
881 	kbuf->image->start = pi->ehdr->e_entry;
882 
883 	for (i = 0; i < pi->ehdr->e_shnum; i++) {
884 		unsigned long align;
885 		void *src, *dst;
886 
887 		if (!(sechdrs[i].sh_flags & SHF_ALLOC))
888 			continue;
889 
890 		align = sechdrs[i].sh_addralign;
891 		if (sechdrs[i].sh_type == SHT_NOBITS) {
892 			bss_addr = ALIGN(bss_addr, align);
893 			sechdrs[i].sh_addr = bss_addr;
894 			bss_addr += sechdrs[i].sh_size;
895 			continue;
896 		}
897 
898 		offset = ALIGN(offset, align);
899 
900 		/*
901 		 * Check if the segment contains the entry point, if so,
902 		 * calculate the value of image->start based on it.
903 		 * If the compiler has produced more than one .text section
904 		 * (Eg: .text.hot), they are generally after the main .text
905 		 * section, and they shall not be used to calculate
906 		 * image->start. So do not re-calculate image->start if it
907 		 * is not set to the initial value, and warn the user so they
908 		 * have a chance to fix their purgatory's linker script.
909 		 */
910 		if (sechdrs[i].sh_flags & SHF_EXECINSTR &&
911 		    pi->ehdr->e_entry >= sechdrs[i].sh_addr &&
912 		    pi->ehdr->e_entry < (sechdrs[i].sh_addr
913 					 + sechdrs[i].sh_size) &&
914 		    !WARN_ON(kbuf->image->start != pi->ehdr->e_entry)) {
915 			kbuf->image->start -= sechdrs[i].sh_addr;
916 			kbuf->image->start += kbuf->mem + offset;
917 		}
918 
919 		src = (void *)pi->ehdr + sechdrs[i].sh_offset;
920 		dst = pi->purgatory_buf + offset;
921 		memcpy(dst, src, sechdrs[i].sh_size);
922 
923 		sechdrs[i].sh_addr = kbuf->mem + offset;
924 		sechdrs[i].sh_offset = offset;
925 		offset += sechdrs[i].sh_size;
926 	}
927 
928 	return 0;
929 }
930 
931 static int kexec_apply_relocations(struct kimage *image)
932 {
933 	int i, ret;
934 	struct purgatory_info *pi = &image->purgatory_info;
935 	const Elf_Shdr *sechdrs;
936 
937 	sechdrs = (void *)pi->ehdr + pi->ehdr->e_shoff;
938 
939 	for (i = 0; i < pi->ehdr->e_shnum; i++) {
940 		const Elf_Shdr *relsec;
941 		const Elf_Shdr *symtab;
942 		Elf_Shdr *section;
943 
944 		relsec = sechdrs + i;
945 
946 		if (relsec->sh_type != SHT_RELA &&
947 		    relsec->sh_type != SHT_REL)
948 			continue;
949 
950 		/*
951 		 * For section of type SHT_RELA/SHT_REL,
952 		 * ->sh_link contains section header index of associated
953 		 * symbol table. And ->sh_info contains section header
954 		 * index of section to which relocations apply.
955 		 */
956 		if (relsec->sh_info >= pi->ehdr->e_shnum ||
957 		    relsec->sh_link >= pi->ehdr->e_shnum)
958 			return -ENOEXEC;
959 
960 		section = pi->sechdrs + relsec->sh_info;
961 		symtab = sechdrs + relsec->sh_link;
962 
963 		if (!(section->sh_flags & SHF_ALLOC))
964 			continue;
965 
966 		/*
967 		 * symtab->sh_link contain section header index of associated
968 		 * string table.
969 		 */
970 		if (symtab->sh_link >= pi->ehdr->e_shnum)
971 			/* Invalid section number? */
972 			continue;
973 
974 		/*
975 		 * Respective architecture needs to provide support for applying
976 		 * relocations of type SHT_RELA/SHT_REL.
977 		 */
978 		if (relsec->sh_type == SHT_RELA)
979 			ret = arch_kexec_apply_relocations_add(pi, section,
980 							       relsec, symtab);
981 		else if (relsec->sh_type == SHT_REL)
982 			ret = arch_kexec_apply_relocations(pi, section,
983 							   relsec, symtab);
984 		if (ret)
985 			return ret;
986 	}
987 
988 	return 0;
989 }
990 
991 /*
992  * kexec_load_purgatory - Load and relocate the purgatory object.
993  * @image:	Image to add the purgatory to.
994  * @kbuf:	Memory parameters to use.
995  *
996  * Allocates the memory needed for image->purgatory_info.sechdrs and
997  * image->purgatory_info.purgatory_buf/kbuf->buffer. Caller is responsible
998  * to free the memory after use.
999  *
1000  * Return: 0 on success, negative errno on error.
1001  */
1002 int kexec_load_purgatory(struct kimage *image, struct kexec_buf *kbuf)
1003 {
1004 	struct purgatory_info *pi = &image->purgatory_info;
1005 	int ret;
1006 
1007 	if (kexec_purgatory_size <= 0)
1008 		return -EINVAL;
1009 
1010 	pi->ehdr = (const Elf_Ehdr *)kexec_purgatory;
1011 
1012 	ret = kexec_purgatory_setup_kbuf(pi, kbuf);
1013 	if (ret)
1014 		return ret;
1015 
1016 	ret = kexec_purgatory_setup_sechdrs(pi, kbuf);
1017 	if (ret)
1018 		goto out_free_kbuf;
1019 
1020 	ret = kexec_apply_relocations(image);
1021 	if (ret)
1022 		goto out;
1023 
1024 	return 0;
1025 out:
1026 	vfree(pi->sechdrs);
1027 	pi->sechdrs = NULL;
1028 out_free_kbuf:
1029 	vfree(pi->purgatory_buf);
1030 	pi->purgatory_buf = NULL;
1031 	return ret;
1032 }
1033 
1034 /*
1035  * kexec_purgatory_find_symbol - find a symbol in the purgatory
1036  * @pi:		Purgatory to search in.
1037  * @name:	Name of the symbol.
1038  *
1039  * Return: pointer to symbol in read-only symtab on success, NULL on error.
1040  */
1041 static const Elf_Sym *kexec_purgatory_find_symbol(struct purgatory_info *pi,
1042 						  const char *name)
1043 {
1044 	const Elf_Shdr *sechdrs;
1045 	const Elf_Ehdr *ehdr;
1046 	const Elf_Sym *syms;
1047 	const char *strtab;
1048 	int i, k;
1049 
1050 	if (!pi->ehdr)
1051 		return NULL;
1052 
1053 	ehdr = pi->ehdr;
1054 	sechdrs = (void *)ehdr + ehdr->e_shoff;
1055 
1056 	for (i = 0; i < ehdr->e_shnum; i++) {
1057 		if (sechdrs[i].sh_type != SHT_SYMTAB)
1058 			continue;
1059 
1060 		if (sechdrs[i].sh_link >= ehdr->e_shnum)
1061 			/* Invalid strtab section number */
1062 			continue;
1063 		strtab = (void *)ehdr + sechdrs[sechdrs[i].sh_link].sh_offset;
1064 		syms = (void *)ehdr + sechdrs[i].sh_offset;
1065 
1066 		/* Go through symbols for a match */
1067 		for (k = 0; k < sechdrs[i].sh_size/sizeof(Elf_Sym); k++) {
1068 			if (ELF_ST_BIND(syms[k].st_info) != STB_GLOBAL)
1069 				continue;
1070 
1071 			if (strcmp(strtab + syms[k].st_name, name) != 0)
1072 				continue;
1073 
1074 			if (syms[k].st_shndx == SHN_UNDEF ||
1075 			    syms[k].st_shndx >= ehdr->e_shnum) {
1076 				pr_debug("Symbol: %s has bad section index %d.\n",
1077 						name, syms[k].st_shndx);
1078 				return NULL;
1079 			}
1080 
1081 			/* Found the symbol we are looking for */
1082 			return &syms[k];
1083 		}
1084 	}
1085 
1086 	return NULL;
1087 }
1088 
1089 void *kexec_purgatory_get_symbol_addr(struct kimage *image, const char *name)
1090 {
1091 	struct purgatory_info *pi = &image->purgatory_info;
1092 	const Elf_Sym *sym;
1093 	Elf_Shdr *sechdr;
1094 
1095 	sym = kexec_purgatory_find_symbol(pi, name);
1096 	if (!sym)
1097 		return ERR_PTR(-EINVAL);
1098 
1099 	sechdr = &pi->sechdrs[sym->st_shndx];
1100 
1101 	/*
1102 	 * Returns the address where symbol will finally be loaded after
1103 	 * kexec_load_segment()
1104 	 */
1105 	return (void *)(sechdr->sh_addr + sym->st_value);
1106 }
1107 
1108 /*
1109  * Get or set value of a symbol. If "get_value" is true, symbol value is
1110  * returned in buf otherwise symbol value is set based on value in buf.
1111  */
1112 int kexec_purgatory_get_set_symbol(struct kimage *image, const char *name,
1113 				   void *buf, unsigned int size, bool get_value)
1114 {
1115 	struct purgatory_info *pi = &image->purgatory_info;
1116 	const Elf_Sym *sym;
1117 	Elf_Shdr *sec;
1118 	char *sym_buf;
1119 
1120 	sym = kexec_purgatory_find_symbol(pi, name);
1121 	if (!sym)
1122 		return -EINVAL;
1123 
1124 	if (sym->st_size != size) {
1125 		pr_err("symbol %s size mismatch: expected %lu actual %u\n",
1126 		       name, (unsigned long)sym->st_size, size);
1127 		return -EINVAL;
1128 	}
1129 
1130 	sec = pi->sechdrs + sym->st_shndx;
1131 
1132 	if (sec->sh_type == SHT_NOBITS) {
1133 		pr_err("symbol %s is in a bss section. Cannot %s\n", name,
1134 		       get_value ? "get" : "set");
1135 		return -EINVAL;
1136 	}
1137 
1138 	sym_buf = (char *)pi->purgatory_buf + sec->sh_offset + sym->st_value;
1139 
1140 	if (get_value)
1141 		memcpy((void *)buf, sym_buf, size);
1142 	else
1143 		memcpy((void *)sym_buf, buf, size);
1144 
1145 	return 0;
1146 }
1147 #endif /* CONFIG_ARCH_SUPPORTS_KEXEC_PURGATORY */
1148