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