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