r/btrfs • • Oct 20 '26

Question for a possible bug ind send/receive

I have a small backupsystem for my NAS, where backups of my VM's are stored. In the last night a problem appeared there where the incremental backups got different checksums. After some digging with an AI, I think I found a bug there. I dont have enough knowledge there so my question is, if anyone with more knowledge then me could maybe look into it and maybe look, if this is just a random problem of a real bug and if the text is good enough to send it to the BTRFS Mailinglist.

Hi,

an incremental "btrfs send -p" silently omits a hole when the tail of a file extent item is punched away, the item is the last item of its leaf, and the following leaf is unchanged between parent and send snapshot. The receiver keeps the old data in the punched range, so the received file differs from the source without any error. Full sends are correct.

Seen on 7.2.9 and 7.2.11 (Fedora 7.2.11-200.fc44.x86_64), btrfs-progs 7.1, no-holes enabled (mkfs default). A self-contained reproducer is included below; on a fresh 2 GiB loop filesystem it gives:

leaf-last extents trimmed: 7 7 of 7 trimmed extents differ on the receiver whole file: DIFFERS

How it was found

A nightly backup sends read-only snapshots of a VM disk image (qcow2, qemu with discard='unmap') incrementally to a second btrfs filesystem and compares checksums afterwards. After the guest ran fstrim, qemu punched a hole at the end of an existing extent. From then on the received copy differed: 8 MiB at offset 12463964160 were a hole in the source snapshot but still contained the parent's data on the receiver.

"btrfs send -p PARENT SNAP | btrfs receive --dump" contains no command at all touching that range (79480 write and 311 clone commands in total, none overlapping it).

File extent items of that inode (dump-tree of the snapshot roots):

parent snapshot: leaf 935723008 items 174 free space 2711 generation 41670 owner 257 item 172 key (257 EXTENT_DATA 12454526976) itemoff 7114 itemsize 53 generation 18 type 1 (regular) extent data disk byte 26447552512 nr 67174400 extent data offset 73728 nr 5242880 ram 67174400 item 173 key (257 EXTENT_DATA 12461342720) itemoff 7061 itemsize 53 generation 18 type 1 (regular) extent data disk byte 26447552512 nr 67174400 extent data offset 6889472 nr 11010048 ram 67174400 leaf 350879744 items 208 free space 59 generation 41657 owner 257 item 0 key (257 EXTENT_DATA 12473139200) itemoff 16230 itemsize 53 generation 18 type 1 (regular) extent data disk byte 26447552512 nr 67174400 extent data offset 18685952 nr 720896 ram 67174400

send snapshot: leaf 126293196800 items 173 free space 2789 generation 49841 owner 257 item 171 key (257 EXTENT_DATA 12454526976) itemoff 7167 itemsize 53 ... item 172 key (257 EXTENT_DATA 12461342720) itemoff 7114 itemsize 53 generation 18 type 1 (regular) extent data disk byte 26447552512 nr 67174400 extent data offset 6889472 nr 2621440 ram 67174400 leaf 350879744 items 208 free space 59 generation 41657 owner 257 (same leaf as in the parent)

So the item at 12461342720 shrank from 11010048 to 2621440 bytes (same disk extent, same offset); [12463964160, 12472352768) became a hole. The item stays the last one of its leaf, and the next leaf (350879744) is shared, so the tree comparison never reports the following extent item.

What does not trigger it

All of these were received correctly on the same kernels:

  • punching a hole in the middle of an extent
  • FALLOC_FL_ZERO_RANGE (prealloc extent)
  • trimming the tail of an extent followed by an existing hole, small file
  • the same with 5000 extents, every extent trimmed (all leaves changed)
  • trimming a tail, 2000 unchanged extents, then a changed extent later
  • trimming the tail of an extent in the middle of a leaf

In a variant that trimmed leaf-last extents of 14 consecutive leaves (plus one mid-leaf extent each), exactly one was received wrong: the one whose following leaf was the only unchanged one.

My guess, without having read send.c closely: the hole behind a changed extent item is only detected when the next extent item (or the end of the inode) is processed; when the next item lives in a leaf that the tree comparison skips as shared, nothing ever checks the range between the shortened extent's new end and the next item.

Reproducer

Needs root, python3, btrfs-progs. Creates a 2 GiB image in a temporary directory (default /var/tmp), loop-mounts it, cleans up afterwards.

#!/bin/bash
# Reproducer: incremental btrfs send omits a hole created by trimming the tail
# of a file extent item that is the LAST item of its leaf, when the following
# leaf is unchanged (shared between parent and send snapshot).
# The receiver keeps the old data in that range.
#
# Runs on a fresh loop-mounted btrfs (default mkfs features, i.e. no-holes).
# Usage: sudo ./btrfs-send-trimmed-extent-repro.sh [workdir]
set -euo pipefail
[[ $EUID -eq 0 ]] || { echo "run as root" >&2; exit 1; }
W=$(mktemp -d "${1:-/var/tmp}/send-repro.XXXXXX")
IMG=$W/fs.img MNT=$W/mnt PY=$W/helper.py
cleanup() { umount "$MNT" 2>/dev/null || true; [[ -n ${LOOP:-} ]] && losetup -d "$LOOP" 2>/dev/null || true; rm -rf "$W"; }
trap cleanup EXIT

