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