hibernate.c 30.3 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0-only
Linus Torvalds's avatar
Linus Torvalds committed
2
/*
3
 * kernel/power/hibernate.c - Hibernation (a.k.a suspend-to-disk) support.
Linus Torvalds's avatar
Linus Torvalds committed
4 5 6
 *
 * Copyright (c) 2003 Patrick Mochel
 * Copyright (c) 2003 Open Source Development Lab
Pavel Machek's avatar
Pavel Machek committed
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>
Linus Torvalds's avatar
Linus Torvalds committed
10 11
 */

12
#define pr_fmt(fmt) "PM: hibernation: " fmt
13

14
#include <linux/export.h>
Linus Torvalds's avatar
Linus Torvalds committed
15 16 17 18
#include <linux/suspend.h>
#include <linux/reboot.h>
#include <linux/string.h>
#include <linux/device.h>
19
#include <linux/async.h>
Linus Torvalds's avatar
Linus Torvalds committed
20 21
#include <linux/delay.h>
#include <linux/fs.h>
22
#include <linux/mount.h>
23
#include <linux/pm.h>
24
#include <linux/nmi.h>
25
#include <linux/console.h>
26
#include <linux/cpu.h>
27
#include <linux/freezer.h>
28
#include <linux/gfp.h>
29
#include <linux/syscore_ops.h>
30 31
#include <linux/ctype.h>
#include <linux/genhd.h>
32
#include <linux/ktime.h>
33
#include <linux/security.h>
34
#include <trace/events/power.h>
35

Linus Torvalds's avatar
Linus Torvalds committed
36 37 38
#include "power.h"


39 40
static int nocompress;
static int noresume;
41
static int nohibernate;
42
static int resume_wait;
43
static unsigned int resume_delay;
44
static char resume_file[256] = CONFIG_PM_STD_PARTITION;
Linus Torvalds's avatar
Linus Torvalds committed
45
dev_t swsusp_resume_device;
46
sector_t swsusp_resume_block;
47
__visible int in_suspend __nosavedata;
Linus Torvalds's avatar
Linus Torvalds committed
48

49 50 51 52 53
enum {
	HIBERNATION_INVALID,
	HIBERNATION_PLATFORM,
	HIBERNATION_SHUTDOWN,
	HIBERNATION_REBOOT,
54 55 56
#ifdef CONFIG_SUSPEND
	HIBERNATION_SUSPEND,
#endif
57
	HIBERNATION_TEST_RESUME,
58 59 60 61 62 63 64 65
	/* keep last */
	__HIBERNATION_AFTER_LAST
};
#define HIBERNATION_MAX (__HIBERNATION_AFTER_LAST-1)
#define HIBERNATION_FIRST (HIBERNATION_INVALID + 1)

static int hibernation_mode = HIBERNATION_SHUTDOWN;

66
bool freezer_test_done;
67

68
static const struct platform_hibernation_ops *hibernation_ops;
69

70 71 72 73 74 75 76 77 78 79 80 81
static atomic_t hibernate_atomic = ATOMIC_INIT(1);

bool hibernate_acquire(void)
{
	return atomic_add_unless(&hibernate_atomic, -1, 0);
}

void hibernate_release(void)
{
	atomic_inc(&hibernate_atomic);
}

82 83
bool hibernation_available(void)
{
84
	return nohibernate == 0 && !security_locked_down(LOCKDOWN_HIBERNATION);
85 86
}

87
/**
88 89
 * hibernation_set_ops - Set the global hibernate operations.
 * @ops: Hibernation operations to use in subsequent hibernation transitions.
90
 */
91
void hibernation_set_ops(const struct platform_hibernation_ops *ops)
92
{
93 94
	if (ops && !(ops->begin && ops->end &&  ops->pre_snapshot
	    && ops->prepare && ops->finish && ops->enter && ops->pre_restore
95
	    && ops->restore_cleanup && ops->leave)) {
96 97 98
		WARN_ON(1);
		return;
	}
99
	lock_system_sleep();
100 101 102 103 104 105
	hibernation_ops = ops;
	if (ops)
		hibernation_mode = HIBERNATION_PLATFORM;
	else if (hibernation_mode == HIBERNATION_PLATFORM)
		hibernation_mode = HIBERNATION_SHUTDOWN;

106
	unlock_system_sleep();
107
}
108
EXPORT_SYMBOL_GPL(hibernation_set_ops);
109

110 111 112 113 114 115 116 117
static bool entering_platform_hibernation;

bool system_entering_hibernation(void)
{
	return entering_platform_hibernation;
}
EXPORT_SYMBOL(system_entering_hibernation);

118 119 120
#ifdef CONFIG_PM_DEBUG
static void hibernation_debug_sleep(void)
{
121
	pr_info("debug: Waiting for 5 seconds.\n");
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
	mdelay(5000);
}

static int hibernation_test(int level)
{
	if (pm_test_level == level) {
		hibernation_debug_sleep();
		return 1;
	}
	return 0;
}
#else /* !CONFIG_PM_DEBUG */
static int hibernation_test(int level) { return 0; }
#endif /* !CONFIG_PM_DEBUG */

137
/**
138 139
 * platform_begin - Call platform to start hibernation.
 * @platform_mode: Whether or not to use the platform driver.
140
 */
141
static int platform_begin(int platform_mode)
142 143
{
	return (platform_mode && hibernation_ops) ?
144
		hibernation_ops->begin(PMSG_FREEZE) : 0;
145 146 147
}

/**
148 149
 * platform_end - Call platform to finish transition to the working state.
 * @platform_mode: Whether or not to use the platform driver.
150 151 152 153 154
 */
static void platform_end(int platform_mode)
{
	if (platform_mode && hibernation_ops)
		hibernation_ops->end();
155
}
156

