Linux how to suspend

Power management/Suspend and hibernate

Currently there are three methods of suspending available:

Suspend to RAM (aka suspend, aka sleep) The S3 sleeping state as defined by ACPI. Works by cutting off power to most parts of the machine aside from the RAM, which is required to restore the machine’s state. Because of the large power savings, it is advisable for laptops to automatically enter this mode when the computer is running on batteries and the lid is closed (or the user is inactive for some time). Suspend to disk (aka hibernate) The S4 sleeping state as defined by ACPI. Saves the machine’s state into swap space and completely powers off the machine. When the machine is powered on, the state is restored. Until then, there is zero power consumption. Suspend to both A hybrid of the aforementioned methods, sometimes called hybrid suspend. Saves the machine’s state into swap space, but does not power off the machine. Instead, it invokes usual suspend to RAM. Therefore, if the battery is not depleted, the system can resume from RAM. If the battery is depleted, the system can be resumed from disk, which is much slower than resuming from RAM, but the machine’s state has not been lost.

There are multiple low level interfaces (backends) providing basic functionality, and some high level interfaces providing tweaks to handle problematic hardware drivers/kernel modules (e.g. video card re-initialization).

This article or section needs expansion.

Contents

Low level interfaces

Though these interfaces can be used directly, it is advisable to use some of high level interfaces to suspend/hibernate. Using low level interfaces directly is significantly faster than using any high level interface, since running all the pre- and post-suspend hooks takes time, but hooks can properly set hardware clock, restore wireless etc.

kernel (swsusp)

The most straightforward approach is to directly inform the in-kernel software suspend code (swsusp) to enter a suspended state; the exact method and state depends on the level of hardware support. On modern kernels, writing appropriate strings to /sys/power/state is the primary mechanism to trigger this suspend.

uswsusp

The uswsusp (‘Userspace Software Suspend’) is a wrapper around the kernel’s suspend-to-RAM mechanism, which performs some graphics adapter manipulations from userspace before suspending and after resuming.

See main article Uswsusp.

High level interfaces

The end goal of these packages is to provide binaries/scripts that can be invoked to perform suspend/hibernate. Actually hooking them up to power buttons or menu clicks or laptop lid events is usually left to other tools. To automatically suspend/hibernate on certain power events, such as laptop lid close or battery depletion percentage, you may want to look into running Acpid.

systemd

systemd provides native commands for suspend, hibernate and a hybrid suspend, see Power management#Power management with systemd for details. This is the default interface used in Arch Linux.

See Power management#Sleep hooks for additional information on configuring suspend/hibernate hooks. Also see systemctl(1) , systemd-sleep(8) , and systemd.special(7) .

Hibernation

In order to use hibernation, you need to create a swap partition or file. You will need to point the kernel to your swap using the resume= kernel parameter, which is configured via the boot loader. You will also need to configure the initramfs. This tells the kernel to attempt resuming from the specified swap in early userspace. These three steps are described in detail below.

About swap partition/file size

Even if your swap partition is smaller than RAM, you still have a big chance of hibernating successfully. See «image_size» in the kernel documentation for information on the image_size sysfs(5) pseudo-file.

You may either decrease the value of /sys/power/image_size to make the suspend image as small as possible (for small swap partitions), or increase it to possibly speed up the hibernation process. For systems with a large amount of RAM, smaller values may drastically increase the speed of resuming a hibernating system. See systemd#systemd-tmpfiles — temporary files to make this change persistent.

The suspend image cannot span multiple swap partitions and/or swap files. It must fully fit in one swap partition or one swap file.[1]

Required kernel parameters

The kernel parameter resume=swap_device must be used. Any of the persistent block device naming methods can be used as swap_device . For example:

  • resume=UUID=4209c845-f495-4c43-8a03-5363dd433153
  • resume=»PARTLABEL=Swap partition»
  • resume=/dev/archVolumeGroup/archLogicalVolume — if swap is on a LVM logical volume

The kernel parameters will only take effect after rebooting. To be able to hibernate right away, obtain the volume’s major and minor device numbers from lsblk and echo them in format major:minor to /sys/power/resume . If using a swap file, additionally echo the resume offset to /sys/power/resume_offset .[2]

For example, if the swap device is 8:3 :

Or when hibernating to a swap file, if the swap file is on volume 8:2 and has the offset 38912 :

Hibernation into swap file

