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