157
/**
158 159 160 161 162
 * platform_pre_snapshot - Call platform to prepare the machine for hibernation.
 * @platform_mode: Whether or not to use the platform driver.
 *
 * Use the platform driver to prepare the system for creating a hibernate image,
 * if so configured, and return an error code if that fails.
163 164
 */

165
static int platform_pre_snapshot(int platform_mode)
166
{
167
	return (platform_mode && hibernation_ops) ?
168
		hibernation_ops->pre_snapshot() : 0;
169
}
170

171
/**
172 173 174 175 176 177 178
 * platform_leave - Call platform to prepare a transition to the working state.
 * @platform_mode: Whether or not to use the platform driver.
 *
 * Use the platform driver prepare to prepare the machine for switching to the
 * normal mode of operation.
 *
 * This routine is called on one CPU with interrupts disabled.
179 180 181 182 183 184 185
 */
static void platform_leave(int platform_mode)
{
	if (platform_mode && hibernation_ops)
		hibernation_ops->leave();
}

186
/**
187 188 189 190 191 192 193
 * platform_finish - Call platform to switch the system to the working state.
 * @platform_mode: Whether or not to use the platform driver.
 *
 * Use the platform driver to switch the machine to the normal mode of
 * operation.
 *
 * This routine must be called after platform_prepare().
194
 */
195
static void platform_finish(int platform_mode)
196
{
197
	if (platform_mode && hibernation_ops)
198
		hibernation_ops->finish();
199 200
}

201
/**
202 203 204 205 206 207 208 209
 * platform_pre_restore - Prepare for hibernate image restoration.
 * @platform_mode: Whether or not to use the platform driver.
 *
 * Use the platform driver to prepare the system for resume from a hibernation
 * image.
 *
 * If the restore fails after this function has been called,
 * platform_restore_cleanup() must be called.
210 211 212 213 214 215 216 217
 */
static int platform_pre_restore(int platform_mode)
{
	return (platform_mode && hibernation_ops) ?
		hibernation_ops->pre_restore() : 0;
}

/**
218 219 220 221 222 223 224 225 226
 * platform_restore_cleanup - Switch to the working state after failing restore.
 * @platform_mode: Whether or not to use the platform driver.
 *
 * Use the platform driver to switch the system to the normal mode of operation
 * after a failing restore.
 *
 * If platform_pre_restore() has been called before the failing restore, this
 * function must be called too, regardless of the result of
 * platform_pre_restore().
227 228 229 230 231 232 233
 */
static void platform_restore_cleanup(int platform_mode)
{
	if (platform_mode && hibernation_ops)
		hibernation_ops->restore_cleanup();
}

234
/**
235 236
 * platform_recover - Recover from a failure to suspend devices.
 * @platform_mode: Whether or not to use the platform driver.
237 238 239 240 241 242 243
 */
static void platform_recover(int platform_mode)
{
	if (platform_mode && hibernation_ops && hibernation_ops->recover)
		hibernation_ops->recover();
}

244
/**
245 246 247 248 249
 * swsusp_show_speed - Print time elapsed between two events during hibernation.
 * @start: Starting event.
 * @stop: Final event.
 * @nr_pages: Number of memory pages processed between @start and @stop.
 * @msg: Additional diagnostic message to print.
250
 */
251 252
void swsusp_show_speed(ktime_t start, ktime_t stop,
		      unsigned nr_pages, char *msg)
253
{
254
	ktime_t diff;
255 256 257 258
	u64 elapsed_centisecs64;
	unsigned int centisecs;
	unsigned int k;
	unsigned int kps;
259

260 261
	diff = ktime_sub(stop, start);
	elapsed_centisecs64 = ktime_divns(diff, 10*NSEC_PER_MSEC);
262 263 264 265 266
	centisecs = elapsed_centisecs64;
	if (centisecs == 0)
		centisecs = 1;	/* avoid div-by-zero */
	k = nr_pages * (PAGE_SIZE / 1024);
	kps = (k * 100) / centisecs;
267 268 269
	pr_info("%s %u kbytes in %u.%02u seconds (%u.%02u MB/s)\n",
		msg, k, centisecs / 100, centisecs % 100, kps / 1000,
		(kps % 1000) / 10);
270 271
}

272 273 274 275 276
__weak int arch_resume_nosmt(void)
{
	return 0;
}

277
/**
278 279 280
 * create_image - Create a hibernation image.
 * @platform_mode: Whether or not to use the platform driver.
 *
281 282
 * Execute device drivers' "late" and "noirq" freeze callbacks, create a
 * hibernation image and run the drivers' "noirq" and "early" thaw callbacks.
283 284
 *
 * Control reappears in this routine after the subsequent restore.
285
 */
286
static int create_image(int platform_mode)
287 288 289
{
	int error;

290
	error = dpm_suspend_end(PMSG_FREEZE);
291
	if (error) {
292
		pr_err("Some devices failed to power down, aborting\n");
293
		return error;
294
	}
295

296 297 298 299
	error = platform_pre_snapshot(platform_mode);
	if (error || hibernation_test(TEST_PLATFORM))
		goto Platform_finish;

300
	error = suspend_disable_secondary_cpus();
301
	if (error || hibernation_test(TEST_CPUS))
302 303
		goto Enable_cpus;

304 305
	local_irq_disable();

306 307
	system_state = SYSTEM_SUSPEND;

308
	error = syscore_suspend();
309
	if (error) {
310
		pr_err("Some system devices failed to power down, aborting\n");
311
		goto Enable_irqs;
312
	}
313

314
	if (hibernation_test(TEST_CORE) || pm_wakeup_pending())
315 316 317
		goto Power_up;

	in_suspend = 1;
318
	save_processor_state();
319
	trace_suspend_resume(TPS("machine_suspend"), PM_EVENT_HIBERNATE, true);
320
	error = swsusp_arch_suspend();
321 322
	/* Restore control flow magically appears here */
	restore_processor_state();
323
	trace_suspend_resume(TPS("machine_suspend"), PM_EVENT_HIBERNATE, false);
324
	if (error)
325
		pr_err("Error %d creating image\n", error);
326

327
	if (!in_suspend) {
328
		events_check_enabled = false;
329 330
		clear_free_pages();
	}
331 332

	platform_leave(platform_mode);
333

334
 Power_up:
335
	syscore_resume();
336

337
 Enable_irqs:
338
	system_state = SYSTEM_RUNNING;
339 340
	local_irq_enable();

341
 Enable_cpus:
342
	suspend_enable_secondary_cpus();
343

344 345 346 347
	/* Allow architectures to do nosmt-specific post-resume dances */
	if (!in_suspend)
		error = arch_resume_nosmt();

348 349 350
 Platform_finish:
	platform_finish(platform_mode);

351
	dpm_resume_start(in_suspend ?
352
		(error ? PMSG_RECOVER : PMSG_THAW) : PMSG_RESTORE);
353

354 355 356
	return error;
}

