← Documents Documentation/power/swsusp.rst GitHub 원문 ↗

Linux 6.18.37 · Power

Swap suspend

Swap 기반 hibernation의 데이터 안전 조건, 진입·복구 절차, device 순서와 실전 FAQ를 설명합니다.

Source pathDocumentation/power/swsusp.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

요약·해설

swsusp.rst:1-503

Swap 기반 hibernation의 데이터 안전 조건, 진입·복구 절차, device 순서와 실전 FAQ를 설명합니다.

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

원문 전체 펼치기
1 ============
2 Swap suspend
3 ============
4
5 Some warnings, first.
6
7 .. warning::
8
9 **BIG FAT WARNING**
10
11 If you touch anything on disk between suspend and resume...
12 ...kiss your data goodbye.
13
14 If you do resume from initrd after your filesystems are mounted...
15 ...bye bye root partition.
16
17 [this is actually same case as above]
18
19 If you have unsupported ( ) devices using DMA, you may have some
20 problems. If your disk driver does not support suspend... (IDE does),
21 it may cause some problems, too. If you change kernel command line
22 between suspend and resume, it may do something wrong. If you change
23 your hardware while system is suspended... well, it was not good idea;
24 but it will probably only crash.
25
26 ( ) suspend/resume support is needed to make it safe.
27
28 If you have any filesystems on USB devices mounted before software suspend,
29 they won't be accessible after resume and you may lose data, as though
30 you have unplugged the USB devices with mounted filesystems on them;
31 see the FAQ below for details. (This is not true for more traditional
32 power states like "standby", which normally don't turn USB off.)
33
34 Swap partition:
35 You need to append resume=/dev/your_swap_partition to kernel command
36 line or specify it using /sys/power/resume.
37
38 Swap file:
39 If using a swapfile you can also specify a resume offset using
40 resume_offset=<number> on the kernel command line or specify it
41 in /sys/power/resume_offset.
42
43 After preparing then you suspend by::
44
45 echo shutdown > /sys/power/disk; echo disk > /sys/power/state
46
47 - If you feel ACPI works pretty well on your system, you might try::
48
49 echo platform > /sys/power/disk; echo disk > /sys/power/state
50
51 - If you would like to write hibernation image to swap and then suspend
52 to RAM (provided your platform supports it), you can try::
53
54 echo suspend > /sys/power/disk; echo disk > /sys/power/state
55
56 - If you have SATA disks, you'll need recent kernels with SATA suspend
57 support. For suspend and resume to work, make sure your disk drivers
58 are built into kernel -- not modules. [There's way to make
59 suspend/resume with modular disk drivers, see FAQ, but you probably
60 should not do that.]
61
62 If you want to limit the suspend image size to N bytes, do::
63
64 echo N > /sys/power/image_size
65
66 before suspend (it is limited to around 2/5 of available RAM by default).
67
68 - The resume process checks for the presence of the resume device,
69 if found, it then checks the contents for the hibernation image signature.
70 If both are found, it resumes the hibernation image.
71
72 - The resume process may be triggered in two ways:
73
74 1) During lateinit: If resume=/dev/your_swap_partition is specified on
75 the kernel command line, lateinit runs the resume process. If the
76 resume device has not been probed yet, the resume process fails and
77 bootup continues.
78 2) Manually from an initrd or initramfs: May be run from
79 the init script by using the /sys/power/resume file. It is vital
80 that this be done prior to remounting any filesystems (even as
81 read-only) otherwise data may be corrupted.
82
83 Article about goals and implementation of Software Suspend for Linux
84 ====================================================================
85
86 Author: Gábor Kuti
87 Last revised: 2003-10-20 by Pavel Machek
88
89 Idea and goals to achieve
90 -------------------------
91
92 Nowadays it is common in several laptops that they have a suspend button. It
93 saves the state of the machine to a filesystem or to a partition and switches
94 to standby mode. Later resuming the machine the saved state is loaded back to
95 ram and the machine can continue its work. It has two real benefits. First we
96 save ourselves the time machine goes down and later boots up, energy costs
97 are real high when running from batteries. The other gain is that we don't have
98 to interrupt our programs so processes that are calculating something for a long
99 time shouldn't need to be written interruptible.
100
101 swsusp saves the state of the machine into active swaps and then reboots or
102 powerdowns. You must explicitly specify the swap partition to resume from with
103 `resume=` kernel option. If signature is found it loads and restores saved
104 state. If the option `noresume` is specified as a boot parameter, it skips
105 the resuming. If the option `hibernate=nocompress` is specified as a boot
106 parameter, it saves hibernation image without compression.
107
108 In the meantime while the system is suspended you should not add/remove any
109 of the hardware, write to the filesystems, etc.
110
111 Sleep states summary
112 ====================
113
114 There are three different interfaces you can use, /proc/acpi should
115 work like this:
116
117 In a really perfect world::
118
119 echo 1 > /proc/acpi/sleep # for standby
120 echo 2 > /proc/acpi/sleep # for suspend to ram
121 echo 3 > /proc/acpi/sleep # for suspend to ram, but with more power
122 # conservative
123 echo 4 > /proc/acpi/sleep # for suspend to disk
124 echo 5 > /proc/acpi/sleep # for shutdown unfriendly the system
125
126 and perhaps::
127
128 echo 4b > /proc/acpi/sleep # for suspend to disk via s4bios
129
130 Frequently Asked Questions
131 ==========================
132
133 Q:
134 well, suspending a server is IMHO a really stupid thing,
135 but... (Diego Zuccato):
136
137 A:
138 You bought new UPS for your server. How do you install it without
139 bringing machine down? Suspend to disk, rearrange power cables,
140 resume.
141
142 You have your server on UPS. Power died, and UPS is indicating 30
143 seconds to failure. What do you do? Suspend to disk.
144
145
146 Q:
147 Maybe I'm missing something, but why don't the regular I/O paths work?
148
149 A:
150 We do use the regular I/O paths. However we cannot restore the data
151 to its original location as we load it. That would create an
152 inconsistent kernel state which would certainly result in an oops.
153 Instead, we load the image into unused memory and then atomically copy
154 it back to it original location. This implies, of course, a maximum
155 image size of half the amount of memory.
156
157 There are two solutions to this:
158
159 * require half of memory to be free during suspend. That way you can
160 read "new" data onto free spots, then cli and copy
161
162 * assume we had special "polling" ide driver that only uses memory
163 between 0-640KB. That way, I'd have to make sure that 0-640KB is free
164 during suspending, but otherwise it would work...
165
166 suspend2 shares this fundamental limitation, but does not include user
167 data and disk caches into "used memory" by saving them in
168 advance. That means that the limitation goes away in practice.
169
170 Q:
171 Does linux support ACPI S4?
172
173 A:
174 Yes. That's what echo platform > /sys/power/disk does.
175
176 Q:
177 What is 'suspend2'?
178
179 A:
180 suspend2 is 'Software Suspend 2', a forked implementation of
181 suspend-to-disk which is available as separate patches for 2.4 and 2.6
182 kernels from swsusp.sourceforge.net. It includes support for SMP, 4GB
183 highmem and preemption. It also has a extensible architecture that
184 allows for arbitrary transformations on the image (compression,
185 encryption) and arbitrary backends for writing the image (eg to swap
186 or an NFS share[Work In Progress]). Questions regarding suspend2
187 should be sent to the mailing list available through the suspend2
188 website, and not to the Linux Kernel Mailing List. We are working
189 toward merging suspend2 into the mainline kernel.
190
191 Q:
192 What is the freezing of tasks and why are we using it?
193
194 A:
195 The freezing of tasks is a mechanism by which user space processes and some
196 kernel threads are controlled during hibernation or system-wide suspend (on
197 some architectures). See freezing-of-tasks.txt for details.
198
199 Q:
200 What is the difference between "platform" and "shutdown"?
201
202 A:
203 shutdown:
204 save state in linux, then tell bios to powerdown
205
206 platform:
207 save state in linux, then tell bios to powerdown and blink
208 "suspended led"
209
210 "platform" is actually right thing to do where supported, but
211 "shutdown" is most reliable (except on ACPI systems).
212
213 Q:
214 I do not understand why you have such strong objections to idea of
215 selective suspend.
216
217 A:
218 Do selective suspend during runtime power management, that's okay. But
219 it's useless for suspend-to-disk. (And I do not see how you could use
220 it for suspend-to-ram, I hope you do not want that).
221
222 Lets see, so you suggest to
223
224 * SUSPEND all but swap device and parents
225 * Snapshot
226 * Write image to disk
227 * SUSPEND swap device and parents
228 * Powerdown
229
230 Oh no, that does not work, if swap device or its parents uses DMA,
231 you've corrupted data. You'd have to do
232
233 * SUSPEND all but swap device and parents
234 * FREEZE swap device and parents
235 * Snapshot
236 * UNFREEZE swap device and parents
237 * Write
238 * SUSPEND swap device and parents
239
240 Which means that you still need that FREEZE state, and you get more
241 complicated code. (And I have not yet introduce details like system
242 devices).
243
244 Q:
245 There don't seem to be any generally useful behavioral
246 distinctions between SUSPEND and FREEZE.
247
248 A:
249 Doing SUSPEND when you are asked to do FREEZE is always correct,
250 but it may be unnecessarily slow. If you want your driver to stay simple,
251 slowness may not matter to you. It can always be fixed later.
252
253 For devices like disk it does matter, you do not want to spindown for
254 FREEZE.
255
256 Q:
257 After resuming, system is paging heavily, leading to very bad interactivity.
258
259 A:
260 Try running::
261
262 cat /proc/[0-9]*/maps | grep / | sed 's:.* /:/:' | sort -u | while read file
263 do
264 test -f "$file" && cat "$file" > /dev/null
265 done
266
267 after resume. swapoff -a; swapon -a may also be useful.
268
269 Q:
270 What happens to devices during swsusp? They seem to be resumed
271 during system suspend?
272
273 A:
274 That's correct. We need to resume them if we want to write image to
275 disk. Whole sequence goes like
276
277 **Suspend part**
278
279 running system, user asks for suspend-to-disk
280
281 user processes are stopped
282
283 suspend(PMSG_FREEZE): devices are frozen so that they don't interfere
284 with state snapshot
285
286 state snapshot: copy of whole used memory is taken with interrupts
287 disabled
288
289 resume(): devices are woken up so that we can write image to swap
290
291 write image to swap
292
293 suspend(PMSG_SUSPEND): suspend devices so that we can power off
294
295 turn the power off
296
297 **Resume part**
298
299 (is actually pretty similar)
300
301 running system, user asks for suspend-to-disk
302
303 user processes are stopped (in common case there are none,
304 but with resume-from-initrd, no one knows)
305
306 read image from disk
307
308 suspend(PMSG_FREEZE): devices are frozen so that they don't interfere
309 with image restoration
310
311 image restoration: rewrite memory with image
312
313 resume(): devices are woken up so that system can continue
314
315 thaw all user processes
316
317 Q:
318 What is this 'Encrypt suspend image' for?
319
320 A:
321 First of all: it is not a replacement for dm-crypt encrypted swap.
322 It cannot protect your computer while it is suspended. Instead it does
323 protect from leaking sensitive data after resume from suspend.
324
325 Think of the following: you suspend while an application is running
326 that keeps sensitive data in memory. The application itself prevents
327 the data from being swapped out. Suspend, however, must write these
328 data to swap to be able to resume later on. Without suspend encryption
329 your sensitive data are then stored in plaintext on disk. This means
330 that after resume your sensitive data are accessible to all
331 applications having direct access to the swap device which was used
332 for suspend. If you don't need swap after resume these data can remain
333 on disk virtually forever. Thus it can happen that your system gets
334 broken in weeks later and sensitive data which you thought were
335 encrypted and protected are retrieved and stolen from the swap device.
336 To prevent this situation you should use 'Encrypt suspend image'.
337
338 During suspend a temporary key is created and this key is used to
339 encrypt the data written to disk. When, during resume, the data was
340 read back into memory the temporary key is destroyed which simply
341 means that all data written to disk during suspend are then
342 inaccessible so they can't be stolen later on. The only thing that
343 you must then take care of is that you call 'mkswap' for the swap
344 partition used for suspend as early as possible during regular
345 boot. This asserts that any temporary key from an oopsed suspend or
346 from a failed or aborted resume is erased from the swap device.
347
348 As a rule of thumb use encrypted swap to protect your data while your
349 system is shut down or suspended. Additionally use the encrypted
350 suspend image to prevent sensitive data from being stolen after
351 resume.
352
353 Q:
354 Can I suspend to a swap file?
355
356 A:
357 Generally, yes, you can. However, it requires you to use the "resume=" and
358 "resume_offset=" kernel command line parameters, so the resume from a swap
359 file cannot be initiated from an initrd or initramfs image. See
360 swsusp-and-swap-files.txt for details.
361
362 Q:
363 Is there a maximum system RAM size that is supported by swsusp?
364
365 A:
366 It should work okay with highmem.
367
368 Q:
369 Does swsusp (to disk) use only one swap partition or can it use
370 multiple swap partitions (aggregate them into one logical space)?
371
372 A:
373 Only one swap partition, sorry.
374
375 Q:
376 If my application(s) causes lots of memory & swap space to be used
377 (over half of the total system RAM), is it correct that it is likely
378 to be useless to try to suspend to disk while that app is running?
379
380 A:
381 No, it should work okay, as long as your app does not mlock()
382 it. Just prepare big enough swap partition.
383
384 Q:
385 What information is useful for debugging suspend-to-disk problems?
386
387 A:
388 Well, last messages on the screen are always useful. If something
389 is broken, it is usually some kernel driver, therefore trying with as
390 little as possible modules loaded helps a lot. I also prefer people to
391 suspend from console, preferably without X running. Booting with
392 init=/bin/bash, then swapon and starting suspend sequence manually
393 usually does the trick. Then it is good idea to try with latest
394 vanilla kernel.
395
396 Q:
397 How can distributions ship a swsusp-supporting kernel with modular
398 disk drivers (especially SATA)?
399
400 A:
401 Well, it can be done, load the drivers, then do echo into
402 /sys/power/resume file from initrd. Be sure not to mount
403 anything, not even read-only mount, or you are going to lose your
404 data.
405
406 Q:
407 How do I make suspend more verbose?
408
409 A:
410 If you want to see any non-error kernel messages on the virtual
411 terminal the kernel switches to during suspend, you have to set the
412 kernel console loglevel to at least 4 (KERN_WARNING), for example by
413 doing::
414
415 # save the old loglevel
416 read LOGLEVEL DUMMY < /proc/sys/kernel/printk
417 # set the loglevel so we see the progress bar.
418 # if the level is higher than needed, we leave it alone.
419 if [ $LOGLEVEL -lt 5 ]; then
420 echo 5 > /proc/sys/kernel/printk
421 fi
422
423 IMG_SZ=0
424 read IMG_SZ < /sys/power/image_size
425 echo -n disk > /sys/power/state
426 RET=$?
427 #
428 # the logic here is:
429 # if image_size > 0 (without kernel support, IMG_SZ will be zero),
430 # then try again with image_size set to zero.
431 if [ $RET -ne 0 -a $IMG_SZ -ne 0 ]; then # try again with minimal image size
432 echo 0 > /sys/power/image_size
433 echo -n disk > /sys/power/state
434 RET=$?
435 fi
436
437 # restore previous loglevel
438 echo $LOGLEVEL > /proc/sys/kernel/printk
439 exit $RET
440
441 Q:
442 Is this true that if I have a mounted filesystem on a USB device and
443 I suspend to disk, I can lose data unless the filesystem has been mounted
444 with "sync"?
445
446 A:
447 That's right ... if you disconnect that device, you may lose data.
448 In fact, even with "-o sync" you can lose data if your programs have
449 information in buffers they haven't written out to a disk you disconnect,
450 or if you disconnect before the device finished saving data you wrote.
451
452 Software suspend normally powers down USB controllers, which is equivalent
453 to disconnecting all USB devices attached to your system.
454
455 Your system might well support low-power modes for its USB controllers
456 while the system is asleep, maintaining the connection, using true sleep
457 modes like "suspend-to-RAM" or "standby". (Don't write "disk" to the
458 /sys/power/state file; write "standby" or "mem".) We've not seen any
459 hardware that can use these modes through software suspend, although in
460 theory some systems might support "platform" modes that won't break the
461 USB connections.
462
463 Remember that it's always a bad idea to unplug a disk drive containing a
464 mounted filesystem. That's true even when your system is asleep! The
465 safest thing is to unmount all filesystems on removable media (such USB,
466 Firewire, CompactFlash, MMC, external SATA, or even IDE hotplug bays)
467 before suspending; then remount them after resuming.
468
469 There is a work-around for this problem. For more information, see
470 Documentation/driver-api/usb/persist.rst.
471
472 Q:
473 Can I suspend-to-disk using a swap partition under LVM?
474
475 A:
476 Yes and No. You can suspend successfully, but the kernel will not be able
477 to resume on its own. You need an initramfs that can recognize the resume
478 situation, activate the logical volume containing the swap volume (but not
479 touch any filesystems!), and eventually call::
480
481 echo -n "$major:$minor" > /sys/power/resume
482
483 where $major and $minor are the respective major and minor device numbers of
484 the swap volume.
485
486 uswsusp works with LVM, too. See http://suspend.sourceforge.net/
487
488 Q:
489 I upgraded the kernel from 2.6.15 to 2.6.16. Both kernels were
490 compiled with the similar configuration files. Anyway I found that
491 suspend to disk (and resume) is much slower on 2.6.16 compared to
492 2.6.15. Any idea for why that might happen or how can I speed it up?
493
494 A:
495 This is because the size of the suspend image is now greater than
496 for 2.6.15 (by saving more data we can get more responsive system
497 after resume).
498
499 There's the /sys/power/image_size knob that controls the size of the
500 image. If you set it to 0 (eg. by echo 0 > /sys/power/image_size as
501 root), the 2.6.15 behavior should be restored. If it is still too
502 slow, take a look at suspend.sf.net -- userland suspend is faster and
503 supports LZF compression to speed it up further.
504

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

