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