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