357
/**
358 359
 * hibernation_snapshot - Quiesce devices and create a hibernation image.
 * @platform_mode: If set, use platform driver to prepare for the transition.
360
 *
361
 * This routine must be called with system_transition_mutex held.
362 363 364
 */
int hibernation_snapshot(int platform_mode)
{
365
	pm_message_t msg;
366
	int error;
367

368
	pm_suspend_clear_flags();
369
	error = platform_begin(platform_mode);
370
	if (error)
371
		goto Close;
372

373 374
	/* Preallocate image memory before shutting down devices. */
	error = hibernate_preallocate_memory();
375 376 377 378 379
	if (error)
		goto Close;

	error = freeze_kernel_threads();
	if (error)
380
		goto Cleanup;
381

382
	if (hibernation_test(TEST_FREEZER)) {
383 384 385 386 387 388

		/*
		 * Indicate to the caller that we are returning due to a
		 * successful freezer test.
		 */
		freezer_test_done = true;
389
		goto Thaw;
390 391
	}

392
	error = dpm_prepare(PMSG_FREEZE);
393
	if (error) {
394
		dpm_complete(PMSG_RECOVER);
395
		goto Thaw;
396
	}
397

398
	suspend_console();
399
	pm_restrict_gfp_mask();
400

401
	error = dpm_suspend(PMSG_FREEZE);
402

403 404 405 406
	if (error || hibernation_test(TEST_DEVICES))
		platform_recover(platform_mode);
	else
		error = create_image(platform_mode);
407

408
	/*
409 410
	 * In the case that we call create_image() above, the control
	 * returns here (1) after the image has been created or the
411 412
	 * image creation has failed and (2) after a successful restore.
	 */
413

414 415 416 417
	/* We may need to release the preallocated image pages here. */
	if (error || !in_suspend)
		swsusp_free();

418 419
	msg = in_suspend ? (error ? PMSG_RECOVER : PMSG_THAW) : PMSG_RESTORE;
	dpm_resume(msg);
420 421 422 423

	if (error || !in_suspend)
		pm_restore_gfp_mask();

424
	resume_console();
425 426
	dpm_complete(msg);

427 428
 Close:
	platform_end(platform_mode);
429
	return error;
430

431 432
 Thaw:
	thaw_kernel_threads();
433 434 435
 Cleanup:
	swsusp_free();
	goto Close;
436 437
}

438 439
int __weak hibernate_resume_nonboot_cpu_disable(void)
{
440
	return suspend_disable_secondary_cpus();
441 442
}

443
/**
444 445 446
 * resume_target_kernel - Restore system state from a hibernation image.
 * @platform_mode: Whether or not to use the platform driver.
 *
447 448 449 450
 * Execute device drivers' "noirq" and "late" freeze callbacks, restore the
 * contents of highmem that have not been restored yet from the image and run
 * the low-level code that will restore the remaining contents of memory and
 * switch to the just restored target kernel.
451
 */
452
static int resume_target_kernel(bool platform_mode)
453 454 455
{
	int error;

456
	error = dpm_suspend_end(PMSG_QUIESCE);
457
	if (error) {
458
		pr_err("Some devices failed to power down, aborting resume\n");
459
		return error;
460
	}
461

462 463 464 465
	error = platform_pre_restore(platform_mode);
	if (error)
		goto Cleanup;

466
	error = hibernate_resume_nonboot_cpu_disable();
467 468 469
	if (error)
		goto Enable_cpus;

470
	local_irq_disable();
471
	system_state = SYSTEM_SUSPEND;
472

473
	error = syscore_suspend();
474 475 476
	if (error)
		goto Enable_irqs;

477 478 479 480 481 482
	save_processor_state();
	error = restore_highmem();
	if (!error) {
		error = swsusp_arch_resume();
		/*
		 * The code below is only ever reached in case of a failure.
483 484
		 * Otherwise, execution continues at the place where
		 * swsusp_arch_suspend() was called.
485 486
		 */
		BUG_ON(!error);
487 488 489 490
		/*
		 * This call to restore_highmem() reverts the changes made by
		 * the previous one.
		 */
491 492 493 494 495
		restore_highmem();
	}
	/*
	 * The only reason why swsusp_arch_resume() can fail is memory being
	 * very tight, so we have to free it as soon as we can to avoid
496
	 * subsequent failures.
497 498 499 500
	 */
	swsusp_free();
	restore_processor_state();
	touch_softlockup_watchdog();
501

502
	syscore_resume();
503

504
 Enable_irqs:
505
	system_state = SYSTEM_RUNNING;
506
	local_irq_enable();
507

508
 Enable_cpus:
509
	suspend_enable_secondary_cpus();
510 511 512 513

 Cleanup:
	platform_restore_cleanup(platform_mode);

514
	dpm_resume_start(PMSG_RECOVER);
515

516 517 518
	return error;
}

