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