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