- uswsusp
- Contents
- Installation
- Configuration
- Support for encryption
- Recreate initramfs
- Sample config
- Usage
- Standalone
- With systemd
- Troubleshooting
- My machine is not whitelisted
- s2ram -f does not work
- s2ram does not work with any combination of options
- Power management (Русский)/Suspend and hibernate (Русский)
- Contents
- Низкоуровневые интерфейсы
- Ядро (swsusp)
- uswsusp
- Интерфейсы высокого уровня
- systemd
- Гибернация
- Про размер раздела/файла подкачки
- Необходимые параметры ядра
- Гибернация в файл подкачки
- Настройка initramfs
- Технология Intel Rapid Start (IRST)
- Исправление проблем
- ACPI_OS_NAME
- Пользователям VAIO
- Ждущий/Спящий режим не работает или сбоит
- Wake-on-LAN
- Мгновенный запуск из режима ожидания
uswsusp
µswsusp (userspace software suspend) is a set of user space tools used for hibernation (suspend-to-disk) and suspend (suspend-to-RAM or standby) on Linux systems. It consists of:
s2ram — a wrapper around the kernel’s suspend-to-RAM mechanism allowing the user to perform some graphics adapter manipulations from the user land before suspending and after resuming that may help to bring the graphics (and the entire system) back to life after the resume. Incorporates the functionality of vbetool and radeontool as well as some tricks of its own. Includes a list of working hardware configurations along with the appropriate sets of operations to be performed to resume them successfully. This is accomplished by a hardware whitelist maintained by HAL — s2ram translates the HAL database options into s2ram parameters.
s2disk — the reference implementation of the userspace software suspend (µswsusp); it coordinates the steps necessary to suspend the system (such as freezing the processes, preparing the swap space, etc.) and handles image writing and reading. s2disk already supports compression and encryption of the image and other features (e.g. a nice progress bar, saving the image on a remote disk, playing tetris while resuming, etc.) can be easily added.
s2both — combines the functionalities of s2ram and s2disk and it is very useful when the battery is almost depleted. s2both writes the system snapshot to the swap (just like s2disk) but then puts the machine into STR (just like s2ram). If the battery has enough power left you can quickly resume from STR, otherwise you can still resume from disk without losing your work.
Contents
Installation
Configuration
You must edit /etc/suspend.conf before attempting to suspend to disk.
- If using a swap partition:
where by-label/swap must be replaced with the correct block device containing the swap partition.
where X and N are the device letter and partition number, respectively, and 123456 is the offset from the beginning of the resume device where the swap file’s header is located. The resume offset can be obtained by running
- The image size parameter (optional) can be used to limit the size of the system snapshot image created by s2disk. If it is not possible to create an image of the desired size, s2disk will suspend anyway, using a bigger image. If image size is set to 0, the image will be as small as possible.
- The shutdown method parameter (optional) specifies the operation that will be carried out when the machine is ready to be powered off. If set to reboot the machine will be rebooted immediately. If set to platform the machine will be shut down using special power management operations available from the kernel that may be necessary for the hardware to be properly reinitialized after the resume, and may cause the system to resume faster. If set to shutdown the machine will simply be powered down, which may cause trouble for some hardware.
- If the compute checksum parameter is set to y , the s2disk and resume tools will use the MD5 algorithm to verify the image integrity.
- If the compress parameter is set to y , the s2disk and resume tools will use the LZF compression algorithm to compress/decompress the image.
- If splash is set to y , s2disk and/or resume will use a splash system. Currently splashy and fbsplash are supported, but they are not available in Arch Linux.
Support for encryption
This article or section is out of date.
- generate a key with the suspend-keygen utility included in the package;
- write the name of the key in /etc/suspend.conf ;
Recreate initramfs
Edit your /etc/mkinitcpio.conf file and add «uresume» to the HOOKS entry.
Sample config
Usage
Standalone
To suspend to disk, run:
To suspend to ram, first run:
to see if your machine is in the database of machines known to work. If it returns something like Machine matched entry xyz then go ahead and run:
Otherwise, the —force parameter will be necessary, possibly combined with other parameters (see s2ram —help ). It may fail.
Now you could try to suspend directly calling s2disk from the command line:
It is probably necessary to resort to a userspace tool which calls internally s2disk.
With systemd
To put your system into hibernation a.k.a Suspend to Disk with systemctl hibernate , edit systemd-hibernate.service , adding:
After that, execute systemctl hibernate to put your system into hibernation. Make similar changes to systemd-hybrid-sleep.service (replace s2disk with s2both) to enable µswsusp-based hybrid sleep.
Troubleshooting
My machine is not whitelisted
If s2ram does not match your machine to an entry in its whitelist, it will output some general purpose identification strings for your machine (the same as those provided s2ram -i ). In this case, you may try to force s2ram to suspend your machine by using s2ram -f .
s2ram -f does not work
If s2ram -f does not work, try the different workarounds offered by s2ram. Run s2ram -h to get a list of the possible options:
Try the following variations:
If none of those combinations work, start again but add the -v switch.
Note that mixing the -a options and vbetool ‘s options ( -p , -m , -s ) is normally only a measure of last resort, it usually does not make much sense.
If you find several combinations that work (e.g. s2ram -f -a 3 and s2ram -f -p -m both work on your machine), the in-kernel method ( -a ) should be preferred over the userspace methods ( -p , -m , -s ).
Verify all combinations in both cases when reporting success to the s2ram developers:
- when issuing s2ram from console
- when issuing s2ram from X
s2ram does not work with any combination of options
There is a trick which does not correspond to a command-line option, because it requires additional operations from you. It is marked with NOFB in the whitelist and used for those laptops which suspend and resume properly only if no framebuffer is used. If you verify that no command line option of s2ram works, you can try disabling the framebuffer. To do this, you need to edit your bootloader configuration, remove any possible vga= values from the kernel line and reboot. This at least if you use the VESAFB framebuffer (as in the Arch default kernel). If you use a different framebuffer driver, refer to the documentation of the driver to see how to disable it.
Источник
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.
Источник