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