Linux refusing mapped image file created with dd as swap device

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

truncate -s $swapsize $flPtDev

by

cp /swap.img $flPtDev

The complete script is the following:

cd /home/myuser/
mkdir ./.myfolder
cd ./.myfolder  
swapsize='4G'
curdir=$(pwd)
flNmDev="myfile.img"
flPtDev="$curdir/$flNmDev" 
flNmKey="mykeyfile" 
flPtKey="$curdir/$flNmKey" 
flNmMnt="myDesiredMappedDeviceName" 
flPtMnt="$curdir/$flNmMnt"  
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
EOF
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

Solution 1:

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 fastest and easiest to integrate into your process is probably going to be:

fallocate -l $swapsize $flPtDev