가장 먼저 확인할 데이터 손상 경고

1-33

Software suspend 뒤 resume하기 전까지 disk의 내용을 조금이라도 바꾸면 저장된 memory image와 disk 상태가 서로 달라져 data를 잃을 수 있습니다. Initrd에서 filesystem을 mount한 뒤 resume하는 것도 같은 문제이므로 root partition까지 손상될 수 있습니다.

DMA를 사용하는데 suspend/resume을 지원하지 않는 device, suspend를 지원하지 않는 disk driver, suspend와 resume 사이에 바뀐 kernel command line 또는 hardware 구성도 문제를 일으킬 수 있습니다. Device가 안전하려면 명시적인 suspend/resume 지원이 필요합니다.

Software suspend 전에 USB device의 filesystem을 mount해 두면 resume 뒤 접근하지 못할 수 있고, mount한 채 device를 뽑은 것처럼 data가 손실될 수 있습니다. USB 전원을 보통 끄지 않는 `standby` 같은 전통적인 power state에는 이 설명이 그대로 적용되지 않습니다.

Swsusp가 보존한다고 가정하는 상태
변경결과
Disk 또는 mounted filesystem 기록Image와 disk 불일치, data corruption
Initrd에서 mount 후 resumeRoot filesystem 손상 가능
지원하지 않는 DMA deviceMemory 손상 또는 crash 가능
Kernel command line/hardware 변경복구 실패 또는 crash 가능

