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