Subject: bug#14618: Erroneous sparse copy command results in empty file

From: Koen De Wit <[email-masked]>
Date: Fri, 14 Jun 2013 13:35:59 +0200

When trying to create a sparse copy of a file on a different filesystem 
you get an "Invalid cross-device link" error, as expected. However, an 
empty file is created instead of the sparse copy:

# mkfs.btrfs -f /dev/sde1
# mkfs.btrfs -f /dev/sde2
# mount /dev/sde1 /mnt/part1
# mount /dev/sde2 /mnt/part2
# echo "abc" > /mnt/part1/testfile
# ./cp --reflink /mnt/part1/testfile /mnt/part2/testcopy
./cp: failed to clone ‘/mnt/part2/testcopy’ from ‘/mnt/part1/testfile’: 
Invalid cross-device link
# ls -la /mnt/part1/testfile
-rw-r--r--. 1 root root 4 Jun 14 14:49 /mnt/part1/testfile
# ls -la /mnt/part2/testcopy
-rw-r--r--. 1 root root 0 Jun 14 14:49 /mnt/part2/testcopy

The same occurs when trying to create a sparse copy on a filesystem that 
does not support sparse copies:

# mkfs.ext3 /dev/sde1
# mount /dev/sde1 /mnt/part1
# echo "abc" > /mnt/part1/testfile
# ./cp --reflink /mnt/part1/testfile /mnt/part1/testcopy
./cp: failed to clone ‘/mnt/part1/testcopy’ from ‘/mnt/part1/testfile’: 
Inappropriate ioctl for device
# ls -la /mnt/part1
(...)
-rw-r--r--. 1 root root 0 Jun 14 14:58 testcopy
-rw-r--r--. 1 root root 4 Jun 14 14:58 testfile

If creating a sparse copy fails, no file should be created.

ln treats this error in the right way:

# ln /mnt/part1/testfile /mnt/part2/testlink
ln: creating hard link `/mnt/part2/testlink' => `/mnt/part1/testfile': 
Invalid cross-device link
# ls -la /mnt/part2/testlink
ls: cannot access /mnt/part2/testlink: No such file or directory

Tested with coreutils today's git HEAD and kernel 3.9.5.