← Documents Documentation/admin-guide/laptops/laptop-mode.rst GitHub 원문 ↗

Linux 6.18.37 · Administration / Laptops

How to conserve battery power using laptop-mode

dirty-page writeback과 filesystem commit을 집중시켜 hard disk spin-up 시간을 줄이는 laptop mode 설정·script·ACPI 통합을 설명합니다.

Source pathDocumentation/admin-guide/laptops/laptop-mode.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

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

1. 요약·해설

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

원리와 주의 사항

laptop-mode.rst:1-104

설치 방법, 데이터 손실·drive 수명 위험과 dirty-page writeback 집중 원리를 설명합니다.

설정과 운용 팁

laptop-mode.rst:105-217

configuration option, filesystem·CPUFreq 조정과 절전 팁을 정리합니다.

Configuration file

laptop-mode.rst:218-304

배포판별 설정 파일과 모든 tunable 예제를 원문 그대로 제공합니다.

Control script

laptop-mode.rst:305-685

Linux 2.4·2.6에서 start/stop 시 sysctl, mount, disk와 CPU 설정을 바꾸는 script입니다.

ACPI와 monitoring

laptop-mode.rst:686-770

전원·battery event handler, low-battery 보호와 disk spin monitoring tool을 안내합니다.

2. 영어 원문 전체

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