Using a swap file requires also setting the resume=swap_device and additionally a resume_offset=swap_file_offset kernel parameters. See the kernel documentation.

Читайте также:  Realtek semiconductor linux driver

swap_device is the volume where the swap file resides and it follows the same format as for the root parameter. The value of swap_file_offset can be obtained by running filefrag -v swap_file , the output is in a table format and the required value is located in the first row of the physical_offset column. For example:

In the example the value of swap_file_offset is the first 38912 with the two periods.

Hibernation into swap file on Btrfs

The resume_offset number can be computed using the tool btrfs_map_physical.c. Do not try to use the filefrag tool, on Btrfs the «physical» offset you get from filefrag is not the real physical offset on disk; there is a virtual disk address space in order to support multiple devices. [3]

Download or copy the tool btrfs_map_physical.c into a file named btrfs_map_physical.c , then compile it,

and run it. An example output is shown below.

Note the the first physical offset returned by this tool. In this example, we use 4009762816 . Also note the pagesize that can be found with getconf PAGESIZE .

To compute the resume_offset value, divide the physical offset by the pagesize. In this example, it is 4009762816 / 4096 = 978946 .

Hibernation into a thinly-provisioned LVM volume

Hibernation into a thinly-provisioned LVM volume is possible, but you have to make sure that the volume is fully allocated. Otherwise resuming from it will fail, see FS#50703.

You can fully allocate the LVM volume by simply filling it with zeros. E.g.:

To verify the volume is fully allocated, you can use:

A fully allocated volume will show up as having 100% data usage.

Configure the initramfs

  • When an initramfs with the base hook is used, which is the default, the resume hook is required in /etc/mkinitcpio.conf . Whether by label or by UUID, the swap partition is referred to with a udev device node, so the resume hook must go after the udev hook. This example was made starting from the default hook configuration:

Remember to regenerate the initramfs for these changes to take effect.

  • When an initramfs with the systemd hook is used, a resume mechanism is already provided, and no further hooks need to be added.

Intel Rapid Start Technology (IRST)

With Intel Rapid Start Technology (IRST) enabled, resuming from a deep sleep takes «a few seconds longer than resuming from S3 but is far faster than resuming from hibernation».

Many Intel-based systems have firmware support for IRST but require a special partition on an SSD (rather than an HDD). OEM deployments of Windows may already have a preexisting IRST partition which can be retained during the Arch Linux installation process (rather than wiping and repartitioning the whole SSD). It should show up as an unformatted partition equal in size to the system’s RAM.

However, if you intend to wipe and repartition the whole drive (or have already done so), then the IRST partition must be recreated if you also plan on using the technology. This can be done by creating an empty partition equal in size to the system’s RAM and by setting its partition type to GUID D3BFE2DE-3DAF-11DF-BA40-E3A556D89593 for a GPT partition or ID 0x84 for an MBR partition. You may also need to enable support for IRST in your system’s firmware settings.

The duration of the IRST hibernation process (i.e., copying the «entire contents of RAM to a special partition») is dependant on the system’s RAM size and SSD speed and can thus take 20–60 seconds. Some systems may indicate the process’s completion with an LED indicator, e.g., when it stops blinking.

See also the general Q&A and user guides for Intel Rapid Start Technology.

Troubleshooting

ACPI_OS_NAME

You might want to tweak your DSDT table to make it work. See DSDT.

Suspend/hibernate does not work, or does not work consistently

There have been many reports about the screen going black without easily viewable errors or the ability to do anything when going into and coming back from suspend and/or hibernate. These problems have been seen on both laptops and desktops. This is not an official solution, but switching to an older kernel, especially the LTS-kernel, will probably fix this.

Also problem may arise when using hardware watchdog timer (disabled by default, see RuntimeWatchdogSec= in systemd-system.conf(5) § OPTIONS ). Bugged watchdog timer may reset the computer before the system finished creating the hibernation image.

Sometimes the screen goes black due to device initialization from within the initramfs. Removing any modules you might have in Mkinitcpio#MODULES and rebuilding the initramfs, can possibly solve this issue, specially graphics drivers for early KMS. Initializing such devices before resuming can cause inconsistencies that prevents the system resuming from hibernation. This does not affect resuming from RAM. Also, check the blog article best practices to debug suspend issues.

Moving from the radeon video driver to the newer AMDGPU driver could also help to make the hibernation and awakening process successful.

