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