Power management (Español)

From ArchWiki
Jump to navigation Jump to search

Tango-preferences-desktop-locale.pngEste artículo o sección necesita ser traducido.Tango-preferences-desktop-locale.png

Notas: Traducción desactualizada (Discusión en Talk:Power management (Español)#)

Power management es una característica que apaga la alimentación o los interruptores del sistema para un menor consume de energía cuando está incactivo.

En Arch Linux, la administración de energía consiste en dos partes principales:

  1. Configurar el kernel de Linux, que interactua con el hardware.
  2. Las herramientas de configuración del espacio del usuario pueden interactuar con el núcleo y reaccionar a sus eventos. Muchas de estás herramientas le permiten también modificar la configuración del núcleo de una forma fácil. Vea #Herramientas de espacio del usuario para las opciones.


Herramientas de espacio del usuario

Utilizando estas herramientas puede remplazar la configuración de muchos ajustes a mano. Solo ejecute una de estas herramientas para evitar conflictos ya que todas trabajan más o menos de la misma forma. Eche un vistazo a la categoria de administracion de energía para tener una noción de las opciones de administración energética que existen en Arch Linux.

Aquí están los scripts y herramientas más populares para ahorrar energía:

Consola

  • acpid — Un demonio para llevar los eventos de energía ACPI con soporte netlink.
http://sourceforge.net/projects/acpid2/ || acpid
  • Laptop Mode Tools — Utilidad para configurar los ajustes de administración de energía de los portátiles considerado por muchos una utilidad clave para ahorrar energía, puede requerir un poco de configuración.
https://github.com/rickysarraf/laptop-mode-tools || laptop-mode-toolsAUR
  • powertop — Una herramienta para diagnosticar problemas con el consumo y la administración de energía para ayudarle a establecer ajustes de ahorro de energía.
https://01.org/powertop/ || powertop
  • systemd — Un administrador de servicios y del sistema.
https://freedesktop.org/wiki/Software/systemd/ || systemd
  • TLP — Administración avanzada de energía de Linux.
http://linrunner.de/tlp || tlp

Gráficos

  • batterymon-clone — Simplemente un icono de la bandeja del sistema del monitor de la batería.
https://github.com/jareksed/batterymon-clone || batterymon-cloneAUR
  • cbatticon — Icono de batería ligero y rápido que se encuentra en la bandeja del sistema.
https://github.com/valr/cbatticon || cbatticon
  • GNOME Power Statistics — Información y estadísticas de la energía del sistema para GNOME.
https://gitlab.gnome.org/GNOME/gnome-power-manager || gnome-power-manager
  • KDE Power Devil — Módulo de administración de energía para Plasma.
https://userbase.kde.org/Power_Devil || powerdevil powerdevil-lightAUR
  • LXQt Power Management — Módulo de administración de energía para LXQt.
https://github.com/lxqt/lxqt-powermanagement || lxqt-powermanagement
  • MATE Power Management — Herramientas de administración de energía para MATE.
https://github.com/mate-desktop/mate-power-manager || mate-power-manager
  • MATE Power Statistics — Información y estadísticas de la energía del sistema para MATE.
https://github.com/mate-desktop/mate-power-manager || mate-power-manager
  • Xfce Power Manager — Administración de energía para Xfce.
https://docs.xfce.org/xfce/xfce4-power-manager/start || xfce4-power-manager
  • vattery — Aplicación de monitorización de la batería escrito en Vala que muestra el estado de la batería del portátil en la bandeja del sistema.
http://www.jezra.net/projects/vattery || vatteryAUR

Administración de energía con systemd

Eventos de ACPI

Systemd puede manejar algunos eventos ACPI («Interfaz Avanzada de Configuración y Energía») cuyas acciones pueden configurarse en /etc/systemd/logind.conf o en /etc/systemd/logind.conf.d/*.conf — vea logind.conf(5). En sistemas que no tienen un administrador de energía dedicado puede que los ajustes se remplacen con el demonio acpid que se usa normalmente para reaccionar a los eventos ACPI.

La acción especificada para cada evento puede ser una de las siguientes: ignore, poweroff, reboot, halt, suspend, hibernate, hybrid-sleep, suspend-then-hibernate, lock o kexec. En caso de hibernar y suspender deben ajustarse apropiadamente. Si un evento no esta configurado systemd utilizara la acción por defecto.

Controlador de evento Descripción Acción por defecto
HandlePowerKey Especifica qué acción se invoca cuando el botón de encendido se pulsa. poweroff
HandleSuspendKey Especifica qué acción se invoca cuando se pulsa el botón de suspensión. suspend
HandleHibernateKey Especifica qué acción se invoca cuando se pulsa el botón de hibernación. hibernate
HandleLidSwitch Especifica qué acción se invoca cuando la tapa del portátil se cierra a excepción de los casos descritos más abajo. suspend
HandleLidSwitchDocked Especifica que acción se invoca la tapa del portátil se cierra si el sistema está insertado en una estación de acoplamiento o si hay más de una pantalla conectada. ignore
HandleLidSwitchExternalPower TEspecifica que acción se invoca la tapa del portátil se cierra si el sistema está conectado a una fuente de corriente externa. Acción establecida por HandleLidSwitch

Para aplicar cualquier cambio reinicie systemd-logind.service (esto terminará todas las sesiones iniciadas).

Nota: Systemd no puede manejar los eventos de AC y de Batería que realiza ACPI, así que sigue siendo necesario el uso de Laptop Mode Tools u otras herramientas similares a acpid.

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 &

Suspensión e hibernación

systemd proporciona órdenes para suspender en RAM, hibernar y una suspensión hibrida usando le funcionalidad de suspensión/reanudación nativa del kernel. También existen mecanismos para agregar hooks para personalizar las acciones de pre y post-suspensión.

Nota: systemd también puede utilizar otros backends (como por ejemplo Uswsusp o TuxOnIce), en conjunción con el banckend por defecto del kernel, con el fin de poner el ordenador a dormir o hibernar. Véase Uswsusp#With systemd para obtener un ejemplo.

systemctl suspend debería funcionar tras su instalación, sin embargo, para que systemctl hibernate pueda trabajar en su sistema debe seguir las instrucciones de Suspend and hibernate#Hibernation.

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

Archivos de servicios para suspender/reanudar

Los archivos de servicios pueden ser asociados a suspend.target, hibernate.target y sleep.target para ejecutar acciones antes o después de suspender/hibernar. Deben crearse archivos separados para las acciones del usuario y las acciones de root/sistema. Para activar los archivos de servicios del usuario, ejecute: # systemctl enable suspend@<usuario> && systemctl enable resume@<usuario>. Ejemplos:

/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 ; /usr/bin/mysql -e 'slave stop'
ExecStart=/usr/bin/sflock

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

[Service]
User=%I
Type=simple
ExecStartPre=/usr/local/bin/ssh-connect.sh
ExecStart=/usr/bin/mysql -e 'slave start'

[Install]
WantedBy=suspend.target

Para las acciones de root/sistema (se activa con # systemctl enable root-suspend):

/etc/systemd/system/root-suspend.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
/etc/systemd/system/root-resume.service
[Unit]
Description=Local system suspend actions
Before=sleep.target

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

[Install]
WantedBy=sleep.target

Unos consejos útiles acerca de estos archivos de servicio (más información en systemd.service(5)):

  • Si está presente Type=OneShot, entonces puede utilizar múltiples líneas ExecStart=. De lo contrario, solo está permitida una línea ExecStart. No obstante, puede agregar más órdenes con ExecStartPre o mediante la separación de las órdenes con un punto y coma (véase el primer ejemplo de arriba —fíjese en los espacios en blanco antes y después del punto y coma... ¡estos son necesarios!—).
  • Una orden con un prefijo - causará un código de salida distinto de cero que será ignorado y la orden será tratada como cumplida.
  • El mejor método para encontrar errores a fin de solucionar problemas con estos archivos de servicios es, por supuesto, con journalctl.

Archivo de servicio combinando suspensión/reanudación

Con el archivo de servicio que combina suspender/reanudar, un solo hook puede hacer todo el trabajo para las diferentes fases (sleep/resume) y para diferentes objetivos (suspend/hibernate/hybrid-sleep).

He aquí un ejemplo y su explicación:

/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: Después de iniciado, el servicio se mantiene siempre activo hasta que se detenga explícitamente.
  • StopWhenUnneeded=yes: Cuando se activa, el servicio se detendrá después de que se detenga sleep.target.
  • Debido a que sleep.target es apartado por suspend.target, hibernate.target y hybrid-sleep.target y sleep.target son en sí mismo un servicio StopWhenUnneeded, lo que nos garantiza que el hook iniciará/detendrá correctamente las diferentes tareas.

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

systemd iniciará todos los archivos ejecutables ubicados en /usr/lib/systemd/system-sleep/, y pasará dos argumentos a cada uno de ellos:

  • Argument 1: o bien pre o post, dependiendo de si la máquina se está durmiendo o despertando.
  • Argument 2: suspend, hibernate o hybrid-sleep, ependiendo de lo que se ha invocado.

systemd ejecutará estos scripts en paralelo y no uno tras el otro.

Las salidas de cualquier script personalizado se registrarán por systemd-suspend.service, systemd-hibernate.service o systemd-hybrid-sleep.service. Se pueden ver las salidas en el journal de systemd:

# journalctl -b -u systemd-suspend
Nota: Tenga en cuenta que también puede utilizar sleep.target, suspend.target, hibernate.target o hybrid-sleep.target para conectar la unidad al estado de suspensión, en lugar de utilizar scripts personalizados.

He aquí un ejemplo de script de sleep personalizado:

/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

No debemos olvidarnos de hacer el script ejecutable:

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

Véanse systemd.special(7) y systemd-sleep(8) para obtener más información.

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 (Español)#)

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[broken link: invalid section] 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 (Español)#)

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

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).

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 (Español)#)

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 (Español)#)

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 it persistent can be achieved by adding the line below to /etc/modprobe.d/iwlwifi.conf file:

options iwlwifi power_save=1 d0i3_disable=0 uapsd_disable=0
options iwldvm force_cam=0

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 ref:

  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 [5].

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 (Español)#)

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