#!/bin/bash

#  In evaluating btrfs for my use case, I stumbled on what appears to be a bug.
#  Originally, I created two lvm logical volumes on the same physical device each
#  with a btrfs file system.  I then cloned the linux kernel into the first one,
#  then attempted to do a btrfs send/receive to "backup" the first filesystem. It
#  was my intent to continue on and experiment with incremental backups using
#  btrfs.  However, the first time I ran the 'receive' command it failed with the
#  following error:
#  
#  mkfile o25030-9-0
#  rename o25030-9-0 -> linux/drivers/clk/clk-axi-clkgen.c
#  ERROR: rename o25030-9-0 -> linux/drivers/clk/clk-axi-clkgen.c failed: No space left on device
#  
#  If I manually delete the subvolume create above, and re-run the transfer,
#  things seem fine.  Further, this doesn't happen every time, but it does happen
#  frequently.
#  
#  I created the filesystems like so:
#  
#  # lvcreate -n test-btrfs2 -L50G storage /dev/sdc1 
#  # mkfs.btrfs -f /dev/storage/test-btrfs2
#  # pvs
#    PV         VG      Fmt  Attr PSize   PFree  
#    /dev/sda3  storage lvm2 a--  463.52g 147.52g
#    /dev/sdb1  storage lvm2 a--  465.76g      0 
#    /dev/sdc1  storage lvm2 a--  476.94g  99.99g
#  # lvs
#    LV          VG      Attr       LSize   Pool Origin Data%  Meta%  Move Log Cpy%Sync Convert
#    btrfs       storage -wi-ao---- 742.70g                                                    
#    slow        storage -wi-ao---- 300.00g                                                    
#    swap        storage -wi-ao----  16.00g                                                    
#    test-btrfs  storage -wi-a-----  50.00g                                                    
#    test-btrfs2 storage -wi-ao----  50.00g                                                    
#  
#  # mount /dev/storage/test-btrfs2 btrfs2
#  which results in a mount like like so on my system: 
#  /dev/mapper/storage-test--btrfs2 on /home/sconnor/tmp/btrfs2 type btrfs (rw,relatime,ssd,space_cache,subvolid=5,subvol=/)
#  
#  Below is a script which reproduces this issue within 30-60 seconds on my
#  system.  I found that it was unnecessary to re-do the send step, so I am only
#  testing on one FS as below.  If it isn't obvious, the script below is not very
#  good, and requires things to be setup just so, and the filesystem must be
#  pre-mounted before it begins.

set -ex

TEST_DIR=/home/sconnor/tmp/
TEST_MNT_POINT=$TEST_DIR/btrfs2
TEST_PART=/dev/storage/test-btrfs2
LOG=/home/sconnor/scratch/receive_log.txt

while true
do
    umount $TEST_MNT_POINT
    mkfs.btrfs -f $TEST_PART
    mount $TEST_PART $TEST_MNT_POINT
    zcat $TEST_DIR/snap_1.bs.gz | btrfs receive -vv $TEST_DIR/btrfs2/ 2> $LOG
done

