#! /bin/bash
# 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.
#
#-----------------------------------------------------------------------
# Copyright (c) 2016 Oracle, Inc.  All Rights Reserved.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it would be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write the Free Software Foundation,
# Inc.,  51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#-----------------------------------------------------------------------
#

seq=`basename $0`
seqres=$RESULT_DIR/$seq
echo "QA output created by $seq"

here=`pwd`
tmp=/tmp/$$
status=1	# failure is the default!
trap "_cleanup; exit \$status" 0 1 2 3 7 15

_cleanup()
{
	cd /
	rm -rf $tmp.*
	wait
}

# get standard environment, filters and checks
. ./common/rc
. ./common/filter
. ./common/reflink

# real QA test starts here
_supported_os Linux
_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
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
