Linux refusing mapped image file created with dd as swap device

Mark asked:

Getting the error “WRITE ERROR ON SWAP DEVICE” on boot but all works fine when I change the line:

truncate -s $swapsize $flPtDev


cp /swap.img $flPtDev

The complete script is the following:

cd /home/myuser/
mkdir ./.myfolder
cd ./.myfolder  
truncate -s $swapsize $flPtDev  # ** THE OFFENDING LINE **
chmod 0600 $flPtDev
chown root $flPtDev 
dd if=/dev/urandom of=$flPtKey bs=4096 count=1 conv=notrunc,noerror
sudo chmod 0600 $flPtKey
chown root $flPtKey
cat << EOF > /etc/crypttab
# <target name> <source device>         <key file>      <options>
$flNmMnt $flPtDev $flPtKey swap,offset=1024,cipher=aes-xts-plain64
cryptdisks_start $flNmMnt
rpl "/swap.img none swap    sw  0   0" "#/swap.img none swap    sw  0   0" /etc/fstab
echo "/dev/mapper/$flNmMnt none swap sw 0 0" > /etc/fstab

My answer:

Swap files cannot be sparse files. They must be fully allocated. If the system tries to write to a part of a swap file that wasn’t allocated, the write error occurs.

Copying the swap file fixes the problem by fully allocating the destination file.

You can fix the original problem by creating a fully allocated swap file to begin with. There are a few ways to do that, but the easiest and fastest to integrate into your process is probably going to be:

fallocate -l $swapsize $flPtDev

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.