Debian Codegraph @

powerd

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 #!/bin/bash
2 # (search for POSIX, below, for notes on shell compatibility)
3 #
4 # powerd -- power management for the XO
5 #
6 # This daemon is a more transparent and flexible (if somewhat
7 # incompatible) replacement for ohmd on the XO. powerd is
8 # independent of X, dbus, and hald, and so might be attractive to
9 # very lightweight software distributions.
10 #
11 # In addition to "standard" XO/ohmd functionality, powerd adds:
12 # -- a power button splash screen (allowing cancel, suspend, or shutdown).
13 # -- the ability to run arbitrary scripts after a resume.
14 # -- configurable timeouts until screen dim and sleep, and configurable
15 # dim level.
16 # -- screen dimming and blanking after laptop has slept
17 # -- shutdown after laptop has slept
18 # -- low battery shutdown (only when not sleeping)
19 # -- different power management behavior when on wall power vs. battery.
20 # -- different behavior when in ebook mode
21 # -- ease of customization, given that its written in shell.
22 # -- integrated power logging, to assist in analyzing XO power usage
23 #
24 #
25 #####
26 #
27 # Configuration:
28 #
29 # Major config variables are documented below. powerd reads
30 # its configuration from /etc/powerd/powerd.conf once at startup,
31 # and again only when it receives a "reconfig" event on its
32 # event fifo. (short answer: "sudo powerd-config =restart")
33 #
34 # If /etc/powerd/powerd.conf is a symlink to another file, then
35 # powerd-config can be used to easily manage a set of
36 # named configuration "profiles". So different configurations
37 # can be used at different times of day, or during different
38 # tasks, etc.
39 #
40 # All times are expressed in seconds (though a UI could do
41 # whatever it wants, of course). Booleans can be enabled with
42 # "yes", "Yes", "true", "True", or "1". Anything else will turn
43 # them off.
44 #
45 # There are "dim", "sleep", and "blank" timers for each of
46 # "plugged in", "battery", and "ebook" modes. (If the laptop is
47 # plugged in while in ebook mode, the plugged in timers are
48 # used.) The nine idle timers are:
49 #
50 # config_BATTERY_TIME_{DIM,SLEEP,BLANK}
51 # config_EBOOK_TIME_{DIM,SLEEP,BLANK}
52 # config_PLUGGED_TIME_{DIM,SLEEP,BLANK}
53 #
54 # Dimming, blanking, and sleep can be scheduled in any order. If
55 # "sleep" happens first, the screen will stay on (potentially
56 # dimmed) while the rest of the system sleeps, but any keystroke
57 # or touchpad activity will awaken it. If "sleep" is scheduled
58 # after "dim" or "blank", the screen will go dim and/or dark
59 # while the laptop remains otherwise fully active. Obviously,
60 # scheduling dimming after blanking only serves to skip the
61 # dimming state, since a blanked screen can't be dimmed.
62 #
63 # Setting any of the timers to '0' suppresses that action. (The
64 # value is converted to 999999999 seconds internally, so you may
65 # see that in the logs.)
66 #
67 # Depending on the setting of # "config_KEYPRESS_WAKE_FROM_BLANK_IDLE_SLEEP",
68 # when the screen is dark _and_ the laptop is sleeping, it may or
69 # may not be in a "deep" sleep -- keystrokes may or may not wake it
70 # up. Likewise, "config_WLAN_WAKE_FROM_BLANK_IDLE_SLEEP" controls
71 # whether wlan packets may wake the laptop. (See below for more
72 # information.) The maximum time that this state (i.e., screen off, cpu
73 # sleeping) will last before the laptop shuts down is given by
74 # "config_MAX_SLEEP_BEFORE_SHUTDOWN". (This is arguably mis-named,
75 # since it's not really "max sleep time before shutdown", but "max
76 # sleeping-and-blank time before shutdown".) Again, a setting of '0'
77 # will be internally converted to 999999999.
78 #
79 # Turning off "config_ALLOW_SHUTDOWN_WHEN_PLUGGED" will keep the
80 # laptop from ever completely shutting down when it has external
81 # power. It may still shut down when using battery power.
82 #
83 # "config_IDLE_DIM_LEVEL" specifies how far the screen will dim
84 # when the dim timer fires. The range is 0-15. If set to 15, the
85 # screen will never dim.
86 #
87 # "config_CONFIRM_SECONDS" determines how long the shutdown/suspend
88 # confirmation splash screen stays visible before the laptop
89 # automatically suspends. If this is set to zero, there will be
90 # no splash screen, and the laptop will suspend immediately on a
91 # power button push. In this case, shutdown must be done via
92 # a menu entry or other command.
93 #
94 # "config_UNFREEZE_SECONDS" specifies the delay before powerd
95 # will unfreeze the DCON, after starting up.
96 #
97 # "config_MESH_DURING_SUSPEND" (boolean) controls whether the
98 # wireless remains powered while the laptop is fully suspended
99 # (i.e., sleeping with a dark screen). The only reason to set
100 # this to "yes" is if you want the laptop to forward packets for
101 # other mesh users while you're not using it.
102 #
103 # "config_CPU_IDLE_LIMIT" (integer) If the cpu is idle less than
104 # this percentage, then the laptop won't suspend, on the
105 # assumption that the system is doing something "important" for the
106 # user. Set this to 0 to to allow the system to sleep no matter
107 # how busy the CPU.
108 #
109 # "config_SLEEP_WHEN_LID_CLOSED" causes the laptop to go to sleep
110 # when closed, and is usually desirable. One might want to turn this
111 # off if using the laptop as a server, or perhaps when running an
112 # application which needs to keep running while the laptop is
113 # transported. The screen will be turned off in any case, of course.
114 #
115 # "config_KEYPRESS_WAKE_FROM_BLANK_IDLE_SLEEP" says that if the screen
116 # is blank and the laptop has "idle suspended" (i.e., gone to sleep
117 # due to inactivity), that a keypress (or touchpad gesture) will wake
118 # the laptop. Otherwise this blank-sleeping condition (which is
119 # visually the same as a power button-induced sleep) will require the
120 # power button to wake it. If you like having the keyboard completely
121 # disabled during any "dark" sleep, then set this to "no". If the
122 # power button is used to put the laptop to sleep, this setting will
123 # have no effect.
124 #
125 # "config_WAKE_ON_WLAN" -- determines whether a packet destined for
126 # your laptop will wake it up from idle suspend, in much the same
127 # way that a keystroke or mouse movement will wake it up. see
128 # also config_WLAN_WAKE_FROM_BLANK_IDLE_SLEEP.
129 #
130 # "config_WLAN_WAKE_FROM_BLANK_IDLE_SLEEP" controls whether the
131 # config_WAKE_ON_WLAN setting also applies once the screen has
132 # blanked. (The "blanked" state is the final idle state, and usually
133 # means the laptop simply isn't being used. Laptops being access
134 # remotely, however, should probably have this set to "yes".) This
135 # setting is conditional on enabling keypress wakeups with
136 # config_KEYPRESS_E_FROM_BLANK_IDLE_SLEEP. If the power button is
137 # used to put the laptop to sleep, this setting will have no effect.
138 #
139 #
140 #####
141 # Power logging
142 #
143 # powerd can optionally perform detailed power usage logging. powerd
144 # must be restarted for any changes to the following config_PWRLOG_*
145 # settings to take effect:
146 #
147 # "config_PWRLOG_INTERVAL" determines whether, and how often, logging
148 # will be performed. A value of less than 30 seconds will disable
149 # power logging. Anything else gives the approximate maximum interval
150 # between logged samples. 5 minutes (i.e., 300 seconds) is a useful
151 # setting. (The value is approximate, because the actual logging
152 # depends on the granularity of the timer events received from
153 # olpc-switchd.)
154 #
155 # "config_PWRLOG_DIR" is the final destination for the power logs.
156 # Logs are initially written to /var/log, and copied every 30 minutes
157 # to the final directory destination.
158 #
159 # "config_PWRLOG_LOGSIZE" is the maximum size, in Kbytes, of any single
160 # log file. When a log file crosses this threshold, it will be
161 # copied to $config_PWRLOG_DIR, removed, and a new log started.
162 #
163 # "config_PWRLOG_LOGDIRSIZE" is the maximum total space alloted for
164 # $config_PWRLOG_DIR. When the directory grows too large, the oldest
165 # files are removed until the size is below this threshold.
166 #
167 #
168 ######
169 #
170 # Inhibiting sleep
171 #
172 # Idle dim/blank/sleep can be inhibited externally by three separate
173 # means:
174 #
175 # 1) A file may be created in
176 # /var/run/powerd-inhibit-suspend/
177 # The file must be named after the PID of the process doing the
178 # inhibiting (and may be empty). Stale inhibit files (i.e.,
179 # their owner pid no longer exists) will be removed the next time
180 # the laptop might sleep. To manually inhibit dim/blank/sleep one
181 # can simply create a file named after a long-running process:
182 # e.g., "touch /var/run/powerd-inhibit-suspend/1". (Such a file
183 # will need to be manually removed, of course.) To assist with the
184 # common case of inhibiting suspend while a given program is
185 # running, the "olpc-nosleep" wrapper is provided. e.g.,
186 # $ olpc-nosleep wget http://veryslow.downloads.com/bigfile
187 #
188 # The above pid-based flags aren't persistent. To inhibit suspend
189 # in a persistent way (i.e., across reboots), create the file:
190 # /etc/powerd/flags/inhibit-suspend
191 # (This is the mechanism used by the Sugar control panel UI.)
192 #
193 # 2) The modification time of the file
194 # /var/run/powerd-inhibit-suspend/.fake_activity
195 # will be checked before any sleep occurs, and will be compared to
196 # the time of the last "real" user activity. If it is newer, the
197 # dim/blank/sleep will be skipped. So a program wishing to indicate
198 # that it is "active" can simply touch this file periodically to
199 # keep it up-to-date. As a convenience, the command:
200 # powerd-config -a
201 # will do this touch. For example, to help keep the laptop alive while
202 # an ssh serial console session is in use, add:
203 # export PROMPT_COMMAND='powerd-config -a'
204 # to your .bash_profile. This will cause the file to be touched
205 # at every shell prompt.
206 #
207 # 3) Finally, powerd will try and keep the laptop awake based on
208 # various system conditions: CPU utilizations, network activity, VT
209 # console usage, camera and audio usage, and usb device presence.
210 # Network and CPU activity are monitored for 5 seconds before
211 # sleep should occur. These conditions are all checked from the
212 # "laptop_busy" function, so look there for details.
213 #
214 # For USB device presence, if the file /etc/powerd/flags/usb-inhibits
215 # is present, it will be consulted for matches against USB device
216 # id (as hex vend:prod format), just the vendor (as 4 hex
217 # characters) or USB device class (as either two byte hex or
218 # kernel-reported string. (i.e., "03" or "hid" will both work to
219 # match all HID devices, while "0603:00f2" might match a specific
220 # keyboard, and "0603" will match all devices by that vendor.
221 #
222 # 4) Idle-suspend will be unconditionally inhibited for 60 seconds
223 # after a wakeup from a "dark" (lid or power button) sleep. In
224 # these sleeps, the wlan is powered down, and it sometimes takes
225 # some time to reassociate after wakeup. We don't really want to
226 # sleep while the user is waiting for that association to happen.
227 #
228 #
229 # Post-resume scripts can be put in /etc/powerd/postresume.d -- the
230 # scripts will be run in lexicographic order. The scripts are run
231 # detached from powerd, so they won't impede its operation -- however,
232 # they should be kept as short as possible.
233 #
234 #
235 ######
236 #
237 # Background discussion:
238 #
239 # The inputs that contribute to power management are:
240 # power button
241 # ebook
242 # lid
243 # AC plugged/unplugged
244 # battery capacity (numeric)
245 # Changes on these inputs cause input events on evdev devices
246 # /dev/input/eventN. powerd relies on the companion program
247 # "olpc-switchd" to report these events via the /var/run/powerevents
248 # fifo it creates for the purpose. The state of these conditions can
249 # also be read from nodes in /sys. (Some are only available as events
250 # on XO-1.)
251 #
252 # - Wakeups:
253 # rtc wakeup
254 # ac_power
255 # battery_error
256 # battery_soc (i.e., "state of charge" --> capacity)
257 # battery_state
258 # ebook_mode_change
259 # ps2event
260 # wlan
261 # lid
262 # When the system wakes from sleep, /sys/power/wakeup-source
263 # reports the cause.
264 #
265 # - User activity/idleness:
266 # powerd expects user activity and user idle events to be delivered via
267 # the olpc-kbdshim daemon. The possible kbdshim events are:
268 # useractivity
269 # useridle1
270 # useridle2
271 # useridle3
272 #
273 # These events may be used to dim the screen, blank the screen, and/or
274 # put the CPU to sleep, in any order.
275 #
276 # - Other system activity: cpu load, network load, etc.
277 #
278 #
279 ######
280 #
281 # Implementation notes:
282 #
283 # - System transitions
284 #
285 # The system can be configured to go through the following 6
286 # transition sequences:
287 #
288 # #1 dim sleep {blank} {shutdown}
289 # #2 dim blank sleep {shutdown}
290 # #3 blank [dim] sleep {shutdown}
291 # #4 blank sleep {[dim]} {shutdown}
292 # #5 sleep {blank} {[dim]} {shutdown}
293 # #6 sleep {dim} {blank} {shutdown}
294 #
295 # {xxx} -- any transition that follows "sleep" is handled in
296 # the snooze() function, and not by the useridleN events.
297 # That's what the {braces} mean: "handled by snooze".
298 # [dim] -- this state is a no-op, since dimming after blanking
299 # doesn't make sense.
300 #
301 # Transitions up through and including "sleep" are driven by the
302 # useridle1,2,3 events, and handled by the action routines
303 # (dim_action(), blank_action(), and sleep_action()). These are
304 # relatively straightforward. Once the system is sleeping (using
305 # rtcwake), the transitions are handled within the snooze()
306 # function.
307 #
308 # As a result of the no-op "[dim]" transition, the
309 # implementation of snooze() for sequences #1 and #5 is
310 # identical, as is the implementation for #2, #3 and #4. So
311 # snooze() only really has three separate cases to deal with,
312 # represented by sequences #2, #1, and #6. These cases are:
313 # - dim then blank then shutdown
314 # - blank then shutdown
315 # - shutdown
316 #
317 #
318 # - X11
319 #
320 # Note that X11 DPMS is neither consulted nor modified, and it
321 # may still blank the display after some period of inactivity.
322 # (This won't happen, of course, unless the DPMS "standby" time
323 # is shorter than powerd's "sleep" time.) The effect of DPMS
324 # doing this will result in confusion, since when DPMS blanks the
325 # screen, powerd can't tell that it's happened. I.e., a laptop
326 # with a screen blanked by DPMS may behave differently than one
327 # blanked by powerd. DPMS should be disabled, either in
328 # xorg.conf, or with "xset -dpms".
329 #
330 #
331 # - POSIX shell
332 #
333 # The intention is that powerd be runnable with most any modern
334 # shell. No bash-specific features were used, unless by accident.
335 # One possible exception: in order to implement a non-blocking
336 # read of the event fifo, I had to use "read -t 1" (in
337 # event_fifo_lookahead()). Most newer shells implement this, but
338 # it's not POSIX. (The Debian "dash" shell does not, the "ash"
339 # shell in busybox works fine.) If run with a shell that doesn't
340 # support "-t", the only failure will be the possibility of lost
341 # wakeups: hitting a key just as the system wakes just to dim
342 # the screen may not prevent the subsequent sleep.
343 #
344 # Another exception is the (optional) inclusion of olpc-pwr-log.sh,
345 # which is heavily dependent on non-POSIX features.
346 #
347 #
348 ######
349 #
350 # Please send commends/suggestions/patches to [email protected].
351 #
352 # -----------------------------------------------
353 #
354 # Copyright (C) 2009,2010, Paul G Fox
355 #
356 # This program is free software; you can redistribute it and/or
357 # modify it under the terms of the GNU General Public License as
358 # published by the Free Software Foundation; either version 2 of
359 # the License, or (at your option) any later version.
360 #
361 # This program is distributed in the hope that it will be
362 # useful, but WITHOUT ANY WARRANTY; without even the implied
363 # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
364 # PURPOSE. See the GNU General Public License for more details.
365 #
366 # You should have received a copy of the GNU General Public
367 # License along with this program; if not, write to the Free
368 # Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139,
369 # USA.
370 #
371
372 XO=;
373 CONFIGDIR=/etc/powerd
374
375 VERSIONFILE=$CONFIGDIR/version
376 CONFIGFILE=$CONFIGDIR/powerd.conf
377 CONFIGFLAGS=$CONFIGDIR/flags
378
379 RUNPARTSDIR=$CONFIGDIR/postresume.d
380
381 # logging only used for debug, currently
382 LOGFILE=/var/log/powerd.trace
383 # LOGFILE=/home/olpc/log/powerd.trace
384
385 INHIBITDIR=/var/run/powerd-inhibit-suspend
386 INHIBIT_BY_TOUCH=$INHIBITDIR/.fake_activity
387
388 CONFIRMSPLASH=$CONFIGDIR/pleaseconfirm.pgm
389 SHUTSPLASH=$CONFIGDIR/shuttingdown.pgm
390 BATTSHUTSPLASH=$CONFIGDIR/shuttingdown.pgm
391
392 EVENTFIFO=/var/run/powerevents
393
394 # note re: battery capacity:
395 # i'd use /sys/.../capacity_level here, but we won't get
396 # "critical" -- the EC and kernel can only currently indicate
397 # "low", "normal", or "full", and "low" lasts for another half
398 # hour -- way too early for shutdown. using /sys/.../capacity
399 # (which gives a percentage), and cutting off at 5% means we're
400 # shutting down with (on my machine and battery under 2 minutes
401 # of runtime left. the right answer is to use battery voltage --
402 # however, we can't get woken for that. so we fudge, and use
403 # a combination.
404 BATTERY_INFO=/sys/class/power_supply/olpc-battery
405 CAPACITY=$BATTERY_INFO/capacity # percentage
406 MICROVOLTS=$BATTERY_INFO/voltage_avg # microvolts
407
408 if [ -d /sys/class/power_supply/olpc-ac ]
409 then
410 AC_ONLINE=/sys/class/power_supply/olpc-ac/online # 1/0
411 elif [ -d /sys/class/power_supply/AC ]
412 then
413 AC_ONLINE=/sys/class/power_supply/AC/online # 1/0
414 else
415 AC_ONLINE=;
416 fi
417 BRIGHTNESS=/sys/class/backlight/dcon-bl/brightness # 0-15
418 MONO_MODE=/sys/devices/platform/dcon/output
419
420 WLAN_ENABLED=/sys/power/wlan-enabled # XO-1 only
421
422 WAKEUP_EVENTS=/sys/power/wakeup_events # directory of mask bits
423 WAKEUP_SOURCE=/sys/power/wakeup-source # contains name of last wakeup source.
424
425 if [ -e /sys/power/wake-on-close ]
426 then
427 WAKE_ON_CLOSE=/sys/power/wake-on-close
428 else
429 WAKE_ON_CLOSE=;
430 fi
431
432 if [ -e /proc/acpi/button/lid/LID/state ]
433 then
434 LID_STATE=/proc/acpi/button/lid/LID/state
435 else
436 LID_STATE=;
437 fi
438
439 if [ -e /proc/acpi/olpc-switch/ebook/EBK/state ]
440 then
441 EBOOK_STATE=/proc/acpi/olpc-switch/ebook/EBK/state
442 else
443 EBOOK_STATE=;
444 fi
445
446 DCON_FREEZE=/sys/devices/platform/dcon/freeze
447 DCON_SLEEP=/sys/class/backlight/dcon-bl/device/sleep
448
449
450 # experimental driver features -- not present in currently
451 # distributed kernels.
452 TPAD_RECAL=/sys/devices/platform/i8042/serio1/recalibrate
453
454 # command fifo for olpc-kbdshim
455 USER_ACTIVITY_CMDS=/var/run/olpc-kbdshim_command
456
457
458 # we signal ourselves early, so we have time to see if it's
459 # really okay to sleep. units are seconds.
460 BUSYCHECK=5
461
462
463 set -u
464
465 log()
466 {
467 logger -t powerd -p daemon.info -- "$@"
468 echo : @ $(date +'%F %T') $@ >&2
469 }
470
471 powerd_version="version unknown"
472 test -e $VERSIONFILE && . $VERSIONFILE
473
474 tracing=;
475 # the trace file will collect stderr, regardless of whether tracing is really on
476 exec 2>>$LOGFILE
477 exec 1>&2 # capture stdout, too. (prevents console spew)
478
479 log powerd $powerd_version startup at $(date)
480
481 set_tracing()
482 {
483 case $1 in
484 on)
485 set -x
486 tracing=1
487 : @ tracing begun, $powerd_version
488 ;;
489 off)
490 if [ "$tracing" ]
491 then
492 : @ tracing stopped
493 set +x
494 tracing=;
495 fi
496 ;;
497 esac
498 }
499
500 # uncomment for full tracing. (or, use "powerd-control =tracing-on"
501 # to enable at runtime.)
502 # set_tracing on
503
504 yes_or_true()
505 {
506 case $1 in
507 1|[yYtT]*) return 0 ;;
508 *) return 1 ;;
509 esac
510 }
511
512 # use $SECONDS for timing when possible
513 if [ "${SECONDS:-}" ]
514 then
515 SECONDS=$(date +%s)
516 seconds()
517 {
518 echo $SECONDS
519 }
520 else
521 seconds()
522 {
523 date +%s
524 }
525 fi
526
527 if [ -e /dev/fb ]
528 then
529 framebuffer=/dev/fb
530 elif [ -e /dev/fb0 ]
531 then
532 framebuffer=/dev/fb0
533 else
534 log "no framebuffer?"
535 fi
536
537
538 splash()
539 {
540 case $1 in
541 confirm)
542 args="$CONFIRMSPLASH $SHUTSPLASH"
543 ;;
544 critical)
545 args="$BATTSHUTSPLASH"
546 ;;
547 shutdown)
548 args="$SHUTSPLASH"
549 ;;
550 esac
551
552 pnmto565fb -d -f $framebuffer -s 9999999 $args &
553 splashpid=$!
554 }
555
556 nextsplash()
557 {
558 # kill -USR1 will cause pnmto565fb to display next image (stays alive)
559 test "${splashpid:-}" && kill -USR1 $splashpid
560 }
561
562 unsplash()
563 {
564 # kill -INT will cause pnmto565fb to restore original VT
565 test "${splashpid:-}" && kill -INT $splashpid
566 splashpid=;
567 }
568
569 leavesplash()
570 {
571 # kill -TERM will cause pnmto565fb to just die
572 test "${splashpid:-}" && kill -TERM $splashpid
573 splashpid=;
574 }
575
576 do_shutdown()
577 {
578 log shutting down due to $*
579 leavesplash # kill the splasher (leaving splash visible)
580 sleep .05s
581 /sbin/poweroff &
582 sleep 9999999
583 }
584
585 #
586 # both cpu_busy and network_busy integrated below, since they
587 # both need a time span over which to work.
588 #cpu_busy()
589 #{
590 # # pull the cpu idle percentage (over one second) out of the
591 # # 15th field of vmstat output. (this metric borrowed from ohmd.)
592 # field='\([[:space:]]\+[[:digit:]]\+\)'
593 # idle=$(vmstat 1 2 | sed -n "\$s/$field\{15\}.*/\1/p")
594 #
595 # # ensure numeric. if failure, assume we're not busy.
596 # test "$idle" && test $idle -eq $idle >/dev/null || return 1
597 #
598 # test $idle -lt $config_CPU_IDLE_LIMIT && : @ cpu busy && return 0
599 #
600 # return 1
601 #}
602 #
603 #network_busy()
604 #{
605 # # TBD
606 # return 1
607 #}
608
609
610 cpu_or_network_busy()
611 {
612 # initial cpu stats -- search for /proc/stat in "man 5 proc"
613 procstat1=( $(< /proc/stat) )
614 jiffies1=$(( procstat1[1] + procstat1[2] + procstat1[3] + procstat1[4] ))
615 idlejifs1=${procstat1[4]}
616
617 # take initial network stats
618 if [ "$monitor_network_activity" ]
619 then
620 netactivity=$(netactivity_snapshot)
621 fi
622
623 # wait a while ($BUSYCHECK, or 5 seconds, currently), and
624 # check for events while doing so. we can wait this 5
625 # seconds because we arranged to be signalled 5 seconds
626 # before actually wanting to suspend.
627 start=$(seconds)
628 while :
629 do
630 event_fifo_lookahead soft && return 0
631 test $(($(seconds) - start)) -ge $BUSYCHECK && break
632 done
633
634 # second cpu stats
635 procstat2=( $(< /proc/stat) )
636 jiffies2=$(( procstat2[1] + procstat2[2] + procstat2[3] + procstat2[4] ))
637 idlejifs2=${procstat2[4]}
638
639 # what fraction of total elapsed jiffies were idle jiffies?
640 idle=$(( (100 * ( idlejifs2 - idlejifs1 ) / ( jiffies2 - jiffies1 ) ) ))
641 if [ $idle -lt $config_CPU_IDLE_LIMIT ]
642 then
643 : @ cpu busy
644 return 0
645 fi
646
647 if [ "$monitor_network_activity" ]
648 then
649 # second network stats -- any network activity?
650 newnetactivity=$(netactivity_snapshot)
651 if [ "$newnetactivity" != "$netactivity" ]
652 then
653 : @ network busy
654 return 0
655 fi
656 fi
657
658 return 1
659 }
660
661
662 # unused for now, because too many sound apps leave the
663 # device open: the tamtams, record (after playing), browse
664 # and firefox (after playing)
665 #audio_busy()
666 #{
667 # grep -q RUNNING /proc/asound/card0/pcm0?/sub0/status && : @ audio busy
668 #}
669
670 camera_busy()
671 {
672 grep -q via-dma /proc/interrupts && : @ camera busy
673 }
674
675
676 # if using both of the above, combine them into a single grep:
677 #audio_or_camera_busy()
678 #{
679 # egrep -q 'RUNNING|via-dma' \
680 # /proc/asound/card0/pcm0?/sub0/status /proc/interrupts && \
681 # : @ audio or camera busy
682 #}
683
684
685 # see if there's been activity during the recent idle period.
686 # checks vty devices and our special touchfile, with one stat.
687 touchfiles="/dev/tty1 /dev/tty2 $INHIBIT_BY_TOUCH"
688
689 filetimes_busy()
690 {
691 timer=$1
692 now=$(seconds)
693 for touched in $(stat -c '%Y' $touchfiles 2>/dev/null )
694 do
695 test $(( touched > now - timer )) = 1 && \
696 : @ touchfile busy && return 0
697 done
698 return 1
699 }
700
701 inhibit_files_present()
702 {
703
704 # check the persistent inhibit flag first
705 test -e $CONFIGFLAGS/inhibit-suspend && return 0
706
707 inhibit_ret=1
708
709 # check for pid files. remove any non-pid files
710 for f in $(ls $INHIBITDIR )
711 do
712 if kill -0 $f 2>/dev/null
713 then
714 inhibit_ret=0
715 break
716 fi
717 rm -f $INHIBITDIR/$f
718 done
719
720 return $inhibit_ret
721 }
722
723 create_inhibit_dir()
724 {
725 # most inhibit-like flags go in /var/run, and aren't persistent
726 mkdir -p $INHIBITDIR
727 chmod a+rwt $INHIBITDIR
728 touch $INHIBIT_BY_TOUCH
729 chmod a+w $INHIBIT_BY_TOUCH
730
731 # some might need to be persistent (mainly for the sake of UI
732 # simplicity, where parsing and writing the config file would
733 # be overkill).
734 mkdir -p $CONFIGFLAGS
735 chmod a+rw $CONFIGFLAGS
736 }
737
738 # checking inhibit files is much faster then checking laptop
739 # "busyness", so it's separated out.
740 inhibited_by_files()
741 {
742 inhibit_files_present || filetimes_busy $t1
743 }
744
745 usb_inhibit()
746 {
747
748 usbpats=/var/run/powerd-usbpatterns
749 usbconf=$CONFIGFLAGS/usb-inhibits
750
751 test -e $usbconf || return 1
752
753 # convert user "strings" to "^strings$", only when user config changes.
754 if [ ! -e $usbpats -o $usbconf -nt $usbpats ]
755 then
756 sed -e 's/^/\^/' -e 's/$/\$/' $usbconf > $usbpats
757 fi
758
759 # pull out all USB class, vendor, and vendor:id values, and
760 # make them available for comparison, one per line, against
761 # the user-supplied strings.
762 gotusb=$(sed -n -e 's/^.*Cls=\([[:xdigit:]]\{2\}\)(\([^ )]\+\).*/\1\
763 \2/p' \
764 -e 's/^.*Vendor=\([[:xdigit:]]\{4\}\).*ProdID=\([[:xdigit:]]\{4\}\).*/\1:\2\
765 \1/p' \
766 /proc/bus/usb/devices |
767 grep -if $usbpats )
768
769 # implicit return value
770 test "$gotusb" && : @ got usb $gotusb
771 }
772
773
774 laptop_busy()
775 {
776 usb_inhibit || cpu_or_network_busy || camera_busy
777 }
778
779 if [ -e $TPAD_RECAL ]
780 then
781 touchpad_recalibrate()
782 {
783 # take advantage of lid open events, which indicate that a)
784 # someone is quite unlikely to be using the touchpad, and b)
785 # the physical environment may have changed since last use,
786 # to force a recalibration:
787 echo 1 > $TPAD_RECAL
788 }
789 else
790 touchpad_recalibrate()
791 {
792 :
793 }
794 fi
795
796 read_wlan_power()
797 {
798 local x
799 read x < $WLAN_ENABLED
800 eval $1=\"$x\"
801 }
802
803 set_wlan_power()
804 {
805 # only on XO-1. (no echo, but that's okay with the callers)
806 test "$XO" != 1 && return
807
808 # very important not to do extra writes to wlan-enabled -- the
809 # node is sort of misnamed. writing a 0 puts the wlan into reset.
810 # writing a 1 puts it into reset, but immediately releases the
811 # reset. so a reset is always involved, even if brief.
812 read_wlan_power w
813 if [ "$w" != "$1" ]
814 then
815 echo $1 > $WLAN_ENABLED
816 fi
817 echo $w
818 }
819
820 set_wake_on_wlan()
821 {
822 # note: ethtool settings aren't remembered after a resume,
823 # i.e., they're essentially a "one-shot" configuration. the
824 # good news is that this means we never have to clear
825 # wake-on-lan settings.
826
827 #ethtool -s eth0 wol ua # we don't support wake-on-arp (yet?)
828 case $1 in
829 yes) ethtool -s eth0 wol u ;;
830 *) ethtool -s eth0 wol d ;;
831 esac
832 }
833
834 wlan_associated()
835 {
836 # do some crude "editor logic" on the iwconfig output.
837 # produce a string that's empty if we're associated, i.e.,
838 # not empty if we're unassociated: try and produce output if
839 # the radio is off, or if it says "unassociated" or
840 # "Not-Associated", but scratch that second part if we're in
841 # ad-hoc mode.
842
843 unassociated=$(
844 iwconfig eth0 |
845 sed -n \
846 -e '/Mode:Ad-Hoc/d' \
847 -e '/radio off\|Tx-Power=off\|[ut][n-][aA]ssociated/p'
848 )
849
850 test ! "$unassociated" # set return value
851 }
852
853 runparts()
854 {
855 rc_action=$1
856 test $rc_action = "resume" || return
857
858 rc_dir=$RUNPARTSDIR
859 test -d $rc_dir || return
860
861 cd $rc_dir
862
863 for s in *[^~]
864 do
865 case $s in
866 '*[^~]') return;; # s is the literal pattern
867 esac
868
869 if [ -x $s ]; then
870 echo "Running $s $rc_action" >&2
871 ./$s $rc_action || echo "*** $s failed"
872 elif [ -f $s ]; then
873 echo "Skipping $s (disabled, not executable)" >&2
874 else
875 if [ -L $s ]; then
876 echo "Removing dangling symlink $s" >&2
877 rm $s
878 else
879 echo "Skipping $s (not an executable file)" >&2
880 fi
881 fi
882 done
883
884 }
885
886 set_acpi_wakeupevents()
887 {
888 # no acpi events on XO-1
889 test "$XO" = 1 && return
890
891 # enable --> enabled, disable --> disabled
892 skip=${2}d
893
894 # fetch the current contents of /proc/acpi/wakeup. if
895 # we're asked to disable FOO, delete its line if it's
896 # already disabled, else print just FOO if it's enabled,
897 # (and vice versa) and write that back to the file.
898 sed -n -e '/^Device\>/d' \
899 -e "/^$1[[:space:]].*\<$skip\>/d" \
900 -e "s/^\($1\)[[:space:]].*/\1/p" \
901 /proc/acpi/wakeup >/proc/acpi/wakeup
902 }
903
904 set_wakeupevents()
905 {
906 # this routine was simpler when only the XO-1 was around -- all
907 # it dealt with was the nodes in /sys/power/wakeup_events.
908 # note that /sys/power/wakeup_events isn't just masking wakeups --
909 # it's masking SCI events, which also provide battery and EC input
910 # events (and ebook on XO-1).
911 case $1 in
912 all) set_acpi_wakeupevents EBK enable
913 test "$WAKE_ON_CLOSE" && echo 1 > $WAKE_ON_CLOSE
914 echo 1 >$WAKEUP_EVENTS/all
915 ;;
916 all_sci) # we want to unmask all SCI events at the EC when
917 # we waken after having masked them, but we don't
918 # need to massage the acpi settings, etc. i.e.,
919 # this is used when we awake, not when we go to sleep.
920 echo 1 >$WAKEUP_EVENTS/all
921 ;;
922 none) set_acpi_wakeupevents EBK disable
923 test "$WAKE_ON_CLOSE" && echo 0 > $WAKE_ON_CLOSE
924 echo 0 >$WAKEUP_EVENTS/all
925 ;;
926 ac) echo 1 >$WAKEUP_EVENTS/ac_power
927 ;;
928 battery) echo 1 >$WAKEUP_EVENTS/battery_soc
929 echo 1 >$WAKEUP_EVENTS/battery_state
930 echo 1 >$WAKEUP_EVENTS/battery_error
931 # next one not always present
932 echo 1 >$WAKEUP_EVENTS/battery_critical 2>&1
933 ;;
934 battery_critical)
935 echo 1 >$WAKEUP_EVENTS/battery_critical 2>&1
936 ;;
937 esac
938 }
939
940 read_wakeupsource()
941 {
942 local x
943 read x < $WAKEUP_SOURCE
944 eval $1=\"$x\"
945 }
946
947 event_fifo_lookahead()
948 {
949 local type
950 type=$1
951
952 # in some cases in snooze() we wake just to perform
953 # a short action or status check, and then we sleep again
954 # immediately. if we don't check the event fifo, we may
955 # well miss an event that would normally wake us (or
956 # keep us from sleeping). there's no way to close this
957 # race completely, but this is way better than nothing.
958
959 while read -t 1 s_event s_tstamp s_arg2 s_arg3 s_more
960 do
961 # if the event we read is "interesting enough" that
962 # it would have woken us if it had arrived just a little
963 # later, break out. otherwise discard it.
964 : @ s_event-type is $s_event-$type
965 case $s_event-$type in
966 powerbutton-*|lidopen-hard|lid*-soft|\
967 ebook*-soft|ac-*-soft|useractive-soft)
968 if [ ! "$s_tstamp" ] || \
969 [ "$s_tstamp" -ge "$eventcutoff" ]
970 then
971 return 0
972 fi
973 ;;
974 esac
975 done <&6 # from the fifo
976
977 return 1
978
979 }
980
981 snooze()
982 {
983
984 local shutdowntime dimtime blanktime orig_rtctime rtctime
985 local until sleep_type wakeupsource prev_wlan_power sleep_started
986
987 prev_wlan_power=;
988
989 runparts suspend
990
991 # we only use rtc alarms to either a) turn of the screen when
992 # we've been sleeping for a while, or b) shutdown after we've been
993 # sleeping for a while. if we do a), we'll do b) next.
994 until=$1 # "until_dim", "until_blank", or "until_shutdown"
995 sleep_type=$keypress_sleep;
996 shutdowntime=${2:-}
997 case $until in
998 until_dim)
999 dimtime=${3:-}
1000 blanktime=${4:-}
1001 orig_rtctime=$dimtime
1002 ;;
1003 until_blank)
1004 blanktime=${3:-}
1005 orig_rtctime=$blanktime
1006 ;;
1007 until_shutdown)
1008 orig_rtctime=$shutdowntime
1009 sleep_type=$3 # "hard" or "soft", i.e., can kbd/tpad wake us up
1010 ;;
1011 esac
1012
1013 rtctime=$orig_rtctime
1014
1015 while :
1016 do
1017
1018 pwrlog_take_reading suspend
1019
1020 : @ until-sleep_type is $until-$sleep_type
1021
1022 case $until-$sleep_type in
1023 until_shutdown-hard)
1024 # if we're waiting for a shutdown, then this is a
1025 # pretty sound sleep. only let the lid wake us up
1026 # (we can't actually prevent that), as well as battery
1027 # events if we're close to shutdown levels.
1028
1029 set_wakeupevents none
1030 # note: it's tempting to allow AC wakeups here, but in
1031 # practice a) there's no advantage -- we won't do anything
1032 # differently if we wake and then go back to sleep, and b) it's
1033 # tricky, when woken for one reason, for which we might
1034 # simply sleep again (i.e., AC), to know that we shouldn't
1035 # also have awoken for another reason (i.e., LID) without
1036 # draining the event queue. far simpler to not take AC
1037 # and LID wakeups at the same time.
1038
1039 # regardless, take battery_critical events
1040 set_wakeupevents battery_critical
1041
1042 # obviously if we ignore AC wakeups, we won't do the following
1043 # if we're subsequently unplugged. hopefully the critical
1044 # wakeup above will save the day.
1045 if [ "$ac" != "online" ]
1046 then
1047 read_battery
1048 if [ "$battery_capacity" -le 20 ]
1049 then
1050 set_wakeupevents battery
1051 fi
1052 fi
1053 # ohmd uses this:
1054 # nm-tool | grep msh0 -A4 | grep Active | awk '{print $2}'\"
1055 # to determine whether mesh is active before turning off wireless.
1056 # i guess we could do the same.
1057 if [ ! "$prev_wlan_power" ] && \
1058 ! yes_or_true "$config_MESH_DURING_SUSPEND"
1059 then
1060 prev_wlan_power=$(set_wlan_power 0)
1061 fi
1062
1063 if [ "$wake_on_wlan" ]
1064 then
1065 set_wake_on_wlan no
1066 fi
1067 ;;
1068 *)
1069 # otherwise we want most anything to wake us.
1070 sleep_type=soft
1071 set_wakeupevents all
1072
1073 if [ "$wake_on_wlan" ]
1074 then
1075 # wake on wlan if we're only waiting for dim or
1076 # blank. else we're blank, so w-o-l if we've
1077 # been asked to and we're currently associated with
1078 # something.
1079 if [ "$until" != until_shutdown ] || \
1080 ( yes_or_true $config_WLAN_WAKE_FROM_BLANK_IDLE_SLEEP && \
1081 wlan_associated )
1082 then
1083 set_wake_on_wlan yes
1084 fi
1085 fi
1086 ;;
1087 esac
1088
1089 reset_idlecounters
1090 event_fifo_lookahead $sleep_type && break
1091
1092 if [ "$sleep_type" = soft ]
1093 then
1094 inhibited_by_files && break
1095 fi
1096
1097 sleep_started=$(seconds)
1098
1099 # this is it. here's where we suspend or sleep.
1100 rtcwake -m mem -a -s $rtctime >/dev/null
1101
1102 set_wakeupevents all_sci
1103
1104 # prepare for the default case of simply re-sleeping for
1105 # the remaining time. may be overridden. note that this
1106 # also protects against a) sleeping for less than a second,
1107 # which is buggy in the kernel, and b) trying to sleep for
1108 # 0 seconds, which might happen if we wake up due to an AC
1109 # event at just the same time that rtcwake should have expired.
1110 lastwakeup=$(seconds)
1111 rtctime=$(( rtctime - ( lastwakeup - sleep_started ) ))
1112 rtctime=$(( (rtctime <= 1) ? 2 : rtctime ))
1113
1114 # we want to toss extra events that happened long ago, as
1115 # we were sleeping, but not those that happened as we
1116 # were waking up. choose the middle of our nap as the
1117 # cutoff:
1118 eventcutoff=$(( ( lastwakeup + sleep_started ) / 2 ))
1119
1120 if [ "$XO" = 1.5 ]
1121 then
1122 # for some reason our ebook and ec interrupts get disabled
1123 # across a suspend/resume cycle
1124 echo enable >/sys/firmware/acpi/interrupts/gpe01
1125 echo enable >/sys/firmware/acpi/interrupts/gpe0A
1126 fi
1127
1128 power_check
1129
1130 read_wakeupsource wakeupsource
1131
1132 # compress out spaces
1133 set -- $wakeupsource
1134 wakeupsource=$1${2:-}${3:-}
1135
1136 : @ got wakeup $wakeupsource @ $lastwakeup, \
1137 slept $(( lastwakeup - sleep_started ))
1138
1139 pwrlog_take_reading resume-$wakeupsource
1140
1141 case $wakeupsource in
1142 "powerbutton")
1143 : @ power button during $until
1144 case $until in
1145 until_shutdown)
1146 # this takes care of the "screen blanked but not sleeping"
1147 # case. we only want the button to give the splash menu
1148 # when the screen was lit when it was pushed.
1149 selfinject fake_useractive $lastwakeup "$wakeupsource"
1150 holdoff_start=$lastwakeup
1151 ;;
1152 *)
1153 # waiting until_dim or until_blank, so screen is still on
1154 selfinject fake_powerbutton $lastwakeup "$wakeupsource"
1155 ;;
1156 esac
1157 break
1158 ;;
1159
1160 "wlanpacket")
1161 if yes_or_true "$config_WAKE_ON_WLAN"
1162 then
1163 selfinject fake_useractive $lastwakeup "$wakeupsource"
1164 break
1165 fi
1166 ;;
1167
1168 "rtcalarm")
1169 : @ rtcalarm during $until
1170 case $until in
1171 until_dim)
1172 # we don't get woken on lid close, so check here.
1173 # if we can't tell, assume we're still open
1174 backlight dim
1175 until=until_blank
1176 orig_rtctime=$blanktime
1177 rtctime=$blanktime
1178 ;;
1179
1180 until_blank)
1181 backlight off
1182 until=until_shutdown
1183 orig_rtctime=$shutdowntime
1184 rtctime=$shutdowntime
1185 ;;
1186
1187 until_shutdown)
1188 if [ $rtctime -le 2 ] # time really expired
1189 then
1190 if [ "$ac" != "online" ] || \
1191 yes_or_true "$config_ALLOW_SHUTDOWN_WHEN_PLUGGED"
1192 then
1193 splash shutdown
1194 do_shutdown "idle timeout"
1195 fi
1196 # if we didn't shut down, we'll sleep again for
1197 # the same time as before, before we check again.
1198 rtctime=$orig_rtctime
1199 log found external power, sleeping instead of shutdown
1200 else
1201 # not sure why this happens, but i've seen a
1202 # sleep of 999999999 turn into 69506 seconds
1203 : awoke for shutdown too early, sleeping again
1204 fi
1205 ;;
1206 esac
1207 ;;
1208
1209 "acpower")
1210 : @ acpower during $until
1211 case $until in
1212 until_shutdown)
1213 # we don't wake on AC, so this shouldn't happen. if it did:
1214 # restart the shutdown timer. the choice of sleep time is
1215 # kind of a guess, since we're not tracking how much
1216 # charging we're getting while plugged in. so if we're
1217 # plugged in, we sleep forever, otherwise, we sleep (again)
1218 # for the original time.
1219 if [ "$ac" = "online" ]
1220 then
1221 rtctime=999999999
1222 else
1223 rtctime=$orig_rtctime
1224 fi
1225 ;;
1226
1227 *) # we were waiting for dim or blank, and we got plugged in.
1228 # we'll wake up fully, so we can re-decide whether we
1229 # should really be sleeping aggressively.
1230 break;
1231 ;;
1232 esac
1233 ;;
1234
1235 "lid"|"emptysci")
1236 # assume "empty sci" comes from lid (kernel bug on XO-1).
1237 # in older kernels an rtc wakeup will report "empty
1238 # sci" as well. powerd doesn't support those kernels
1239 # very well.
1240 am_ebook=;
1241 selfinject fake_useractive $lastwakeup "$wakeupsource"
1242 touchpad_recalibrate
1243 holdoff_start=$lastwakeup
1244 break
1245 ;;
1246
1247 battery*) # all we do is check battery level, and sleep again
1248 ;;
1249
1250 *) # "keypress"|"ebook"|"unknown")
1251 selfinject fake_useractive $lastwakeup "$wakeupsource"
1252 break
1253 ;;
1254 esac
1255
1256 # unless we've broken out of the loop, we're going to sleep
1257 # again.
1258
1259 done
1260
1261 test "$prev_wlan_power" && set_wlan_power $prev_wlan_power
1262
1263 reset_idlecounters
1264 runparts resume &
1265 }
1266
1267 set_brightness()
1268 {
1269 echo $1 >$BRIGHTNESS
1270 echo $(( $1 == 0 )) >$MONO_MODE
1271 }
1272
1273 read_brightness()
1274 {
1275 local x
1276 read x < $BRIGHTNESS
1277 eval $1=\"$x\"
1278 }
1279
1280 brightness_ramp()
1281 {
1282 local i
1283 test $1 = $2 && return
1284
1285 # ramp in either direction
1286 incr=1
1287 test $1 -gt $2 && incr=-1
1288
1289 i=$1
1290 while :
1291 do
1292 : $((i += incr))
1293 echo $i >$BRIGHTNESS
1294 test $i = $2 && break
1295 sleep .025s
1296 done
1297 echo $(( $i == 0 )) >$MONO_MODE
1298 }
1299
1300 backlight()
1301 {
1302 case $1 in
1303 restore)
1304 if [ "$dimmed" -a "$savebright" ]
1305 then
1306 # could ramp here, but it wastes time while
1307 # the user is starting to work again
1308 # read_brightness curbright
1309 # if [ $curbright -lt $savebright ]
1310 # then
1311 # brightness_ramp $curbright $savebright
1312 # fi
1313 set_brightness $savebright
1314 dimmed=;
1315 fi
1316 dcon wake
1317 ;;
1318 dim)
1319 if [ ! "${dimmed}" ]
1320 then
1321 read_brightness savebright
1322 if [ $savebright -gt $config_IDLE_DIM_LEVEL ]
1323 then
1324 brightness_ramp $savebright $config_IDLE_DIM_LEVEL
1325 fi
1326 dimmed=true
1327 fi
1328 ;;
1329 off)
1330 # this is all unneeded: sleeping the dcon disables BL.
1331 #if [ ! "${dimmed}" ]
1332 #then
1333 # read_brightness savebright
1334 # dimmed=true
1335 #fi
1336 # set_brightness 0
1337 dcon sleep
1338 ;;
1339
1340 is_off)
1341 local d
1342 read d < $DCON_SLEEP
1343 test $d = 1
1344 return
1345 ;;
1346 esac
1347 }
1348
1349 dcon()
1350 {
1351 case $1 in
1352 freeze) echo 1 > $DCON_FREEZE ;;
1353 thaw) echo 0 > $DCON_FREEZE ;;
1354 is_frozen)
1355 local d
1356 read d < $DCON_FREEZE
1357 test $d = 1
1358 return
1359 ;;
1360 sleep) echo 1 > $DCON_SLEEP ;;
1361 wake) echo 0 > $DCON_SLEEP ;;
1362 esac
1363 }
1364
1365 lid_closed()
1366 {
1367 am_ebook=;
1368 backlight off
1369 if yes_or_true "$config_SLEEP_WHEN_LID_CLOSED"
1370 then
1371 invalidate_powertimer
1372 # hard sleep until it's time to shut down
1373 snooze until_shutdown "$shutdowntimer" hard
1374 fi
1375 }
1376
1377 read_lidstate()
1378 {
1379 local x
1380 read x < $LID_STATE
1381 eval $1=\"$x\"
1382 }
1383
1384 if [ "$LID_STATE" ]
1385 then
1386 lid_check()
1387 {
1388 read_lidstate lidstate
1389 case $lidstate in
1390 *closed) lid_closed ;; # check against "state: closed"
1391 esac
1392 }
1393 else
1394 lid_check()
1395 {
1396 :
1397 }
1398 fi
1399
1400 read_ebookstate()
1401 {
1402 local x
1403 read x < $EBOOK_STATE
1404 eval $1=\"$x\"
1405 }
1406
1407 if [ "$EBOOK_STATE" ]
1408 then
1409 ebook_check()
1410 {
1411 read_ebookstate ebookstate
1412 case $ebookstate in
1413 *closed) am_ebook=true ;; # check against "state: closed"
1414 *) am_ebook=; ;;
1415 esac
1416 }
1417 else
1418 ebook_check()
1419 {
1420 :
1421 }
1422 fi
1423
1424 set_config_defaults()
1425 {
1426 # give all config values defaults, so we'll
1427 # never find them unset
1428 config_BATTERY_TIME_DIM=120
1429 config_BATTERY_TIME_SLEEP=130
1430 config_BATTERY_TIME_BLANK=240
1431 config_EBOOK_TIME_DIM=120
1432 config_EBOOK_TIME_SLEEP=130
1433 config_EBOOK_TIME_BLANK=240
1434 config_PLUGGED_TIME_DIM=120
1435 config_PLUGGED_TIME_SLEEP=130
1436 config_PLUGGED_TIME_BLANK=240
1437
1438 config_IDLE_DIM_LEVEL=5
1439
1440 config_WAKE_ON_WLAN=yes
1441 config_WLAN_WAKE_FROM_BLANK_IDLE_SLEEP=no
1442 config_KEYPRESS_WAKE_FROM_BLANK_IDLE_SLEEP=yes
1443 config_MAX_SLEEP_BEFORE_SHUTDOWN=3600
1444 config_ALLOW_SHUTDOWN_WHEN_PLUGGED=yes
1445 config_SLEEP_WHEN_LID_CLOSED=yes
1446 config_MESH_DURING_SUSPEND=no
1447
1448 config_CONFIRM_SECONDS=7
1449 config_UNFREEZE_SECONDS=1
1450
1451 config_CPU_IDLE_LIMIT=10
1452 config_MONITOR_NETWORK_ACTIVITY=yes
1453
1454 config_PWRLOG_INTERVAL=0
1455 config_PWRLOG_DIR=/home/olpc/power-logs
1456 config_PWRLOG_LOGSIZE=50 # Kbytes
1457 config_PWRLOG_LOGDIRSIZE=1000 # Kbytes
1458 }
1459
1460 read_config()
1461 {
1462 if [ ! -e $CONFIGFILE ]
1463 then
1464 log "cannot find $CONFIGFILE, recreating (empty)"
1465 touch $CONFIGFILE
1466 fi
1467 . $CONFIGFILE
1468
1469 if [ "$config_CONFIRM_SECONDS" -eq 0 ]
1470 then
1471 logger configured so power button will cause immediate sleep
1472 fi
1473
1474 if ! yes_or_true "$config_ALLOW_SHUTDOWN_WHEN_PLUGGED"
1475 then
1476 log configured to never shutdown while plugged in
1477 fi
1478
1479 wake_on_wlan=;
1480 # no wake on wlan on XO-1
1481 if [ "$XO" = 1.5 ] && yes_or_true "$config_WAKE_ON_WLAN"
1482 then
1483 wake_on_wlan=true
1484 log configured to wake on wireless activity
1485 fi
1486
1487 if yes_or_true "$config_KEYPRESS_WAKE_FROM_BLANK_IDLE_SLEEP"
1488 then
1489 keypress_sleep=soft
1490 else
1491 keypress_sleep=hard
1492 fi
1493
1494 }
1495
1496 maybe_battery_shutdown()
1497 {
1498
1499 test "$ac" = "online" && return
1500
1501 case $battery_capacity in
1502 [987654321])
1503 read uvolts < $MICROVOLTS
1504 if [ $uvolts -le 5700000 ] # EC's idea of critical voltage: 5.7V
1505 then
1506 splash critical
1507 sleep 1
1508 do_shutdown "low battery"
1509 fi
1510 ;;
1511 esac
1512
1513 }
1514
1515 read_battery()
1516 {
1517 read battery_capacity < $CAPACITY || battery_capacity=0
1518 }
1519
1520 plugged_in()
1521 {
1522 test "$AC_ONLINE" || return 1
1523
1524 read on_ac < $AC_ONLINE
1525 if [ "$on_ac" = 1 ]
1526 then
1527 ac="online"
1528 return 0
1529 else
1530 ac="offline"
1531 return 1
1532 fi
1533 }
1534
1535 power_check()
1536 {
1537 if ! plugged_in
1538 then
1539 read_battery
1540 maybe_battery_shutdown
1541 fi
1542 }
1543
1544 reset_idlecounters()
1545 {
1546 # if given arguments, remember then for reuse later on.
1547 # (olpc-kbdshim will reset its idle timers when the deadlines are reset)
1548 test "${1:-}" && last_idlecounters="$*"
1549 echo "I $last_idlecounters" >$USER_ACTIVITY_CMDS
1550 }
1551
1552 set_idletimes()
1553 {
1554 local dt st bt nt1 nt2 nt3 d
1555
1556 if [ "$ac" = "online" ]
1557 then
1558 dt=$config_PLUGGED_TIME_DIM
1559 st=$config_PLUGGED_TIME_SLEEP
1560 bt=$config_PLUGGED_TIME_BLANK
1561 else
1562 if [ "$am_ebook" ]
1563 then
1564 dt=$config_EBOOK_TIME_DIM
1565 st=$config_EBOOK_TIME_SLEEP
1566 bt=$config_EBOOK_TIME_BLANK
1567 else
1568 dt=$config_BATTERY_TIME_DIM
1569 st=$config_BATTERY_TIME_SLEEP
1570 bt=$config_BATTERY_TIME_BLANK
1571 fi
1572 fi
1573
1574 # have the values changed?
1575 if [ "$dt $st $bt" = "$last_t_values" ]
1576 then
1577 return 1
1578 fi
1579 last_t_values="$dt $st $bt"
1580
1581 # now validate the configured times...
1582
1583 # force all to be numeric:
1584 test "$dt" -eq "$dt" || \
1585 { logger non-numeric dim time found; dt=120; }
1586 test "$st" -eq "$st" || \
1587 { logger non-numeric sleep time found; st=120; }
1588 test "$bt" -eq "$bt" || \
1589 { logger non-numeric blank time found; bt=120; }
1590
1591 # change '0' to infinite
1592 test "$dt" -eq 0 && \
1593 { logger zero dim time found, now 999999999; dt=999999999; }
1594 test "$st" -eq 0 && \
1595 { logger zero sleep time found, now 999999999; st=999999999; }
1596 test "$bt" -eq 0 && \
1597 { logger zero blank time found, now 999999999; bt=999999999; }
1598
1599 # we want the timers in time order, so we sort them, along
1600 # with their associated action routines and names (for logging).
1601 set -- $( (
1602 echo $dt "dim" dim_action
1603 echo $st "sleep" sleep_action
1604 echo $bt "blank" blank_action
1605 ) | sort -n )
1606
1607 # extract the sorted values
1608 t1=$1; aname1=$2; useridle1_action=$3
1609 t2=$4; aname2=$5; useridle2_action=$6
1610 t3=$7; aname3=$8; useridle3_action=$9
1611
1612 # this is a pain. first, we want the timers to be at least a
1613 # second apart. in addition, if the timer will trigger a
1614 # sleep, we want to have advance it by an extra $BUSYCHECK
1615 # seconds, so we can do a cpu and network activity check
1616 # before actually sleeping. so for that one, the gap needs
1617 # to be 6 (i.e., $BUSYCHECK + 1) seconds.
1618
1619 test "$aname1" = "sleep" && d=$BUSYCHECK || d=0
1620 test $(( (t1 - d) )) -le 0 && : $(( t1 += (1 + d) ))
1621 test "$aname1" = "sleep" && nt1=$(( t1 - d ))
1622
1623 test "$aname2" = "sleep" && d=$BUSYCHECK || d=0
1624 test $(( (t2 - d) )) -le $t1 && : $(( t2 = t1 + (1 + d) ))
1625 test "$aname2" = "sleep" && nt2=$(( t2 - d ))
1626
1627 test "$aname3" = "sleep" && d=$BUSYCHECK || d=0
1628 test $(( (t3 - d) )) -le $t2 && : $(( t3 = t2 + (1 + d) ))
1629 test "$aname3" = "sleep" && nt3=$(( t3 - d ))
1630
1631 useridle1_delta=$((t2 - t1))
1632 useridle2_delta=$((t3 - t2))
1633 useridle1_next=$useridle2_action
1634 useridle2_next=$useridle3_action
1635
1636 # give olpc-kbdshim the timeouts
1637 reset_idlecounters ${nt1:-$t1} ${nt2:-$t2} ${nt3:-$t3}
1638
1639 t4=${config_MAX_SLEEP_BEFORE_SHUTDOWN:-0}
1640 test "$t4" -eq "$t4" || t4=300
1641 test "$t4" -eq 0 && \
1642 { logger zero max-sleep time found, now 999999999; t4=999999999; }
1643 test "$t4" -le "5" && t4=300
1644
1645 log $aname1 $t1, $aname2 $t2, $aname3 $t3, shutdown after $t4
1646 dimtimer=;
1647 blanktimer=;
1648 shutdowntimer=$t4
1649
1650 return 0
1651 }
1652
1653 reevaluate()
1654 {
1655 if [ "${1:-}" = all -o \
1656 "${o_ac:-}" != "$ac" -o \
1657 "${o_ebook:-}" != "$am_ebook" ]
1658 then
1659 set_idletimes || reset_idlecounters
1660 fi
1661 o_ebook=$am_ebook
1662 o_ac=$ac
1663 }
1664
1665 selfinject()
1666 {
1667 test -p $EVENTFIFO || exit 1
1668 echo $* >$EVENTFIFO
1669 }
1670
1671 sched_powertimer()
1672 {
1673 # we can't cancel timers, so give them sequence numbers
1674 : $((timerseqno += 1))
1675 (sleep $1; shift 1; selfinject powertimerdone $(seconds) $timerseqno $*) &
1676 }
1677
1678 sched_unfreezetimer()
1679 {
1680 (sleep $config_UNFREEZE_SECONDS; selfinject unfreeze_dcon ) &
1681 }
1682
1683 invalidate_powertimer()
1684 {
1685 # bump the seq number so we won't match a scheduled timer
1686 # when it arrives.
1687 : $((timerseqno += 1))
1688 }
1689
1690 gotactivity()
1691 {
1692 invalidate_powertimer
1693 unsplash
1694 }
1695
1696 dim_action()
1697 {
1698 backlight is_off || backlight dim
1699 }
1700
1701 blank_action()
1702 {
1703 backlight off
1704 }
1705
1706 sleep_action()
1707 {
1708 nextaction=$1
1709 delta1=$2
1710 delta2=$3
1711
1712 # if we're still booting, the dcon may still be frozen.
1713 # don't sleep until we're sort of all the way up.
1714 if dcon is_frozen
1715 then
1716 reset_idlecounters
1717 return
1718 fi
1719
1720 # extend the first wakeup after power or lid sleep to at
1721 # least 60 seconds to work around slow wlan startup (#9854)
1722 : ${holdoff_start:=}
1723 if [ "$holdoff_start" -a $(($(seconds) - holdoff_start)) -lt 60 ]
1724 then
1725 reset_idlecounters
1726 return
1727 fi
1728
1729 # we'll check the files again later, just before sleeping.
1730 # checking now keeps from doing extra work, and checking
1731 # later narrows the race condition (laptop_busy() takes many
1732 # seconds)
1733 if inhibited_by_files
1734 then
1735 reset_idlecounters
1736 return
1737 fi
1738
1739 # kick off a sync if there isn't one running. it will be
1740 # less disruptive to the user now than if it happens during
1741 # the actual suspend.
1742 killall -q -0 sync || { sync & }
1743
1744 # we've allowed an extra $BUSYCHECK seconds for this action.
1745 # use it here.
1746 if laptop_busy
1747 then
1748 reset_idlecounters # restart the timers
1749 return
1750 fi
1751
1752 # sleep until it's time to shut down
1753 if [ $nextaction = dim_action ] && ! backlight is_off
1754 then
1755 snooze until_dim "$shutdowntimer" "$delta1" "$delta2"
1756 elif [ $nextaction = blank_action ]
1757 then
1758 snooze until_blank "$shutdowntimer" "$delta1"
1759 else
1760 snooze until_shutdown "$shutdowntimer" $keypress_sleep
1761 fi
1762 }
1763
1764 exit_actions()
1765 {
1766 pwrlog_take_reading shutdown
1767 set_wakeupevents none
1768 unsplash
1769 dcon thaw
1770 dcon wake
1771 rm -f $EVENTFIFO
1772 rm -rf $INHIBITDIR
1773 exit
1774 }
1775
1776 event_loop()
1777 {
1778 local event tstamp arg2 arg3 more
1779
1780 : @ starting eventloop
1781
1782 set_idletimes
1783
1784 unsplash
1785
1786 # recreate to flush, and to make sure it's a fifo
1787 rm -f $EVENTFIFO
1788 mkfifo $EVENTFIFO
1789 chmod 600 $EVENTFIFO
1790 exec 6<> $EVENTFIFO
1791
1792 lid_check
1793
1794 while :
1795 do
1796
1797 reevaluate
1798
1799 # if we did lookahead on events in snooze(), use the result here
1800 if [ "${s_event:-}" ]
1801 then
1802 event=$s_event
1803 tstamp=$s_tstamp
1804 arg2=$s_arg2
1805 arg3=$s_arg3
1806 more=$s_more
1807 unset s_event s_tstamp s_arg2 s_arg3 s_more
1808 else
1809 read event tstamp arg2 arg3 more
1810 fi
1811
1812 : -------------------------
1813 : @ got event $event, $tstamp, $arg2, $arg3, $more.
1814
1815 if [ "$tstamp" -a "$tstamp" != '-' ] && [ "$tstamp" -lt "$eventcutoff" ]
1816 then
1817 # it's possible for olpc-switchd to generate multiple
1818 # hardware-related events (e.g., lidopen/lidclose/lidopen)
1819 # before we go to sleep due the first one. toss any
1820 # that are stale.
1821 continue
1822 fi
1823
1824 pwrlog_take_reading $event-event $arg2 $arg3 $more
1825
1826 case $event in
1827
1828 powerbutton|fake_powerbutton)
1829 # sync, in case the user keeps holding the button.
1830 # hope it's finished in 4 seconds.
1831 killall -q -0 sync || { sync & }
1832
1833 if backlight is_off
1834 then
1835 # if the screen is off, the power button should simply
1836 # wake the system up.
1837 gotactivity
1838 backlight restore
1839 reset_idlecounters
1840 else
1841 if [ $config_CONFIRM_SECONDS = 0 ]
1842 then
1843 backlight off
1844 # hard sleep until it's time to shut down
1845 snooze until_shutdown "$shutdowntimer" hard
1846 else
1847 if [ "$powerseqno" != "$timerseqno" ]
1848 then # first press
1849 splash confirm
1850 reset_idlecounters # reprime for "useractivity"
1851 sched_powertimer $config_CONFIRM_SECONDS gotosleep
1852 powerseqno=$timerseqno
1853 backlight restore
1854 else # second press
1855 nextsplash # advance to next splash screen
1856 sleep 1
1857 do_shutdown "power press"
1858 fi
1859 fi
1860 fi
1861 ;;
1862
1863 powertimerdone)
1864 # are we still waiting for this timer?
1865 if [ "$timerseqno" = "$arg2" ]
1866 then
1867 echo $arg3 $(seconds) >&6
1868 : $((timerseqno += 1))
1869 fi
1870 ;;
1871
1872 gotosleep)
1873 invalidate_powertimer
1874 backlight off
1875 # hard sleep until it's time to shut down
1876 snooze until_shutdown "$shutdowntimer" hard
1877 ;;
1878
1879 lidclose)
1880 lid_closed
1881 ;;
1882
1883 lidopen)
1884 touchpad_recalibrate
1885 gotactivity
1886 am_ebook=;
1887 backlight restore
1888 ;;
1889
1890 ebookclose) # i.e., fully flat in ebook mode
1891 am_ebook=true
1892 ;;
1893
1894 ebookopen)
1895 am_ebook=;
1896 ;;
1897
1898 useractive)
1899 test "$tracing" && : $(seconds)
1900 gotactivity
1901 backlight restore
1902 ;;
1903
1904 fake_useractive)
1905 test "$tracing" && : $(seconds)
1906 gotactivity
1907 case "$arg2" in
1908 wlanpacket|unknown|ectimer)
1909 ;; # don't brighten for wlan or other unknowns
1910 *)
1911 backlight restore
1912 ;;
1913 esac
1914 reset_idlecounters
1915 ;;
1916
1917 useridle1)
1918 test "$tracing" && : $(seconds)
1919 $useridle1_action \
1920 $useridle1_next $useridle1_delta $useridle2_delta
1921 ;;
1922
1923 useridle2)
1924 test "$tracing" && : $(seconds)
1925 $useridle2_action $useridle2_next $useridle2_delta ""
1926 ;;
1927
1928 useridle3)
1929 test "$tracing" && : $(seconds)
1930 $useridle3_action none "" ""
1931 ;;
1932
1933 ac-online|ac-offline)
1934 ac=${event#ac-}
1935 ;;
1936
1937 battery)
1938 battery_capacity=$arg2
1939 maybe_battery_shutdown
1940 ;;
1941
1942 timer)
1943 # olpc-switchd will emit a "timer" event periodically
1944 # if asked to. the only purpose is to make sure
1945 # olpc-pwr-log.sh has a reason to log once in a while.
1946 test "$tracing" && : $(seconds)
1947 ;;
1948
1949 reconfig)
1950 read_config
1951 power_check
1952 reevaluate all
1953 ;;
1954
1955 unfreeze_dcon)
1956 # this is a bit of a hack. on the XO, the bootanim
1957 # script contrives to leave the dcon frozen at the end
1958 # of the init sequence. it remains frozen until sugar
1959 # first becomes idle, at which point sugar sends a dbus
1960 # message to ohmd, causing ohmd to unfreeze the dcon.
1961 # since we don't do dbus, we unfreeze the dcon after 10
1962 # seconds.
1963 reset_idlecounters
1964 dcon thaw
1965 ;;
1966
1967 dark-suspend)
1968 # we have some external power measurement scripts that
1969 # want to quiesce the laptop without killing off powerd.
1970 # this lets them work together.
1971 backlight off
1972 snooze until_shutdown "$shutdowntimer" soft
1973 ;;
1974
1975 trace-on)
1976 set_tracing on
1977 ;;
1978 trace-off)
1979 set_tracing off
1980 ;;
1981 esac
1982
1983 done <&6 # from the fifo
1984 }
1985
1986 read_hwinfo()
1987 {
1988 read hwvendor < /sys/class/dmi/id/sys_vendor ||
1989 hwvendor="n/a"
1990 read hwname < /sys/class/dmi/id/product_name ||
1991 hwname="n/a"
1992 read hwversion < /sys/class/dmi/id/product_version ||
1993 hwversion="n/a"
1994 }
1995
1996 choose_xo_model()
1997 {
1998 read_hwinfo
1999
2000 case $hwvendor-$hwname-$hwversion in
2001 OLPC-XO-1|OLPC-XO-1.5)
2002 XO=$hwversion
2003 ;;
2004 *) # pre-F11 releases didn't have the /sys/class/dmi tree, so we
2005 # also check for an olpc-only node in /sys
2006 if [ -e /sys/power/wakeup_events/ebook_mode_change ]
2007 then
2008 XO=1
2009 fi
2010 ;;
2011 esac
2012
2013 if [ ! "$XO" ]
2014 then
2015 log Unsupported hardware: vendor "$hwvendor", version "$hwversion"
2016 exit 1
2017 fi
2018 }
2019
2020 configure_pwrlog()
2021 {
2022 if [ $config_PWRLOG_INTERVAL -gt 30 -a \
2023 -s $CONFIGDIR/olpc-pwr-log.sh ]
2024 then
2025 pwrlog_inside_powerd=yes
2026
2027 mkdir -p $config_PWRLOG_DIR
2028 chown olpc:olpc $config_PWRLOG_DIR
2029
2030 . $CONFIGDIR/olpc-pwr-log.sh
2031 pwrlog_init $config_PWRLOG_INTERVAL $config_PWRLOG_DIR \
2032 $config_PWRLOG_LOGSIZE $config_PWRLOG_LOGDIRSIZE
2033
2034 else
2035 # install a null handler
2036 pwrlog_take_reading()
2037 {
2038 : @ pwrlog unconfigured, or unavailable
2039 }
2040 fi
2041 }
2042
2043 netactivity_snapshot()
2044 {
2045 iptables --list netactivity --verbose --exact --numeric
2046 }
2047
2048 init_netactivity_tracking()
2049 {
2050 local iface oface
2051
2052 monitor_network_activity=;
2053
2054 if ! yes_or_true "$config_MONITOR_NETWORK_ACTIVITY" || \
2055 ! test -x /sbin/iptables
2056 then
2057 return
2058 fi
2059 monitor_network_activity=true
2060
2061 iface="! --in-interface lo"
2062 oface="! --out-interface lo"
2063
2064 # this initialization may interfere with other future
2065 # uses of iptables. but for now it's the right thing.
2066 iptables --flush INPUT
2067 iptables --policy INPUT ACCEPT
2068 iptables --flush OUTPUT
2069 iptables --policy OUTPUT ACCEPT
2070
2071
2072 iptables --flush netactivity 2>/dev/null
2073 iptables --delete-chain netactivity 2>/dev/null
2074 iptables --new-chain netactivity # (re)create the chain
2075
2076 # count incoming pings
2077 iptables --insert INPUT -p icmp $iface -j netactivity
2078
2079 # count incoming, already-connected tcp
2080 iptables --insert INPUT -p tcp ! --syn $iface -j netactivity
2081
2082 # count outgoing already-connected tcp
2083 # redundant with next rule
2084 #iptables --insert OUTPUT -p tcp ! --syn $oface -j netactivity
2085
2086 # count all outgoing packets _except_ mdns
2087 iptables --insert OUTPUT -p tcp ! --dport mdns $oface -j netactivity
2088 iptables --insert OUTPUT -p udp ! --dport mdns $oface -j netactivity
2089
2090 ## count all incoming packets _except_ mdns
2091 #iptables --insert INPUT -p tcp ! --dport mdns $iface -j netactivity
2092 #iptables --insert INPUT -p udp ! --dport mdns $iface -j netactivity
2093
2094 # this is the null "rule" that aggregates the above counts,
2095 iptables --insert netactivity
2096
2097 }
2098
2099
2100 am_ebook=;
2101 o_ebook=xxx;
2102 dimmed=;
2103 savebright=;
2104 last_t_values=;
2105 timerseqno=1;
2106 powerseqno=0;
2107 eventcutoff=0;
2108
2109 choose_xo_model
2110
2111 log starting
2112
2113 set_config_defaults
2114 if [ -r $CONFIGFILE ]
2115 then
2116 log configuring from $CONFIGFILE
2117 fi
2118
2119 create_inhibit_dir
2120
2121 read_config
2122
2123 init_netactivity_tracking
2124
2125 configure_pwrlog
2126
2127 pwrlog_take_reading startup
2128
2129 sched_unfreezetimer
2130
2131 trap "exit_actions" 0
2132
2133 power_check
2134 ebook_check
2135
2136 reevaluate all
2137
2138 # let user programs control brightness
2139 chmod a+w $BRIGHTNESS $MONO_MODE
2140
2141 set_acpi_wakeupevents LID enable
2142 set_acpi_wakeupevents EC enable
2143 set_wakeupevents all_sci
2144
2145
2146 event_loop