519
/**
520 521
 * hibernation_restore - Quiesce devices and restore from a hibernation image.
 * @platform_mode: If set, use platform driver to prepare for the transition.
522
 *
523 524 525
 * This routine must be called with system_transition_mutex held.  If it is
 * successful, control reappears in the restored target kernel in
 * hibernation_snapshot().
526
 */
527
int hibernation_restore(int platform_mode)
528
{
529
	int error;
530 531 532

	pm_prepare_console();
	suspend_console();
533
	pm_restrict_gfp_mask();
534
	error = dpm_suspend_start(PMSG_QUIESCE);
535
	if (!error) {
536
		error = resume_target_kernel(platform_mode);
537 538 539 540 541 542
		/*
		 * The above should either succeed and jump to the new kernel,
		 * or return with an error. Otherwise things are just
		 * undefined, so let's be paranoid.
		 */
		BUG_ON(!error);
543
	}
544
	dpm_resume_end(PMSG_RECOVER);
545
	pm_restore_gfp_mask();
546 547 548 549 550 551
	resume_console();
	pm_restore_console();
	return error;
}

/**
552
 * hibernation_platform_enter - Power off the system using the platform driver.
553 554 555
 */
int hibernation_platform_enter(void)
{
556
	int error;
557

558 559 560 561 562 563 564 565
	if (!hibernation_ops)
		return -ENOSYS;

	/*
	 * We have cancelled the power transition by running
	 * hibernation_ops->finish() before saving the image, so we should let
	 * the firmware know that we're going to enter the sleep state after all
	 */
566
	error = hibernation_ops->begin(PMSG_HIBERNATE);
567
	if (error)
568
		goto Close;
569

570
	entering_platform_hibernation = true;
571
	suspend_console();
572
	error = dpm_suspend_start(PMSG_HIBERNATE);
573 574 575 576 577
	if (error) {
		if (hibernation_ops->recover)
			hibernation_ops->recover();
		goto Resume_devices;
	}
578

579
	error = dpm_suspend_end(PMSG_HIBERNATE);
580
	if (error)
581
		goto Resume_devices;
582

583 584
	error = hibernation_ops->prepare();
	if (error)
585
		goto Platform_finish;
586

587
	error = suspend_disable_secondary_cpus();
588
	if (error)
589
		goto Enable_cpus;
590

591
	local_irq_disable();
592
	system_state = SYSTEM_SUSPEND;
593
	syscore_suspend();
594
	if (pm_wakeup_pending()) {
595 596 597 598
		error = -EAGAIN;
		goto Power_up;
	}

599 600 601
	hibernation_ops->enter();
	/* We should never get here */
	while (1);
602

603
 Power_up:
604
	syscore_resume();
605
	system_state = SYSTEM_RUNNING;
606
	local_irq_enable();
607 608

 Enable_cpus:
609
	suspend_enable_secondary_cpus();
610

611
 Platform_finish:
612
	hibernation_ops->finish();
613

614
	dpm_resume_start(PMSG_RESTORE);
615

616
 Resume_devices:
617
	entering_platform_hibernation = false;
618
	dpm_resume_end(PMSG_RESTORE);
619
	resume_console();
620

621 622
 Close:
	hibernation_ops->end();
623

624
	return error;
625 626
}

Linus Torvalds's avatar
Linus Torvalds committed
627
/**
628
 * power_down - Shut the machine down for hibernation.
Linus Torvalds's avatar
Linus Torvalds committed
629
 *
630 631 632
 * Use the platform driver, if configured, to put the system into the sleep
 * state corresponding to hibernation, or try to power it off or reboot,
 * depending on the value of hibernation_mode.
Linus Torvalds's avatar
Linus Torvalds committed
633
 */
634
static void power_down(void)
Linus Torvalds's avatar
Linus Torvalds committed
635
{
636 637
#ifdef CONFIG_SUSPEND
	int error;
638 639 640 641 642 643 644 645 646 647 648

	if (hibernation_mode == HIBERNATION_SUSPEND) {
		error = suspend_devices_and_enter(PM_SUSPEND_MEM);
		if (error) {
			hibernation_mode = hibernation_ops ?
						HIBERNATION_PLATFORM :
						HIBERNATION_SHUTDOWN;
		} else {
			/* Restore swap signature. */
			error = swsusp_unmark();
			if (error)
649
				pr_err("Swap will be unusable! Try swapon -a.\n");
650 651 652 653

			return;
		}
	}
654 655
#endif

656 657
	switch (hibernation_mode) {
	case HIBERNATION_REBOOT:
658
		kernel_restart(NULL);
Linus Torvalds's avatar
Linus Torvalds committed
659
		break;
660
	case HIBERNATION_PLATFORM:
661
		hibernation_platform_enter();
662
		fallthrough;
663
	case HIBERNATION_SHUTDOWN:
664 665
		if (pm_power_off)
			kernel_power_off();
666
		break;
Linus Torvalds's avatar
Linus Torvalds committed
667
	}
668
	kernel_halt();
669 670 671 672
	/*
	 * Valid image is on the disk, if we continue we risk serious data
	 * corruption after resume.
	 */
673
	pr_crit("Power down manually\n");
674 675
	while (1)
		cpu_relax();
Linus Torvalds's avatar
Linus Torvalds committed
676 677
}

678 679 680 681 682
static int load_image_and_restore(void)
{
	int error;
	unsigned int flags;

683
	pm_pr_dbg("Loading hibernation image.\n");
684 685 686 687 688 689 690 691 692

	lock_device_hotplug();
	error = create_basic_memory_bitmaps();
	if (error)
		goto Unlock;

	error = swsusp_read(&flags);
	swsusp_close(FMODE_READ);
	if (!error)
693
		error = hibernation_restore(flags & SF_PLATFORM_MODE);
694

695
	pr_err("Failed to load image, recovering.\n");
696 697 698 699 700 701 702 703
	swsusp_free();
	free_basic_memory_bitmaps();
 Unlock:
	unlock_device_hotplug();

	return error;
}