Image를 기록한 순간의 memory와 storage·hardware 상태가 resume 순간까지 일치해야 합니다.

============
Swap suspend
============

Some warnings, first.

.. warning::

   **BIG FAT WARNING**

   If you touch anything on disk between suspend and resume...
                                ...kiss your data goodbye.

   If you do resume from initrd after your filesystems are mounted...
                                ...bye bye root partition.

                        [this is actually same case as above]

   If you have unsupported ( ) devices using DMA, you may have some
   problems. If your disk driver does not support suspend... (IDE does),
   it may cause some problems, too. If you change kernel command line
   between suspend and resume, it may do something wrong. If you change
   your hardware while system is suspended... well, it was not good idea;
   but it will probably only crash.

   ( ) suspend/resume support is needed to make it safe.

   If you have any filesystems on USB devices mounted before software suspend,
   they won't be accessible after resume and you may lose data, as though
   you have unplugged the USB devices with mounted filesystems on them;
   see the FAQ below for details.  (This is not true for more traditional
   power states like "standby", which normally don't turn USB off.)

Swap 지정, hibernation 진입과 resume 시점

34-82

Swap partition을 사용할 때는 kernel command line에 `resume=/dev/your_swap_partition`을 추가하거나 `/sys/power/resume`으로 device를 지정합니다. Swap file은 여기에 `resume_offset=<number>` 또는 `/sys/power/resume_offset`으로 file header의 offset도 지정해야 합니다.

준비가 끝나면 `shutdown` mode로 image를 swap에 기록한 뒤 전원을 끌 수 있습니다. ACPI가 안정적으로 동작하면 `platform`을, image를 기록한 뒤 suspend-to-RAM으로 들어가려면 platform 지원을 전제로 `suspend`를 선택합니다.

echo shutdown > /sys/power/disk; echo disk > /sys/power/state
echo platform > /sys/power/disk; echo disk > /sys/power/state
echo suspend > /sys/power/disk; echo disk > /sys/power/state

SATA disk에는 SATA suspend를 지원하는 최신 kernel이 필요합니다. Suspend와 resume에 필요한 disk driver는 kernel에 built-in으로 넣는 편이 안전합니다. Modular disk driver도 initrd에서 준비할 수 있지만 이 문서의 FAQ는 일반적으로 권하지 않습니다.

Image 크기를 N byte로 제한하려면 suspend 전에 `echo N > /sys/power/image_size`를 실행합니다. 기본 한도는 사용 가능한 RAM의 약 2/5입니다.

Resume 과정은 resume device가 존재하는지 확인한 다음 hibernation image signature를 검사하고, 둘 다 있으면 image를 복구합니다. `resume=`이 command line에 있으면 `lateinit`에서 시도하지만 device probe가 아직 끝나지 않았으면 실패한 채 boot를 계속합니다.

다른 방법은 initrd 또는 initramfs의 init script에서 `/sys/power/resume`을 쓰는 것입니다. 이 호출은 read-only를 포함해 어떤 filesystem도 다시 mount하기 전에 반드시 실행해야 합니다.

Hibernation과 resume 진입점
configure resume device/offsetselect shutdown, platform, or suspendwrite disk to /sys/power/stateboot kernellateinit resume= or initrd /sys/power/resumeverify signaturerestore image

Resume device 접근 전에 filesystem 상태를 바꾸지 않는 것이 핵심입니다.

Swap partition:
  You need to append resume=/dev/your_swap_partition to kernel command
  line or specify it using /sys/power/resume.

Swap file:
  If using a swapfile you can also specify a resume offset using
  resume_offset=<number> on the kernel command line or specify it
  in /sys/power/resume_offset.

After preparing then you suspend by::

        echo shutdown > /sys/power/disk; echo disk > /sys/power/state

- If you feel ACPI works pretty well on your system, you might try::

        echo platform > /sys/power/disk; echo disk > /sys/power/state

- If you would like to write hibernation image to swap and then suspend
  to RAM (provided your platform supports it), you can try::

        echo suspend > /sys/power/disk; echo disk > /sys/power/state

- If you have SATA disks, you'll need recent kernels with SATA suspend
  support. For suspend and resume to work, make sure your disk drivers
  are built into kernel -- not modules. [There's way to make
  suspend/resume with modular disk drivers, see FAQ, but you probably
  should not do that.]

If you want to limit the suspend image size to N bytes, do::

        echo N > /sys/power/image_size

before suspend (it is limited to around 2/5 of available RAM by default).

- The resume process checks for the presence of the resume device,
  if found, it then checks the contents for the hibernation image signature.
  If both are found, it resumes the hibernation image.

- The resume process may be triggered in two ways:

  1) During lateinit:  If resume=/dev/your_swap_partition is specified on
     the kernel command line, lateinit runs the resume process.  If the
     resume device has not been probed yet, the resume process fails and
     bootup continues.
  2) Manually from an initrd or initramfs:  May be run from
     the init script by using the /sys/power/resume file.  It is vital
     that this be done prior to remounting any filesystems (even as
     read-only) otherwise data may be corrupted.