원문 전체 펼치기
1 ===============================================
2 How to conserve battery power using laptop-mode
3 ===============================================
4
5 Document Author: Bart Samwel ([email protected])
6
7 Date created: January 2, 2004
8
9 Last modified: December 06, 2004
10
11 Introduction
12 ------------
13
14 Laptop mode is used to minimize the time that the hard disk needs to be spun up,
15 to conserve battery power on laptops. It has been reported to cause significant
16 power savings.
17
18 .. Contents
19
20 * Introduction
21 * Installation
22 * Caveats
23 * The Details
24 * Tips & Tricks
25 * Control script
26 * ACPI integration
27 * Monitoring tool
28
29
30 Installation
31 ------------
32
33 To use laptop mode, you don't need to set any kernel configuration options
34 or anything. Simply install all the files included in this document, and
35 laptop mode will automatically be started when you're on battery. For
36 your convenience, a tarball containing an installer can be downloaded at:
37
38 http://www.samwel.tk/laptop_mode/laptop_mode/
39
40 To configure laptop mode, you need to edit the configuration file, which is
41 located in /etc/default/laptop-mode on Debian-based systems, or in
42 /etc/sysconfig/laptop-mode on other systems.
43
44 Unfortunately, automatic enabling of laptop mode does not work for
45 laptops that don't have ACPI. On those laptops, you need to start laptop
46 mode manually. To start laptop mode, run "laptop_mode start", and to
47 stop it, run "laptop_mode stop". (Note: The laptop mode tools package now
48 has experimental support for APM, you might want to try that first.)
49
50
51 Caveats
52 -------
53
54 * The downside of laptop mode is that you have a chance of losing up to 10
55 minutes of work. If you cannot afford this, don't use it! The supplied ACPI
56 scripts automatically turn off laptop mode when the battery almost runs out,
57 so that you won't lose any data at the end of your battery life.
58
59 * Most desktop hard drives have a very limited lifetime measured in spindown
60 cycles, typically about 50.000 times (it's usually listed on the spec sheet).
61 Check your drive's rating, and don't wear down your drive's lifetime if you
62 don't need to.
63
64 * If you mount some of your ext3 filesystems with the -n option, then
65 the control script will not be able to remount them correctly. You must set
66 DO_REMOUNTS=0 in the control script, otherwise it will remount them with the
67 wrong options -- or it will fail because it cannot write to /etc/mtab.
68
69 * If you have your filesystems listed as type "auto" in fstab, like I did, then
70 the control script will not recognize them as filesystems that need remounting.
71 You must list the filesystems with their true type instead.
72
73 * It has been reported that some versions of the mutt mail client use file access
74 times to determine whether a folder contains new mail. If you use mutt and
75 experience this, you must disable the noatime remounting by setting the option
76 DO_REMOUNT_NOATIME to 0 in the configuration file.
77
78
79 The Details
80 -----------
81
82 Laptop mode is controlled by the knob /proc/sys/vm/laptop_mode. This knob is
83 present for all kernels that have the laptop mode patch, regardless of any
84 configuration options. When the knob is set, any physical disk I/O (that might
85 have caused the hard disk to spin up) causes Linux to flush all dirty blocks. The
86 result of this is that after a disk has spun down, it will not be spun up
87 anymore to write dirty blocks, because those blocks had already been written
88 immediately after the most recent read operation. The value of the laptop_mode
89 knob determines the time between the occurrence of disk I/O and when the flush
90 is triggered. A sensible value for the knob is 5 seconds. Setting the knob to
91 0 disables laptop mode.
92
93 To increase the effectiveness of the laptop_mode strategy, the laptop_mode
94 control script increases dirty_expire_centisecs and dirty_writeback_centisecs in
95 /proc/sys/vm to about 10 minutes (by default), which means that pages that are
96 dirtied are not forced to be written to disk as often. The control script also
97 changes the dirty background ratio, so that background writeback of dirty pages
98 is not done anymore. Combined with a higher commit value (also 10 minutes) for
99 ext3 filesystem (also done automatically by the control script),
100 this results in concentration of disk activity in a small time interval which
101 occurs only once every 10 minutes, or whenever the disk is forced to spin up by
102 a cache miss. The disk can then be spun down in the periods of inactivity.
103
104
105 Configuration
106 -------------
107
108 The laptop mode configuration file is located in /etc/default/laptop-mode on
109 Debian-based systems, or in /etc/sysconfig/laptop-mode on other systems. It
110 contains the following options:
111
112 MAX_AGE:
113
114 Maximum time, in seconds, of hard drive spindown time that you are
115 comfortable with. Worst case, it's possible that you could lose this
116 amount of work if your battery fails while you're in laptop mode.
117
118 MINIMUM_BATTERY_MINUTES:
119
120 Automatically disable laptop mode if the remaining number of minutes of
121 battery power is less than this value. Default is 10 minutes.
122
123 AC_HD/BATT_HD:
124
125 The idle timeout that should be set on your hard drive when laptop mode
126 is active (BATT_HD) and when it is not active (AC_HD). The defaults are
127 20 seconds (value 4) for BATT_HD and 2 hours (value 244) for AC_HD. The
128 possible values are those listed in the manual page for "hdparm" for the
129 "-S" option.
130
131 HD:
132
133 The devices for which the spindown timeout should be adjusted by laptop mode.
134 Default is /dev/hda. If you specify multiple devices, separate them by a space.
135
136 READAHEAD:
137
138 Disk readahead, in 512-byte sectors, while laptop mode is active. A large
139 readahead can prevent disk accesses for things like executable pages (which are
140 loaded on demand while the application executes) and sequentially accessed data
141 (MP3s).
142
143 DO_REMOUNTS:
144
145 The control script automatically remounts any mounted journaled filesystems
146 with appropriate commit interval options. When this option is set to 0, this
147 feature is disabled.
148
149 DO_REMOUNT_NOATIME:
150
151 When remounting, should the filesystems be remounted with the noatime option?
152 Normally, this is set to "1" (enabled), but there may be programs that require
153 access time recording.
154
155 DIRTY_RATIO:
156
157 The percentage of memory that is allowed to contain "dirty" or unsaved data
158 before a writeback is forced, while laptop mode is active. Corresponds to
159 the /proc/sys/vm/dirty_ratio sysctl.
160
161 DIRTY_BACKGROUND_RATIO:
162
163 The percentage of memory that is allowed to contain "dirty" or unsaved data
164 after a forced writeback is done due to an exceeding of DIRTY_RATIO. Set
165 this nice and low. This corresponds to the /proc/sys/vm/dirty_background_ratio
166 sysctl.
167
168 Note that the behaviour of dirty_background_ratio is quite different
169 when laptop mode is active and when it isn't. When laptop mode is inactive,
170 dirty_background_ratio is the threshold percentage at which background writeouts
171 start taking place. When laptop mode is active, however, background writeouts
172 are disabled, and the dirty_background_ratio only determines how much writeback
173 is done when dirty_ratio is reached.
174
175 DO_CPU:
176
177 Enable CPU frequency scaling when in laptop mode. (Requires CPUFreq to be setup.
178 See Documentation/admin-guide/pm/cpufreq.rst for more info. Disabled by default.)
179
180 CPU_MAXFREQ:
181
182 When on battery, what is the maximum CPU speed that the system should use? Legal
183 values are "slowest" for the slowest speed that your CPU is able to operate at,
184 or a value listed in /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies.
185
186
187 Tips & Tricks
188 -------------
189
190 * Bartek Kania reports getting up to 50 minutes of extra battery life (on top
191 of his regular 3 to 3.5 hours) using a spindown time of 5 seconds (BATT_HD=1).
192
193 * You can spin down the disk while playing MP3, by setting disk readahead
194 to 8MB (READAHEAD=16384). Effectively, the disk will read a complete MP3 at
195 once, and will then spin down while the MP3 is playing. (Thanks to Bartek
196 Kania.)
197
198 * Drew Scott Daniels observed: "I don't know why, but when I decrease the number
199 of colours that my display uses it consumes less battery power. I've seen
200 this on powerbooks too. I hope that this is a piece of information that
201 might be useful to the Laptop Mode patch or its users."
202
203 * In syslog.conf, you can prefix entries with a dash `-` to omit syncing the
204 file after every logging. When you're using laptop-mode and your disk doesn't
205 spin down, this is a likely culprit.
206
207 * Richard Atterer observed that laptop mode does not work well with noflushd
208 (http://noflushd.sourceforge.net/), it seems that noflushd prevents laptop-mode
209 from doing its thing.
210
211 * If you're worried about your data, you might want to consider using a USB
212 memory stick or something like that as a "working area". (Be aware though
213 that flash memory can only handle a limited number of writes, and overuse
214 may wear out your memory stick pretty quickly. Do _not_ use journalling
215 filesystems on flash memory sticks.)
216
217
218 Configuration file for control and ACPI battery scripts
219 -------------------------------------------------------
220
221 This allows the tunables to be changed for the scripts via an external
222 configuration file
223
224 It should be installed as /etc/default/laptop-mode on Debian, and as
225 /etc/sysconfig/laptop-mode on Red Hat, SUSE, Mandrake, and other work-alikes.
226
227 Config file::
228
229 # Maximum time, in seconds, of hard drive spindown time that you are
230 # comfortable with. Worst case, it's possible that you could lose this
231 # amount of work if your battery fails you while in laptop mode.
232 #MAX_AGE=600
233
234 # Automatically disable laptop mode when the number of minutes of battery
235 # that you have left goes below this threshold.
236 MINIMUM_BATTERY_MINUTES=10
237
238 # Read-ahead, in 512-byte sectors. You can spin down the disk while playing MP3/OGG
239 # by setting the disk readahead to 8MB (READAHEAD=16384). Effectively, the disk
240 # will read a complete MP3 at once, and will then spin down while the MP3/OGG is
241 # playing.
242 #READAHEAD=4096
243
244 # Shall we remount journaled fs. with appropriate commit interval? (1=yes)
245 #DO_REMOUNTS=1
246
247 # And shall we add the "noatime" option to that as well? (1=yes)
248 #DO_REMOUNT_NOATIME=1
249
250 # Dirty synchronous ratio. At this percentage of dirty pages the process
251 # which
252 # calls write() does its own writeback
253 #DIRTY_RATIO=40
254
255 #
256 # Allowed dirty background ratio, in percent. Once DIRTY_RATIO has been
257 # exceeded, the kernel will wake flusher threads which will then reduce the
258 # amount of dirty memory to dirty_background_ratio. Set this nice and low,
259 # so once some writeout has commenced, we do a lot of it.
260 #
261 #DIRTY_BACKGROUND_RATIO=5
262
263 # kernel default dirty buffer age
264 #DEF_AGE=30
265 #DEF_UPDATE=5
266 #DEF_DIRTY_BACKGROUND_RATIO=10
267 #DEF_DIRTY_RATIO=40
268 #DEF_XFS_AGE_BUFFER=15
269 #DEF_XFS_SYNC_INTERVAL=30
270 #DEF_XFS_BUFD_INTERVAL=1
271
272 # This must be adjusted manually to the value of HZ in the running kernel
273 # on 2.4, until the XFS people change their 2.4 external interfaces to work in
274 # centisecs. This can be automated, but it's a work in progress that still
275 # needs# some fixes. On 2.6 kernels, XFS uses USER_HZ instead of HZ for
276 # external interfaces, and that is currently always set to 100. So you don't
277 # need to change this on 2.6.
278 #XFS_HZ=100
279
280 # Should the maximum CPU frequency be adjusted down while on battery?
281 # Requires CPUFreq to be setup.
282 # See Documentation/admin-guide/pm/cpufreq.rst for more info
283 #DO_CPU=0
284
285 # When on battery what is the maximum CPU speed that the system should
286 # use? Legal values are "slowest" for the slowest speed that your
287 # CPU is able to operate at, or a value listed in:
288 # /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies
289 # Only applicable if DO_CPU=1.
290 #CPU_MAXFREQ=slowest
291
292 # Idle timeout for your hard drive (man hdparm for valid values, -S option)
293 # Default is 2 hours on AC (AC_HD=244) and 20 seconds for battery (BATT_HD=4).
294 #AC_HD=244
295 #BATT_HD=4
296
297 # The drives for which to adjust the idle timeout. Separate them by a space,
298 # e.g. HD="/dev/hda /dev/hdb".
299 #HD="/dev/hda"
300
301 # Set the spindown timeout on a hard drive?
302 #DO_HD=1
303
304
305 Control script
306 --------------
307
308 Please note that this control script works for the Linux 2.4 and 2.6 series (thanks
309 to Kiko Piris).
310
311 Control script::
312
313 #!/bin/bash
314
315 # start or stop laptop_mode, best run by a power management daemon when
316 # ac gets connected/disconnected from a laptop
317 #
318 # install as /sbin/laptop_mode
319 #
320 # Contributors to this script: Kiko Piris
321 # Bart Samwel
322 # Micha Feigin
323 # Andrew Morton
324 # Herve Eychenne
325 # Dax Kelson
326 #
327 # Original Linux 2.4 version by: Jens Axboe
328
329 #############################################################################
330
331 # Source config
332 if [ -f /etc/default/laptop-mode ] ; then
333 # Debian
334 . /etc/default/laptop-mode
335 elif [ -f /etc/sysconfig/laptop-mode ] ; then
336 # Others
337 . /etc/sysconfig/laptop-mode
338 fi
339
340 # Don't raise an error if the config file is incomplete
341 # set defaults instead:
342
343 # Maximum time, in seconds, of hard drive spindown time that you are
344 # comfortable with. Worst case, it's possible that you could lose this
345 # amount of work if your battery fails you while in laptop mode.
346 MAX_AGE=${MAX_AGE:-'600'}
347
348 # Read-ahead, in kilobytes
349 READAHEAD=${READAHEAD:-'4096'}
350
351 # Shall we remount journaled fs. with appropriate commit interval? (1=yes)
352 DO_REMOUNTS=${DO_REMOUNTS:-'1'}
353
354 # And shall we add the "noatime" option to that as well? (1=yes)
355 DO_REMOUNT_NOATIME=${DO_REMOUNT_NOATIME:-'1'}
356
357 # Shall we adjust the idle timeout on a hard drive?
358 DO_HD=${DO_HD:-'1'}
359
360 # Adjust idle timeout on which hard drive?
361 HD="${HD:-'/dev/hda'}"
362
363 # spindown time for HD (hdparm -S values)
364 AC_HD=${AC_HD:-'244'}
365 BATT_HD=${BATT_HD:-'4'}
366
367 # Dirty synchronous ratio. At this percentage of dirty pages the process which
368 # calls write() does its own writeback
369 DIRTY_RATIO=${DIRTY_RATIO:-'40'}
370
371 # cpu frequency scaling
372 # See Documentation/admin-guide/pm/cpufreq.rst for more info
373 DO_CPU=${CPU_MANAGE:-'0'}
374 CPU_MAXFREQ=${CPU_MAXFREQ:-'slowest'}
375
376 #
377 # Allowed dirty background ratio, in percent. Once DIRTY_RATIO has been
378 # exceeded, the kernel will wake flusher threads which will then reduce the
379 # amount of dirty memory to dirty_background_ratio. Set this nice and low,
380 # so once some writeout has commenced, we do a lot of it.
381 #
382 DIRTY_BACKGROUND_RATIO=${DIRTY_BACKGROUND_RATIO:-'5'}
383
384 # kernel default dirty buffer age
385 DEF_AGE=${DEF_AGE:-'30'}
386 DEF_UPDATE=${DEF_UPDATE:-'5'}
387 DEF_DIRTY_BACKGROUND_RATIO=${DEF_DIRTY_BACKGROUND_RATIO:-'10'}
388 DEF_DIRTY_RATIO=${DEF_DIRTY_RATIO:-'40'}
389 DEF_XFS_AGE_BUFFER=${DEF_XFS_AGE_BUFFER:-'15'}
390 DEF_XFS_SYNC_INTERVAL=${DEF_XFS_SYNC_INTERVAL:-'30'}
391 DEF_XFS_BUFD_INTERVAL=${DEF_XFS_BUFD_INTERVAL:-'1'}
392
393 # This must be adjusted manually to the value of HZ in the running kernel
394 # on 2.4, until the XFS people change their 2.4 external interfaces to work in
395 # centisecs. This can be automated, but it's a work in progress that still needs
396 # some fixes. On 2.6 kernels, XFS uses USER_HZ instead of HZ for external
397 # interfaces, and that is currently always set to 100. So you don't need to
398 # change this on 2.6.
399 XFS_HZ=${XFS_HZ:-'100'}
400
401 #############################################################################
402
403 KLEVEL="$(uname -r |
404 {
405 IFS='.' read a b c
406 echo $a.$b
407 }
408 )"
409 case "$KLEVEL" in
410 "2.4"|"2.6")
411 ;;
412 *)
413 echo "Unhandled kernel version: $KLEVEL ('uname -r' = '$(uname -r)')" >&2
414 exit 1
415 ;;
416 esac
417
418 if [ ! -e /proc/sys/vm/laptop_mode ] ; then
419 echo "Kernel is not patched with laptop_mode patch." >&2
420 exit 1
421 fi
422
423 if [ ! -w /proc/sys/vm/laptop_mode ] ; then
424 echo "You do not have enough privileges to enable laptop_mode." >&2
425 exit 1
426 fi
427
428 # Remove an option (the first parameter) of the form option=<number> from
429 # a mount options string (the rest of the parameters).
430 parse_mount_opts () {
431 OPT="$1"
432 shift
433 echo ",$*," | sed \
434 -e 's/,'"$OPT"'=[0-9]*,/,/g' \
435 -e 's/,,*/,/g' \
436 -e 's/^,//' \
437 -e 's/,$//'
438 }
439
440 # Remove an option (the first parameter) without any arguments from
441 # a mount option string (the rest of the parameters).
442 parse_nonumber_mount_opts () {
443 OPT="$1"
444 shift
445 echo ",$*," | sed \
446 -e 's/,'"$OPT"',/,/g' \
447 -e 's/,,*/,/g' \
448 -e 's/^,//' \
449 -e 's/,$//'
450 }
451
452 # Find out the state of a yes/no option (e.g. "atime"/"noatime") in
453 # fstab for a given filesystem, and use this state to replace the
454 # value of the option in another mount options string. The device
455 # is the first argument, the option name the second, and the default
456 # value the third. The remainder is the mount options string.
457 #
458 # Example:
459 # parse_yesno_opts_wfstab /dev/hda1 atime atime defaults,noatime
460 #
461 # If fstab contains, say, "rw" for this filesystem, then the result
462 # will be "defaults,atime".
463 parse_yesno_opts_wfstab () {
464 L_DEV="$1"
465 OPT="$2"
466 DEF_OPT="$3"
467 shift 3
468 L_OPTS="$*"
469 PARSEDOPTS1="$(parse_nonumber_mount_opts $OPT $L_OPTS)"
470 PARSEDOPTS1="$(parse_nonumber_mount_opts no$OPT $PARSEDOPTS1)"
471 # Watch for a default atime in fstab
472 FSTAB_OPTS="$(awk '$1 == "'$L_DEV'" { print $4 }' /etc/fstab)"
473 if echo "$FSTAB_OPTS" | grep "$OPT" > /dev/null ; then
474 # option specified in fstab: extract the value and use it
475 if echo "$FSTAB_OPTS" | grep "no$OPT" > /dev/null ; then
476 echo "$PARSEDOPTS1,no$OPT"
477 else
478 # no$OPT not found -- so we must have $OPT.
479 echo "$PARSEDOPTS1,$OPT"
480 fi
481 else
482 # option not specified in fstab -- choose the default.
483 echo "$PARSEDOPTS1,$DEF_OPT"
484 fi
485 }
486
487 # Find out the state of a numbered option (e.g. "commit=NNN") in
488 # fstab for a given filesystem, and use this state to replace the
489 # value of the option in another mount options string. The device
490 # is the first argument, and the option name the second. The
491 # remainder is the mount options string in which the replacement
492 # must be done.
493 #
494 # Example:
495 # parse_mount_opts_wfstab /dev/hda1 commit defaults,commit=7
496 #
497 # If fstab contains, say, "commit=3,rw" for this filesystem, then the
498 # result will be "rw,commit=3".
499 parse_mount_opts_wfstab () {
500 L_DEV="$1"
501 OPT="$2"
502 shift 2
503 L_OPTS="$*"
504 PARSEDOPTS1="$(parse_mount_opts $OPT $L_OPTS)"
505 # Watch for a default commit in fstab
506 FSTAB_OPTS="$(awk '$1 == "'$L_DEV'" { print $4 }' /etc/fstab)"
507 if echo "$FSTAB_OPTS" | grep "$OPT=" > /dev/null ; then
508 # option specified in fstab: extract the value, and use it
509 echo -n "$PARSEDOPTS1,$OPT="
510 echo ",$FSTAB_OPTS," | sed \
511 -e 's/.*,'"$OPT"'=//' \
512 -e 's/,.*//'
513 else
514 # option not specified in fstab: set it to 0
515 echo "$PARSEDOPTS1,$OPT=0"
516 fi
517 }
518
519 deduce_fstype () {
520 MP="$1"
521 # My root filesystem unfortunately has
522 # type "unknown" in /etc/mtab. If we encounter
523 # "unknown", we try to get the type from fstab.
524 cat /etc/fstab |
525 grep -v '^#' |
526 while read FSTAB_DEV FSTAB_MP FSTAB_FST FSTAB_OPTS FSTAB_DUMP FSTAB_DUMP ; do
527 if [ "$FSTAB_MP" = "$MP" ]; then
528 echo $FSTAB_FST
529 exit 0
530 fi
531 done
532 }
533
534 if [ $DO_REMOUNT_NOATIME -eq 1 ] ; then
535 NOATIME_OPT=",noatime"
536 fi
537
538 case "$1" in
539 start)
540 AGE=$((100*$MAX_AGE))
541 XFS_AGE=$(($XFS_HZ*$MAX_AGE))
542 echo -n "Starting laptop_mode"
543
544 if [ -d /proc/sys/vm/pagebuf ] ; then
545 # (For 2.4 and early 2.6.)
546 # This only needs to be set, not reset -- it is only used when
547 # laptop mode is enabled.
548 echo $XFS_AGE > /proc/sys/vm/pagebuf/lm_flush_age
549 echo $XFS_AGE > /proc/sys/fs/xfs/lm_sync_interval
550 elif [ -f /proc/sys/fs/xfs/lm_age_buffer ] ; then
551 # (A couple of early 2.6 laptop mode patches had these.)
552 # The same goes for these.
553 echo $XFS_AGE > /proc/sys/fs/xfs/lm_age_buffer
554 echo $XFS_AGE > /proc/sys/fs/xfs/lm_sync_interval
555 elif [ -f /proc/sys/fs/xfs/age_buffer ] ; then
556 # (2.6.6)
557 # But not for these -- they are also used in normal
558 # operation.
559 echo $XFS_AGE > /proc/sys/fs/xfs/age_buffer
560 echo $XFS_AGE > /proc/sys/fs/xfs/sync_interval
561 elif [ -f /proc/sys/fs/xfs/age_buffer_centisecs ] ; then
562 # (2.6.7 upwards)
563 # And not for these either. These are in centisecs,
564 # not USER_HZ, so we have to use $AGE, not $XFS_AGE.
565 echo $AGE > /proc/sys/fs/xfs/age_buffer_centisecs
566 echo $AGE > /proc/sys/fs/xfs/xfssyncd_centisecs
567 echo 3000 > /proc/sys/fs/xfs/xfsbufd_centisecs
568 fi
569
570 case "$KLEVEL" in
571 "2.4")
572 echo 1 > /proc/sys/vm/laptop_mode
573 echo "30 500 0 0 $AGE $AGE 60 20 0" > /proc/sys/vm/bdflush
574 ;;
575 "2.6")
576 echo 5 > /proc/sys/vm/laptop_mode
577 echo "$AGE" > /proc/sys/vm/dirty_writeback_centisecs
578 echo "$AGE" > /proc/sys/vm/dirty_expire_centisecs
579 echo "$DIRTY_RATIO" > /proc/sys/vm/dirty_ratio
580 echo "$DIRTY_BACKGROUND_RATIO" > /proc/sys/vm/dirty_background_ratio
581 ;;
582 esac
583 if [ $DO_REMOUNTS -eq 1 ]; then
584 cat /etc/mtab | while read DEV MP FST OPTS DUMP PASS ; do
585 PARSEDOPTS="$(parse_mount_opts "$OPTS")"
586 if [ "$FST" = 'unknown' ]; then
587 FST=$(deduce_fstype $MP)
588 fi
589 case "$FST" in
590 "ext3")
591 PARSEDOPTS="$(parse_mount_opts commit "$OPTS")"
592 mount $DEV -t $FST $MP -o remount,$PARSEDOPTS,commit=$MAX_AGE$NOATIME_OPT
593 ;;
594 "xfs")
595 mount $DEV -t $FST $MP -o remount,$OPTS$NOATIME_OPT
596 ;;
597 esac
598 if [ -b $DEV ] ; then
599 blockdev --setra $(($READAHEAD * 2)) $DEV
600 fi
601 done
602 fi
603 if [ $DO_HD -eq 1 ] ; then
604 for THISHD in $HD ; do
605 /sbin/hdparm -S $BATT_HD $THISHD > /dev/null 2>&1
606 /sbin/hdparm -B 1 $THISHD > /dev/null 2>&1
607 done
608 fi
609 if [ $DO_CPU -eq 1 -a -e /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq ]; then
610 if [ $CPU_MAXFREQ = 'slowest' ]; then
611 CPU_MAXFREQ=`cat /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq`
612 fi
613 echo $CPU_MAXFREQ > /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq
614 fi
615 echo "."
616 ;;
617 stop)
618 U_AGE=$((100*$DEF_UPDATE))
619 B_AGE=$((100*$DEF_AGE))
620 echo -n "Stopping laptop_mode"
621 echo 0 > /proc/sys/vm/laptop_mode
622 if [ -f /proc/sys/fs/xfs/age_buffer -a ! -f /proc/sys/fs/xfs/lm_age_buffer ] ; then
623 # These need to be restored, if there are no lm_*.
624 echo $(($XFS_HZ*$DEF_XFS_AGE_BUFFER)) > /proc/sys/fs/xfs/age_buffer
625 echo $(($XFS_HZ*$DEF_XFS_SYNC_INTERVAL)) > /proc/sys/fs/xfs/sync_interval
626 elif [ -f /proc/sys/fs/xfs/age_buffer_centisecs ] ; then
627 # These need to be restored as well.
628 echo $((100*$DEF_XFS_AGE_BUFFER)) > /proc/sys/fs/xfs/age_buffer_centisecs
629 echo $((100*$DEF_XFS_SYNC_INTERVAL)) > /proc/sys/fs/xfs/xfssyncd_centisecs
630 echo $((100*$DEF_XFS_BUFD_INTERVAL)) > /proc/sys/fs/xfs/xfsbufd_centisecs
631 fi
632 case "$KLEVEL" in
633 "2.4")
634 echo "30 500 0 0 $U_AGE $B_AGE 60 20 0" > /proc/sys/vm/bdflush
635 ;;
636 "2.6")
637 echo "$U_AGE" > /proc/sys/vm/dirty_writeback_centisecs
638 echo "$B_AGE" > /proc/sys/vm/dirty_expire_centisecs
639 echo "$DEF_DIRTY_RATIO" > /proc/sys/vm/dirty_ratio
640 echo "$DEF_DIRTY_BACKGROUND_RATIO" > /proc/sys/vm/dirty_background_ratio
641 ;;
642 esac
643 if [ $DO_REMOUNTS -eq 1 ] ; then
644 cat /etc/mtab | while read DEV MP FST OPTS DUMP PASS ; do
645 # Reset commit and atime options to defaults.
646 if [ "$FST" = 'unknown' ]; then
647 FST=$(deduce_fstype $MP)
648 fi
649 case "$FST" in
650 "ext3")
651 PARSEDOPTS="$(parse_mount_opts_wfstab $DEV commit $OPTS)"
652 PARSEDOPTS="$(parse_yesno_opts_wfstab $DEV atime atime $PARSEDOPTS)"
653 mount $DEV -t $FST $MP -o remount,$PARSEDOPTS
654 ;;
655 "xfs")
656 PARSEDOPTS="$(parse_yesno_opts_wfstab $DEV atime atime $OPTS)"
657 mount $DEV -t $FST $MP -o remount,$PARSEDOPTS
658 ;;
659 esac
660 if [ -b $DEV ] ; then
661 blockdev --setra 256 $DEV
662 fi
663 done
664 fi
665 if [ $DO_HD -eq 1 ] ; then
666 for THISHD in $HD ; do
667 /sbin/hdparm -S $AC_HD $THISHD > /dev/null 2>&1
668 /sbin/hdparm -B 255 $THISHD > /dev/null 2>&1
669 done
670 fi
671 if [ $DO_CPU -eq 1 -a -e /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq ]; then
672 echo `cat /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq` > /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq
673 fi
674 echo "."
675 ;;
676 *)
677 echo "Usage: $0 {start|stop}" 2>&1
678 exit 1
679 ;;
680
681 esac
682
683 exit 0
684
685
686 ACPI integration
687 ----------------
688
689 Dax Kelson submitted this so that the ACPI acpid daemon will
690 kick off the laptop_mode script and run hdparm. The part that
691 automatically disables laptop mode when the battery is low was
692 written by Jan Topinski.
693
694 /etc/acpi/events/ac_adapter::
695
696 event=ac_adapter
697 action=/etc/acpi/actions/ac.sh %e
698
699 /etc/acpi/events/battery::
700
701 event=battery.*
702 action=/etc/acpi/actions/battery.sh %e
703
704 /etc/acpi/actions/ac.sh::
705
706 #!/bin/bash
707
708 # ac on/offline event handler
709
710 status=`awk '/^state: / { print $2 }' /proc/acpi/ac_adapter/$2/state`
711
712 case $status in
713 "on-line")
714 /sbin/laptop_mode stop
715 exit 0
716 ;;
717 "off-line")
718 /sbin/laptop_mode start
719 exit 0
720 ;;
721 esac
722
723
724 /etc/acpi/actions/battery.sh::
725
726 #! /bin/bash
727
728 # Automatically disable laptop mode when the battery almost runs out.
729
730 BATT_INFO=/proc/acpi/battery/$2/state
731
732 if [[ -f /proc/sys/vm/laptop_mode ]]
733 then
734 LM=`cat /proc/sys/vm/laptop_mode`
735 if [[ $LM -gt 0 ]]
736 then
737 if [[ -f $BATT_INFO ]]
738 then
739 # Source the config file only now that we know we need
740 if [ -f /etc/default/laptop-mode ] ; then
741 # Debian
742 . /etc/default/laptop-mode
743 elif [ -f /etc/sysconfig/laptop-mode ] ; then
744 # Others
745 . /etc/sysconfig/laptop-mode
746 fi
747 MINIMUM_BATTERY_MINUTES=${MINIMUM_BATTERY_MINUTES:-'10'}
748
749 ACTION="`cat $BATT_INFO | grep charging | cut -c 26-`"
750 if [[ ACTION -eq "discharging" ]]
751 then
752 PRESENT_RATE=`cat $BATT_INFO | grep "present rate:" | sed "s/.* \([0-9][0-9]* \).*/\1/" `
753 REMAINING=`cat $BATT_INFO | grep "remaining capacity:" | sed "s/.* \([0-9][0-9]* \).*/\1/" `
754 fi
755 if (($REMAINING * 60 / $PRESENT_RATE < $MINIMUM_BATTERY_MINUTES))
756 then
757 /sbin/laptop_mode stop
758 fi
759 else
760 logger -p daemon.warning "You are using laptop mode and your battery interface $BATT_INFO is missing. This may lead to loss of data when the battery runs out. Check kernel ACPI support and /proc/acpi/battery folder, and edit /etc/acpi/battery.sh to set BATT_INFO to the correct path."
761 fi
762 fi
763 fi
764
765
766 Monitoring tool
767 ---------------
768
769 Bartek Kania submitted this, it can be used to measure how much time your disk
770 spends spun up/down. See tools/laptop/dslm/dslm.c
771

