sched/headers: Prepare for new header dependencies before moving code to <linux/sched...
[linux-2.6-block.git] / kernel / power / hibernate.c
1 /*
2  * kernel/power/hibernate.c - Hibernation (a.k.a suspend-to-disk) support.
3  *
4  * Copyright (c) 2003 Patrick Mochel
5  * Copyright (c) 2003 Open Source Development Lab
6  * Copyright (c) 2004 Pavel Machek <pavel@ucw.cz>
7  * Copyright (c) 2009 Rafael J. Wysocki, Novell Inc.
8  * Copyright (C) 2012 Bojan Smojver <bojan@rexursive.com>
9  *
10  * This file is released under the GPLv2.
11  */
12
13 #include <linux/export.h>
14 #include <linux/suspend.h>
15 #include <linux/syscalls.h>
16 #include <linux/reboot.h>
17 #include <linux/string.h>
18 #include <linux/device.h>
19 #include <linux/async.h>
20 #include <linux/delay.h>
21 #include <linux/fs.h>
22 #include <linux/mount.h>
23 #include <linux/pm.h>
24 #include <linux/nmi.h>
25 #include <linux/console.h>
26 #include <linux/cpu.h>
27 #include <linux/freezer.h>
28 #include <linux/gfp.h>
29 #include <linux/syscore_ops.h>
30 #include <linux/ctype.h>
31 #include <linux/genhd.h>
32 #include <linux/ktime.h>
33 #include <trace/events/power.h>
34
35 #include "power.h"
36
37
38 static int nocompress;
39 static int noresume;
40 static int nohibernate;
41 static int resume_wait;
42 static unsigned int resume_delay;
43 static char resume_file[256] = CONFIG_PM_STD_PARTITION;
44 dev_t swsusp_resume_device;
45 sector_t swsusp_resume_block;
46 __visible int in_suspend __nosavedata;
47
48 enum {
49         HIBERNATION_INVALID,
50         HIBERNATION_PLATFORM,
51         HIBERNATION_SHUTDOWN,
52         HIBERNATION_REBOOT,
53 #ifdef CONFIG_SUSPEND
54         HIBERNATION_SUSPEND,
55 #endif
56         HIBERNATION_TEST_RESUME,
57         /* keep last */
58         __HIBERNATION_AFTER_LAST
59 };
60 #define HIBERNATION_MAX (__HIBERNATION_AFTER_LAST-1)
61 #define HIBERNATION_FIRST (HIBERNATION_INVALID + 1)
62
63 static int hibernation_mode = HIBERNATION_SHUTDOWN;
64
65 bool freezer_test_done;
66
67 static const struct platform_hibernation_ops *hibernation_ops;
68
69 bool hibernation_available(void)
70 {
71         return (nohibernate == 0);
72 }
73
74 /**
75  * hibernation_set_ops - Set the global hibernate operations.
76  * @ops: Hibernation operations to use in subsequent hibernation transitions.
77  */
78 void hibernation_set_ops(const struct platform_hibernation_ops *ops)
79 {
80         if (ops && !(ops->begin && ops->end &&  ops->pre_snapshot
81             && ops->prepare && ops->finish && ops->enter && ops->pre_restore
82             && ops->restore_cleanup && ops->leave)) {
83                 WARN_ON(1);
84                 return;
85         }
86         lock_system_sleep();
87         hibernation_ops = ops;
88         if (ops)
89                 hibernation_mode = HIBERNATION_PLATFORM;
90         else if (hibernation_mode == HIBERNATION_PLATFORM)
91                 hibernation_mode = HIBERNATION_SHUTDOWN;
92
93         unlock_system_sleep();
94 }
95 EXPORT_SYMBOL_GPL(hibernation_set_ops);
96
97 static bool entering_platform_hibernation;
98
99 bool system_entering_hibernation(void)
100 {
101         return entering_platform_hibernation;
102 }
103 EXPORT_SYMBOL(system_entering_hibernation);
104
105 #ifdef CONFIG_PM_DEBUG
106 static void hibernation_debug_sleep(void)
107 {
108         printk(KERN_INFO "hibernation debug: Waiting for 5 seconds.\n");
109         mdelay(5000);
110 }
111
112 static int hibernation_test(int level)
113 {
114         if (pm_test_level == level) {
115                 hibernation_debug_sleep();
116                 return 1;
117         }
118         return 0;
119 }
120 #else /* !CONFIG_PM_DEBUG */
121 static int hibernation_test(int level) { return 0; }
122 #endif /* !CONFIG_PM_DEBUG */
123
124 /**
125  * platform_begin - Call platform to start hibernation.
126  * @platform_mode: Whether or not to use the platform driver.
127  */
128 static int platform_begin(int platform_mode)
129 {
130         return (platform_mode && hibernation_ops) ?
131                 hibernation_ops->begin() : 0;
132 }
133
134 /**
135  * platform_end - Call platform to finish transition to the working state.
136  * @platform_mode: Whether or not to use the platform driver.
137  */
138 static void platform_end(int platform_mode)
139 {
140         if (platform_mode && hibernation_ops)
141                 hibernation_ops->end();
142 }
143
144 /**
145  * platform_pre_snapshot - Call platform to prepare the machine for hibernation.
146  * @platform_mode: Whether or not to use the platform driver.
147  *
148  * Use the platform driver to prepare the system for creating a hibernate image,
149  * if so configured, and return an error code if that fails.
150  */
151
152 static int platform_pre_snapshot(int platform_mode)
153 {
154         return (platform_mode && hibernation_ops) ?
155                 hibernation_ops->pre_snapshot() : 0;
156 }
157
158 /**
159  * platform_leave - Call platform to prepare a transition to the working state.
160  * @platform_mode: Whether or not to use the platform driver.
161  *
162  * Use the platform driver prepare to prepare the machine for switching to the
163  * normal mode of operation.
164  *
165  * This routine is called on one CPU with interrupts disabled.
166  */
167 static void platform_leave(int platform_mode)
168 {
169         if (platform_mode && hibernation_ops)
170                 hibernation_ops->leave();
171 }
172
173 /**
174  * platform_finish - Call platform to switch the system to the working state.
175  * @platform_mode: Whether or not to use the platform driver.
176  *
177  * Use the platform driver to switch the machine to the normal mode of
178  * operation.
179  *
180  * This routine must be called after platform_prepare().
181  */
182 static void platform_finish(int platform_mode)
183 {
184         if (platform_mode && hibernation_ops)
185                 hibernation_ops->finish();
186 }
187
188 /**
189  * platform_pre_restore - Prepare for hibernate image restoration.
190  * @platform_mode: Whether or not to use the platform driver.
191  *
192  * Use the platform driver to prepare the system for resume from a hibernation
193  * image.
194  *
195  * If the restore fails after this function has been called,
196  * platform_restore_cleanup() must be called.
197  */
198 static int platform_pre_restore(int platform_mode)
199 {
200         return (platform_mode && hibernation_ops) ?
201                 hibernation_ops->pre_restore() : 0;
202 }
203
204 /**
205  * platform_restore_cleanup - Switch to the working state after failing restore.
206  * @platform_mode: Whether or not to use the platform driver.
207  *
208  * Use the platform driver to switch the system to the normal mode of operation
209  * after a failing restore.
210  *
211  * If platform_pre_restore() has been called before the failing restore, this
212  * function must be called too, regardless of the result of
213  * platform_pre_restore().
214  */
215 static void platform_restore_cleanup(int platform_mode)
216 {
217         if (platform_mode && hibernation_ops)
218                 hibernation_ops->restore_cleanup();
219 }
220
221 /**
222  * platform_recover - Recover from a failure to suspend devices.
223  * @platform_mode: Whether or not to use the platform driver.
224  */
225 static void platform_recover(int platform_mode)
226 {
227         if (platform_mode && hibernation_ops && hibernation_ops->recover)
228                 hibernation_ops->recover();
229 }
230
231 /**
232  * swsusp_show_speed - Print time elapsed between two events during hibernation.
233  * @start: Starting event.
234  * @stop: Final event.
235  * @nr_pages: Number of memory pages processed between @start and @stop.
236  * @msg: Additional diagnostic message to print.
237  */
238 void swsusp_show_speed(ktime_t start, ktime_t stop,
239                       unsigned nr_pages, char *msg)
240 {
241         ktime_t diff;
242         u64 elapsed_centisecs64;
243         unsigned int centisecs;
244         unsigned int k;
245         unsigned int kps;
246
247         diff = ktime_sub(stop, start);
248         elapsed_centisecs64 = ktime_divns(diff, 10*NSEC_PER_MSEC);
249         centisecs = elapsed_centisecs64;
250         if (centisecs == 0)
251                 centisecs = 1;  /* avoid div-by-zero */
252         k = nr_pages * (PAGE_SIZE / 1024);
253         kps = (k * 100) / centisecs;
254         printk(KERN_INFO "PM: %s %u kbytes in %u.%02u seconds (%u.%02u MB/s)\n",
255                         msg, k,
256                         centisecs / 100, centisecs % 100,
257                         kps / 1000, (kps % 1000) / 10);
258 }
259
260 /**
261  * create_image - Create a hibernation image.
262  * @platform_mode: Whether or not to use the platform driver.
263  *
264  * Execute device drivers' "late" and "noirq" freeze callbacks, create a
265  * hibernation image and run the drivers' "noirq" and "early" thaw callbacks.
266  *
267  * Control reappears in this routine after the subsequent restore.
268  */
269 static int create_image(int platform_mode)
270 {
271         int error;
272
273         error = dpm_suspend_end(PMSG_FREEZE);
274         if (error) {
275                 printk(KERN_ERR "PM: Some devices failed to power down, "
276                         "aborting hibernation\n");
277                 return error;
278         }
279
280         error = platform_pre_snapshot(platform_mode);
281         if (error || hibernation_test(TEST_PLATFORM))
282                 goto Platform_finish;
283
284         error = disable_nonboot_cpus();
285         if (error || hibernation_test(TEST_CPUS))
286                 goto Enable_cpus;
287
288         local_irq_disable();
289
290         error = syscore_suspend();
291         if (error) {
292                 printk(KERN_ERR "PM: Some system devices failed to power down, "
293                         "aborting hibernation\n");
294                 goto Enable_irqs;
295         }
296
297         if (hibernation_test(TEST_CORE) || pm_wakeup_pending())
298                 goto Power_up;
299
300         in_suspend = 1;
301         save_processor_state();
302         trace_suspend_resume(TPS("machine_suspend"), PM_EVENT_HIBERNATE, true);
303         error = swsusp_arch_suspend();
304         /* Restore control flow magically appears here */
305         restore_processor_state();
306         trace_suspend_resume(TPS("machine_suspend"), PM_EVENT_HIBERNATE, false);
307         if (error)
308                 printk(KERN_ERR "PM: Error %d creating hibernation image\n",
309                         error);
310         if (!in_suspend) {
311                 events_check_enabled = false;
312                 clear_free_pages();
313         }
314
315         platform_leave(platform_mode);
316
317  Power_up:
318         syscore_resume();
319
320  Enable_irqs:
321         local_irq_enable();
322
323  Enable_cpus:
324         enable_nonboot_cpus();
325
326  Platform_finish:
327         platform_finish(platform_mode);
328
329         dpm_resume_start(in_suspend ?
330                 (error ? PMSG_RECOVER : PMSG_THAW) : PMSG_RESTORE);
331
332         return error;
333 }
334
335 /**
336  * hibernation_snapshot - Quiesce devices and create a hibernation image.
337  * @platform_mode: If set, use platform driver to prepare for the transition.
338  *
339  * This routine must be called with pm_mutex held.
340  */
341 int hibernation_snapshot(int platform_mode)
342 {
343         pm_message_t msg;
344         int error;
345
346         pm_suspend_clear_flags();
347         error = platform_begin(platform_mode);
348         if (error)
349                 goto Close;
350
351         /* Preallocate image memory before shutting down devices. */
352         error = hibernate_preallocate_memory();
353         if (error)
354                 goto Close;
355
356         error = freeze_kernel_threads();
357         if (error)
358                 goto Cleanup;
359
360         if (hibernation_test(TEST_FREEZER)) {
361
362                 /*
363                  * Indicate to the caller that we are returning due to a
364                  * successful freezer test.
365                  */
366                 freezer_test_done = true;
367                 goto Thaw;
368         }
369
370         error = dpm_prepare(PMSG_FREEZE);
371         if (error) {
372                 dpm_complete(PMSG_RECOVER);
373                 goto Thaw;
374         }
375
376         suspend_console();
377         pm_restrict_gfp_mask();
378
379         error = dpm_suspend(PMSG_FREEZE);
380
381         if (error || hibernation_test(TEST_DEVICES))
382                 platform_recover(platform_mode);
383         else
384                 error = create_image(platform_mode);
385
386         /*
387          * In the case that we call create_image() above, the control
388          * returns here (1) after the image has been created or the
389          * image creation has failed and (2) after a successful restore.
390          */
391
392         /* We may need to release the preallocated image pages here. */
393         if (error || !in_suspend)
394                 swsusp_free();
395
396         msg = in_suspend ? (error ? PMSG_RECOVER : PMSG_THAW) : PMSG_RESTORE;
397         dpm_resume(msg);
398
399         if (error || !in_suspend)
400                 pm_restore_gfp_mask();
401
402         resume_console();
403         dpm_complete(msg);
404
405  Close:
406         platform_end(platform_mode);
407         return error;
408
409  Thaw:
410         thaw_kernel_threads();
411  Cleanup:
412         swsusp_free();
413         goto Close;
414 }
415
416 int __weak hibernate_resume_nonboot_cpu_disable(void)
417 {
418         return disable_nonboot_cpus();
419 }
420
421 /**
422  * resume_target_kernel - Restore system state from a hibernation image.
423  * @platform_mode: Whether or not to use the platform driver.
424  *
425  * Execute device drivers' "noirq" and "late" freeze callbacks, restore the
426  * contents of highmem that have not been restored yet from the image and run
427  * the low-level code that will restore the remaining contents of memory and
428  * switch to the just restored target kernel.
429  */
430 static int resume_target_kernel(bool platform_mode)
431 {
432         int error;
433
434         error = dpm_suspend_end(PMSG_QUIESCE);
435         if (error) {
436                 printk(KERN_ERR "PM: Some devices failed to power down, "
437                         "aborting resume\n");
438                 return error;
439         }
440
441         error = platform_pre_restore(platform_mode);
442         if (error)
443                 goto Cleanup;
444
445         error = hibernate_resume_nonboot_cpu_disable();
446         if (error)
447                 goto Enable_cpus;
448
449         local_irq_disable();
450
451         error = syscore_suspend();
452         if (error)
453                 goto Enable_irqs;
454
455         save_processor_state();
456         error = restore_highmem();
457         if (!error) {
458                 error = swsusp_arch_resume();
459                 /*
460                  * The code below is only ever reached in case of a failure.
461                  * Otherwise, execution continues at the place where
462                  * swsusp_arch_suspend() was called.
463                  */
464                 BUG_ON(!error);
465                 /*
466                  * This call to restore_highmem() reverts the changes made by
467                  * the previous one.
468                  */
469                 restore_highmem();
470         }
471         /*
472          * The only reason why swsusp_arch_resume() can fail is memory being
473          * very tight, so we have to free it as soon as we can to avoid
474          * subsequent failures.
475          */
476         swsusp_free();
477         restore_processor_state();
478         touch_softlockup_watchdog();
479
480         syscore_resume();
481
482  Enable_irqs:
483         local_irq_enable();
484
485  Enable_cpus:
486         enable_nonboot_cpus();
487
488  Cleanup:
489         platform_restore_cleanup(platform_mode);
490
491         dpm_resume_start(PMSG_RECOVER);
492
493         return error;
494 }
495
496 /**
497  * hibernation_restore - Quiesce devices and restore from a hibernation image.
498  * @platform_mode: If set, use platform driver to prepare for the transition.
499  *
500  * This routine must be called with pm_mutex held.  If it is successful, control
501  * reappears in the restored target kernel in hibernation_snapshot().
502  */
503 int hibernation_restore(int platform_mode)
504 {
505         int error;
506
507         pm_prepare_console();
508         suspend_console();
509         pm_restrict_gfp_mask();
510         error = dpm_suspend_start(PMSG_QUIESCE);
511         if (!error) {
512                 error = resume_target_kernel(platform_mode);
513                 /*
514                  * The above should either succeed and jump to the new kernel,
515                  * or return with an error. Otherwise things are just
516                  * undefined, so let's be paranoid.
517                  */
518                 BUG_ON(!error);
519         }
520         dpm_resume_end(PMSG_RECOVER);
521         pm_restore_gfp_mask();
522         resume_console();
523         pm_restore_console();
524         return error;
525 }
526
527 /**
528  * hibernation_platform_enter - Power off the system using the platform driver.
529  */
530 int hibernation_platform_enter(void)
531 {
532         int error;
533
534         if (!hibernation_ops)
535                 return -ENOSYS;
536
537         /*
538          * We have cancelled the power transition by running
539          * hibernation_ops->finish() before saving the image, so we should let
540          * the firmware know that we're going to enter the sleep state after all
541          */
542         error = hibernation_ops->begin();
543         if (error)
544                 goto Close;
545
546         entering_platform_hibernation = true;
547         suspend_console();
548         error = dpm_suspend_start(PMSG_HIBERNATE);
549         if (error) {
550                 if (hibernation_ops->recover)
551                         hibernation_ops->recover();
552                 goto Resume_devices;
553         }
554
555         error = dpm_suspend_end(PMSG_HIBERNATE);
556         if (error)
557                 goto Resume_devices;
558
559         error = hibernation_ops->prepare();
560         if (error)
561                 goto Platform_finish;
562
563         error = disable_nonboot_cpus();
564         if (error)
565                 goto Enable_cpus;
566
567         local_irq_disable();
568         syscore_suspend();
569         if (pm_wakeup_pending()) {
570                 error = -EAGAIN;
571                 goto Power_up;
572         }
573
574         hibernation_ops->enter();
575         /* We should never get here */
576         while (1);
577
578  Power_up:
579         syscore_resume();
580         local_irq_enable();
581
582  Enable_cpus:
583         enable_nonboot_cpus();
584
585  Platform_finish:
586         hibernation_ops->finish();
587
588         dpm_resume_start(PMSG_RESTORE);
589
590  Resume_devices:
591         entering_platform_hibernation = false;
592         dpm_resume_end(PMSG_RESTORE);
593         resume_console();
594
595  Close:
596         hibernation_ops->end();
597
598         return error;
599 }
600
601 /**
602  * power_down - Shut the machine down for hibernation.
603  *
604  * Use the platform driver, if configured, to put the system into the sleep
605  * state corresponding to hibernation, or try to power it off or reboot,
606  * depending on the value of hibernation_mode.
607  */
608 static void power_down(void)
609 {
610 #ifdef CONFIG_SUSPEND
611         int error;
612 #endif
613
614         switch (hibernation_mode) {
615         case HIBERNATION_REBOOT:
616                 kernel_restart(NULL);
617                 break;
618         case HIBERNATION_PLATFORM:
619                 hibernation_platform_enter();
620         case HIBERNATION_SHUTDOWN:
621                 if (pm_power_off)
622                         kernel_power_off();
623                 break;
624 #ifdef CONFIG_SUSPEND
625         case HIBERNATION_SUSPEND:
626                 error = suspend_devices_and_enter(PM_SUSPEND_MEM);
627                 if (error) {
628                         if (hibernation_ops)
629                                 hibernation_mode = HIBERNATION_PLATFORM;
630                         else
631                                 hibernation_mode = HIBERNATION_SHUTDOWN;
632                         power_down();
633                 }
634                 /*
635                  * Restore swap signature.
636                  */
637                 error = swsusp_unmark();
638                 if (error)
639                         printk(KERN_ERR "PM: Swap will be unusable! "
640                                         "Try swapon -a.\n");
641                 return;
642 #endif
643         }
644         kernel_halt();
645         /*
646          * Valid image is on the disk, if we continue we risk serious data
647          * corruption after resume.
648          */
649         printk(KERN_CRIT "PM: Please power down manually\n");
650         while (1)
651                 cpu_relax();
652 }
653
654 static int load_image_and_restore(void)
655 {
656         int error;
657         unsigned int flags;
658
659         pr_debug("PM: Loading hibernation image.\n");
660
661         lock_device_hotplug();
662         error = create_basic_memory_bitmaps();
663         if (error)
664                 goto Unlock;
665
666         error = swsusp_read(&flags);
667         swsusp_close(FMODE_READ);
668         if (!error)
669                 hibernation_restore(flags & SF_PLATFORM_MODE);
670
671         printk(KERN_ERR "PM: Failed to load hibernation image, recovering.\n");
672         swsusp_free();
673         free_basic_memory_bitmaps();
674  Unlock:
675         unlock_device_hotplug();
676
677         return error;
678 }
679
680 /**
681  * hibernate - Carry out system hibernation, including saving the image.
682  */
683 int hibernate(void)
684 {
685         int error, nr_calls = 0;
686         bool snapshot_test = false;
687
688         if (!hibernation_available()) {
689                 pr_debug("PM: Hibernation not available.\n");
690                 return -EPERM;
691         }
692
693         lock_system_sleep();
694         /* The snapshot device should not be opened while we're running */
695         if (!atomic_add_unless(&snapshot_device_available, -1, 0)) {
696                 error = -EBUSY;
697                 goto Unlock;
698         }
699
700         pm_prepare_console();
701         error = __pm_notifier_call_chain(PM_HIBERNATION_PREPARE, -1, &nr_calls);
702         if (error) {
703                 nr_calls--;
704                 goto Exit;
705         }
706
707         printk(KERN_INFO "PM: Syncing filesystems ... ");
708         sys_sync();
709         printk("done.\n");
710
711         error = freeze_processes();
712         if (error)
713                 goto Exit;
714
715         lock_device_hotplug();
716         /* Allocate memory management structures */
717         error = create_basic_memory_bitmaps();
718         if (error)
719                 goto Thaw;
720
721         error = hibernation_snapshot(hibernation_mode == HIBERNATION_PLATFORM);
722         if (error || freezer_test_done)
723                 goto Free_bitmaps;
724
725         if (in_suspend) {
726                 unsigned int flags = 0;
727
728                 if (hibernation_mode == HIBERNATION_PLATFORM)
729                         flags |= SF_PLATFORM_MODE;
730                 if (nocompress)
731                         flags |= SF_NOCOMPRESS_MODE;
732                 else
733                         flags |= SF_CRC32_MODE;
734
735                 pr_debug("PM: writing image.\n");
736                 error = swsusp_write(flags);
737                 swsusp_free();
738                 if (!error) {
739                         if (hibernation_mode == HIBERNATION_TEST_RESUME)
740                                 snapshot_test = true;
741                         else
742                                 power_down();
743                 }
744                 in_suspend = 0;
745                 pm_restore_gfp_mask();
746         } else {
747                 pr_debug("PM: Image restored successfully.\n");
748         }
749
750  Free_bitmaps:
751         free_basic_memory_bitmaps();
752  Thaw:
753         unlock_device_hotplug();
754         if (snapshot_test) {
755                 pr_debug("PM: Checking hibernation image\n");
756                 error = swsusp_check();
757                 if (!error)
758                         error = load_image_and_restore();
759         }
760         thaw_processes();
761
762         /* Don't bother checking whether freezer_test_done is true */
763         freezer_test_done = false;
764  Exit:
765         __pm_notifier_call_chain(PM_POST_HIBERNATION, nr_calls, NULL);
766         pm_restore_console();
767         atomic_inc(&snapshot_device_available);
768  Unlock:
769         unlock_system_sleep();
770         return error;
771 }
772
773
774 /**
775  * software_resume - Resume from a saved hibernation image.
776  *
777  * This routine is called as a late initcall, when all devices have been
778  * discovered and initialized already.
779  *
780  * The image reading code is called to see if there is a hibernation image
781  * available for reading.  If that is the case, devices are quiesced and the
782  * contents of memory is restored from the saved image.
783  *
784  * If this is successful, control reappears in the restored target kernel in
785  * hibernation_snapshot() which returns to hibernate().  Otherwise, the routine
786  * attempts to recover gracefully and make the kernel return to the normal mode
787  * of operation.
788  */
789 static int software_resume(void)
790 {
791         int error, nr_calls = 0;
792
793         /*
794          * If the user said "noresume".. bail out early.
795          */
796         if (noresume || !hibernation_available())
797                 return 0;
798
799         /*
800          * name_to_dev_t() below takes a sysfs buffer mutex when sysfs
801          * is configured into the kernel. Since the regular hibernate
802          * trigger path is via sysfs which takes a buffer mutex before
803          * calling hibernate functions (which take pm_mutex) this can
804          * cause lockdep to complain about a possible ABBA deadlock
805          * which cannot happen since we're in the boot code here and
806          * sysfs can't be invoked yet. Therefore, we use a subclass
807          * here to avoid lockdep complaining.
808          */
809         mutex_lock_nested(&pm_mutex, SINGLE_DEPTH_NESTING);
810
811         if (swsusp_resume_device)
812                 goto Check_image;
813
814         if (!strlen(resume_file)) {
815                 error = -ENOENT;
816                 goto Unlock;
817         }
818
819         pr_debug("PM: Checking hibernation image partition %s\n", resume_file);
820
821         if (resume_delay) {
822                 printk(KERN_INFO "Waiting %dsec before reading resume device...\n",
823                         resume_delay);
824                 ssleep(resume_delay);
825         }
826
827         /* Check if the device is there */
828         swsusp_resume_device = name_to_dev_t(resume_file);
829
830         /*
831          * name_to_dev_t is ineffective to verify parition if resume_file is in
832          * integer format. (e.g. major:minor)
833          */
834         if (isdigit(resume_file[0]) && resume_wait) {
835                 int partno;
836                 while (!get_gendisk(swsusp_resume_device, &partno))
837                         msleep(10);
838         }
839
840         if (!swsusp_resume_device) {
841                 /*
842                  * Some device discovery might still be in progress; we need
843                  * to wait for this to finish.
844                  */
845                 wait_for_device_probe();
846
847                 if (resume_wait) {
848                         while ((swsusp_resume_device = name_to_dev_t(resume_file)) == 0)
849                                 msleep(10);
850                         async_synchronize_full();
851                 }
852
853                 swsusp_resume_device = name_to_dev_t(resume_file);
854                 if (!swsusp_resume_device) {
855                         error = -ENODEV;
856                         goto Unlock;
857                 }
858         }
859
860  Check_image:
861         pr_debug("PM: Hibernation image partition %d:%d present\n",
862                 MAJOR(swsusp_resume_device), MINOR(swsusp_resume_device));
863
864         pr_debug("PM: Looking for hibernation image.\n");
865         error = swsusp_check();
866         if (error)
867                 goto Unlock;
868
869         /* The snapshot device should not be opened while we're running */
870         if (!atomic_add_unless(&snapshot_device_available, -1, 0)) {
871                 error = -EBUSY;
872                 swsusp_close(FMODE_READ);
873                 goto Unlock;
874         }
875
876         pm_prepare_console();
877         error = __pm_notifier_call_chain(PM_RESTORE_PREPARE, -1, &nr_calls);
878         if (error) {
879                 nr_calls--;
880                 goto Close_Finish;
881         }
882
883         pr_debug("PM: Preparing processes for restore.\n");
884         error = freeze_processes();
885         if (error)
886                 goto Close_Finish;
887         error = load_image_and_restore();
888         thaw_processes();
889  Finish:
890         __pm_notifier_call_chain(PM_POST_RESTORE, nr_calls, NULL);
891         pm_restore_console();
892         atomic_inc(&snapshot_device_available);
893         /* For success case, the suspend path will release the lock */
894  Unlock:
895         mutex_unlock(&pm_mutex);
896         pr_debug("PM: Hibernation image not present or could not be loaded.\n");
897         return error;
898  Close_Finish:
899         swsusp_close(FMODE_READ);
900         goto Finish;
901 }
902
903 late_initcall_sync(software_resume);
904
905
906 static const char * const hibernation_modes[] = {
907         [HIBERNATION_PLATFORM]  = "platform",
908         [HIBERNATION_SHUTDOWN]  = "shutdown",
909         [HIBERNATION_REBOOT]    = "reboot",
910 #ifdef CONFIG_SUSPEND
911         [HIBERNATION_SUSPEND]   = "suspend",
912 #endif
913         [HIBERNATION_TEST_RESUME]       = "test_resume",
914 };
915
916 /*
917  * /sys/power/disk - Control hibernation mode.
918  *
919  * Hibernation can be handled in several ways.  There are a few different ways
920  * to put the system into the sleep state: using the platform driver (e.g. ACPI
921  * or other hibernation_ops), powering it off or rebooting it (for testing
922  * mostly).
923  *
924  * The sysfs file /sys/power/disk provides an interface for selecting the
925  * hibernation mode to use.  Reading from this file causes the available modes
926  * to be printed.  There are 3 modes that can be supported:
927  *
928  *      'platform'
929  *      'shutdown'
930  *      'reboot'
931  *
932  * If a platform hibernation driver is in use, 'platform' will be supported
933  * and will be used by default.  Otherwise, 'shutdown' will be used by default.
934  * The selected option (i.e. the one corresponding to the current value of
935  * hibernation_mode) is enclosed by a square bracket.
936  *
937  * To select a given hibernation mode it is necessary to write the mode's
938  * string representation (as returned by reading from /sys/power/disk) back
939  * into /sys/power/disk.
940  */
941
942 static ssize_t disk_show(struct kobject *kobj, struct kobj_attribute *attr,
943                          char *buf)
944 {
945         int i;
946         char *start = buf;
947
948         if (!hibernation_available())
949                 return sprintf(buf, "[disabled]\n");
950
951         for (i = HIBERNATION_FIRST; i <= HIBERNATION_MAX; i++) {
952                 if (!hibernation_modes[i])
953                         continue;
954                 switch (i) {
955                 case HIBERNATION_SHUTDOWN:
956                 case HIBERNATION_REBOOT:
957 #ifdef CONFIG_SUSPEND
958                 case HIBERNATION_SUSPEND:
959 #endif
960                 case HIBERNATION_TEST_RESUME:
961                         break;
962                 case HIBERNATION_PLATFORM:
963                         if (hibernation_ops)
964                                 break;
965                         /* not a valid mode, continue with loop */
966                         continue;
967                 }
968                 if (i == hibernation_mode)
969                         buf += sprintf(buf, "[%s] ", hibernation_modes[i]);
970                 else
971                         buf += sprintf(buf, "%s ", hibernation_modes[i]);
972         }
973         buf += sprintf(buf, "\n");
974         return buf-start;
975 }
976
977 static ssize_t disk_store(struct kobject *kobj, struct kobj_attribute *attr,
978                           const char *buf, size_t n)
979 {
980         int error = 0;
981         int i;
982         int len;
983         char *p;
984         int mode = HIBERNATION_INVALID;
985
986         if (!hibernation_available())
987                 return -EPERM;
988
989         p = memchr(buf, '\n', n);
990         len = p ? p - buf : n;
991
992         lock_system_sleep();
993         for (i = HIBERNATION_FIRST; i <= HIBERNATION_MAX; i++) {
994                 if (len == strlen(hibernation_modes[i])
995                     && !strncmp(buf, hibernation_modes[i], len)) {
996                         mode = i;
997                         break;
998                 }
999         }
1000         if (mode != HIBERNATION_INVALID) {
1001                 switch (mode) {
1002                 case HIBERNATION_SHUTDOWN:
1003                 case HIBERNATION_REBOOT:
1004 #ifdef CONFIG_SUSPEND
1005                 case HIBERNATION_SUSPEND:
1006 #endif
1007                 case HIBERNATION_TEST_RESUME:
1008                         hibernation_mode = mode;
1009                         break;
1010                 case HIBERNATION_PLATFORM:
1011                         if (hibernation_ops)
1012                                 hibernation_mode = mode;
1013                         else
1014                                 error = -EINVAL;
1015                 }
1016         } else
1017                 error = -EINVAL;
1018
1019         if (!error)
1020                 pr_debug("PM: Hibernation mode set to '%s'\n",
1021                          hibernation_modes[mode]);
1022         unlock_system_sleep();
1023         return error ? error : n;
1024 }
1025
1026 power_attr(disk);
1027
1028 static ssize_t resume_show(struct kobject *kobj, struct kobj_attribute *attr,
1029                            char *buf)
1030 {
1031         return sprintf(buf,"%d:%d\n", MAJOR(swsusp_resume_device),
1032                        MINOR(swsusp_resume_device));
1033 }
1034
1035 static ssize_t resume_store(struct kobject *kobj, struct kobj_attribute *attr,
1036                             const char *buf, size_t n)
1037 {
1038         dev_t res;
1039         int len = n;
1040         char *name;
1041
1042         if (len && buf[len-1] == '\n')
1043                 len--;
1044         name = kstrndup(buf, len, GFP_KERNEL);
1045         if (!name)
1046                 return -ENOMEM;
1047
1048         res = name_to_dev_t(name);
1049         kfree(name);
1050         if (!res)
1051                 return -EINVAL;
1052
1053         lock_system_sleep();
1054         swsusp_resume_device = res;
1055         unlock_system_sleep();
1056         printk(KERN_INFO "PM: Starting manual resume from disk\n");
1057         noresume = 0;
1058         software_resume();
1059         return n;
1060 }
1061
1062 power_attr(resume);
1063
1064 static ssize_t image_size_show(struct kobject *kobj, struct kobj_attribute *attr,
1065                                char *buf)
1066 {
1067         return sprintf(buf, "%lu\n", image_size);
1068 }
1069
1070 static ssize_t image_size_store(struct kobject *kobj, struct kobj_attribute *attr,
1071                                 const char *buf, size_t n)
1072 {
1073         unsigned long size;
1074
1075         if (sscanf(buf, "%lu", &size) == 1) {
1076                 image_size = size;
1077                 return n;
1078         }
1079
1080         return -EINVAL;
1081 }
1082
1083 power_attr(image_size);
1084
1085 static ssize_t reserved_size_show(struct kobject *kobj,
1086                                   struct kobj_attribute *attr, char *buf)
1087 {
1088         return sprintf(buf, "%lu\n", reserved_size);
1089 }
1090
1091 static ssize_t reserved_size_store(struct kobject *kobj,
1092                                    struct kobj_attribute *attr,
1093                                    const char *buf, size_t n)
1094 {
1095         unsigned long size;
1096
1097         if (sscanf(buf, "%lu", &size) == 1) {
1098                 reserved_size = size;
1099                 return n;
1100         }
1101
1102         return -EINVAL;
1103 }
1104
1105 power_attr(reserved_size);
1106
1107 static struct attribute * g[] = {
1108         &disk_attr.attr,
1109         &resume_attr.attr,
1110         &image_size_attr.attr,
1111         &reserved_size_attr.attr,
1112         NULL,
1113 };
1114
1115
1116 static struct attribute_group attr_group = {
1117         .attrs = g,
1118 };
1119
1120
1121 static int __init pm_disk_init(void)
1122 {
1123         return sysfs_create_group(power_kobj, &attr_group);
1124 }
1125
1126 core_initcall(pm_disk_init);
1127
1128
1129 static int __init resume_setup(char *str)
1130 {
1131         if (noresume)
1132                 return 1;
1133
1134         strncpy( resume_file, str, 255 );
1135         return 1;
1136 }
1137
1138 static int __init resume_offset_setup(char *str)
1139 {
1140         unsigned long long offset;
1141
1142         if (noresume)
1143                 return 1;
1144
1145         if (sscanf(str, "%llu", &offset) == 1)
1146                 swsusp_resume_block = offset;
1147
1148         return 1;
1149 }
1150
1151 static int __init hibernate_setup(char *str)
1152 {
1153         if (!strncmp(str, "noresume", 8)) {
1154                 noresume = 1;
1155         } else if (!strncmp(str, "nocompress", 10)) {
1156                 nocompress = 1;
1157         } else if (!strncmp(str, "no", 2)) {
1158                 noresume = 1;
1159                 nohibernate = 1;
1160         } else if (IS_ENABLED(CONFIG_STRICT_KERNEL_RWX)
1161                    && !strncmp(str, "protect_image", 13)) {
1162                 enable_restore_image_protection();
1163         }
1164         return 1;
1165 }
1166
1167 static int __init noresume_setup(char *str)
1168 {
1169         noresume = 1;
1170         return 1;
1171 }
1172
1173 static int __init resumewait_setup(char *str)
1174 {
1175         resume_wait = 1;
1176         return 1;
1177 }
1178
1179 static int __init resumedelay_setup(char *str)
1180 {
1181         int rc = kstrtouint(str, 0, &resume_delay);
1182
1183         if (rc)
1184                 return rc;
1185         return 1;
1186 }
1187
1188 static int __init nohibernate_setup(char *str)
1189 {
1190         noresume = 1;
1191         nohibernate = 1;
1192         return 1;
1193 }
1194
1195 __setup("noresume", noresume_setup);
1196 __setup("resume_offset=", resume_offset_setup);
1197 __setup("resume=", resume_setup);
1198 __setup("hibernate=", hibernate_setup);
1199 __setup("resumewait", resumewait_setup);
1200 __setup("resumedelay=", resumedelay_setup);
1201 __setup("nohibernate", nohibernate_setup);