Software Suspend의 목표와 boot parameter

83-110

이 글은 Gábor Kuti가 작성하고 Pavel Machek이 2003년 10월 20일 마지막으로 개정한 Linux Software Suspend의 목표와 구현 개요입니다.

Laptop의 suspend button은 machine state를 filesystem이나 partition에 저장하고 standby 상태로 전환합니다. 나중에 state를 RAM으로 다시 읽으면 기존 작업을 이어갈 수 있습니다. 이 방식은 종료와 boot 시간을 줄여 battery 사용량을 낮추고, 긴 계산을 수행하는 program을 중단 가능하게 따로 작성하지 않아도 된다는 장점이 있습니다.

`swsusp`는 machine state를 active swap에 저장한 뒤 reboot하거나 전원을 끕니다. Resume할 swap partition은 `resume=` kernel option으로 명시해야 합니다. Signature를 발견하면 저장된 state를 읽어 복원하고, `noresume` boot parameter가 있으면 복구를 건너뜁니다. `hibernate=nocompress`를 지정하면 hibernation image를 압축하지 않고 저장합니다.

System이 suspended 상태인 동안 hardware를 추가·제거하거나 filesystem에 기록해서는 안 됩니다.

주요 boot parameter
Parameter효과
resume=복구할 swap partition 지정
noresume저장된 image 복구 생략
hibernate=nocompressImage compression 비활성화

Image 탐색과 저장 형식을 boot 단계에서 결정합니다.

Article about goals and implementation of Software Suspend for Linux
====================================================================

Author: Gábor Kuti
Last revised: 2003-10-20 by Pavel Machek

Idea and goals to achieve
-------------------------

Nowadays it is common in several laptops that they have a suspend button. It
saves the state of the machine to a filesystem or to a partition and switches
to standby mode. Later resuming the machine the saved state is loaded back to
ram and the machine can continue its work. It has two real benefits. First we
save ourselves the time machine goes down and later boots up, energy costs
are real high when running from batteries. The other gain is that we don't have
to interrupt our programs so processes that are calculating something for a long
time shouldn't need to be written interruptible.

swsusp saves the state of the machine into active swaps and then reboots or
powerdowns.  You must explicitly specify the swap partition to resume from with
`resume=` kernel option. If signature is found it loads and restores saved
state. If the option `noresume` is specified as a boot parameter, it skips
the resuming.  If the option `hibernate=nocompress` is specified as a boot
parameter, it saves hibernation image without compression.

In the meantime while the system is suspended you should not add/remove any
of the hardware, write to the filesystems, etc.

과거 ACPI sleep interface 요약

111-129

문서가 작성되던 시점에는 세 가지 interface가 있었으며, 여기서는 `/proc/acpi/sleep`의 이상적인 동작 예를 보여 줍니다. 값 1은 standby, 2는 suspend-to-RAM, 3은 전력을 더 절약하는 suspend-to-RAM, 4는 suspend-to-disk, 5는 system을 비정상적으로 shutdown하는 동작입니다. `4b`는 S4 BIOS를 통한 suspend-to-disk를 뜻할 수 있습니다.

echo 1 > /proc/acpi/sleep       # standby
echo 2 > /proc/acpi/sleep       # suspend to RAM
echo 3 > /proc/acpi/sleep       # more power-conservative suspend to RAM
echo 4 > /proc/acpi/sleep       # suspend to disk
echo 5 > /proc/acpi/sleep       # unfriendly shutdown
echo 4b > /proc/acpi/sleep      # suspend to disk via s4bios

이 절은 역사적인 `/proc/acpi/sleep` interface를 설명합니다. 현재 hibernation 진입은 앞 절의 `/sys/power/disk`와 `/sys/power/state` interface를 기준으로 판단해야 합니다.

Sleep states summary
====================

There are three different interfaces you can use, /proc/acpi should
work like this:

In a really perfect world::

  echo 1 > /proc/acpi/sleep       # for standby
  echo 2 > /proc/acpi/sleep       # for suspend to ram
  echo 3 > /proc/acpi/sleep       # for suspend to ram, but with more power
                                  # conservative
  echo 4 > /proc/acpi/sleep       # for suspend to disk
  echo 5 > /proc/acpi/sleep       # for shutdown unfriendly the system

and perhaps::

  echo 4b > /proc/acpi/sleep      # for suspend to disk via s4bios