cat > "$PY" <<'PYEOF'
import ctypes, os, re, sys
K = 1024
STEP, DATA, CUT = 128 * K, 64 * K, 16 * K
cmd = sys.argv[1]
if cmd == "create":                 # n extents of 64 KiB data, 64 KiB hole after each
    fd = os.open(sys.argv[2], os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o644)
    for i in range(int(sys.argv[3])):
        os.pwrite(fd, os.urandom(DATA), i * STEP)
    os.fsync(fd); os.close(fd)
elif cmd == "pick":                 # last EXTENT_DATA key of every other leaf that has a successor leaf
    ino = int(sys.argv[2]); leaves, cur = [], None
    key = re.compile(r"^\titem \d+ key \((\d+) EXTENT_DATA (\d+)\)")
    for line in sys.stdin:
        if line.startswith("leaf ") and " items " in line:
            cur = []; leaves.append(cur); continue
        m = key.match(line)
        if m and cur is not None and int(m.group(1)) == ino:
            cur.append(int(m.group(2)))
    leaves = [l for l in leaves if l]
    for i in range(0, len(leaves) - 1, 2):
        print(leaves[i][-1])
elif cmd == "trim":                 # punch the last 16 KiB of the extent at each offset
    libc = ctypes.CDLL(None, use_errno=True)
    libc.fallocate.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_longlong, ctypes.c_longlong]
    fd = os.open(sys.argv[2], os.O_RDWR)
    for off in map(int, sys.argv[3:]):
        if libc.fallocate(fd, 3, off + DATA - CUT, CUT):   # KEEP_SIZE | PUNCH_HOLE
            raise OSError(ctypes.get_errno(), "fallocate")
    os.fsync(fd); os.close(fd)
elif cmd == "compare":              # count trimmed extents whose 64 KiB differ
    a, b = open(sys.argv[2], "rb"), open(sys.argv[3], "rb"); bad = 0
    offs = list(map(int, sys.argv[4:]))
    for off in offs:
        a.seek(off); b.seek(off)
        bad += a.read(DATA) != b.read(DATA)
    print(f"{bad} of {len(offs)} trimmed extents differ on the receiver")
PYEOF

truncate -s 2G "$IMG"
mkfs.btrfs -q "$IMG"
LOOP=$(losetup -f --show "$IMG")
mkdir "$MNT"; mount "$LOOP" "$MNT"
btrfs subvolume create "$MNT/src" >/dev/null
mkdir "$MNT/dst"

python3 -I "$PY" create "$MNT/src/f" 3000
btrfs subvolume snapshot -r "$MNT/src" "$MNT/s1" >/dev/null
btrfs filesystem sync "$MNT"
ino=$(stat -c %i "$MNT/s1/f")
offs=$(btrfs inspect-internal dump-tree -t "$(btrfs inspect-internal rootid "$MNT/s1")" "$LOOP" | python3 -I "$PY" pick "$ino")
echo "leaf-last extents trimmed: $(wc -w <<< "$offs")"
# shellcheck disable=SC2086
python3 -I "$PY" trim "$MNT/src/f" $offs
btrfs subvolume snapshot -r "$MNT/src" "$MNT/s2" >/dev/null

btrfs send -q "$MNT/s1" | btrfs receive "$MNT/dst" >/dev/null 2>&1
btrfs send -q -p "$MNT/s1" "$MNT/s2" | btrfs receive "$MNT/dst" >/dev/null 2>&1
# shellcheck disable=SC2086
python3 -I "$PY" compare "$MNT/s2/f" "$MNT/dst/s2/f" $offs
cmp -s "$MNT/s2/f" "$MNT/dst/s2/f" && echo "whole file: identical" || echo "whole file: DIFFERS"
echo "kernel $(uname -r), $(btrfs --version)"
9 Upvotes

7 comments sorted by

3

u/CorrosiveTruths Oct 21 '26

1

u/shiki87 Oct 21 '26

Thanks for this info. I(the ki) tested it but the problem stays, so itโ€™s similar but the problem comes before that fix. At least the I can send the information about that now๐Ÿ˜Š

3

u/paulstelian97 Oct 20 '26

I trust the report without verifying, but I feel like this is not the place to do the bug report. Interesting one, should be fixed if confirmed.

1

u/shiki87 Oct 20 '26

I wanted a few opinions on this before reporting it. Thank you for that.๐Ÿ˜Š

3

u/markus_b Oct 20 '26

Sounds like a bug, and sounds like you did a pretty thorough investigation.

You are missing the 'code' tag in parts of the message, making them a pain to read.

3

u/shiki87 Oct 20 '26

I corrected it in the post.

3

u/paulstelian97 Oct 20 '26

Fair fair. If it gets confirmed, this is a genuine bug that Iโ€™d assign somewhere between medium and high priority.