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