Difference between revisions of "Power management"

From ArchWiki
Jump to navigation Jump to search
(update link)
(update status of external links (interactive))
Tag: wiki-scripts
 
(225 intermediate revisions by 80 users not shown)
Line 1: Line 1:
 
[[Category:Power management]]
 
[[Category:Power management]]
[[es:Power Management]]
+
[[es:Power management]]
 
[[ja:電源管理]]
 
[[ja:電源管理]]
[[zh-CN:Power Management]]
+
[[zh-hans:Power management]]
 
{{Related articles start}}
 
{{Related articles start}}
{{Related|Power management/Energy saving}}
 
 
{{Related|Power management/Suspend and hibernate}}
 
{{Related|Power management/Suspend and hibernate}}
 
{{Related|Display Power Management Signaling}}
 
{{Related|Display Power Management Signaling}}
 +
{{Related|CPU frequency scaling}}
 +
{{Related|Hybrid graphics}}
 +
{{Related|Kernel modules}}
 +
{{Related|sysctl}}
 +
{{Related|udev}}
 
{{Related articles end}}
 
{{Related articles end}}
 +
[[Wikipedia:Power management|Power management]] is a feature that turns off the power or switches system's components to a low-power state when inactive.
  
The purpose of this page is to provide general overview of power management in Arch Linux. As Arch Linux uses [[systemd]] as system manager, this article focuses on it.
+
In Arch Linux, power management consists of two main parts:
  
There are multiple places where one can change power management settings:
+
# Configuration of the Linux kernel, which interacts with the hardware.
* [[Kernel parameters]]
+
#* [[Kernel parameters]]
* [[Kernel modules]]
+
#* [[Kernel modules]]
* [[udev]] rules
+
#* [[udev]] rules
 +
# Configuration of userspace tools, which interact with the kernel and react to its events. Many userspace tools also allow to modify kernel configuration in a "user-friendly" way. See [[#Userspace tools]] for the options.
  
There are also many power management tools:
+
== Userspace tools ==
* [[systemd]]
 
* [[pm-utils]]
 
* [[Laptop Mode Tools]]
 
* [[TLP]]
 
* [[acpid]]
 
  
{{Note|Power settings you set in one place/tool could be overwritten in another place/tool.}}
+
Using these tools can replace setting a lot of settings by hand.  Only run '''one''' of these tools to avoid possible conflicts as they all work more or less similarly.  Have a look at the [[:Category:Power management|power management category]] to get an overview on what power management options exist in Arch Linux.
 +
 
 +
These are the more popular scripts and tools designed to help power saving:
 +
 
 +
=== Console ===
 +
 
 +
