#! /bin/bash
# SPDX-License-Identifier: GPL-2.0
# Copyright (c) 2016 Oracle, Inc.  All Rights Reserved.
#
# FS QA Test No. 359
#
# Make sure that the reference counting mechanism can handle the case
# where we share the first 1/4 of an extent with a file, share the
# last 1/4 of the extent with a second file, share the first half of
# the extent with N files, and share the second half of the extent
# with a different set of N files.  The key point here is to test that
# we handle the case where a refcount extent record doesn't coincide
# exactly with the block mapping records.
#
. ./common/preamble
_begin_fstest auto quick clone

_register_cleanup "_cleanup" BUS

# Override the default cleanup function.
_cleanup()
{
	cd /
	rm -rf $tmp.*
	wait
}

# Import common functions.
. ./common/filter
. ./common/reflink

_require_scratch_reflink

echo "Format and mount"
_scratch_mkfs > $seqres.full 2>&1
_scratch_mount >> $seqres.full 2>&1

testdir=$SCRATCH_MNT/test-$seq
mkdir $testdir

blocks=64
blksz=65536
_require_congruent_file_oplen $SCRATCH_MNT $blksz
nr=4
halfway=$((blocks / 2 * blksz))
quarter=$((blocks / 4 * blksz))

echo "Initialize file"
_pwrite_byte 0x61 0 $((blocks * blksz)) $testdir/file >> $seqres.full

echo "Share the first half of the extent"
seq 1 $nr | while read nr; do
	_reflink_range $testdir/file 0 $testdir/file$nr.0 0 $halfway >> $seqres.full
done

echo "Share the last half of the extent"
seq 1 $nr | while read nr; do
	_reflink_range $testdir/file $halfway $testdir/file$nr.1 0 $halfway >> $seqres.full
done

echo "Share the first quarter of the extent"
_reflink_range $testdir/file 0 $testdir/file.2 0 $quarter >> $seqres.full

echo "Share the last quarter of the extent"
_reflink_range $testdir/file $((quarter * 3)) $testdir/file.3 0 $quarter >> $seqres.full

_scratch_cycle_mount

echo "Check output"
md5sum $testdir/file $testdir/file* | _filter_scratch

# success, all done
status=0
exit