For Intel graphics drivers, enabling early KMS may help to solve the blank screen issue. Refer to Kernel mode setting#Early KMS start for details.

After upgrading to kernel 4.15.3, resume may fail with a static (non-blinking) cursor on a black screen. Blacklisting the module nvidiafb might help. [5]

Laptops with Intel CPU that load intel_lpss_pci module for touchpad, may face kernel panic on resume (blinking caps lock) [6]. The module needs to be added to initramfs as:

Wake-on-LAN

If Wake-on-LAN is active, the network interface card will consume power even if the computer is hibernated.

Читайте также:  Что такое windows update как отключить

Instantaneous wakeups from suspend

For some Intel Haswell systems with the LynxPoint and LynxPoint-LP chipset, instantaneous wakeups after suspend are reported. They are linked to erroneous BIOS ACPI implementations and how the xhci_hcd module interprets it during boot. As a work-around reported affected systems are added to a denylist (named XHCI_SPURIOUS_WAKEUP ) by the kernel case-by-case.[7]

Instantaneous resume may happen, for example, if a USB device is plugged during suspend and ACPI wakeup triggers are enabled. A viable work-around for such a system, if it is not on the denylist yet, is to disable the wakeup triggers. An example to disable wakeup through USB is described as follows.[8]

To view the current configuration:

The relevant devices are EHC1 , EHC2 and XHC (for USB 3.0). To toggle their state you have to echo the device name to the file as root.

This should result in suspension working again. However, this settings are only temporary and would have to be set at every reboot. To automate this take a look at systemd#systemd-tmpfiles — temporary files or see BBS thread for a possible solution and more information.

Example solution with disabling PTXH and XHC0 at the same time. For some reason, two lines with PTXH and XHC0 one per line or in different files does not work.

If you use nouveau driver, the reason of instantaneous wakeup may be a bug in that driver, which sometimes prevents graphics card from suspension. One possible workaround is unloading nouveau kernel module right before going to sleep and loading it back after wakeup. To do this, create the following script:

The first echo line unbinds nouveaufb from the framebuffer console driver (fbcon). Usually it is vtcon1 as in this example, but it may also be another vtcon* . See /sys/class/vtconsole/vtcon*/name which one of them is a «frame buffer device» [9].

System does not power off when hibernating

When you hibernate your system, the system should power off (after saving the state on the disk). Sometimes, you might see the power LED is still glowing. If that happens, it might be instructive to set the HibernateMode to shutdown in sleep.conf.d(5) :

With the above configuration, if everything else is set up correctly, on invocation of a systemctl hibernate the machine will shutdown saving state to disk as it does so.

Источник

Power management (Русский)/Suspend and hibernate (Русский)

В настоящее время существует три метода приостановки работы компьютера: suspend to RAM обычно называемая просто suspend(приостановка, ждущий режим, сон, STR, S3 ), suspend to disk известный как hibernate( гибернация, спящий режим, STD, S4 ), и hybrid suspend( гибридная приостановка, гибридный спящий режим, иногда применяется название suspend to both):

  • Suspend to RAM отключает питание большинства частей компьютера, кроме ОЗУ, что требуется для восстановления состояния машины. Из-за большой экономии энергии рекомендуется, чтобы ноутбуки автоматически входили в этот режим, когда компьютер работает от батарей, и крышка закрыта или пользователь неактивен в течение некоторого времени.
  • Suspend to disk метод сохраняет состояние машины на диске Swap (Русский) и полностью отключает компьютер, потребления электроэнергии нет. Когда устройство включается, состояние восстанавливается.
  • Suspend to both сохраняет состояние машины на диске в свопе, но не выключает ее. Вместо этого выполняется обычная приостановка в ОЗУ. Поэтому, если батарея не разряжена, система может возобновиться из ОЗУ. Если батарея разряжена, система может быть возобновлена с диска, что намного медленнее, чем возобновление работы из ОЗУ, но состояние машины не будет потеряно.

Существует несколько низкоуровневых интерфейсов, обеспечивающих базовые функции, а также некоторые интерфейсы высокого уровня, обеспечивающие трюки для обработки проблемных аппаратных драйверов / модулей ядра (например, повторная инициализация видеокарты).

Contents

Низкоуровневые интерфейсы