Linus Torvalds's avatar
Linus Torvalds committed
704
/**
705
 * hibernate - Carry out system hibernation, including saving the image.
Linus Torvalds's avatar
Linus Torvalds committed
706
 */
707
int hibernate(void)
Linus Torvalds's avatar
Linus Torvalds committed
708
{
709
	bool snapshot_test = false;
710
	int error;
Linus Torvalds's avatar
Linus Torvalds committed
711

712
	if (!hibernation_available()) {
713
		pm_pr_dbg("Hibernation not available.\n");
714 715 716
		return -EPERM;
	}

717
	lock_system_sleep();
718
	/* The snapshot device should not be opened while we're running */
719
	if (!hibernate_acquire()) {
720 721 722 723
		error = -EBUSY;
		goto Unlock;
	}

724
	pr_info("hibernation entry\n");
725
	pm_prepare_console();
726 727 728
	error = pm_notifier_call_chain_robust(PM_HIBERNATION_PREPARE, PM_POST_HIBERNATION);
	if (error)
		goto Restore;
729

730
	ksys_sync_helper();
731

732
	error = freeze_processes();
733
	if (error)
734 735
		goto Exit;

736
	lock_device_hotplug();
737 738 739 740
	/* Allocate memory management structures */
	error = create_basic_memory_bitmaps();
	if (error)
		goto Thaw;
Linus Torvalds's avatar
Linus Torvalds committed
741

742
	error = hibernation_snapshot(hibernation_mode == HIBERNATION_PLATFORM);
743
	if (error || freezer_test_done)
744
		goto Free_bitmaps;
745 746

	if (in_suspend) {
747 748 749 750
		unsigned int flags = 0;

		if (hibernation_mode == HIBERNATION_PLATFORM)
			flags |= SF_PLATFORM_MODE;
751 752
		if (nocompress)
			flags |= SF_NOCOMPRESS_MODE;
753 754 755
		else
		        flags |= SF_CRC32_MODE;

756
		pm_pr_dbg("Writing hibernation image.\n");
757
		error = swsusp_write(flags);
758
		swsusp_free();
759 760 761 762 763 764
		if (!error) {
			if (hibernation_mode == HIBERNATION_TEST_RESUME)
				snapshot_test = true;
			else
				power_down();
		}
765
		in_suspend = 0;
766
		pm_restore_gfp_mask();
767
	} else {
768
		pm_pr_dbg("Hibernation image restored successfully.\n");
769
	}
770

771 772
 Free_bitmaps:
	free_basic_memory_bitmaps();
773
 Thaw:
774
	unlock_device_hotplug();
775
	if (snapshot_test) {
776
		pm_pr_dbg("Checking hibernation image\n");
777 778 779 780
		error = swsusp_check();
		if (!error)
			error = load_image_and_restore();
	}
781
	thaw_processes();
782 783 784

	/* Don't bother checking whether freezer_test_done is true */
	freezer_test_done = false;
785
 Exit:
786 787
	pm_notifier_call_chain(PM_POST_HIBERNATION);
 Restore:
788
	pm_restore_console();
789
	hibernate_release();
790
 Unlock:
791
	unlock_system_sleep();
792 793
	pr_info("hibernation exit\n");

Linus Torvalds's avatar
Linus Torvalds committed
794 795 796
	return error;
}

797 798 799 800 801 802 803 804 805
/**
 * hibernate_quiet_exec - Execute a function with all devices frozen.
 * @func: Function to execute.
 * @data: Data pointer to pass to @func.
 *
 * Return the @func return value or an error code if it cannot be executed.
 */
int hibernate_quiet_exec(int (*func)(void *data), void *data)
{
806
	int error;
807 808 809 810 811 812 813 814 815 816

	lock_system_sleep();

	if (!hibernate_acquire()) {
		error = -EBUSY;
		goto unlock;
	}

	pm_prepare_console();

817 818 819
	error = pm_notifier_call_chain_robust(PM_HIBERNATION_PREPARE, PM_POST_HIBERNATION);
	if (error)
		goto restore;
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879

	error = freeze_processes();
	if (error)
		goto exit;

	lock_device_hotplug();

	pm_suspend_clear_flags();

	error = platform_begin(true);
	if (error)
		goto thaw;

	error = freeze_kernel_threads();
	if (error)
		goto thaw;

	error = dpm_prepare(PMSG_FREEZE);
	if (error)
		goto dpm_complete;

	suspend_console();

	error = dpm_suspend(PMSG_FREEZE);
	if (error)
		goto dpm_resume;

	error = dpm_suspend_end(PMSG_FREEZE);
	if (error)
		goto dpm_resume;

	error = platform_pre_snapshot(true);
	if (error)
		goto skip;

	error = func(data);

skip:
	platform_finish(true);

	dpm_resume_start(PMSG_THAW);

dpm_resume:
	dpm_resume(PMSG_THAW);

	resume_console();

dpm_complete:
	dpm_complete(PMSG_THAW);

	thaw_kernel_threads();

thaw:
	platform_end(true);

	unlock_device_hotplug();

	thaw_processes();

exit:
880
	pm_notifier_call_chain(PM_POST_HIBERNATION);
881

882
restore:
883 884 885 886 887 888 889 890 891 892
	pm_restore_console();

	hibernate_release();

unlock:
	unlock_system_sleep();

	return error;
}
EXPORT_SYMBOL_GPL(hibernate_quiet_exec);
Linus Torvalds's avatar
Linus Torvalds committed
893 894