3. 한국어 전문 번역

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

laptop mode 소개

1-29

문서 작성자: Bart Samwel ([email protected])

작성일: 2004년 1월 2일, 마지막 수정: 2004년 12월 6일

laptop mode는 laptop의 battery 전력을 절약하기 위해 hard disk가 spin-up 상태로 있어야 하는 시간을 최소화합니다. 상당한 절전 효과가 있다는 보고가 있습니다.

문서는 소개, 설치, 주의 사항, 세부 동작, 팁과 요령, control script, ACPI 통합, monitoring tool 순서로 구성됩니다.

설치와 수동 시작

30-50

laptop mode를 사용하기 위해 별도의 kernel configuration option을 설정할 필요는 없습니다. 이 문서에 포함된 파일을 모두 설치하면 battery로 동작할 때 laptop mode가 자동으로 시작됩니다.

installer가 들어 있는 tarball은 다음 위치에서 받을 수 있습니다.

설정 파일은 Debian 계열에서는 `/etc/default/laptop-mode`, 그 밖의 시스템에서는 `/etc/sysconfig/laptop-mode`에 있습니다.

ACPI가 없는 laptop에서는 자동 enable이 동작하지 않습니다. 이 경우 `laptop_mode start`로 수동 시작하고 `laptop_mode stop`으로 중지합니다. laptop mode tools package에는 experimental APM 지원도 있으므로 먼저 시험할 수 있습니다.