* {{App|[[acpid]]| A daemon for delivering ACPI power management events with netlink support.|http://sourceforge.net/projects/acpid2/|{{Pkg|acpid}}}}
 +
* {{App|[[Laptop Mode Tools]]|Utility to configure laptop power saving settings, considered by many to be the de facto utility for power saving though may take a bit of configuration.|https://github.com/rickysarraf/laptop-mode-tools|{{AUR|laptop-mode-tools}}}}
 +
* {{App|libsmbios|Library and tools for interacting with Dell SMBIOS tables.|https://github.com/dell/libsmbios|{{Pkg|libsmbios}}}}
 +
* {{App|[[powertop]]|A tool to diagnose issues with power consumption and power management to help set power saving settings.|https://01.org/powertop/|{{Pkg|powertop}}}}
 +
* {{App|[[systemd]]|A system and service manager.|https://freedesktop.org/wiki/Software/systemd/|{{Pkg|systemd}}}}
 +
* {{App|[[TLP]]|Advanced power management for Linux.|http://linrunner.de/tlp|{{Pkg|tlp}}}}
 +
 
 +
=== Graphical ===
 +
 
 +
* {{App|batterymon-clone|Simple battery monitor tray icon.|https://github.com/jareksed/batterymon-clone|{{AUR|batterymon-clone}}}}
 +
* {{App|cbatticon|Lightweight and fast battery icon that sits in your system tray.|https://github.com/valr/cbatticon|{{Pkg|cbatticon}}}}
 +
* {{App|GNOME Power Statistics|System power information and statistics for GNOME.|https://gitlab.gnome.org/GNOME/gnome-power-manager|{{Pkg|gnome-power-manager}}}}
 +
* {{App|KDE Power Devil|Power management module for Plasma.|https://userbase.kde.org/Power_Devil{{Dead link|2020|04|01|status=404}}|{{Pkg|powerdevil}} {{aur|powerdevil-light}}}}
 +
* {{App|LXQt Power Management|Power management module for LXQt.|https://github.com/lxqt/lxqt-powermanagement|{{Pkg|lxqt-powermanagement}}}}
 +
* {{App|MATE Power Management|Power management tool for MATE.|https://github.com/mate-desktop/mate-power-manager|{{Pkg|mate-power-manager}}}}
 +
* {{App|MATE Power Statistics|System power information and statistics for MATE.|https://github.com/mate-desktop/mate-power-manager|{{Pkg|mate-power-manager}}}}
 +
* {{App|powerkit|Desktop independent power manager.|https://github.com/rodlie/powerkit|{{AUR|powerkit}}}}
 +
* {{App|Xfce Power Manager|Power manager for Xfce.|https://docs.xfce.org/xfce/xfce4-power-manager/start|{{Pkg|xfce4-power-manager}}}}
 +
* {{App|vattery|Battery monitoring application written in Vala that will display the status of a laptop battery in a system tray.|http://www.jezra.net/projects/vattery{{Dead link|2020|04|01|status=404}}|{{AUR|vattery}}}}
  
 
== Power management with systemd ==
 
== Power management with systemd ==
Line 29: Line 54:
 
=== ACPI events ===
 
=== ACPI events ===
  
''systemd'' handles some power-related [[Wikipedia:Advanced_Configuration_and_Power_Interface|ACPI]] events. They can be configured via the following options from {{ic|/etc/systemd/logind.conf}} (or {{ic|/etc/systemd/logind.conf.d/*.conf}}):
+
''systemd'' handles some power-related [[Wikipedia:Advanced_Configuration_and_Power_Interface|ACPI]] events, whose actions can be configured in {{ic|/etc/systemd/logind.conf}} or {{ic|/etc/systemd/logind.conf.d/*.conf}} — see {{man|5|logind.conf}}. On systems with no dedicated power manager, this may replace the [[acpid]] daemon which is usually used to react to these ACPI events.
 +
 
 +
The specified action for each event can be one of {{ic|ignore}}, {{ic|poweroff}}, {{ic|reboot}}, {{ic|halt}}, {{ic|suspend}}, {{ic|hibernate}}, {{ic|hybrid-sleep}}, {{ic|suspend-then-hibernate}}, {{ic|lock}} or {{ic|kexec}}. In case of hibernation and suspension, they must be properly [[Power management/Suspend and hibernate|set up]]. If an event is not configured, ''systemd'' will use a default action.
 +
 
 +
{| class="wikitable sortable" border=1
 +
!Event handler
 +
!Description
 +
!Default action
 +
|-
 +
|{{ic|HandlePowerKey}}
 +
|Triggered when the power key/button is pressed.
 +
|{{ic|poweroff}}
 +
|-
 +
|{{ic|HandleSuspendKey}}
 +
|Triggered when the suspend key/button is pressed.
 +
|{{ic|suspend}}
 +
|-
 +
|{{ic|HandleHibernateKey}}
 +
|Triggered when the hibernate key/button is pressed.
 +
|{{ic|hibernate}}
 +
|-
 +
|{{ic|HandleLidSwitch}}
 +
|Triggered when the lid is closed, except in the cases below.
 +
|{{ic|suspend}}
 +
|-
 +
|{{ic|HandleLidSwitchDocked}}
 +
|Triggered when the lid is closed if the system is inserted in a docking station, or more than one display is connected.
 +
|{{ic|ignore}}
 +
|-
 +
|{{ic|HandleLidSwitchExternalPower}}
 +
|Triggered when the lid is closed if the system is connected to external power.
 +
|action set for {{ic|HandleLidSwitch}}
 +
|}
 +
 
 +
To apply any changes, signal {{ic|systemd-logind}} with {{ic|HUP}}:
 +
 
 +
# kill -s HUP $(systemctl show --property MainPID systemd-logind | cut -d= -f2)
 +
 
 +
{{Note|''systemd'' cannot handle AC and Battery ACPI events, so if you use [[Laptop Mode Tools]] or other similar tools [[acpid]] is still required.}}
  
* {{ic|HandlePowerKey}}: specifies which action is invoked when the power key is pressed.
+
==== Power managers ====
* {{ic|HandleSuspendKey}}: specifies which action is invoked when the suspend key is pressed.
 
* {{ic|HandleHibernateKey}}: specifies which action is invoked when the hibernate key is pressed.
 
* {{ic|HandleLidSwitch}}: specifies which action is invoked when the lid is closed.
 
  
The specified action can be one of {{ic|ignore}}, {{ic|poweroff}}, {{ic|reboot}}, {{ic|halt}}, {{ic|suspend}}, {{ic|hibernate}}, {{ic|hybrid-sleep}}, {{ic|lock}} or {{ic|kexec}}.
+
Some [[desktop environment]]s include power managers which [http://www.freedesktop.org/wiki/Software/systemd/inhibit/ inhibit] (temporarily turn off) some or all of the ''systemd'' ACPI settings. If such a power manager is running, then the actions for ACPI events can be configured in the power manager alone. Changes to {{ic|/etc/systemd/logind.conf}} or {{ic|/etc/systemd/logind.conf.d/*.conf}} need be made only if you wish to configure behaviour for a particular event that is not inhibited by the power manager.  
  
If these options are not configured, ''systemd'' will use its defaults: {{ic|1=HandlePowerKey=poweroff}}, {{ic|1=HandleSuspendKey=suspend}}, {{ic|1=HandleHibernateKey=hibernate}}, and {{ic|1=HandleLidSwitch=suspend}}.
+
Note that if the power manager does not inhibit ''systemd'' for the appropriate events you can end up with a situation where ''systemd'' suspends your system and then when the system is woken up the other power manager suspends it again. As of December 2016, the power managers of [[KDE]], [[GNOME]], [[Xfce]] and [[MATE]] issue the necessary ''inhibited'' commands. If the ''inhibited'' commands are not being issued, such as when using [[acpid]] or others to handle ACPI events, set the {{ic|Handle}} options to {{ic|ignore}}. See also {{man|1|systemd-inhibit}}.
  
On systems which run no graphical setup or only a simple window manager like [[i3]] or [[awesome]], this may replace the [[acpid]] daemon which is usually used to react to these ACPI events.
+
==== xss-lock ====
  
{{Note|
+
{{pkg|xss-lock}} subscribes to the systemd-events {{ic|suspend}}, {{ic|hibernate}}, {{ic|lock-session}}, and {{ic|unlock-session}} with appropriate actions (run locker and wait for user to unlock or kill locker). ''xss-lock'' also reacts to [[DPMS]] events and runs or kills the locker in response.
* [[systemd#Using units|Restart]] the {{ic|systemd-logind}} daemon for your changes to take effect (be warned: this will terminate all login sessions).
 
* ''systemd'' cannot handle AC and Battery ACPI events, so if you use [[Laptop Mode Tools]] or other similar tools [[acpid]] is still required.
 
* If more than one display is connected, the action specified by {{ic|HandleLidSwitchDocked}} occurs.
 
}}
 
  
In the current version of ''systemd'', the {{ic|Handle*}} options will apply throughout the system unless they are "inhibited" (temporarily turned off) by a program, such as a power manager inside a desktop environment. If these inhibits are not taken, you can end up with a situation where ''systemd'' suspends your system, then when it wakes up the other power manager suspends it again.
+
Start xss-lock in your [[autostart]], for example
  
{{Warning|Currently, only the power managers of [[KDE]], [[GNOME]] and [[Xfce]] issue the necessary ''inhibited'' commands. When using [[acpid]] or others to handle ACPI events, set the {{ic|Handle}} options to {{ic|ignore}}.}}
+
xss-lock -- i3lock -n -i ''background_image.png'' &
  
 
=== Suspend and hibernate ===
 
=== Suspend and hibernate ===
  
''systemd'' provides commands for suspend to RAM, hibernate and a hybrid suspend using the kernel's native suspend/resume functionality. There are also mechanisms to add hooks to customize pre- and post-suspend actions.
+
''systemd'' provides commands to suspend to RAM or hibernate using the kernel's native suspend/resume functionality. There are also mechanisms to add hooks to customize pre- and post-suspend actions.
  
{{Note|''systemd'' can also use other suspend backends (such as [[Uswsusp]] or [[TuxOnIce]]), in addition to the default ''kernel'' backend, in order to put the computer to sleep or hibernate. See [[Uswsusp#With systemd]] for an example.}}
+
{{ic|systemctl suspend}} should work out of the box, for {{ic|systemctl hibernate}} to work on your system you need to follow the instructions at [[Suspend and hibernate#Hibernation]].
  
{{ic|systemctl suspend}} should work out of the box, for {{ic|systemctl hibernate}} to work on your system you need to follow the instructions at [[Suspend and hibernate#Hibernation]].
+
There are also two modes combining suspend and hibernate:
 +
 
 +
* {{ic|systemctl hybrid-sleep}} suspends the system both to RAM and disk, so a complete power loss does not result in lost data. This mode is also called [[Power management/Suspend and hibernate|suspend to both]].
 +
* {{ic|systemctl suspend-then-hibernate}} initially suspends the system to RAM and if it is not interrupted within the delay specified by {{ic|HibernateDelaySec}} in {{man|5|systemd-sleep.conf}}, then the system will be woken using an RTC alarm and hibernated.
 +
 
 +
{{Note|''systemd'' can also use other suspend backends (such as [[Uswsusp]]), in addition to the default ''kernel'' backend, in order to put the computer to sleep or hibernate. See [[Uswsusp#With systemd]] for an example.}}
 +
 
 +
==== Hybrid-sleep on suspend or hibernation request ====
 +
 
 +
It is possible to configure systemd to always do a ''hybrid-sleep'' even on a ''suspend'' or ''hibernation'' request.
 +
 
 +
The default ''suspend'' and ''hibernation'' action can be configured in the {{ic|/etc/systemd/sleep.conf}} file. To set both actions to ''hybrid-sleep'':
  
==== Hybrid sleep ====
+
{{hc|/etc/systemd/sleep.conf|2=
 +
[Sleep]
 +
# suspend=hybrid-sleep
 +
SuspendMode=suspend
 +
SuspendState=disk
 +
# hibernate=hybrid-sleep
 +
HibernateMode=suspend
 +
HibernateState=disk
 +
}}
  
{{ic|systemctl hybrid-sleep}} both hibernates and suspends at the same time. This combines some of the benefits and drawbacks of suspension and hibernation. This is useful in case a computer were to suddenly lose power (AC disconnection or battery depletion) since upon powerup it will resume from hibernation. If there is no power loss, then it will resume from suspension, which is much faster than resuming from hibernation. However, since "hybrid-sleep" has to dump memory to swap in order for hibernation to work, it is slower to enter sleep than a plain {{ic|systemctl suspend}}. An alternative is a [[#Delayed_hibernation_service_file|delayed hibernation service file]].
+
See the {{man|5|sleep.conf.d}} manual page for details and the [https://www.kernel.org/doc/html/latest/admin-guide/pm/sleep-states.html#basic-sysfs-interfaces-for-system-suspend-and-hibernation linux kernel documentation on power states].
  
 
=== Sleep hooks ===
 
=== Sleep hooks ===
 
''systemd'' does not use [[pm-utils]] to put the machine to sleep when using {{ic|systemctl suspend}}, {{ic|systemctl hibernate}} or {{ic|systemctl hybrid-sleep}}; ''pm-utils'' hooks, including any [[Pm-utils#Creating_your_own_hooks|custom hooks]], will not be run. However, ''systemd'' provides two similar mechanisms to run custom scripts on these events.
 
  
 
==== Suspend/resume service files ====
 
==== Suspend/resume service files ====
  
Service files can be hooked into ''suspend.target'', ''hibernate.target'' and ''sleep.target'' to execute actions before or after suspend/hibernate. Separate files should be created for user actions and root/system actions. [[systemd#Using units|Enable]] the {{ic|suspend@''user''}} and {{ic|resume@''user''}} services to have them started at boot. Examples:
+
Service files can be hooked into ''suspend.target'', ''hibernate.target'', ''sleep.target'', ''hybrid-sleep.target'' and ''suspend-then-hibernate.target'' to execute actions before or after suspend/hibernate. Separate files should be created for user actions and root/system actions. [[Enable]] the {{ic|suspend@''user''}} and {{ic|resume@''user''}} services to have them started at boot. Examples:
  
{{hc|/etc/systemd/system/suspend@.service|2=<nowiki>
+
{{hc|/etc/systemd/system/suspend@.service|2=
 
[Unit]
 
[Unit]
 
Description=User suspend actions
 
Description=User suspend actions
Line 81: Line 154:
 
Type=forking
 
Type=forking
 
Environment=DISPLAY=:0
 
Environment=DISPLAY=:0
ExecStartPre= -/usr/bin/pkill -u %u unison ; /usr/local/bin/music.sh stop ; /usr/bin/mysql -e 'slave stop'
+
ExecStartPre= -/usr/bin/pkill -u %u unison ; /usr/local/bin/music.sh stop
 
ExecStart=/usr/bin/sflock
 
ExecStart=/usr/bin/sflock
 +
ExecStartPost=/usr/bin/sleep 1
  
 
[Install]
 
[Install]
WantedBy=sleep.target</nowiki>}}
+
WantedBy=sleep.target
 +
}}
  
{{hc|/etc/systemd/system/resume@.service|2=<nowiki>
+
{{hc|/etc/systemd/system/resume@.service|2=
 
[Unit]
 
[Unit]
 
Description=User resume actions
 
Description=User resume actions
Line 95: Line 170:
 
User=%I
 
User=%I
 
Type=simple
 
Type=simple
ExecStartPre=/usr/local/bin/ssh-connect.sh
+
ExecStart=/usr/local/bin/ssh-connect.sh
ExecStart=/usr/bin/mysql -e 'slave start'
 
  
 
[Install]
 
[Install]
WantedBy=suspend.target</nowiki>}}
+
WantedBy=suspend.target}}
 +
 
 +
{{Note|As screen lockers may return before the screen is "locked", the screen may flash on resuming from suspend. Adding a small delay via {{ic|1=ExecStartPost=/usr/bin/sleep 1}} helps prevent this.}}
  
For root/system actions ([[systemd#Using units|enable]] the {{ic|root-resume}} and {{ic|root-suspend}} services to have them started at boot):
+
For root/system actions ([[enable]] the {{ic|root-resume}} and {{ic|root-suspend}} services to have them started at boot):
  
{{hc|/etc/systemd/system/root-resume.service|2=<nowiki>
+
{{hc|/etc/systemd/system/root-suspend.service|2=
 
[Unit]
 
[Unit]
Description=Local system resume actions
+
Description=Local system suspend actions
After=suspend.target
+
Before=sleep.target
  
 
[Service]
 
[Service]
 
Type=simple
 
Type=simple
ExecStart=/usr/bin/systemctl restart mnt-media.automount
+
ExecStart=-/usr/bin/pkill sshfs
  
 
[Install]
 
[Install]
WantedBy=suspend.target</nowiki>}}
+
WantedBy=sleep.target}}
  
{{hc|/etc/systemd/system/root-suspend.service|2=<nowiki>
+
{{hc|/etc/systemd/system/root-resume.service|2=
 
[Unit]
 
[Unit]
Description=Local system suspend actions
+
Description=Local system resume actions
Before=sleep.target
+
After=suspend.target
  
 
[Service]
 
[Service]
 
Type=simple
 
Type=simple
ExecStart=-/usr/bin/pkill sshfs
+
ExecStart=/usr/bin/systemctl restart mnt-media.automount
  
 
[Install]
 
[Install]
WantedBy=sleep.target</nowiki>}}
+
WantedBy=suspend.target}}
 +
 
 +
{{Tip|A couple of handy hints about these service files (more in {{man|5|systemd.service}}):
  
A couple of handy hints about these service files (more in {{ic|man systemd.service}}):
 
 
* If {{ic|1=<nowiki>Type=oneshot</nowiki>}} then you can use multiple {{ic|1=<nowiki>ExecStart=</nowiki>}} lines. Otherwise only one {{ic|ExecStart}} line is allowed. You can add more commands with either {{ic|ExecStartPre}} or by separating commands with a semicolon (see the first example above; note the spaces before and after the semicolon, as they are ''required'').
 
* If {{ic|1=<nowiki>Type=oneshot</nowiki>}} then you can use multiple {{ic|1=<nowiki>ExecStart=</nowiki>}} lines. Otherwise only one {{ic|ExecStart}} line is allowed. You can add more commands with either {{ic|ExecStartPre}} or by separating commands with a semicolon (see the first example above; note the spaces before and after the semicolon, as they are ''required'').
 
* A command prefixed with {{ic|-}} will cause a non-zero exit status to be ignored and treated as a successful command.  
 
* A command prefixed with {{ic|-}} will cause a non-zero exit status to be ignored and treated as a successful command.  
* The best place to find errors when troubleshooting these service files is of course with [[Systemd#Journal|journalctl]].
+
* The best place to find errors when troubleshooting these service files is of course with [[journalctl]].
 +
}}
  
 
==== Combined Suspend/resume service file ====
 
==== Combined Suspend/resume service file ====
Line 151: Line 229:
  
 
[Install]
 
[Install]
WantedBy=sleep.target</nowiki>}}
+
WantedBy=sleep.target
 +
</nowiki>}}
  
 
* {{ic|1=<nowiki>RemainAfterExit=yes</nowiki>}}: After started, the service is considered active until it is explicitly stopped.
 
* {{ic|1=<nowiki>RemainAfterExit=yes</nowiki>}}: After started, the service is considered active until it is explicitly stopped.
 
* {{ic|1=<nowiki>StopWhenUnneeded=yes</nowiki>}}: When active, the service will be stopped if no other active service requires it. In this specific example, it will be stopped after ''sleep.target'' is stopped.
 
* {{ic|1=<nowiki>StopWhenUnneeded=yes</nowiki>}}: When active, the service will be stopped if no other active service requires it. In this specific example, it will be stopped after ''sleep.target'' is stopped.
* Because ''sleep.target'' is pulled in by ''suspend.target'', ''hibernate.target'' and ''hybrid-sleep.target'' and ''sleep.target'' itself is a ''StopWhenUnneeded'' service, the hook is guaranteed to start/stop properly for different tasks.
+
* Because ''sleep.target'' is pulled in by ''suspend.target'', ''hibernate.target'' and ''hybrid-sleep.target'' and because ''sleep.target'' itself is a ''StopWhenUnneeded'' service, the hook is guaranteed to start/stop properly for different tasks.
 
 
==== Delayed hibernation service file ====
 
 
 
An alternative approach is delayed hibernation. This makes use of sleep hooks to suspend as usual but sets a timer to wake up later to perform hibernation. Here, entering sleep is faster than {{ic|systemctl hybrid-sleep}} since no hibernation is performed initially. However, unlike "hybrid-sleep", at this point there is no protection against power loss via hibernation while in suspension. This caveat makes this approach more suitable for laptops than desktops. Since hibernation is delayed, the laptop battery is only used during suspension and to trigger the eventual hibernation. This uses less power over the long-term than a "hybrid-sleep" which will remain suspended until the battery is drained. Note that if your laptop has a spinning hard disk, when it wakes up from suspend in order to hibernate, you may not want to be moving or carrying the laptop for these few seconds. Delayed hibernation may be desirable both to reduce power use as well as for security reasons (e.g. when using full disk encryption). An example script is located [http://superuser.com/questions/298672/linuxhow-to-hibernate-after-a-period-of-sleep here]. See also [https://bbs.archlinux.org/viewtopic.php?pid=1420279#p1420279 this post] for an updated systemd sleep hook.
 
 
 
A slightly updated version of the service is:
 
{{hc|/etc/systemd/system/suspend-to-hibernate.service|<nowiki>
 
[Unit]
 
Description=Delayed hibernation trigger
 
Documentation=https://bbs.archlinux.org/viewtopic.php?pid=1420279#p1420279
 
Documentation=https://wiki.archlinux.org/index.php/Power_management
 
Before=suspend.target
 
Conflicts=hibernate.target hybrid-suspend.target
 
StopWhenUnneeded=true
 
 
 
[Service]
 
Type=oneshot
 
RemainAfterExit=yes
 
Environment="WAKEALARM=/sys/class/rtc/rtc0/wakealarm"
 
Environment="SLEEPLENGTH=+2hour"
 
ExecStart=-/usr/bin/sh -c 'echo -n "alarm set for "; date +%%s -d$SLEEPLENGTH | tee $WAKEALARM'
 
ExecStop=-/usr/bin/sh -c '\
 
  alarm=$(cat $WAKEALARM); \
 
  now=$(date +%%s); \
 
  if [ -z "$alarm" ] || [ "$now" -ge "$alarm" ]; then \
 
    echo "hibernate triggered"; \
 
    systemctl hibernate; \
 
  else \
 
    echo "normal wakeup"; \
 
  fi; \
 
  echo 0 > $WAKEALARM; \
 
'
 
 
 
[Install]
 
WantedBy=sleep.target
 
</nowiki>
 
}}
 
 
 
The {{ic|Before}} and {{ic|Conflicts}} options ensure it only is run for suspension and not hibernation--otherwise the service will run twice if delayed hibernation is triggered. The {{ic|WantedBy}} and {{ic|StopWhenUnneeded}} options are so it is started before sleep and stops upon resume. (Note that the {{ic|suspend.target}} and {{ic|hibernate.target}} targets do not stop when unneeded, but {{ic|sleep.target}} does). [[systemd#Using units|Enable]] the service.
 
  
 
==== Hooks in /usr/lib/systemd/system-sleep ====
 
==== Hooks in /usr/lib/systemd/system-sleep ====
Line 203: Line 243:
 
* Argument 2: {{ic|suspend}}, {{ic|hibernate}} or {{ic|hybrid-sleep}}, depending on which is being invoked
 
* Argument 2: {{ic|suspend}}, {{ic|hibernate}} or {{ic|hybrid-sleep}}, depending on which is being invoked
  
In contrast to [[pm-utils]], ''systemd'' will run these scripts concurrently and not one after another.
+
''systemd'' will run these scripts concurrently and not one after another.
  
The output of any custom script will be logged by ''systemd-suspend.service'', ''systemd-hibernate.service'' or ''systemd-hybrid-sleep.service''. You can see its output in ''systemd''<nowiki>'</nowiki>s [[systemd#Journal|journal]]:
+
The output of any custom script will be logged by ''systemd-suspend.service'', ''systemd-hibernate.service'' or ''systemd-hybrid-sleep.service''. You can see its output in ''systemd''<nowiki>'</nowiki>s [[journalctl]]:
  # journalctl -b -u systemd-suspend
+
 
 +
  # journalctl -b -u systemd-suspend.service
  
 
{{Note|You can also use ''sleep.target'', ''suspend.target'', ''hibernate.target'' or ''hybrid-sleep.target'' to hook units into the sleep state logic instead of using custom scripts.}}
 
{{Note|You can also use ''sleep.target'', ''suspend.target'', ''hibernate.target'' or ''hybrid-sleep.target'' to hook units into the sleep state logic instead of using custom scripts.}}
Line 221: Line 262:
 
     echo "Waking up from $2..."
 
     echo "Waking up from $2..."
 
     ;;
 
     ;;
esac}}
+
esac
 +
}}
  
 
Do not forget to make your script executable:
 
Do not forget to make your script executable:
 +
 
  # chmod a+x /usr/lib/systemd/system-sleep/example.sh
 
  # chmod a+x /usr/lib/systemd/system-sleep/example.sh
  
See {{ic|man 7 systemd.special}} and {{ic|man 8 systemd-sleep}} for more details.
+
See {{man|7|systemd.special}} and {{man|8|systemd-sleep}} for more details.
 +
 
 +
=== Troubleshooting ===
 +
 
 +
==== Delayed lid switch action ====
 +
 
 +
When performing lid switches in short succession, ''logind'' will delay the suspend action for up to 90s to detect possible docks. [http://lists.freedesktop.org/archives/systemd-devel/2015-January/027131.html] This delay was made configurable with systemd v220:[https://github.com/systemd/systemd/commit/9d10cbee89ca7f82d29b9cb27bef11e23e3803ba]
 +
 
 +
{{hc|/etc/systemd/logind.conf|2=
 +
...
 +
HoldoffTimeoutSec=30s
 +
...
 +
}}
 +
 
 +
==== Suspend from corresponding laptop Fn key not working ====
 +
 
 +
If, regardless of the setting in logind.conf, the sleep button does not work (pressing it does not even produce a message in syslog), then logind is probably not watching the keyboard device. [http://lists.freedesktop.org/archives/systemd-devel/2015-February/028325.html] Do:
 +
 
 +
# journalctl --grep="Watching system buttons"
 +
 
 +
You might see something like this:
 +
 
 +
May 25 21:28:19 vmarch.lan systemd-logind[210]: Watching system buttons on /dev/input/event2 (Power Button)
 +
May 25 21:28:19 vmarch.lan systemd-logind[210]: Watching system buttons on /dev/input/event3 (Sleep Button)
 +
May 25 21:28:19 vmarch.lan systemd-logind[210]: Watching system buttons on /dev/input/event4 (Video Bus)
 +
 
 +
Notice no keyboard device. Now obtain ATTRS{name} for the parent keyboard device [http://systemd-devel.freedesktop.narkive.com/Rbi3rjNN/patch-1-2-logind-add-support-for-tps65217-power-button] :
 +
 
 +
{{hc|# udevadm info -a /dev/input/by-path/*-kbd|2=
 +
...
 +
KERNEL=="event0"
 +
...
 +
ATTRS{name}=="AT Translated Set 2 keyboard"
 +
}}
 +
 
 +
Now write a custom udev rule to add the "power-switch" tag:
 +
 
 +
{{hc|/etc/udev/rules.d/70-power-switch-my.rules|<nowiki>
 +
ACTION=="remove", GOTO="power_switch_my_end"
 +
SUBSYSTEM=="input", KERNEL=="event*", ATTRS{name}=="AT Translated Set 2 keyboard", TAG+="power-switch"
 +
LABEL="power_switch_my_end"
 +
</nowiki>}}
 +
 
 +
{{Style|Explicit {{ic|systemctl}} commands should not be provided.}}
 +
 
 +
Restart services and reload rules:
 +
 
 +
# systemctl restart systemd-udevd.service
 +
# udevadm trigger
 +
# systemctl restart systemd-logind.service
 +
 
 +
Now you should see {{ic|Watching system buttons on /dev/input/event0}} in syslog.
 +
 
 +
== Power saving ==
 +
 
 +
{{Note|See [[Laptop#Power management]] for power management specific to laptops, such as battery monitoring.}}
 +
 
 +
This section is a reference for creating custom scripts and power saving settings such as by udev rules. Make sure that the settings are not managed by some [[#Userspace tools|other utility]] to avoid conflicts.
 +
 
 +
Almost all of the features listed here are worth using whether or not the computer is on AC or battery power. Most have negligible performance impact and are just not enabled by default because of commonly broken hardware/drivers. Reducing power usage means reducing heat, which can even lead to higher performance on a modern Intel or AMD CPU, thanks to [[Wikipedia:Intel Turbo Boost|dynamic overclocking]].
 +
 
 +
=== Processors with HWP (Hardware P-state) support ===
 +
 
 +
{{Merge|CPU frequency scaling|More context in the main article.}}
 +
 
 +
The available energy preferences of a HWP supported processor are {{ic|default performance balance_performance balance_power power}}.
 +
 
 +
This can be validated by {{ic|$ cat /sys/devices/system/cpu/cpufreq/policy?/energy_performance_available_preferences}}
 +
 
 +
To conserve more energy, you can config by creating the following file:
 +
 
 +
{{hc|/etc/tmpfiles.d/energy_performance_preference.conf|
 +
w /sys/devices/system/cpu/cpufreq/policy?/energy_performance_preference - - - - balance_power
 +
}}
 +
 
 +
See the {{man|8|systemd-tmpfiles}} and {{man|5|tmpfiles.d}} man pages for details.
 +
 
 +
=== Audio ===
 +
 
 +
==== Kernel ====
 +
By default, audio power saving is turned off by most drivers. It can be enabled by setting the {{ic|power_save}} parameter; a time (in seconds) to go into idle mode. To idle the audio card after one second, create the following file for Intel soundcards.
 +
 
 +
{{hc|/etc/modprobe.d/audio_powersave.conf|2=
 +
options snd_hda_intel power_save=1
 +
}}
 +
 
 +
Alternatively, use the following for ac97:
 +
 
 +
options snd_ac97_codec power_save=1
 +
 
 +
{{Note|
 +
* To retrieve the manufacturer and the corresponding kernel driver which is used for your sound card, run {{ic|lspci -k}}.
 +
* Toggling the audio card's power state can cause a popping sound or noticeable latency on some broken hardware.
 +
}}
 +
 
 +
It is also possible to further reduce the audio power requirements by disabling the HDMI audio output, which can done by [[blacklisting]] the appropriate kernel modules (e.g. {{ic|snd_hda_codec_hdmi}} in case of Intel hardware).
 +
 
 +
==== PulseAudio ====
 +
By default, PulseAudio suspends any audio sources that have become idle for too long. When using an external USB microphone, recordings may start with a pop sound. As a workaround, comment out the following line in {{ic|/etc/pulse/default.pa}}:
 +
 
 +
load-module module-suspend-on-idle
 +
 
 +
Afterwards, restart PulseAudio with {{ic|systemctl restart --user pulseaudio}}.
 +
 
 +
=== Backlight ===
 +
 
 +
See [[Backlight]].
 +
 
 +
=== Bluetooth ===
 +
 
 +
{{expansion|reason=The device should likely be disabled with hciconfig first.}}
 +
 
 +
To disable bluetooth completely, [[blacklist]] the {{ic|btusb}} and {{ic|bluetooth}} modules.
 +
 
 +
To turn off bluetooth only temporarily, use ''rfkill'':
 +
 
 +
# rfkill block bluetooth
 +
 
 +
Or with udev rule:
 +
 
 +
{{hc|/etc/udev/rules.d/50-bluetooth.rules|<nowiki>
 +
# disable bluetooth
 +
SUBSYSTEM=="rfkill", ATTR{type}=="bluetooth", ATTR{state}="0"
 +
</nowiki>}}
 +
 
 +
=== Web camera ===
 +
 
 +
If you will not use integrated web camera then [[blacklist]] the {{ic|uvcvideo}} module.
 +
 
 +
=== Kernel parameters ===
 +
 
 +
This section uses configs in {{ic|/etc/sysctl.d/}}, which is ''"a drop-in directory for kernel sysctl parameters."''  See [http://0pointer.de/blog/projects/the-new-configuration-files The New Configuration Files] and more specifically {{man|5|sysctl.d}} for more information.
 +
 
 +
==== Disabling NMI watchdog ====
 +
 
 +
{{Expansion|This or {{ic|nowatchdog}} as can be seen in [[Improving performance#Watchdogs]]}}
 +
 
 +
The [[Wikipedia:Non-maskable interrupt|NMI]] watchdog is a debugging feature to catch hardware hangs that cause a kernel panic. On some systems it can generate a lot of interrupts, causing a noticeable increase in power usage:
 +
 
 +
{{hc|/etc/sysctl.d/disable_watchdog.conf|2=
 +
kernel.nmi_watchdog = 0
 +
}}
 +
 
 +
or add {{ic|1=nmi_watchdog=0}} to the [[kernel line]] to disable it completely from early boot.
 +
 
 +
==== Writeback Time ====
 +
 
 +
Increasing the virtual memory dirty writeback time helps to aggregate disk I/O together, thus reducing spanned disk writes, and increasing power saving. To set the value to 60 seconds (default is 5 seconds):
 +
 
 +
{{hc|/etc/sysctl.d/dirty.conf|2=
 +
vm.dirty_writeback_centisecs = 6000
 +
}}
 +
 
 +
To do the same for journal commits on supported filesystems (e.g. ext4, btrfs...), use {{ic|1=commit=60}} as a option in [[fstab]].
 +
 
 +
Note that this value is modified as a side effect of the Laptop Mode setting below.
 +
See also [[sysctl#Virtual memory]] for other parameters affecting I/O performance and power saving.
 +
 
 +
==== Laptop Mode ====
 +
 
 +
See the [https://www.kernel.org/doc/Documentation/laptops/laptop-mode.txt kernel documentation] on the laptop mode 'knob.' ''"A sensible value for the knob is 5 seconds."''
 +
 
 +
{{hc|/etc/sysctl.d/laptop.conf|2=
 +
vm.laptop_mode = 5
 +
}}
 +
 
 +
{{Note|This setting is mainly relevant to spinning-disk drives.}}
 +
 
 +
=== Network interfaces ===
 +
 
 +
[[Wake-on-LAN]] can be a useful feature, but if you are not making use of it then it is simply draining extra power waiting for a magic packet while in suspend. You can adapt the [[Wake-on-LAN#udev]] rule to disable the feature for all ethernet interfaces.
 +
To enable powersaving with {{Pkg|iw}} on all wireless interfaces:
 +
 
 +
{{hc|/etc/udev/rules.d/'''81'''-wifi-powersave.rules|2=
 +
ACTION=="add", SUBSYSTEM=="net", KERNEL=="wl*", RUN+="/usr/bin/iw dev $name set power_save on"}}
 +
 
 +
The name of the configuration file is important. With the use of [[Network configuration#Change interface name|persistent device names]] in systemd, the above network rule, named lexicographically '''after''' {{ic|80-net-setup-link.rules}}, is applied after the device is renamed with a persistent name e.g. {{ic|wlan0}} renamed {{ic|wlp3s0}}.
 +
Be aware that the {{ic|RUN}} command is executed after all rules have been processed and must anyway use the persistent name, available in {{ic|$name}} for the matched device.
 +
 
 +
==== Intel wireless cards (iwlwifi) ====
 +
 
 +
Additional power saving functions of Intel wireless cards with {{ic|iwlwifi}} driver can be enabled by passing the correct parameters to the kernel module. Making them persistent can be achieved by adding the lines below to the {{ic|/etc/modprobe.d/iwlwifi.conf}} file:
 +
 
 +
options iwlwifi power_save=1
 +
 
 +
This option will probably increase your median latency:
 +
 
 +
options iwlwifi uapsd_disable=0
 +
 
 +
On kernels < 5.4 you can use this option, but it will probably decrease your maximum throughput:
 +
 
 +
options iwlwifi d0i3_disable=0
 +
 
 +
Depending on your wireless card one of these two options will apply.
 +
 
 +
options iwlmvm power_scheme=3
 +
 
 +
options iwldvm force_cam=0
 +
 
 +
You can check which one is relevant by checking which of these modules is running using
 +
 
 +
# lsmod | grep '^iwl.vm'
 +
 
 +
Keep in mind that these power saving options are experimental and can cause an unstable system.
 +
 
 +
=== Bus power management ===
 +
 
 +
==== Active State Power Management ====
 +
 
 +
If the computer is believed not to support [[Wikipedia:Active State Power Management|ASPM]] it will be disabled on boot:
 +
 
 +
# lspci -vv | grep 'ASPM.*abled;'
 +
 
 +
ASPM is handled by the BIOS, if ASPM is disabled it will be because [https://wireless.wiki.kernel.org/en/users/documentation/ASPM]:
 +
 
 +
# The BIOS disabled it for some reason (for conflicts?).
 +
# PCIE requires ASPM but L0s are optional (so L0s might be disabled and only L1 enabled).
 +
# The BIOS might not have been programmed for it.
 +
# The BIOS is buggy.
 +
 
 +
If believing the computer has support for ASPM it can be forced on for the kernel to handle with the {{ic|1=pcie_aspm=force}} [[kernel parameter]].
 +
 
 +
{{Warning|
 +
* Forcing on ASPM can cause a freeze/panic, so make sure you have a way to undo the option if it does not work.
 +
* On systems that do not support it forcing on ASPM can even increase power consumption.
 +
* This forces ASPM in kernel while it can still remain disabled in hardware and not work. To check whether this is the case the {{ic|dmesg {{!}} grep ASPM}} command can be used and if that is the case, hardware-specific Wiki article should be consulted.
 +
}}
 +
 
 +
To adjust to {{ic|powersave}} do (the following command will not work unless enabled):
 +
 
 +
# echo powersave > /sys/module/pcie_aspm/parameters/policy
 +
 
 +
By default it looks like this:
 +
 
 +
{{hc|$ cat /sys/module/pcie_aspm/parameters/policy|
 +
[default] performance powersave
 +
}}
 +
 
 +
==== PCI Runtime Power Management ====
 +
 
 +
{{hc|/etc/udev/rules.d/pci_pm.rules|2=
 +
SUBSYSTEM=="pci", ATTR{power/control}="auto"
 +
}}
 +
 
 +
The rule above powers all unused devices down, but some devices will not wake up again.
 +
To allow runtime power management only for devices that are known to work, use simple matching against vendor and device IDs (use {{ic|lspci -nn}} to get these values):
 +
 
 +
{{hc|/etc/udev/rules.d/pci_pm.rules|<nowiki>
 +
# whitelist for pci autosuspend
 +
SUBSYSTEM=="pci", ATTR{vendor}=="0x1234", ATTR{device}=="0x1234", ATTR{power/control}="auto"
 +
</nowiki>}}
 +
 
 +
Alternatively, to blacklist devices that are not working with PCI runtime power management and enable it for all other devices:
 +
 
 +
{{hc|/etc/udev/rules.d/pci_pm.rules|<nowiki>
 +
# blacklist for pci runtime power management
 +
SUBSYSTEM=="pci", ATTR{vendor}=="0x1234", ATTR{device}=="0x1234", ATTR{power/control}="on", GOTO="pci_pm_end"
 +
 
 +
SUBSYSTEM=="pci", ATTR{power/control}="auto"
 +
LABEL="pci_pm_end"
 +
</nowiki>}}
 +
 
 +
==== USB autosuspend ====
 +
 
 +
The Linux kernel can automatically suspend USB devices when they are not in use. This can sometimes save quite a bit of power, however some USB devices are not compatible with USB power saving and start to misbehave (common for USB mice/keyboards). [[udev]] rules based on whitelist or blacklist filtering can help to mitigate the problem.
 +
 
 +
The most simple and likely useless example is enabling autosuspend for all USB devices:
 +
 
 +
{{hc|/etc/udev/rules.d/50-usb_power_save.rules|<nowiki>
 +
ACTION=="add", SUBSYSTEM=="usb", TEST=="power/control", ATTR{power/control}="auto"
 +
</nowiki>}}
 +
 
 +
To allow autosuspend only for devices that are known to work, use simple matching against vendor and product IDs (use ''lsusb'' to get these values):
 +
 
 +
{{hc|/etc/udev/rules.d/50-usb_power_save.rules|<nowiki>
 +
# whitelist for usb autosuspend
 +
ACTION=="add", SUBSYSTEM=="usb", TEST=="power/control", ATTR{idVendor}=="05c6", ATTR{idProduct}=="9205", ATTR{power/control}="auto"
 +
</nowiki>}}
 +
 
 +
Alternatively, to blacklist devices that are not working with USB autosuspend and enable it for all other devices:
 +
 
 +
{{hc|/etc/udev/rules.d/50-usb_power_save.rules|<nowiki>
 +
# blacklist for usb autosuspend
 +
ACTION=="add", SUBSYSTEM=="usb", ATTR{idVendor}=="05c6", ATTR{idProduct}=="9205", GOTO="power_usb_rules_end"
 +
 
 +
ACTION=="add", SUBSYSTEM=="usb", TEST=="power/control", ATTR{power/control}="auto"
 +
LABEL="power_usb_rules_end"
 +
</nowiki>}}
 +
 
 +
The default autosuspend idle delay time is controlled by the {{ic|autosuspend}} parameter of the {{ic|usbcore}} [[kernel module]]. To set the delay to 5 seconds instead of the default 2 seconds:
 +
 
 +
{{hc|/etc/modprobe.d/usb-autosuspend.conf|<nowiki>
 +
options usbcore autosuspend=5
 +
</nowiki>}}
 +
 
 +
Similarly to {{ic|power/control}}, the delay time can be fine-tuned per device by setting the {{ic|power/autosuspend}} attribute.
 +
 
 +
See the [https://www.kernel.org/doc/Documentation/usb/power-management.txt Linux kernel documentation] for more information on USB power management.
 +
 
 +
==== SATA Active Link Power Management ====
 +
 
 +
{{Warning|SATA Active Link Power Management can lead to data loss on some devices. Do not enable this setting unless you have frequent backups.}}
 +
 
 +
Since Linux 4.15 there is a [https://hansdegoede.livejournal.com/18412.html new setting] called {{ic|med_power_with_dipm}} that matches the behaviour of Windows IRST driver settings and should not cause data loss with recent SSD/HDD drives. The power saving can be significant, ranging [https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=ebb82e3c79d2a956366d0848304a53648bd6350b from 1.0 to 1.5 Watts (when idle)]. It will become a default setting for Intel based laptops in Linux 4.16 [https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=ebb82e3c79d2a956366d0848304a53648bd6350b].
 +
 
 +
The current setting can be read from {{ic|/sys/class/scsi_host/host*/link_power_management_policy}} as follows:
 +
 
 +
# cat /sys/class/scsi_host/host*/link_power_management_policy
 +
 
 +
{| class="wikitable"
 +
|+ Available ALPM settings
 +
! Setting
 +
! Description
 +
! Power saving
 +
|-
 +
| max_performance
 +
| current default
 +
| None
 +
|-
 +
| medium_power
 +
| -
 +
| ~1.0 Watts
 +
|-
 +
| med_power_with_dipm
 +
| recommended setting
 +
| ~1.5 Watts
 +
|-
 +
| min_power
 +
| '''WARNING: possible data loss'''
 +
| ~1.5 Watts
 +
|}
 +
 
 +
{{hc|/etc/udev/rules.d/hd_power_save.rules|2=
 +
ACTION=="add", SUBSYSTEM=="scsi_host", KERNEL=="host*", ATTR{link_power_management_policy}="med_power_with_dipm"
 +
}}
 +
 
 +
{{Note|This adds latency when accessing a drive that has been idle, so it is one of the few settings that may be worth toggling based on whether you are on AC power.}}
 +
 
 +
=== Hard disk drive ===
 +
 
 +
See [[hdparm#Power management configuration]] for drive parameters that can be set.
 +
 
 +
Power saving is not effective when too many programs are frequently writing to the disk. Tracking all programs, and how and when they write to disk is the way to limit disk usage. Use {{Pkg|iotop}} to see which programs use the disk frequently. See [[Improving performance#Storage devices]] for other tips.
 +
 
 +
Also little things like setting the [[Fstab#atime options|noatime]] option can help. If enough RAM is available, consider disabling or limiting [[swappiness]] as it has the possibility to limit a good number of disk writes.
 +
 
 +
=== CD-ROM or DVD drive ===
 +
 
 +
See [[Udisks#Devices do not remain unmounted (udisks)]].
 +
 
 +
== Tools and scripts ==
 +
 
 +
{{Style|Merged from [[Power saving]], needs reorganization to fit into this page.}}
 +
 
 +
=== Using a script and an udev rule ===
 +
 
 +
Since systemd users can suspend and hibernate through {{ic|systemctl suspend}} or {{ic|systemctl hibernate}} and handle acpi events with {{ic|/etc/systemd/logind.conf}}, it might be interesting to remove ''pm-utils'' and [[acpid]]. There is just one thing systemd cannot do (as of systemd-204): power management depending on whether the system is running on AC or battery. To fill this gap, you can create a single [[udev]] rule that runs a script when the AC adapter is plugged and unplugged:
 +
 
 +
{{hc|/etc/udev/rules.d/powersave.rules|2=<nowiki>
 +
SUBSYSTEM=="power_supply", ATTR{online}=="0", RUN+="/path/to/your/script true"
 +
SUBSYSTEM=="power_supply", ATTR{online}=="1", RUN+="/path/to/your/script false"
 +
</nowiki>}}
 +
 
 +
{{Note|You can use the same script that ''pm-powersave'' uses. You just have to make it executable and place it somewhere else (for example {{ic|/usr/local/bin/}}).}}
 +
 
 +
Examples of powersave scripts:
 +
 
 +
* [https://github.com/supplantr/ftw ftw], package: {{AUR|ftw-git}}
 +
* [https://github.com/Unia/powersave powersave]
 +
* [https://github.com/quequotion/pantheon-bzr-qq/blob/master/EXTRAS/indicator-powersave/throttle throttle], from {{AUR|indicator-powersave}}
 +
 
 +
The above udev rule should work as expected, but if your power settings are not updated after a suspend or hibernate cycle, you should add a script in {{ic|/usr/lib/systemd/system-sleep/}} with the following contents:
 +
 
 +
{{hc|/usr/lib/systemd/system-sleep/00powersave|<nowiki>
 +
#!/bin/sh
 +
 
 +
case $1 in
 +
    pre) /path/to/your/script false ;;
 +
    post)     
 +
if cat /sys/class/power_supply/AC0/online | grep 0 > /dev/null 2>&1
 +
then
 +
    /path/to/your/script true
 +
else
 +
    /path/to/your/script false
 +
fi
 +
    ;;
 +
esac
 +
exit 0
 +
</nowiki>}}
 +
 
 +
Do not forget to make it executable!
 +
 
 +
{{Note|Be aware that AC0 may be different for your laptop, change it if that is the case.}}
 +
 
 +
=== Print power settings ===
 +
 
 +
This script prints power settings and a variety of other properties for USB and PCI devices.  Note that root permissions are needed to see all settings.
 +
 
 +
{{bc|<nowiki>
 +
#!/bin/bash
 +
 
 +
for i in $(find /sys/devices -name "bMaxPower")
 +
do
 +
busdir=${i%/*}
 +
busnum=$(<$busdir/busnum)
 +
devnum=$(<$busdir/devnum)
 +
title=$(lsusb -s $busnum:$devnum)
  
==== Troubleshooting ====
+
printf "\n\n+++ %s\n  -%s\n" "$title" "$busdir"
  
===== Delayed lid switch action =====
+
for ff in $(find $busdir/power -type f ! -empty 2>/dev/null)
 +
do
 +
v=$(cat $ff 2>/dev/null|tr -d "\n")
 +
[[ ${#v} -gt 0 ]] && echo -e " ${ff##*/}=$v";
 +
v=;
 +
done | sort -g;
 +
done;
  
When performing lid switches in short succession, ''logind'' will delay the suspend action for up to 90s to detect possible docks. [http://lists.freedesktop.org/archives/systemd-devel/2015-January/027131.html] This delay will be configurable with systemd v210. [http://cgit.freedesktop.org/systemd/systemd/commit/?id=9d10cbee89ca7f82d29b9cb27bef11e23e3803ba]
+
printf "\n\n\n+++ %s\n" "Kernel Modules"
 +
for mod in $(lspci -k | sed -n '/in use:/s,^.*: ,,p' | sort -u)
 +
do
 +
echo "+ $mod";
 +
systool -v -m $mod 2> /dev/null | sed -n "/Parameters:/,/^$/p";
 +
done
 +
</nowiki>}}
  
 
== See also ==
 
== See also ==
  
* [[Laptop#Power management]] describes power management specific for laptops - especially battery monitoring.
+
* [http://www.thinkwiki.org/wiki/How_to_reduce_power_consumption ThinkWiki:How to reduce power consumption]
* [[General recommendations#Power management]]
+
* [http://ivanvojtko.blogspot.sk/2016/04/how-to-get-longer-battery-life-on-linux.html How to get longer battery life on Linux]

Latest revision as of 18:23, 1 April 2020

Power management is a feature that turns off the power or switches system's components to a low-power state when inactive.

In Arch Linux, power management consists of two main parts:

  1. Configuration of the Linux kernel, which interacts with the hardware.
  2. Configuration of userspace tools, which interact with the kernel and react to its events. Many userspace tools also allow to modify kernel configuration in a "user-friendly" way. See #Userspace tools for the options.

Userspace tools

Using these tools can replace setting a lot of settings by hand. Only run one of these tools to avoid possible conflicts as they all work more or less similarly. Have a look at the power management category to get an overview on what power management options exist in Arch Linux.

These are the more popular scripts and tools designed to help power saving:

Console

  • acpid — A daemon for delivering ACPI power management events with netlink support.
http://sourceforge.net/projects/acpid2/ || acpid
  • Laptop Mode Tools — Utility to configure laptop power saving settings, considered by many to be the de facto utility for power saving though may take a bit of configuration.
https://github.com/rickysarraf/laptop-mode-tools || laptop-mode-toolsAUR
  • libsmbios — Library and tools for interacting with Dell SMBIOS tables.
https://github.com/dell/libsmbios || libsmbios
  • powertop — A tool to diagnose issues with power consumption and power management to help set power saving settings.
https://01.org/powertop/ || powertop
  • systemd — A system and service manager.
https://freedesktop.org/wiki/Software/systemd/ || systemd
  • TLP — Advanced power management for Linux.
http://linrunner.de/tlp || tlp

Graphical

  • batterymon-clone — Simple battery monitor tray icon.
https://github.com/jareksed/batterymon-clone || batterymon-cloneAUR
  • cbatticon — Lightweight and fast battery icon that sits in your system tray.
https://github.com/valr/cbatticon || cbatticon
  • GNOME Power Statistics — System power information and statistics for GNOME.
https://gitlab.gnome.org/GNOME/gnome-power-manager || gnome-power-manager
  • KDE Power Devil — Power management module for Plasma.
https://userbase.kde.org/Power_Devil[dead link 2020-04-01 ⓘ] || powerdevil powerdevil-lightAUR
  • LXQt Power Management — Power management module for LXQt.
https://github.com/lxqt/lxqt-powermanagement || lxqt-powermanagement
  • MATE Power Management — Power management tool for MATE.
https://github.com/mate-desktop/mate-power-manager || mate-power-manager
  • MATE Power Statistics — System power information and statistics for MATE.
https://github.com/mate-desktop/mate-power-manager || mate-power-manager
  • powerkit — Desktop independent power manager.
https://github.com/rodlie/powerkit || powerkitAUR
  • Xfce Power Manager — Power manager for Xfce.
https://docs.xfce.org/xfce/xfce4-power-manager/start || xfce4-power-manager
  • vattery — Battery monitoring application written in Vala that will display the status of a laptop battery in a system tray.
http://www.jezra.net/projects/vattery[dead link 2020-04-01 ⓘ] || vatteryAUR

Power management with systemd

ACPI events

systemd handles some power-related ACPI events, whose actions can be configured in /etc/systemd/logind.conf or /etc/systemd/logind.conf.d/*.conf — see logind.conf(5). On systems with no dedicated power manager, this may replace the acpid daemon which is usually used to react to these ACPI events.

The specified action for each event can be one of ignore, poweroff, reboot, halt, suspend, hibernate, hybrid-sleep, suspend-then-hibernate, lock or kexec. In case of hibernation and suspension, they must be properly set up. If an event is not configured, systemd will use a default action.

Event handler Description Default action
HandlePowerKey Triggered when the power key/button is pressed. poweroff
HandleSuspendKey Triggered when the suspend key/button is pressed. suspend
HandleHibernateKey Triggered when the hibernate key/button is pressed. hibernate
HandleLidSwitch Triggered when the lid is closed, except in the cases below. suspend
HandleLidSwitchDocked Triggered when the lid is closed if the system is inserted in a docking station, or more than one display is connected. ignore
HandleLidSwitchExternalPower Triggered when the lid is closed if the system is connected to external power. action set for HandleLidSwitch

To apply any changes, signal systemd-logind with HUP:

# kill -s HUP $(systemctl show --property MainPID systemd-logind | cut -d= -f2)
Note: systemd cannot handle AC and Battery ACPI events, so if you use Laptop Mode Tools or other similar tools acpid is still required.

Power managers

Some desktop environments include power managers which inhibit (temporarily turn off) some or all of the systemd ACPI settings. If such a power manager is running, then the actions for ACPI events can be configured in the power manager alone. Changes to /etc/systemd/logind.conf or /etc/systemd/logind.conf.d/*.conf need be made only if you wish to configure behaviour for a particular event that is not inhibited by the power manager.

Note that if the power manager does not inhibit systemd for the appropriate events you can end up with a situation where systemd suspends your system and then when the system is woken up the other power manager suspends it again. As of December 2016, the power managers of KDE, GNOME, Xfce and MATE issue the necessary inhibited commands. If the inhibited commands are not being issued, such as when using acpid or others to handle ACPI events, set the Handle options to ignore. See also systemd-inhibit(1).

xss-lock

xss-lock subscribes to the systemd-events suspend, hibernate, lock-session, and unlock-session with appropriate actions (run locker and wait for user to unlock or kill locker). xss-lock also reacts to DPMS events and runs or kills the locker in response.

Start xss-lock in your autostart, for example

xss-lock -- i3lock -n -i background_image.png &

Suspend and hibernate

systemd provides commands to suspend to RAM or hibernate using the kernel's native suspend/resume functionality. There are also mechanisms to add hooks to customize pre- and post-suspend actions.

systemctl suspend should work out of the box, for systemctl hibernate to work on your system you need to follow the instructions at Suspend and hibernate#Hibernation.

There are also two modes combining suspend and hibernate:

  • systemctl hybrid-sleep suspends the system both to RAM and disk, so a complete power loss does not result in lost data. This mode is also called suspend to both.
  • systemctl suspend-then-hibernate initially suspends the system to RAM and if it is not interrupted within the delay specified by HibernateDelaySec in systemd-sleep.conf(5), then the system will be woken using an RTC alarm and hibernated.
Note: systemd can also use other suspend backends (such as Uswsusp), in addition to the default kernel backend, in order to put the computer to sleep or hibernate. See Uswsusp#With systemd for an example.

Hybrid-sleep on suspend or hibernation request

It is possible to configure systemd to always do a hybrid-sleep even on a suspend or hibernation request.

The default suspend and hibernation action can be configured in the /etc/systemd/sleep.conf file. To set both actions to hybrid-sleep:

/etc/systemd/sleep.conf
[Sleep]
# suspend=hybrid-sleep
SuspendMode=suspend
SuspendState=disk
# hibernate=hybrid-sleep
HibernateMode=suspend
HibernateState=disk

See the sleep.conf.d(5) manual page for details and the linux kernel documentation on power states.

Sleep hooks

Suspend/resume service files

Service files can be hooked into suspend.target, hibernate.target, sleep.target, hybrid-sleep.target and suspend-then-hibernate.target to execute actions before or after suspend/hibernate. Separate files should be created for user actions and root/system actions. Enable the suspend@user and resume@user services to have them started at boot. Examples:

/etc/systemd/system/suspend@.service
[Unit]
Description=User suspend actions
Before=sleep.target

[Service]
User=%I
Type=forking
Environment=DISPLAY=:0
ExecStartPre= -/usr/bin/pkill -u %u unison ; /usr/local/bin/music.sh stop
ExecStart=/usr/bin/sflock
ExecStartPost=/usr/bin/sleep 1

[Install]
WantedBy=sleep.target
/etc/systemd/system/resume@.service
[Unit]
Description=User resume actions
After=suspend.target

[Service]
User=%I
Type=simple
ExecStart=/usr/local/bin/ssh-connect.sh

[Install]
WantedBy=suspend.target
Note: As screen lockers may return before the screen is "locked", the screen may flash on resuming from suspend. Adding a small delay via ExecStartPost=/usr/bin/sleep 1 helps prevent this.

For root/system actions (enable the root-resume and root-suspend services to have them started at boot):

/etc/systemd/system/root-suspend.service
[Unit]
Description=Local system suspend actions
Before=sleep.target

[Service]
Type=simple
ExecStart=-/usr/bin/pkill sshfs

[Install]
WantedBy=sleep.target
/etc/systemd/system/root-resume.service
[Unit]
Description=Local system resume actions
After=suspend.target

[Service]
Type=simple
ExecStart=/usr/bin/systemctl restart mnt-media.automount

[Install]
WantedBy=suspend.target
Tip: A couple of handy hints about these service files (more in systemd.service(5)):
  • If Type=oneshot then you can use multiple ExecStart= lines. Otherwise only one ExecStart line is allowed. You can add more commands with either ExecStartPre or by separating commands with a semicolon (see the first example above; note the spaces before and after the semicolon, as they are required).
  • A command prefixed with - will cause a non-zero exit status to be ignored and treated as a successful command.
  • The best place to find errors when troubleshooting these service files is of course with journalctl.

Combined Suspend/resume service file

With the combined suspend/resume service file, a single hook does all the work for different phases (sleep/resume) and for different targets (suspend/hibernate/hybrid-sleep).

Example and explanation:

/etc/systemd/system/wicd-sleep.service
[Unit]
Description=Wicd sleep hook
Before=sleep.target
StopWhenUnneeded=yes

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=-/usr/share/wicd/daemon/suspend.py
ExecStop=-/usr/share/wicd/daemon/autoconnect.py

[Install]
WantedBy=sleep.target
  • RemainAfterExit=yes: After started, the service is considered active until it is explicitly stopped.
  • StopWhenUnneeded=yes: When active, the service will be stopped if no other active service requires it. In this specific example, it will be stopped after sleep.target is stopped.
  • Because sleep.target is pulled in by suspend.target, hibernate.target and hybrid-sleep.target and because sleep.target itself is a StopWhenUnneeded service, the hook is guaranteed to start/stop properly for different tasks.

Hooks in /usr/lib/systemd/system-sleep

systemd runs all executables in /usr/lib/systemd/system-sleep/, passing two arguments to each of them:

  • Argument 1: either pre or post, depending on whether the machine is going to sleep or waking up
  • Argument 2: suspend, hibernate or hybrid-sleep, depending on which is being invoked

systemd will run these scripts concurrently and not one after another.

The output of any custom script will be logged by systemd-suspend.service, systemd-hibernate.service or systemd-hybrid-sleep.service. You can see its output in systemd's journalctl:

# journalctl -b -u systemd-suspend.service
Note: You can also use sleep.target, suspend.target, hibernate.target or hybrid-sleep.target to hook units into the sleep state logic instead of using custom scripts.

An example of a custom sleep script:

/usr/lib/systemd/system-sleep/example.sh
#!/bin/sh
case $1/$2 in
  pre/*)
    echo "Going to $2..."
    ;;
  post/*)
    echo "Waking up from $2..."
    ;;
esac

Do not forget to make your script executable:

# chmod a+x /usr/lib/systemd/system-sleep/example.sh

See systemd.special(7) and systemd-sleep(8) for more details.

Troubleshooting

Delayed lid switch action

When performing lid switches in short succession, logind will delay the suspend action for up to 90s to detect possible docks. [1] This delay was made configurable with systemd v220:[2]

/etc/systemd/logind.conf
...
HoldoffTimeoutSec=30s
...

Suspend from corresponding laptop Fn key not working

If, regardless of the setting in logind.conf, the sleep button does not work (pressing it does not even produce a message in syslog), then logind is probably not watching the keyboard device. [3] Do:

# journalctl --grep="Watching system buttons"

You might see something like this:

May 25 21:28:19 vmarch.lan systemd-logind[210]: Watching system buttons on /dev/input/event2 (Power Button)
May 25 21:28:19 vmarch.lan systemd-logind[210]: Watching system buttons on /dev/input/event3 (Sleep Button)
May 25 21:28:19 vmarch.lan systemd-logind[210]: Watching system buttons on /dev/input/event4 (Video Bus)

Notice no keyboard device. Now obtain ATTRS{name} for the parent keyboard device [4] :

# udevadm info -a /dev/input/by-path/*-kbd
...
KERNEL=="event0"
...
ATTRS{name}=="AT Translated Set 2 keyboard"

Now write a custom udev rule to add the "power-switch" tag:

/etc/udev/rules.d/70-power-switch-my.rules
ACTION=="remove", GOTO="power_switch_my_end"
SUBSYSTEM=="input", KERNEL=="event*", ATTRS{name}=="AT Translated Set 2 keyboard", TAG+="power-switch"
LABEL="power_switch_my_end"

Tango-edit-clear.pngThis article or section needs language, wiki syntax or style improvements. See Help:Style for reference.Tango-edit-clear.png

Reason: Explicit systemctl commands should not be provided. (Discuss in Talk:Power management#)

Restart services and reload rules:

# systemctl restart systemd-udevd.service
# udevadm trigger
# systemctl restart systemd-logind.service

Now you should see Watching system buttons on /dev/input/event0 in syslog.

Power saving

Note: See Laptop#Power management for power management specific to laptops, such as battery monitoring.

This section is a reference for creating custom scripts and power saving settings such as by udev rules. Make sure that the settings are not managed by some other utility to avoid conflicts.

Almost all of the features listed here are worth using whether or not the computer is on AC or battery power. Most have negligible performance impact and are just not enabled by default because of commonly broken hardware/drivers. Reducing power usage means reducing heat, which can even lead to higher performance on a modern Intel or AMD CPU, thanks to dynamic overclocking.

Processors with HWP (Hardware P-state) support

Merge-arrows-2.pngThis article or section is a candidate for merging with CPU frequency scaling.Merge-arrows-2.png

Notes: More context in the main article. (Discuss in Talk:Power management#)

The available energy preferences of a HWP supported processor are default performance balance_performance balance_power power.

This can be validated by $ cat /sys/devices/system/cpu/cpufreq/policy?/energy_performance_available_preferences

To conserve more energy, you can config by creating the following file:

/etc/tmpfiles.d/energy_performance_preference.conf
w /sys/devices/system/cpu/cpufreq/policy?/energy_performance_preference - - - - balance_power

See the systemd-tmpfiles(8) and tmpfiles.d(5) man pages for details.

Audio

Kernel

By default, audio power saving is turned off by most drivers. It can be enabled by setting the power_save parameter; a time (in seconds) to go into idle mode. To idle the audio card after one second, create the following file for Intel soundcards.

/etc/modprobe.d/audio_powersave.conf
options snd_hda_intel power_save=1

Alternatively, use the following for ac97:

options snd_ac97_codec power_save=1
Note:
  • To retrieve the manufacturer and the corresponding kernel driver which is used for your sound card, run lspci -k.
  • Toggling the audio card's power state can cause a popping sound or noticeable latency on some broken hardware.

It is also possible to further reduce the audio power requirements by disabling the HDMI audio output, which can done by blacklisting the appropriate kernel modules (e.g. snd_hda_codec_hdmi in case of Intel hardware).

PulseAudio

By default, PulseAudio suspends any audio sources that have become idle for too long. When using an external USB microphone, recordings may start with a pop sound. As a workaround, comment out the following line in /etc/pulse/default.pa:

load-module module-suspend-on-idle

Afterwards, restart PulseAudio with systemctl restart --user pulseaudio.

Backlight

See Backlight.

Bluetooth

Tango-view-fullscreen.pngThis article or section needs expansion.Tango-view-fullscreen.png

Reason: The device should likely be disabled with hciconfig first. (Discuss in Talk:Power management#)

To disable bluetooth completely, blacklist the btusb and bluetooth modules.

To turn off bluetooth only temporarily, use rfkill:

# rfkill block bluetooth

Or with udev rule:

/etc/udev/rules.d/50-bluetooth.rules
# disable bluetooth
SUBSYSTEM=="rfkill", ATTR{type}=="bluetooth", ATTR{state}="0"

Web camera

If you will not use integrated web camera then blacklist the uvcvideo module.

Kernel parameters

This section uses configs in /etc/sysctl.d/, which is "a drop-in directory for kernel sysctl parameters." See The New Configuration Files and more specifically sysctl.d(5) for more information.

Disabling NMI watchdog

Tango-view-fullscreen.pngThis article or section needs expansion.Tango-view-fullscreen.png

Reason: This or nowatchdog as can be seen in Improving performance#Watchdogs (Discuss in Talk:Power management#)

The NMI watchdog is a debugging feature to catch hardware hangs that cause a kernel panic. On some systems it can generate a lot of interrupts, causing a noticeable increase in power usage:

/etc/sysctl.d/disable_watchdog.conf
kernel.nmi_watchdog = 0

or add nmi_watchdog=0 to the kernel line to disable it completely from early boot.

Writeback Time

Increasing the virtual memory dirty writeback time helps to aggregate disk I/O together, thus reducing spanned disk writes, and increasing power saving. To set the value to 60 seconds (default is 5 seconds):

/etc/sysctl.d/dirty.conf
vm.dirty_writeback_centisecs = 6000

To do the same for journal commits on supported filesystems (e.g. ext4, btrfs...), use commit=60 as a option in fstab.

Note that this value is modified as a side effect of the Laptop Mode setting below. See also sysctl#Virtual memory for other parameters affecting I/O performance and power saving.

Laptop Mode

See the kernel documentation on the laptop mode 'knob.' "A sensible value for the knob is 5 seconds."

/etc/sysctl.d/laptop.conf
vm.laptop_mode = 5
Note: This setting is mainly relevant to spinning-disk drives.

Network interfaces

Wake-on-LAN can be a useful feature, but if you are not making use of it then it is simply draining extra power waiting for a magic packet while in suspend. You can adapt the Wake-on-LAN#udev rule to disable the feature for all ethernet interfaces. To enable powersaving with iw on all wireless interfaces:

/etc/udev/rules.d/81-wifi-powersave.rules
ACTION=="add", SUBSYSTEM=="net", KERNEL=="wl*", RUN+="/usr/bin/iw dev $name set power_save on"

The name of the configuration file is important. With the use of persistent device names in systemd, the above network rule, named lexicographically after 80-net-setup-link.rules, is applied after the device is renamed with a persistent name e.g. wlan0 renamed wlp3s0. Be aware that the RUN command is executed after all rules have been processed and must anyway use the persistent name, available in $name for the matched device.

Intel wireless cards (iwlwifi)

Additional power saving functions of Intel wireless cards with iwlwifi driver can be enabled by passing the correct parameters to the kernel module. Making them persistent can be achieved by adding the lines below to the /etc/modprobe.d/iwlwifi.conf file:

options iwlwifi power_save=1

This option will probably increase your median latency:

options iwlwifi uapsd_disable=0

On kernels < 5.4 you can use this option, but it will probably decrease your maximum throughput:

options iwlwifi d0i3_disable=0

Depending on your wireless card one of these two options will apply.

options iwlmvm power_scheme=3
options iwldvm force_cam=0

You can check which one is relevant by checking which of these modules is running using

# lsmod | grep '^iwl.vm'

Keep in mind that these power saving options are experimental and can cause an unstable system.

Bus power management

Active State Power Management

If the computer is believed not to support ASPM it will be disabled on boot:

# lspci -vv | grep 'ASPM.*abled;'

ASPM is handled by the BIOS, if ASPM is disabled it will be because [5]:

  1. The BIOS disabled it for some reason (for conflicts?).
  2. PCIE requires ASPM but L0s are optional (so L0s might be disabled and only L1 enabled).
  3. The BIOS might not have been programmed for it.
  4. The BIOS is buggy.

If believing the computer has support for ASPM it can be forced on for the kernel to handle with the pcie_aspm=force kernel parameter.

Warning:
  • Forcing on ASPM can cause a freeze/panic, so make sure you have a way to undo the option if it does not work.
  • On systems that do not support it forcing on ASPM can even increase power consumption.
  • This forces ASPM in kernel while it can still remain disabled in hardware and not work. To check whether this is the case the dmesg | grep ASPM command can be used and if that is the case, hardware-specific Wiki article should be consulted.

To adjust to powersave do (the following command will not work unless enabled):

# echo powersave > /sys/module/pcie_aspm/parameters/policy

By default it looks like this:

$ cat /sys/module/pcie_aspm/parameters/policy
[default] performance powersave

PCI Runtime Power Management

/etc/udev/rules.d/pci_pm.rules
SUBSYSTEM=="pci", ATTR{power/control}="auto"

The rule above powers all unused devices down, but some devices will not wake up again. To allow runtime power management only for devices that are known to work, use simple matching against vendor and device IDs (use lspci -nn to get these values):

/etc/udev/rules.d/pci_pm.rules
# whitelist for pci autosuspend
SUBSYSTEM=="pci", ATTR{vendor}=="0x1234", ATTR{device}=="0x1234", ATTR{power/control}="auto"

Alternatively, to blacklist devices that are not working with PCI runtime power management and enable it for all other devices:

/etc/udev/rules.d/pci_pm.rules
# blacklist for pci runtime power management
SUBSYSTEM=="pci", ATTR{vendor}=="0x1234", ATTR{device}=="0x1234", ATTR{power/control}="on", GOTO="pci_pm_end"

SUBSYSTEM=="pci", ATTR{power/control}="auto"
LABEL="pci_pm_end"

USB autosuspend

The Linux kernel can automatically suspend USB devices when they are not in use. This can sometimes save quite a bit of power, however some USB devices are not compatible with USB power saving and start to misbehave (common for USB mice/keyboards). udev rules based on whitelist or blacklist filtering can help to mitigate the problem.

The most simple and likely useless example is enabling autosuspend for all USB devices:

/etc/udev/rules.d/50-usb_power_save.rules
ACTION=="add", SUBSYSTEM=="usb", TEST=="power/control", ATTR{power/control}="auto"

To allow autosuspend only for devices that are known to work, use simple matching against vendor and product IDs (use lsusb to get these values):

/etc/udev/rules.d/50-usb_power_save.rules
# whitelist for usb autosuspend
ACTION=="add", SUBSYSTEM=="usb", TEST=="power/control", ATTR{idVendor}=="05c6", ATTR{idProduct}=="9205", ATTR{power/control}="auto"

Alternatively, to blacklist devices that are not working with USB autosuspend and enable it for all other devices:

/etc/udev/rules.d/50-usb_power_save.rules
# blacklist for usb autosuspend
ACTION=="add", SUBSYSTEM=="usb", ATTR{idVendor}=="05c6", ATTR{idProduct}=="9205", GOTO="power_usb_rules_end"

ACTION=="add", SUBSYSTEM=="usb", TEST=="power/control", ATTR{power/control}="auto"
LABEL="power_usb_rules_end"

The default autosuspend idle delay time is controlled by the autosuspend parameter of the usbcore kernel module. To set the delay to 5 seconds instead of the default 2 seconds:

/etc/modprobe.d/usb-autosuspend.conf
options usbcore autosuspend=5

Similarly to power/control, the delay time can be fine-tuned per device by setting the power/autosuspend attribute.

See the Linux kernel documentation for more information on USB power management.

SATA Active Link Power Management

Warning: SATA Active Link Power Management can lead to data loss on some devices. Do not enable this setting unless you have frequent backups.

Since Linux 4.15 there is a new setting called med_power_with_dipm that matches the behaviour of Windows IRST driver settings and should not cause data loss with recent SSD/HDD drives. The power saving can be significant, ranging from 1.0 to 1.5 Watts (when idle). It will become a default setting for Intel based laptops in Linux 4.16 [6].

The current setting can be read from /sys/class/scsi_host/host*/link_power_management_policy as follows:

# cat /sys/class/scsi_host/host*/link_power_management_policy
Available ALPM settings
Setting Description Power saving
max_performance current default None
medium_power - ~1.0 Watts
med_power_with_dipm recommended setting ~1.5 Watts
min_power WARNING: possible data loss ~1.5 Watts
/etc/udev/rules.d/hd_power_save.rules
ACTION=="add", SUBSYSTEM=="scsi_host", KERNEL=="host*", ATTR{link_power_management_policy}="med_power_with_dipm"
Note: This adds latency when accessing a drive that has been idle, so it is one of the few settings that may be worth toggling based on whether you are on AC power.

Hard disk drive

See hdparm#Power management configuration for drive parameters that can be set.

Power saving is not effective when too many programs are frequently writing to the disk. Tracking all programs, and how and when they write to disk is the way to limit disk usage. Use iotop to see which programs use the disk frequently. See Improving performance#Storage devices for other tips.

Also little things like setting the noatime option can help. If enough RAM is available, consider disabling or limiting swappiness as it has the possibility to limit a good number of disk writes.

CD-ROM or DVD drive

See Udisks#Devices do not remain unmounted (udisks).

Tools and scripts

Tango-edit-clear.pngThis article or section needs language, wiki syntax or style improvements. See Help:Style for reference.Tango-edit-clear.png

Reason: Merged from Power saving, needs reorganization to fit into this page. (Discuss in Talk:Power management#)

Using a script and an udev rule

Since systemd users can suspend and hibernate through systemctl suspend or systemctl hibernate and handle acpi events with /etc/systemd/logind.conf, it might be interesting to remove pm-utils and acpid. There is just one thing systemd cannot do (as of systemd-204): power management depending on whether the system is running on AC or battery. To fill this gap, you can create a single udev rule that runs a script when the AC adapter is plugged and unplugged:

/etc/udev/rules.d/powersave.rules
SUBSYSTEM=="power_supply", ATTR{online}=="0", RUN+="/path/to/your/script true"
SUBSYSTEM=="power_supply", ATTR{online}=="1", RUN+="/path/to/your/script false"
Note: You can use the same script that pm-powersave uses. You just have to make it executable and place it somewhere else (for example /usr/local/bin/).

Examples of powersave scripts:

The above udev rule should work as expected, but if your power settings are not updated after a suspend or hibernate cycle, you should add a script in /usr/lib/systemd/system-sleep/ with the following contents:

/usr/lib/systemd/system-sleep/00powersave
#!/bin/sh

case $1 in
    pre) /path/to/your/script false ;;
    post)       
	if cat /sys/class/power_supply/AC0/online | grep 0 > /dev/null 2>&1
	then
    		/path/to/your/script true	
	else
    		/path/to/your/script false
	fi
    ;;
esac
exit 0

Do not forget to make it executable!

Note: Be aware that AC0 may be different for your laptop, change it if that is the case.

Print power settings

This script prints power settings and a variety of other properties for USB and PCI devices. Note that root permissions are needed to see all settings.

#!/bin/bash

for i in $(find /sys/devices -name "bMaxPower")
do
	busdir=${i%/*}
	busnum=$(<$busdir/busnum)
	devnum=$(<$busdir/devnum)
	title=$(lsusb -s $busnum:$devnum)

	printf "\n\n+++ %s\n  -%s\n" "$title" "$busdir"

	for ff in $(find $busdir/power -type f ! -empty 2>/dev/null)
	do
		v=$(cat $ff 2>/dev/null|tr -d "\n")
		[[ ${#v} -gt 0 ]] && echo -e " ${ff##*/}=$v";
		v=;
	done | sort -g;
done;

printf "\n\n\n+++ %s\n" "Kernel Modules"
for mod in $(lspci -k | sed -n '/in use:/s,^.*: ,,p' | sort -u)
do
	echo "+ $mod";
	systool -v -m $mod 2> /dev/null | sed -n "/Parameters:/,/^$/p";
done

See also