Хотя эти интерфейсы могут использоваться напрямую, рекомендуется использовать какой-либо из #Интерфейсы высокого уровня для ждущего / спящего режима. Использование низкоуровневых интерфейсов напрямую существенно быстрее, чем использование любого интерфейса высокого уровня, поскольку запуск всех хуков перед и после режима приостановки требует времени, но хуки могут правильно устанавливать аппаратные часы, восстанавливать беспроводное соединение и т.д.

Ядро (swsusp)

Самый простой подход для входа в режим сна заключается в прямом информировании встроенного программного кода ядра (swsusp); точный метод и состояние зависят от уровня аппаратной поддержки. В современных ядрах основным механизмом переключения режимов является запись соответствующих значений в /sys/power/state .

Cмотрите документацию для подробностей.

uswsusp

Uswsusp (‘Userspace Software Suspend’) представляет собой оболочку ядерного механизма приостановки в ОЗУ, которая выполняет некоторые манипуляции с графическим адаптером из пользовательского пространства перед приостановкой и после возобновления.

Смотрите основную статью Uswsusp.

Интерфейсы высокого уровня

Конечной целью этих пакетов является предоставление программ( двоичных файлов/скриптов), которые могут быть вызваны для выполнения приостановки компьютера. Фактическая привязка их к кнопкам питания, щелчкам меню или событиям крышки ноутбука обычно предоставляется другим инструментам. Чтобы автоматически приостановить работу при определенных событиях, таких как закрытие крышки ноутбука или процент истощения батареи, вам может потребоваться запустить Acpid.

systemd

systemd предоставляет собственные команды для ждущего, спящего и гибридного режима приостановки, смотрите Power management#Power management with systemd для деталей. Это интерфейс по умолчанию, используемый в Arch Linux. Смотрите Power management#Sleep hooks для получения дополнительной информации о настройке хуков режимов сна. Также смотрите systemctl(1) , systemd-sleep(8) и systemd.special(7) .

Гибернация

Чтобы использовать спящий режим, вам нужно создать swap раздел или файл. Вам нужно будет указать ядру на своп, используя параметр resume= , который настраивается через загрузчик. Вам также понадобится настроить initramfs. Это говорит ядру попытаться возобновить работу с указанного свопа в раннем пользовательском пространстве. Эти три этапа подробно описаны ниже.

Про размер раздела/файла подкачки

Даже если ваш раздел подкачки меньше ОЗУ, у вас все еще есть большая вероятность успешно перейти в спящий режим. Согласно ядерной документации:

/sys/power/image_size управляет размером образа, создаваемого механизмом приостановки на диск. Это может быть строка, представляющая неотрицательное целое число, которое будет использоваться в качестве верхнего предела размера образа в байтах. Механизм приостановки сделает все возможное, чтобы размер образа не превышал это число. Однако, если это окажется невозможным, он попытается приостановить все равно, используя наименьший возможный размер образа. В частности, если в этот файл записать «0», размер образа будет настолько мал на сколько это возможно. Чтение из этого файла отображает текущее ограничение размера образа, которое по умолчанию установлено на 2/5 доступного ОЗУ.

Читайте также:  Windows store minecraft bedrock

Вы можете либо уменьшить значение /sys/power/image_size , чтобы сделать образ как можно меньшим (для небольших разделов подкачки) или увеличить его, чтобы ускорить процесс гибернации.

Необходимые параметры ядра

Должен быть использован параметр ядра resume=swap_partition . Либо имя, назначенное ядром для раздела, либо его UUID, можно использовать как swap_partition . Например:

  • resume=/dev/sda1
  • resume=UUID=4209c845-f495-4c43-8a03-5363dd433153
  • resume=/dev/mapper/archVolumeGroup-archLogicVolume — если используется LVM

В общем, метод именования, используемый для параметра resume , должен быть таким же, как и для параметра root . Конфигурация зависит от используемого загрузчика, обратитесь к Kernel parameters за деталями.

Гибернация в файл подкачки

Для использования файла подкачки также необходимо установить resume=swap_device и resume_offset=swap_file_offset kernel parameters. Смотрите документацию ядра.

Значение swap_file_offset можно получить запустив filefrag -v swap_file , требуемое значение расположено в столбце physical_offset первого ряда таблицы выводимой командой. Например:

В этом примере значение swap_file_offset это первое число 38912 с двумя точками.

Значение swap_file_offset так же может быть получено с помощью swap-offset swap_file . Файл команды swap-offset предоставляется пакетом uswsusp-git AUR .