/**
895 896 897 898
 * software_resume - Resume from a saved hibernation image.
 *
 * This routine is called as a late initcall, when all devices have been
 * discovered and initialized already.
Linus Torvalds's avatar
Linus Torvalds committed
899
 *
900 901 902
 * The image reading code is called to see if there is a hibernation image
 * available for reading.  If that is the case, devices are quiesced and the
 * contents of memory is restored from the saved image.
Linus Torvalds's avatar
Linus Torvalds committed
903
 *
904
 * If this is successful, control reappears in the restored target kernel in
905
 * hibernation_snapshot() which returns to hibernate().  Otherwise, the routine
906 907
 * attempts to recover gracefully and make the kernel return to the normal mode
 * of operation.
Linus Torvalds's avatar
Linus Torvalds committed
908 909 910
 */
static int software_resume(void)
{
911
	int error;
Linus Torvalds's avatar
Linus Torvalds committed
912

913 914 915
	/*
	 * If the user said "noresume".. bail out early.
	 */
916
	if (noresume || !hibernation_available())
917 918
		return 0;

919 920 921 922
	/*
	 * name_to_dev_t() below takes a sysfs buffer mutex when sysfs
	 * is configured into the kernel. Since the regular hibernate
	 * trigger path is via sysfs which takes a buffer mutex before
923 924
	 * calling hibernate functions (which take system_transition_mutex)
	 * this can cause lockdep to complain about a possible ABBA deadlock
925 926 927 928
	 * which cannot happen since we're in the boot code here and
	 * sysfs can't be invoked yet. Therefore, we use a subclass
	 * here to avoid lockdep complaining.
	 */
929
	mutex_lock_nested(&system_transition_mutex, SINGLE_DEPTH_NESTING);
930 931 932 933 934 935 936 937 938

	if (swsusp_resume_device)
		goto Check_image;

	if (!strlen(resume_file)) {
		error = -ENOENT;
		goto Unlock;
	}

939
	pm_pr_dbg("Checking hibernation image partition %s\n", resume_file);
940

941
	if (resume_delay) {
942
		pr_info("Waiting %dsec before reading resume device ...\n",
943 944 945 946
			resume_delay);
		ssleep(resume_delay);
	}

947 948
	/* Check if the device is there */
	swsusp_resume_device = name_to_dev_t(resume_file);
949 950 951 952 953 954 955 956 957 958 959

	/*
	 * name_to_dev_t is ineffective to verify parition if resume_file is in
	 * integer format. (e.g. major:minor)
	 */
	if (isdigit(resume_file[0]) && resume_wait) {
		int partno;
		while (!get_gendisk(swsusp_resume_device, &partno))
			msleep(10);
	}

960
	if (!swsusp_resume_device) {
961 962 963 964 965
		/*
		 * Some device discovery might still be in progress; we need
		 * to wait for this to finish.
		 */
		wait_for_device_probe();
966 967 968 969 970 971 972

		if (resume_wait) {
			while ((swsusp_resume_device = name_to_dev_t(resume_file)) == 0)
				msleep(10);
			async_synchronize_full();
		}

973
		swsusp_resume_device = name_to_dev_t(resume_file);
974 975 976 977
		if (!swsusp_resume_device) {
			error = -ENODEV;
			goto Unlock;
		}
978 979
	}

980
 Check_image:
981
	pm_pr_dbg("Hibernation image partition %d:%d present\n",
982
		MAJOR(swsusp_resume_device), MINOR(swsusp_resume_device));
Linus Torvalds's avatar
Linus Torvalds committed
983

984
	pm_pr_dbg("Looking for hibernation image.\n");
985 986
	error = swsusp_check();
	if (error)
987
		goto Unlock;
Linus Torvalds's avatar
Linus Torvalds committed
988

989
	/* The snapshot device should not be opened while we're running */
990
	if (!hibernate_acquire()) {
991
		error = -EBUSY;
992
		swsusp_close(FMODE_READ);
993 994 995
		goto Unlock;
	}

996
	pr_info("resume from hibernation\n");
997
	pm_prepare_console();
998 999 1000
	error = pm_notifier_call_chain_robust(PM_RESTORE_PREPARE, PM_POST_RESTORE);
	if (error)
		goto Restore;
1001

1002
	pm_pr_dbg("Preparing processes for hibernation restore.\n");
1003
	error = freeze_processes();
1004 1005
	if (error)
		goto Close_Finish;
1006 1007 1008 1009 1010 1011 1012

	error = freeze_kernel_threads();
	if (error) {
		thaw_processes();
		goto Close_Finish;
	}

1013
	error = load_image_and_restore();
1014
	thaw_processes();
1015
 Finish:
1016 1017
	pm_notifier_call_chain(PM_POST_RESTORE);
 Restore:
1018
	pm_restore_console();
1019
	pr_info("resume failed (%d)\n", error);
1020
	hibernate_release();
1021
	/* For success case, the suspend path will release the lock */
1022
 Unlock:
1023
	mutex_unlock(&system_transition_mutex);
1024
	pm_pr_dbg("Hibernation image not present or could not be loaded.\n");
1025
	return error;
1026
 Close_Finish:
1027 1028
	swsusp_close(FMODE_READ);
	goto Finish;
Linus Torvalds's avatar
Linus Torvalds committed
1029 1030
}

1031
late_initcall_sync(software_resume);
Linus Torvalds's avatar
Linus Torvalds committed
1032 1033


1034 1035 1036 1037
static const char * const hibernation_modes[] = {
	[HIBERNATION_PLATFORM]	= "platform",
	[HIBERNATION_SHUTDOWN]	= "shutdown",
	[HIBERNATION_REBOOT]	= "reboot",
1038 1039 1040
#ifdef CONFIG_SUSPEND
	[HIBERNATION_SUSPEND]	= "suspend",
#endif
1041
	[HIBERNATION_TEST_RESUME]	= "test_resume",
Linus Torvalds's avatar
Linus Torvalds committed
1042 1043
};