FAQ: Server 활용과 image 복원 방식

130-169

Q: Server를 suspend하는 것은 무의미하지 않습니까? A: 새 UPS를 설치하려고 power cable을 재배치해야 할 때 server를 disk에 suspend한 뒤 작업하고 resume할 수 있습니다. UPS가 정전 뒤 30초 안에 꺼질 예정이라고 알릴 때도 suspend-to-disk로 현재 상태를 보존할 수 있습니다.

Q: 왜 일반 I/O 경로만으로 바로 복원하지 못합니까? A: 실제 I/O 경로는 일반 경로를 사용하지만, image를 읽는 즉시 원래 memory 위치에 덮어쓰면 실행 중인 kernel state가 불일치해 oops가 납니다. 따라서 image를 사용하지 않는 memory에 먼저 읽고, 마지막에 원래 위치로 atomic copy합니다. 이 구조는 원칙적으로 image 크기를 memory 절반으로 제한합니다.

해결책 하나는 suspend할 때 memory 절반을 비워 새 data를 free area에 읽은 뒤 interrupt를 끄고 copy하는 것입니다. 다른 가상 해법은 0-640KB만 쓰는 polling IDE driver를 두고 suspend할 때 그 영역만 비워 두는 것입니다.

당시 별도 구현인 `suspend2`도 같은 근본 제한이 있지만 user data와 disk cache를 미리 저장해 used memory 계산에서 제외했으므로 실사용에서는 제한을 줄였습니다.

Image 복원의 memory 제약
reserve unused memoryread hibernation imagedisable interruptsatomically copy to original locationsresume saved kernel state

실행 중인 kernel을 망가뜨리지 않도록 image를 임시 영역에 먼저 읽습니다.

Frequently Asked Questions
==========================

Q:
  well, suspending a server is IMHO a really stupid thing,
  but... (Diego Zuccato):

A:
  You bought new UPS for your server. How do you install it without
  bringing machine down? Suspend to disk, rearrange power cables,
  resume.

  You have your server on UPS. Power died, and UPS is indicating 30
  seconds to failure. What do you do? Suspend to disk.


Q:
  Maybe I'm missing something, but why don't the regular I/O paths work?

A:
  We do use the regular I/O paths. However we cannot restore the data
  to its original location as we load it. That would create an
  inconsistent kernel state which would certainly result in an oops.
  Instead, we load the image into unused memory and then atomically copy
  it back to it original location. This implies, of course, a maximum
  image size of half the amount of memory.

  There are two solutions to this:

  * require half of memory to be free during suspend. That way you can
    read "new" data onto free spots, then cli and copy

  * assume we had special "polling" ide driver that only uses memory
    between 0-640KB. That way, I'd have to make sure that 0-640KB is free
    during suspending, but otherwise it would work...

  suspend2 shares this fundamental limitation, but does not include user
  data and disk caches into "used memory" by saving them in
  advance. That means that the limitation goes away in practice.

FAQ: ACPI S4, suspend2, freezer와 power-off mode

170-212

Q: Linux는 ACPI S4를 지원합니까? A: 지원합니다. `echo platform > /sys/power/disk`가 그 mode를 선택합니다.

Q: `suspend2`는 무엇입니까? A: 2.4와 2.6 kernel용 별도 patch로 배포되던 Software Suspend 2 fork입니다. SMP, 4GB highmem, preemption을 지원했고 image compression·encryption 같은 변환과 swap 또는 개발 중이던 NFS backend를 확장할 수 있었습니다. 관련 질문은 LKML이 아니라 당시 suspend2 website의 mailing list로 보내야 했으며, 문서 작성 시점에는 mainline merge 작업이 진행 중이었습니다.

Q: Task freezing이란 무엇이며 왜 사용합니까? A: Hibernation과 일부 architecture의 system-wide suspend 동안 userspace process와 일부 kernel thread를 통제하는 mechanism입니다. 자세한 내용은 원문이 가리키는 `freezing-of-tasks.txt`를 참조합니다.

Q: `platform`과 `shutdown`의 차이는 무엇입니까? A: `shutdown`은 Linux에서 state를 저장한 뒤 BIOS에 power down을 요청합니다. `platform`은 state를 저장한 뒤 BIOS에 power down과 suspended LED 표시를 함께 요청합니다. 지원되는 곳에서는 `platform`이 올바른 선택이고, ACPI system을 제외하면 `shutdown`이 가장 신뢰할 만하다고 문서는 설명합니다.

/sys/power/disk mode
Mode동작문서의 판단
shutdownLinux state 저장 후 BIOS power down대체로 가장 신뢰성 높음
platformFirmware S4 절차와 suspended 표시 사용지원될 때 권장

Platform firmware가 hibernation 종료 절차에 관여하는 정도가 다릅니다.

Q:
  Does linux support ACPI S4?

A:
  Yes. That's what echo platform > /sys/power/disk does.

Q:
  What is 'suspend2'?

A:
  suspend2 is 'Software Suspend 2', a forked implementation of
  suspend-to-disk which is available as separate patches for 2.4 and 2.6
  kernels from swsusp.sourceforge.net. It includes support for SMP, 4GB
  highmem and preemption. It also has a extensible architecture that
  allows for arbitrary transformations on the image (compression,
  encryption) and arbitrary backends for writing the image (eg to swap
  or an NFS share[Work In Progress]). Questions regarding suspend2
  should be sent to the mailing list available through the suspend2
  website, and not to the Linux Kernel Mailing List. We are working
  toward merging suspend2 into the mainline kernel.

Q:
  What is the freezing of tasks and why are we using it?

A:
  The freezing of tasks is a mechanism by which user space processes and some
  kernel threads are controlled during hibernation or system-wide suspend (on
  some architectures).  See freezing-of-tasks.txt for details.

Q:
  What is the difference between "platform" and "shutdown"?

A:
  shutdown:
        save state in linux, then tell bios to powerdown

  platform:
        save state in linux, then tell bios to powerdown and blink
        "suspended led"

  "platform" is actually right thing to do where supported, but
  "shutdown" is most reliable (except on ACPI systems).

FAQ: Selective suspend와 FREEZE 상태

213-255

Q: Selective suspend를 반대하는 이유는 무엇입니까? A: Runtime power management에는 쓸 수 있지만 suspend-to-disk에는 도움이 되지 않습니다. Swap device와 그 parent만 남겨 놓고 나머지를 suspend한 뒤 snapshot을 만들면, 남겨 둔 device나 parent가 DMA를 수행해 snapshot data를 손상할 수 있습니다.

따라서 실제로는 swap device와 parent를 `FREEZE`하고 snapshot을 만든 뒤 `UNFREEZE`하여 image를 기록하고, 마지막에 다시 `SUSPEND`해야 합니다. 결국 별도 FREEZE 상태가 필요하고 system device 같은 세부 사항까지 고려하면 code가 더 복잡해집니다.

SUSPEND all but swap device and parents
FREEZE swap device and parents
Snapshot
UNFREEZE swap device and parents
Write image
SUSPEND swap device and parents

