#! /bin/bash
# FS QA Test No. 472
#
# write() to a file opened with O_DIRECT with count > remaining
# bytes. In case of a bug, the write returns ENOSPC wheras the
# showing no data is written, but the file contents are updated.
# Result should be the write should return remaining bytes
# (to aligned bytes) instead of ENOSPC error.
#
#-----------------------------------------------------------------------
# Copyright (c) 2017, SUSE Linux Products.  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 15

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

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

# real QA test starts here
_supported_os Linux
_require_odirect
_require_xfs_io_command pwrite -O
_require_scratch

rm -f $seqres.full

echo "Reformat with 320M size"
sz_bytes=$((320 * 1024 * 1024))
_scratch_mkfs_sized $sz_bytes >> $seqres.full 2>&1
_scratch_mount >> $seqres.full 2>&1
testdir=$SCRATCH_MNT/$seq
mkdir $testdir

# Reserve some space to remove later
$XFS_IO_PROG -f -c "pwrite 0 2M" $testdir/reserve > /dev/null

mkdir $testdir/fillspace
echo "Fill the filesystem"
_fill_fs $(( 1024 * 1024 * 1024 )) $testdir/fillspace 4096 0 > /dev/null 2>&1

# Remove the reserve file to work on almost full filesystem
rm $testdir/reserve
sync

# Create a file using buffered I/O which succeeds only partially
$XFS_IO_PROG -f -c "pwrite -w -S 0xaa 0 4M" $testdir/partial

# re-write using direct I/O with another pattern using one single buffer, once
write_size=`$XFS_IO_PROG -d -c "pwrite -O -S 0xbb -V 1 -b 4M 0 4M" $testdir/partial | \
	$AWK_PROG '/^wrote/ {split($2, bytes, "/"); print bytes[1]}'`
if [ -z $write_size ]; then
	write_size=0
fi

# If bug is not fixed, pwrite will return error and but still write data
if [ $write_size -gt 0 ]; then
	echo "pwrite wrote more than zero bytes."
else
	echo "pwrite wrote zero bytes"
fi

# read the partial file to check if data written is of last write
$XFS_IO_PROG -c "pread 0 1M -v" $testdir/partial | _filter_xfs_io_unique

# success, all done
status=0
exit
