Is it possible to hibernate with swap-file?

Hi everyone

I got it to work with a complex setup so I thought I would leave this here for the future generations.

My setup is Btrfs + LUKS2 + TPM unlock + swapfile. Long story short, I got to this setup by doing the recommended auto partitioning during the install, then a long time later I changed things up. I used a live USB NixOS, removed my swap partition and filled the space with the root partition in gparted (leaving a few megabytes at the end empty). I followed a guide to convert from ext4 to btrfs and another guide to upgrade to LUKS2 from the default LUKS1 and also switched to a stronger key algo there. The TPM enrolling is pretty simple too.

Btrfs convert guide
Luks upgrade guide
TPM enroll guide

I only have 2 partitions, the boot and the root. During the boot sequence the encrypted root volume gets automatically unlocked using the TPM and mapped to /dev/dm-0. I found this with ll /dev/mapper/luks*

I have an 18G swapfile at /var/swapfile. It’s auto created by my NixOS config.
I used btrfs inspect-internal map-swapfile -r /var/swapfile to get the resume offset for the kernel parameter.

Here’s my config:

  swapDevices = [ { device = "/var/swapfile"; size = 18*1024; } ];
  boot.resumeDevice = "/dev/dm-0";  # the unlocked drive mapping
  boot.kernelParams = [
    "resume_offset=10134041"
  ];

After building and rebooting I can finally hibernate with systemctl hibernate and my PC wakes up from keyboard or mouse input.

I still don’t know how to add a hibernate button to the shutdown menu and disable the wake from mouse/keyboard but it’s good progress for day.
I’m planning to try Suspend then hibernate - #5 by ericgundrum next

2 Likes