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