Enabling Grub Hibernation

Table of Contents

Enabling Grub Hibernation

Creating a Swap File

The first step towards enabling hibernation with Grub is creating a swap file. Here are the steps as outlined in the Arch Linux Guide.

To create a swap file of your choice size, you can use the dd command. The following example creates an 8 GiB swap file:

dd if=/dev/zero of=/swapfile bs=1M count=8k status=progress

Once you've created the swap file, you need to set the right permissions. A world-readable swap file can present a significant local vulnerability:

chmod 0600 /swapfile

After creating the appropriately-sized file, you need to format it to swap:

mkswap -U clear /swapfile

Next, you'll activate the swap file:

swapon /swapfile

Finally, add an entry for the swap file in the fstab configuration:

# /etc/fstab
/swapfile none swap defaults 0 0

Enabling Hibernation into the Swap File

Adjusting mkinitcpio

If your swap file is located on an encrypted device, you need to add the 'resume' hook after the 'encrypt' hook in the mkinitcpio.conf, so that the swap file can be decrypted:

# /etc/mkinitcpio.conf
...
HOOKS=(... encrypt resume...)
...

Next, run the following command:

sudo mkinitcpio -P

Adjusting Grub Kernel Parameters

The Arch Linux documentation are helpful here:

If you are using a swap file, you need to set the resume=UUID=swap_device_uuid kernel parameters, and also add a resume_offset=swap_file_offset.

  • Finding the resumeoffset

    On file systems other than Btrfs, you can obtain the value of swap_file_offset by running filefrag -v swap_file. The required value can be found in the first row of the physical_offset column in the output table.

    For example:

    $ filefrag -v /swapfile
    ---
    
    Filesystem type is: ef53
    File size of /swapfile is 4294967296 (1048576 blocks of 4096 bytes)
     ext:     logical_offset:        physical_offset: length:   expected: flags:
       0:        0..       0:      38912..     38912:      1:            
       1:        1..   22527:      38913..     61439:  22527:             unwritten
       2:    22528..   53247:     899072..    929791:  30720:      61440: unwritten
    ...
    ~~~
    

    In the example, the value of swap_file_offset is the first 38912 (with the two periods), and the kernel parameter would be resume_offset=38912.

  • Finding the UUID of the Swapfile

    You can use the following command to identify swap_device_uuid:

    findmnt -no UUID -T /swapfile
    
  • Modifying /etc/default/grub

    You need to write these values into the /etc/default/grub file.

    # /etc/default/grub
    GRUB_CMDLINE_LINUX="resume=UUID=<UUID goes here> resume_offset=<resume_offset goes here>"
    

    Finally, you can regenerate the grub configuration:

    sudo grub-mkconfig -o /boot/grub/grub.cfg
    

Conclusion

We have now created a swap file, modified the mkinitcpio.conf, and adjusted the Grub kernel parameters.