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