Настройка initramfs

  • Когда используется initramfs с хуком base , а по умолчанию это так, хук resume требуется в /etc/mkinitcpio.conf . Будь то по метке или по UUID раздел подкачки ссылается на файл устройства создаваемый udev, поэтому хук resume должен идти «после» хука udev . Этот пример был сделан на основе конфигурации хуков по умолчанию:

Не забудьте пересобрать образ initramfs чтобы эти изменения вступили в силу.

  • Когда используется initramfs с хуком systemd , механизм возобновления уже предоставлен и дополнительные хуки не нужны.

Технология Intel Rapid Start (IRST)

При включенной технологии Intel Rapid Start Technology (IRST) для выхода из глубокого сна требуется «на несколько секунд больше, чем для выхода из S3, но намного меньше, чем для выхода из спящего режима».

Многие системы на базе Intel имеют встроенную поддержку IRST, но для этого требуется специальный раздел на SSD (а не на HDD). OEM-развертывания Windows могут уже иметь уже существующий раздел IRST, который можно сохранить во время процесса установки Arch Linux (вместо очистки и перераспределения всего SSD). Он должен отображаться как неотформатированный раздел, равный размеру ОЗУ системы.

Однако, если вы собираетесь стереть и переразбить весь диск (или уже сделали это), то раздел IRST необходимо создать заново, если вы планируете использовать эту технологию. Это можно сделать, создав пустой раздел, равный размеру ОЗУ системы, и установив для него тип раздела GUID D3BFE2DE-3DAF-11DF-BA40- E3A556D89593 для раздела GPT или ID 0x84 для раздела MBR. Вам также может потребоваться включить поддержку IRST в настройках прошивки вашей системы.

Продолжительность процесса гибернации IRST (например, копирования «всего содержимого ОЗУ в специальный раздел») зависит от размера ОЗУ системы и скорости SSD и, таким образом, может занять 20–60 секунд. Некоторые системы могут сигнализировать о завершении процесса светодиодным индикатором (LED), например, когда он перестает мигать.

Смотрите также общие вопросы и ответы и руководства пользователей для технологии Intel Rapid Start.

Исправление проблем

ACPI_OS_NAME

Возможно, вы захотите настроить свою таблицу DSDT, чтобы заставить ее работать. Смотрите статью DSDT

Пользователям VAIO

Добавьте acpi_sleep=nonvs параметр ядра в ваш загрузчик и возьмите себе с полки пирожок!

Ждущий/Спящий режим не работает или сбоит

There have been many reports about the screen going black without easily viewable errors or the ability to do anything when going into and coming back from suspend and/or hibernate. These problems have been seen on both laptops and desktops. This is not an official solution, but switching to an older kernel, especially the LTS-kernel, will probably fix this.

Sometimes the screen goes black due to device initialization from within the initramfs. Removing any modules you might have in Mkinitcpio#MODULES and rebuilding the initramfs, can possibly solve this issue, specially graphics drivers for early KMS. Initializing such devices before resuming can cause inconsistencies that prevents the system resuming from hibernation. This does not affect resuming from RAM. Also, check this article for the best practices to debug suspend/hibernate issues.

For Intel graphics drivers, enabling early KMS may help to solve the blank screen issue. Refer to Kernel mode setting#Early KMS start for details.

Wake-on-LAN

If Wake-on-LAN is active, the network interface card will consume power even if the computer is hibernated.

Мгновенный запуск из режима ожидания

For some Intel Haswell systems with the LynxPoint and LynxPoint-LP chipset, instantaneous wakeups after suspend are reported. They are linked to erroneous BIOS ACPI implementations and how the xhci_hcd module interprets it during boot. As a work-around reported affected systems are added to a blacklist (named XHCI_SPURIOUS_WAKEUP ) by the kernel case-by-case.[2]

Instantaneous resume may happen, for example, if a USB device is plugged during suspend and ACPI wakeup triggers are enabled. A viable work-around for such a system, if it is not on the blacklist yet, is to disable the wakeup triggers. An example to disable wakeup through USB is described as follows.[3]

To view the current configuration:

The relevant devices are EHC1 , EHC1 and XHC (for USB 3.0). To toggle their state you have to echo the device name to the file as root.

This should result in suspension working again. However, this settings are only temporary and would have to be set at every reboot. To automate this take a look at systemd#Написание файлов юнитов. See BBS thread for a possible solution and more information.

Источник

Оцените статью