Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /*
0003  * kernel/power/hibernate.c - Hibernation (a.k.a suspend-to-disk) support.
0004  *
0005  * Copyright (c) 2003 Patrick Mochel
0006  * Copyright (c) 2003 Open Source Development Lab
0007  * Copyright (c) 2004 Pavel Machek <pavel@ucw.cz>
0008  * Copyright (c) 2009 Rafael J. Wysocki, Novell Inc.
0009  * Copyright (C) 2012 Bojan Smojver <bojan@rexursive.com>
0010  */
0011 
0012 #define pr_fmt(fmt) "PM: hibernation: " fmt
0013 
0014 #include <linux/export.h>
0015 #include <linux/suspend.h>
0016 #include <linux/reboot.h>
0017 #include <linux/string.h>
0018 #include <linux/device.h>
0019 #include <linux/async.h>
0020 #include <linux/delay.h>
0021 #include <linux/fs.h>
0022 #include <linux/mount.h>
0023 #include <linux/pm.h>
0024 #include <linux/nmi.h>
0025 #include <linux/console.h>
0026 #include <linux/cpu.h>
0027 #include <linux/freezer.h>
0028 #include <linux/gfp.h>
0029 #include <linux/syscore_ops.h>
0030 #include <linux/ctype.h>
0031 #include <linux/ktime.h>
0032 #include <linux/security.h>
0033 #include <linux/secretmem.h>
0034 #include <trace/events/power.h>
0035 
0036 #include "power.h"
0037 
0038 
0039 static int nocompress;
0040 static int noresume;
0041 static int nohibernate;
0042 static int resume_wait;
0043 static unsigned int resume_delay;
0044 static char resume_file[256] = CONFIG_PM_STD_PARTITION;
0045 dev_t swsusp_resume_device;
0046 sector_t swsusp_resume_block;
0047 __visible int in_suspend __nosavedata;
0048 
0049 enum {
0050     HIBERNATION_INVALID,
0051     HIBERNATION_PLATFORM,
0052     HIBERNATION_SHUTDOWN,
0053     HIBERNATION_REBOOT,
0054 #ifdef CONFIG_SUSPEND
0055     HIBERNATION_SUSPEND,
0056 #endif
0057     HIBERNATION_TEST_RESUME,
0058     /* keep last */
0059     __HIBERNATION_AFTER_LAST
0060 };
0061 #define HIBERNATION_MAX (__HIBERNATION_AFTER_LAST-1)
0062 #define HIBERNATION_FIRST (HIBERNATION_INVALID + 1)
0063 
0064 static int hibernation_mode = HIBERNATION_SHUTDOWN;
0065 
0066 bool freezer_test_done;
0067 
0068 static const struct platform_hibernation_ops *hibernation_ops;
0069 
0070 static atomic_t hibernate_atomic = ATOMIC_INIT(1);
0071 
0072 bool hibernate_acquire(void)
0073 {
0074     return atomic_add_unless(&hibernate_atomic, -1, 0);
0075 }
0076 
0077 void hibernate_release(void)
0078 {
0079     atomic_inc(&hibernate_atomic);
0080 }
0081 
0082 bool hibernation_available(void)
0083 {
0084     return nohibernate == 0 &&
0085         !security_locked_down(LOCKDOWN_HIBERNATION) &&
0086         !secretmem_active() && !cxl_mem_active();
0087 }
0088 
0089 /**
0090  * hibernation_set_ops - Set the global hibernate operations.
0091  * @ops: Hibernation operations to use in subsequent hibernation transitions.
0092  */
0093 void hibernation_set_ops(const struct platform_hibernation_ops *ops)
0094 {
0095     if (ops && !(ops->begin && ops->end &&  ops->pre_snapshot
0096         && ops->prepare && ops->finish && ops->enter && ops->pre_restore
0097         && ops->restore_cleanup && ops->leave)) {
0098         WARN_ON(1);
0099         return;
0100     }
0101     lock_system_sleep();
0102     hibernation_ops = ops;
0103     if (ops)
0104         hibernation_mode = HIBERNATION_PLATFORM;
0105     else if (hibernation_mode == HIBERNATION_PLATFORM)
0106         hibernation_mode = HIBERNATION_SHUTDOWN;
0107 
0108     unlock_system_sleep();
0109 }
0110 EXPORT_SYMBOL_GPL(hibernation_set_ops);
0111 
0112 static bool entering_platform_hibernation;
0113 
0114 bool system_entering_hibernation(void)
0115 {
0116     return entering_platform_hibernation;
0117 }
0118 EXPORT_SYMBOL(system_entering_hibernation);
0119 
0120 #ifdef CONFIG_PM_DEBUG
0121 static void hibernation_debug_sleep(void)
0122 {
0123     pr_info("debug: Waiting for 5 seconds.\n");
0124     mdelay(5000);
0125 }
0126 
0127 static int hibernation_test(int level)
0128 {
0129     if (pm_test_level == level) {
0130         hibernation_debug_sleep();
0131         return 1;
0132     }
0133     return 0;
0134 }
0135 #else /* !CONFIG_PM_DEBUG */
0136 static int hibernation_test(int level) { return 0; }
0137 #endif /* !CONFIG_PM_DEBUG */
0138 
0139 /**
0140  * platform_begin - Call platform to start hibernation.
0141  * @platform_mode: Whether or not to use the platform driver.
0142  */
0143 static int platform_begin(int platform_mode)
0144 {
0145     return (platform_mode && hibernation_ops) ?
0146         hibernation_ops->begin(PMSG_FREEZE) : 0;
0147 }
0148 
0149 /**
0150  * platform_end - Call platform to finish transition to the working state.
0151  * @platform_mode: Whether or not to use the platform driver.
0152  */
0153 static void platform_end(int platform_mode)
0154 {
0155     if (platform_mode && hibernation_ops)
0156         hibernation_ops->end();
0157 }
0158 
0159 /**
0160  * platform_pre_snapshot - Call platform to prepare the machine for hibernation.
0161  * @platform_mode: Whether or not to use the platform driver.
0162  *
0163  * Use the platform driver to prepare the system for creating a hibernate image,
0164  * if so configured, and return an error code if that fails.
0165  */
0166 
0167 static int platform_pre_snapshot(int platform_mode)
0168 {
0169     return (platform_mode && hibernation_ops) ?
0170         hibernation_ops->pre_snapshot() : 0;
0171 }
0172 
0173 /**
0174  * platform_leave - Call platform to prepare a transition to the working state.
0175  * @platform_mode: Whether or not to use the platform driver.
0176  *
0177  * Use the platform driver prepare to prepare the machine for switching to the
0178  * normal mode of operation.
0179  *
0180  * This routine is called on one CPU with interrupts disabled.
0181  */
0182 static void platform_leave(int platform_mode)
0183 {
0184     if (platform_mode && hibernation_ops)
0185         hibernation_ops->leave();
0186 }
0187 
0188 /**
0189  * platform_finish - Call platform to switch the system to the working state.
0190  * @platform_mode: Whether or not to use the platform driver.
0191  *
0192  * Use the platform driver to switch the machine to the normal mode of
0193  * operation.
0194  *
0195  * This routine must be called after platform_prepare().
0196  */
0197 static void platform_finish(int platform_mode)
0198 {
0199     if (platform_mode && hibernation_ops)
0200         hibernation_ops->finish();
0201 }
0202 
0203 /**
0204  * platform_pre_restore - Prepare for hibernate image restoration.
0205  * @platform_mode: Whether or not to use the platform driver.
0206  *
0207  * Use the platform driver to prepare the system for resume from a hibernation
0208  * image.
0209  *
0210  * If the restore fails after this function has been called,
0211  * platform_restore_cleanup() must be called.
0212  */
0213 static int platform_pre_restore(int platform_mode)
0214 {
0215     return (platform_mode && hibernation_ops) ?
0216         hibernation_ops->pre_restore() : 0;
0217 }
0218 
0219 /**
0220  * platform_restore_cleanup - Switch to the working state after failing restore.
0221  * @platform_mode: Whether or not to use the platform driver.
0222  *
0223  * Use the platform driver to switch the system to the normal mode of operation
0224  * after a failing restore.
0225  *
0226  * If platform_pre_restore() has been called before the failing restore, this
0227  * function must be called too, regardless of the result of
0228  * platform_pre_restore().
0229  */
0230 static void platform_restore_cleanup(int platform_mode)
0231 {
0232     if (platform_mode && hibernation_ops)
0233         hibernation_ops->restore_cleanup();
0234 }
0235 
0236 /**
0237  * platform_recover - Recover from a failure to suspend devices.
0238  * @platform_mode: Whether or not to use the platform driver.
0239  */
0240 static void platform_recover(int platform_mode)
0241 {
0242     if (platform_mode && hibernation_ops && hibernation_ops->recover)
0243         hibernation_ops->recover();
0244 }
0245 
0246 /**
0247  * swsusp_show_speed - Print time elapsed between two events during hibernation.
0248  * @start: Starting event.
0249  * @stop: Final event.
0250  * @nr_pages: Number of memory pages processed between @start and @stop.
0251  * @msg: Additional diagnostic message to print.
0252  */
0253 void swsusp_show_speed(ktime_t start, ktime_t stop,
0254               unsigned nr_pages, char *msg)
0255 {
0256     ktime_t diff;
0257     u64 elapsed_centisecs64;
0258     unsigned int centisecs;
0259     unsigned int k;
0260     unsigned int kps;
0261 
0262     diff = ktime_sub(stop, start);
0263     elapsed_centisecs64 = ktime_divns(diff, 10*NSEC_PER_MSEC);
0264     centisecs = elapsed_centisecs64;
0265     if (centisecs == 0)
0266         centisecs = 1;  /* avoid div-by-zero */
0267     k = nr_pages * (PAGE_SIZE / 1024);
0268     kps = (k * 100) / centisecs;
0269     pr_info("%s %u kbytes in %u.%02u seconds (%u.%02u MB/s)\n",
0270         msg, k, centisecs / 100, centisecs % 100, kps / 1000,
0271         (kps % 1000) / 10);
0272 }
0273 
0274 __weak int arch_resume_nosmt(void)
0275 {
0276     return 0;
0277 }
0278 
0279 /**
0280  * create_image - Create a hibernation image.
0281  * @platform_mode: Whether or not to use the platform driver.
0282  *
0283  * Execute device drivers' "late" and "noirq" freeze callbacks, create a
0284  * hibernation image and run the drivers' "noirq" and "early" thaw callbacks.
0285  *
0286  * Control reappears in this routine after the subsequent restore.
0287  */
0288 static int create_image(int platform_mode)
0289 {
0290     int error;
0291 
0292     error = dpm_suspend_end(PMSG_FREEZE);
0293     if (error) {
0294         pr_err("Some devices failed to power down, aborting\n");
0295         return error;
0296     }
0297 
0298     error = platform_pre_snapshot(platform_mode);
0299     if (error || hibernation_test(TEST_PLATFORM))
0300         goto Platform_finish;
0301 
0302     error = pm_sleep_disable_secondary_cpus();
0303     if (error || hibernation_test(TEST_CPUS))
0304         goto Enable_cpus;
0305 
0306     local_irq_disable();
0307 
0308     system_state = SYSTEM_SUSPEND;
0309 
0310     error = syscore_suspend();
0311     if (error) {
0312         pr_err("Some system devices failed to power down, aborting\n");
0313         goto Enable_irqs;
0314     }
0315 
0316     if (hibernation_test(TEST_CORE) || pm_wakeup_pending())
0317         goto Power_up;
0318 
0319     in_suspend = 1;
0320     save_processor_state();
0321     trace_suspend_resume(TPS("machine_suspend"), PM_EVENT_HIBERNATE, true);
0322     error = swsusp_arch_suspend();
0323     /* Restore control flow magically appears here */
0324     restore_processor_state();
0325     trace_suspend_resume(TPS("machine_suspend"), PM_EVENT_HIBERNATE, false);
0326     if (error)
0327         pr_err("Error %d creating image\n", error);
0328 
0329     if (!in_suspend) {
0330         events_check_enabled = false;
0331         clear_or_poison_free_pages();
0332     }
0333 
0334     platform_leave(platform_mode);
0335 
0336  Power_up:
0337     syscore_resume();
0338 
0339  Enable_irqs:
0340     system_state = SYSTEM_RUNNING;
0341     local_irq_enable();
0342 
0343  Enable_cpus:
0344     pm_sleep_enable_secondary_cpus();
0345 
0346     /* Allow architectures to do nosmt-specific post-resume dances */
0347     if (!in_suspend)
0348         error = arch_resume_nosmt();
0349 
0350  Platform_finish:
0351     platform_finish(platform_mode);
0352 
0353     dpm_resume_start(in_suspend ?
0354         (error ? PMSG_RECOVER : PMSG_THAW) : PMSG_RESTORE);
0355 
0356     return error;
0357 }
0358 
0359 /**
0360  * hibernation_snapshot - Quiesce devices and create a hibernation image.
0361  * @platform_mode: If set, use platform driver to prepare for the transition.
0362  *
0363  * This routine must be called with system_transition_mutex held.
0364  */
0365 int hibernation_snapshot(int platform_mode)
0366 {
0367     pm_message_t msg;
0368     int error;
0369 
0370     pm_suspend_clear_flags();
0371     error = platform_begin(platform_mode);
0372     if (error)
0373         goto Close;
0374 
0375     /* Preallocate image memory before shutting down devices. */
0376     error = hibernate_preallocate_memory();
0377     if (error)
0378         goto Close;
0379 
0380     error = freeze_kernel_threads();
0381     if (error)
0382         goto Cleanup;
0383 
0384     if (hibernation_test(TEST_FREEZER)) {
0385 
0386         /*
0387          * Indicate to the caller that we are returning due to a
0388          * successful freezer test.
0389          */
0390         freezer_test_done = true;
0391         goto Thaw;
0392     }
0393 
0394     error = dpm_prepare(PMSG_FREEZE);
0395     if (error) {
0396         dpm_complete(PMSG_RECOVER);
0397         goto Thaw;
0398     }
0399 
0400     suspend_console();
0401     pm_restrict_gfp_mask();
0402 
0403     error = dpm_suspend(PMSG_FREEZE);
0404 
0405     if (error || hibernation_test(TEST_DEVICES))
0406         platform_recover(platform_mode);
0407     else
0408         error = create_image(platform_mode);
0409 
0410     /*
0411      * In the case that we call create_image() above, the control
0412      * returns here (1) after the image has been created or the
0413      * image creation has failed and (2) after a successful restore.
0414      */
0415 
0416     /* We may need to release the preallocated image pages here. */
0417     if (error || !in_suspend)
0418         swsusp_free();
0419 
0420     msg = in_suspend ? (error ? PMSG_RECOVER : PMSG_THAW) : PMSG_RESTORE;
0421     dpm_resume(msg);
0422 
0423     if (error || !in_suspend)
0424         pm_restore_gfp_mask();
0425 
0426     resume_console();
0427     dpm_complete(msg);
0428 
0429  Close:
0430     platform_end(platform_mode);
0431     return error;
0432 
0433  Thaw:
0434     thaw_kernel_threads();
0435  Cleanup:
0436     swsusp_free();
0437     goto Close;
0438 }
0439 
0440 int __weak hibernate_resume_nonboot_cpu_disable(void)
0441 {
0442     return suspend_disable_secondary_cpus();
0443 }
0444 
0445 /**
0446  * resume_target_kernel - Restore system state from a hibernation image.
0447  * @platform_mode: Whether or not to use the platform driver.
0448  *
0449  * Execute device drivers' "noirq" and "late" freeze callbacks, restore the
0450  * contents of highmem that have not been restored yet from the image and run
0451  * the low-level code that will restore the remaining contents of memory and
0452  * switch to the just restored target kernel.
0453  */
0454 static int resume_target_kernel(bool platform_mode)
0455 {
0456     int error;
0457 
0458     error = dpm_suspend_end(PMSG_QUIESCE);
0459     if (error) {
0460         pr_err("Some devices failed to power down, aborting resume\n");
0461         return error;
0462     }
0463 
0464     error = platform_pre_restore(platform_mode);
0465     if (error)
0466         goto Cleanup;
0467 
0468     cpuidle_pause();
0469 
0470     error = hibernate_resume_nonboot_cpu_disable();
0471     if (error)
0472         goto Enable_cpus;
0473 
0474     local_irq_disable();
0475     system_state = SYSTEM_SUSPEND;
0476 
0477     error = syscore_suspend();
0478     if (error)
0479         goto Enable_irqs;
0480 
0481     save_processor_state();
0482     error = restore_highmem();
0483     if (!error) {
0484         error = swsusp_arch_resume();
0485         /*
0486          * The code below is only ever reached in case of a failure.
0487          * Otherwise, execution continues at the place where
0488          * swsusp_arch_suspend() was called.
0489          */
0490         BUG_ON(!error);
0491         /*
0492          * This call to restore_highmem() reverts the changes made by
0493          * the previous one.
0494          */
0495         restore_highmem();
0496     }
0497     /*
0498      * The only reason why swsusp_arch_resume() can fail is memory being
0499      * very tight, so we have to free it as soon as we can to avoid
0500      * subsequent failures.
0501      */
0502     swsusp_free();
0503     restore_processor_state();
0504     touch_softlockup_watchdog();
0505 
0506     syscore_resume();
0507 
0508  Enable_irqs:
0509     system_state = SYSTEM_RUNNING;
0510     local_irq_enable();
0511 
0512  Enable_cpus:
0513     pm_sleep_enable_secondary_cpus();
0514 
0515  Cleanup:
0516     platform_restore_cleanup(platform_mode);
0517 
0518     dpm_resume_start(PMSG_RECOVER);
0519 
0520     return error;
0521 }
0522 
0523 /**
0524  * hibernation_restore - Quiesce devices and restore from a hibernation image.
0525  * @platform_mode: If set, use platform driver to prepare for the transition.
0526  *
0527  * This routine must be called with system_transition_mutex held.  If it is
0528  * successful, control reappears in the restored target kernel in
0529  * hibernation_snapshot().
0530  */
0531 int hibernation_restore(int platform_mode)
0532 {
0533     int error;
0534 
0535     pm_prepare_console();
0536     suspend_console();
0537     pm_restrict_gfp_mask();
0538     error = dpm_suspend_start(PMSG_QUIESCE);
0539     if (!error) {
0540         error = resume_target_kernel(platform_mode);
0541         /*
0542          * The above should either succeed and jump to the new kernel,
0543          * or return with an error. Otherwise things are just
0544          * undefined, so let's be paranoid.
0545          */
0546         BUG_ON(!error);
0547     }
0548     dpm_resume_end(PMSG_RECOVER);
0549     pm_restore_gfp_mask();
0550     resume_console();
0551     pm_restore_console();
0552     return error;
0553 }
0554 
0555 /**
0556  * hibernation_platform_enter - Power off the system using the platform driver.
0557  */
0558 int hibernation_platform_enter(void)
0559 {
0560     int error;
0561 
0562     if (!hibernation_ops)
0563         return -ENOSYS;
0564 
0565     /*
0566      * We have cancelled the power transition by running
0567      * hibernation_ops->finish() before saving the image, so we should let
0568      * the firmware know that we're going to enter the sleep state after all
0569      */
0570     error = hibernation_ops->begin(PMSG_HIBERNATE);
0571     if (error)
0572         goto Close;
0573 
0574     entering_platform_hibernation = true;
0575     suspend_console();
0576     error = dpm_suspend_start(PMSG_HIBERNATE);
0577     if (error) {
0578         if (hibernation_ops->recover)
0579             hibernation_ops->recover();
0580         goto Resume_devices;
0581     }
0582 
0583     error = dpm_suspend_end(PMSG_HIBERNATE);
0584     if (error)
0585         goto Resume_devices;
0586 
0587     error = hibernation_ops->prepare();
0588     if (error)
0589         goto Platform_finish;
0590 
0591     error = pm_sleep_disable_secondary_cpus();
0592     if (error)
0593         goto Enable_cpus;
0594 
0595     local_irq_disable();
0596     system_state = SYSTEM_SUSPEND;
0597     syscore_suspend();
0598     if (pm_wakeup_pending()) {
0599         error = -EAGAIN;
0600         goto Power_up;
0601     }
0602 
0603     hibernation_ops->enter();
0604     /* We should never get here */
0605     while (1);
0606 
0607  Power_up:
0608     syscore_resume();
0609     system_state = SYSTEM_RUNNING;
0610     local_irq_enable();
0611 
0612  Enable_cpus:
0613     pm_sleep_enable_secondary_cpus();
0614 
0615  Platform_finish:
0616     hibernation_ops->finish();
0617 
0618     dpm_resume_start(PMSG_RESTORE);
0619 
0620  Resume_devices:
0621     entering_platform_hibernation = false;
0622     dpm_resume_end(PMSG_RESTORE);
0623     resume_console();
0624 
0625  Close:
0626     hibernation_ops->end();
0627 
0628     return error;
0629 }
0630 
0631 /**
0632  * power_down - Shut the machine down for hibernation.
0633  *
0634  * Use the platform driver, if configured, to put the system into the sleep
0635  * state corresponding to hibernation, or try to power it off or reboot,
0636  * depending on the value of hibernation_mode.
0637  */
0638 static void power_down(void)
0639 {
0640 #ifdef CONFIG_SUSPEND
0641     int error;
0642 
0643     if (hibernation_mode == HIBERNATION_SUSPEND) {
0644         error = suspend_devices_and_enter(PM_SUSPEND_MEM);
0645         if (error) {
0646             hibernation_mode = hibernation_ops ?
0647                         HIBERNATION_PLATFORM :
0648                         HIBERNATION_SHUTDOWN;
0649         } else {
0650             /* Restore swap signature. */
0651             error = swsusp_unmark();
0652             if (error)
0653                 pr_err("Swap will be unusable! Try swapon -a.\n");
0654 
0655             return;
0656         }
0657     }
0658 #endif
0659 
0660     switch (hibernation_mode) {
0661     case HIBERNATION_REBOOT:
0662         kernel_restart(NULL);
0663         break;
0664     case HIBERNATION_PLATFORM:
0665         hibernation_platform_enter();
0666         fallthrough;
0667     case HIBERNATION_SHUTDOWN:
0668         if (kernel_can_power_off())
0669             kernel_power_off();
0670         break;
0671     }
0672     kernel_halt();
0673     /*
0674      * Valid image is on the disk, if we continue we risk serious data
0675      * corruption after resume.
0676      */
0677     pr_crit("Power down manually\n");
0678     while (1)
0679         cpu_relax();
0680 }
0681 
0682 static int load_image_and_restore(void)
0683 {
0684     int error;
0685     unsigned int flags;
0686 
0687     pm_pr_dbg("Loading hibernation image.\n");
0688 
0689     lock_device_hotplug();
0690     error = create_basic_memory_bitmaps();
0691     if (error) {
0692         swsusp_close(FMODE_READ | FMODE_EXCL);
0693         goto Unlock;
0694     }
0695 
0696     error = swsusp_read(&flags);
0697     swsusp_close(FMODE_READ | FMODE_EXCL);
0698     if (!error)
0699         error = hibernation_restore(flags & SF_PLATFORM_MODE);
0700 
0701     pr_err("Failed to load image, recovering.\n");
0702     swsusp_free();
0703     free_basic_memory_bitmaps();
0704  Unlock:
0705     unlock_device_hotplug();
0706 
0707     return error;
0708 }
0709 
0710 /**
0711  * hibernate - Carry out system hibernation, including saving the image.
0712  */
0713 int hibernate(void)
0714 {
0715     bool snapshot_test = false;
0716     int error;
0717 
0718     if (!hibernation_available()) {
0719         pm_pr_dbg("Hibernation not available.\n");
0720         return -EPERM;
0721     }
0722 
0723     lock_system_sleep();
0724     /* The snapshot device should not be opened while we're running */
0725     if (!hibernate_acquire()) {
0726         error = -EBUSY;
0727         goto Unlock;
0728     }
0729 
0730     pr_info("hibernation entry\n");
0731     pm_prepare_console();
0732     error = pm_notifier_call_chain_robust(PM_HIBERNATION_PREPARE, PM_POST_HIBERNATION);
0733     if (error)
0734         goto Restore;
0735 
0736     ksys_sync_helper();
0737 
0738     error = freeze_processes();
0739     if (error)
0740         goto Exit;
0741 
0742     lock_device_hotplug();
0743     /* Allocate memory management structures */
0744     error = create_basic_memory_bitmaps();
0745     if (error)
0746         goto Thaw;
0747 
0748     error = hibernation_snapshot(hibernation_mode == HIBERNATION_PLATFORM);
0749     if (error || freezer_test_done)
0750         goto Free_bitmaps;
0751 
0752     if (in_suspend) {
0753         unsigned int flags = 0;
0754 
0755         if (hibernation_mode == HIBERNATION_PLATFORM)
0756             flags |= SF_PLATFORM_MODE;
0757         if (nocompress)
0758             flags |= SF_NOCOMPRESS_MODE;
0759         else
0760                 flags |= SF_CRC32_MODE;
0761 
0762         pm_pr_dbg("Writing hibernation image.\n");
0763         error = swsusp_write(flags);
0764         swsusp_free();
0765         if (!error) {
0766             if (hibernation_mode == HIBERNATION_TEST_RESUME)
0767                 snapshot_test = true;
0768             else
0769                 power_down();
0770         }
0771         in_suspend = 0;
0772         pm_restore_gfp_mask();
0773     } else {
0774         pm_pr_dbg("Hibernation image restored successfully.\n");
0775     }
0776 
0777  Free_bitmaps:
0778     free_basic_memory_bitmaps();
0779  Thaw:
0780     unlock_device_hotplug();
0781     if (snapshot_test) {
0782         pm_pr_dbg("Checking hibernation image\n");
0783         error = swsusp_check();
0784         if (!error)
0785             error = load_image_and_restore();
0786     }
0787     thaw_processes();
0788 
0789     /* Don't bother checking whether freezer_test_done is true */
0790     freezer_test_done = false;
0791  Exit:
0792     pm_notifier_call_chain(PM_POST_HIBERNATION);
0793  Restore:
0794     pm_restore_console();
0795     hibernate_release();
0796  Unlock:
0797     unlock_system_sleep();
0798     pr_info("hibernation exit\n");
0799 
0800     return error;
0801 }
0802 
0803 /**
0804  * hibernate_quiet_exec - Execute a function with all devices frozen.
0805  * @func: Function to execute.
0806  * @data: Data pointer to pass to @func.
0807  *
0808  * Return the @func return value or an error code if it cannot be executed.
0809  */
0810 int hibernate_quiet_exec(int (*func)(void *data), void *data)
0811 {
0812     int error;
0813 
0814     lock_system_sleep();
0815 
0816     if (!hibernate_acquire()) {
0817         error = -EBUSY;
0818         goto unlock;
0819     }
0820 
0821     pm_prepare_console();
0822 
0823     error = pm_notifier_call_chain_robust(PM_HIBERNATION_PREPARE, PM_POST_HIBERNATION);
0824     if (error)
0825         goto restore;
0826 
0827     error = freeze_processes();
0828     if (error)
0829         goto exit;
0830 
0831     lock_device_hotplug();
0832 
0833     pm_suspend_clear_flags();
0834 
0835     error = platform_begin(true);
0836     if (error)
0837         goto thaw;
0838 
0839     error = freeze_kernel_threads();
0840     if (error)
0841         goto thaw;
0842 
0843     error = dpm_prepare(PMSG_FREEZE);
0844     if (error)
0845         goto dpm_complete;
0846 
0847     suspend_console();
0848 
0849     error = dpm_suspend(PMSG_FREEZE);
0850     if (error)
0851         goto dpm_resume;
0852 
0853     error = dpm_suspend_end(PMSG_FREEZE);
0854     if (error)
0855         goto dpm_resume;
0856 
0857     error = platform_pre_snapshot(true);
0858     if (error)
0859         goto skip;
0860 
0861     error = func(data);
0862 
0863 skip:
0864     platform_finish(true);
0865 
0866     dpm_resume_start(PMSG_THAW);
0867 
0868 dpm_resume:
0869     dpm_resume(PMSG_THAW);
0870 
0871     resume_console();
0872 
0873 dpm_complete:
0874     dpm_complete(PMSG_THAW);
0875 
0876     thaw_kernel_threads();
0877 
0878 thaw:
0879     platform_end(true);
0880 
0881     unlock_device_hotplug();
0882 
0883     thaw_processes();
0884 
0885 exit:
0886     pm_notifier_call_chain(PM_POST_HIBERNATION);
0887 
0888 restore:
0889     pm_restore_console();
0890 
0891     hibernate_release();
0892 
0893 unlock:
0894     unlock_system_sleep();
0895 
0896     return error;
0897 }
0898 EXPORT_SYMBOL_GPL(hibernate_quiet_exec);
0899 
0900 /**
0901  * software_resume - Resume from a saved hibernation image.
0902  *
0903  * This routine is called as a late initcall, when all devices have been
0904  * discovered and initialized already.
0905  *
0906  * The image reading code is called to see if there is a hibernation image
0907  * available for reading.  If that is the case, devices are quiesced and the
0908  * contents of memory is restored from the saved image.
0909  *
0910  * If this is successful, control reappears in the restored target kernel in
0911  * hibernation_snapshot() which returns to hibernate().  Otherwise, the routine
0912  * attempts to recover gracefully and make the kernel return to the normal mode
0913  * of operation.
0914  */
0915 static int software_resume(void)
0916 {
0917     int error;
0918 
0919     /*
0920      * If the user said "noresume".. bail out early.
0921      */
0922     if (noresume || !hibernation_available())
0923         return 0;
0924 
0925     /*
0926      * name_to_dev_t() below takes a sysfs buffer mutex when sysfs
0927      * is configured into the kernel. Since the regular hibernate
0928      * trigger path is via sysfs which takes a buffer mutex before
0929      * calling hibernate functions (which take system_transition_mutex)
0930      * this can cause lockdep to complain about a possible ABBA deadlock
0931      * which cannot happen since we're in the boot code here and
0932      * sysfs can't be invoked yet. Therefore, we use a subclass
0933      * here to avoid lockdep complaining.
0934      */
0935     mutex_lock_nested(&system_transition_mutex, SINGLE_DEPTH_NESTING);
0936 
0937     if (swsusp_resume_device)
0938         goto Check_image;
0939 
0940     if (!strlen(resume_file)) {
0941         error = -ENOENT;
0942         goto Unlock;
0943     }
0944 
0945     pm_pr_dbg("Checking hibernation image partition %s\n", resume_file);
0946 
0947     if (resume_delay) {
0948         pr_info("Waiting %dsec before reading resume device ...\n",
0949             resume_delay);
0950         ssleep(resume_delay);
0951     }
0952 
0953     /* Check if the device is there */
0954     swsusp_resume_device = name_to_dev_t(resume_file);
0955     if (!swsusp_resume_device) {
0956         /*
0957          * Some device discovery might still be in progress; we need
0958          * to wait for this to finish.
0959          */
0960         wait_for_device_probe();
0961 
0962         if (resume_wait) {
0963             while ((swsusp_resume_device = name_to_dev_t(resume_file)) == 0)
0964                 msleep(10);
0965             async_synchronize_full();
0966         }
0967 
0968         swsusp_resume_device = name_to_dev_t(resume_file);
0969         if (!swsusp_resume_device) {
0970             error = -ENODEV;
0971             goto Unlock;
0972         }
0973     }
0974 
0975  Check_image:
0976     pm_pr_dbg("Hibernation image partition %d:%d present\n",
0977         MAJOR(swsusp_resume_device), MINOR(swsusp_resume_device));
0978 
0979     pm_pr_dbg("Looking for hibernation image.\n");
0980     error = swsusp_check();
0981     if (error)
0982         goto Unlock;
0983 
0984     /* The snapshot device should not be opened while we're running */
0985     if (!hibernate_acquire()) {
0986         error = -EBUSY;
0987         swsusp_close(FMODE_READ | FMODE_EXCL);
0988         goto Unlock;
0989     }
0990 
0991     pr_info("resume from hibernation\n");
0992     pm_prepare_console();
0993     error = pm_notifier_call_chain_robust(PM_RESTORE_PREPARE, PM_POST_RESTORE);
0994     if (error)
0995         goto Restore;
0996 
0997     pm_pr_dbg("Preparing processes for hibernation restore.\n");
0998     error = freeze_processes();
0999     if (error)
1000         goto Close_Finish;
1001 
1002     error = freeze_kernel_threads();
1003     if (error) {
1004         thaw_processes();
1005         goto Close_Finish;
1006     }
1007 
1008     error = load_image_and_restore();
1009     thaw_processes();
1010  Finish:
1011     pm_notifier_call_chain(PM_POST_RESTORE);
1012  Restore:
1013     pm_restore_console();
1014     pr_info("resume failed (%d)\n", error);
1015     hibernate_release();
1016     /* For success case, the suspend path will release the lock */
1017  Unlock:
1018     mutex_unlock(&system_transition_mutex);
1019     pm_pr_dbg("Hibernation image not present or could not be loaded.\n");
1020     return error;
1021  Close_Finish:
1022     swsusp_close(FMODE_READ | FMODE_EXCL);
1023     goto Finish;
1024 }
1025 
1026 late_initcall_sync(software_resume);
1027 
1028 
1029 static const char * const hibernation_modes[] = {
1030     [HIBERNATION_PLATFORM]  = "platform",
1031     [HIBERNATION_SHUTDOWN]  = "shutdown",
1032     [HIBERNATION_REBOOT]    = "reboot",
1033 #ifdef CONFIG_SUSPEND
1034     [HIBERNATION_SUSPEND]   = "suspend",
1035 #endif
1036     [HIBERNATION_TEST_RESUME]   = "test_resume",
1037 };
1038 
1039 /*
1040  * /sys/power/disk - Control hibernation mode.
1041  *
1042  * Hibernation can be handled in several ways.  There are a few different ways
1043  * to put the system into the sleep state: using the platform driver (e.g. ACPI
1044  * or other hibernation_ops), powering it off or rebooting it (for testing
1045  * mostly).
1046  *
1047  * The sysfs file /sys/power/disk provides an interface for selecting the
1048  * hibernation mode to use.  Reading from this file causes the available modes
1049  * to be printed.  There are 3 modes that can be supported:
1050  *
1051  *  'platform'
1052  *  'shutdown'
1053  *  'reboot'
1054  *
1055  * If a platform hibernation driver is in use, 'platform' will be supported
1056  * and will be used by default.  Otherwise, 'shutdown' will be used by default.
1057  * The selected option (i.e. the one corresponding to the current value of
1058  * hibernation_mode) is enclosed by a square bracket.
1059  *
1060  * To select a given hibernation mode it is necessary to write the mode's
1061  * string representation (as returned by reading from /sys/power/disk) back
1062  * into /sys/power/disk.
1063  */
1064 
1065 static ssize_t disk_show(struct kobject *kobj, struct kobj_attribute *attr,
1066              char *buf)
1067 {
1068     int i;
1069     char *start = buf;
1070 
1071     if (!hibernation_available())
1072         return sprintf(buf, "[disabled]\n");
1073 
1074     for (i = HIBERNATION_FIRST; i <= HIBERNATION_MAX; i++) {
1075         if (!hibernation_modes[i])
1076             continue;
1077         switch (i) {
1078         case HIBERNATION_SHUTDOWN:
1079         case HIBERNATION_REBOOT:
1080 #ifdef CONFIG_SUSPEND
1081         case HIBERNATION_SUSPEND:
1082 #endif
1083         case HIBERNATION_TEST_RESUME:
1084             break;
1085         case HIBERNATION_PLATFORM:
1086             if (hibernation_ops)
1087                 break;
1088             /* not a valid mode, continue with loop */
1089             continue;
1090         }
1091         if (i == hibernation_mode)
1092             buf += sprintf(buf, "[%s] ", hibernation_modes[i]);
1093         else
1094             buf += sprintf(buf, "%s ", hibernation_modes[i]);
1095     }
1096     buf += sprintf(buf, "\n");
1097     return buf-start;
1098 }
1099 
1100 static ssize_t disk_store(struct kobject *kobj, struct kobj_attribute *attr,
1101               const char *buf, size_t n)
1102 {
1103     int error = 0;
1104     int i;
1105     int len;
1106     char *p;
1107     int mode = HIBERNATION_INVALID;
1108 
1109     if (!hibernation_available())
1110         return -EPERM;
1111 
1112     p = memchr(buf, '\n', n);
1113     len = p ? p - buf : n;
1114 
1115     lock_system_sleep();
1116     for (i = HIBERNATION_FIRST; i <= HIBERNATION_MAX; i++) {
1117         if (len == strlen(hibernation_modes[i])
1118             && !strncmp(buf, hibernation_modes[i], len)) {
1119             mode = i;
1120             break;
1121         }
1122     }
1123     if (mode != HIBERNATION_INVALID) {
1124         switch (mode) {
1125         case HIBERNATION_SHUTDOWN:
1126         case HIBERNATION_REBOOT:
1127 #ifdef CONFIG_SUSPEND
1128         case HIBERNATION_SUSPEND:
1129 #endif
1130         case HIBERNATION_TEST_RESUME:
1131             hibernation_mode = mode;
1132             break;
1133         case HIBERNATION_PLATFORM:
1134             if (hibernation_ops)
1135                 hibernation_mode = mode;
1136             else
1137                 error = -EINVAL;
1138         }
1139     } else
1140         error = -EINVAL;
1141 
1142     if (!error)
1143         pm_pr_dbg("Hibernation mode set to '%s'\n",
1144                    hibernation_modes[mode]);
1145     unlock_system_sleep();
1146     return error ? error : n;
1147 }
1148 
1149 power_attr(disk);
1150 
1151 static ssize_t resume_show(struct kobject *kobj, struct kobj_attribute *attr,
1152                char *buf)
1153 {
1154     return sprintf(buf, "%d:%d\n", MAJOR(swsusp_resume_device),
1155                MINOR(swsusp_resume_device));
1156 }
1157 
1158 static ssize_t resume_store(struct kobject *kobj, struct kobj_attribute *attr,
1159                 const char *buf, size_t n)
1160 {
1161     dev_t res;
1162     int len = n;
1163     char *name;
1164 
1165     if (len && buf[len-1] == '\n')
1166         len--;
1167     name = kstrndup(buf, len, GFP_KERNEL);
1168     if (!name)
1169         return -ENOMEM;
1170 
1171     res = name_to_dev_t(name);
1172     kfree(name);
1173     if (!res)
1174         return -EINVAL;
1175 
1176     lock_system_sleep();
1177     swsusp_resume_device = res;
1178     unlock_system_sleep();
1179     pm_pr_dbg("Configured hibernation resume from disk to %u\n",
1180           swsusp_resume_device);
1181     noresume = 0;
1182     software_resume();
1183     return n;
1184 }
1185 
1186 power_attr(resume);
1187 
1188 static ssize_t resume_offset_show(struct kobject *kobj,
1189                   struct kobj_attribute *attr, char *buf)
1190 {
1191     return sprintf(buf, "%llu\n", (unsigned long long)swsusp_resume_block);
1192 }
1193 
1194 static ssize_t resume_offset_store(struct kobject *kobj,
1195                    struct kobj_attribute *attr, const char *buf,
1196                    size_t n)
1197 {
1198     unsigned long long offset;
1199     int rc;
1200 
1201     rc = kstrtoull(buf, 0, &offset);
1202     if (rc)
1203         return rc;
1204     swsusp_resume_block = offset;
1205 
1206     return n;
1207 }
1208 
1209 power_attr(resume_offset);
1210 
1211 static ssize_t image_size_show(struct kobject *kobj, struct kobj_attribute *attr,
1212                    char *buf)
1213 {
1214     return sprintf(buf, "%lu\n", image_size);
1215 }
1216 
1217 static ssize_t image_size_store(struct kobject *kobj, struct kobj_attribute *attr,
1218                 const char *buf, size_t n)
1219 {
1220     unsigned long size;
1221 
1222     if (sscanf(buf, "%lu", &size) == 1) {
1223         image_size = size;
1224         return n;
1225     }
1226 
1227     return -EINVAL;
1228 }
1229 
1230 power_attr(image_size);
1231 
1232 static ssize_t reserved_size_show(struct kobject *kobj,
1233                   struct kobj_attribute *attr, char *buf)
1234 {
1235     return sprintf(buf, "%lu\n", reserved_size);
1236 }
1237 
1238 static ssize_t reserved_size_store(struct kobject *kobj,
1239                    struct kobj_attribute *attr,
1240                    const char *buf, size_t n)
1241 {
1242     unsigned long size;
1243 
1244     if (sscanf(buf, "%lu", &size) == 1) {
1245         reserved_size = size;
1246         return n;
1247     }
1248 
1249     return -EINVAL;
1250 }
1251 
1252 power_attr(reserved_size);
1253 
1254 static struct attribute *g[] = {
1255     &disk_attr.attr,
1256     &resume_offset_attr.attr,
1257     &resume_attr.attr,
1258     &image_size_attr.attr,
1259     &reserved_size_attr.attr,
1260     NULL,
1261 };
1262 
1263 
1264 static const struct attribute_group attr_group = {
1265     .attrs = g,
1266 };
1267 
1268 
1269 static int __init pm_disk_init(void)
1270 {
1271     return sysfs_create_group(power_kobj, &attr_group);
1272 }
1273 
1274 core_initcall(pm_disk_init);
1275 
1276 
1277 static int __init resume_setup(char *str)
1278 {
1279     if (noresume)
1280         return 1;
1281 
1282     strncpy(resume_file, str, 255);
1283     return 1;
1284 }
1285 
1286 static int __init resume_offset_setup(char *str)
1287 {
1288     unsigned long long offset;
1289 
1290     if (noresume)
1291         return 1;
1292 
1293     if (sscanf(str, "%llu", &offset) == 1)
1294         swsusp_resume_block = offset;
1295 
1296     return 1;
1297 }
1298 
1299 static int __init hibernate_setup(char *str)
1300 {
1301     if (!strncmp(str, "noresume", 8)) {
1302         noresume = 1;
1303     } else if (!strncmp(str, "nocompress", 10)) {
1304         nocompress = 1;
1305     } else if (!strncmp(str, "no", 2)) {
1306         noresume = 1;
1307         nohibernate = 1;
1308     } else if (IS_ENABLED(CONFIG_STRICT_KERNEL_RWX)
1309            && !strncmp(str, "protect_image", 13)) {
1310         enable_restore_image_protection();
1311     }
1312     return 1;
1313 }
1314 
1315 static int __init noresume_setup(char *str)
1316 {
1317     noresume = 1;
1318     return 1;
1319 }
1320 
1321 static int __init resumewait_setup(char *str)
1322 {
1323     resume_wait = 1;
1324     return 1;
1325 }
1326 
1327 static int __init resumedelay_setup(char *str)
1328 {
1329     int rc = kstrtouint(str, 0, &resume_delay);
1330 
1331     if (rc)
1332         pr_warn("resumedelay: bad option string '%s'\n", str);
1333     return 1;
1334 }
1335 
1336 static int __init nohibernate_setup(char *str)
1337 {
1338     noresume = 1;
1339     nohibernate = 1;
1340     return 1;
1341 }
1342 
1343 __setup("noresume", noresume_setup);
1344 __setup("resume_offset=", resume_offset_setup);
1345 __setup("resume=", resume_setup);
1346 __setup("hibernate=", hibernate_setup);
1347 __setup("resumewait", resumewait_setup);
1348 __setup("resumedelay=", resumedelay_setup);
1349 __setup("nohibernate", nohibernate_setup);