데이터·drive·filesystem 주의 사항

51-78

laptop mode의 단점은 최대 10분 분량의 작업을 잃을 가능성이 있다는 것입니다. 이를 감당할 수 없다면 사용하지 마십시오. 함께 제공되는 ACPI script는 battery가 거의 소진되면 laptop mode를 자동으로 꺼서 battery 수명 끝에 데이터가 손실되지 않게 합니다.

대부분의 desktop hard drive는 spindown cycle로 측정하는 수명이 매우 제한적이며 보통 약 50,000회입니다. specification sheet에서 drive 등급을 확인하고, 필요하지 않다면 불필요한 cycle로 수명을 줄이지 마십시오.

일부 ext3 filesystem을 `-n` option으로 mount했다면 control script가 올바르게 remount할 수 없습니다. `DO_REMOUNTS=0`으로 설정해야 합니다. 그렇지 않으면 잘못된 option으로 remount하거나 `/etc/mtab`에 쓸 수 없어 실패합니다.

`fstab`에 filesystem type을 `auto`로 기록하면 control script가 remount 대상 filesystem으로 인식하지 못합니다. 실제 filesystem type을 적어야 합니다.

일부 `mutt` mail client 버전은 folder에 새 mail이 있는지 판단할 때 file access time을 사용한다고 보고되었습니다. 이 문제가 있다면 configuration file에서 `DO_REMOUNT_NOATIME=0`으로 설정하여 `noatime` remount를 disable해야 합니다.