1044 1045
/*
 * /sys/power/disk - Control hibernation mode.
Linus Torvalds's avatar
Linus Torvalds committed
1046
 *
1047 1048 1049
 * Hibernation can be handled in several ways.  There are a few different ways
 * to put the system into the sleep state: using the platform driver (e.g. ACPI
 * or other hibernation_ops), powering it off or rebooting it (for testing
1050
 * mostly).
Linus Torvalds's avatar
Linus Torvalds committed
1051
 *
1052 1053
 * The sysfs file /sys/power/disk provides an interface for selecting the
 * hibernation mode to use.  Reading from this file causes the available modes
1054
 * to be printed.  There are 3 modes that can be supported:
Linus Torvalds's avatar
Linus Torvalds committed
1055 1056 1057 1058 1059
 *
 *	'platform'
 *	'shutdown'
 *	'reboot'
 *
1060 1061 1062 1063 1064 1065 1066 1067
 * If a platform hibernation driver is in use, 'platform' will be supported
 * and will be used by default.  Otherwise, 'shutdown' will be used by default.
 * The selected option (i.e. the one corresponding to the current value of
 * hibernation_mode) is enclosed by a square bracket.
 *
 * To select a given hibernation mode it is necessary to write the mode's
 * string representation (as returned by reading from /sys/power/disk) back
 * into /sys/power/disk.
Linus Torvalds's avatar
Linus Torvalds committed
1068 1069
 */

1070 1071
static ssize_t disk_show(struct kobject *kobj, struct kobj_attribute *attr,
			 char *buf)
Linus Torvalds's avatar
Linus Torvalds committed
1072
{
1073 1074 1075
	int i;
	char *start = buf;

1076 1077 1078
	if (!hibernation_available())
		return sprintf(buf, "[disabled]\n");

1079 1080
	for (i = HIBERNATION_FIRST; i <= HIBERNATION_MAX; i++) {
		if (!hibernation_modes[i])
1081 1082
			continue;
		switch (i) {
1083 1084
		case HIBERNATION_SHUTDOWN:
		case HIBERNATION_REBOOT:
1085 1086 1087
#ifdef CONFIG_SUSPEND
		case HIBERNATION_SUSPEND:
#endif
1088
		case HIBERNATION_TEST_RESUME:
1089
			break;
1090 1091
		case HIBERNATION_PLATFORM:
			if (hibernation_ops)
1092 1093 1094 1095
				break;
			/* not a valid mode, continue with loop */
			continue;
		}
1096 1097
		if (i == hibernation_mode)
			buf += sprintf(buf, "[%s] ", hibernation_modes[i]);
1098
		else
1099
			buf += sprintf(buf, "%s ", hibernation_modes[i]);
1100 1101 1102
	}
	buf += sprintf(buf, "\n");
	return buf-start;
Linus Torvalds's avatar
Linus Torvalds committed
1103 1104
}

1105 1106
static ssize_t disk_store(struct kobject *kobj, struct kobj_attribute *attr,
			  const char *buf, size_t n)
Linus Torvalds's avatar
Linus Torvalds committed
1107 1108 1109 1110 1111
{
	int error = 0;
	int i;
	int len;
	char *p;
1112
	int mode = HIBERNATION_INVALID;
Linus Torvalds's avatar
Linus Torvalds committed
1113

1114 1115 1116
	if (!hibernation_available())
		return -EPERM;

Linus Torvalds's avatar
Linus Torvalds committed
1117 1118 1119
	p = memchr(buf, '\n', n);
	len = p ? p - buf : n;

1120
	lock_system_sleep();
1121
	for (i = HIBERNATION_FIRST; i <= HIBERNATION_MAX; i++) {
1122 1123
		if (len == strlen(hibernation_modes[i])
		    && !strncmp(buf, hibernation_modes[i], len)) {
Linus Torvalds's avatar
Linus Torvalds committed
1124 1125 1126 1127
			mode = i;
			break;
		}
	}
1128
	if (mode != HIBERNATION_INVALID) {
1129
		switch (mode) {
1130 1131
		case HIBERNATION_SHUTDOWN:
		case HIBERNATION_REBOOT:
1132 1133 1134
#ifdef CONFIG_SUSPEND
		case HIBERNATION_SUSPEND:
#endif
1135
		case HIBERNATION_TEST_RESUME:
1136
			hibernation_mode = mode;
1137
			break;
1138 1139 1140
		case HIBERNATION_PLATFORM:
			if (hibernation_ops)
				hibernation_mode = mode;
Linus Torvalds's avatar
Linus Torvalds committed
1141 1142 1143
			else
				error = -EINVAL;
		}
1144
	} else
Linus Torvalds's avatar
Linus Torvalds committed
1145 1146
		error = -EINVAL;

1147
	if (!error)
1148 1149
		pm_pr_dbg("Hibernation mode set to '%s'\n",
			       hibernation_modes[mode]);
1150
	unlock_system_sleep();
Linus Torvalds's avatar
Linus Torvalds committed
1151 1152 1153 1154 1155
	return error ? error : n;
}

power_attr(disk);

1156 1157
static ssize_t resume_show(struct kobject *kobj, struct kobj_attribute *attr,
			   char *buf)
Linus Torvalds's avatar
Linus Torvalds committed
1158
{
1159
	return sprintf(buf, "%d:%d\n", MAJOR(swsusp_resume_device),
Linus Torvalds's avatar
Linus Torvalds committed
1160 1161 1162
		       MINOR(swsusp_resume_device));
}

1163 1164
static ssize_t resume_store(struct kobject *kobj, struct kobj_attribute *attr,
			    const char *buf, size_t n)
