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