dirty page writeback 집중 원리

79-104

laptop mode는 `/proc/sys/vm/laptop_mode` knob으로 제어합니다. 이 knob은 configuration option과 무관하게 laptop mode patch가 적용된 모든 kernel에 있습니다.

knob을 설정하면 hard disk를 spin-up시킬 수 있는 physical disk I/O가 발생할 때 Linux가 모든 dirty block을 flush합니다. 따라서 disk가 spin-down된 뒤에는 dirty block을 쓰려고 다시 spin-up할 필요가 없습니다. 그 block은 가장 최근 read operation 직후 이미 기록되었기 때문입니다.

`laptop_mode` knob 값은 disk I/O 발생과 flush trigger 사이의 시간을 정합니다. 합리적인 값은 5초이며, 0으로 설정하면 laptop mode를 disable합니다.

효과를 높이기 위해 control script는 `/proc/sys/vm`의 `dirty_expire_centisecs`와 `dirty_writeback_centisecs`를 기본적으로 약 10분으로 늘려 dirty page가 disk에 강제로 기록되는 빈도를 낮춥니다. dirty background ratio도 바꾸어 background dirty-page writeback이 더 이상 일어나지 않게 합니다.

ext3 filesystem의 commit 값도 10분으로 늘립니다. 그 결과 disk activity는 10분마다 한 번 또는 cache miss 때문에 disk를 강제로 spin-up할 때만 짧은 시간에 집중되며, 비활성 구간에는 disk를 spin-down할 수 있습니다.

Configuration option

105-186

configuration file은 Debian 계열의 `/etc/default/laptop-mode` 또는 다른 시스템의 `/etc/sysconfig/laptop-mode`에 있으며 다음 option을 포함합니다.

option설명
MAX_AGE허용할 hard drive spindown 시간의 최댓값(초)입니다. battery가 laptop mode 중 실패하면 최악의 경우 이 시간만큼 작업을 잃을 수 있습니다.
MINIMUM_BATTERY_MINUTES남은 battery 시간이 이 값보다 작으면 laptop mode를 자동 disable합니다. 기본값은 10분입니다.
AC_HD / BATT_HDlaptop mode가 비활성일 때와 활성일 때의 hard-drive idle timeout입니다. 기본값은 AC에서 2시간(`244`), battery에서 20초(`4`)입니다. 가능한 값은 `hdparm -S` manual을 따릅니다.
HDlaptop mode가 spindown timeout을 조정할 device입니다. 기본값은 `/dev/hda`이며 여러 device는 space로 구분합니다.
READAHEADlaptop mode 중 disk readahead 크기이며 단위는 512-byte sector입니다. 큰 값은 demand-load executable page나 MP3 같은 sequential data 때문에 생기는 disk access를 줄일 수 있습니다.
DO_REMOUNTSjournaled filesystem을 적절한 commit interval로 자동 remount합니다. `0`이면 disable합니다.
DO_REMOUNT_NOATIMEremount할 때 `noatime`을 추가할지 정합니다. 보통 `1`이지만 access-time 기록이 필요한 program이 있을 수 있습니다.
DIRTY_RATIO강제 writeback 전까지 dirty 또는 미저장 data가 차지해도 되는 memory 비율입니다. `/proc/sys/vm/dirty_ratio`에 대응합니다.
DIRTY_BACKGROUND_RATIO`DIRTY_RATIO` 초과로 강제 writeback한 뒤 남겨 둘 dirty memory 비율입니다. 낮게 설정하며 `/proc/sys/vm/dirty_background_ratio`에 대응합니다.
DO_CPUlaptop mode에서 CPU frequency scaling을 enable합니다. CPUFreq 설정이 필요하며 기본적으로 disable입니다. `Documentation/admin-guide/pm/cpufreq.rst`를 참조하십시오.
CPU_MAXFREQbattery 사용 중 허용할 최대 CPU speed입니다. CPU 최저 속도를 뜻하는 `slowest` 또는 `/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies`에 나열된 값을 사용합니다.

`dirty_background_ratio`의 동작은 laptop mode 활성 여부에 따라 크게 다릅니다. 비활성일 때는 background writeout을 시작하는 threshold 비율입니다. 활성일 때는 background writeout이 disable되므로 `dirty_ratio`에 도달했을 때 얼마만큼 writeback할지만 정합니다.

팁과 요령

187-217

Bartek Kania는 5초 spindown time(`BATT_HD=1`)으로 평소 3~3.5시간에 최대 50분의 battery 사용 시간을 더 얻었다고 보고했습니다.

disk readahead를 8MB(`READAHEAD=16384`)로 설정하면 MP3를 재생하면서 disk를 spin-down할 수 있습니다. disk가 MP3 하나를 한 번에 읽고 재생 중에는 spin-down하는 방식입니다.

Drew Scott Daniels는 display 색상 수를 줄였을 때 battery 소비가 감소했으며 PowerBook에서도 이를 보았다고 보고했습니다.

`syslog.conf` entry 앞에 dash `-`를 붙이면 logging할 때마다 file을 sync하지 않습니다. laptop mode에서 disk가 spin-down하지 않는다면 이것이 원인일 가능성이 큽니다.

Richard Atterer는 laptop mode와 `noflushd`가 잘 동작하지 않으며, noflushd가 laptop mode의 동작을 방해하는 것으로 보인다고 관찰했습니다.

데이터가 걱정된다면 USB memory stick 등을 작업 영역으로 사용할 수 있습니다. 다만 flash memory는 write 횟수가 제한되어 과도하게 사용하면 빠르게 마모될 수 있습니다. flash memory stick에 journalling filesystem을 사용하지 마십시오.

Control·ACPI script용 configuration file

218-304

이 외부 configuration file을 사용하면 control script와 ACPI battery script의 tunable을 바꿀 수 있습니다. Debian에서는 `/etc/default/laptop-mode`, Red Hat·SUSE·Mandrake 및 유사 시스템에서는 `/etc/sysconfig/laptop-mode`로 설치합니다.

