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