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