Skip to content

Commit

Permalink
nixos/swap: support for resizing swapfile
Browse files Browse the repository at this point in the history
Currently NixOS creates the swapfile (with the specified size) only if
it doesn't already exist. Changing the swapfile size afterwards will not
have any effect.

This commit changes that so the swapfile will be recreated whenever
swapDevices.*.size is changed (or more precisely, whenever the actual
file size differs from the configured one), allowing both growing and
shrinking the swapfile.

The service unit has "restartIfChanged = false", so we don't have to
worry about the swapfile being in use at the time this code is run (you
have to reboot for swapfile changes).

fallocate doesn't shrink files, use truncate for that. truncate can also
be used to grow files, but it creates "holes" in the file which doesn't
work with swapfiles.

(cherry picked from commit b30852e)
  • Loading branch information
bjornfor committed Jul 16, 2016
1 parent 08f4bc4 commit bd1d9ff
Showing 1 changed file with 6 additions and 3 deletions.
9 changes: 6 additions & 3 deletions nixos/modules/config/swap.nix
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,7 @@ let
description = ''
If this option is set, ‘device’ is interpreted as the
path of a swapfile that will be created automatically
with the indicated size (in megabytes) if it doesn't
exist.
with the indicated size (in megabytes).
'';
};

Expand Down Expand Up @@ -132,9 +131,13 @@ in
script =
''
${optionalString (sw.size != null) ''
if [ ! -e "${sw.device}" ]; then
currentSize=$(( $(stat -c "%s" "${sw.device}" 2>/dev/null || echo 0) / 1024 / 1024 ))
if [ "${toString sw.size}" != "$currentSize" ]; then
fallocate -l ${toString sw.size}M "${sw.device}" ||
dd if=/dev/zero of="${sw.device}" bs=1M count=${toString sw.size}
if [ "${toString sw.size}" -lt "$currentSize" ]; then
truncate --size "${toString sw.size}M" "${sw.device}"
fi
chmod 0600 ${sw.device}
${optionalString (!sw.randomEncryption) "mkswap ${sw.realDevice}"}
fi
Expand Down

0 comments on commit bd1d9ff

Please sign in to comment.