Improved Hibernation (s2disk) HDD Performance and less SSD aging

I still like to use HDDs. And in most scenarios the overall performance on Linux is actually quite good, especially if the computer has lots of RAM. But when it comes to having a lot of RAM some optimizations should be made.

Last year I upgraded my desktop PC to 96 GB of memory (mainly needed when compiling large FOSS). So when the PC hibernates (s2disk or s2both) Linux sets /sys/power/image_size to 2/5 of that by default (~38 GB). So not just process memory gets written to the hibernation image, but also all cached data that fits into 38GB. There’s a slight advantage of having data in the hibernation image because it’s compressed and written to the HDD in one block, resulting in a better performance then re-reading it from arbitrary locations. But a 38 GB hibernation image is clearly too much when my system is usually at 8 GB RAM usage before I hibernate it.

And on my Notebook which has an SSD and 32 GB RAM it seems even more reasonable not to write cached data into the hibernation image. On an SSD such data can be quickly reread from it’s actual location and copying it to the hibernation image just ages the SSD.

So I came up with these two files :-)

/etc/scripts/before_s2both_s2disk.bash

#!/bin/bash

sync

# ==== IMPORTANT: USE ON SSDs ====
# # Don't write cache to swap image.
# # On SSDs it'll just age the SSDs.
# sync
# echo 1 > /proc/sys/vm/drop_caches

# ==== IMPORTANT: USE ON HDDs ====
# Write only the latest cache to the compressed hibernation image.
# Will provide optimal suspend/resume speed when often doing s2disk/s2both on HDDs.
used=$(LC_ALL=C free -b | grep '^Mem:' | tr -s ' ' | cut -d' ' -f3)
echo $((used + 4 * 1024**3)) > /sys/power/image_size
# default: 2/5 of the RAM size
# check => start before shutdown: dmesg -w | grep 'PM: hibernation: Wrote'

/etc/systemd/system/before-s2both-s2disk.service

[Unit]
Description=Runs before s2both and s2disk
# Before: in which position of the sleep transaction order the command is being run
#   sleep.target places it definitely before the system goes to sleep
Before=sleep.target
# systemctl get-default => graphical.target
# Run to enable and after changing this section:
#   systemctl enable before-s2both-s2disk.service

[Service]
Type=oneshot
ExecStart=/etc/scripts/before_s2both_s2disk.bash

[Install]
# WantedBy: which actions trigger the unit, but NOT when
WantedBy=hibernate.target hybrid-sleep.target suspend-then-hibernate.target