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