Q: `SUSPEND`와 `FREEZE`에 일반적으로 유용한 동작 차이가 없어 보입니다. A: FREEZE 요청에 SUSPEND를 수행하는 것은 정확하지만 불필요하게 느릴 수 있습니다. 단순한 driver에서는 허용할 수 있고 나중에 최적화할 수 있습니다. Disk처럼 FREEZE 때 spindle을 멈추면 안 되는 device에는 차이가 중요합니다.

FREEZE와 SUSPEND
상태목적Disk 예
FREEZESnapshot과 간섭하지 않도록 I/O 정지Spindown 없이 곧 image 기록에 재사용
SUSPENDPower-off를 위해 최종 저전력 상태 진입필요하면 spindown

Snapshot 전후에 device를 다시 사용해야 하는지에 따라 동작이 달라집니다.

Q:
  I do not understand why you have such strong objections to idea of
  selective suspend.

A:
  Do selective suspend during runtime power management, that's okay. But
  it's useless for suspend-to-disk. (And I do not see how you could use
  it for suspend-to-ram, I hope you do not want that).

  Lets see, so you suggest to

  * SUSPEND all but swap device and parents
  * Snapshot
  * Write image to disk
  * SUSPEND swap device and parents
  * Powerdown

  Oh no, that does not work, if swap device or its parents uses DMA,
  you've corrupted data. You'd have to do

  * SUSPEND all but swap device and parents
  * FREEZE swap device and parents
  * Snapshot
  * UNFREEZE swap device and parents
  * Write
  * SUSPEND swap device and parents

  Which means that you still need that FREEZE state, and you get more
  complicated code. (And I have not yet introduce details like system
  devices).

Q:
  There don't seem to be any generally useful behavioral
  distinctions between SUSPEND and FREEZE.

A:
  Doing SUSPEND when you are asked to do FREEZE is always correct,
  but it may be unnecessarily slow. If you want your driver to stay simple,
  slowness may not matter to you. It can always be fixed later.

  For devices like disk it does matter, you do not want to spindown for
  FREEZE.

FAQ: Resume 뒤 심한 paging

256-268

Q: Resume 뒤 paging이 심해 반응성이 나쁩니다. A: 아래 pipeline은 실행 중인 process의 memory map에서 file path를 모아 각 file을 `/dev/null`로 읽어 page cache를 다시 덥힙니다. `swapoff -a; swapon -a`도 도움이 될 수 있습니다.

cat /proc/[0-9]*/maps | grep / | sed 's:.* /:/:' | sort -u | while read file
do
  test -f "$file" && cat "$file" > /dev/null
done

swapoff -a; swapon -a
Q:
  After resuming, system is paging heavily, leading to very bad interactivity.

A:
  Try running::

    cat /proc/[0-9]*/maps | grep / | sed 's:.* /:/:' | sort -u | while read file
    do
      test -f "$file" && cat "$file" > /dev/null
    done

  after resume. swapoff -a; swapon -a may also be useful.

FAQ: Hibernation 중 device suspend와 resume 순서

269-316

Q: Swsusp 동안 device는 어떻게 처리됩니까? System suspend 중간에 다시 resume되는 것처럼 보입니다. A: Image를 disk에 기록하려면 snapshot을 만든 뒤 storage device를 깨워야 하므로 맞는 관찰입니다.

Suspend 절반에서는 user request 뒤 process를 멈추고, `suspend(PMSG_FREEZE)`로 device가 state snapshot을 방해하지 못하게 합니다. Interrupt를 끈 채 사용 중인 memory 전체의 snapshot을 만든 다음 `resume()`으로 device를 깨워 image를 swap에 씁니다. 그 후 `suspend(PMSG_SUSPEND)`로 device를 최종 suspend하고 전원을 끕니다.

Resume 절반도 비슷합니다. Boot 중 process를 멈추고 image를 disk에서 읽은 뒤 `suspend(PMSG_FREEZE)`로 device를 고정합니다. Image restoration 단계에서 memory를 저장된 내용으로 덮어쓰고 `resume()`으로 device를 깨운 뒤 모든 user process를 thaw합니다. Initrd에서 resume한다면 실행 중인 process가 있을 수도 있으므로 이를 무시할 수 없습니다.

Suspend part
stop user processessuspend(PMSG_FREEZE)snapshot used memory with interrupts disabledresume deviceswrite image to swapsuspend(PMSG_SUSPEND)power off

Snapshot 작성과 image 기록 사이에 device를 한 번 다시 깨웁니다.

Resume part
stop user processesread image from disksuspend(PMSG_FREEZE)restore memory imageresume devicesthaw user processes

Image를 읽은 새 kernel이 device를 고정한 뒤 저장된 memory로 전환합니다.

Q:
  What happens to devices during swsusp? They seem to be resumed
  during system suspend?

A:
  That's correct. We need to resume them if we want to write image to
  disk. Whole sequence goes like

      **Suspend part**

      running system, user asks for suspend-to-disk

      user processes are stopped

      suspend(PMSG_FREEZE): devices are frozen so that they don't interfere
      with state snapshot

      state snapshot: copy of whole used memory is taken with interrupts
      disabled

      resume(): devices are woken up so that we can write image to swap

      write image to swap

      suspend(PMSG_SUSPEND): suspend devices so that we can power off

      turn the power off

      **Resume part**

      (is actually pretty similar)

      running system, user asks for suspend-to-disk

      user processes are stopped (in common case there are none,
      but with resume-from-initrd, no one knows)

      read image from disk

      suspend(PMSG_FREEZE): devices are frozen so that they don't interfere
      with image restoration

      image restoration: rewrite memory with image

      resume(): devices are woken up so that system can continue

      thaw all user processes

FAQ: Suspend image encryption의 목적

317-352

Q: `Encrypt suspend image`는 무엇을 위한 기능입니까? A: Dm-crypt로 암호화한 swap을 대신하지 않으며 system이 suspended 상태일 때의 공격을 막지 않습니다. Resume 뒤 swap에 남은 민감한 data가 유출되는 것을 막는 기능입니다.

Application이 memory의 민감한 data를 swap out되지 않게 막아도 hibernation은 resume을 위해 그 memory를 swap에 기록해야 합니다. Image encryption이 없으면 plaintext가 disk에 남고, resume 뒤 해당 swap device에 직접 접근할 수 있는 application이 이를 읽을 수 있습니다. Swap을 다시 쓰지 않으면 data가 오래 남아 나중의 침해에서 회수될 수도 있습니다.

Suspend할 때 temporary key를 만들고 disk에 쓰는 data를 암호화합니다. Resume에서 data를 memory로 읽은 뒤 key를 파기하면 disk의 image는 더 이상 해독할 수 없습니다. Suspend가 oops로 끝나거나 resume이 실패·중단되어 key가 남는 경우를 없애려면 정상 boot 초기에 해당 swap partition에 `mkswap`을 실행해야 합니다.

정리하면 system이 꺼져 있거나 suspended일 때의 보호에는 encrypted swap을 사용하고, resume 뒤 남은 image에서 민감한 data가 유출되는 위험까지 줄이려면 suspend image encryption을 추가합니다.

두 암호화 계층의 역할
기능보호 범위
Encrypted swap전원이 꺼졌거나 suspended인 동안 저장 data 보호
Suspend image encryptionResume 뒤 swap에 남은 hibernation image의 사후 유출 방지

보호 시점이 다르므로 서로 대체 관계가 아닙니다.

Q:
  What is this 'Encrypt suspend image' for?

