#!/bin/bash
# btrfs: resumed snapshot delete zeroes drop_progress; the restart tries to free shared blocks again and aborts.
# Run as root: ./repro-simple2.sh [DIR]. Prints "BUG: ..." and exits 1 if the bug is hit.
set -e
D=$(readlink -f "${1:-work-simple2}"); M=$D/mnt; R=$(dirname "$(readlink -f "$0")"); DM=repro2-$$
mkdir -p "$M"; rm -f "$D/img"; truncate -s 2G "$D/img"
L=$(losetup -f --show "$D/img")
trap 'umount "$M" 2>/dev/null; dmsetup remove $DM 2>/dev/null; losetup -d "$L"' EXIT
dmsetup create $DM --table "0 $(blockdev --getsz "$L") delay $L 0 15 $L 0 5"
mkfs.btrfs -q -f -n 4096 /dev/mapper/$DM
mnt() { mount -o noatime,max_inline=0 /dev/mapper/$DM "$M"; }
mnt
btrfs subvolume create "$M/S1" >/dev/null; mkdir "$M/S1/data"
python3 -I "$R/mkfiles.py" "$M/S1/data" 100000 >/dev/null
btrfs filesystem sync "$M"
btrfs subvolume snapshot -r "$M/S1" "$M/S2" >/dev/null
btrfs subvolume delete "$M/S1" >/dev/null
btrfs filesystem sync "$M"; echo 3 >/proc/sys/vm/drop_caches; sleep 5; btrfs filesystem sync "$M"
umount "$M"
mnt; umount "$M"
echo "repro2 $DM" >/dev/kmsg
mnt; timeout 150 btrfs subvolume sync "$M" >/dev/null 2>&1 || true
HIT=$(dmesg | sed -n "/repro2 $DM\$/,\$p" | grep -m1 'unable to find ref byte nr' || true)
[ -z "$HIT" ] || { echo "BUG: restarted snapshot drop aborted: ${HIT#*] }"; exit 1; }
