- Suspend
- Help on software suspend
- Debian Jessie and newer (8 and newer)
- In Gnome
- In KDE Plasma
- Disable suspend and hibernation
- Debian Wheezy (7)
- Enabling Debugging for pm-utils
- Fixing corrupted video on resume
- Kernel testing facility
- Power management (Русский)/Suspend and hibernate (Русский)
- Contents
- Низкоуровневые интерфейсы
- Ядро (swsusp)
- uswsusp
- Интерфейсы высокого уровня
- systemd
- Гибернация
- Про размер раздела/файла подкачки
- Необходимые параметры ядра
- Гибернация в файл подкачки
- Настройка initramfs
- Технология Intel Rapid Start (IRST)
- Исправление проблем
- ACPI_OS_NAME
- Пользователям VAIO
- Ждущий/Спящий режим не работает или сбоит
- Wake-on-LAN
- Мгновенный запуск из режима ожидания
- Suspend
Help on software suspend
This page gathers bits of information about getting software suspend to work in Debian. Because the core system components change rapidly among Debian versions, software suspend works differently on different versions of Debians. This page is divided according to Debian versions from new to old.
For more reading material, see also the links at the bottom of this page about hibernate and suspend.
Debian Jessie and newer (8 and newer)
With systemd, pm-utils and its hooks are not used any more, instead there’s systemd-suspend. To suspend use:
In Gnome
Another option, under Gnome shell, is to simply press ALT before clicking the shutdown button in the user menu.
In KDE Plasma
KDE already has a suspend button in its normal shutdown menu, though it may instead be labelled as «Sleep» in Plasma 5.16 and newer. Cases where it might not appear are if powerdevil or upower aren’t installed. systemd is used if available, but it’s not required.
Note that if power management is suspended by an application, the system may not suspend automatically, even if configured otherwise in your Energy Saving settings. This is often done by media players, for instance, to keep the screen from dimming. The Battery and Brightness item in your system tray will let you know if power management is suspended, and what process is currently suspending it.
Disable suspend and hibernation
For systems which should never attempt any type of suspension, these targets can be disabled at the systemd level with the following:
To re-enable hibernate and suspend use the following command:
A modern alternative approach for disabling suspend and hibernation is to create /etc/systemd/sleep.conf.d/nosuspend.conf as
The above technique works on Debian 10 Buster and newer. See systemd-sleep.conf(5) for details.
If you just want to prevent suspending when the lid is closed you can set the following options in /etc/systemd/logind.conf:
Then run systemctl restart systemd-logind.service or reboot.
More information is available in the manpage: man logind.conf
Debian Wheezy (7)
A very notable change is that HAL is phased out. If you still have the hal package installed, you should remove it or it will interference with pm-utils during suspend.
If the suspend / resume works well on your system, you are lucky and no need to read anything on this page. Or else, the first step to debug is to enable debugging for pm-utils, who control the suspend and resume process.
Enabling Debugging for pm-utils
The log of suspend and resume processes are in file /var/log/pm-suspend.log. It contains moderately verbose information by default. More information can be enabled for debugging by inserting line export PM_DEBUG=true into the beginning of file /usr/lib/pm-utils/pm-functions.
Fixing corrupted video on resume
A very common issue found after the computer resumes is corrupted video (or black screen, or no LCD backlight). The first step is to check whether the system is still running, which can be simply done by pressing the Capslock button and check whether the Capslock LED is changing accordingly. If the system is still running, in most cases we need to add a video quirk for your video card.
Debian now has kernel mode setting (KMS) enabled by default for most Intel, nVidia and ATI video cards. But pm-utils’ video quirk does support KMS yet. So in most cases you should try disabling KMS first. The detail steps for your specific video card can be found on the KernelModesetting page.
After disabled KMS, if the video after resume still corrupts, you can try to suspend the system by using some video quirks. Read the manpage of the pm-suspend program for a very detailed explanation of all the quirks available, and try the combinations of them from command-line. If you successfully find one combination of quirks that works for your system, you can add them into /usr/lib/pm-utils/video-quirks to make them permanent. At the same time, please help to file a bug against the pm-utils package with a patch about your changes so it can benefit the mass.
A common issue found on systems upgrading from old versions of Debian is the enabling of quirk-s3-bios freezes the system during suspend. If your system freezes during suspend, check the pm-suspend.log carefully after enabled debugging and make sure quirk-s3-bios is not used.
Kernel testing facility
The kernel has a Suspend testing facility changelog.
Introduce sysfs attribute /sys/power/pm_test allowing one to test the suspend core code. Namely, writing one of the strings below to this file causes the suspend code to work in one of the test modes defined as follows: freezer test the freezing of processes devices test the freezing of processes and suspending of devices platform test the freezing of processes, suspending of devices and platform global control methods(*) processors test the freezing of processes, suspending of devices, platform global control methods and the disabling of nonboot CPUs core test the freezing of processes, suspending of devices, platform global control methods, the disabling of nonboot CPUs and suspending of platform/system devices
(*) These are ACPI global control methods on ACPI systems
Then, if a suspend is started by normal means, the suspend core will perform its normal operations up to the point indicated by given test level. Next, it will wait for 5 seconds and carry out the resume operations needed to transition the system back to the fully functional state. Writing «none» to /sys/power/pm_test turns the testing off.
When open for reading, /sys/power/pm_test contains a space-separated list of all available tests (including «none» that represents the normal functionality) in which the current test level is indicated by square brackets.
The actual message (for googlers) are suspend debug: Waiting for 5 seconds.
Источник
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 доступного ОЗУ.
Вы можете либо уменьшить значение /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.
Источник