아래 원문 configuration은 `MAX_AGE`, battery threshold, readahead, remount·noatime, dirty ratio 기본값, XFS timer, CPUFreq, `hdparm` timeout과 대상 drive를 정의합니다. Kernel 2.4의 XFS external interface는 `HZ`를 수동 반영해야 하지만 2.6은 항상 100인 `USER_HZ`를 사용합니다.

# Maximum time, in seconds, of hard drive spindown time that you are
# comfortable with. Worst case, it's possible that you could lose this
# amount of work if your battery fails you while in laptop mode.
#MAX_AGE=600

# Automatically disable laptop mode when the number of minutes of battery
# that you have left goes below this threshold.
MINIMUM_BATTERY_MINUTES=10

# Read-ahead, in 512-byte sectors. You can spin down the disk while playing MP3/OGG
# by setting the disk readahead to 8MB (READAHEAD=16384). Effectively, the disk
# will read a complete MP3 at once, and will then spin down while the MP3/OGG is
# playing.
#READAHEAD=4096

# Shall we remount journaled fs. with appropriate commit interval? (1=yes)
#DO_REMOUNTS=1

# And shall we add the "noatime" option to that as well? (1=yes)
#DO_REMOUNT_NOATIME=1

# Dirty synchronous ratio.  At this percentage of dirty pages the process
# which
# calls write() does its own writeback
#DIRTY_RATIO=40

#
# Allowed dirty background ratio, in percent.  Once DIRTY_RATIO has been
# exceeded, the kernel will wake flusher threads which will then reduce the
# amount of dirty memory to dirty_background_ratio.  Set this nice and low,
# so once some writeout has commenced, we do a lot of it.
#
#DIRTY_BACKGROUND_RATIO=5

# kernel default dirty buffer age
#DEF_AGE=30
#DEF_UPDATE=5
#DEF_DIRTY_BACKGROUND_RATIO=10
#DEF_DIRTY_RATIO=40
#DEF_XFS_AGE_BUFFER=15
#DEF_XFS_SYNC_INTERVAL=30
#DEF_XFS_BUFD_INTERVAL=1

# This must be adjusted manually to the value of HZ in the running kernel
# on 2.4, until the XFS people change their 2.4 external interfaces to work in
# centisecs. This can be automated, but it's a work in progress that still
# needs# some fixes. On 2.6 kernels, XFS uses USER_HZ instead of HZ for
# external interfaces, and that is currently always set to 100. So you don't
# need to change this on 2.6.
#XFS_HZ=100

# Should the maximum CPU frequency be adjusted down while on battery?
# Requires CPUFreq to be setup.
# See Documentation/admin-guide/pm/cpufreq.rst for more info
#DO_CPU=0

# When on battery what is the maximum CPU speed that the system should
# use? Legal values are "slowest" for the slowest speed that your
# CPU is able to operate at, or a value listed in:
# /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies
# Only applicable if DO_CPU=1.
#CPU_MAXFREQ=slowest

# Idle timeout for your hard drive (man hdparm for valid values, -S option)
# Default is 2 hours on AC (AC_HD=244) and 20 seconds for battery (BATT_HD=4).
#AC_HD=244
#BATT_HD=4

# The drives for which to adjust the idle timeout. Separate them by a space,
# e.g. HD="/dev/hda /dev/hdb".
#HD="/dev/hda"

# Set the spindown timeout on a hard drive?
#DO_HD=1

Control script 초기화와 기본값

305-400

이 control script는 Kiko Piris의 기여로 Linux 2.4와 2.6 series에서 동작합니다. AC 전원 연결 상태가 바뀔 때 power-management daemon이 `/sbin/laptop_mode`를 `start` 또는 `stop`으로 실행하는 용도입니다.

script는 배포판별 configuration file을 source하고, 빠진 값에는 기본값을 설정합니다. writeback age·ratio, XFS 기본 timer, disk timeout, readahead와 CPU frequency 값을 준비합니다. Kernel 2.4의 XFS에는 `HZ`, 2.6 external interface에는 `USER_HZ=100`을 사용합니다.

#!/bin/bash

# start or stop laptop_mode, best run by a power management daemon when
# ac gets connected/disconnected from a laptop
#
# install as /sbin/laptop_mode
#
# Contributors to this script:   Kiko Piris
#				 Bart Samwel
#				 Micha Feigin
#				 Andrew Morton
#				 Herve Eychenne
#				 Dax Kelson
#
# Original Linux 2.4 version by: Jens Axboe

#############################################################################

# Source config
if [ -f /etc/default/laptop-mode ] ; then
	# Debian
	. /etc/default/laptop-mode
elif [ -f /etc/sysconfig/laptop-mode ] ; then
	# Others
        . /etc/sysconfig/laptop-mode
fi

# Don't raise an error if the config file is incomplete
# set defaults instead:

# Maximum time, in seconds, of hard drive spindown time that you are
# comfortable with. Worst case, it's possible that you could lose this
# amount of work if your battery fails you while in laptop mode.
MAX_AGE=${MAX_AGE:-'600'}

# Read-ahead, in kilobytes
READAHEAD=${READAHEAD:-'4096'}

# Shall we remount journaled fs. with appropriate commit interval? (1=yes)
DO_REMOUNTS=${DO_REMOUNTS:-'1'}

# And shall we add the "noatime" option to that as well? (1=yes)
DO_REMOUNT_NOATIME=${DO_REMOUNT_NOATIME:-'1'}

# Shall we adjust the idle timeout on a hard drive?
DO_HD=${DO_HD:-'1'}

# Adjust idle timeout on which hard drive?
HD="${HD:-'/dev/hda'}"

# spindown time for HD (hdparm -S values)
AC_HD=${AC_HD:-'244'}
BATT_HD=${BATT_HD:-'4'}

# Dirty synchronous ratio.  At this percentage of dirty pages the process which
# calls write() does its own writeback
DIRTY_RATIO=${DIRTY_RATIO:-'40'}

# cpu frequency scaling
# See Documentation/admin-guide/pm/cpufreq.rst for more info
DO_CPU=${CPU_MANAGE:-'0'}
CPU_MAXFREQ=${CPU_MAXFREQ:-'slowest'}

#
# Allowed dirty background ratio, in percent.  Once DIRTY_RATIO has been
# exceeded, the kernel will wake flusher threads which will then reduce the
# amount of dirty memory to dirty_background_ratio.  Set this nice and low,
# so once some writeout has commenced, we do a lot of it.
#
DIRTY_BACKGROUND_RATIO=${DIRTY_BACKGROUND_RATIO:-'5'}

# kernel default dirty buffer age
DEF_AGE=${DEF_AGE:-'30'}
DEF_UPDATE=${DEF_UPDATE:-'5'}
DEF_DIRTY_BACKGROUND_RATIO=${DEF_DIRTY_BACKGROUND_RATIO:-'10'}
DEF_DIRTY_RATIO=${DEF_DIRTY_RATIO:-'40'}
DEF_XFS_AGE_BUFFER=${DEF_XFS_AGE_BUFFER:-'15'}
DEF_XFS_SYNC_INTERVAL=${DEF_XFS_SYNC_INTERVAL:-'30'}
DEF_XFS_BUFD_INTERVAL=${DEF_XFS_BUFD_INTERVAL:-'1'}

# This must be adjusted manually to the value of HZ in the running kernel
# on 2.4, until the XFS people change their 2.4 external interfaces to work in
# centisecs. This can be automated, but it's a work in progress that still needs
# some fixes. On 2.6 kernels, XFS uses USER_HZ instead of HZ for external
# interfaces, and that is currently always set to 100. So you don't need to
# change this on 2.6.
XFS_HZ=${XFS_HZ:-'100'}

Kernel 검사와 mount option helper

401-537

script는 `uname -r`에서 major.minor를 읽어 Linux 2.4 또는 2.6만 허용합니다. `/proc/sys/vm/laptop_mode`의 존재와 write 권한도 확인합니다.

`parse_mount_opts()`와 `parse_nonumber_mount_opts()`는 숫자형·boolean mount option을 제거합니다. `parse_yesno_opts_wfstab()`과 `parse_mount_opts_wfstab()`은 `/etc/fstab`의 원래 설정을 조회해 `atime/noatime`과 `commit=NNN`을 복구합니다. `deduce_fstype()`은 `/etc/mtab`에서 type이 `unknown`일 때 `/etc/fstab`에서 실제 type을 찾습니다.

#############################################################################

