xref: /linux/kernel/kexec_file.c (revision 895931232d9358e0016f580f26b336c29c9528cc)
1 /*
2  * kexec: kexec_file_load system call
3  *
4  * Copyright (C) 2014 Red Hat Inc.
5  * Authors:
6  *      Vivek Goyal <vgoyal@redhat.com>
7  *
8  * This source code is licensed under the GNU General Public License,
9  * Version 2.  See the file COPYING for more details.
10  */
11 
12 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
13 
14 #include <linux/capability.h>
15 #include <linux/mm.h>
16 #include <linux/file.h>
17 #include <linux/slab.h>
18 #include <linux/kexec.h>
19 #include <linux/mutex.h>
20 #include <linux/list.h>
21 #include <linux/fs.h>
22 #include <linux/ima.h>
23 #include <crypto/hash.h>
24 #include <crypto/sha.h>
25 #include <linux/syscalls.h>
26 #include <linux/vmalloc.h>
27 #include "kexec_internal.h"
28 
29 /*
30  * Declare these symbols weak so that if architecture provides a purgatory,
31  * these will be overridden.
32  */
33 char __weak kexec_purgatory[0];
34 size_t __weak kexec_purgatory_size = 0;
35 
36 static int kexec_calculate_store_digests(struct kimage *image);
37 
38 /* Architectures can provide this probe function */
39 int __weak arch_kexec_kernel_image_probe(struct kimage *image, void *buf,
40 					 unsigned long buf_len)
41 {
42 	return -ENOEXEC;
43 }
44 
45 void * __weak arch_kexec_kernel_image_load(struct kimage *image)
46 {
47 	return ERR_PTR(-ENOEXEC);
48 }
49 
50 int __weak arch_kimage_file_post_load_cleanup(struct kimage *image)
51 {
52 	return -EINVAL;
53 }
54 
55 #ifdef CONFIG_KEXEC_VERIFY_SIG
56 int __weak arch_kexec_kernel_verify_sig(struct kimage *image, void *buf,
57 					unsigned long buf_len)
58 {
59 	return -EKEYREJECTED;
60 }
61 #endif
62 
63 /* Apply relocations of type RELA */
64 int __weak
65 arch_kexec_apply_relocations_add(const Elf_Ehdr *ehdr, Elf_Shdr *sechdrs,
66 				 unsigned int relsec)
67 {
68 	pr_err("RELA relocation unsupported.\n");
69 	return -ENOEXEC;
70 }
71 
72 /* Apply relocations of type REL */
73 int __weak
74 arch_kexec_apply_relocations(const Elf_Ehdr *ehdr, Elf_Shdr *sechdrs,
75 			     unsigned int relsec)
76 {
77 	pr_err("REL relocation unsupported.\n");
78 	return -ENOEXEC;
79 }
80 
81 /*
82  * Free up memory used by kernel, initrd, and command line. This is temporary
83  * memory allocation which is not needed any more after these buffers have
84  * been loaded into separate segments and have been copied elsewhere.
85  */
86 void kimage_file_post_load_cleanup(struct kimage *image)
87 {
88 	struct purgatory_info *pi = &image->purgatory_info;
89 
90 	vfree(image->kernel_buf);
91 	image->kernel_buf = NULL;
92 
93 	vfree(image->initrd_buf);
94 	image->initrd_buf = NULL;
95 
96 	kfree(image->cmdline_buf);
97 	image->cmdline_buf = NULL;
98 
99 	vfree(pi->purgatory_buf);
100 	pi->purgatory_buf = NULL;
101 
102 	vfree(pi->sechdrs);
103 	pi->sechdrs = NULL;
104 
105 	/* See if architecture has anything to cleanup post load */
106 	arch_kimage_file_post_load_cleanup(image);
107 
108 	/*
109 	 * Above call should have called into bootloader to free up
110 	 * any data stored in kimage->image_loader_data. It should
111 	 * be ok now to free it up.
112 	 */
113 	kfree(image->image_loader_data);
114 	image->image_loader_data = NULL;
115 }
116 
117 /*
118  * In file mode list of segments is prepared by kernel. Copy relevant
119  * data from user space, do error checking, prepare segment list
120  */
121 static int
122 kimage_file_prepare_segments(struct kimage *image, int kernel_fd, int initrd_fd,
123 			     const char __user *cmdline_ptr,
124 			     unsigned long cmdline_len, unsigned flags)
125 {
126 	int ret = 0;
127 	void *ldata;
128 	loff_t size;
129 
130 	ret = kernel_read_file_from_fd(kernel_fd, &image->kernel_buf,
131 				       &size, INT_MAX, READING_KEXEC_IMAGE);
132 	if (ret)
133 		return ret;
134 	image->kernel_buf_len = size;
135 
136 	/* IMA needs to pass the measurement list to the next kernel. */
137 	ima_add_kexec_buffer(image);
138 
139 	/* Call arch image probe handlers */
140 	ret = arch_kexec_kernel_image_probe(image, image->kernel_buf,
141 					    image->kernel_buf_len);
142 	if (ret)
143 		goto out;
144 
145 #ifdef CONFIG_KEXEC_VERIFY_SIG
146 	ret = arch_kexec_kernel_verify_sig(image, image->kernel_buf,
147 					   image->kernel_buf_len);
148 	if (ret) {
149 		pr_debug("kernel signature verification failed.\n");
150 		goto out;
151 	}
152 	pr_debug("kernel signature verification successful.\n");
153 #endif
154 	/* It is possible that there no initramfs is being loaded */
155 	if (!(flags & KEXEC_FILE_NO_INITRAMFS)) {
156 		ret = kernel_read_file_from_fd(initrd_fd, &image->initrd_buf,
157 					       &size, INT_MAX,
158 					       READING_KEXEC_INITRAMFS);
159 		if (ret)
160 			goto out;
161 		image->initrd_buf_len = size;
162 	}
163 
164 	if (cmdline_len) {
165 		image->cmdline_buf = memdup_user(cmdline_ptr, cmdline_len);
166 		if (IS_ERR(image->cmdline_buf)) {
167 			ret = PTR_ERR(image->cmdline_buf);
168 			image->cmdline_buf = NULL;
169 			goto out;
170 		}
171 
172 		image->cmdline_buf_len = cmdline_len;
173 
174 		/* command line should be a string with last byte null */
175 		if (image->cmdline_buf[cmdline_len - 1] != '\0') {
176 			ret = -EINVAL;
177 			goto out;
178 		}
179 	}
180 
181 	/* Call arch image load handlers */
182 	ldata = arch_kexec_kernel_image_load(image);
183 
184 	if (IS_ERR(ldata)) {
185 		ret = PTR_ERR(ldata);
186 		goto out;
187 	}
188 
189 	image->image_loader_data = ldata;
190 out:
191 	/* In case of error, free up all allocated memory in this function */
192 	if (ret)
193 		kimage_file_post_load_cleanup(image);
194 	return ret;
195 }
196 
197 static int
198 kimage_file_alloc_init(struct kimage **rimage, int kernel_fd,
199 		       int initrd_fd, const char __user *cmdline_ptr,
200 		       unsigned long cmdline_len, unsigned long flags)
201 {
202 	int ret;
203 	struct kimage *image;
204 	bool kexec_on_panic = flags & KEXEC_FILE_ON_CRASH;
205 
206 	image = do_kimage_alloc_init();
207 	if (!image)
208 		return -ENOMEM;
209 
210 	image->file_mode = 1;
211 
212 	if (kexec_on_panic) {
213 		/* Enable special crash kernel control page alloc policy. */
214 		image->control_page = crashk_res.start;
215 		image->type = KEXEC_TYPE_CRASH;
216 	}
217 
218 	ret = kimage_file_prepare_segments(image, kernel_fd, initrd_fd,
219 					   cmdline_ptr, cmdline_len, flags);
220 	if (ret)
221 		goto out_free_image;
222 
223 	ret = sanity_check_segment_list(image);
224 	if (ret)
225 		goto out_free_post_load_bufs;
226 
227 	ret = -ENOMEM;
228 	image->control_code_page = kimage_alloc_control_pages(image,
229 					   get_order(KEXEC_CONTROL_PAGE_SIZE));
230 	if (!image->control_code_page) {
231 		pr_err("Could not allocate control_code_buffer\n");
232 		goto out_free_post_load_bufs;
233 	}
234 
235 	if (!kexec_on_panic) {
236 		image->swap_page = kimage_alloc_control_pages(image, 0);
237 		if (!image->swap_page) {
238 			pr_err("Could not allocate swap buffer\n");
239 			goto out_free_control_pages;
240 		}
241 	}
242 
243 	*rimage = image;
244 	return 0;
245 out_free_control_pages:
246 	kimage_free_page_list(&image->control_pages);
247 out_free_post_load_bufs:
248 	kimage_file_post_load_cleanup(image);
249 out_free_image:
250 	kfree(image);
251 	return ret;
252 }
253 
254 SYSCALL_DEFINE5(kexec_file_load, int, kernel_fd, int, initrd_fd,
255 		unsigned long, cmdline_len, const char __user *, cmdline_ptr,
256 		unsigned long, flags)
257 {
258 	int ret = 0, i;
259 	struct kimage **dest_image, *image;
260 
261 	/* We only trust the superuser with rebooting the system. */
262 	if (!capable(CAP_SYS_BOOT) || kexec_load_disabled)
263 		return -EPERM;
264 
265 	/* Make sure we have a legal set of flags */
266 	if (flags != (flags & KEXEC_FILE_FLAGS))
267 		return -EINVAL;
268 
269 	image = NULL;
270 
271 	if (!mutex_trylock(&kexec_mutex))
272 		return -EBUSY;
273 
274 	dest_image = &kexec_image;
275 	if (flags & KEXEC_FILE_ON_CRASH) {
276 		dest_image = &kexec_crash_image;
277 		if (kexec_crash_image)
278 			arch_kexec_unprotect_crashkres();
279 	}
280 
281 	if (flags & KEXEC_FILE_UNLOAD)
282 		goto exchange;
283 
284 	/*
285 	 * In case of crash, new kernel gets loaded in reserved region. It is
286 	 * same memory where old crash kernel might be loaded. Free any
287 	 * current crash dump kernel before we corrupt it.
288 	 */
289 	if (flags & KEXEC_FILE_ON_CRASH)
290 		kimage_free(xchg(&kexec_crash_image, NULL));
291 
292 	ret = kimage_file_alloc_init(&image, kernel_fd, initrd_fd, cmdline_ptr,
293 				     cmdline_len, flags);
294 	if (ret)
295 		goto out;
296 
297 	ret = machine_kexec_prepare(image);
298 	if (ret)
299 		goto out;
300 
301 	ret = kexec_calculate_store_digests(image);
302 	if (ret)
303 		goto out;
304 
305 	for (i = 0; i < image->nr_segments; i++) {
306 		struct kexec_segment *ksegment;
307 
308 		ksegment = &image->segment[i];
309 		pr_debug("Loading segment %d: buf=0x%p bufsz=0x%zx mem=0x%lx memsz=0x%zx\n",
310 			 i, ksegment->buf, ksegment->bufsz, ksegment->mem,
311 			 ksegment->memsz);
312 
313 		ret = kimage_load_segment(image, &image->segment[i]);
314 		if (ret)
315 			goto out;
316 	}
317 
318 	kimage_terminate(image);
319 
320 	/*
321 	 * Free up any temporary buffers allocated which are not needed
322 	 * after image has been loaded
323 	 */
324 	kimage_file_post_load_cleanup(image);
325 exchange:
326 	image = xchg(dest_image, image);
327 out:
328 	if ((flags & KEXEC_FILE_ON_CRASH) && kexec_crash_image)
329 		arch_kexec_protect_crashkres();
330 
331 	mutex_unlock(&kexec_mutex);
332 	kimage_free(image);
333 	return ret;
334 }
335 
336 static int locate_mem_hole_top_down(unsigned long start, unsigned long end,
337 				    struct kexec_buf *kbuf)
338 {
339 	struct kimage *image = kbuf->image;
340 	unsigned long temp_start, temp_end;
341 
342 	temp_end = min(end, kbuf->buf_max);
343 	temp_start = temp_end - kbuf->memsz;
344 
345 	do {
346 		/* align down start */
347 		temp_start = temp_start & (~(kbuf->buf_align - 1));
348 
349 		if (temp_start < start || temp_start < kbuf->buf_min)
350 			return 0;
351 
352 		temp_end = temp_start + kbuf->memsz - 1;
353 
354 		/*
355 		 * Make sure this does not conflict with any of existing
356 		 * segments
357 		 */
358 		if (kimage_is_destination_range(image, temp_start, temp_end)) {
359 			temp_start = temp_start - PAGE_SIZE;
360 			continue;
361 		}
362 
363 		/* We found a suitable memory range */
364 		break;
365 	} while (1);
366 
367 	/* If we are here, we found a suitable memory range */
368 	kbuf->mem = temp_start;
369 
370 	/* Success, stop navigating through remaining System RAM ranges */
371 	return 1;
372 }
373 
374 static int locate_mem_hole_bottom_up(unsigned long start, unsigned long end,
375 				     struct kexec_buf *kbuf)
376 {
377 	struct kimage *image = kbuf->image;
378 	unsigned long temp_start, temp_end;
379 
380 	temp_start = max(start, kbuf->buf_min);
381 
382 	do {
383 		temp_start = ALIGN(temp_start, kbuf->buf_align);
384 		temp_end = temp_start + kbuf->memsz - 1;
385 
386 		if (temp_end > end || temp_end > kbuf->buf_max)
387 			return 0;
388 		/*
389 		 * Make sure this does not conflict with any of existing
390 		 * segments
391 		 */
392 		if (kimage_is_destination_range(image, temp_start, temp_end)) {
393 			temp_start = temp_start + PAGE_SIZE;
394 			continue;
395 		}
396 
397 		/* We found a suitable memory range */
398 		break;
399 	} while (1);
400 
401 	/* If we are here, we found a suitable memory range */
402 	kbuf->mem = temp_start;
403 
404 	/* Success, stop navigating through remaining System RAM ranges */
405 	return 1;
406 }
407 
408 static int locate_mem_hole_callback(u64 start, u64 end, void *arg)
409 {
410 	struct kexec_buf *kbuf = (struct kexec_buf *)arg;
411 	unsigned long sz = end - start + 1;
412 
413 	/* Returning 0 will take to next memory range */
414 	if (sz < kbuf->memsz)
415 		return 0;
416 
417 	if (end < kbuf->buf_min || start > kbuf->buf_max)
418 		return 0;
419 
420 	/*
421 	 * Allocate memory top down with-in ram range. Otherwise bottom up
422 	 * allocation.
423 	 */
424 	if (kbuf->top_down)
425 		return locate_mem_hole_top_down(start, end, kbuf);
426 	return locate_mem_hole_bottom_up(start, end, kbuf);
427 }
428 
429 /**
430  * arch_kexec_walk_mem - call func(data) on free memory regions
431  * @kbuf:	Context info for the search. Also passed to @func.
432  * @func:	Function to call for each memory region.
433  *
434  * Return: The memory walk will stop when func returns a non-zero value
435  * and that value will be returned. If all free regions are visited without
436  * func returning non-zero, then zero will be returned.
437  */
438 int __weak arch_kexec_walk_mem(struct kexec_buf *kbuf,
439 			       int (*func)(u64, u64, void *))
440 {
441 	if (kbuf->image->type == KEXEC_TYPE_CRASH)
442 		return walk_iomem_res_desc(crashk_res.desc,
443 					   IORESOURCE_SYSTEM_RAM | IORESOURCE_BUSY,
444 					   crashk_res.start, crashk_res.end,
445 					   kbuf, func);
446 	else
447 		return walk_system_ram_res(0, ULONG_MAX, kbuf, func);
448 }
449 
450 /**
451  * kexec_locate_mem_hole - find free memory for the purgatory or the next kernel
452  * @kbuf:	Parameters for the memory search.
453  *
454  * On success, kbuf->mem will have the start address of the memory region found.
455  *
456  * Return: 0 on success, negative errno on error.
457  */
458 int kexec_locate_mem_hole(struct kexec_buf *kbuf)
459 {
460 	int ret;
461 
462 	ret = arch_kexec_walk_mem(kbuf, locate_mem_hole_callback);
463 
464 	return ret == 1 ? 0 : -EADDRNOTAVAIL;
465 }
466 
467 /**
468  * kexec_add_buffer - place a buffer in a kexec segment
469  * @kbuf:	Buffer contents and memory parameters.
470  *
471  * This function assumes that kexec_mutex is held.
472  * On successful return, @kbuf->mem will have the physical address of
473  * the buffer in memory.
474  *
475  * Return: 0 on success, negative errno on error.
476  */
477 int kexec_add_buffer(struct kexec_buf *kbuf)
478 {
479 
480 	struct kexec_segment *ksegment;
481 	int ret;
482 
483 	/* Currently adding segment this way is allowed only in file mode */
484 	if (!kbuf->image->file_mode)
485 		return -EINVAL;
486 
487 	if (kbuf->image->nr_segments >= KEXEC_SEGMENT_MAX)
488 		return -EINVAL;
489 
490 	/*
491 	 * Make sure we are not trying to add buffer after allocating
492 	 * control pages. All segments need to be placed first before
493 	 * any control pages are allocated. As control page allocation
494 	 * logic goes through list of segments to make sure there are
495 	 * no destination overlaps.
496 	 */
497 	if (!list_empty(&kbuf->image->control_pages)) {
498 		WARN_ON(1);
499 		return -EINVAL;
500 	}
501 
502 	/* Ensure minimum alignment needed for segments. */
503 	kbuf->memsz = ALIGN(kbuf->memsz, PAGE_SIZE);
504 	kbuf->buf_align = max(kbuf->buf_align, PAGE_SIZE);
505 
506 	/* Walk the RAM ranges and allocate a suitable range for the buffer */
507 	ret = kexec_locate_mem_hole(kbuf);
508 	if (ret)
509 		return ret;
510 
511 	/* Found a suitable memory range */
512 	ksegment = &kbuf->image->segment[kbuf->image->nr_segments];
513 	ksegment->kbuf = kbuf->buffer;
514 	ksegment->bufsz = kbuf->bufsz;
515 	ksegment->mem = kbuf->mem;
516 	ksegment->memsz = kbuf->memsz;
517 	kbuf->image->nr_segments++;
518 	return 0;
519 }
520 
521 /* Calculate and store the digest of segments */
522 static int kexec_calculate_store_digests(struct kimage *image)
523 {
524 	struct crypto_shash *tfm;
525 	struct shash_desc *desc;
526 	int ret = 0, i, j, zero_buf_sz, sha_region_sz;
527 	size_t desc_size, nullsz;
528 	char *digest;
529 	void *zero_buf;
530 	struct kexec_sha_region *sha_regions;
531 	struct purgatory_info *pi = &image->purgatory_info;
532 
533 	zero_buf = __va(page_to_pfn(ZERO_PAGE(0)) << PAGE_SHIFT);
534 	zero_buf_sz = PAGE_SIZE;
535 
536 	tfm = crypto_alloc_shash("sha256", 0, 0);
537 	if (IS_ERR(tfm)) {
538 		ret = PTR_ERR(tfm);
539 		goto out;
540 	}
541 
542 	desc_size = crypto_shash_descsize(tfm) + sizeof(*desc);
543 	desc = kzalloc(desc_size, GFP_KERNEL);
544 	if (!desc) {
545 		ret = -ENOMEM;
546 		goto out_free_tfm;
547 	}
548 
549 	sha_region_sz = KEXEC_SEGMENT_MAX * sizeof(struct kexec_sha_region);
550 	sha_regions = vzalloc(sha_region_sz);
551 	if (!sha_regions)
552 		goto out_free_desc;
553 
554 	desc->tfm   = tfm;
555 	desc->flags = 0;
556 
557 	ret = crypto_shash_init(desc);
558 	if (ret < 0)
559 		goto out_free_sha_regions;
560 
561 	digest = kzalloc(SHA256_DIGEST_SIZE, GFP_KERNEL);
562 	if (!digest) {
563 		ret = -ENOMEM;
564 		goto out_free_sha_regions;
565 	}
566 
567 	for (j = i = 0; i < image->nr_segments; i++) {
568 		struct kexec_segment *ksegment;
569 
570 		ksegment = &image->segment[i];
571 		/*
572 		 * Skip purgatory as it will be modified once we put digest
573 		 * info in purgatory.
574 		 */
575 		if (ksegment->kbuf == pi->purgatory_buf)
576 			continue;
577 
578 		ret = crypto_shash_update(desc, ksegment->kbuf,
579 					  ksegment->bufsz);
580 		if (ret)
581 			break;
582 
583 		/*
584 		 * Assume rest of the buffer is filled with zero and
585 		 * update digest accordingly.
586 		 */
587 		nullsz = ksegment->memsz - ksegment->bufsz;
588 		while (nullsz) {
589 			unsigned long bytes = nullsz;
590 
591 			if (bytes > zero_buf_sz)
592 				bytes = zero_buf_sz;
593 			ret = crypto_shash_update(desc, zero_buf, bytes);
594 			if (ret)
595 				break;
596 			nullsz -= bytes;
597 		}
598 
599 		if (ret)
600 			break;
601 
602 		sha_regions[j].start = ksegment->mem;
603 		sha_regions[j].len = ksegment->memsz;
604 		j++;
605 	}
606 
607 	if (!ret) {
608 		ret = crypto_shash_final(desc, digest);
609 		if (ret)
610 			goto out_free_digest;
611 		ret = kexec_purgatory_get_set_symbol(image, "purgatory_sha_regions",
612 						     sha_regions, sha_region_sz, 0);
613 		if (ret)
614 			goto out_free_digest;
615 
616 		ret = kexec_purgatory_get_set_symbol(image, "purgatory_sha256_digest",
617 						     digest, SHA256_DIGEST_SIZE, 0);
618 		if (ret)
619 			goto out_free_digest;
620 	}
621 
622 out_free_digest:
623 	kfree(digest);
624 out_free_sha_regions:
625 	vfree(sha_regions);
626 out_free_desc:
627 	kfree(desc);
628 out_free_tfm:
629 	kfree(tfm);
630 out:
631 	return ret;
632 }
633 
634 /* Actually load purgatory. Lot of code taken from kexec-tools */
635 static int __kexec_load_purgatory(struct kimage *image, unsigned long min,
636 				  unsigned long max, int top_down)
637 {
638 	struct purgatory_info *pi = &image->purgatory_info;
639 	unsigned long align, bss_align, bss_sz, bss_pad;
640 	unsigned long entry, load_addr, curr_load_addr, bss_addr, offset;
641 	unsigned char *buf_addr, *src;
642 	int i, ret = 0, entry_sidx = -1;
643 	const Elf_Shdr *sechdrs_c;
644 	Elf_Shdr *sechdrs = NULL;
645 	struct kexec_buf kbuf = { .image = image, .bufsz = 0, .buf_align = 1,
646 				  .buf_min = min, .buf_max = max,
647 				  .top_down = top_down };
648 
649 	/*
650 	 * sechdrs_c points to section headers in purgatory and are read
651 	 * only. No modifications allowed.
652 	 */
653 	sechdrs_c = (void *)pi->ehdr + pi->ehdr->e_shoff;
654 
655 	/*
656 	 * We can not modify sechdrs_c[] and its fields. It is read only.
657 	 * Copy it over to a local copy where one can store some temporary
658 	 * data and free it at the end. We need to modify ->sh_addr and
659 	 * ->sh_offset fields to keep track of permanent and temporary
660 	 * locations of sections.
661 	 */
662 	sechdrs = vzalloc(pi->ehdr->e_shnum * sizeof(Elf_Shdr));
663 	if (!sechdrs)
664 		return -ENOMEM;
665 
666 	memcpy(sechdrs, sechdrs_c, pi->ehdr->e_shnum * sizeof(Elf_Shdr));
667 
668 	/*
669 	 * We seem to have multiple copies of sections. First copy is which
670 	 * is embedded in kernel in read only section. Some of these sections
671 	 * will be copied to a temporary buffer and relocated. And these
672 	 * sections will finally be copied to their final destination at
673 	 * segment load time.
674 	 *
675 	 * Use ->sh_offset to reflect section address in memory. It will
676 	 * point to original read only copy if section is not allocatable.
677 	 * Otherwise it will point to temporary copy which will be relocated.
678 	 *
679 	 * Use ->sh_addr to contain final address of the section where it
680 	 * will go during execution time.
681 	 */
682 	for (i = 0; i < pi->ehdr->e_shnum; i++) {
683 		if (sechdrs[i].sh_type == SHT_NOBITS)
684 			continue;
685 
686 		sechdrs[i].sh_offset = (unsigned long)pi->ehdr +
687 						sechdrs[i].sh_offset;
688 	}
689 
690 	/*
691 	 * Identify entry point section and make entry relative to section
692 	 * start.
693 	 */
694 	entry = pi->ehdr->e_entry;
695 	for (i = 0; i < pi->ehdr->e_shnum; i++) {
696 		if (!(sechdrs[i].sh_flags & SHF_ALLOC))
697 			continue;
698 
699 		if (!(sechdrs[i].sh_flags & SHF_EXECINSTR))
700 			continue;
701 
702 		/* Make entry section relative */
703 		if (sechdrs[i].sh_addr <= pi->ehdr->e_entry &&
704 		    ((sechdrs[i].sh_addr + sechdrs[i].sh_size) >
705 		     pi->ehdr->e_entry)) {
706 			entry_sidx = i;
707 			entry -= sechdrs[i].sh_addr;
708 			break;
709 		}
710 	}
711 
712 	/* Determine how much memory is needed to load relocatable object. */
713 	bss_align = 1;
714 	bss_sz = 0;
715 
716 	for (i = 0; i < pi->ehdr->e_shnum; i++) {
717 		if (!(sechdrs[i].sh_flags & SHF_ALLOC))
718 			continue;
719 
720 		align = sechdrs[i].sh_addralign;
721 		if (sechdrs[i].sh_type != SHT_NOBITS) {
722 			if (kbuf.buf_align < align)
723 				kbuf.buf_align = align;
724 			kbuf.bufsz = ALIGN(kbuf.bufsz, align);
725 			kbuf.bufsz += sechdrs[i].sh_size;
726 		} else {
727 			/* bss section */
728 			if (bss_align < align)
729 				bss_align = align;
730 			bss_sz = ALIGN(bss_sz, align);
731 			bss_sz += sechdrs[i].sh_size;
732 		}
733 	}
734 
735 	/* Determine the bss padding required to align bss properly */
736 	bss_pad = 0;
737 	if (kbuf.bufsz & (bss_align - 1))
738 		bss_pad = bss_align - (kbuf.bufsz & (bss_align - 1));
739 
740 	kbuf.memsz = kbuf.bufsz + bss_pad + bss_sz;
741 
742 	/* Allocate buffer for purgatory */
743 	kbuf.buffer = vzalloc(kbuf.bufsz);
744 	if (!kbuf.buffer) {
745 		ret = -ENOMEM;
746 		goto out;
747 	}
748 
749 	if (kbuf.buf_align < bss_align)
750 		kbuf.buf_align = bss_align;
751 
752 	/* Add buffer to segment list */
753 	ret = kexec_add_buffer(&kbuf);
754 	if (ret)
755 		goto out;
756 	pi->purgatory_load_addr = kbuf.mem;
757 
758 	/* Load SHF_ALLOC sections */
759 	buf_addr = kbuf.buffer;
760 	load_addr = curr_load_addr = pi->purgatory_load_addr;
761 	bss_addr = load_addr + kbuf.bufsz + bss_pad;
762 
763 	for (i = 0; i < pi->ehdr->e_shnum; i++) {
764 		if (!(sechdrs[i].sh_flags & SHF_ALLOC))
765 			continue;
766 
767 		align = sechdrs[i].sh_addralign;
768 		if (sechdrs[i].sh_type != SHT_NOBITS) {
769 			curr_load_addr = ALIGN(curr_load_addr, align);
770 			offset = curr_load_addr - load_addr;
771 			/* We already modifed ->sh_offset to keep src addr */
772 			src = (char *) sechdrs[i].sh_offset;
773 			memcpy(buf_addr + offset, src, sechdrs[i].sh_size);
774 
775 			/* Store load address and source address of section */
776 			sechdrs[i].sh_addr = curr_load_addr;
777 
778 			/*
779 			 * This section got copied to temporary buffer. Update
780 			 * ->sh_offset accordingly.
781 			 */
782 			sechdrs[i].sh_offset = (unsigned long)(buf_addr + offset);
783 
784 			/* Advance to the next address */
785 			curr_load_addr += sechdrs[i].sh_size;
786 		} else {
787 			bss_addr = ALIGN(bss_addr, align);
788 			sechdrs[i].sh_addr = bss_addr;
789 			bss_addr += sechdrs[i].sh_size;
790 		}
791 	}
792 
793 	/* Update entry point based on load address of text section */
794 	if (entry_sidx >= 0)
795 		entry += sechdrs[entry_sidx].sh_addr;
796 
797 	/* Make kernel jump to purgatory after shutdown */
798 	image->start = entry;
799 
800 	/* Used later to get/set symbol values */
801 	pi->sechdrs = sechdrs;
802 
803 	/*
804 	 * Used later to identify which section is purgatory and skip it
805 	 * from checksumming.
806 	 */
807 	pi->purgatory_buf = kbuf.buffer;
808 	return ret;
809 out:
810 	vfree(sechdrs);
811 	vfree(kbuf.buffer);
812 	return ret;
813 }
814 
815 static int kexec_apply_relocations(struct kimage *image)
816 {
817 	int i, ret;
818 	struct purgatory_info *pi = &image->purgatory_info;
819 	Elf_Shdr *sechdrs = pi->sechdrs;
820 
821 	/* Apply relocations */
822 	for (i = 0; i < pi->ehdr->e_shnum; i++) {
823 		Elf_Shdr *section, *symtab;
824 
825 		if (sechdrs[i].sh_type != SHT_RELA &&
826 		    sechdrs[i].sh_type != SHT_REL)
827 			continue;
828 
829 		/*
830 		 * For section of type SHT_RELA/SHT_REL,
831 		 * ->sh_link contains section header index of associated
832 		 * symbol table. And ->sh_info contains section header
833 		 * index of section to which relocations apply.
834 		 */
835 		if (sechdrs[i].sh_info >= pi->ehdr->e_shnum ||
836 		    sechdrs[i].sh_link >= pi->ehdr->e_shnum)
837 			return -ENOEXEC;
838 
839 		section = &sechdrs[sechdrs[i].sh_info];
840 		symtab = &sechdrs[sechdrs[i].sh_link];
841 
842 		if (!(section->sh_flags & SHF_ALLOC))
843 			continue;
844 
845 		/*
846 		 * symtab->sh_link contain section header index of associated
847 		 * string table.
848 		 */
849 		if (symtab->sh_link >= pi->ehdr->e_shnum)
850 			/* Invalid section number? */
851 			continue;
852 
853 		/*
854 		 * Respective architecture needs to provide support for applying
855 		 * relocations of type SHT_RELA/SHT_REL.
856 		 */
857 		if (sechdrs[i].sh_type == SHT_RELA)
858 			ret = arch_kexec_apply_relocations_add(pi->ehdr,
859 							       sechdrs, i);
860 		else if (sechdrs[i].sh_type == SHT_REL)
861 			ret = arch_kexec_apply_relocations(pi->ehdr,
862 							   sechdrs, i);
863 		if (ret)
864 			return ret;
865 	}
866 
867 	return 0;
868 }
869 
870 /* Load relocatable purgatory object and relocate it appropriately */
871 int kexec_load_purgatory(struct kimage *image, unsigned long min,
872 			 unsigned long max, int top_down,
873 			 unsigned long *load_addr)
874 {
875 	struct purgatory_info *pi = &image->purgatory_info;
876 	int ret;
877 
878 	if (kexec_purgatory_size <= 0)
879 		return -EINVAL;
880 
881 	if (kexec_purgatory_size < sizeof(Elf_Ehdr))
882 		return -ENOEXEC;
883 
884 	pi->ehdr = (Elf_Ehdr *)kexec_purgatory;
885 
886 	if (memcmp(pi->ehdr->e_ident, ELFMAG, SELFMAG) != 0
887 	    || pi->ehdr->e_type != ET_REL
888 	    || !elf_check_arch(pi->ehdr)
889 	    || pi->ehdr->e_shentsize != sizeof(Elf_Shdr))
890 		return -ENOEXEC;
891 
892 	if (pi->ehdr->e_shoff >= kexec_purgatory_size
893 	    || (pi->ehdr->e_shnum * sizeof(Elf_Shdr) >
894 	    kexec_purgatory_size - pi->ehdr->e_shoff))
895 		return -ENOEXEC;
896 
897 	ret = __kexec_load_purgatory(image, min, max, top_down);
898 	if (ret)
899 		return ret;
900 
901 	ret = kexec_apply_relocations(image);
902 	if (ret)
903 		goto out;
904 
905 	*load_addr = pi->purgatory_load_addr;
906 	return 0;
907 out:
908 	vfree(pi->sechdrs);
909 	pi->sechdrs = NULL;
910 
911 	vfree(pi->purgatory_buf);
912 	pi->purgatory_buf = NULL;
913 	return ret;
914 }
915 
916 static Elf_Sym *kexec_purgatory_find_symbol(struct purgatory_info *pi,
917 					    const char *name)
918 {
919 	Elf_Sym *syms;
920 	Elf_Shdr *sechdrs;
921 	Elf_Ehdr *ehdr;
922 	int i, k;
923 	const char *strtab;
924 
925 	if (!pi->sechdrs || !pi->ehdr)
926 		return NULL;
927 
928 	sechdrs = pi->sechdrs;
929 	ehdr = pi->ehdr;
930 
931 	for (i = 0; i < ehdr->e_shnum; i++) {
932 		if (sechdrs[i].sh_type != SHT_SYMTAB)
933 			continue;
934 
935 		if (sechdrs[i].sh_link >= ehdr->e_shnum)
936 			/* Invalid strtab section number */
937 			continue;
938 		strtab = (char *)sechdrs[sechdrs[i].sh_link].sh_offset;
939 		syms = (Elf_Sym *)sechdrs[i].sh_offset;
940 
941 		/* Go through symbols for a match */
942 		for (k = 0; k < sechdrs[i].sh_size/sizeof(Elf_Sym); k++) {
943 			if (ELF_ST_BIND(syms[k].st_info) != STB_GLOBAL)
944 				continue;
945 
946 			if (strcmp(strtab + syms[k].st_name, name) != 0)
947 				continue;
948 
949 			if (syms[k].st_shndx == SHN_UNDEF ||
950 			    syms[k].st_shndx >= ehdr->e_shnum) {
951 				pr_debug("Symbol: %s has bad section index %d.\n",
952 						name, syms[k].st_shndx);
953 				return NULL;
954 			}
955 
956 			/* Found the symbol we are looking for */
957 			return &syms[k];
958 		}
959 	}
960 
961 	return NULL;
962 }
963 
964 void *kexec_purgatory_get_symbol_addr(struct kimage *image, const char *name)
965 {
966 	struct purgatory_info *pi = &image->purgatory_info;
967 	Elf_Sym *sym;
968 	Elf_Shdr *sechdr;
969 
970 	sym = kexec_purgatory_find_symbol(pi, name);
971 	if (!sym)
972 		return ERR_PTR(-EINVAL);
973 
974 	sechdr = &pi->sechdrs[sym->st_shndx];
975 
976 	/*
977 	 * Returns the address where symbol will finally be loaded after
978 	 * kexec_load_segment()
979 	 */
980 	return (void *)(sechdr->sh_addr + sym->st_value);
981 }
982 
983 /*
984  * Get or set value of a symbol. If "get_value" is true, symbol value is
985  * returned in buf otherwise symbol value is set based on value in buf.
986  */
987 int kexec_purgatory_get_set_symbol(struct kimage *image, const char *name,
988 				   void *buf, unsigned int size, bool get_value)
989 {
990 	Elf_Sym *sym;
991 	Elf_Shdr *sechdrs;
992 	struct purgatory_info *pi = &image->purgatory_info;
993 	char *sym_buf;
994 
995 	sym = kexec_purgatory_find_symbol(pi, name);
996 	if (!sym)
997 		return -EINVAL;
998 
999 	if (sym->st_size != size) {
1000 		pr_err("symbol %s size mismatch: expected %lu actual %u\n",
1001 		       name, (unsigned long)sym->st_size, size);
1002 		return -EINVAL;
1003 	}
1004 
1005 	sechdrs = pi->sechdrs;
1006 
1007 	if (sechdrs[sym->st_shndx].sh_type == SHT_NOBITS) {
1008 		pr_err("symbol %s is in a bss section. Cannot %s\n", name,
1009 		       get_value ? "get" : "set");
1010 		return -EINVAL;
1011 	}
1012 
1013 	sym_buf = (unsigned char *)sechdrs[sym->st_shndx].sh_offset +
1014 					sym->st_value;
1015 
1016 	if (get_value)
1017 		memcpy((void *)buf, sym_buf, size);
1018 	else
1019 		memcpy((void *)sym_buf, buf, size);
1020 
1021 	return 0;
1022 }
1023