A:
  First of all: it is not a replacement for dm-crypt encrypted swap.
  It cannot protect your computer while it is suspended. Instead it does
  protect from leaking sensitive data after resume from suspend.

  Think of the following: you suspend while an application is running
  that keeps sensitive data in memory. The application itself prevents
  the data from being swapped out. Suspend, however, must write these
  data to swap to be able to resume later on. Without suspend encryption
  your sensitive data are then stored in plaintext on disk.  This means
  that after resume your sensitive data are accessible to all
  applications having direct access to the swap device which was used
  for suspend. If you don't need swap after resume these data can remain
  on disk virtually forever. Thus it can happen that your system gets
  broken in weeks later and sensitive data which you thought were
  encrypted and protected are retrieved and stolen from the swap device.
  To prevent this situation you should use 'Encrypt suspend image'.

  During suspend a temporary key is created and this key is used to
  encrypt the data written to disk. When, during resume, the data was
  read back into memory the temporary key is destroyed which simply
  means that all data written to disk during suspend are then
  inaccessible so they can't be stolen later on.  The only thing that
  you must then take care of is that you call 'mkswap' for the swap
  partition used for suspend as early as possible during regular
  boot. This asserts that any temporary key from an oopsed suspend or
  from a failed or aborted resume is erased from the swap device.

  As a rule of thumb use encrypted swap to protect your data while your
  system is shut down or suspended. Additionally use the encrypted
  suspend image to prevent sensitive data from being stolen after
  resume.

FAQ: Swap file, RAM 크기와 swap 사용량

353-383

Q: Swap file에도 suspend할 수 있습니까? A: 일반적으로 가능합니다. 다만 `resume=`과 `resume_offset=` kernel command-line parameter가 필요하므로, 이 문서가 쓰인 시점의 설명에서는 initrd 또는 initramfs image가 swap file resume을 직접 시작할 수 없다고 합니다. 자세한 내용은 `swsusp-and-swap-files.txt`를 참조합니다.

Q: Swsusp가 지원하는 system RAM의 최대 크기가 있습니까? A: Highmem에서도 동작해야 합니다.

Q: 여러 swap partition을 하나의 논리 공간처럼 합쳐 사용할 수 있습니까? A: Hibernation image에는 swap partition 하나만 사용합니다.

Q: Application이 system RAM 절반보다 많은 memory와 swap을 쓰면 suspend-to-disk가 쓸모없습니까? A: Application이 memory를 `mlock()`하지 않았다면 동작해야 합니다. 충분히 큰 swap partition을 준비해야 합니다.

Image 저장 공간 제약
질문
Highmem지원 대상
여러 swap partition 집계지원하지 않음
RAM 절반 이상 사용mlock되지 않고 swap이 충분하면 가능

Memory 사용량 자체보다 pin 여부와 하나의 충분한 swap 대상이 중요합니다.

Q:
  Can I suspend to a swap file?

A:
  Generally, yes, you can.  However, it requires you to use the "resume=" and
  "resume_offset=" kernel command line parameters, so the resume from a swap
  file cannot be initiated from an initrd or initramfs image.  See
  swsusp-and-swap-files.txt for details.

Q:
  Is there a maximum system RAM size that is supported by swsusp?

A:
  It should work okay with highmem.

Q:
  Does swsusp (to disk) use only one swap partition or can it use
  multiple swap partitions (aggregate them into one logical space)?

A:
  Only one swap partition, sorry.

Q:
  If my application(s) causes lots of memory & swap space to be used
  (over half of the total system RAM), is it correct that it is likely
  to be useless to try to suspend to disk while that app is running?

A:
  No, it should work okay, as long as your app does not mlock()
  it. Just prepare big enough swap partition.

FAQ: 문제 보고와 modular disk driver

384-405

Q: Suspend-to-disk 문제를 debug할 때 어떤 정보가 유용합니까? A: 화면의 마지막 message가 중요합니다. 원인은 대개 kernel driver이므로 module을 가능한 적게 load하고, X를 종료한 console에서 suspend하는 것이 좋습니다. `init=/bin/bash`로 boot한 뒤 swap을 켜고 suspend sequence를 직접 실행하면 원인을 줄이는 데 도움이 됩니다. 최신 vanilla kernel에서도 재현되는지 확인해야 합니다.

Q: Distribution은 SATA 같은 modular disk driver와 swsusp를 어떻게 함께 제공할 수 있습니까? A: Initrd에서 driver를 load한 다음 `/sys/power/resume`에 device를 씁니다. 그 전에 어떤 filesystem도 mount해서는 안 되며 read-only mount도 data 손상을 일으킬 수 있습니다.

최소 재현 환경
latest vanilla kernelinit=/bin/bashminimal modulesconsole without Xswaponrun suspend sequence manuallycapture last messages

Driver와 userspace 변수를 줄여 마지막 정상 지점을 확인합니다.

Q:
  What information is useful for debugging suspend-to-disk problems?

A:
  Well, last messages on the screen are always useful. If something
  is broken, it is usually some kernel driver, therefore trying with as
  little as possible modules loaded helps a lot. I also prefer people to
  suspend from console, preferably without X running. Booting with
  init=/bin/bash, then swapon and starting suspend sequence manually
  usually does the trick. Then it is good idea to try with latest
  vanilla kernel.

Q:
  How can distributions ship a swsusp-supporting kernel with modular
  disk drivers (especially SATA)?

A:
  Well, it can be done, load the drivers, then do echo into
  /sys/power/resume file from initrd. Be sure not to mount
  anything, not even read-only mount, or you are going to lose your
  data.

FAQ: Suspend message와 image size 재시도 script

406-440

Q: Suspend 과정을 더 자세히 보려면 어떻게 합니까? A: Suspend 중 kernel이 전환한 virtual terminal에서 non-error message를 보려면 console loglevel을 최소 4(`KERN_WARNING`)로 설정해야 합니다. 예제 script는 기존 loglevel을 저장하고 5보다 낮을 때 5로 올립니다.

Script는 `/sys/power/image_size`를 읽은 뒤 `echo -n disk > /sys/power/state`를 실행합니다. 실패했고 image size가 0이 아니면 size를 0으로 바꿔 최소 image size로 한 번 더 시도합니다. 마지막에는 기존 loglevel을 복원하고 suspend 명령의 return code로 종료합니다.

read LOGLEVEL DUMMY < /proc/sys/kernel/printk
if [ $LOGLEVEL -lt 5 ]; then
  echo 5 > /proc/sys/kernel/printk
fi
IMG_SZ=0
read IMG_SZ < /sys/power/image_size
echo -n disk > /sys/power/state
RET=$?
if [ $RET -ne 0 -a $IMG_SZ -ne 0 ]; then
  echo 0 > /sys/power/image_size
  echo -n disk > /sys/power/state
  RET=$?
fi
echo $LOGLEVEL > /proc/sys/kernel/printk
exit $RET
Verbose suspend 재시도
save console loglevelraise to 5 if neededread image_sizeattempt hibernationon failure and nonzero size: set image_size=0retryrestore loglevel

진단 message를 보존하면서 image 크기 제약 때문에 실패했는지 한 번 확인합니다.

Q:
  How do I make suspend more verbose?

