#! /bin/bash
# FS QA Test No. 433
#
# Regression test for an XFS NULL xattr buffer problem during unlink. XFS had a
# bug where the attr fork walk during file removal could go off the rails due to
# a stale reference to content of a released buffer. Memory pressure could cause
# this reference to point to free or reused memory and cause subsequent
# attribute fork lookups to fail, return a NULL buffer and possibly crash.
#
# This test emulates this behavior using an error injection knob to explicitly
# disable buffer LRU caching. This forces the attr walk to execute under
# conditions where each buffer is immediately freed on release.
#
# Commit f35c5e10c6ed ("xfs: reinit btree pointer on attr tree inactivation
# walk") fixed the bug.
#
#-----------------------------------------------------------------------
# Copyright (c) 2017 Red Hat, 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 15

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

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

# remove previous $seqres.full before test
rm -f $seqres.full

# real QA test starts here

# Modify as appropriate.
_supported_fs generic
_supported_os Linux
_require_xfs_io_error_injection buf_lru_ref
_require_scratch
_require_attrs

_scratch_mkfs > $seqres.full 2>&1
_scratch_mount

file=$SCRATCH_MNT/testfile

# create a bunch of xattrs to form a multi-level attr tree
touch $file
for i in $(seq 0 499); do
	$SETFATTR_PROG -n trusted.user.$i -v 0 $file
done

# cycle the mount to clear any buffer references
_scratch_cycle_mount || _fail "cycle mount failure"

# disable the lru cache and unlink the file
_scratch_inject_error buf_lru_ref 1
rm -f $file
_scratch_inject_error buf_lru_ref 0

echo Silence is golden

# success, all done
status=0
exit
