kexec: split kexec_file syscall code to kexec_file.c
[platform/kernel/linux-rpi.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/vmalloc.h>
32 #include <linux/pm.h>
33 #include <linux/cpu.h>
34 #include <linux/console.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 #include "kexec_internal.h"
48
49 DEFINE_MUTEX(kexec_mutex);
50
51 /* Per cpu memory for storing cpu states in case of system crash. */
52 note_buf_t __percpu *crash_notes;
53
54 /* vmcoreinfo stuff */
55 static unsigned char vmcoreinfo_data[VMCOREINFO_BYTES];
56 u32 vmcoreinfo_note[VMCOREINFO_NOTE_SIZE/4];
57 size_t vmcoreinfo_size;
58 size_t vmcoreinfo_max_size = sizeof(vmcoreinfo_data);
59
60 /* Flag to indicate we are going to kexec a new kernel */
61 bool kexec_in_progress = false;
62
63
64 /* Location of the reserved area for the crash kernel */
65 struct resource crashk_res = {
66         .name  = "Crash kernel",
67         .start = 0,
68         .end   = 0,
69         .flags = IORESOURCE_BUSY | IORESOURCE_MEM
70 };
71 struct resource crashk_low_res = {
72         .name  = "Crash kernel",
73         .start = 0,
74         .end   = 0,
75         .flags = IORESOURCE_BUSY | IORESOURCE_MEM
76 };
77
78 int kexec_should_crash(struct task_struct *p)
79 {
80         /*
81          * If crash_kexec_post_notifiers is enabled, don't run
82          * crash_kexec() here yet, which must be run after panic
83          * notifiers in panic().
84          */
85         if (crash_kexec_post_notifiers)
86                 return 0;
87         /*
88          * There are 4 panic() calls in do_exit() path, each of which
89          * corresponds to each of these 4 conditions.
90          */
91         if (in_interrupt() || !p->pid || is_global_init(p) || panic_on_oops)
92                 return 1;
93         return 0;
94 }
95
96 /*
97  * When kexec transitions to the new kernel there is a one-to-one
98  * mapping between physical and virtual addresses.  On processors
99  * where you can disable the MMU this is trivial, and easy.  For
100  * others it is still a simple predictable page table to setup.
101  *
102  * In that environment kexec copies the new kernel to its final
103  * resting place.  This means I can only support memory whose
104  * physical address can fit in an unsigned long.  In particular
105  * addresses where (pfn << PAGE_SHIFT) > ULONG_MAX cannot be handled.
106  * If the assembly stub has more restrictive requirements
107  * KEXEC_SOURCE_MEMORY_LIMIT and KEXEC_DEST_MEMORY_LIMIT can be
108  * defined more restrictively in <asm/kexec.h>.
109  *
110  * The code for the transition from the current kernel to the
111  * the new kernel is placed in the control_code_buffer, whose size
112  * is given by KEXEC_CONTROL_PAGE_SIZE.  In the best case only a single
113  * page of memory is necessary, but some architectures require more.
114  * Because this memory must be identity mapped in the transition from
115  * virtual to physical addresses it must live in the range
116  * 0 - TASK_SIZE, as only the user space mappings are arbitrarily
117  * modifiable.
118  *
119  * The assembly stub in the control code buffer is passed a linked list
120  * of descriptor pages detailing the source pages of the new kernel,
121  * and the destination addresses of those source pages.  As this data
122  * structure is not used in the context of the current OS, it must
123  * be self-contained.
124  *
125  * The code has been made to work with highmem pages and will use a
126  * destination page in its final resting place (if it happens
127  * to allocate it).  The end product of this is that most of the
128  * physical address space, and most of RAM can be used.
129  *
130  * Future directions include:
131  *  - allocating a page table with the control code buffer identity
132  *    mapped, to simplify machine_kexec and make kexec_on_panic more
133  *    reliable.
134  */
135
136 /*
137  * KIMAGE_NO_DEST is an impossible destination address..., for
138  * allocating pages whose destination address we do not care about.
139  */
140 #define KIMAGE_NO_DEST (-1UL)
141
142 static struct page *kimage_alloc_page(struct kimage *image,
143                                        gfp_t gfp_mask,
144                                        unsigned long dest);
145
146 static int copy_user_segment_list(struct kimage *image,
147                                   unsigned long nr_segments,
148                                   struct kexec_segment __user *segments)
149 {
150         int ret;
151         size_t segment_bytes;
152
153         /* Read in the segments */
154         image->nr_segments = nr_segments;
155         segment_bytes = nr_segments * sizeof(*segments);
156         ret = copy_from_user(image->segment, segments, segment_bytes);
157         if (ret)
158                 ret = -EFAULT;
159
160         return ret;
161 }
162
163 int sanity_check_segment_list(struct kimage *image)
164 {
165         int result, i;
166         unsigned long nr_segments = image->nr_segments;
167
168         /*
169          * Verify we have good destination addresses.  The caller is
170          * responsible for making certain we don't attempt to load
171          * the new image into invalid or reserved areas of RAM.  This
172          * just verifies it is an address we can use.
173          *
174          * Since the kernel does everything in page size chunks ensure
175          * the destination addresses are page aligned.  Too many
176          * special cases crop of when we don't do this.  The most
177          * insidious is getting overlapping destination addresses
178          * simply because addresses are changed to page size
179          * granularity.
180          */
181         result = -EADDRNOTAVAIL;
182         for (i = 0; i < nr_segments; i++) {
183                 unsigned long mstart, mend;
184
185                 mstart = image->segment[i].mem;
186                 mend   = mstart + image->segment[i].memsz;
187                 if ((mstart & ~PAGE_MASK) || (mend & ~PAGE_MASK))
188                         return result;
189                 if (mend >= KEXEC_DESTINATION_MEMORY_LIMIT)
190                         return result;
191         }
192
193         /* Verify our destination addresses do not overlap.
194          * If we alloed overlapping destination addresses
195          * through very weird things can happen with no
196          * easy explanation as one segment stops on another.
197          */
198         result = -EINVAL;
199         for (i = 0; i < nr_segments; i++) {
200                 unsigned long mstart, mend;
201                 unsigned long j;
202
203                 mstart = image->segment[i].mem;
204                 mend   = mstart + image->segment[i].memsz;
205                 for (j = 0; j < i; j++) {
206                         unsigned long pstart, pend;
207                         pstart = image->segment[j].mem;
208                         pend   = pstart + image->segment[j].memsz;
209                         /* Do the segments overlap ? */
210                         if ((mend > pstart) && (mstart < pend))
211                                 return result;
212                 }
213         }
214
215         /* Ensure our buffer sizes are strictly less than
216          * our memory sizes.  This should always be the case,
217          * and it is easier to check up front than to be surprised
218          * later on.
219          */
220         result = -EINVAL;
221         for (i = 0; i < nr_segments; i++) {
222                 if (image->segment[i].bufsz > image->segment[i].memsz)
223                         return result;
224         }
225
226         /*
227          * Verify we have good destination addresses.  Normally
228          * the caller is responsible for making certain we don't
229          * attempt to load the new image into invalid or reserved
230          * areas of RAM.  But crash kernels are preloaded into a
231          * reserved area of ram.  We must ensure the addresses
232          * are in the reserved area otherwise preloading the
233          * kernel could corrupt things.
234          */
235
236         if (image->type == KEXEC_TYPE_CRASH) {
237                 result = -EADDRNOTAVAIL;
238                 for (i = 0; i < nr_segments; i++) {
239                         unsigned long mstart, mend;
240
241                         mstart = image->segment[i].mem;
242                         mend = mstart + image->segment[i].memsz - 1;
243                         /* Ensure we are within the crash kernel limits */
244                         if ((mstart < crashk_res.start) ||
245                             (mend > crashk_res.end))
246                                 return result;
247                 }
248         }
249
250         return 0;
251 }
252
253 struct kimage *do_kimage_alloc_init(void)
254 {
255         struct kimage *image;
256
257         /* Allocate a controlling structure */
258         image = kzalloc(sizeof(*image), GFP_KERNEL);
259         if (!image)
260                 return NULL;
261
262         image->head = 0;
263         image->entry = &image->head;
264         image->last_entry = &image->head;
265         image->control_page = ~0; /* By default this does not apply */
266         image->type = KEXEC_TYPE_DEFAULT;
267
268         /* Initialize the list of control pages */
269         INIT_LIST_HEAD(&image->control_pages);
270
271         /* Initialize the list of destination pages */
272         INIT_LIST_HEAD(&image->dest_pages);
273
274         /* Initialize the list of unusable pages */
275         INIT_LIST_HEAD(&image->unusable_pages);
276
277         return image;
278 }
279
280 static int kimage_alloc_init(struct kimage **rimage, unsigned long entry,
281                              unsigned long nr_segments,
282                              struct kexec_segment __user *segments,
283                              unsigned long flags)
284 {
285         int ret;
286         struct kimage *image;
287         bool kexec_on_panic = flags & KEXEC_ON_CRASH;
288
289         if (kexec_on_panic) {
290                 /* Verify we have a valid entry point */
291                 if ((entry < crashk_res.start) || (entry > crashk_res.end))
292                         return -EADDRNOTAVAIL;
293         }
294
295         /* Allocate and initialize a controlling structure */
296         image = do_kimage_alloc_init();
297         if (!image)
298                 return -ENOMEM;
299
300         image->start = entry;
301
302         ret = copy_user_segment_list(image, nr_segments, segments);
303         if (ret)
304                 goto out_free_image;
305
306         ret = sanity_check_segment_list(image);
307         if (ret)
308                 goto out_free_image;
309
310          /* Enable the special crash kernel control page allocation policy. */
311         if (kexec_on_panic) {
312                 image->control_page = crashk_res.start;
313                 image->type = KEXEC_TYPE_CRASH;
314         }
315
316         /*
317          * Find a location for the control code buffer, and add it
318          * the vector of segments so that it's pages will also be
319          * counted as destination pages.
320          */
321         ret = -ENOMEM;
322         image->control_code_page = kimage_alloc_control_pages(image,
323                                            get_order(KEXEC_CONTROL_PAGE_SIZE));
324         if (!image->control_code_page) {
325                 pr_err("Could not allocate control_code_buffer\n");
326                 goto out_free_image;
327         }
328
329         if (!kexec_on_panic) {
330                 image->swap_page = kimage_alloc_control_pages(image, 0);
331                 if (!image->swap_page) {
332                         pr_err("Could not allocate swap buffer\n");
333                         goto out_free_control_pages;
334                 }
335         }
336
337         *rimage = image;
338         return 0;
339 out_free_control_pages:
340         kimage_free_page_list(&image->control_pages);
341 out_free_image:
342         kfree(image);
343         return ret;
344 }
345
346 int kimage_is_destination_range(struct kimage *image,
347                                         unsigned long start,
348                                         unsigned long end)
349 {
350         unsigned long i;
351
352         for (i = 0; i < image->nr_segments; i++) {
353                 unsigned long mstart, mend;
354
355                 mstart = image->segment[i].mem;
356                 mend = mstart + image->segment[i].memsz;
357                 if ((end > mstart) && (start < mend))
358                         return 1;
359         }
360
361         return 0;
362 }
363
364 static struct page *kimage_alloc_pages(gfp_t gfp_mask, unsigned int order)
365 {
366         struct page *pages;
367
368         pages = alloc_pages(gfp_mask, order);
369         if (pages) {
370                 unsigned int count, i;
371                 pages->mapping = NULL;
372                 set_page_private(pages, order);
373                 count = 1 << order;
374                 for (i = 0; i < count; i++)
375                         SetPageReserved(pages + i);
376         }
377
378         return pages;
379 }
380
381 static void kimage_free_pages(struct page *page)
382 {
383         unsigned int order, count, i;
384
385         order = page_private(page);
386         count = 1 << order;
387         for (i = 0; i < count; i++)
388                 ClearPageReserved(page + i);
389         __free_pages(page, order);
390 }
391
392 void kimage_free_page_list(struct list_head *list)
393 {
394         struct list_head *pos, *next;
395
396         list_for_each_safe(pos, next, list) {
397                 struct page *page;
398
399                 page = list_entry(pos, struct page, lru);
400                 list_del(&page->lru);
401                 kimage_free_pages(page);
402         }
403 }
404
405 static struct page *kimage_alloc_normal_control_pages(struct kimage *image,
406                                                         unsigned int order)
407 {
408         /* Control pages are special, they are the intermediaries
409          * that are needed while we copy the rest of the pages
410          * to their final resting place.  As such they must
411          * not conflict with either the destination addresses
412          * or memory the kernel is already using.
413          *
414          * The only case where we really need more than one of
415          * these are for architectures where we cannot disable
416          * the MMU and must instead generate an identity mapped
417          * page table for all of the memory.
418          *
419          * At worst this runs in O(N) of the image size.
420          */
421         struct list_head extra_pages;
422         struct page *pages;
423         unsigned int count;
424
425         count = 1 << order;
426         INIT_LIST_HEAD(&extra_pages);
427
428         /* Loop while I can allocate a page and the page allocated
429          * is a destination page.
430          */
431         do {
432                 unsigned long pfn, epfn, addr, eaddr;
433
434                 pages = kimage_alloc_pages(KEXEC_CONTROL_MEMORY_GFP, order);
435                 if (!pages)
436                         break;
437                 pfn   = page_to_pfn(pages);
438                 epfn  = pfn + count;
439                 addr  = pfn << PAGE_SHIFT;
440                 eaddr = epfn << PAGE_SHIFT;
441                 if ((epfn >= (KEXEC_CONTROL_MEMORY_LIMIT >> PAGE_SHIFT)) ||
442                               kimage_is_destination_range(image, addr, eaddr)) {
443                         list_add(&pages->lru, &extra_pages);
444                         pages = NULL;
445                 }
446         } while (!pages);
447
448         if (pages) {
449                 /* Remember the allocated page... */
450                 list_add(&pages->lru, &image->control_pages);
451
452                 /* Because the page is already in it's destination
453                  * location we will never allocate another page at
454                  * that address.  Therefore kimage_alloc_pages
455                  * will not return it (again) and we don't need
456                  * to give it an entry in image->segment[].
457                  */
458         }
459         /* Deal with the destination pages I have inadvertently allocated.
460          *
461          * Ideally I would convert multi-page allocations into single
462          * page allocations, and add everything to image->dest_pages.
463          *
464          * For now it is simpler to just free the pages.
465          */
466         kimage_free_page_list(&extra_pages);
467
468         return pages;
469 }
470
471 static struct page *kimage_alloc_crash_control_pages(struct kimage *image,
472                                                       unsigned int order)
473 {
474         /* Control pages are special, they are the intermediaries
475          * that are needed while we copy the rest of the pages
476          * to their final resting place.  As such they must
477          * not conflict with either the destination addresses
478          * or memory the kernel is already using.
479          *
480          * Control pages are also the only pags we must allocate
481          * when loading a crash kernel.  All of the other pages
482          * are specified by the segments and we just memcpy
483          * into them directly.
484          *
485          * The only case where we really need more than one of
486          * these are for architectures where we cannot disable
487          * the MMU and must instead generate an identity mapped
488          * page table for all of the memory.
489          *
490          * Given the low demand this implements a very simple
491          * allocator that finds the first hole of the appropriate
492          * size in the reserved memory region, and allocates all
493          * of the memory up to and including the hole.
494          */
495         unsigned long hole_start, hole_end, size;
496         struct page *pages;
497
498         pages = NULL;
499         size = (1 << order) << PAGE_SHIFT;
500         hole_start = (image->control_page + (size - 1)) & ~(size - 1);
501         hole_end   = hole_start + size - 1;
502         while (hole_end <= crashk_res.end) {
503                 unsigned long i;
504
505                 if (hole_end > KEXEC_CRASH_CONTROL_MEMORY_LIMIT)
506                         break;
507                 /* See if I overlap any of the segments */
508                 for (i = 0; i < image->nr_segments; i++) {
509                         unsigned long mstart, mend;
510
511                         mstart = image->segment[i].mem;
512                         mend   = mstart + image->segment[i].memsz - 1;
513                         if ((hole_end >= mstart) && (hole_start <= mend)) {
514                                 /* Advance the hole to the end of the segment */
515                                 hole_start = (mend + (size - 1)) & ~(size - 1);
516                                 hole_end   = hole_start + size - 1;
517                                 break;
518                         }
519                 }
520                 /* If I don't overlap any segments I have found my hole! */
521                 if (i == image->nr_segments) {
522                         pages = pfn_to_page(hole_start >> PAGE_SHIFT);
523                         break;
524                 }
525         }
526         if (pages)
527                 image->control_page = hole_end;
528
529         return pages;
530 }
531
532
533 struct page *kimage_alloc_control_pages(struct kimage *image,
534                                          unsigned int order)
535 {
536         struct page *pages = NULL;
537
538         switch (image->type) {
539         case KEXEC_TYPE_DEFAULT:
540                 pages = kimage_alloc_normal_control_pages(image, order);
541                 break;
542         case KEXEC_TYPE_CRASH:
543                 pages = kimage_alloc_crash_control_pages(image, order);
544                 break;
545         }
546
547         return pages;
548 }
549
550 static int kimage_add_entry(struct kimage *image, kimage_entry_t entry)
551 {
552         if (*image->entry != 0)
553                 image->entry++;
554
555         if (image->entry == image->last_entry) {
556                 kimage_entry_t *ind_page;
557                 struct page *page;
558
559                 page = kimage_alloc_page(image, GFP_KERNEL, KIMAGE_NO_DEST);
560                 if (!page)
561                         return -ENOMEM;
562
563                 ind_page = page_address(page);
564                 *image->entry = virt_to_phys(ind_page) | IND_INDIRECTION;
565                 image->entry = ind_page;
566                 image->last_entry = ind_page +
567                                       ((PAGE_SIZE/sizeof(kimage_entry_t)) - 1);
568         }
569         *image->entry = entry;
570         image->entry++;
571         *image->entry = 0;
572
573         return 0;
574 }
575
576 static int kimage_set_destination(struct kimage *image,
577                                    unsigned long destination)
578 {
579         int result;
580
581         destination &= PAGE_MASK;
582         result = kimage_add_entry(image, destination | IND_DESTINATION);
583
584         return result;
585 }
586
587
588 static int kimage_add_page(struct kimage *image, unsigned long page)
589 {
590         int result;
591
592         page &= PAGE_MASK;
593         result = kimage_add_entry(image, page | IND_SOURCE);
594
595         return result;
596 }
597
598
599 static void kimage_free_extra_pages(struct kimage *image)
600 {
601         /* Walk through and free any extra destination pages I may have */
602         kimage_free_page_list(&image->dest_pages);
603
604         /* Walk through and free any unusable pages I have cached */
605         kimage_free_page_list(&image->unusable_pages);
606
607 }
608 void kimage_terminate(struct kimage *image)
609 {
610         if (*image->entry != 0)
611                 image->entry++;
612
613         *image->entry = IND_DONE;
614 }
615
616 #define for_each_kimage_entry(image, ptr, entry) \
617         for (ptr = &image->head; (entry = *ptr) && !(entry & IND_DONE); \
618                 ptr = (entry & IND_INDIRECTION) ? \
619                         phys_to_virt((entry & PAGE_MASK)) : ptr + 1)
620
621 static void kimage_free_entry(kimage_entry_t entry)
622 {
623         struct page *page;
624
625         page = pfn_to_page(entry >> PAGE_SHIFT);
626         kimage_free_pages(page);
627 }
628
629 void kimage_free(struct kimage *image)
630 {
631         kimage_entry_t *ptr, entry;
632         kimage_entry_t ind = 0;
633
634         if (!image)
635                 return;
636
637         kimage_free_extra_pages(image);
638         for_each_kimage_entry(image, ptr, entry) {
639                 if (entry & IND_INDIRECTION) {
640                         /* Free the previous indirection page */
641                         if (ind & IND_INDIRECTION)
642                                 kimage_free_entry(ind);
643                         /* Save this indirection page until we are
644                          * done with it.
645                          */
646                         ind = entry;
647                 } else if (entry & IND_SOURCE)
648                         kimage_free_entry(entry);
649         }
650         /* Free the final indirection page */
651         if (ind & IND_INDIRECTION)
652                 kimage_free_entry(ind);
653
654         /* Handle any machine specific cleanup */
655         machine_kexec_cleanup(image);
656
657         /* Free the kexec control pages... */
658         kimage_free_page_list(&image->control_pages);
659
660         /*
661          * Free up any temporary buffers allocated. This might hit if
662          * error occurred much later after buffer allocation.
663          */
664         if (image->file_mode)
665                 kimage_file_post_load_cleanup(image);
666
667         kfree(image);
668 }
669
670 static kimage_entry_t *kimage_dst_used(struct kimage *image,
671                                         unsigned long page)
672 {
673         kimage_entry_t *ptr, entry;
674         unsigned long destination = 0;
675
676         for_each_kimage_entry(image, ptr, entry) {
677                 if (entry & IND_DESTINATION)
678                         destination = entry & PAGE_MASK;
679                 else if (entry & IND_SOURCE) {
680                         if (page == destination)
681                                 return ptr;
682                         destination += PAGE_SIZE;
683                 }
684         }
685
686         return NULL;
687 }
688
689 static struct page *kimage_alloc_page(struct kimage *image,
690                                         gfp_t gfp_mask,
691                                         unsigned long destination)
692 {
693         /*
694          * Here we implement safeguards to ensure that a source page
695          * is not copied to its destination page before the data on
696          * the destination page is no longer useful.
697          *
698          * To do this we maintain the invariant that a source page is
699          * either its own destination page, or it is not a
700          * destination page at all.
701          *
702          * That is slightly stronger than required, but the proof
703          * that no problems will not occur is trivial, and the
704          * implementation is simply to verify.
705          *
706          * When allocating all pages normally this algorithm will run
707          * in O(N) time, but in the worst case it will run in O(N^2)
708          * time.   If the runtime is a problem the data structures can
709          * be fixed.
710          */
711         struct page *page;
712         unsigned long addr;
713
714         /*
715          * Walk through the list of destination pages, and see if I
716          * have a match.
717          */
718         list_for_each_entry(page, &image->dest_pages, lru) {
719                 addr = page_to_pfn(page) << PAGE_SHIFT;
720                 if (addr == destination) {
721                         list_del(&page->lru);
722                         return page;
723                 }
724         }
725         page = NULL;
726         while (1) {
727                 kimage_entry_t *old;
728
729                 /* Allocate a page, if we run out of memory give up */
730                 page = kimage_alloc_pages(gfp_mask, 0);
731                 if (!page)
732                         return NULL;
733                 /* If the page cannot be used file it away */
734                 if (page_to_pfn(page) >
735                                 (KEXEC_SOURCE_MEMORY_LIMIT >> PAGE_SHIFT)) {
736                         list_add(&page->lru, &image->unusable_pages);
737                         continue;
738                 }
739                 addr = page_to_pfn(page) << PAGE_SHIFT;
740
741                 /* If it is the destination page we want use it */
742                 if (addr == destination)
743                         break;
744
745                 /* If the page is not a destination page use it */
746                 if (!kimage_is_destination_range(image, addr,
747                                                   addr + PAGE_SIZE))
748                         break;
749
750                 /*
751                  * I know that the page is someones destination page.
752                  * See if there is already a source page for this
753                  * destination page.  And if so swap the source pages.
754                  */
755                 old = kimage_dst_used(image, addr);
756                 if (old) {
757                         /* If so move it */
758                         unsigned long old_addr;
759                         struct page *old_page;
760
761                         old_addr = *old & PAGE_MASK;
762                         old_page = pfn_to_page(old_addr >> PAGE_SHIFT);
763                         copy_highpage(page, old_page);
764                         *old = addr | (*old & ~PAGE_MASK);
765
766                         /* The old page I have found cannot be a
767                          * destination page, so return it if it's
768                          * gfp_flags honor the ones passed in.
769                          */
770                         if (!(gfp_mask & __GFP_HIGHMEM) &&
771                             PageHighMem(old_page)) {
772                                 kimage_free_pages(old_page);
773                                 continue;
774                         }
775                         addr = old_addr;
776                         page = old_page;
777                         break;
778                 } else {
779                         /* Place the page on the destination list I
780                          * will use it later.
781                          */
782                         list_add(&page->lru, &image->dest_pages);
783                 }
784         }
785
786         return page;
787 }
788
789 static int kimage_load_normal_segment(struct kimage *image,
790                                          struct kexec_segment *segment)
791 {
792         unsigned long maddr;
793         size_t ubytes, mbytes;
794         int result;
795         unsigned char __user *buf = NULL;
796         unsigned char *kbuf = NULL;
797
798         result = 0;
799         if (image->file_mode)
800                 kbuf = segment->kbuf;
801         else
802                 buf = segment->buf;
803         ubytes = segment->bufsz;
804         mbytes = segment->memsz;
805         maddr = segment->mem;
806
807         result = kimage_set_destination(image, maddr);
808         if (result < 0)
809                 goto out;
810
811         while (mbytes) {
812                 struct page *page;
813                 char *ptr;
814                 size_t uchunk, mchunk;
815
816                 page = kimage_alloc_page(image, GFP_HIGHUSER, maddr);
817                 if (!page) {
818                         result  = -ENOMEM;
819                         goto out;
820                 }
821                 result = kimage_add_page(image, page_to_pfn(page)
822                                                                 << PAGE_SHIFT);
823                 if (result < 0)
824                         goto out;
825
826                 ptr = kmap(page);
827                 /* Start with a clear page */
828                 clear_page(ptr);
829                 ptr += maddr & ~PAGE_MASK;
830                 mchunk = min_t(size_t, mbytes,
831                                 PAGE_SIZE - (maddr & ~PAGE_MASK));
832                 uchunk = min(ubytes, mchunk);
833
834                 /* For file based kexec, source pages are in kernel memory */
835                 if (image->file_mode)
836                         memcpy(ptr, kbuf, uchunk);
837                 else
838                         result = copy_from_user(ptr, buf, uchunk);
839                 kunmap(page);
840                 if (result) {
841                         result = -EFAULT;
842                         goto out;
843                 }
844                 ubytes -= uchunk;
845                 maddr  += mchunk;
846                 if (image->file_mode)
847                         kbuf += mchunk;
848                 else
849                         buf += mchunk;
850                 mbytes -= mchunk;
851         }
852 out:
853         return result;
854 }
855
856 static int kimage_load_crash_segment(struct kimage *image,
857                                         struct kexec_segment *segment)
858 {
859         /* For crash dumps kernels we simply copy the data from
860          * user space to it's destination.
861          * We do things a page at a time for the sake of kmap.
862          */
863         unsigned long maddr;
864         size_t ubytes, mbytes;
865         int result;
866         unsigned char __user *buf = NULL;
867         unsigned char *kbuf = NULL;
868
869         result = 0;
870         if (image->file_mode)
871                 kbuf = segment->kbuf;
872         else
873                 buf = segment->buf;
874         ubytes = segment->bufsz;
875         mbytes = segment->memsz;
876         maddr = segment->mem;
877         while (mbytes) {
878                 struct page *page;
879                 char *ptr;
880                 size_t uchunk, mchunk;
881
882                 page = pfn_to_page(maddr >> PAGE_SHIFT);
883                 if (!page) {
884                         result  = -ENOMEM;
885                         goto out;
886                 }
887                 ptr = kmap(page);
888                 ptr += maddr & ~PAGE_MASK;
889                 mchunk = min_t(size_t, mbytes,
890                                 PAGE_SIZE - (maddr & ~PAGE_MASK));
891                 uchunk = min(ubytes, mchunk);
892                 if (mchunk > uchunk) {
893                         /* Zero the trailing part of the page */
894                         memset(ptr + uchunk, 0, mchunk - uchunk);
895                 }
896
897                 /* For file based kexec, source pages are in kernel memory */
898                 if (image->file_mode)
899                         memcpy(ptr, kbuf, uchunk);
900                 else
901                         result = copy_from_user(ptr, buf, uchunk);
902                 kexec_flush_icache_page(page);
903                 kunmap(page);
904                 if (result) {
905                         result = -EFAULT;
906                         goto out;
907                 }
908                 ubytes -= uchunk;
909                 maddr  += mchunk;
910                 if (image->file_mode)
911                         kbuf += mchunk;
912                 else
913                         buf += mchunk;
914                 mbytes -= mchunk;
915         }
916 out:
917         return result;
918 }
919
920 int kimage_load_segment(struct kimage *image,
921                                 struct kexec_segment *segment)
922 {
923         int result = -ENOMEM;
924
925         switch (image->type) {
926         case KEXEC_TYPE_DEFAULT:
927                 result = kimage_load_normal_segment(image, segment);
928                 break;
929         case KEXEC_TYPE_CRASH:
930                 result = kimage_load_crash_segment(image, segment);
931                 break;
932         }
933
934         return result;
935 }
936
937 /*
938  * Exec Kernel system call: for obvious reasons only root may call it.
939  *
940  * This call breaks up into three pieces.
941  * - A generic part which loads the new kernel from the current
942  *   address space, and very carefully places the data in the
943  *   allocated pages.
944  *
945  * - A generic part that interacts with the kernel and tells all of
946  *   the devices to shut down.  Preventing on-going dmas, and placing
947  *   the devices in a consistent state so a later kernel can
948  *   reinitialize them.
949  *
950  * - A machine specific part that includes the syscall number
951  *   and then copies the image to it's final destination.  And
952  *   jumps into the image at entry.
953  *
954  * kexec does not sync, or unmount filesystems so if you need
955  * that to happen you need to do that yourself.
956  */
957 struct kimage *kexec_image;
958 struct kimage *kexec_crash_image;
959 int kexec_load_disabled;
960
961 SYSCALL_DEFINE4(kexec_load, unsigned long, entry, unsigned long, nr_segments,
962                 struct kexec_segment __user *, segments, unsigned long, flags)
963 {
964         struct kimage **dest_image, *image;
965         int result;
966
967         /* We only trust the superuser with rebooting the system. */
968         if (!capable(CAP_SYS_BOOT) || kexec_load_disabled)
969                 return -EPERM;
970
971         /*
972          * Verify we have a legal set of flags
973          * This leaves us room for future extensions.
974          */
975         if ((flags & KEXEC_FLAGS) != (flags & ~KEXEC_ARCH_MASK))
976                 return -EINVAL;
977
978         /* Verify we are on the appropriate architecture */
979         if (((flags & KEXEC_ARCH_MASK) != KEXEC_ARCH) &&
980                 ((flags & KEXEC_ARCH_MASK) != KEXEC_ARCH_DEFAULT))
981                 return -EINVAL;
982
983         /* Put an artificial cap on the number
984          * of segments passed to kexec_load.
985          */
986         if (nr_segments > KEXEC_SEGMENT_MAX)
987                 return -EINVAL;
988
989         image = NULL;
990         result = 0;
991
992         /* Because we write directly to the reserved memory
993          * region when loading crash kernels we need a mutex here to
994          * prevent multiple crash  kernels from attempting to load
995          * simultaneously, and to prevent a crash kernel from loading
996          * over the top of a in use crash kernel.
997          *
998          * KISS: always take the mutex.
999          */
1000         if (!mutex_trylock(&kexec_mutex))
1001                 return -EBUSY;
1002
1003         dest_image = &kexec_image;
1004         if (flags & KEXEC_ON_CRASH)
1005                 dest_image = &kexec_crash_image;
1006         if (nr_segments > 0) {
1007                 unsigned long i;
1008
1009                 if (flags & KEXEC_ON_CRASH) {
1010                         /*
1011                          * Loading another kernel to switch to if this one
1012                          * crashes.  Free any current crash dump kernel before
1013                          * we corrupt it.
1014                          */
1015
1016                         kimage_free(xchg(&kexec_crash_image, NULL));
1017                         result = kimage_alloc_init(&image, entry, nr_segments,
1018                                                    segments, flags);
1019                         crash_map_reserved_pages();
1020                 } else {
1021                         /* Loading another kernel to reboot into. */
1022
1023                         result = kimage_alloc_init(&image, entry, nr_segments,
1024                                                    segments, flags);
1025                 }
1026                 if (result)
1027                         goto out;
1028
1029                 if (flags & KEXEC_PRESERVE_CONTEXT)
1030                         image->preserve_context = 1;
1031                 result = machine_kexec_prepare(image);
1032                 if (result)
1033                         goto out;
1034
1035                 for (i = 0; i < nr_segments; i++) {
1036                         result = kimage_load_segment(image, &image->segment[i]);
1037                         if (result)
1038                                 goto out;
1039                 }
1040                 kimage_terminate(image);
1041                 if (flags & KEXEC_ON_CRASH)
1042                         crash_unmap_reserved_pages();
1043         }
1044         /* Install the new kernel, and  Uninstall the old */
1045         image = xchg(dest_image, image);
1046
1047 out:
1048         mutex_unlock(&kexec_mutex);
1049         kimage_free(image);
1050
1051         return result;
1052 }
1053
1054 /*
1055  * Add and remove page tables for crashkernel memory
1056  *
1057  * Provide an empty default implementation here -- architecture
1058  * code may override this
1059  */
1060 void __weak crash_map_reserved_pages(void)
1061 {}
1062
1063 void __weak crash_unmap_reserved_pages(void)
1064 {}
1065
1066 #ifdef CONFIG_COMPAT
1067 COMPAT_SYSCALL_DEFINE4(kexec_load, compat_ulong_t, entry,
1068                        compat_ulong_t, nr_segments,
1069                        struct compat_kexec_segment __user *, segments,
1070                        compat_ulong_t, flags)
1071 {
1072         struct compat_kexec_segment in;
1073         struct kexec_segment out, __user *ksegments;
1074         unsigned long i, result;
1075
1076         /* Don't allow clients that don't understand the native
1077          * architecture to do anything.
1078          */
1079         if ((flags & KEXEC_ARCH_MASK) == KEXEC_ARCH_DEFAULT)
1080                 return -EINVAL;
1081
1082         if (nr_segments > KEXEC_SEGMENT_MAX)
1083                 return -EINVAL;
1084
1085         ksegments = compat_alloc_user_space(nr_segments * sizeof(out));
1086         for (i = 0; i < nr_segments; i++) {
1087                 result = copy_from_user(&in, &segments[i], sizeof(in));
1088                 if (result)
1089                         return -EFAULT;
1090
1091                 out.buf   = compat_ptr(in.buf);
1092                 out.bufsz = in.bufsz;
1093                 out.mem   = in.mem;
1094                 out.memsz = in.memsz;
1095
1096                 result = copy_to_user(&ksegments[i], &out, sizeof(out));
1097                 if (result)
1098                         return -EFAULT;
1099         }
1100
1101         return sys_kexec_load(entry, nr_segments, ksegments, flags);
1102 }
1103 #endif
1104
1105 void crash_kexec(struct pt_regs *regs)
1106 {
1107         /* Take the kexec_mutex here to prevent sys_kexec_load
1108          * running on one cpu from replacing the crash kernel
1109          * we are using after a panic on a different cpu.
1110          *
1111          * If the crash kernel was not located in a fixed area
1112          * of memory the xchg(&kexec_crash_image) would be
1113          * sufficient.  But since I reuse the memory...
1114          */
1115         if (mutex_trylock(&kexec_mutex)) {
1116                 if (kexec_crash_image) {
1117                         struct pt_regs fixed_regs;
1118
1119                         crash_setup_regs(&fixed_regs, regs);
1120                         crash_save_vmcoreinfo();
1121                         machine_crash_shutdown(&fixed_regs);
1122                         machine_kexec(kexec_crash_image);
1123                 }
1124                 mutex_unlock(&kexec_mutex);
1125         }
1126 }
1127
1128 size_t crash_get_memory_size(void)
1129 {
1130         size_t size = 0;
1131         mutex_lock(&kexec_mutex);
1132         if (crashk_res.end != crashk_res.start)
1133                 size = resource_size(&crashk_res);
1134         mutex_unlock(&kexec_mutex);
1135         return size;
1136 }
1137
1138 void __weak crash_free_reserved_phys_range(unsigned long begin,
1139                                            unsigned long end)
1140 {
1141         unsigned long addr;
1142
1143         for (addr = begin; addr < end; addr += PAGE_SIZE)
1144                 free_reserved_page(pfn_to_page(addr >> PAGE_SHIFT));
1145 }
1146
1147 int crash_shrink_memory(unsigned long new_size)
1148 {
1149         int ret = 0;
1150         unsigned long start, end;
1151         unsigned long old_size;
1152         struct resource *ram_res;
1153
1154         mutex_lock(&kexec_mutex);
1155
1156         if (kexec_crash_image) {
1157                 ret = -ENOENT;
1158                 goto unlock;
1159         }
1160         start = crashk_res.start;
1161         end = crashk_res.end;
1162         old_size = (end == 0) ? 0 : end - start + 1;
1163         if (new_size >= old_size) {
1164                 ret = (new_size == old_size) ? 0 : -EINVAL;
1165                 goto unlock;
1166         }
1167
1168         ram_res = kzalloc(sizeof(*ram_res), GFP_KERNEL);
1169         if (!ram_res) {
1170                 ret = -ENOMEM;
1171                 goto unlock;
1172         }
1173
1174         start = roundup(start, KEXEC_CRASH_MEM_ALIGN);
1175         end = roundup(start + new_size, KEXEC_CRASH_MEM_ALIGN);
1176
1177         crash_map_reserved_pages();
1178         crash_free_reserved_phys_range(end, crashk_res.end);
1179
1180         if ((start == end) && (crashk_res.parent != NULL))
1181                 release_resource(&crashk_res);
1182
1183         ram_res->start = end;
1184         ram_res->end = crashk_res.end;
1185         ram_res->flags = IORESOURCE_BUSY | IORESOURCE_MEM;
1186         ram_res->name = "System RAM";
1187
1188         crashk_res.end = end - 1;
1189
1190         insert_resource(&iomem_resource, ram_res);
1191         crash_unmap_reserved_pages();
1192
1193 unlock:
1194         mutex_unlock(&kexec_mutex);
1195         return ret;
1196 }
1197
1198 static u32 *append_elf_note(u32 *buf, char *name, unsigned type, void *data,
1199                             size_t data_len)
1200 {
1201         struct elf_note note;
1202
1203         note.n_namesz = strlen(name) + 1;
1204         note.n_descsz = data_len;
1205         note.n_type   = type;
1206         memcpy(buf, &note, sizeof(note));
1207         buf += (sizeof(note) + 3)/4;
1208         memcpy(buf, name, note.n_namesz);
1209         buf += (note.n_namesz + 3)/4;
1210         memcpy(buf, data, note.n_descsz);
1211         buf += (note.n_descsz + 3)/4;
1212
1213         return buf;
1214 }
1215
1216 static void final_note(u32 *buf)
1217 {
1218         struct elf_note note;
1219
1220         note.n_namesz = 0;
1221         note.n_descsz = 0;
1222         note.n_type   = 0;
1223         memcpy(buf, &note, sizeof(note));
1224 }
1225
1226 void crash_save_cpu(struct pt_regs *regs, int cpu)
1227 {
1228         struct elf_prstatus prstatus;
1229         u32 *buf;
1230
1231         if ((cpu < 0) || (cpu >= nr_cpu_ids))
1232                 return;
1233
1234         /* Using ELF notes here is opportunistic.
1235          * I need a well defined structure format
1236          * for the data I pass, and I need tags
1237          * on the data to indicate what information I have
1238          * squirrelled away.  ELF notes happen to provide
1239          * all of that, so there is no need to invent something new.
1240          */
1241         buf = (u32 *)per_cpu_ptr(crash_notes, cpu);
1242         if (!buf)
1243                 return;
1244         memset(&prstatus, 0, sizeof(prstatus));
1245         prstatus.pr_pid = current->pid;
1246         elf_core_copy_kernel_regs(&prstatus.pr_reg, regs);
1247         buf = append_elf_note(buf, KEXEC_CORE_NOTE_NAME, NT_PRSTATUS,
1248                               &prstatus, sizeof(prstatus));
1249         final_note(buf);
1250 }
1251
1252 static int __init crash_notes_memory_init(void)
1253 {
1254         /* Allocate memory for saving cpu registers. */
1255         crash_notes = alloc_percpu(note_buf_t);
1256         if (!crash_notes) {
1257                 pr_warn("Kexec: Memory allocation for saving cpu register states failed\n");
1258                 return -ENOMEM;
1259         }
1260         return 0;
1261 }
1262 subsys_initcall(crash_notes_memory_init);
1263
1264
1265 /*
1266  * parsing the "crashkernel" commandline
1267  *
1268  * this code is intended to be called from architecture specific code
1269  */
1270
1271
1272 /*
1273  * This function parses command lines in the format
1274  *
1275  *   crashkernel=ramsize-range:size[,...][@offset]
1276  *
1277  * The function returns 0 on success and -EINVAL on failure.
1278  */
1279 static int __init parse_crashkernel_mem(char *cmdline,
1280                                         unsigned long long system_ram,
1281                                         unsigned long long *crash_size,
1282                                         unsigned long long *crash_base)
1283 {
1284         char *cur = cmdline, *tmp;
1285
1286         /* for each entry of the comma-separated list */
1287         do {
1288                 unsigned long long start, end = ULLONG_MAX, size;
1289
1290                 /* get the start of the range */
1291                 start = memparse(cur, &tmp);
1292                 if (cur == tmp) {
1293                         pr_warn("crashkernel: Memory value expected\n");
1294                         return -EINVAL;
1295                 }
1296                 cur = tmp;
1297                 if (*cur != '-') {
1298                         pr_warn("crashkernel: '-' expected\n");
1299                         return -EINVAL;
1300                 }
1301                 cur++;
1302
1303                 /* if no ':' is here, than we read the end */
1304                 if (*cur != ':') {
1305                         end = memparse(cur, &tmp);
1306                         if (cur == tmp) {
1307                                 pr_warn("crashkernel: Memory value expected\n");
1308                                 return -EINVAL;
1309                         }
1310                         cur = tmp;
1311                         if (end <= start) {
1312                                 pr_warn("crashkernel: end <= start\n");
1313                                 return -EINVAL;
1314                         }
1315                 }
1316
1317                 if (*cur != ':') {
1318                         pr_warn("crashkernel: ':' expected\n");
1319                         return -EINVAL;
1320                 }
1321                 cur++;
1322
1323                 size = memparse(cur, &tmp);
1324                 if (cur == tmp) {
1325                         pr_warn("Memory value expected\n");
1326                         return -EINVAL;
1327                 }
1328                 cur = tmp;
1329                 if (size >= system_ram) {
1330                         pr_warn("crashkernel: invalid size\n");
1331                         return -EINVAL;
1332                 }
1333
1334                 /* match ? */
1335                 if (system_ram >= start && system_ram < end) {
1336                         *crash_size = size;
1337                         break;
1338                 }
1339         } while (*cur++ == ',');
1340
1341         if (*crash_size > 0) {
1342                 while (*cur && *cur != ' ' && *cur != '@')
1343                         cur++;
1344                 if (*cur == '@') {
1345                         cur++;
1346                         *crash_base = memparse(cur, &tmp);
1347                         if (cur == tmp) {
1348                                 pr_warn("Memory value expected after '@'\n");
1349                                 return -EINVAL;
1350                         }
1351                 }
1352         }
1353
1354         return 0;
1355 }
1356
1357 /*
1358  * That function parses "simple" (old) crashkernel command lines like
1359  *
1360  *      crashkernel=size[@offset]
1361  *
1362  * It returns 0 on success and -EINVAL on failure.
1363  */
1364 static int __init parse_crashkernel_simple(char *cmdline,
1365                                            unsigned long long *crash_size,
1366                                            unsigned long long *crash_base)
1367 {
1368         char *cur = cmdline;
1369
1370         *crash_size = memparse(cmdline, &cur);
1371         if (cmdline == cur) {
1372                 pr_warn("crashkernel: memory value expected\n");
1373                 return -EINVAL;
1374         }
1375
1376         if (*cur == '@')
1377                 *crash_base = memparse(cur+1, &cur);
1378         else if (*cur != ' ' && *cur != '\0') {
1379                 pr_warn("crashkernel: unrecognized char\n");
1380                 return -EINVAL;
1381         }
1382
1383         return 0;
1384 }
1385
1386 #define SUFFIX_HIGH 0
1387 #define SUFFIX_LOW  1
1388 #define SUFFIX_NULL 2
1389 static __initdata char *suffix_tbl[] = {
1390         [SUFFIX_HIGH] = ",high",
1391         [SUFFIX_LOW]  = ",low",
1392         [SUFFIX_NULL] = NULL,
1393 };
1394
1395 /*
1396  * That function parses "suffix"  crashkernel command lines like
1397  *
1398  *      crashkernel=size,[high|low]
1399  *
1400  * It returns 0 on success and -EINVAL on failure.
1401  */
1402 static int __init parse_crashkernel_suffix(char *cmdline,
1403                                            unsigned long long   *crash_size,
1404                                            const char *suffix)
1405 {
1406         char *cur = cmdline;
1407
1408         *crash_size = memparse(cmdline, &cur);
1409         if (cmdline == cur) {
1410                 pr_warn("crashkernel: memory value expected\n");
1411                 return -EINVAL;
1412         }
1413
1414         /* check with suffix */
1415         if (strncmp(cur, suffix, strlen(suffix))) {
1416                 pr_warn("crashkernel: unrecognized char\n");
1417                 return -EINVAL;
1418         }
1419         cur += strlen(suffix);
1420         if (*cur != ' ' && *cur != '\0') {
1421                 pr_warn("crashkernel: unrecognized char\n");
1422                 return -EINVAL;
1423         }
1424
1425         return 0;
1426 }
1427
1428 static __init char *get_last_crashkernel(char *cmdline,
1429                              const char *name,
1430                              const char *suffix)
1431 {
1432         char *p = cmdline, *ck_cmdline = NULL;
1433
1434         /* find crashkernel and use the last one if there are more */
1435         p = strstr(p, name);
1436         while (p) {
1437                 char *end_p = strchr(p, ' ');
1438                 char *q;
1439
1440                 if (!end_p)
1441                         end_p = p + strlen(p);
1442
1443                 if (!suffix) {
1444                         int i;
1445
1446                         /* skip the one with any known suffix */
1447                         for (i = 0; suffix_tbl[i]; i++) {
1448                                 q = end_p - strlen(suffix_tbl[i]);
1449                                 if (!strncmp(q, suffix_tbl[i],
1450                                              strlen(suffix_tbl[i])))
1451                                         goto next;
1452                         }
1453                         ck_cmdline = p;
1454                 } else {
1455                         q = end_p - strlen(suffix);
1456                         if (!strncmp(q, suffix, strlen(suffix)))
1457                                 ck_cmdline = p;
1458                 }
1459 next:
1460                 p = strstr(p+1, name);
1461         }
1462
1463         if (!ck_cmdline)
1464                 return NULL;
1465
1466         return ck_cmdline;
1467 }
1468
1469 static int __init __parse_crashkernel(char *cmdline,
1470                              unsigned long long system_ram,
1471                              unsigned long long *crash_size,
1472                              unsigned long long *crash_base,
1473                              const char *name,
1474                              const char *suffix)
1475 {
1476         char    *first_colon, *first_space;
1477         char    *ck_cmdline;
1478
1479         BUG_ON(!crash_size || !crash_base);
1480         *crash_size = 0;
1481         *crash_base = 0;
1482
1483         ck_cmdline = get_last_crashkernel(cmdline, name, suffix);
1484
1485         if (!ck_cmdline)
1486                 return -EINVAL;
1487
1488         ck_cmdline += strlen(name);
1489
1490         if (suffix)
1491                 return parse_crashkernel_suffix(ck_cmdline, crash_size,
1492                                 suffix);
1493         /*
1494          * if the commandline contains a ':', then that's the extended
1495          * syntax -- if not, it must be the classic syntax
1496          */
1497         first_colon = strchr(ck_cmdline, ':');
1498         first_space = strchr(ck_cmdline, ' ');
1499         if (first_colon && (!first_space || first_colon < first_space))
1500                 return parse_crashkernel_mem(ck_cmdline, system_ram,
1501                                 crash_size, crash_base);
1502
1503         return parse_crashkernel_simple(ck_cmdline, crash_size, crash_base);
1504 }
1505
1506 /*
1507  * That function is the entry point for command line parsing and should be
1508  * called from the arch-specific code.
1509  */
1510 int __init parse_crashkernel(char *cmdline,
1511                              unsigned long long system_ram,
1512                              unsigned long long *crash_size,
1513                              unsigned long long *crash_base)
1514 {
1515         return __parse_crashkernel(cmdline, system_ram, crash_size, crash_base,
1516                                         "crashkernel=", NULL);
1517 }
1518
1519 int __init parse_crashkernel_high(char *cmdline,
1520                              unsigned long long system_ram,
1521                              unsigned long long *crash_size,
1522                              unsigned long long *crash_base)
1523 {
1524         return __parse_crashkernel(cmdline, system_ram, crash_size, crash_base,
1525                                 "crashkernel=", suffix_tbl[SUFFIX_HIGH]);
1526 }
1527
1528 int __init parse_crashkernel_low(char *cmdline,
1529                              unsigned long long system_ram,
1530                              unsigned long long *crash_size,
1531                              unsigned long long *crash_base)
1532 {
1533         return __parse_crashkernel(cmdline, system_ram, crash_size, crash_base,
1534                                 "crashkernel=", suffix_tbl[SUFFIX_LOW]);
1535 }
1536
1537 static void update_vmcoreinfo_note(void)
1538 {
1539         u32 *buf = vmcoreinfo_note;
1540
1541         if (!vmcoreinfo_size)
1542                 return;
1543         buf = append_elf_note(buf, VMCOREINFO_NOTE_NAME, 0, vmcoreinfo_data,
1544                               vmcoreinfo_size);
1545         final_note(buf);
1546 }
1547
1548 void crash_save_vmcoreinfo(void)
1549 {
1550         vmcoreinfo_append_str("CRASHTIME=%ld\n", get_seconds());
1551         update_vmcoreinfo_note();
1552 }
1553
1554 void vmcoreinfo_append_str(const char *fmt, ...)
1555 {
1556         va_list args;
1557         char buf[0x50];
1558         size_t r;
1559
1560         va_start(args, fmt);
1561         r = vscnprintf(buf, sizeof(buf), fmt, args);
1562         va_end(args);
1563
1564         r = min(r, vmcoreinfo_max_size - vmcoreinfo_size);
1565
1566         memcpy(&vmcoreinfo_data[vmcoreinfo_size], buf, r);
1567
1568         vmcoreinfo_size += r;
1569 }
1570
1571 /*
1572  * provide an empty default implementation here -- architecture
1573  * code may override this
1574  */
1575 void __weak arch_crash_save_vmcoreinfo(void)
1576 {}
1577
1578 unsigned long __weak paddr_vmcoreinfo_note(void)
1579 {
1580         return __pa((unsigned long)(char *)&vmcoreinfo_note);
1581 }
1582
1583 static int __init crash_save_vmcoreinfo_init(void)
1584 {
1585         VMCOREINFO_OSRELEASE(init_uts_ns.name.release);
1586         VMCOREINFO_PAGESIZE(PAGE_SIZE);
1587
1588         VMCOREINFO_SYMBOL(init_uts_ns);
1589         VMCOREINFO_SYMBOL(node_online_map);
1590 #ifdef CONFIG_MMU
1591         VMCOREINFO_SYMBOL(swapper_pg_dir);
1592 #endif
1593         VMCOREINFO_SYMBOL(_stext);
1594         VMCOREINFO_SYMBOL(vmap_area_list);
1595
1596 #ifndef CONFIG_NEED_MULTIPLE_NODES
1597         VMCOREINFO_SYMBOL(mem_map);
1598         VMCOREINFO_SYMBOL(contig_page_data);
1599 #endif
1600 #ifdef CONFIG_SPARSEMEM
1601         VMCOREINFO_SYMBOL(mem_section);
1602         VMCOREINFO_LENGTH(mem_section, NR_SECTION_ROOTS);
1603         VMCOREINFO_STRUCT_SIZE(mem_section);
1604         VMCOREINFO_OFFSET(mem_section, section_mem_map);
1605 #endif
1606         VMCOREINFO_STRUCT_SIZE(page);
1607         VMCOREINFO_STRUCT_SIZE(pglist_data);
1608         VMCOREINFO_STRUCT_SIZE(zone);
1609         VMCOREINFO_STRUCT_SIZE(free_area);
1610         VMCOREINFO_STRUCT_SIZE(list_head);
1611         VMCOREINFO_SIZE(nodemask_t);
1612         VMCOREINFO_OFFSET(page, flags);
1613         VMCOREINFO_OFFSET(page, _count);
1614         VMCOREINFO_OFFSET(page, mapping);
1615         VMCOREINFO_OFFSET(page, lru);
1616         VMCOREINFO_OFFSET(page, _mapcount);
1617         VMCOREINFO_OFFSET(page, private);
1618         VMCOREINFO_OFFSET(pglist_data, node_zones);
1619         VMCOREINFO_OFFSET(pglist_data, nr_zones);
1620 #ifdef CONFIG_FLAT_NODE_MEM_MAP
1621         VMCOREINFO_OFFSET(pglist_data, node_mem_map);
1622 #endif
1623         VMCOREINFO_OFFSET(pglist_data, node_start_pfn);
1624         VMCOREINFO_OFFSET(pglist_data, node_spanned_pages);
1625         VMCOREINFO_OFFSET(pglist_data, node_id);
1626         VMCOREINFO_OFFSET(zone, free_area);
1627         VMCOREINFO_OFFSET(zone, vm_stat);
1628         VMCOREINFO_OFFSET(zone, spanned_pages);
1629         VMCOREINFO_OFFSET(free_area, free_list);
1630         VMCOREINFO_OFFSET(list_head, next);
1631         VMCOREINFO_OFFSET(list_head, prev);
1632         VMCOREINFO_OFFSET(vmap_area, va_start);
1633         VMCOREINFO_OFFSET(vmap_area, list);
1634         VMCOREINFO_LENGTH(zone.free_area, MAX_ORDER);
1635         log_buf_kexec_setup();
1636         VMCOREINFO_LENGTH(free_area.free_list, MIGRATE_TYPES);
1637         VMCOREINFO_NUMBER(NR_FREE_PAGES);
1638         VMCOREINFO_NUMBER(PG_lru);
1639         VMCOREINFO_NUMBER(PG_private);
1640         VMCOREINFO_NUMBER(PG_swapcache);
1641         VMCOREINFO_NUMBER(PG_slab);
1642 #ifdef CONFIG_MEMORY_FAILURE
1643         VMCOREINFO_NUMBER(PG_hwpoison);
1644 #endif
1645         VMCOREINFO_NUMBER(PG_head_mask);
1646         VMCOREINFO_NUMBER(PAGE_BUDDY_MAPCOUNT_VALUE);
1647 #ifdef CONFIG_HUGETLBFS
1648         VMCOREINFO_SYMBOL(free_huge_page);
1649 #endif
1650
1651         arch_crash_save_vmcoreinfo();
1652         update_vmcoreinfo_note();
1653
1654         return 0;
1655 }
1656
1657 subsys_initcall(crash_save_vmcoreinfo_init);
1658
1659 /*
1660  * Move into place and start executing a preloaded standalone
1661  * executable.  If nothing was preloaded return an error.
1662  */
1663 int kernel_kexec(void)
1664 {
1665         int error = 0;
1666
1667         if (!mutex_trylock(&kexec_mutex))
1668                 return -EBUSY;
1669         if (!kexec_image) {
1670                 error = -EINVAL;
1671                 goto Unlock;
1672         }
1673
1674 #ifdef CONFIG_KEXEC_JUMP
1675         if (kexec_image->preserve_context) {
1676                 lock_system_sleep();
1677                 pm_prepare_console();
1678                 error = freeze_processes();
1679                 if (error) {
1680                         error = -EBUSY;
1681                         goto Restore_console;
1682                 }
1683                 suspend_console();
1684                 error = dpm_suspend_start(PMSG_FREEZE);
1685                 if (error)
1686                         goto Resume_console;
1687                 /* At this point, dpm_suspend_start() has been called,
1688                  * but *not* dpm_suspend_end(). We *must* call
1689                  * dpm_suspend_end() now.  Otherwise, drivers for
1690                  * some devices (e.g. interrupt controllers) become
1691                  * desynchronized with the actual state of the
1692                  * hardware at resume time, and evil weirdness ensues.
1693                  */
1694                 error = dpm_suspend_end(PMSG_FREEZE);
1695                 if (error)
1696                         goto Resume_devices;
1697                 error = disable_nonboot_cpus();
1698                 if (error)
1699                         goto Enable_cpus;
1700                 local_irq_disable();
1701                 error = syscore_suspend();
1702                 if (error)
1703                         goto Enable_irqs;
1704         } else
1705 #endif
1706         {
1707                 kexec_in_progress = true;
1708                 kernel_restart_prepare(NULL);
1709                 migrate_to_reboot_cpu();
1710
1711                 /*
1712                  * migrate_to_reboot_cpu() disables CPU hotplug assuming that
1713                  * no further code needs to use CPU hotplug (which is true in
1714                  * the reboot case). However, the kexec path depends on using
1715                  * CPU hotplug again; so re-enable it here.
1716                  */
1717                 cpu_hotplug_enable();
1718                 pr_emerg("Starting new kernel\n");
1719                 machine_shutdown();
1720         }
1721
1722         machine_kexec(kexec_image);
1723
1724 #ifdef CONFIG_KEXEC_JUMP
1725         if (kexec_image->preserve_context) {
1726                 syscore_resume();
1727  Enable_irqs:
1728                 local_irq_enable();
1729  Enable_cpus:
1730                 enable_nonboot_cpus();
1731                 dpm_resume_start(PMSG_RESTORE);
1732  Resume_devices:
1733                 dpm_resume_end(PMSG_RESTORE);
1734  Resume_console:
1735                 resume_console();
1736                 thaw_processes();
1737  Restore_console:
1738                 pm_restore_console();
1739                 unlock_system_sleep();
1740         }
1741 #endif
1742
1743  Unlock:
1744         mutex_unlock(&kexec_mutex);
1745         return error;
1746 }