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
  • I dont see where you're actually creating a swap area. You're just creating a file. mkswap man page. – yoonix May 9 '19 at 22:58
  • 1
    @yoonix Thanks for the help too. – Mark May 10 '19 at 17:08

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
  • 1
    Thanks for the help and as @yoonix warned I forgot put the mkswap command on this question too. – Mark May 10 '19 at 17:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.