A:
  If you want to see any non-error kernel messages on the virtual
  terminal the kernel switches to during suspend, you have to set the
  kernel console loglevel to at least 4 (KERN_WARNING), for example by
  doing::

        # save the old loglevel
        read LOGLEVEL DUMMY < /proc/sys/kernel/printk
        # set the loglevel so we see the progress bar.
        # if the level is higher than needed, we leave it alone.
        if [ $LOGLEVEL -lt 5 ]; then
                echo 5 > /proc/sys/kernel/printk
                fi

        IMG_SZ=0
        read IMG_SZ < /sys/power/image_size
        echo -n disk > /sys/power/state
        RET=$?
        #
        # the logic here is:
        # if image_size > 0 (without kernel support, IMG_SZ will be zero),
        # then try again with image_size set to zero.
        if [ $RET -ne 0 -a $IMG_SZ -ne 0 ]; then # try again with minimal image size
                echo 0 > /sys/power/image_size
                echo -n disk > /sys/power/state
                RET=$?
        fi

        # restore previous loglevel
        echo $LOGLEVEL > /proc/sys/kernel/printk
        exit $RET

FAQ: USB와 removable filesystem의 data 보존

441-471

Q: USB device의 mounted filesystem은 `sync` option이 없으면 suspend-to-disk에서 data를 잃습니까? A: Device 연결이 끊기면 그렇습니다. `-o sync`를 사용해도 program buffer에 아직 쓰지 않은 data가 있거나 device가 기록을 끝내기 전에 끊기면 data를 잃을 수 있습니다.

Software suspend는 보통 USB controller의 전원을 끄므로 모든 USB device를 분리하는 것과 같습니다. System이 suspend-to-RAM 또는 standby 같은 실제 sleep mode에서 USB controller의 low-power mode를 지원하면 연결을 유지할 수 있습니다. 이때 `/sys/power/state`에 `disk` 대신 `standby` 또는 `mem`을 씁니다. 문서 작성 당시에는 software suspend의 `platform` mode로 USB 연결을 유지하는 hardware가 확인되지 않았습니다.

Mounted filesystem이 있는 disk를 unplug하는 것은 system이 sleep 중이어도 위험합니다. 가장 안전한 방법은 USB, FireWire, CompactFlash, MMC, external SATA, IDE hotplug bay 등 removable media의 filesystem을 suspend 전에 모두 unmount하고 resume 뒤 remount하는 것입니다.

이 문제의 우회책은 `Documentation/driver-api/usb/persist.rst`에서 설명합니다.

Removable media suspend 준비
조치안전성
-o sync만 사용불충분
Suspend-to-RAM/standby로 연결 유지Platform 지원에 의존
Suspend 전 unmount, resume 후 remount권장

`sync`만으로는 userspace buffer와 device 내부 write 완료를 보장하지 못합니다.

Q:
  Is this true that if I have a mounted filesystem on a USB device and
  I suspend to disk, I can lose data unless the filesystem has been mounted
  with "sync"?

A:
  That's right ... if you disconnect that device, you may lose data.
  In fact, even with "-o sync" you can lose data if your programs have
  information in buffers they haven't written out to a disk you disconnect,
  or if you disconnect before the device finished saving data you wrote.

  Software suspend normally powers down USB controllers, which is equivalent
  to disconnecting all USB devices attached to your system.

  Your system might well support low-power modes for its USB controllers
  while the system is asleep, maintaining the connection, using true sleep
  modes like "suspend-to-RAM" or "standby".  (Don't write "disk" to the
  /sys/power/state file; write "standby" or "mem".)  We've not seen any
  hardware that can use these modes through software suspend, although in
  theory some systems might support "platform" modes that won't break the
  USB connections.

  Remember that it's always a bad idea to unplug a disk drive containing a
  mounted filesystem.  That's true even when your system is asleep!  The
  safest thing is to unmount all filesystems on removable media (such USB,
  Firewire, CompactFlash, MMC, external SATA, or even IDE hotplug bays)
  before suspending; then remount them after resuming.

  There is a work-around for this problem.  For more information, see
  Documentation/driver-api/usb/persist.rst.

FAQ: LVM swap volume에서 resume

472-487

Q: LVM 아래의 swap partition에 suspend-to-disk할 수 있습니까? A: Suspend 자체는 가능하지만 kernel만으로는 resume할 수 없습니다. Initramfs가 resume 상황을 감지하고 swap volume을 포함한 logical volume을 활성화해야 합니다. 이때 filesystem은 전혀 건드리지 않아야 합니다.

그 다음 swap volume의 major와 minor device number를 사용해 `echo -n "$major:$minor" > /sys/power/resume`을 호출합니다. `uswsusp`도 LVM을 지원하며 원문은 `http://suspend.sourceforge.net/`를 참조합니다.

echo -n "$major:$minor" > /sys/power/resume
LVM resume
initramfs detects resumeactivate logical volumedo not touch filesystemsobtain swap LV major:minorwrite /sys/power/resumerestore image

Kernel이 image를 찾기 전에 initramfs가 block-device mapping만 준비합니다.

Q:
  Can I suspend-to-disk using a swap partition under LVM?

A:
  Yes and No.  You can suspend successfully, but the kernel will not be able
  to resume on its own.  You need an initramfs that can recognize the resume
  situation, activate the logical volume containing the swap volume (but not
  touch any filesystems!), and eventually call::

    echo -n "$major:$minor" > /sys/power/resume

  where $major and $minor are the respective major and minor device numbers of
  the swap volume.

  uswsusp works with LVM, too.  See http://suspend.sourceforge.net/

FAQ: Kernel 변경 뒤 느려진 hibernation

488-503

Q: 2.6.15에서 2.6.16으로 올린 뒤 suspend-to-disk와 resume이 느려진 이유와 개선 방법은 무엇입니까? A: 2.6.16은 resume 뒤 반응성을 높이기 위해 더 많은 data를 저장하므로 suspend image가 커졌기 때문입니다.

`/sys/power/image_size`가 image 크기를 제어합니다. Root로 `echo 0 > /sys/power/image_size`를 실행하면 2.6.15과 비슷한 동작을 되살릴 수 있습니다. 그래도 느리다면 원문은 LZF compression을 지원해 더 빠른 당시의 userland suspend 구현인 `suspend.sf.net`을 살펴보라고 안내합니다.

Image 크기 절충
설정효과
기본/큰 imageHibernation은 느려질 수 있으나 resume 뒤 반응성 향상
image_size=0더 작은 image, 과거 동작에 가까움

더 큰 image는 저장·복구 시간이 늘지만 resume 직후의 working set을 더 많이 보존합니다.

Q:
  I upgraded the kernel from 2.6.15 to 2.6.16. Both kernels were
  compiled with the similar configuration files. Anyway I found that
  suspend to disk (and resume) is much slower on 2.6.16 compared to
  2.6.15. Any idea for why that might happen or how can I speed it up?

A:
  This is because the size of the suspend image is now greater than
  for 2.6.15 (by saving more data we can get more responsive system
  after resume).

  There's the /sys/power/image_size knob that controls the size of the
  image.  If you set it to 0 (eg. by echo 0 > /sys/power/image_size as
  root), the 2.6.15 behavior should be restored.  If it is still too
  slow, take a look at suspend.sf.net -- userland suspend is faster and
  supports LZF compression to speed it up further.