Linus Torvalds's avatar
Linus Torvalds committed
1165 1166
{
	dev_t res;
1167 1168
	int len = n;
	char *name;
Linus Torvalds's avatar
Linus Torvalds committed
1169

1170 1171 1172 1173 1174
	if (len && buf[len-1] == '\n')
		len--;
	name = kstrndup(buf, len, GFP_KERNEL);
	if (!name)
		return -ENOMEM;
Linus Torvalds's avatar
Linus Torvalds committed
1175

1176 1177 1178 1179
	res = name_to_dev_t(name);
	kfree(name);
	if (!res)
		return -EINVAL;
Linus Torvalds's avatar
Linus Torvalds committed
1180

1181
	lock_system_sleep();
1182
	swsusp_resume_device = res;
1183
	unlock_system_sleep();
1184 1185
	pm_pr_dbg("Configured hibernation resume from disk to %u\n",
		  swsusp_resume_device);
1186 1187
	noresume = 0;
	software_resume();
1188
	return n;
Linus Torvalds's avatar
Linus Torvalds committed
1189 1190 1191 1192
}

power_attr(resume);

1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
static ssize_t resume_offset_show(struct kobject *kobj,
				  struct kobj_attribute *attr, char *buf)
{
	return sprintf(buf, "%llu\n", (unsigned long long)swsusp_resume_block);
}

static ssize_t resume_offset_store(struct kobject *kobj,
				   struct kobj_attribute *attr, const char *buf,
				   size_t n)
{
	unsigned long long offset;
	int rc;

	rc = kstrtoull(buf, 0, &offset);
	if (rc)
		return rc;
	swsusp_resume_block = offset;

	return n;
}

power_attr(resume_offset);

1216 1217
static ssize_t image_size_show(struct kobject *kobj, struct kobj_attribute *attr,
			       char *buf)
1218
{
1219
	return sprintf(buf, "%lu\n", image_size);
1220 1221
}

1222 1223
static ssize_t image_size_store(struct kobject *kobj, struct kobj_attribute *attr,
				const char *buf, size_t n)
1224
{
1225
	unsigned long size;
1226

1227
	if (sscanf(buf, "%lu", &size) == 1) {
1228 1229 1230 1231 1232 1233 1234 1235 1236
		image_size = size;
		return n;
	}

	return -EINVAL;
}

power_attr(image_size);

1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
static ssize_t reserved_size_show(struct kobject *kobj,
				  struct kobj_attribute *attr, char *buf)
{
	return sprintf(buf, "%lu\n", reserved_size);
}

static ssize_t reserved_size_store(struct kobject *kobj,
				   struct kobj_attribute *attr,
				   const char *buf, size_t n)
{
	unsigned long size;

	if (sscanf(buf, "%lu", &size) == 1) {
		reserved_size = size;
		return n;
	}

	return -EINVAL;
}

power_attr(reserved_size);

1259
static struct attribute *g[] = {
Linus Torvalds's avatar
Linus Torvalds committed
1260
	&disk_attr.attr,
1261
	&resume_offset_attr.attr,
Linus Torvalds's avatar
Linus Torvalds committed
1262
	&resume_attr.attr,
1263
	&image_size_attr.attr,
1264
	&reserved_size_attr.attr,
Linus Torvalds's avatar
Linus Torvalds committed
1265 1266 1267 1268
	NULL,
};


1269
static const struct attribute_group attr_group = {
Linus Torvalds's avatar
Linus Torvalds committed
1270 1271 1272 1273 1274 1275
	.attrs = g,
};


static int __init pm_disk_init(void)
{
1276
	return sysfs_create_group(power_kobj, &attr_group);
Linus Torvalds's avatar
Linus Torvalds committed
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
}

core_initcall(pm_disk_init);


static int __init resume_setup(char *str)
{
	if (noresume)
		return 1;

1287
	strncpy(resume_file, str, 255);
Linus Torvalds's avatar
Linus Torvalds committed
1288 1289 1290
	return 1;
}

1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
static int __init resume_offset_setup(char *str)
{
	unsigned long long offset;

	if (noresume)
		return 1;

	if (sscanf(str, "%llu", &offset) == 1)
		swsusp_resume_block = offset;

	return 1;
}

1304 1305
static int __init hibernate_setup(char *str)
{
1306
	if (!strncmp(str, "noresume", 8)) {
1307
		noresume = 1;
1308
	} else if (!strncmp(str, "nocompress", 10)) {
1309
		nocompress = 1;
1310
	} else if (!strncmp(str, "no", 2)) {
1311 1312
		noresume = 1;
		nohibernate = 1;
1313
	} else if (IS_ENABLED(CONFIG_STRICT_KERNEL_RWX)
1314 1315
		   && !strncmp(str, "protect_image", 13)) {
		enable_restore_image_protection();
1316
	}
1317 1318 1319
	return 1;
}

Linus Torvalds's avatar
Linus Torvalds committed
1320 1321 1322 1323 1324 1325
static int __init noresume_setup(char *str)
{
	noresume = 1;
	return 1;
}

1326 1327 1328 1329 1330 1331
static int __init resumewait_setup(char *str)
{
	resume_wait = 1;
	return 1;
}

1332 1333
static int __init resumedelay_setup(char *str)
{
1334
	int rc = kstrtouint(str, 0, &resume_delay);
1335 1336 1337

	if (rc)
		return rc;
1338 1339 1340
	return 1;
}

1341 1342 1343 1344 1345 1346 1347
static int __init nohibernate_setup(char *str)
{
	noresume = 1;
	nohibernate = 1;
	return 1;
}

Linus Torvalds's avatar
Linus Torvalds committed
1348
__setup("noresume", noresume_setup);
1349
__setup("resume_offset=", resume_offset_setup);
Linus Torvalds's avatar
Linus Torvalds committed
1350
__setup("resume=", resume_setup);
1351
__setup("hibernate=", hibernate_setup);
1352
__setup("resumewait", resumewait_setup);
1353
__setup("resumedelay=", resumedelay_setup);
1354
__setup("nohibernate", nohibernate_setup);