kexec: load and relocate purgatory at kernel load time
[firefly-linux-kernel-4.4.55.git] / kernel / kexec.c
1 /*
2  * kexec.c - kexec system call
3  * Copyright (C) 2002-2004 Eric Biederman  <ebiederm@xmission.com>
4  *
5  * This source code is licensed under the GNU General Public License,
6  * Version 2.  See the file COPYING for more details.
7  */
8
9 #define pr_fmt(fmt)     "kexec: " fmt
10
11 #include <linux/capability.h>
12 #include <linux/mm.h>
13 #include <linux/file.h>
14 #include <linux/slab.h>
15 #include <linux/fs.h>
16 #include <linux/kexec.h>
17 #include <linux/mutex.h>
18 #include <linux/list.h>
19 #include <linux/highmem.h>
20 #include <linux/syscalls.h>
21 #include <linux/reboot.h>
22 #include <linux/ioport.h>
23 #include <linux/hardirq.h>
24 #include <linux/elf.h>
25 #include <linux/elfcore.h>
26 #include <linux/utsname.h>
27 #include <linux/numa.h>
28 #include <linux/suspend.h>
29 #include <linux/device.h>
30 #include <linux/freezer.h>
31 #include <linux/pm.h>
32 #include <linux/cpu.h>
33 #include <linux/console.h>
34 #include <linux/vmalloc.h>
35 #include <linux/swap.h>
36 #include <linux/syscore_ops.h>
37 #include <linux/compiler.h>
38 #include <linux/hugetlb.h>
39
40 #include <asm/page.h>
41 #include <asm/uaccess.h>
42 #include <asm/io.h>
43 #include <asm/sections.h>
44
45 #include <crypto/hash.h>
46 #include <crypto/sha.h>
47
48 /* Per cpu memory for storing cpu states in case of system crash. */
49 note_buf_t __percpu *crash_notes;
50
51 /* vmcoreinfo stuff */
52 static unsigned char vmcoreinfo_data[VMCOREINFO_BYTES];
53 u32 vmcoreinfo_note[VMCOREINFO_NOTE_SIZE/4];
54 size_t vmcoreinfo_size;
55 size_t vmcoreinfo_max_size = sizeof(vmcoreinfo_data);
56
57 /* Flag to indicate we are going to kexec a new kernel */
58 bool kexec_in_progress = false;
59
60 /*
61  * Declare these symbols weak so that if architecture provides a purgatory,
62  * these will be overridden.
63  */
64 char __weak kexec_purgatory[0];
65 size_t __weak kexec_purgatory_size = 0;
66
67 static int kexec_calculate_store_digests(struct kimage *image);
68
69 /* Location of the reserved area for the crash kernel */
70 struct resource crashk_res = {
71         .name  = "Crash kernel",
72         .start = 0,
73         .end   = 0,
74         .flags = IORESOURCE_BUSY | IORESOURCE_MEM
75 };
76 struct resource crashk_low_res = {
77         .name  = "Crash kernel",
78         .start = 0,
79         .end   = 0,
80         .flags = IORESOURCE_BUSY | IORESOURCE_MEM
81 };
82
83 int kexec_should_crash(struct task_struct *p)
84 {
85         if (in_interrupt() || !p->pid || is_global_init(p) || panic_on_oops)
86                 return 1;
87         return 0;
88 }
89
90 /*
91  * When kexec transitions to the new kernel there is a one-to-one
92  * mapping between physical and virtual addresses.  On processors
93  * where you can disable the MMU this is trivial, and easy.  For
94  * others it is still a simple predictable page table to setup.
95  *
96  * In that environment kexec copies the new kernel to its final
97  * resting place.  This means I can only support memory whose
98  * physical address can fit in an unsigned long.  In particular
99  * addresses where (pfn << PAGE_SHIFT) > ULONG_MAX cannot be handled.
100  * If the assembly stub has more restrictive requirements
101  * KEXEC_SOURCE_MEMORY_LIMIT and KEXEC_DEST_MEMORY_LIMIT can be
102  * defined more restrictively in <asm/kexec.h>.
103  *
104  * The code for the transition from the current kernel to the
105  * the new kernel is placed in the control_code_buffer, whose size
106  * is given by KEXEC_CONTROL_PAGE_SIZE.  In the best case only a single
107  * page of memory is necessary, but some architectures require more.
108  * Because this memory must be identity mapped in the transition from
109  * virtual to physical addresses it must live in the range
110  * 0 - TASK_SIZE, as only the user space mappings are arbitrarily
111  * modifiable.
112  *
113  * The assembly stub in the control code buffer is passed a linked list
114  * of descriptor pages detailing the source pages of the new kernel,
115  * and the destination addresses of those source pages.  As this data
116  * structure is not used in the context of the current OS, it must
117  * be self-contained.
118  *
119  * The code has been made to work with highmem pages and will use a
120  * destination page in its final resting place (if it happens
121  * to allocate it).  The end product of this is that most of the
122  * physical address space, and most of RAM can be used.
123  *
124  * Future directions include:
125  *  - allocating a page table with the control code buffer identity
126  *    mapped, to simplify machine_kexec and make kexec_on_panic more
127  *    reliable.
128  */
129
130 /*
131  * KIMAGE_NO_DEST is an impossible destination address..., for
132  * allocating pages whose destination address we do not care about.
133  */
134 #define KIMAGE_NO_DEST (-1UL)
135
136 static int kimage_is_destination_range(struct kimage *image,
137                                        unsigned long start, unsigned long end);
138 static struct page *kimage_alloc_page(struct kimage *image,
139                                        gfp_t gfp_mask,
140                                        unsigned long dest);
141
142 static int copy_user_segment_list(struct kimage *image,
143                                   unsigned long nr_segments,
144                                   struct kexec_segment __user *segments)
145 {
146         int ret;
147         size_t segment_bytes;
148
149         /* Read in the segments */
150         image->nr_segments = nr_segments;
151         segment_bytes = nr_segments * sizeof(*segments);
152         ret = copy_from_user(image->segment, segments, segment_bytes);
153         if (ret)
154                 ret = -EFAULT;
155
156         return ret;
157 }
158
159 static int sanity_check_segment_list(struct kimage *image)
160 {
161         int result, i;
162         unsigned long nr_segments = image->nr_segments;
163
164         /*
165          * Verify we have good destination addresses.  The caller is
166          * responsible for making certain we don't attempt to load
167          * the new image into invalid or reserved areas of RAM.  This
168          * just verifies it is an address we can use.
169          *
170          * Since the kernel does everything in page size chunks ensure
171          * the destination addresses are page aligned.  Too many
172          * special cases crop of when we don't do this.  The most
173          * insidious is getting overlapping destination addresses
174          * simply because addresses are changed to page size
175          * granularity.
176          */
177         result = -EADDRNOTAVAIL;
178         for (i = 0; i < nr_segments; i++) {
179                 unsigned long mstart, mend;
180
181                 mstart = image->segment[i].mem;
182                 mend   = mstart + image->segment[i].memsz;
183                 if ((mstart & ~PAGE_MASK) || (mend & ~PAGE_MASK))
184                         return result;
185                 if (mend >= KEXEC_DESTINATION_MEMORY_LIMIT)
186                         return result;
187         }
188
189         /* Verify our destination addresses do not overlap.
190          * If we alloed overlapping destination addresses
191          * through very weird things can happen with no
192          * easy explanation as one segment stops on another.
193          */
194         result = -EINVAL;
195         for (i = 0; i < nr_segments; i++) {
196                 unsigned long mstart, mend;
197                 unsigned long j;
198
199                 mstart = image->segment[i].mem;
200                 mend   = mstart + image->segment[i].memsz;
201                 for (j = 0; j < i; j++) {
202                         unsigned long pstart, pend;
203                         pstart = image->segment[j].mem;
204                         pend   = pstart + image->segment[j].memsz;
205                         /* Do the segments overlap ? */
206                         if ((mend > pstart) && (mstart < pend))
207                                 return result;
208                 }
209         }
210
211         /* Ensure our buffer sizes are strictly less than
212          * our memory sizes.  This should always be the case,
213          * and it is easier to check up front than to be surprised
214          * later on.
215          */
216         result = -EINVAL;
217         for (i = 0; i < nr_segments; i++) {
218                 if (image->segment[i].bufsz > image->segment[i].memsz)
219                         return result;
220         }
221
222         /*
223          * Verify we have good destination addresses.  Normally
224          * the caller is responsible for making certain we don't
225          * attempt to load the new image into invalid or reserved
226          * areas of RAM.  But crash kernels are preloaded into a
227          * reserved area of ram.  We must ensure the addresses
228          * are in the reserved area otherwise preloading the
229          * kernel could corrupt things.
230          */
231
232         if (image->type == KEXEC_TYPE_CRASH) {
233                 result = -EADDRNOTAVAIL;
234                 for (i = 0; i < nr_segments; i++) {
235                         unsigned long mstart, mend;
236
237                         mstart = image->segment[i].mem;
238                         mend = mstart + image->segment[i].memsz - 1;
239                         /* Ensure we are within the crash kernel limits */
240                         if ((mstart < crashk_res.start) ||
241                             (mend > crashk_res.end))
242                                 return result;
243                 }
244         }
245
246         return 0;
247 }
248
249 static struct kimage *do_kimage_alloc_init(void)
250 {
251         struct kimage *image;
252
253         /* Allocate a controlling structure */
254         image = kzalloc(sizeof(*image), GFP_KERNEL);
255         if (!image)
256                 return NULL;
257
258         image->head = 0;
259         image->entry = &image->head;
260         image->last_entry = &image->head;
261         image->control_page = ~0; /* By default this does not apply */
262         image->type = KEXEC_TYPE_DEFAULT;
263
264         /* Initialize the list of control pages */
265         INIT_LIST_HEAD(&image->control_pages);
266
267         /* Initialize the list of destination pages */
268         INIT_LIST_HEAD(&image->dest_pages);
269
270         /* Initialize the list of unusable pages */
271         INIT_LIST_HEAD(&image->unusable_pages);
272
273         return image;
274 }
275
276 static void kimage_free_page_list(struct list_head *list);
277
278 static int kimage_alloc_init(struct kimage **rimage, unsigned long entry,
279                              unsigned long nr_segments,
280                              struct kexec_segment __user *segments,
281                              unsigned long flags)
282 {
283         int ret;
284         struct kimage *image;
285         bool kexec_on_panic = flags & KEXEC_ON_CRASH;
286
287         if (kexec_on_panic) {
288                 /* Verify we have a valid entry point */
289                 if ((entry < crashk_res.start) || (entry > crashk_res.end))
290                         return -EADDRNOTAVAIL;
291         }
292
293         /* Allocate and initialize a controlling structure */
294         image = do_kimage_alloc_init();
295         if (!image)
296                 return -ENOMEM;
297
298         image->start = entry;
299
300         ret = copy_user_segment_list(image, nr_segments, segments);
301         if (ret)
302                 goto out_free_image;
303
304         ret = sanity_check_segment_list(image);
305         if (ret)
306                 goto out_free_image;
307
308          /* Enable the special crash kernel control page allocation policy. */
309         if (kexec_on_panic) {
310                 image->control_page = crashk_res.start;
311                 image->type = KEXEC_TYPE_CRASH;
312         }
313
314         /*
315          * Find a location for the control code buffer, and add it
316          * the vector of segments so that it's pages will also be
317          * counted as destination pages.
318          */
319         ret = -ENOMEM;
320         image->control_code_page = kimage_alloc_control_pages(image,
321                                            get_order(KEXEC_CONTROL_PAGE_SIZE));
322         if (!image->control_code_page) {
323                 pr_err("Could not allocate control_code_buffer\n");
324                 goto out_free_image;
325         }
326
327         if (!kexec_on_panic) {
328                 image->swap_page = kimage_alloc_control_pages(image, 0);
329                 if (!image->swap_page) {
330                         pr_err("Could not allocate swap buffer\n");
331                         goto out_free_control_pages;
332                 }
333         }
334
335         *rimage = image;
336         return 0;
337 out_free_control_pages:
338         kimage_free_page_list(&image->control_pages);
339 out_free_image:
340         kfree(image);
341         return ret;
342 }
343
344 static int copy_file_from_fd(int fd, void **buf, unsigned long *buf_len)
345 {
346         struct fd f = fdget(fd);
347         int ret;
348         struct kstat stat;
349         loff_t pos;
350         ssize_t bytes = 0;
351
352         if (!f.file)
353                 return -EBADF;
354
355         ret = vfs_getattr(&f.file->f_path, &stat);
356         if (ret)
357                 goto out;
358
359         if (stat.size > INT_MAX) {
360                 ret = -EFBIG;
361                 goto out;
362         }
363
364         /* Don't hand 0 to vmalloc, it whines. */
365         if (stat.size == 0) {
366                 ret = -EINVAL;
367                 goto out;
368         }
369
370         *buf = vmalloc(stat.size);
371         if (!*buf) {
372                 ret = -ENOMEM;
373                 goto out;
374         }
375
376         pos = 0;
377         while (pos < stat.size) {
378                 bytes = kernel_read(f.file, pos, (char *)(*buf) + pos,
379                                     stat.size - pos);
380                 if (bytes < 0) {
381                         vfree(*buf);
382                         ret = bytes;
383                         goto out;
384                 }
385
386                 if (bytes == 0)
387                         break;
388                 pos += bytes;
389         }
390
391         if (pos != stat.size) {
392                 ret = -EBADF;
393                 vfree(*buf);
394                 goto out;
395         }
396
397         *buf_len = pos;
398 out:
399         fdput(f);
400         return ret;
401 }
402
403 /* Architectures can provide this probe function */
404 int __weak arch_kexec_kernel_image_probe(struct kimage *image, void *buf,
405                                          unsigned long buf_len)
406 {
407         return -ENOEXEC;
408 }
409
410 void * __weak arch_kexec_kernel_image_load(struct kimage *image)
411 {
412         return ERR_PTR(-ENOEXEC);
413 }
414
415 void __weak arch_kimage_file_post_load_cleanup(struct kimage *image)
416 {
417 }
418
419 /* Apply relocations of type RELA */
420 int __weak
421 arch_kexec_apply_relocations_add(const Elf_Ehdr *ehdr, Elf_Shdr *sechdrs,
422                                  unsigned int relsec)
423 {
424         pr_err("RELA relocation unsupported.\n");
425         return -ENOEXEC;
426 }
427
428 /* Apply relocations of type REL */
429 int __weak
430 arch_kexec_apply_relocations(const Elf_Ehdr *ehdr, Elf_Shdr *sechdrs,
431                              unsigned int relsec)
432 {
433         pr_err("REL relocation unsupported.\n");
434         return -ENOEXEC;
435 }
436
437 /*
438  * Free up memory used by kernel, initrd, and comand line. This is temporary
439  * memory allocation which is not needed any more after these buffers have
440  * been loaded into separate segments and have been copied elsewhere.
441  */
442 static void kimage_file_post_load_cleanup(struct kimage *image)
443 {
444         struct purgatory_info *pi = &image->purgatory_info;
445
446         vfree(image->kernel_buf);
447         image->kernel_buf = NULL;
448
449         vfree(image->initrd_buf);
450         image->initrd_buf = NULL;
451
452         kfree(image->cmdline_buf);
453         image->cmdline_buf = NULL;
454
455         vfree(pi->purgatory_buf);
456         pi->purgatory_buf = NULL;
457
458         vfree(pi->sechdrs);
459         pi->sechdrs = NULL;
460
461         /* See if architecture has anything to cleanup post load */
462         arch_kimage_file_post_load_cleanup(image);
463 }
464
465 /*
466  * In file mode list of segments is prepared by kernel. Copy relevant
467  * data from user space, do error checking, prepare segment list
468  */
469 static int
470 kimage_file_prepare_segments(struct kimage *image, int kernel_fd, int initrd_fd,
471                              const char __user *cmdline_ptr,
472                              unsigned long cmdline_len, unsigned flags)
473 {
474         int ret = 0;
475         void *ldata;
476
477         ret = copy_file_from_fd(kernel_fd, &image->kernel_buf,
478                                 &image->kernel_buf_len);
479         if (ret)
480                 return ret;
481
482         /* Call arch image probe handlers */
483         ret = arch_kexec_kernel_image_probe(image, image->kernel_buf,
484                                             image->kernel_buf_len);
485
486         if (ret)
487                 goto out;
488
489         /* It is possible that there no initramfs is being loaded */
490         if (!(flags & KEXEC_FILE_NO_INITRAMFS)) {
491                 ret = copy_file_from_fd(initrd_fd, &image->initrd_buf,
492                                         &image->initrd_buf_len);
493                 if (ret)
494                         goto out;
495         }
496
497         if (cmdline_len) {
498                 image->cmdline_buf = kzalloc(cmdline_len, GFP_KERNEL);
499                 if (!image->cmdline_buf) {
500                         ret = -ENOMEM;
501                         goto out;
502                 }
503
504                 ret = copy_from_user(image->cmdline_buf, cmdline_ptr,
505                                      cmdline_len);
506                 if (ret) {
507                         ret = -EFAULT;
508                         goto out;
509                 }
510
511                 image->cmdline_buf_len = cmdline_len;
512
513                 /* command line should be a string with last byte null */
514                 if (image->cmdline_buf[cmdline_len - 1] != '\0') {
515                         ret = -EINVAL;
516                         goto out;
517                 }
518         }
519
520         /* Call arch image load handlers */
521         ldata = arch_kexec_kernel_image_load(image);
522
523         if (IS_ERR(ldata)) {
524                 ret = PTR_ERR(ldata);
525                 goto out;
526         }
527
528         image->image_loader_data = ldata;
529 out:
530         /* In case of error, free up all allocated memory in this function */
531         if (ret)
532                 kimage_file_post_load_cleanup(image);
533         return ret;
534 }
535
536 static int
537 kimage_file_alloc_init(struct kimage **rimage, int kernel_fd,
538                        int initrd_fd, const char __user *cmdline_ptr,
539                        unsigned long cmdline_len, unsigned long flags)
540 {
541         int ret;
542         struct kimage *image;
543
544         image = do_kimage_alloc_init();
545         if (!image)
546                 return -ENOMEM;
547
548         image->file_mode = 1;
549
550         ret = kimage_file_prepare_segments(image, kernel_fd, initrd_fd,
551                                            cmdline_ptr, cmdline_len, flags);
552         if (ret)
553                 goto out_free_image;
554
555         ret = sanity_check_segment_list(image);
556         if (ret)
557                 goto out_free_post_load_bufs;
558
559         ret = -ENOMEM;
560         image->control_code_page = kimage_alloc_control_pages(image,
561                                            get_order(KEXEC_CONTROL_PAGE_SIZE));
562         if (!image->control_code_page) {
563                 pr_err("Could not allocate control_code_buffer\n");
564                 goto out_free_post_load_bufs;
565         }
566
567         image->swap_page = kimage_alloc_control_pages(image, 0);
568         if (!image->swap_page) {
569                 pr_err(KERN_ERR "Could not allocate swap buffer\n");
570                 goto out_free_control_pages;
571         }
572
573         *rimage = image;
574         return 0;
575 out_free_control_pages:
576         kimage_free_page_list(&image->control_pages);
577 out_free_post_load_bufs:
578         kimage_file_post_load_cleanup(image);
579         kfree(image->image_loader_data);
580 out_free_image:
581         kfree(image);
582         return ret;
583 }
584
585 static int kimage_is_destination_range(struct kimage *image,
586                                         unsigned long start,
587                                         unsigned long end)
588 {
589         unsigned long i;
590
591         for (i = 0; i < image->nr_segments; i++) {
592                 unsigned long mstart, mend;
593
594                 mstart = image->segment[i].mem;
595                 mend = mstart + image->segment[i].memsz;
596                 if ((end > mstart) && (start < mend))
597                         return 1;
598         }
599
600         return 0;
601 }
602
603 static struct page *kimage_alloc_pages(gfp_t gfp_mask, unsigned int order)
604 {
605         struct page *pages;
606
607         pages = alloc_pages(gfp_mask, order);
608         if (pages) {
609                 unsigned int count, i;
610                 pages->mapping = NULL;
611                 set_page_private(pages, order);
612                 count = 1 << order;
613                 for (i = 0; i < count; i++)
614                         SetPageReserved(pages + i);
615         }
616
617         return pages;
618 }
619
620 static void kimage_free_pages(struct page *page)
621 {
622         unsigned int order, count, i;
623
624         order = page_private(page);
625         count = 1 << order;
626         for (i = 0; i < count; i++)
627                 ClearPageReserved(page + i);
628         __free_pages(page, order);
629 }
630
631 static void kimage_free_page_list(struct list_head *list)
632 {
633         struct list_head *pos, *next;
634
635         list_for_each_safe(pos, next, list) {
636                 struct page *page;
637
638                 page = list_entry(pos, struct page, lru);
639                 list_del(&page->lru);
640                 kimage_free_pages(page);
641         }
642 }
643
644 static struct page *kimage_alloc_normal_control_pages(struct kimage *image,
645                                                         unsigned int order)
646 {
647         /* Control pages are special, they are the intermediaries
648          * that are needed while we copy the rest of the pages
649          * to their final resting place.  As such they must
650          * not conflict with either the destination addresses
651          * or memory the kernel is already using.
652          *
653          * The only case where we really need more than one of
654          * these are for architectures where we cannot disable
655          * the MMU and must instead generate an identity mapped
656          * page table for all of the memory.
657          *
658          * At worst this runs in O(N) of the image size.
659          */
660         struct list_head extra_pages;
661         struct page *pages;
662         unsigned int count;
663
664         count = 1 << order;
665         INIT_LIST_HEAD(&extra_pages);
666
667         /* Loop while I can allocate a page and the page allocated
668          * is a destination page.
669          */
670         do {
671                 unsigned long pfn, epfn, addr, eaddr;
672
673                 pages = kimage_alloc_pages(GFP_KERNEL, order);
674                 if (!pages)
675                         break;
676                 pfn   = page_to_pfn(pages);
677                 epfn  = pfn + count;
678                 addr  = pfn << PAGE_SHIFT;
679                 eaddr = epfn << PAGE_SHIFT;
680                 if ((epfn >= (KEXEC_CONTROL_MEMORY_LIMIT >> PAGE_SHIFT)) ||
681                               kimage_is_destination_range(image, addr, eaddr)) {
682                         list_add(&pages->lru, &extra_pages);
683                         pages = NULL;
684                 }
685         } while (!pages);
686
687         if (pages) {
688                 /* Remember the allocated page... */
689                 list_add(&pages->lru, &image->control_pages);
690
691                 /* Because the page is already in it's destination
692                  * location we will never allocate another page at
693                  * that address.  Therefore kimage_alloc_pages
694                  * will not return it (again) and we don't need
695                  * to give it an entry in image->segment[].
696                  */
697         }
698         /* Deal with the destination pages I have inadvertently allocated.
699          *
700          * Ideally I would convert multi-page allocations into single
701          * page allocations, and add everything to image->dest_pages.
702          *
703          * For now it is simpler to just free the pages.
704          */
705         kimage_free_page_list(&extra_pages);
706
707         return pages;
708 }
709
710 static struct page *kimage_alloc_crash_control_pages(struct kimage *image,
711                                                       unsigned int order)
712 {
713         /* Control pages are special, they are the intermediaries
714          * that are needed while we copy the rest of the pages
715          * to their final resting place.  As such they must
716          * not conflict with either the destination addresses
717          * or memory the kernel is already using.
718          *
719          * Control pages are also the only pags we must allocate
720          * when loading a crash kernel.  All of the other pages
721          * are specified by the segments and we just memcpy
722          * into them directly.
723          *
724          * The only case where we really need more than one of
725          * these are for architectures where we cannot disable
726          * the MMU and must instead generate an identity mapped
727          * page table for all of the memory.
728          *
729          * Given the low demand this implements a very simple
730          * allocator that finds the first hole of the appropriate
731          * size in the reserved memory region, and allocates all
732          * of the memory up to and including the hole.
733          */
734         unsigned long hole_start, hole_end, size;
735         struct page *pages;
736
737         pages = NULL;
738         size = (1 << order) << PAGE_SHIFT;
739         hole_start = (image->control_page + (size - 1)) & ~(size - 1);
740         hole_end   = hole_start + size - 1;
741         while (hole_end <= crashk_res.end) {
742                 unsigned long i;
743
744                 if (hole_end > KEXEC_CRASH_CONTROL_MEMORY_LIMIT)
745                         break;
746                 /* See if I overlap any of the segments */
747                 for (i = 0; i < image->nr_segments; i++) {
748                         unsigned long mstart, mend;
749
750                         mstart = image->segment[i].mem;
751                         mend   = mstart + image->segment[i].memsz - 1;
752                         if ((hole_end >= mstart) && (hole_start <= mend)) {
753                                 /* Advance the hole to the end of the segment */
754                                 hole_start = (mend + (size - 1)) & ~(size - 1);
755                                 hole_end   = hole_start + size - 1;
756                                 break;
757                         }
758                 }
759                 /* If I don't overlap any segments I have found my hole! */
760                 if (i == image->nr_segments) {
761                         pages = pfn_to_page(hole_start >> PAGE_SHIFT);
762                         break;
763                 }
764         }
765         if (pages)
766                 image->control_page = hole_end;
767
768         return pages;
769 }
770
771
772 struct page *kimage_alloc_control_pages(struct kimage *image,
773                                          unsigned int order)
774 {
775         struct page *pages = NULL;
776
777         switch (image->type) {
778         case KEXEC_TYPE_DEFAULT:
779                 pages = kimage_alloc_normal_control_pages(image, order);
780                 break;
781         case KEXEC_TYPE_CRASH:
782                 pages = kimage_alloc_crash_control_pages(image, order);
783                 break;
784         }
785
786         return pages;
787 }
788
789 static int kimage_add_entry(struct kimage *image, kimage_entry_t entry)
790 {
791         if (*image->entry != 0)
792                 image->entry++;
793
794         if (image->entry == image->last_entry) {
795                 kimage_entry_t *ind_page;
796                 struct page *page;
797
798                 page = kimage_alloc_page(image, GFP_KERNEL, KIMAGE_NO_DEST);
799                 if (!page)
800                         return -ENOMEM;
801
802                 ind_page = page_address(page);
803                 *image->entry = virt_to_phys(ind_page) | IND_INDIRECTION;
804                 image->entry = ind_page;
805                 image->last_entry = ind_page +
806                                       ((PAGE_SIZE/sizeof(kimage_entry_t)) - 1);
807         }
808         *image->entry = entry;
809         image->entry++;
810         *image->entry = 0;
811
812         return 0;
813 }
814
815 static int kimage_set_destination(struct kimage *image,
816                                    unsigned long destination)
817 {
818         int result;
819
820         destination &= PAGE_MASK;
821         result = kimage_add_entry(image, destination | IND_DESTINATION);
822         if (result == 0)
823                 image->destination = destination;
824
825         return result;
826 }
827
828
829 static int kimage_add_page(struct kimage *image, unsigned long page)
830 {
831         int result;
832
833         page &= PAGE_MASK;
834         result = kimage_add_entry(image, page | IND_SOURCE);
835         if (result == 0)
836                 image->destination += PAGE_SIZE;
837
838         return result;
839 }
840
841
842 static void kimage_free_extra_pages(struct kimage *image)
843 {
844         /* Walk through and free any extra destination pages I may have */
845         kimage_free_page_list(&image->dest_pages);
846
847         /* Walk through and free any unusable pages I have cached */
848         kimage_free_page_list(&image->unusable_pages);
849
850 }
851 static void kimage_terminate(struct kimage *image)
852 {
853         if (*image->entry != 0)
854                 image->entry++;
855
856         *image->entry = IND_DONE;
857 }
858
859 #define for_each_kimage_entry(image, ptr, entry) \
860         for (ptr = &image->head; (entry = *ptr) && !(entry & IND_DONE); \
861                 ptr = (entry & IND_INDIRECTION) ? \
862                         phys_to_virt((entry & PAGE_MASK)) : ptr + 1)
863
864 static void kimage_free_entry(kimage_entry_t entry)
865 {
866         struct page *page;
867
868         page = pfn_to_page(entry >> PAGE_SHIFT);
869         kimage_free_pages(page);
870 }
871
872 static void kimage_free(struct kimage *image)
873 {
874         kimage_entry_t *ptr, entry;
875         kimage_entry_t ind = 0;
876
877         if (!image)
878                 return;
879
880         kimage_free_extra_pages(image);
881         for_each_kimage_entry(image, ptr, entry) {
882                 if (entry & IND_INDIRECTION) {
883                         /* Free the previous indirection page */
884                         if (ind & IND_INDIRECTION)
885                                 kimage_free_entry(ind);
886                         /* Save this indirection page until we are
887                          * done with it.
888                          */
889                         ind = entry;
890                 } else if (entry & IND_SOURCE)
891                         kimage_free_entry(entry);
892         }
893         /* Free the final indirection page */
894         if (ind & IND_INDIRECTION)
895                 kimage_free_entry(ind);
896
897         /* Handle any machine specific cleanup */
898         machine_kexec_cleanup(image);
899
900         /* Free the kexec control pages... */
901         kimage_free_page_list(&image->control_pages);
902
903         kfree(image->image_loader_data);
904
905         /*
906          * Free up any temporary buffers allocated. This might hit if
907          * error occurred much later after buffer allocation.
908          */
909         if (image->file_mode)
910                 kimage_file_post_load_cleanup(image);
911
912         kfree(image);
913 }
914
915 static kimage_entry_t *kimage_dst_used(struct kimage *image,
916                                         unsigned long page)
917 {
918         kimage_entry_t *ptr, entry;
919         unsigned long destination = 0;
920
921         for_each_kimage_entry(image, ptr, entry) {
922                 if (entry & IND_DESTINATION)
923                         destination = entry & PAGE_MASK;
924                 else if (entry & IND_SOURCE) {
925                         if (page == destination)
926                                 return ptr;
927                         destination += PAGE_SIZE;
928                 }
929         }
930
931         return NULL;
932 }
933
934 static struct page *kimage_alloc_page(struct kimage *image,
935                                         gfp_t gfp_mask,
936                                         unsigned long destination)
937 {
938         /*
939          * Here we implement safeguards to ensure that a source page
940          * is not copied to its destination page before the data on
941          * the destination page is no longer useful.
942          *
943          * To do this we maintain the invariant that a source page is
944          * either its own destination page, or it is not a
945          * destination page at all.
946          *
947          * That is slightly stronger than required, but the proof
948          * that no problems will not occur is trivial, and the
949          * implementation is simply to verify.
950          *
951          * When allocating all pages normally this algorithm will run
952          * in O(N) time, but in the worst case it will run in O(N^2)
953          * time.   If the runtime is a problem the data structures can
954          * be fixed.
955          */
956         struct page *page;
957         unsigned long addr;
958
959         /*
960          * Walk through the list of destination pages, and see if I
961          * have a match.
962          */
963         list_for_each_entry(page, &image->dest_pages, lru) {
964                 addr = page_to_pfn(page) << PAGE_SHIFT;
965                 if (addr == destination) {
966                         list_del(&page->lru);
967                         return page;
968                 }
969         }
970         page = NULL;
971         while (1) {
972                 kimage_entry_t *old;
973
974                 /* Allocate a page, if we run out of memory give up */
975                 page = kimage_alloc_pages(gfp_mask, 0);
976                 if (!page)
977                         return NULL;
978                 /* If the page cannot be used file it away */
979                 if (page_to_pfn(page) >
980                                 (KEXEC_SOURCE_MEMORY_LIMIT >> PAGE_SHIFT)) {
981                         list_add(&page->lru, &image->unusable_pages);
982                         continue;
983                 }
984                 addr = page_to_pfn(page) << PAGE_SHIFT;
985
986                 /* If it is the destination page we want use it */
987                 if (addr == destination)
988                         break;
989
990                 /* If the page is not a destination page use it */
991                 if (!kimage_is_destination_range(image, addr,
992                                                   addr + PAGE_SIZE))
993                         break;
994
995                 /*
996                  * I know that the page is someones destination page.
997                  * See if there is already a source page for this
998                  * destination page.  And if so swap the source pages.
999                  */
1000                 old = kimage_dst_used(image, addr);
1001                 if (old) {
1002                         /* If so move it */
1003                         unsigned long old_addr;
1004                         struct page *old_page;
1005
1006                         old_addr = *old & PAGE_MASK;
1007                         old_page = pfn_to_page(old_addr >> PAGE_SHIFT);
1008                         copy_highpage(page, old_page);
1009                         *old = addr | (*old & ~PAGE_MASK);
1010
1011                         /* The old page I have found cannot be a
1012                          * destination page, so return it if it's
1013                          * gfp_flags honor the ones passed in.
1014                          */
1015                         if (!(gfp_mask & __GFP_HIGHMEM) &&
1016                             PageHighMem(old_page)) {
1017                                 kimage_free_pages(old_page);
1018                                 continue;
1019                         }
1020                         addr = old_addr;
1021                         page = old_page;
1022                         break;
1023                 } else {
1024                         /* Place the page on the destination list I
1025                          * will use it later.
1026                          */
1027                         list_add(&page->lru, &image->dest_pages);
1028                 }
1029         }
1030
1031         return page;
1032 }
1033
1034 static int kimage_load_normal_segment(struct kimage *image,
1035                                          struct kexec_segment *segment)
1036 {
1037         unsigned long maddr;
1038         size_t ubytes, mbytes;
1039         int result;
1040         unsigned char __user *buf = NULL;
1041         unsigned char *kbuf = NULL;
1042
1043         result = 0;
1044         if (image->file_mode)
1045                 kbuf = segment->kbuf;
1046         else
1047                 buf = segment->buf;
1048         ubytes = segment->bufsz;
1049         mbytes = segment->memsz;
1050         maddr = segment->mem;
1051
1052         result = kimage_set_destination(image, maddr);
1053         if (result < 0)
1054                 goto out;
1055
1056         while (mbytes) {
1057                 struct page *page;
1058                 char *ptr;
1059                 size_t uchunk, mchunk;
1060
1061                 page = kimage_alloc_page(image, GFP_HIGHUSER, maddr);
1062                 if (!page) {
1063                         result  = -ENOMEM;
1064                         goto out;
1065                 }
1066                 result = kimage_add_page(image, page_to_pfn(page)
1067                                                                 << PAGE_SHIFT);
1068                 if (result < 0)
1069                         goto out;
1070
1071                 ptr = kmap(page);
1072                 /* Start with a clear page */
1073                 clear_page(ptr);
1074                 ptr += maddr & ~PAGE_MASK;
1075                 mchunk = min_t(size_t, mbytes,
1076                                 PAGE_SIZE - (maddr & ~PAGE_MASK));
1077                 uchunk = min(ubytes, mchunk);
1078
1079                 /* For file based kexec, source pages are in kernel memory */
1080                 if (image->file_mode)
1081                         memcpy(ptr, kbuf, uchunk);
1082                 else
1083                         result = copy_from_user(ptr, buf, uchunk);
1084                 kunmap(page);
1085                 if (result) {
1086                         result = -EFAULT;
1087                         goto out;
1088                 }
1089                 ubytes -= uchunk;
1090                 maddr  += mchunk;
1091                 if (image->file_mode)
1092                         kbuf += mchunk;
1093                 else
1094                         buf += mchunk;
1095                 mbytes -= mchunk;
1096         }
1097 out:
1098         return result;
1099 }
1100
1101 static int kimage_load_crash_segment(struct kimage *image,
1102                                         struct kexec_segment *segment)
1103 {
1104         /* For crash dumps kernels we simply copy the data from
1105          * user space to it's destination.
1106          * We do things a page at a time for the sake of kmap.
1107          */
1108         unsigned long maddr;
1109         size_t ubytes, mbytes;
1110         int result;
1111         unsigned char __user *buf;
1112
1113         result = 0;
1114         buf = segment->buf;
1115         ubytes = segment->bufsz;
1116         mbytes = segment->memsz;
1117         maddr = segment->mem;
1118         while (mbytes) {
1119                 struct page *page;
1120                 char *ptr;
1121                 size_t uchunk, mchunk;
1122
1123                 page = pfn_to_page(maddr >> PAGE_SHIFT);
1124                 if (!page) {
1125                         result  = -ENOMEM;
1126                         goto out;
1127                 }
1128                 ptr = kmap(page);
1129                 ptr += maddr & ~PAGE_MASK;
1130                 mchunk = min_t(size_t, mbytes,
1131                                 PAGE_SIZE - (maddr & ~PAGE_MASK));
1132                 uchunk = min(ubytes, mchunk);
1133                 if (mchunk > uchunk) {
1134                         /* Zero the trailing part of the page */
1135                         memset(ptr + uchunk, 0, mchunk - uchunk);
1136                 }
1137                 result = copy_from_user(ptr, buf, uchunk);
1138                 kexec_flush_icache_page(page);
1139                 kunmap(page);
1140                 if (result) {
1141                         result = -EFAULT;
1142                         goto out;
1143                 }
1144                 ubytes -= uchunk;
1145                 maddr  += mchunk;
1146                 buf += mchunk;
1147                 mbytes -= mchunk;
1148         }
1149 out:
1150         return result;
1151 }
1152
1153 static int kimage_load_segment(struct kimage *image,
1154                                 struct kexec_segment *segment)
1155 {
1156         int result = -ENOMEM;
1157
1158         switch (image->type) {
1159         case KEXEC_TYPE_DEFAULT:
1160                 result = kimage_load_normal_segment(image, segment);
1161                 break;
1162         case KEXEC_TYPE_CRASH:
1163                 result = kimage_load_crash_segment(image, segment);
1164                 break;
1165         }
1166
1167         return result;
1168 }
1169
1170 /*
1171  * Exec Kernel system call: for obvious reasons only root may call it.
1172  *
1173  * This call breaks up into three pieces.
1174  * - A generic part which loads the new kernel from the current
1175  *   address space, and very carefully places the data in the
1176  *   allocated pages.
1177  *
1178  * - A generic part that interacts with the kernel and tells all of
1179  *   the devices to shut down.  Preventing on-going dmas, and placing
1180  *   the devices in a consistent state so a later kernel can
1181  *   reinitialize them.
1182  *
1183  * - A machine specific part that includes the syscall number
1184  *   and then copies the image to it's final destination.  And
1185  *   jumps into the image at entry.
1186  *
1187  * kexec does not sync, or unmount filesystems so if you need
1188  * that to happen you need to do that yourself.
1189  */
1190 struct kimage *kexec_image;
1191 struct kimage *kexec_crash_image;
1192 int kexec_load_disabled;
1193
1194 static DEFINE_MUTEX(kexec_mutex);
1195
1196 SYSCALL_DEFINE4(kexec_load, unsigned long, entry, unsigned long, nr_segments,
1197                 struct kexec_segment __user *, segments, unsigned long, flags)
1198 {
1199         struct kimage **dest_image, *image;
1200         int result;
1201
1202         /* We only trust the superuser with rebooting the system. */
1203         if (!capable(CAP_SYS_BOOT) || kexec_load_disabled)
1204                 return -EPERM;
1205
1206         /*
1207          * Verify we have a legal set of flags
1208          * This leaves us room for future extensions.
1209          */
1210         if ((flags & KEXEC_FLAGS) != (flags & ~KEXEC_ARCH_MASK))
1211                 return -EINVAL;
1212
1213         /* Verify we are on the appropriate architecture */
1214         if (((flags & KEXEC_ARCH_MASK) != KEXEC_ARCH) &&
1215                 ((flags & KEXEC_ARCH_MASK) != KEXEC_ARCH_DEFAULT))
1216                 return -EINVAL;
1217
1218         /* Put an artificial cap on the number
1219          * of segments passed to kexec_load.
1220          */
1221         if (nr_segments > KEXEC_SEGMENT_MAX)
1222                 return -EINVAL;
1223
1224         image = NULL;
1225         result = 0;
1226
1227         /* Because we write directly to the reserved memory
1228          * region when loading crash kernels we need a mutex here to
1229          * prevent multiple crash  kernels from attempting to load
1230          * simultaneously, and to prevent a crash kernel from loading
1231          * over the top of a in use crash kernel.
1232          *
1233          * KISS: always take the mutex.
1234          */
1235         if (!mutex_trylock(&kexec_mutex))
1236                 return -EBUSY;
1237
1238         dest_image = &kexec_image;
1239         if (flags & KEXEC_ON_CRASH)
1240                 dest_image = &kexec_crash_image;
1241         if (nr_segments > 0) {
1242                 unsigned long i;
1243
1244                 /* Loading another kernel to reboot into */
1245                 if ((flags & KEXEC_ON_CRASH) == 0)
1246                         result = kimage_alloc_init(&image, entry, nr_segments,
1247                                                    segments, flags);
1248                 /* Loading another kernel to switch to if this one crashes */
1249                 else if (flags & KEXEC_ON_CRASH) {
1250                         /* Free any current crash dump kernel before
1251                          * we corrupt it.
1252                          */
1253                         kimage_free(xchg(&kexec_crash_image, NULL));
1254                         result = kimage_alloc_init(&image, entry, nr_segments,
1255                                                    segments, flags);
1256                         crash_map_reserved_pages();
1257                 }
1258                 if (result)
1259                         goto out;
1260
1261                 if (flags & KEXEC_PRESERVE_CONTEXT)
1262                         image->preserve_context = 1;
1263                 result = machine_kexec_prepare(image);
1264                 if (result)
1265                         goto out;
1266
1267                 for (i = 0; i < nr_segments; i++) {
1268                         result = kimage_load_segment(image, &image->segment[i]);
1269                         if (result)
1270                                 goto out;
1271                 }
1272                 kimage_terminate(image);
1273                 if (flags & KEXEC_ON_CRASH)
1274                         crash_unmap_reserved_pages();
1275         }
1276         /* Install the new kernel, and  Uninstall the old */
1277         image = xchg(dest_image, image);
1278
1279 out:
1280         mutex_unlock(&kexec_mutex);
1281         kimage_free(image);
1282
1283         return result;
1284 }
1285
1286 /*
1287  * Add and remove page tables for crashkernel memory
1288  *
1289  * Provide an empty default implementation here -- architecture
1290  * code may override this
1291  */
1292 void __weak crash_map_reserved_pages(void)
1293 {}
1294
1295 void __weak crash_unmap_reserved_pages(void)
1296 {}
1297
1298 #ifdef CONFIG_COMPAT
1299 COMPAT_SYSCALL_DEFINE4(kexec_load, compat_ulong_t, entry,
1300                        compat_ulong_t, nr_segments,
1301                        struct compat_kexec_segment __user *, segments,
1302                        compat_ulong_t, flags)
1303 {
1304         struct compat_kexec_segment in;
1305         struct kexec_segment out, __user *ksegments;
1306         unsigned long i, result;
1307
1308         /* Don't allow clients that don't understand the native
1309          * architecture to do anything.
1310          */
1311         if ((flags & KEXEC_ARCH_MASK) == KEXEC_ARCH_DEFAULT)
1312                 return -EINVAL;
1313
1314         if (nr_segments > KEXEC_SEGMENT_MAX)
1315                 return -EINVAL;
1316
1317         ksegments = compat_alloc_user_space(nr_segments * sizeof(out));
1318         for (i = 0; i < nr_segments; i++) {
1319                 result = copy_from_user(&in, &segments[i], sizeof(in));
1320                 if (result)
1321                         return -EFAULT;
1322
1323                 out.buf   = compat_ptr(in.buf);
1324                 out.bufsz = in.bufsz;
1325                 out.mem   = in.mem;
1326                 out.memsz = in.memsz;
1327
1328                 result = copy_to_user(&ksegments[i], &out, sizeof(out));
1329                 if (result)
1330                         return -EFAULT;
1331         }
1332
1333         return sys_kexec_load(entry, nr_segments, ksegments, flags);
1334 }
1335 #endif
1336
1337 SYSCALL_DEFINE5(kexec_file_load, int, kernel_fd, int, initrd_fd,
1338                 unsigned long, cmdline_len, const char __user *, cmdline_ptr,
1339                 unsigned long, flags)
1340 {
1341         int ret = 0, i;
1342         struct kimage **dest_image, *image;
1343
1344         /* We only trust the superuser with rebooting the system. */
1345         if (!capable(CAP_SYS_BOOT) || kexec_load_disabled)
1346                 return -EPERM;
1347
1348         /* Make sure we have a legal set of flags */
1349         if (flags != (flags & KEXEC_FILE_FLAGS))
1350                 return -EINVAL;
1351
1352         image = NULL;
1353
1354         if (!mutex_trylock(&kexec_mutex))
1355                 return -EBUSY;
1356
1357         dest_image = &kexec_image;
1358         if (flags & KEXEC_FILE_ON_CRASH)
1359                 dest_image = &kexec_crash_image;
1360
1361         if (flags & KEXEC_FILE_UNLOAD)
1362                 goto exchange;
1363
1364         /*
1365          * In case of crash, new kernel gets loaded in reserved region. It is
1366          * same memory where old crash kernel might be loaded. Free any
1367          * current crash dump kernel before we corrupt it.
1368          */
1369         if (flags & KEXEC_FILE_ON_CRASH)
1370                 kimage_free(xchg(&kexec_crash_image, NULL));
1371
1372         ret = kimage_file_alloc_init(&image, kernel_fd, initrd_fd, cmdline_ptr,
1373                                      cmdline_len, flags);
1374         if (ret)
1375                 goto out;
1376
1377         ret = machine_kexec_prepare(image);
1378         if (ret)
1379                 goto out;
1380
1381         ret = kexec_calculate_store_digests(image);
1382         if (ret)
1383                 goto out;
1384
1385         for (i = 0; i < image->nr_segments; i++) {
1386                 struct kexec_segment *ksegment;
1387
1388                 ksegment = &image->segment[i];
1389                 pr_debug("Loading segment %d: buf=0x%p bufsz=0x%zx mem=0x%lx memsz=0x%zx\n",
1390                          i, ksegment->buf, ksegment->bufsz, ksegment->mem,
1391                          ksegment->memsz);
1392
1393                 ret = kimage_load_segment(image, &image->segment[i]);
1394                 if (ret)
1395                         goto out;
1396         }
1397
1398         kimage_terminate(image);
1399
1400         /*
1401          * Free up any temporary buffers allocated which are not needed
1402          * after image has been loaded
1403          */
1404         kimage_file_post_load_cleanup(image);
1405 exchange:
1406         image = xchg(dest_image, image);
1407 out:
1408         mutex_unlock(&kexec_mutex);
1409         kimage_free(image);
1410         return ret;
1411 }
1412
1413 void crash_kexec(struct pt_regs *regs)
1414 {
1415         /* Take the kexec_mutex here to prevent sys_kexec_load
1416          * running on one cpu from replacing the crash kernel
1417          * we are using after a panic on a different cpu.
1418          *
1419          * If the crash kernel was not located in a fixed area
1420          * of memory the xchg(&kexec_crash_image) would be
1421          * sufficient.  But since I reuse the memory...
1422          */
1423         if (mutex_trylock(&kexec_mutex)) {
1424                 if (kexec_crash_image) {
1425                         struct pt_regs fixed_regs;
1426
1427                         crash_setup_regs(&fixed_regs, regs);
1428                         crash_save_vmcoreinfo();
1429                         machine_crash_shutdown(&fixed_regs);
1430                         machine_kexec(kexec_crash_image);
1431                 }
1432                 mutex_unlock(&kexec_mutex);
1433         }
1434 }
1435
1436 size_t crash_get_memory_size(void)
1437 {
1438         size_t size = 0;
1439         mutex_lock(&kexec_mutex);
1440         if (crashk_res.end != crashk_res.start)
1441                 size = resource_size(&crashk_res);
1442         mutex_unlock(&kexec_mutex);
1443         return size;
1444 }
1445
1446 void __weak crash_free_reserved_phys_range(unsigned long begin,
1447                                            unsigned long end)
1448 {
1449         unsigned long addr;
1450
1451         for (addr = begin; addr < end; addr += PAGE_SIZE)
1452                 free_reserved_page(pfn_to_page(addr >> PAGE_SHIFT));
1453 }
1454
1455 int crash_shrink_memory(unsigned long new_size)
1456 {
1457         int ret = 0;
1458         unsigned long start, end;
1459         unsigned long old_size;
1460         struct resource *ram_res;
1461
1462         mutex_lock(&kexec_mutex);
1463
1464         if (kexec_crash_image) {
1465                 ret = -ENOENT;
1466                 goto unlock;
1467         }
1468         start = crashk_res.start;
1469         end = crashk_res.end;
1470         old_size = (end == 0) ? 0 : end - start + 1;
1471         if (new_size >= old_size) {
1472                 ret = (new_size == old_size) ? 0 : -EINVAL;
1473                 goto unlock;
1474         }
1475
1476         ram_res = kzalloc(sizeof(*ram_res), GFP_KERNEL);
1477         if (!ram_res) {
1478                 ret = -ENOMEM;
1479                 goto unlock;
1480         }
1481
1482         start = roundup(start, KEXEC_CRASH_MEM_ALIGN);
1483         end = roundup(start + new_size, KEXEC_CRASH_MEM_ALIGN);
1484
1485         crash_map_reserved_pages();
1486         crash_free_reserved_phys_range(end, crashk_res.end);
1487
1488         if ((start == end) && (crashk_res.parent != NULL))
1489                 release_resource(&crashk_res);
1490
1491         ram_res->start = end;
1492         ram_res->end = crashk_res.end;
1493         ram_res->flags = IORESOURCE_BUSY | IORESOURCE_MEM;
1494         ram_res->name = "System RAM";
1495
1496         crashk_res.end = end - 1;
1497
1498         insert_resource(&iomem_resource, ram_res);
1499         crash_unmap_reserved_pages();
1500
1501 unlock:
1502         mutex_unlock(&kexec_mutex);
1503         return ret;
1504 }
1505
1506 static u32 *append_elf_note(u32 *buf, char *name, unsigned type, void *data,
1507                             size_t data_len)
1508 {
1509         struct elf_note note;
1510
1511         note.n_namesz = strlen(name) + 1;
1512         note.n_descsz = data_len;
1513         note.n_type   = type;
1514         memcpy(buf, &note, sizeof(note));
1515         buf += (sizeof(note) + 3)/4;
1516         memcpy(buf, name, note.n_namesz);
1517         buf += (note.n_namesz + 3)/4;
1518         memcpy(buf, data, note.n_descsz);
1519         buf += (note.n_descsz + 3)/4;
1520
1521         return buf;
1522 }
1523
1524 static void final_note(u32 *buf)
1525 {
1526         struct elf_note note;
1527
1528         note.n_namesz = 0;
1529         note.n_descsz = 0;
1530         note.n_type   = 0;
1531         memcpy(buf, &note, sizeof(note));
1532 }
1533
1534 void crash_save_cpu(struct pt_regs *regs, int cpu)
1535 {
1536         struct elf_prstatus prstatus;
1537         u32 *buf;
1538
1539         if ((cpu < 0) || (cpu >= nr_cpu_ids))
1540                 return;
1541
1542         /* Using ELF notes here is opportunistic.
1543          * I need a well defined structure format
1544          * for the data I pass, and I need tags
1545          * on the data to indicate what information I have
1546          * squirrelled away.  ELF notes happen to provide
1547          * all of that, so there is no need to invent something new.
1548          */
1549         buf = (u32 *)per_cpu_ptr(crash_notes, cpu);
1550         if (!buf)
1551                 return;
1552         memset(&prstatus, 0, sizeof(prstatus));
1553         prstatus.pr_pid = current->pid;
1554         elf_core_copy_kernel_regs(&prstatus.pr_reg, regs);
1555         buf = append_elf_note(buf, KEXEC_CORE_NOTE_NAME, NT_PRSTATUS,
1556                               &prstatus, sizeof(prstatus));
1557         final_note(buf);
1558 }
1559
1560 static int __init crash_notes_memory_init(void)
1561 {
1562         /* Allocate memory for saving cpu registers. */
1563         crash_notes = alloc_percpu(note_buf_t);
1564         if (!crash_notes) {
1565                 pr_warn("Kexec: Memory allocation for saving cpu register states failed\n");
1566                 return -ENOMEM;
1567         }
1568         return 0;
1569 }
1570 subsys_initcall(crash_notes_memory_init);
1571
1572
1573 /*
1574  * parsing the "crashkernel" commandline
1575  *
1576  * this code is intended to be called from architecture specific code
1577  */
1578
1579
1580 /*
1581  * This function parses command lines in the format
1582  *
1583  *   crashkernel=ramsize-range:size[,...][@offset]
1584  *
1585  * The function returns 0 on success and -EINVAL on failure.
1586  */
1587 static int __init parse_crashkernel_mem(char *cmdline,
1588                                         unsigned long long system_ram,
1589                                         unsigned long long *crash_size,
1590                                         unsigned long long *crash_base)
1591 {
1592         char *cur = cmdline, *tmp;
1593
1594         /* for each entry of the comma-separated list */
1595         do {
1596                 unsigned long long start, end = ULLONG_MAX, size;
1597
1598                 /* get the start of the range */
1599                 start = memparse(cur, &tmp);
1600                 if (cur == tmp) {
1601                         pr_warn("crashkernel: Memory value expected\n");
1602                         return -EINVAL;
1603                 }
1604                 cur = tmp;
1605                 if (*cur != '-') {
1606                         pr_warn("crashkernel: '-' expected\n");
1607                         return -EINVAL;
1608                 }
1609                 cur++;
1610
1611                 /* if no ':' is here, than we read the end */
1612                 if (*cur != ':') {
1613                         end = memparse(cur, &tmp);
1614                         if (cur == tmp) {
1615                                 pr_warn("crashkernel: Memory value expected\n");
1616                                 return -EINVAL;
1617                         }
1618                         cur = tmp;
1619                         if (end <= start) {
1620                                 pr_warn("crashkernel: end <= start\n");
1621                                 return -EINVAL;
1622                         }
1623                 }
1624
1625                 if (*cur != ':') {
1626                         pr_warn("crashkernel: ':' expected\n");
1627                         return -EINVAL;
1628                 }
1629                 cur++;
1630
1631                 size = memparse(cur, &tmp);
1632                 if (cur == tmp) {
1633                         pr_warn("Memory value expected\n");
1634                         return -EINVAL;
1635                 }
1636                 cur = tmp;
1637                 if (size >= system_ram) {
1638                         pr_warn("crashkernel: invalid size\n");
1639                         return -EINVAL;
1640                 }
1641
1642                 /* match ? */
1643                 if (system_ram >= start && system_ram < end) {
1644                         *crash_size = size;
1645                         break;
1646                 }
1647         } while (*cur++ == ',');
1648
1649         if (*crash_size > 0) {
1650                 while (*cur && *cur != ' ' && *cur != '@')
1651                         cur++;
1652                 if (*cur == '@') {
1653                         cur++;
1654                         *crash_base = memparse(cur, &tmp);
1655                         if (cur == tmp) {
1656                                 pr_warn("Memory value expected after '@'\n");
1657                                 return -EINVAL;
1658                         }
1659                 }
1660         }
1661
1662         return 0;
1663 }
1664
1665 /*
1666  * That function parses "simple" (old) crashkernel command lines like
1667  *
1668  *      crashkernel=size[@offset]
1669  *
1670  * It returns 0 on success and -EINVAL on failure.
1671  */
1672 static int __init parse_crashkernel_simple(char *cmdline,
1673                                            unsigned long long *crash_size,
1674                                            unsigned long long *crash_base)
1675 {
1676         char *cur = cmdline;
1677
1678         *crash_size = memparse(cmdline, &cur);
1679         if (cmdline == cur) {
1680                 pr_warn("crashkernel: memory value expected\n");
1681                 return -EINVAL;
1682         }
1683
1684         if (*cur == '@')
1685                 *crash_base = memparse(cur+1, &cur);
1686         else if (*cur != ' ' && *cur != '\0') {
1687                 pr_warn("crashkernel: unrecognized char\n");
1688                 return -EINVAL;
1689         }
1690
1691         return 0;
1692 }
1693
1694 #define SUFFIX_HIGH 0
1695 #define SUFFIX_LOW  1
1696 #define SUFFIX_NULL 2
1697 static __initdata char *suffix_tbl[] = {
1698         [SUFFIX_HIGH] = ",high",
1699         [SUFFIX_LOW]  = ",low",
1700         [SUFFIX_NULL] = NULL,
1701 };
1702
1703 /*
1704  * That function parses "suffix"  crashkernel command lines like
1705  *
1706  *      crashkernel=size,[high|low]
1707  *
1708  * It returns 0 on success and -EINVAL on failure.
1709  */
1710 static int __init parse_crashkernel_suffix(char *cmdline,
1711                                            unsigned long long   *crash_size,
1712                                            unsigned long long   *crash_base,
1713                                            const char *suffix)
1714 {
1715         char *cur = cmdline;
1716
1717         *crash_size = memparse(cmdline, &cur);
1718         if (cmdline == cur) {
1719                 pr_warn("crashkernel: memory value expected\n");
1720                 return -EINVAL;
1721         }
1722
1723         /* check with suffix */
1724         if (strncmp(cur, suffix, strlen(suffix))) {
1725                 pr_warn("crashkernel: unrecognized char\n");
1726                 return -EINVAL;
1727         }
1728         cur += strlen(suffix);
1729         if (*cur != ' ' && *cur != '\0') {
1730                 pr_warn("crashkernel: unrecognized char\n");
1731                 return -EINVAL;
1732         }
1733
1734         return 0;
1735 }
1736
1737 static __init char *get_last_crashkernel(char *cmdline,
1738                              const char *name,
1739                              const char *suffix)
1740 {
1741         char *p = cmdline, *ck_cmdline = NULL;
1742
1743         /* find crashkernel and use the last one if there are more */
1744         p = strstr(p, name);
1745         while (p) {
1746                 char *end_p = strchr(p, ' ');
1747                 char *q;
1748
1749                 if (!end_p)
1750                         end_p = p + strlen(p);
1751
1752                 if (!suffix) {
1753                         int i;
1754
1755                         /* skip the one with any known suffix */
1756                         for (i = 0; suffix_tbl[i]; i++) {
1757                                 q = end_p - strlen(suffix_tbl[i]);
1758                                 if (!strncmp(q, suffix_tbl[i],
1759                                              strlen(suffix_tbl[i])))
1760                                         goto next;
1761                         }
1762                         ck_cmdline = p;
1763                 } else {
1764                         q = end_p - strlen(suffix);
1765                         if (!strncmp(q, suffix, strlen(suffix)))
1766                                 ck_cmdline = p;
1767                 }
1768 next:
1769                 p = strstr(p+1, name);
1770         }
1771
1772         if (!ck_cmdline)
1773                 return NULL;
1774
1775         return ck_cmdline;
1776 }
1777
1778 static int __init __parse_crashkernel(char *cmdline,
1779                              unsigned long long system_ram,
1780                              unsigned long long *crash_size,
1781                              unsigned long long *crash_base,
1782                              const char *name,
1783                              const char *suffix)
1784 {
1785         char    *first_colon, *first_space;
1786         char    *ck_cmdline;
1787
1788         BUG_ON(!crash_size || !crash_base);
1789         *crash_size = 0;
1790         *crash_base = 0;
1791
1792         ck_cmdline = get_last_crashkernel(cmdline, name, suffix);
1793
1794         if (!ck_cmdline)
1795                 return -EINVAL;
1796
1797         ck_cmdline += strlen(name);
1798
1799         if (suffix)
1800                 return parse_crashkernel_suffix(ck_cmdline, crash_size,
1801                                 crash_base, suffix);
1802         /*
1803          * if the commandline contains a ':', then that's the extended
1804          * syntax -- if not, it must be the classic syntax
1805          */
1806         first_colon = strchr(ck_cmdline, ':');
1807         first_space = strchr(ck_cmdline, ' ');
1808         if (first_colon && (!first_space || first_colon < first_space))
1809                 return parse_crashkernel_mem(ck_cmdline, system_ram,
1810                                 crash_size, crash_base);
1811
1812         return parse_crashkernel_simple(ck_cmdline, crash_size, crash_base);
1813 }
1814
1815 /*
1816  * That function is the entry point for command line parsing and should be
1817  * called from the arch-specific code.
1818  */
1819 int __init parse_crashkernel(char *cmdline,
1820                              unsigned long long system_ram,
1821                              unsigned long long *crash_size,
1822                              unsigned long long *crash_base)
1823 {
1824         return __parse_crashkernel(cmdline, system_ram, crash_size, crash_base,
1825                                         "crashkernel=", NULL);
1826 }
1827
1828 int __init parse_crashkernel_high(char *cmdline,
1829                              unsigned long long system_ram,
1830                              unsigned long long *crash_size,
1831                              unsigned long long *crash_base)
1832 {
1833         return __parse_crashkernel(cmdline, system_ram, crash_size, crash_base,
1834                                 "crashkernel=", suffix_tbl[SUFFIX_HIGH]);
1835 }
1836
1837 int __init parse_crashkernel_low(char *cmdline,
1838                              unsigned long long system_ram,
1839                              unsigned long long *crash_size,
1840                              unsigned long long *crash_base)
1841 {
1842         return __parse_crashkernel(cmdline, system_ram, crash_size, crash_base,
1843                                 "crashkernel=", suffix_tbl[SUFFIX_LOW]);
1844 }
1845
1846 static void update_vmcoreinfo_note(void)
1847 {
1848         u32 *buf = vmcoreinfo_note;
1849
1850         if (!vmcoreinfo_size)
1851                 return;
1852         buf = append_elf_note(buf, VMCOREINFO_NOTE_NAME, 0, vmcoreinfo_data,
1853                               vmcoreinfo_size);
1854         final_note(buf);
1855 }
1856
1857 void crash_save_vmcoreinfo(void)
1858 {
1859         vmcoreinfo_append_str("CRASHTIME=%ld\n", get_seconds());
1860         update_vmcoreinfo_note();
1861 }
1862
1863 void vmcoreinfo_append_str(const char *fmt, ...)
1864 {
1865         va_list args;
1866         char buf[0x50];
1867         size_t r;
1868
1869         va_start(args, fmt);
1870         r = vscnprintf(buf, sizeof(buf), fmt, args);
1871         va_end(args);
1872
1873         r = min(r, vmcoreinfo_max_size - vmcoreinfo_size);
1874
1875         memcpy(&vmcoreinfo_data[vmcoreinfo_size], buf, r);
1876
1877         vmcoreinfo_size += r;
1878 }
1879
1880 /*
1881  * provide an empty default implementation here -- architecture
1882  * code may override this
1883  */
1884 void __weak arch_crash_save_vmcoreinfo(void)
1885 {}
1886
1887 unsigned long __weak paddr_vmcoreinfo_note(void)
1888 {
1889         return __pa((unsigned long)(char *)&vmcoreinfo_note);
1890 }
1891
1892 static int __init crash_save_vmcoreinfo_init(void)
1893 {
1894         VMCOREINFO_OSRELEASE(init_uts_ns.name.release);
1895         VMCOREINFO_PAGESIZE(PAGE_SIZE);
1896
1897         VMCOREINFO_SYMBOL(init_uts_ns);
1898         VMCOREINFO_SYMBOL(node_online_map);
1899 #ifdef CONFIG_MMU
1900         VMCOREINFO_SYMBOL(swapper_pg_dir);
1901 #endif
1902         VMCOREINFO_SYMBOL(_stext);
1903         VMCOREINFO_SYMBOL(vmap_area_list);
1904
1905 #ifndef CONFIG_NEED_MULTIPLE_NODES
1906         VMCOREINFO_SYMBOL(mem_map);
1907         VMCOREINFO_SYMBOL(contig_page_data);
1908 #endif
1909 #ifdef CONFIG_SPARSEMEM
1910         VMCOREINFO_SYMBOL(mem_section);
1911         VMCOREINFO_LENGTH(mem_section, NR_SECTION_ROOTS);
1912         VMCOREINFO_STRUCT_SIZE(mem_section);
1913         VMCOREINFO_OFFSET(mem_section, section_mem_map);
1914 #endif
1915         VMCOREINFO_STRUCT_SIZE(page);
1916         VMCOREINFO_STRUCT_SIZE(pglist_data);
1917         VMCOREINFO_STRUCT_SIZE(zone);
1918         VMCOREINFO_STRUCT_SIZE(free_area);
1919         VMCOREINFO_STRUCT_SIZE(list_head);
1920         VMCOREINFO_SIZE(nodemask_t);
1921         VMCOREINFO_OFFSET(page, flags);
1922         VMCOREINFO_OFFSET(page, _count);
1923         VMCOREINFO_OFFSET(page, mapping);
1924         VMCOREINFO_OFFSET(page, lru);
1925         VMCOREINFO_OFFSET(page, _mapcount);
1926         VMCOREINFO_OFFSET(page, private);
1927         VMCOREINFO_OFFSET(pglist_data, node_zones);
1928         VMCOREINFO_OFFSET(pglist_data, nr_zones);
1929 #ifdef CONFIG_FLAT_NODE_MEM_MAP
1930         VMCOREINFO_OFFSET(pglist_data, node_mem_map);
1931 #endif
1932         VMCOREINFO_OFFSET(pglist_data, node_start_pfn);
1933         VMCOREINFO_OFFSET(pglist_data, node_spanned_pages);
1934         VMCOREINFO_OFFSET(pglist_data, node_id);
1935         VMCOREINFO_OFFSET(zone, free_area);
1936         VMCOREINFO_OFFSET(zone, vm_stat);
1937         VMCOREINFO_OFFSET(zone, spanned_pages);
1938         VMCOREINFO_OFFSET(free_area, free_list);
1939         VMCOREINFO_OFFSET(list_head, next);
1940         VMCOREINFO_OFFSET(list_head, prev);
1941         VMCOREINFO_OFFSET(vmap_area, va_start);
1942         VMCOREINFO_OFFSET(vmap_area, list);
1943         VMCOREINFO_LENGTH(zone.free_area, MAX_ORDER);
1944         log_buf_kexec_setup();
1945         VMCOREINFO_LENGTH(free_area.free_list, MIGRATE_TYPES);
1946         VMCOREINFO_NUMBER(NR_FREE_PAGES);
1947         VMCOREINFO_NUMBER(PG_lru);
1948         VMCOREINFO_NUMBER(PG_private);
1949         VMCOREINFO_NUMBER(PG_swapcache);
1950         VMCOREINFO_NUMBER(PG_slab);
1951 #ifdef CONFIG_MEMORY_FAILURE
1952         VMCOREINFO_NUMBER(PG_hwpoison);
1953 #endif
1954         VMCOREINFO_NUMBER(PG_head_mask);
1955         VMCOREINFO_NUMBER(PAGE_BUDDY_MAPCOUNT_VALUE);
1956 #ifdef CONFIG_HUGETLBFS
1957         VMCOREINFO_SYMBOL(free_huge_page);
1958 #endif
1959
1960         arch_crash_save_vmcoreinfo();
1961         update_vmcoreinfo_note();
1962
1963         return 0;
1964 }
1965
1966 subsys_initcall(crash_save_vmcoreinfo_init);
1967
1968 static int __kexec_add_segment(struct kimage *image, char *buf,
1969                                unsigned long bufsz, unsigned long mem,
1970                                unsigned long memsz)
1971 {
1972         struct kexec_segment *ksegment;
1973
1974         ksegment = &image->segment[image->nr_segments];
1975         ksegment->kbuf = buf;
1976         ksegment->bufsz = bufsz;
1977         ksegment->mem = mem;
1978         ksegment->memsz = memsz;
1979         image->nr_segments++;
1980
1981         return 0;
1982 }
1983
1984 static int locate_mem_hole_top_down(unsigned long start, unsigned long end,
1985                                     struct kexec_buf *kbuf)
1986 {
1987         struct kimage *image = kbuf->image;
1988         unsigned long temp_start, temp_end;
1989
1990         temp_end = min(end, kbuf->buf_max);
1991         temp_start = temp_end - kbuf->memsz;
1992
1993         do {
1994                 /* align down start */
1995                 temp_start = temp_start & (~(kbuf->buf_align - 1));
1996
1997                 if (temp_start < start || temp_start < kbuf->buf_min)
1998                         return 0;
1999
2000                 temp_end = temp_start + kbuf->memsz - 1;
2001
2002                 /*
2003                  * Make sure this does not conflict with any of existing
2004                  * segments
2005                  */
2006                 if (kimage_is_destination_range(image, temp_start, temp_end)) {
2007                         temp_start = temp_start - PAGE_SIZE;
2008                         continue;
2009                 }
2010
2011                 /* We found a suitable memory range */
2012                 break;
2013         } while (1);
2014
2015         /* If we are here, we found a suitable memory range */
2016         __kexec_add_segment(image, kbuf->buffer, kbuf->bufsz, temp_start,
2017                             kbuf->memsz);
2018
2019         /* Success, stop navigating through remaining System RAM ranges */
2020         return 1;
2021 }
2022
2023 static int locate_mem_hole_bottom_up(unsigned long start, unsigned long end,
2024                                      struct kexec_buf *kbuf)
2025 {
2026         struct kimage *image = kbuf->image;
2027         unsigned long temp_start, temp_end;
2028
2029         temp_start = max(start, kbuf->buf_min);
2030
2031         do {
2032                 temp_start = ALIGN(temp_start, kbuf->buf_align);
2033                 temp_end = temp_start + kbuf->memsz - 1;
2034
2035                 if (temp_end > end || temp_end > kbuf->buf_max)
2036                         return 0;
2037                 /*
2038                  * Make sure this does not conflict with any of existing
2039                  * segments
2040                  */
2041                 if (kimage_is_destination_range(image, temp_start, temp_end)) {
2042                         temp_start = temp_start + PAGE_SIZE;
2043                         continue;
2044                 }
2045
2046                 /* We found a suitable memory range */
2047                 break;
2048         } while (1);
2049
2050         /* If we are here, we found a suitable memory range */
2051         __kexec_add_segment(image, kbuf->buffer, kbuf->bufsz, temp_start,
2052                             kbuf->memsz);
2053
2054         /* Success, stop navigating through remaining System RAM ranges */
2055         return 1;
2056 }
2057
2058 static int locate_mem_hole_callback(u64 start, u64 end, void *arg)
2059 {
2060         struct kexec_buf *kbuf = (struct kexec_buf *)arg;
2061         unsigned long sz = end - start + 1;
2062
2063         /* Returning 0 will take to next memory range */
2064         if (sz < kbuf->memsz)
2065                 return 0;
2066
2067         if (end < kbuf->buf_min || start > kbuf->buf_max)
2068                 return 0;
2069
2070         /*
2071          * Allocate memory top down with-in ram range. Otherwise bottom up
2072          * allocation.
2073          */
2074         if (kbuf->top_down)
2075                 return locate_mem_hole_top_down(start, end, kbuf);
2076         return locate_mem_hole_bottom_up(start, end, kbuf);
2077 }
2078
2079 /*
2080  * Helper function for placing a buffer in a kexec segment. This assumes
2081  * that kexec_mutex is held.
2082  */
2083 int kexec_add_buffer(struct kimage *image, char *buffer, unsigned long bufsz,
2084                      unsigned long memsz, unsigned long buf_align,
2085                      unsigned long buf_min, unsigned long buf_max,
2086                      bool top_down, unsigned long *load_addr)
2087 {
2088
2089         struct kexec_segment *ksegment;
2090         struct kexec_buf buf, *kbuf;
2091         int ret;
2092
2093         /* Currently adding segment this way is allowed only in file mode */
2094         if (!image->file_mode)
2095                 return -EINVAL;
2096
2097         if (image->nr_segments >= KEXEC_SEGMENT_MAX)
2098                 return -EINVAL;
2099
2100         /*
2101          * Make sure we are not trying to add buffer after allocating
2102          * control pages. All segments need to be placed first before
2103          * any control pages are allocated. As control page allocation
2104          * logic goes through list of segments to make sure there are
2105          * no destination overlaps.
2106          */
2107         if (!list_empty(&image->control_pages)) {
2108                 WARN_ON(1);
2109                 return -EINVAL;
2110         }
2111
2112         memset(&buf, 0, sizeof(struct kexec_buf));
2113         kbuf = &buf;
2114         kbuf->image = image;
2115         kbuf->buffer = buffer;
2116         kbuf->bufsz = bufsz;
2117
2118         kbuf->memsz = ALIGN(memsz, PAGE_SIZE);
2119         kbuf->buf_align = max(buf_align, PAGE_SIZE);
2120         kbuf->buf_min = buf_min;
2121         kbuf->buf_max = buf_max;
2122         kbuf->top_down = top_down;
2123
2124         /* Walk the RAM ranges and allocate a suitable range for the buffer */
2125         ret = walk_system_ram_res(0, -1, kbuf, locate_mem_hole_callback);
2126         if (ret != 1) {
2127                 /* A suitable memory range could not be found for buffer */
2128                 return -EADDRNOTAVAIL;
2129         }
2130
2131         /* Found a suitable memory range */
2132         ksegment = &image->segment[image->nr_segments - 1];
2133         *load_addr = ksegment->mem;
2134         return 0;
2135 }
2136
2137 /* Calculate and store the digest of segments */
2138 static int kexec_calculate_store_digests(struct kimage *image)
2139 {
2140         struct crypto_shash *tfm;
2141         struct shash_desc *desc;
2142         int ret = 0, i, j, zero_buf_sz, sha_region_sz;
2143         size_t desc_size, nullsz;
2144         char *digest;
2145         void *zero_buf;
2146         struct kexec_sha_region *sha_regions;
2147         struct purgatory_info *pi = &image->purgatory_info;
2148
2149         zero_buf = __va(page_to_pfn(ZERO_PAGE(0)) << PAGE_SHIFT);
2150         zero_buf_sz = PAGE_SIZE;
2151
2152         tfm = crypto_alloc_shash("sha256", 0, 0);
2153         if (IS_ERR(tfm)) {
2154                 ret = PTR_ERR(tfm);
2155                 goto out;
2156         }
2157
2158         desc_size = crypto_shash_descsize(tfm) + sizeof(*desc);
2159         desc = kzalloc(desc_size, GFP_KERNEL);
2160         if (!desc) {
2161                 ret = -ENOMEM;
2162                 goto out_free_tfm;
2163         }
2164
2165         sha_region_sz = KEXEC_SEGMENT_MAX * sizeof(struct kexec_sha_region);
2166         sha_regions = vzalloc(sha_region_sz);
2167         if (!sha_regions)
2168                 goto out_free_desc;
2169
2170         desc->tfm   = tfm;
2171         desc->flags = 0;
2172
2173         ret = crypto_shash_init(desc);
2174         if (ret < 0)
2175                 goto out_free_sha_regions;
2176
2177         digest = kzalloc(SHA256_DIGEST_SIZE, GFP_KERNEL);
2178         if (!digest) {
2179                 ret = -ENOMEM;
2180                 goto out_free_sha_regions;
2181         }
2182
2183         for (j = i = 0; i < image->nr_segments; i++) {
2184                 struct kexec_segment *ksegment;
2185
2186                 ksegment = &image->segment[i];
2187                 /*
2188                  * Skip purgatory as it will be modified once we put digest
2189                  * info in purgatory.
2190                  */
2191                 if (ksegment->kbuf == pi->purgatory_buf)
2192                         continue;
2193
2194                 ret = crypto_shash_update(desc, ksegment->kbuf,
2195                                           ksegment->bufsz);
2196                 if (ret)
2197                         break;
2198
2199                 /*
2200                  * Assume rest of the buffer is filled with zero and
2201                  * update digest accordingly.
2202                  */
2203                 nullsz = ksegment->memsz - ksegment->bufsz;
2204                 while (nullsz) {
2205                         unsigned long bytes = nullsz;
2206
2207                         if (bytes > zero_buf_sz)
2208                                 bytes = zero_buf_sz;
2209                         ret = crypto_shash_update(desc, zero_buf, bytes);
2210                         if (ret)
2211                                 break;
2212                         nullsz -= bytes;
2213                 }
2214
2215                 if (ret)
2216                         break;
2217
2218                 sha_regions[j].start = ksegment->mem;
2219                 sha_regions[j].len = ksegment->memsz;
2220                 j++;
2221         }
2222
2223         if (!ret) {
2224                 ret = crypto_shash_final(desc, digest);
2225                 if (ret)
2226                         goto out_free_digest;
2227                 ret = kexec_purgatory_get_set_symbol(image, "sha_regions",
2228                                                 sha_regions, sha_region_sz, 0);
2229                 if (ret)
2230                         goto out_free_digest;
2231
2232                 ret = kexec_purgatory_get_set_symbol(image, "sha256_digest",
2233                                                 digest, SHA256_DIGEST_SIZE, 0);
2234                 if (ret)
2235                         goto out_free_digest;
2236         }
2237
2238 out_free_digest:
2239         kfree(digest);
2240 out_free_sha_regions:
2241         vfree(sha_regions);
2242 out_free_desc:
2243         kfree(desc);
2244 out_free_tfm:
2245         kfree(tfm);
2246 out:
2247         return ret;
2248 }
2249
2250 /* Actually load purgatory. Lot of code taken from kexec-tools */
2251 static int __kexec_load_purgatory(struct kimage *image, unsigned long min,
2252                                   unsigned long max, int top_down)
2253 {
2254         struct purgatory_info *pi = &image->purgatory_info;
2255         unsigned long align, buf_align, bss_align, buf_sz, bss_sz, bss_pad;
2256         unsigned long memsz, entry, load_addr, curr_load_addr, bss_addr, offset;
2257         unsigned char *buf_addr, *src;
2258         int i, ret = 0, entry_sidx = -1;
2259         const Elf_Shdr *sechdrs_c;
2260         Elf_Shdr *sechdrs = NULL;
2261         void *purgatory_buf = NULL;
2262
2263         /*
2264          * sechdrs_c points to section headers in purgatory and are read
2265          * only. No modifications allowed.
2266          */
2267         sechdrs_c = (void *)pi->ehdr + pi->ehdr->e_shoff;
2268
2269         /*
2270          * We can not modify sechdrs_c[] and its fields. It is read only.
2271          * Copy it over to a local copy where one can store some temporary
2272          * data and free it at the end. We need to modify ->sh_addr and
2273          * ->sh_offset fields to keep track of permanent and temporary
2274          * locations of sections.
2275          */
2276         sechdrs = vzalloc(pi->ehdr->e_shnum * sizeof(Elf_Shdr));
2277         if (!sechdrs)
2278                 return -ENOMEM;
2279
2280         memcpy(sechdrs, sechdrs_c, pi->ehdr->e_shnum * sizeof(Elf_Shdr));
2281
2282         /*
2283          * We seem to have multiple copies of sections. First copy is which
2284          * is embedded in kernel in read only section. Some of these sections
2285          * will be copied to a temporary buffer and relocated. And these
2286          * sections will finally be copied to their final destination at
2287          * segment load time.
2288          *
2289          * Use ->sh_offset to reflect section address in memory. It will
2290          * point to original read only copy if section is not allocatable.
2291          * Otherwise it will point to temporary copy which will be relocated.
2292          *
2293          * Use ->sh_addr to contain final address of the section where it
2294          * will go during execution time.
2295          */
2296         for (i = 0; i < pi->ehdr->e_shnum; i++) {
2297                 if (sechdrs[i].sh_type == SHT_NOBITS)
2298                         continue;
2299
2300                 sechdrs[i].sh_offset = (unsigned long)pi->ehdr +
2301                                                 sechdrs[i].sh_offset;
2302         }
2303
2304         /*
2305          * Identify entry point section and make entry relative to section
2306          * start.
2307          */
2308         entry = pi->ehdr->e_entry;
2309         for (i = 0; i < pi->ehdr->e_shnum; i++) {
2310                 if (!(sechdrs[i].sh_flags & SHF_ALLOC))
2311                         continue;
2312
2313                 if (!(sechdrs[i].sh_flags & SHF_EXECINSTR))
2314                         continue;
2315
2316                 /* Make entry section relative */
2317                 if (sechdrs[i].sh_addr <= pi->ehdr->e_entry &&
2318                     ((sechdrs[i].sh_addr + sechdrs[i].sh_size) >
2319                      pi->ehdr->e_entry)) {
2320                         entry_sidx = i;
2321                         entry -= sechdrs[i].sh_addr;
2322                         break;
2323                 }
2324         }
2325
2326         /* Determine how much memory is needed to load relocatable object. */
2327         buf_align = 1;
2328         bss_align = 1;
2329         buf_sz = 0;
2330         bss_sz = 0;
2331
2332         for (i = 0; i < pi->ehdr->e_shnum; i++) {
2333                 if (!(sechdrs[i].sh_flags & SHF_ALLOC))
2334                         continue;
2335
2336                 align = sechdrs[i].sh_addralign;
2337                 if (sechdrs[i].sh_type != SHT_NOBITS) {
2338                         if (buf_align < align)
2339                                 buf_align = align;
2340                         buf_sz = ALIGN(buf_sz, align);
2341                         buf_sz += sechdrs[i].sh_size;
2342                 } else {
2343                         /* bss section */
2344                         if (bss_align < align)
2345                                 bss_align = align;
2346                         bss_sz = ALIGN(bss_sz, align);
2347                         bss_sz += sechdrs[i].sh_size;
2348                 }
2349         }
2350
2351         /* Determine the bss padding required to align bss properly */
2352         bss_pad = 0;
2353         if (buf_sz & (bss_align - 1))
2354                 bss_pad = bss_align - (buf_sz & (bss_align - 1));
2355
2356         memsz = buf_sz + bss_pad + bss_sz;
2357
2358         /* Allocate buffer for purgatory */
2359         purgatory_buf = vzalloc(buf_sz);
2360         if (!purgatory_buf) {
2361                 ret = -ENOMEM;
2362                 goto out;
2363         }
2364
2365         if (buf_align < bss_align)
2366                 buf_align = bss_align;
2367
2368         /* Add buffer to segment list */
2369         ret = kexec_add_buffer(image, purgatory_buf, buf_sz, memsz,
2370                                 buf_align, min, max, top_down,
2371                                 &pi->purgatory_load_addr);
2372         if (ret)
2373                 goto out;
2374
2375         /* Load SHF_ALLOC sections */
2376         buf_addr = purgatory_buf;
2377         load_addr = curr_load_addr = pi->purgatory_load_addr;
2378         bss_addr = load_addr + buf_sz + bss_pad;
2379
2380         for (i = 0; i < pi->ehdr->e_shnum; i++) {
2381                 if (!(sechdrs[i].sh_flags & SHF_ALLOC))
2382                         continue;
2383
2384                 align = sechdrs[i].sh_addralign;
2385                 if (sechdrs[i].sh_type != SHT_NOBITS) {
2386                         curr_load_addr = ALIGN(curr_load_addr, align);
2387                         offset = curr_load_addr - load_addr;
2388                         /* We already modifed ->sh_offset to keep src addr */
2389                         src = (char *) sechdrs[i].sh_offset;
2390                         memcpy(buf_addr + offset, src, sechdrs[i].sh_size);
2391
2392                         /* Store load address and source address of section */
2393                         sechdrs[i].sh_addr = curr_load_addr;
2394
2395                         /*
2396                          * This section got copied to temporary buffer. Update
2397                          * ->sh_offset accordingly.
2398                          */
2399                         sechdrs[i].sh_offset = (unsigned long)(buf_addr + offset);
2400
2401                         /* Advance to the next address */
2402                         curr_load_addr += sechdrs[i].sh_size;
2403                 } else {
2404                         bss_addr = ALIGN(bss_addr, align);
2405                         sechdrs[i].sh_addr = bss_addr;
2406                         bss_addr += sechdrs[i].sh_size;
2407                 }
2408         }
2409
2410         /* Update entry point based on load address of text section */
2411         if (entry_sidx >= 0)
2412                 entry += sechdrs[entry_sidx].sh_addr;
2413
2414         /* Make kernel jump to purgatory after shutdown */
2415         image->start = entry;
2416
2417         /* Used later to get/set symbol values */
2418         pi->sechdrs = sechdrs;
2419
2420         /*
2421          * Used later to identify which section is purgatory and skip it
2422          * from checksumming.
2423          */
2424         pi->purgatory_buf = purgatory_buf;
2425         return ret;
2426 out:
2427         vfree(sechdrs);
2428         vfree(purgatory_buf);
2429         return ret;
2430 }
2431
2432 static int kexec_apply_relocations(struct kimage *image)
2433 {
2434         int i, ret;
2435         struct purgatory_info *pi = &image->purgatory_info;
2436         Elf_Shdr *sechdrs = pi->sechdrs;
2437
2438         /* Apply relocations */
2439         for (i = 0; i < pi->ehdr->e_shnum; i++) {
2440                 Elf_Shdr *section, *symtab;
2441
2442                 if (sechdrs[i].sh_type != SHT_RELA &&
2443                     sechdrs[i].sh_type != SHT_REL)
2444                         continue;
2445
2446                 /*
2447                  * For section of type SHT_RELA/SHT_REL,
2448                  * ->sh_link contains section header index of associated
2449                  * symbol table. And ->sh_info contains section header
2450                  * index of section to which relocations apply.
2451                  */
2452                 if (sechdrs[i].sh_info >= pi->ehdr->e_shnum ||
2453                     sechdrs[i].sh_link >= pi->ehdr->e_shnum)
2454                         return -ENOEXEC;
2455
2456                 section = &sechdrs[sechdrs[i].sh_info];
2457                 symtab = &sechdrs[sechdrs[i].sh_link];
2458
2459                 if (!(section->sh_flags & SHF_ALLOC))
2460                         continue;
2461
2462                 /*
2463                  * symtab->sh_link contain section header index of associated
2464                  * string table.
2465                  */
2466                 if (symtab->sh_link >= pi->ehdr->e_shnum)
2467                         /* Invalid section number? */
2468                         continue;
2469
2470                 /*
2471                  * Respective archicture needs to provide support for applying
2472                  * relocations of type SHT_RELA/SHT_REL.
2473                  */
2474                 if (sechdrs[i].sh_type == SHT_RELA)
2475                         ret = arch_kexec_apply_relocations_add(pi->ehdr,
2476                                                                sechdrs, i);
2477                 else if (sechdrs[i].sh_type == SHT_REL)
2478                         ret = arch_kexec_apply_relocations(pi->ehdr,
2479                                                            sechdrs, i);
2480                 if (ret)
2481                         return ret;
2482         }
2483
2484         return 0;
2485 }
2486
2487 /* Load relocatable purgatory object and relocate it appropriately */
2488 int kexec_load_purgatory(struct kimage *image, unsigned long min,
2489                          unsigned long max, int top_down,
2490                          unsigned long *load_addr)
2491 {
2492         struct purgatory_info *pi = &image->purgatory_info;
2493         int ret;
2494
2495         if (kexec_purgatory_size <= 0)
2496                 return -EINVAL;
2497
2498         if (kexec_purgatory_size < sizeof(Elf_Ehdr))
2499                 return -ENOEXEC;
2500
2501         pi->ehdr = (Elf_Ehdr *)kexec_purgatory;
2502
2503         if (memcmp(pi->ehdr->e_ident, ELFMAG, SELFMAG) != 0
2504             || pi->ehdr->e_type != ET_REL
2505             || !elf_check_arch(pi->ehdr)
2506             || pi->ehdr->e_shentsize != sizeof(Elf_Shdr))
2507                 return -ENOEXEC;
2508
2509         if (pi->ehdr->e_shoff >= kexec_purgatory_size
2510             || (pi->ehdr->e_shnum * sizeof(Elf_Shdr) >
2511             kexec_purgatory_size - pi->ehdr->e_shoff))
2512                 return -ENOEXEC;
2513
2514         ret = __kexec_load_purgatory(image, min, max, top_down);
2515         if (ret)
2516                 return ret;
2517
2518         ret = kexec_apply_relocations(image);
2519         if (ret)
2520                 goto out;
2521
2522         *load_addr = pi->purgatory_load_addr;
2523         return 0;
2524 out:
2525         vfree(pi->sechdrs);
2526         vfree(pi->purgatory_buf);
2527         return ret;
2528 }
2529
2530 static Elf_Sym *kexec_purgatory_find_symbol(struct purgatory_info *pi,
2531                                             const char *name)
2532 {
2533         Elf_Sym *syms;
2534         Elf_Shdr *sechdrs;
2535         Elf_Ehdr *ehdr;
2536         int i, k;
2537         const char *strtab;
2538
2539         if (!pi->sechdrs || !pi->ehdr)
2540                 return NULL;
2541
2542         sechdrs = pi->sechdrs;
2543         ehdr = pi->ehdr;
2544
2545         for (i = 0; i < ehdr->e_shnum; i++) {
2546                 if (sechdrs[i].sh_type != SHT_SYMTAB)
2547                         continue;
2548
2549                 if (sechdrs[i].sh_link >= ehdr->e_shnum)
2550                         /* Invalid strtab section number */
2551                         continue;
2552                 strtab = (char *)sechdrs[sechdrs[i].sh_link].sh_offset;
2553                 syms = (Elf_Sym *)sechdrs[i].sh_offset;
2554
2555                 /* Go through symbols for a match */
2556                 for (k = 0; k < sechdrs[i].sh_size/sizeof(Elf_Sym); k++) {
2557                         if (ELF_ST_BIND(syms[k].st_info) != STB_GLOBAL)
2558                                 continue;
2559
2560                         if (strcmp(strtab + syms[k].st_name, name) != 0)
2561                                 continue;
2562
2563                         if (syms[k].st_shndx == SHN_UNDEF ||
2564                             syms[k].st_shndx >= ehdr->e_shnum) {
2565                                 pr_debug("Symbol: %s has bad section index %d.\n",
2566                                                 name, syms[k].st_shndx);
2567                                 return NULL;
2568                         }
2569
2570                         /* Found the symbol we are looking for */
2571                         return &syms[k];
2572                 }
2573         }
2574
2575         return NULL;
2576 }
2577
2578 void *kexec_purgatory_get_symbol_addr(struct kimage *image, const char *name)
2579 {
2580         struct purgatory_info *pi = &image->purgatory_info;
2581         Elf_Sym *sym;
2582         Elf_Shdr *sechdr;
2583
2584         sym = kexec_purgatory_find_symbol(pi, name);
2585         if (!sym)
2586                 return ERR_PTR(-EINVAL);
2587
2588         sechdr = &pi->sechdrs[sym->st_shndx];
2589
2590         /*
2591          * Returns the address where symbol will finally be loaded after
2592          * kexec_load_segment()
2593          */
2594         return (void *)(sechdr->sh_addr + sym->st_value);
2595 }
2596
2597 /*
2598  * Get or set value of a symbol. If "get_value" is true, symbol value is
2599  * returned in buf otherwise symbol value is set based on value in buf.
2600  */
2601 int kexec_purgatory_get_set_symbol(struct kimage *image, const char *name,
2602                                    void *buf, unsigned int size, bool get_value)
2603 {
2604         Elf_Sym *sym;
2605         Elf_Shdr *sechdrs;
2606         struct purgatory_info *pi = &image->purgatory_info;
2607         char *sym_buf;
2608
2609         sym = kexec_purgatory_find_symbol(pi, name);
2610         if (!sym)
2611                 return -EINVAL;
2612
2613         if (sym->st_size != size) {
2614                 pr_err("symbol %s size mismatch: expected %lu actual %u\n",
2615                        name, (unsigned long)sym->st_size, size);
2616                 return -EINVAL;
2617         }
2618
2619         sechdrs = pi->sechdrs;
2620
2621         if (sechdrs[sym->st_shndx].sh_type == SHT_NOBITS) {
2622                 pr_err("symbol %s is in a bss section. Cannot %s\n", name,
2623                        get_value ? "get" : "set");
2624                 return -EINVAL;
2625         }
2626
2627         sym_buf = (unsigned char *)sechdrs[sym->st_shndx].sh_offset +
2628                                         sym->st_value;
2629
2630         if (get_value)
2631                 memcpy((void *)buf, sym_buf, size);
2632         else
2633                 memcpy((void *)sym_buf, buf, size);
2634
2635         return 0;
2636 }
2637
2638 /*
2639  * Move into place and start executing a preloaded standalone
2640  * executable.  If nothing was preloaded return an error.
2641  */
2642 int kernel_kexec(void)
2643 {
2644         int error = 0;
2645
2646         if (!mutex_trylock(&kexec_mutex))
2647                 return -EBUSY;
2648         if (!kexec_image) {
2649                 error = -EINVAL;
2650                 goto Unlock;
2651         }
2652
2653 #ifdef CONFIG_KEXEC_JUMP
2654         if (kexec_image->preserve_context) {
2655                 lock_system_sleep();
2656                 pm_prepare_console();
2657                 error = freeze_processes();
2658                 if (error) {
2659                         error = -EBUSY;
2660                         goto Restore_console;
2661                 }
2662                 suspend_console();
2663                 error = dpm_suspend_start(PMSG_FREEZE);
2664                 if (error)
2665                         goto Resume_console;
2666                 /* At this point, dpm_suspend_start() has been called,
2667                  * but *not* dpm_suspend_end(). We *must* call
2668                  * dpm_suspend_end() now.  Otherwise, drivers for
2669                  * some devices (e.g. interrupt controllers) become
2670                  * desynchronized with the actual state of the
2671                  * hardware at resume time, and evil weirdness ensues.
2672                  */
2673                 error = dpm_suspend_end(PMSG_FREEZE);
2674                 if (error)
2675                         goto Resume_devices;
2676                 error = disable_nonboot_cpus();
2677                 if (error)
2678                         goto Enable_cpus;
2679                 local_irq_disable();
2680                 error = syscore_suspend();
2681                 if (error)
2682                         goto Enable_irqs;
2683         } else
2684 #endif
2685         {
2686                 kexec_in_progress = true;
2687                 kernel_restart_prepare(NULL);
2688                 migrate_to_reboot_cpu();
2689
2690                 /*
2691                  * migrate_to_reboot_cpu() disables CPU hotplug assuming that
2692                  * no further code needs to use CPU hotplug (which is true in
2693                  * the reboot case). However, the kexec path depends on using
2694                  * CPU hotplug again; so re-enable it here.
2695                  */
2696                 cpu_hotplug_enable();
2697                 pr_emerg("Starting new kernel\n");
2698                 machine_shutdown();
2699         }
2700
2701         machine_kexec(kexec_image);
2702
2703 #ifdef CONFIG_KEXEC_JUMP
2704         if (kexec_image->preserve_context) {
2705                 syscore_resume();
2706  Enable_irqs:
2707                 local_irq_enable();
2708  Enable_cpus:
2709                 enable_nonboot_cpus();
2710                 dpm_resume_start(PMSG_RESTORE);
2711  Resume_devices:
2712                 dpm_resume_end(PMSG_RESTORE);
2713  Resume_console:
2714                 resume_console();
2715                 thaw_processes();
2716  Restore_console:
2717                 pm_restore_console();
2718                 unlock_system_sleep();
2719         }
2720 #endif
2721
2722  Unlock:
2723         mutex_unlock(&kexec_mutex);
2724         return error;
2725 }