KLEVEL="$(uname -r |
             {
	       IFS='.' read a b c
	       echo $a.$b
	     }
)"
case "$KLEVEL" in
	"2.4"|"2.6")
		;;
	*)
		echo "Unhandled kernel version: $KLEVEL ('uname -r' = '$(uname -r)')" >&2
		exit 1
		;;
esac

if [ ! -e /proc/sys/vm/laptop_mode ] ; then
	echo "Kernel is not patched with laptop_mode patch." >&2
	exit 1
fi

if [ ! -w /proc/sys/vm/laptop_mode ] ; then
	echo "You do not have enough privileges to enable laptop_mode." >&2
	exit 1
fi

# Remove an option (the first parameter) of the form option=<number> from
# a mount options string (the rest of the parameters).
parse_mount_opts () {
	OPT="$1"
	shift
	echo ",$*," | sed		\
	 -e 's/,'"$OPT"'=[0-9]*,/,/g'	\
	 -e 's/,,*/,/g'			\
	 -e 's/^,//'			\
	 -e 's/,$//'
}

# Remove an option (the first parameter) without any arguments from
# a mount option string (the rest of the parameters).
parse_nonumber_mount_opts () {
	OPT="$1"
	shift
	echo ",$*," | sed		\
	 -e 's/,'"$OPT"',/,/g'		\
	 -e 's/,,*/,/g'			\
	 -e 's/^,//'			\
	 -e 's/,$//'
}

# Find out the state of a yes/no option (e.g. "atime"/"noatime") in
# fstab for a given filesystem, and use this state to replace the
# value of the option in another mount options string. The device
# is the first argument, the option name the second, and the default
# value the third. The remainder is the mount options string.
#
# Example:
# parse_yesno_opts_wfstab /dev/hda1 atime atime defaults,noatime
#
# If fstab contains, say, "rw" for this filesystem, then the result
# will be "defaults,atime".
parse_yesno_opts_wfstab () {
	L_DEV="$1"
	OPT="$2"
	DEF_OPT="$3"
	shift 3
	L_OPTS="$*"
	PARSEDOPTS1="$(parse_nonumber_mount_opts $OPT $L_OPTS)"
	PARSEDOPTS1="$(parse_nonumber_mount_opts no$OPT $PARSEDOPTS1)"
	# Watch for a default atime in fstab
	FSTAB_OPTS="$(awk '$1 == "'$L_DEV'" { print $4 }' /etc/fstab)"
	if echo "$FSTAB_OPTS" | grep "$OPT" > /dev/null ; then
		# option specified in fstab: extract the value and use it
		if echo "$FSTAB_OPTS" | grep "no$OPT" > /dev/null ; then
			echo "$PARSEDOPTS1,no$OPT"
		else
			# no$OPT not found -- so we must have $OPT.
			echo "$PARSEDOPTS1,$OPT"
		fi
	else
		# option not specified in fstab -- choose the default.
		echo "$PARSEDOPTS1,$DEF_OPT"
	fi
}

# Find out the state of a numbered option (e.g. "commit=NNN") in
# fstab for a given filesystem, and use this state to replace the
# value of the option in another mount options string. The device
# is the first argument, and the option name the second. The
# remainder is the mount options string in which the replacement
# must be done.
#
# Example:
# parse_mount_opts_wfstab /dev/hda1 commit defaults,commit=7
#
# If fstab contains, say, "commit=3,rw" for this filesystem, then the
# result will be "rw,commit=3".
parse_mount_opts_wfstab () {
	L_DEV="$1"
	OPT="$2"
	shift 2
	L_OPTS="$*"
	PARSEDOPTS1="$(parse_mount_opts $OPT $L_OPTS)"
	# Watch for a default commit in fstab
	FSTAB_OPTS="$(awk '$1 == "'$L_DEV'" { print $4 }' /etc/fstab)"
	if echo "$FSTAB_OPTS" | grep "$OPT=" > /dev/null ; then
		# option specified in fstab: extract the value, and use it
		echo -n "$PARSEDOPTS1,$OPT="
		echo ",$FSTAB_OPTS," | sed \
		 -e 's/.*,'"$OPT"'=//'	\
		 -e 's/,.*//'
	else
		# option not specified in fstab: set it to 0
		echo "$PARSEDOPTS1,$OPT=0"
	fi
}

deduce_fstype () {
	MP="$1"
	# My root filesystem unfortunately has
	# type "unknown" in /etc/mtab. If we encounter
	# "unknown", we try to get the type from fstab.
	cat /etc/fstab |
	grep -v '^#' |
	while read FSTAB_DEV FSTAB_MP FSTAB_FST FSTAB_OPTS FSTAB_DUMP FSTAB_DUMP ; do
		if [ "$FSTAB_MP" = "$MP" ]; then
			echo $FSTAB_FST
			exit 0
		fi
	done
}

if [ $DO_REMOUNT_NOATIME -eq 1 ] ; then
	NOATIME_OPT=",noatime"
fi

laptop_mode start 동작

538-616

`start`는 `MAX_AGE`를 centisecond와 XFS tick 값으로 바꾸고, kernel 세대에 맞는 XFS flush-age interface를 설정합니다. Linux 2.4에서는 `bdflush`, 2.6에서는 `dirty_writeback_centisecs`, `dirty_expire_centisecs`, `dirty_ratio`, `dirty_background_ratio`를 조정합니다.

`DO_REMOUNTS=1`이면 `/etc/mtab`의 ext3에 `commit=$MAX_AGE`와 선택적 `noatime`을 적용하고 XFS도 선택적으로 `noatime`으로 remount합니다. block device readahead를 바꾸고, `hdparm -S/-B`로 battery용 spindown·power-management 값을 설정하며, 요청한 경우 CPU maximum frequency를 낮춥니다.

case "$1" in
	start)
		AGE=$((100*$MAX_AGE))
		XFS_AGE=$(($XFS_HZ*$MAX_AGE))
		echo -n "Starting laptop_mode"

		if [ -d /proc/sys/vm/pagebuf ] ; then
			# (For 2.4 and early 2.6.)
			# This only needs to be set, not reset -- it is only used when
			# laptop mode is enabled.
			echo $XFS_AGE > /proc/sys/vm/pagebuf/lm_flush_age
			echo $XFS_AGE > /proc/sys/fs/xfs/lm_sync_interval
		elif [ -f /proc/sys/fs/xfs/lm_age_buffer ] ; then
			# (A couple of early 2.6 laptop mode patches had these.)
			# The same goes for these.
			echo $XFS_AGE > /proc/sys/fs/xfs/lm_age_buffer
			echo $XFS_AGE > /proc/sys/fs/xfs/lm_sync_interval
		elif [ -f /proc/sys/fs/xfs/age_buffer ] ; then
			# (2.6.6)
			# But not for these -- they are also used in normal
			# operation.
			echo $XFS_AGE > /proc/sys/fs/xfs/age_buffer
			echo $XFS_AGE > /proc/sys/fs/xfs/sync_interval
		elif [ -f /proc/sys/fs/xfs/age_buffer_centisecs ] ; then
			# (2.6.7 upwards)
			# And not for these either. These are in centisecs,
			# not USER_HZ, so we have to use $AGE, not $XFS_AGE.
			echo $AGE > /proc/sys/fs/xfs/age_buffer_centisecs
			echo $AGE > /proc/sys/fs/xfs/xfssyncd_centisecs
			echo 3000 > /proc/sys/fs/xfs/xfsbufd_centisecs
		fi

		case "$KLEVEL" in
			"2.4")
				echo 1					> /proc/sys/vm/laptop_mode
				echo "30 500 0 0 $AGE $AGE 60 20 0"	> /proc/sys/vm/bdflush
				;;
			"2.6")
				echo 5					> /proc/sys/vm/laptop_mode
				echo "$AGE"				> /proc/sys/vm/dirty_writeback_centisecs
				echo "$AGE"				> /proc/sys/vm/dirty_expire_centisecs
				echo "$DIRTY_RATIO"			> /proc/sys/vm/dirty_ratio
				echo "$DIRTY_BACKGROUND_RATIO"		> /proc/sys/vm/dirty_background_ratio
				;;
		esac
		if [ $DO_REMOUNTS -eq 1 ]; then
			cat /etc/mtab | while read DEV MP FST OPTS DUMP PASS ; do
				PARSEDOPTS="$(parse_mount_opts "$OPTS")"
				if [ "$FST" = 'unknown' ]; then
					FST=$(deduce_fstype $MP)
				fi
				case "$FST" in
					"ext3")
						PARSEDOPTS="$(parse_mount_opts commit "$OPTS")"
						mount $DEV -t $FST $MP -o remount,$PARSEDOPTS,commit=$MAX_AGE$NOATIME_OPT
						;;
					"xfs")
						mount $DEV -t $FST $MP -o remount,$OPTS$NOATIME_OPT
						;;
				esac
				if [ -b $DEV ] ; then
					blockdev --setra $(($READAHEAD * 2)) $DEV
				fi
			done
		fi
		if [ $DO_HD -eq 1 ] ; then
			for THISHD in $HD ; do
				/sbin/hdparm -S $BATT_HD $THISHD > /dev/null 2>&1
				/sbin/hdparm -B 1 $THISHD > /dev/null 2>&1
			done
		fi
		if [ $DO_CPU -eq 1 -a -e /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq ]; then
			if [ $CPU_MAXFREQ = 'slowest' ]; then
				CPU_MAXFREQ=`cat /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq`
			fi
			echo $CPU_MAXFREQ > /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq
		fi
		echo "."
		;;

