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