_require_scratch_size $((3 * 1024 * 1024)) #kB
-# First, create a 1GB filesystem and fill it up.
-_scratch_mkfs_sized $((1024 * 1024 * 1024)) >> $seqres.full 2>&1
+# First, create a 1GB filesystem.
+fssize=$((1024 * 1024 * 1024))
+_scratch_mkfs_sized $fssize >> $seqres.full 2>&1
_scratch_mount
-dd if=/dev/zero of="$SCRATCH_MNT/fill" bs=1024k >> $seqres.full 2>&1
-# Now add more space and create a swap file. We know that the first 1GB of the
-# filesystem was used, so the swap file must be in the new part of the
+
+# Create a small file and run balance so we shall deal with the chunk
+# size as allocated by the kernel, mkfs allocated chunks are smaller.
+dd if=/dev/zero of="$SCRATCH_MNT/fill" bs=4096 count=1 >> $seqres.full 2>&1
+_run_btrfs_balance_start "$SCRATCH_MNT"
+
+# Now fill it up.
+dd if=/dev/zero of="$SCRATCH_MNT/refill" bs=4096 >> $seqres.full 2>&1
+
+# Now add more space and create a swap file. We know that the first $fssize
+# of the filesystem was used, so the swap file must be in the new part of the
# filesystem.
-$BTRFS_UTIL_PROG filesystem resize 2G "$SCRATCH_MNT" | _filter_scratch
+$BTRFS_UTIL_PROG filesystem resize $((3 * fssize)) "$SCRATCH_MNT" | \
+ _filter_scratch
_format_swapfile "$swapfile" $((32 * 1024 * 1024))
swapon "$swapfile"
-# Add even more space which we know is unused.
-$BTRFS_UTIL_PROG filesystem resize 3G "$SCRATCH_MNT" | _filter_scratch
+
# Free up the first 1GB of the filesystem.
rm -f "$SCRATCH_MNT/fill"
+rm -f "$SCRATCH_MNT/refill"
+
# Get rid of empty block groups and also make sure that balance skips block
# groups containing active swap files.
_run_btrfs_balance_start "$SCRATCH_MNT"
-# Shrink away the unused space.
-$BTRFS_UTIL_PROG filesystem resize 2G "$SCRATCH_MNT" | _filter_scratch
+
# Try to shrink away the area occupied by the swap file, which should fail.
$BTRFS_UTIL_PROG filesystem resize 1G "$SCRATCH_MNT" 2>&1 | grep -o "Text file busy"
+
swapoff "$swapfile"
+
# It should work again after swapoff.
-$BTRFS_UTIL_PROG filesystem resize 1G "$SCRATCH_MNT" | _filter_scratch
+$BTRFS_UTIL_PROG filesystem resize $fssize "$SCRATCH_MNT" | _filter_scratch
status=0
exit