laptop_mode stop 동작

617-685

`stop`은 `/proc/sys/vm/laptop_mode`를 0으로 만들고 XFS, Linux 2.4 `bdflush`, Linux 2.6 dirty-page sysctl을 기본값으로 복원합니다.

ext3·XFS mount option은 `/etc/fstab`을 기준으로 `commit`과 `atime` 상태를 되돌리고 readahead는 256으로 설정합니다. `hdparm -S $AC_HD -B 255`로 AC용 disk 설정을 적용하고 CPU maximum frequency도 hardware 최댓값으로 복원합니다. 인수가 `start|stop`이 아니면 usage를 출력하고 실패합니다.

	stop)
		U_AGE=$((100*$DEF_UPDATE))
		B_AGE=$((100*$DEF_AGE))
		echo -n "Stopping laptop_mode"
		echo 0 > /proc/sys/vm/laptop_mode
		if [ -f /proc/sys/fs/xfs/age_buffer -a ! -f /proc/sys/fs/xfs/lm_age_buffer ] ; then
			# These need to be restored, if there are no lm_*.
			echo $(($XFS_HZ*$DEF_XFS_AGE_BUFFER))	 	> /proc/sys/fs/xfs/age_buffer
			echo $(($XFS_HZ*$DEF_XFS_SYNC_INTERVAL)) 	> /proc/sys/fs/xfs/sync_interval
		elif [ -f /proc/sys/fs/xfs/age_buffer_centisecs ] ; then
			# These need to be restored as well.
			echo $((100*$DEF_XFS_AGE_BUFFER))	> /proc/sys/fs/xfs/age_buffer_centisecs
			echo $((100*$DEF_XFS_SYNC_INTERVAL))	> /proc/sys/fs/xfs/xfssyncd_centisecs
			echo $((100*$DEF_XFS_BUFD_INTERVAL))	> /proc/sys/fs/xfs/xfsbufd_centisecs
		fi
		case "$KLEVEL" in
			"2.4")
				echo "30 500 0 0 $U_AGE $B_AGE 60 20 0"	> /proc/sys/vm/bdflush
				;;
			"2.6")
				echo "$U_AGE"				> /proc/sys/vm/dirty_writeback_centisecs
				echo "$B_AGE"				> /proc/sys/vm/dirty_expire_centisecs
				echo "$DEF_DIRTY_RATIO"			> /proc/sys/vm/dirty_ratio
				echo "$DEF_DIRTY_BACKGROUND_RATIO"	> /proc/sys/vm/dirty_background_ratio
				;;
		esac
		if [ $DO_REMOUNTS -eq 1 ] ; then
			cat /etc/mtab | while read DEV MP FST OPTS DUMP PASS ; do
				# Reset commit and atime options to defaults.
				if [ "$FST" = 'unknown' ]; then
					FST=$(deduce_fstype $MP)
				fi
				case "$FST" in
					"ext3")
						PARSEDOPTS="$(parse_mount_opts_wfstab $DEV commit $OPTS)"
						PARSEDOPTS="$(parse_yesno_opts_wfstab $DEV atime atime $PARSEDOPTS)"
						mount $DEV -t $FST $MP -o remount,$PARSEDOPTS
						;;
					"xfs")
						PARSEDOPTS="$(parse_yesno_opts_wfstab $DEV atime atime $OPTS)"
						mount $DEV -t $FST $MP -o remount,$PARSEDOPTS
						;;
				esac
				if [ -b $DEV ] ; then
					blockdev --setra 256 $DEV
				fi
			done
		fi
		if [ $DO_HD -eq 1 ] ; then
			for THISHD in $HD ; do
				/sbin/hdparm -S $AC_HD $THISHD > /dev/null 2>&1
				/sbin/hdparm -B 255 $THISHD > /dev/null 2>&1
			done
		fi
		if [ $DO_CPU -eq 1 -a -e /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq ]; then
			echo `cat /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq` > /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq
		fi
		echo "."
		;;
	*)
		echo "Usage: $0 {start|stop}" 2>&1
		exit 1
		;;

esac

exit 0

ACPI event 통합과 low-battery 보호

686-765

Dax Kelson은 ACPI `acpid` daemon이 `laptop_mode` script와 `hdparm`을 실행하도록 이 통합 예제를 제출했습니다. battery가 부족할 때 laptop mode를 자동 disable하는 부분은 Jan Topinski가 작성했습니다.

/etc/acpi/events/ac_adapter

AC adapter event를 `/etc/acpi/actions/ac.sh`로 전달합니다.

event=ac_adapter
action=/etc/acpi/actions/ac.sh %e

/etc/acpi/events/battery

battery event를 `/etc/acpi/actions/battery.sh`로 전달합니다.

event=battery.*
action=/etc/acpi/actions/battery.sh %e

/etc/acpi/actions/ac.sh

AC 상태가 `on-line`이면 `/sbin/laptop_mode stop`, `off-line`이면 `/sbin/laptop_mode start`를 실행합니다.

#!/bin/bash

# ac on/offline event handler

status=`awk '/^state: / { print $2 }' /proc/acpi/ac_adapter/$2/state`

case $status in
        "on-line")
                /sbin/laptop_mode stop
                exit 0
        ;;
        "off-line")
                /sbin/laptop_mode start
                exit 0
        ;;
esac

/etc/acpi/actions/battery.sh

laptop mode가 활성이고 battery state 파일이 있으면 configuration을 읽고, remaining capacity와 present rate로 남은 시간을 계산합니다. 남은 시간이 `MINIMUM_BATTERY_MINUTES`보다 작으면 laptop mode를 중지합니다. battery interface가 없으면 데이터 손실 가능성을 알리는 daemon warning을 기록합니다.

#! /bin/bash

# Automatically disable laptop mode when the battery almost runs out.

BATT_INFO=/proc/acpi/battery/$2/state

if [[ -f /proc/sys/vm/laptop_mode ]]
then
   LM=`cat /proc/sys/vm/laptop_mode`
   if [[ $LM -gt 0 ]]
   then
     if [[ -f $BATT_INFO ]]
     then
        # Source the config file only now that we know we need
        if [ -f /etc/default/laptop-mode ] ; then
                # Debian
                . /etc/default/laptop-mode
        elif [ -f /etc/sysconfig/laptop-mode ] ; then
                # Others
                . /etc/sysconfig/laptop-mode
        fi
        MINIMUM_BATTERY_MINUTES=${MINIMUM_BATTERY_MINUTES:-'10'}

        ACTION="`cat $BATT_INFO | grep charging | cut -c 26-`"
        if [[ ACTION -eq "discharging" ]]
        then
           PRESENT_RATE=`cat $BATT_INFO | grep "present rate:" | sed  "s/.* \([0-9][0-9]* \).*/\1/" `
           REMAINING=`cat $BATT_INFO | grep "remaining capacity:" | sed  "s/.* \([0-9][0-9]* \).*/\1/" `
        fi
        if (($REMAINING * 60 / $PRESENT_RATE < $MINIMUM_BATTERY_MINUTES))
        then
           /sbin/laptop_mode stop
        fi
     else
       logger -p daemon.warning "You are using laptop mode and your battery interface $BATT_INFO is missing. This may lead to loss of data when the battery runs out. Check kernel ACPI support and /proc/acpi/battery folder, and edit /etc/acpi/battery.sh to set BATT_INFO to the correct path."
     fi
   fi
fi

Disk spin 상태 monitoring tool

766-770

Bartek Kania가 제출한 monitoring tool은 disk가 spin-up과 spin-down 상태에서 각각 보낸 시간을 측정합니다. source는 `tools/laptop/dslm/dslm.c`를 참조하십시오.