Viewing: sanity.sh

#!/usr/bin/bash
#
# Run select tests by setting ONLY, or as arguments to the script.
# Skip specific tests by setting EXCEPT.
#
# e.g. ONLY="22 23" or ONLY="`seq 32 39`" or EXCEPT="31"
set -e

ONLY=${ONLY:-"$*"}

# Check Grants after these tests
GRANT_CHECK_LIST="$GRANT_CHECK_LIST 42a 42b 42c 42d 42e 63a 63b 64a 64b 64c 64d 64j"

OSC=${OSC:-"osc"}

CC=${CC:-cc}
CREATETEST=${CREATETEST:-createtest}
LVERIFY=${LVERIFY:-ll_dirstripe_verify}
OPENFILE=${OPENFILE:-openfile}
OPENUNLINK=${OPENUNLINK:-openunlink}
READS=${READS:-"reads"}
SOCKETSERVER=${SOCKETSERVER:-socketserver}
SOCKETCLIENT=${SOCKETCLIENT:-socketclient}
MEMHOG=${MEMHOG:-memhog}
DIRECTIO=${DIRECTIO:-directio}
ACCEPTOR_PORT=${ACCEPTOR_PORT:-988}
DEF_STRIPE_COUNT=${DEF_STRIPE_COUNT:--1}
CHECK_GRANT=${CHECK_GRANT:-"yes"}
GRANT_CHECK_LIST=${GRANT_CHECK_LIST:-""}

TRACE=${TRACE:-""}
LUSTRE=${LUSTRE:-$(dirname $0)/..}
LUSTRE_TESTS_API_DIR=${LUSTRE_TESTS_API_DIR:-${LUSTRE}/tests/clientapi}
. $LUSTRE/tests/test-framework.sh
init_test_env "$@"

init_logging

ALWAYS_EXCEPT="$SANITY_EXCEPT "
always_except LU-9693  42a 42c
always_except LU-6493  42b
always_except LU-16515 118c 118d
always_except LU-8411  407
always_except LU-18032 119i
always_except LU-12550 216

if $SHARED_KEY; then
	always_except LU-14181 64e 64f
	always_except LU-17127 39o
fi

# skip nfs tests on kernels >= 4.12.0 until they are fixed
if [ $LINUX_VERSION_CODE -ge $(version_code 4.12.0) ]; then
	always_except LU-12661 817
fi
# skip cgroup tests on RHEL8.1 kernels until they are fixed
if (( $LINUX_VERSION_CODE >= $(version_code 4.18.0) &&
      $LINUX_VERSION_CODE <  $(version_code 5.4.0) )); then
	always_except LU-13063 411a
fi

# skip cgroup tests for kernels < v4.18.0
if (( $LINUX_VERSION_CODE < $(version_code 4.18.0) )); then
	always_except LU-13063 411b
fi

# minutes runtime:                   5              12     8   12   15   10
[[ "$SLOW" = "no" ]] && EXCEPT_SLOW="27m 60i 64b 68 71 135 136 230d 300o 842"

if [[ "$mds1_FSTYPE" == "zfs" ]]; then
	#                                               13    (min)"
	[[ "$SLOW" == "no" ]] && EXCEPT_SLOW="$EXCEPT_SLOW 51b"
fi

# Janitor is very slow for some different subtests than Autotest
if [[ "$HOSTNAME" =~ "oleg" ]]; then
	# minutes runtime: 60  32  21
	EXCEPT_SLOW+="    51c 51e 834"
fi

if [[ "$ost1_FSTYPE" == "zfs" ]]; then
	always_except LU-1941 130b 130c 130d 130e 130f 130g
fi

# Check if running on specific distros to skip certain subtests
if [[ "$CLIENT_OS_ID_LIKE" =~ "rhel" ]]; then
	if (( $CLIENT_OS_VERSION_CODE >= $(version_code 9.3.0) )); then
		# disable test_906 temporarily until rhel9.3 solves the
		# failure on fio io_uring I/O engine.
		always_except LU-17289 906
	fi
elif [[ "$CLIENT_OS_ID_LIKE" =~ "ubuntu" ]] &&
     (( $CLIENT_OS_VERSION_CODE == $(version_code 22.04) )); then
	always_except LU-19124 27P
fi

if [[ "$FSTYPE" = "wbcfs" ]]; then
	# Lack of lprocfs support
	always_except LU-18813 0f 27A 53 66 270a
	# lack of lprocfs: osd.*.nonrotational
	always_except LU-18813 119e 119f 119g 119h
	# No stats (similar to openZFS)
	always_except LU-18813 156
	# MemFS-based OSD (wbcfs) cannot recovery from a server restart
	always_except LU-18813 17o 27oo 27z 27F  60a 64i 232 257
	always_except LU-18813 278 280  427 801c 818 820
	# Symlink/CHR/SOCK/FIFO/BLK file types do not support
	always_except LU-18813 17a 17b 17e 17g 17i 17p 21   25a
	always_except LU-18813 25b 26a 26c 26d 26e 26f 27ga 27Q
	always_except LU-18813 28  32e 32f 32g 32h 32m 32n  32o
	always_except LU-18813 32p 48a 54a 54c 54d 56l 56m  56n  56rd
	always_except LU-18813 56xb 56Eb 56eg 56eh 56ei 133a 140 170b
	always_except LU-18813 162a 226a
	# Truncate operation is not supported yet.
	always_except LU-18813 27p 27q 34a
	# cross directory hardlink in DNE env
	always_except LU-18813 31g 31l 31m
	# FMD not expired: cannot reproduce on local testing
	always_except LU-18813 36g
	# Filemap is not supported yet.
	always_except LU-18813 44f 130a 130b 130c 130d 130e 130i 430a
	# inodes/blocks space usage accounting and statfs() is not supported
	always_except LU-18813 51b 56ab 81b 220 413 418 806
	# lsattr: append-only/immutable flags
	always_except LU-18813 52a 52b
	# xattr_list() is not implemented yet
	always_except LU-18813 102a 102h 102i 102r 102t
	# linkea and fid2path wrong...
	always_except LU-18813 154B 154f 154g
	# changelog related failures: wbcfs-target device label is not correct
	always_except LU-18813 160 161c 161d 205a 65k 807 808 812
	# DNE does not work well
	always_except LU-18813 56 65e 65a 406
	# user.job XATTR
	always_except LU-18813 205h
	# Exclusive open timeout
	always_except LU-18813 208
	# OFD access log failure
	always_except LU-18813 165
	# rename() operations: the source may not empty
	# always_except LU-18813 214
	# Data page cache has been updated during bulk write
	always_except LU-18813 224d
	# fid2path failure
	always_except LU-18813 226d
	# ladvise failure
	always_except LU-18813 255
	# sec related failure
	always_except LU-18813 258
	# DoM migration failure
	always_except LU-18813 272
	# Unkown reason timeout!
	always_except LU-18813 275 277 311 410 414 419 831
	# last_rcvd should fail
	always_except LU-18813 313 314 315
	# block accting is wrong...
	always_except LU-18813 317
	# Other timeouts
	always_except LU-18813 200 350 398 399 403 404 408 432 433
	# DIO locking issue?
	always_except LU-18813 398a
	# Layout swap is not working
	always_except LU-18813 405
	# Memory pressure under memcg control
	always_except LU-18813 411
	# rmfid in DNE and in large numbers
	always_except LU-18813 421
	# local testing passed but Maloo testing failed!
	always_except LU-18813 27Cg 27U 422 424 425 426 428 429 434 442
	# OOM failure
	always_except LU-18813 430b 430c 431 814 833 850
	# Expired barrier
	always_except LU-18813 801a 801b
	# ro is not implemented yet
	always_except LU-18813 802b
	# openZFS related partial page write
	always_except LU-18813 810
	# Quota is not supported yet...
	always_except LU-18813 812b
	# ldlm kunit test
	always_except LU-18813 842
	# fanotify does not work
	always_except LU-18813 851
	# MGC locks and client umount
	always_except LU-18813 901
	# destroy takes too much time
	always_except LU-18813 903
fi

# Although every sanity.sh test has been run, we stop sooner for
# stability reasons. As we get farther, increment the STOP_AT value.
if [[ "$FSTYPE" = "wbcfs" ]]; then
	export STOP_AT=${STOP_AT:-"440"}
fi

build_test_filter
FAIL_ON_ERROR=false

proc_regexp="/{proc,sys}/{fs,sys,kernel/debug}/{lustre,lnet}/"

cleanup() {
	echo -n "cln.."
	wait_update_facet client "pgrep ll_sa" "" 35 ||
		error "ll_sa thread is still running"
	pgrep ll_sa > /dev/null && { echo "There are ll_sa thread not exit!"; exit 20; }
	cleanupall ${FORCE} $* || { echo "FAILed to clean up"; exit 20; }
}
setup() {
	echo -n "mnt.."
	load_modules
	setupall || exit 10
	echo "done"
}

check_swap_layouts_support()
{
	$LCTL get_param -n llite.*.sbi_flags | grep -q layout ||
		skip "Does not support layout lock."
}

check_swap_layout_no_dom()
{
	local FOLDER=$1
	local SUPP=$(lfs getstripe $FOLDER | grep "pattern:       mdt" | wc -l)
	[ $SUPP -eq 0 ] || skip "layout swap does not support DOM files so far"
}

check_and_setup_lustre
DIR=${DIR:-$MOUNT}
assert_DIR

MAXFREE=${MAXFREE:-$((300000 * $OSTCOUNT))}

[ -f $DIR/d52a/foo ] && chattr -a $DIR/d52a/foo
[ -f $DIR/d52b/foo ] && chattr -i $DIR/d52b/foo
rm -rf $DIR/[Rdfs][0-9]*

# $RUNAS_ID may get set incorrectly somewhere else
[ $UID -eq 0 -a $RUNAS_ID -eq 0 ] &&
	error "\$RUNAS_ID set to 0, but \$UID is also 0!"

check_runas_id $RUNAS_ID $RUNAS_GID $RUNAS

if [ "${ONLY}" = "MOUNT" ] ; then
	echo "Lustre is up, please go on"
	exit
fi

echo "preparing for tests involving mounts"
EXT2_DEV=${EXT2_DEV:-$TMP/SANITY.LOOP}
touch $EXT2_DEV
mke2fs -j -F $EXT2_DEV 8000 > /dev/null
echo # add a newline after mke2fs.

umask 077

OLDDEBUG=$(lctl get_param -n debug 2> /dev/null)

# ensure all internal functions know we want full debug
export PTLDEBUG=all
lctl set_param debug=$PTLDEBUG 2> /dev/null || true

test_0a() {
	touch $DIR/$tfile
	$CHECKSTAT -t file $DIR/$tfile || error "$tfile is not a file"
	rm $DIR/$tfile
	$CHECKSTAT -a $DIR/$tfile || error "$tfile was not removed"
}
run_test 0a "touch; rm ====================="

test_0b() {
	chmod 0755 $DIR || error "chmod 0755 $DIR failed"
	$CHECKSTAT -p 0755 $DIR || error "$DIR permission is not 0755"
}
run_test 0b "chmod 0755 $DIR ============================="

test_0c() {
	$LCTL get_param mdc.*.import | grep "state: FULL" ||
		error "import not FULL"
	$LCTL get_param mdc.*.import | grep "target: $FSNAME-MDT" ||
		error "bad target"
}
run_test 0c "check import proc"

test_0d() { # LU-3397
	(( $MGS_VERSION >= $(version_code v2_10_57_0-64-gb4b773466a) )) ||
		skip "need MGS >= 2.10.57 for proc exports supported"

	local mgs_exp="mgs.MGS.exports"
	local client_uuid=$($LCTL get_param -n mgc.*.uuid)
	local exp_uuid
	local exp_client_version
	local exp_val
	local imp_val
	local temp_imp=$DIR/$tfile.import
	local temp_exp=$DIR/$tfile.export

	# save mgc import file to $temp_imp
	$LCTL get_param mgc.*.import | tee $temp_imp
	# Check if client uuid is found in MGS export
	for exp_uuid in $(do_facet mgs $LCTL get_param -N $mgs_exp.*.uuid); do
		echo $exp_uuid
		do_facet mgs $LCTL get_param -n $exp_uuid
		[[ $(do_facet mgs $LCTL get_param -n $exp_uuid) == \
		   $client_uuid ]] && break
	done
	# save mgs export file to $temp_exp
	do_facet mgs $LCTL get_param ${exp_uuid%.uuid}.export | tee $temp_exp

	# Compare the value of field "connect_flags"
	imp_val=$(grep "connect_flags" $temp_imp)
	exp_val=$(grep "connect_flags" $temp_exp)
	[ "$exp_val" == "$imp_val" ] ||
		error "export flags '$exp_val' != import flags '$imp_val'"

	# Compare client versions.
	exp_client_version=$(awk '/target_version:/ { print $2 }' $temp_exp)
	exp_val=$(version_code $exp_client_version)
	imp_client_version=$(lustre_build_version client)
	imp_val=$(version_code $imp_client_version)
	(( "$exp_val" == "$imp_val" )) ||
		error "exp version '$exp_client_version'($exp_val) != '$(imp_client_version)'($imp_val)"
}
run_test 0d "check export proc"

test_0e() { # LU-13417
	(( $MDSCOUNT > 1 )) ||
		skip "We need at least 2 MDTs for this test"

	(( $MDS1_VERSION >= $(version_code 2.14.51) )) ||
		skip "Need server version at least 2.14.51"

	local default_lmv_count=$($LFS getdirstripe -D -c $MOUNT)
	local default_lmv_index=$($LFS getdirstripe -D -i $MOUNT)

	[ $default_lmv_count -eq 1 ] ||
		error "$MOUNT default stripe count $default_lmv_count"

	[ $default_lmv_index -eq -1 ] ||
		error "$MOUNT default stripe index $default_lmv_index"

	mkdir $MOUNT/$tdir.1 || error "mkdir $MOUNT/$tdir.1 failed"
	mkdir $MOUNT/$tdir.2 || error "mkdir $MOUNT/$tdir.2 failed"

	local mdt_index1=$($LFS getdirstripe -i $MOUNT/$tdir.1)
	local mdt_index2=$($LFS getdirstripe -i $MOUNT/$tdir.2)

	[ $mdt_index1 -eq $mdt_index2 ] &&
		error "directories are on the same MDT $mdt_index1=$mdt_index2"

	rmdir $MOUNT/$tdir.1 $MOUNT/$tdir.2
}
run_test 0e "Enable DNE MDT balancing for mkdir in the ROOT"

test_1() {
	test_mkdir $DIR/$tdir
	test_mkdir $DIR/$tdir/d2
	mkdir $DIR/$tdir/d2 && error "we expect EEXIST, but not returned"
	$CHECKSTAT -t dir $DIR/$tdir/d2 || error "$tdir/d2 is not a dir"
	rmdir $DIR/$tdir/d2
	rmdir $DIR/$tdir
	$CHECKSTAT -a $DIR/$tdir || error "$tdir was not removed"
}
run_test 1 "mkdir; remkdir; rmdir"

test_2() {
	test_mkdir $DIR/$tdir
	touch $DIR/$tdir/$tfile || error "touch $tdir/$tfile failed"
	$CHECKSTAT -t file $DIR/$tdir/$tfile || error "$tdir/$tfile not a file"
	rm -r $DIR/$tdir
	$CHECKSTAT -a $DIR/$tdir/$tfile || error "$tdir/$file is not removed"
}
run_test 2 "mkdir; touch; rmdir; check file"

test_3() {
	test_mkdir $DIR/$tdir
	$CHECKSTAT -t dir $DIR/$tdir || error "$tdir is not a directory"
	touch $DIR/$tdir/$tfile
	$CHECKSTAT -t file $DIR/$tdir/$tfile || error "$tdir/$tfile not a file"
	rm -r $DIR/$tdir
	$CHECKSTAT -a $DIR/$tdir || error "$tdir is not removed"
}
run_test 3 "mkdir; touch; rmdir; check dir"

# LU-4471 - failed rmdir on remote directories still removes directory on MDT0
test_4() {
	test_mkdir -i 1 $DIR/$tdir

	touch $DIR/$tdir/$tfile ||
		error "Create file under remote directory failed"

	rmdir $DIR/$tdir &&
		error "Expect error removing in-use dir $DIR/$tdir"

	test -d $DIR/$tdir || error "Remote directory disappeared"

	rm -rf $DIR/$tdir || error "remove remote dir error"
}
run_test 4 "mkdir; touch dir/file; rmdir; checkdir (expect error)"

test_5() {
	test_mkdir $DIR/$tdir
	test_mkdir $DIR/$tdir/d2
	chmod 0707 $DIR/$tdir/d2 || error "chmod 0707 $tdir/d2 failed"
	$CHECKSTAT -t dir -p 0707 $DIR/$tdir/d2 || error "$tdir/d2 not mode 707"
	$CHECKSTAT -t dir $DIR/$tdir/d2 || error "$tdir/d2 is not a directory"
}
run_test 5 "mkdir .../d5 .../d5/d2; chmod .../d5/d2"

test_6a() {
	touch $DIR/$tfile || error "touch $DIR/$tfile failed"
	chmod 0666 $DIR/$tfile || error "chmod 0666 $tfile failed"
	$CHECKSTAT -t file -p 0666 -u \#$UID $DIR/$tfile ||
		error "$tfile does not have perm 0666 or UID $UID"
	$RUNAS chmod 0444 $DIR/$tfile && error "chmod $tfile worked on UID $UID"
	$CHECKSTAT -t file -p 0666 -u \#$UID $DIR/$tfile ||
		error "$tfile should be 0666 and owned by UID $UID"
}
run_test 6a "touch f6a; chmod f6a; $RUNAS chmod f6a (should return error) =="

test_6c() {
	[ $RUNAS_ID -eq $UID ] && skip_env "RUNAS_ID = UID = $UID"

	touch $DIR/$tfile
	chown $RUNAS_ID $DIR/$tfile || error "chown $RUNAS_ID $file failed"
	$CHECKSTAT -t file -u \#$RUNAS_ID $DIR/$tfile ||
		error "$tfile should be owned by UID $RUNAS_ID"
	$RUNAS chown $UID $DIR/$tfile && error "chown $UID $file succeeded"
	$CHECKSTAT -t file -u \#$RUNAS_ID $DIR/$tfile ||
		error "$tfile should be owned by UID $RUNAS_ID"
}
run_test 6c "touch f6c; chown f6c; $RUNAS chown f6c (should return error) =="

test_6e() {
	[ $RUNAS_ID -eq $UID ] && skip_env "RUNAS_ID = UID = $UID"

	touch $DIR/$tfile
	chgrp $RUNAS_ID $DIR/$tfile || error "chgrp $RUNAS_ID $file failed"
	$CHECKSTAT -t file -u \#$UID -g \#$RUNAS_ID $DIR/$tfile ||
		error "$tfile should be owned by GID $UID"
	$RUNAS chgrp $UID $DIR/$tfile && error "chgrp $UID $file succeeded"
	$CHECKSTAT -t file -u \#$UID -g \#$RUNAS_ID $DIR/$tfile ||
		error "$tfile should be owned by UID $UID and GID $RUNAS_ID"
}
run_test 6e "touch+chgrp $tfile; $RUNAS chgrp $tfile (should return error)"

test_6g() {
	[ $RUNAS_ID -eq $UID ] && skip_env "RUNAS_ID = UID = $UID"

	test_mkdir $DIR/$tdir
	chmod 777 $DIR/$tdir || error "chmod 0777 $tdir failed"
	$RUNAS mkdir $DIR/$tdir/d || error "mkdir $tdir/d failed"
	chmod g+s $DIR/$tdir/d || error "chmod g+s $tdir/d failed"
	test_mkdir $DIR/$tdir/d/subdir
	$CHECKSTAT -g \#$RUNAS_GID $DIR/$tdir/d/subdir ||
		error "$tdir/d/subdir should be GID $RUNAS_GID"
	if [[ $MDSCOUNT -gt 1 ]]; then
		# check remote dir sgid inherite
		$LFS mkdir -i 0 $DIR/$tdir.local ||
			error "mkdir $tdir.local failed"
		chmod g+s $DIR/$tdir.local ||
			error "chmod $tdir.local failed"
		chgrp $RUNAS_GID $DIR/$tdir.local ||
			error "chgrp $tdir.local failed"
		$LFS mkdir -i 1 $DIR/$tdir.local/$tdir.remote ||
			error "mkdir $tdir.remote failed"
		$CHECKSTAT -g \#$RUNAS_GID $DIR/$tdir.local/$tdir.remote ||
			error "$tdir.remote should be owned by $UID.$RUNAS_ID"
		$CHECKSTAT -p 02755 $DIR/$tdir.local/$tdir.remote ||
			error "$tdir.remote should be mode 02755"
	fi
}
run_test 6g "verify new dir in sgid dir inherits group"

test_6h() { # bug 7331
	[ $RUNAS_ID -eq $UID ] && skip_env "RUNAS_ID = UID = $UID"

	touch $DIR/$tfile || error "touch failed"
	chown $RUNAS_ID:$RUNAS_GID $DIR/$tfile || error "initial chown failed"
	$RUNAS -G$RUNAS_GID chown $RUNAS_ID:0 $DIR/$tfile &&
		error "chown $RUNAS_ID:0 $tfile worked as GID $RUNAS_GID"
	$CHECKSTAT -t file -u \#$RUNAS_ID -g \#$RUNAS_GID $DIR/$tfile ||
		error "$tdir/$tfile should be UID $RUNAS_UID GID $RUNAS_GID"
}
run_test 6h "$RUNAS chown RUNAS_ID.0 .../$tfile (should return error)"

test_6i() {
        (( MDS1_VERSION >= $(version_code 2.16.51) )) ||
		skip "Need MDS version at least 2.16.51"
	(( $RUNAS_ID != $UID )) || skip_env "RUNAS_ID = UID = $UID"

        touch $DIR/$tfile
        chmod 444 $DIR/$tfile
        chown $RUNAS_ID $DIR/$tfile || error "initial chown failed"
        $RUNAS -u $RUNAS_ID -g $RUNAS_ID chgrp $RUNAS_ID $DIR/$tfile ||
		error "chgrp $RUNAS_ID $file failed"
        $CHECKSTAT -t file -u \#$RUNAS_ID -g \#$RUNAS_ID $DIR/$tfile ||
                error "$tfile should be owned by GID $RUNAS_ID"
}
run_test 6i "touch+chmod+chgrp $tfile; chgrp read-only file should succeed"

test_7a() {
	test_mkdir $DIR/$tdir
	$MCREATE $DIR/$tdir/$tfile
	chmod 0666 $DIR/$tdir/$tfile
	$CHECKSTAT -t file -p 0666 $DIR/$tdir/$tfile ||
		error "$tdir/$tfile should be mode 0666"
}
run_test 7a "mkdir .../d7; mcreate .../d7/f; chmod .../d7/f ===="

test_7b() {
	if [ ! -d $DIR/$tdir ]; then
		test_mkdir $DIR/$tdir
	fi
	$MCREATE $DIR/$tdir/$tfile
	echo -n foo > $DIR/$tdir/$tfile
	[ "$(cat $DIR/$tdir/$tfile)" = "foo" ] || error "$tdir/$tfile not 'foo'"
	$CHECKSTAT -t file -s 3 $DIR/$tdir/$tfile || error "$tfile size not 3"
}
run_test 7b "mkdir .../d7; mcreate d7/f2; echo foo > d7/f2 ====="

test_8() {
	test_mkdir $DIR/$tdir
	touch $DIR/$tdir/$tfile
	chmod 0666 $DIR/$tdir/$tfile
	$CHECKSTAT -t file -p 0666 $DIR/$tdir/$tfile ||
		error "$tfile mode not 0666"
}
run_test 8 "mkdir .../d8; touch .../d8/f; chmod .../d8/f ======="

test_9() {
	test_mkdir $DIR/$tdir
	test_mkdir $DIR/$tdir/d2
	test_mkdir $DIR/$tdir/d2/d3
	$CHECKSTAT -t dir $DIR/$tdir/d2/d3 || error "$tdir/d2/d3 not a dir"
}
run_test 9 "mkdir .../d9 .../d9/d2 .../d9/d2/d3 ================"

test_10() {
	test_mkdir $DIR/$tdir
	test_mkdir $DIR/$tdir/d2
	touch $DIR/$tdir/d2/$tfile
	$CHECKSTAT -t file $DIR/$tdir/d2/$tfile ||
		error "$tdir/d2/$tfile not a file"
}
run_test 10 "mkdir .../d10 .../d10/d2; touch .../d10/d2/f ======"

test_11() {
	test_mkdir $DIR/$tdir
	test_mkdir $DIR/$tdir/d2
	chmod 0666 $DIR/$tdir/d2
	chmod 0705 $DIR/$tdir/d2
	$CHECKSTAT -t dir -p 0705 $DIR/$tdir/d2 ||
		error "$tdir/d2 mode not 0705"
}
run_test 11 "mkdir .../d11 d11/d2; chmod .../d11/d2 ============"

test_12() {
	test_mkdir $DIR/$tdir
	touch $DIR/$tdir/$tfile
	chmod 0666 $DIR/$tdir/$tfile
	chmod 0654 $DIR/$tdir/$tfile
	$CHECKSTAT -t file -p 0654 $DIR/$tdir/$tfile ||
		error "$tdir/d2 mode not 0654"
}
run_test 12 "touch .../d12/f; chmod .../d12/f .../d12/f ========"

test_13() {
	test_mkdir $DIR/$tdir
	dd if=/dev/zero of=$DIR/$tdir/$tfile count=10
	>  $DIR/$tdir/$tfile
	$CHECKSTAT -t file -s 0 $DIR/$tdir/$tfile ||
		error "$tdir/$tfile size not 0 after truncate"
}
run_test 13 "creat .../d13/f; dd .../d13/f; > .../d13/f ========"

test_14() {
	test_mkdir $DIR/$tdir
	touch $DIR/$tdir/$tfile
	rm $DIR/$tdir/$tfile
	$CHECKSTAT -a $DIR/$tdir/$tfile || error "$tdir/$tfile not removed"
}
run_test 14 "touch .../d14/f; rm .../d14/f; rm .../d14/f ======="

test_15() {
	test_mkdir $DIR/$tdir
	touch $DIR/$tdir/$tfile
	mv $DIR/$tdir/$tfile $DIR/$tdir/${tfile}_2
	$CHECKSTAT -t file $DIR/$tdir/${tfile}_2 ||
		error "$tdir/${tfile_2} not a file after rename"
	rm $DIR/$tdir/${tfile}_2 || error "unlink failed after rename"
}
run_test 15 "touch .../d15/f; mv .../d15/f .../d15/f2 =========="

test_16() {
	test_mkdir $DIR/$tdir
	touch $DIR/$tdir/$tfile
	rm -rf $DIR/$tdir/$tfile
	$CHECKSTAT -a $DIR/$tdir/$tfile || error "$tdir/$tfile not removed"
}
run_test 16 "touch .../d16/f; rm -rf .../d16/f"

test_17a() {
	test_mkdir $DIR/$tdir
	touch $DIR/$tdir/$tfile
	ln -s $DIR/$tdir/$tfile $DIR/$tdir/l-exist
	ls -l $DIR/$tdir
	$CHECKSTAT -l $DIR/$tdir/$tfile $DIR/$tdir/l-exist ||
		error "$tdir/l-exist not a symlink"
	$CHECKSTAT -f -t f $DIR/$tdir/l-exist ||
		error "$tdir/l-exist not referencing a file"
	rm -f $DIR/$tdir/l-exist
	$CHECKSTAT -a $DIR/$tdir/l-exist || error "$tdir/l-exist not removed"
}
run_test 17a "symlinks: create, remove (real)"

test_17b() {
	test_mkdir $DIR/$tdir
	ln -s no-such-file $DIR/$tdir/l-dangle
	ls -l $DIR/$tdir
	$CHECKSTAT -l no-such-file $DIR/$tdir/l-dangle ||
		error "$tdir/l-dangle not referencing no-such-file"
	$CHECKSTAT -fa $DIR/$tdir/l-dangle ||
		error "$tdir/l-dangle not referencing non-existent file"
	rm -f $DIR/$tdir/l-dangle
	$CHECKSTAT -a $DIR/$tdir/l-dangle || error "$tdir/l-dangle not removed"
}
run_test 17b "symlinks: create, remove (dangling)"

test_17c() { # bug 3440 - don't save failed open RPC for replay
	test_mkdir $DIR/$tdir
	ln -s foo $DIR/$tdir/$tfile
	cat $DIR/$tdir/$tfile && error "opened non-existent symlink" || true
}
run_test 17c "symlinks: open dangling (should return error)"

test_17d() {
	test_mkdir $DIR/$tdir
	ln -s foo $DIR/$tdir/$tfile
	touch $DIR/$tdir/$tfile || error "creating to new symlink"
}
run_test 17d "symlinks: create dangling"

test_17e() {
	test_mkdir $DIR/$tdir
	local foo=$DIR/$tdir/$tfile
	ln -s $foo $foo || error "create symlink failed"
	ls -l $foo || error "ls -l failed"
	ls $foo && error_ignore LU-18093 "ls not failed" || true
}
run_test 17e "symlinks: create recursive symlink (should return error)"

test_17f() {
	test_mkdir $DIR/$tdir
	ln -s 1234567890/2234567890/3234567890/4234567890 $DIR/$tdir/111
	ln -s 1234567890/2234567890/3234567890/4234567890/5234567890/6234567890 $DIR/$tdir/222
	ln -s 1234567890/2234567890/3234567890/4234567890/5234567890/6234567890/7234567890/8234567890 $DIR/$tdir/333
	ln -s 1234567890/2234567890/3234567890/4234567890/5234567890/6234567890/7234567890/8234567890/9234567890/a234567890/b234567890 $DIR/$tdir/444
	ln -s 1234567890/2234567890/3234567890/4234567890/5234567890/6234567890/7234567890/8234567890/9234567890/a234567890/b234567890/c234567890/d234567890/f234567890 $DIR/$tdir/555
	ln -s 1234567890/2234567890/3234567890/4234567890/5234567890/6234567890/7234567890/8234567890/9234567890/a234567890/b234567890/c234567890/d234567890/f234567890/aaaaaaaaaa/bbbbbbbbbb/cccccccccc/dddddddddd/eeeeeeeeee/ffffffffff/ $DIR/$tdir/666
	ls -l  $DIR/$tdir
}
run_test 17f "symlinks: long and very long symlink name"

# str_repeat(S, N) generate a string that is string S repeated N times
str_repeat() {
	local s=$1
	local n=$2
	local ret=''
	while [ $((n -= 1)) -ge 0 ]; do
		ret=$ret$s
	done
	echo $ret
}

# Long symlinks and LU-2241
test_17g() {
	test_mkdir $DIR/$tdir
	local TESTS="59 60 61 4094 4095"

	# Fix for inode size boundary in 2.1.4
	[ $MDS1_VERSION -lt $(version_code 2.1.4) ] &&
		TESTS="4094 4095"

	# Patch not applied to 2.2 or 2.3 branches
	[ $MDS1_VERSION -ge $(version_code 2.2.0) ] &&
	[ $MDS1_VERSION -le $(version_code 2.3.55) ] &&
		TESTS="4094 4095"

	for i in $TESTS; do
		local SYMNAME=$(str_repeat 'x' $i)
		ln -s $SYMNAME $DIR/$tdir/f$i || error "failed $i-char symlink"
		readlink $DIR/$tdir/f$i	|| error "failed $i-char readlink"
	done
}
run_test 17g "symlinks: really long symlink name and inode boundaries"

test_17h() { #bug 17378
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"

	local mdt_idx

	test_mkdir $DIR/$tdir
	mdt_idx=$($LFS getdirstripe -i $DIR/$tdir)
	$LFS setstripe -c -1 $DIR/$tdir
	#define OBD_FAIL_MDS_LOV_PREP_CREATE 0x141
	do_facet mds$((mdt_idx + 1)) lctl set_param fail_loc=0x80000141
	touch $DIR/$tdir/$tfile || true
}
run_test 17h "create objects: lov_free_memmd() doesn't lbug"

test_17i() { #bug 20018
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"

	local foo=$DIR/$tdir/$tfile
	local mdt_idx

	test_mkdir -c1 $DIR/$tdir
	mdt_idx=$($LFS getdirstripe -i $DIR/$tdir)
	ln -s $foo $foo || error "create symlink failed"
#define OBD_FAIL_MDS_READLINK_EPROTO     0x143
	do_facet mds$((mdt_idx + 1)) lctl set_param fail_loc=0x80000143
	ls -l $foo && error "error not detected"
	return 0
}
run_test 17i "don't panic on short symlink (should return error)"

test_17k() { #bug 22301
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[[ -z "$(which rsync 2>/dev/null)" ]] &&
		skip "no rsync command"
	rsync --help | grep -q xattr ||
		skip_env "$(rsync --version | head -n1) does not support xattrs"
	test_mkdir $DIR/$tdir
	test_mkdir $DIR/$tdir.new
	touch $DIR/$tdir/$tfile
	ln -s $DIR/$tdir/$tfile $DIR/$tdir/$tfile.lnk
	rsync -av -X $DIR/$tdir/ $DIR/$tdir.new ||
		error "rsync failed with xattrs enabled"
}
run_test 17k "symlinks: rsync with xattrs enabled"

test_17l() { # LU-279
	[[ -z "$(which getfattr 2>/dev/null)" ]] &&
		skip "no getfattr command"

	test_mkdir $DIR/$tdir
	touch $DIR/$tdir/$tfile
	ln -s $DIR/$tdir/$tfile $DIR/$tdir/$tfile.lnk
	for path in "$DIR/$tdir" "$DIR/$tdir/$tfile" "$DIR/$tdir/$tfile.lnk"; do
		# -h to not follow symlinks. -m '' to list all the xattrs.
		# grep to remove first line: '# file: $path'.
		for xattr in `getfattr -hm '' $path 2>/dev/null | grep -v '^#'`;
		do
			lgetxattr_size_check $path $xattr ||
				error "lgetxattr_size_check $path $xattr failed"
		done
	done
}
run_test 17l "Ensure lgetxattr's returned xattr size is consistent"

# LU-1540
test_17m() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ "$mds1_FSTYPE" != "ldiskfs" ] && skip_env "ldiskfs only test"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	[ $MDS1_VERSION -ge $(version_code 2.2.0) ] &&
	[ $MDS1_VERSION -le $(version_code 2.2.93) ] &&
		skip "MDS 2.2.0-2.2.93 do not NUL-terminate symlinks"

	local short_sym="0123456789"
	local wdir=$DIR/$tdir
	local i

	test_mkdir $wdir
	long_sym=$short_sym
	# create a long symlink file
	for ((i = 0; i < 4; ++i)); do
		long_sym=${long_sym}${long_sym}
	done

	echo "create 512 short and long symlink files under $wdir"
	for ((i = 0; i < 256; ++i)); do
		ln -sf ${long_sym}"a5a5" $wdir/long-$i
		ln -sf ${short_sym}"a5a5" $wdir/short-$i
	done

	echo "erase them"
	rm -f $wdir/*
	sync
	wait_delete_completed

	echo "recreate the 512 symlink files with a shorter string"
	for ((i = 0; i < 512; ++i)); do
		# rewrite the symlink file with a shorter string
		ln -sf ${long_sym} $wdir/long-$i || error "long_sym failed"
		ln -sf ${short_sym} $wdir/short-$i || error "short_sym failed"
	done

	local mds_index=$(($($LFS getstripe -m $wdir) + 1))

	echo "stop and checking mds${mds_index}:"
	# e2fsck should not return error
	stop mds${mds_index}
	local devname=$(mdsdevname $mds_index)
	run_e2fsck $(facet_active_host mds${mds_index}) $devname -n
	rc=$?

	start mds${mds_index} $devname $MDS_MOUNT_OPTS ||
		error "start mds${mds_index} failed"
	df $MOUNT > /dev/null 2>&1
	[ $rc -eq 0 ] ||
		error "e2fsck detected error for short/long symlink: rc=$rc"
	rm -f $wdir/*
}
run_test 17m "run e2fsck against MDT which contains short/long symlink"

check_fs_consistency_17n() {
	local mdt_index
	local rc=0

	# create/unlink in 17n only change 2 MDTs(MDT1/MDT2),
	# so it only check MDT1/MDT2 instead of all of MDTs.
	for mdt_index in 1 2; do
		# e2fsck should not return error
		stop mds${mdt_index}
		local devname=$(mdsdevname $mdt_index)
		run_e2fsck $(facet_active_host mds$mdt_index) $devname -n ||
			rc=$((rc + $?))

		start mds${mdt_index} $devname $MDS_MOUNT_OPTS ||
			error "mount mds$mdt_index failed"
		df $MOUNT > /dev/null 2>&1
	done
	return $rc
}

test_17n() {
	[[ $MDSCOUNT -lt 2 ]] && skip_env "needs >= 2 MDTs"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ "$mds1_FSTYPE" != "ldiskfs" ] && skip_env "ldiskfs only test"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	[ $MDS1_VERSION -ge $(version_code 2.2.0) ] &&
	[ $MDS1_VERSION -le $(version_code 2.2.93) ] &&
		skip "MDS 2.2.0-2.2.93 do not NUL-terminate symlinks"

	local i

	test_mkdir $DIR/$tdir
	for ((i=0; i<10; i++)); do
		$LFS mkdir -i1 -c2 $DIR/$tdir/remote_dir_${i} ||
			error "create remote dir error $i"
		createmany -o $DIR/$tdir/remote_dir_${i}/f 10 ||
			error "create files under remote dir failed $i"
	done

	check_fs_consistency_17n ||
		error "e2fsck report error after create files under remote dir"

	for ((i = 0; i < 10; i++)); do
		rm -rf $DIR/$tdir/remote_dir_${i} ||
			error "destroy remote dir error $i"
	done

	check_fs_consistency_17n ||
		error "e2fsck report error after unlink files under remote dir"

	[ $MDS1_VERSION -lt $(version_code 2.4.50) ] &&
		skip "lustre < 2.4.50 does not support migrate mv"

	for ((i = 0; i < 10; i++)); do
		mkdir -p $DIR/$tdir/remote_dir_${i}
		createmany -o $DIR/$tdir/remote_dir_${i}/f 10 ||
			error "create files under remote dir failed $i"
		$LFS migrate --mdt-index 1 $DIR/$tdir/remote_dir_${i} ||
			error "migrate remote dir error $i"
	done
	check_fs_consistency_17n || error "e2fsck report error after migration"

	for ((i = 0; i < 10; i++)); do
		rm -rf $DIR/$tdir/remote_dir_${i} ||
			error "destroy remote dir error $i"
	done

	check_fs_consistency_17n || error "e2fsck report error after unlink"
}
run_test 17n "run e2fsck against master/slave MDT which contains remote dir"

test_17o() {
	remote_mds_nodsh && skip "remote MDS with nodsh"
	[ $MDS1_VERSION -lt $(version_code 2.3.64) ] &&
		skip "Need MDS version at least 2.3.64"

	local wdir=$DIR/${tdir}o
	local mdt_index
	local rc=0

	test_mkdir $wdir
	touch $wdir/$tfile
	mdt_index=$($LFS getstripe -m $wdir/$tfile)
	mdt_index=$((mdt_index + 1))

	cancel_lru_locks mdc
	#fail mds will wait the failover finish then set
	#following fail_loc to avoid interfer the recovery process.
	fail mds${mdt_index}

	#define OBD_FAIL_OSD_LMA_INCOMPAT 0x194
	do_facet mds${mdt_index} lctl set_param fail_loc=0x194
	ls -l $wdir/$tfile && rc=1
	do_facet mds${mdt_index} lctl set_param fail_loc=0
	[[ $rc -eq 0 ]] || error "stat file should fail"
}
run_test 17o "stat file with incompat LMA feature"


# LU-17660: "cannot overwrite directory" when creating symlink
test_17p() {
	touch $DIR/$tfile
	test_mkdir $DIR/$tdir

	# there is a kernel bug in el9.x series (9.0 - 9.4 as we know till now)
	# kernel, we need to stat the target dir to cache it first
	if [[ "$CLIENT_OS_ID_LIKE" =~ "rhel" ]]; then
		if (( $CLIENT_OS_VERSION_CODE >= $(version_code 9.0) &&
		      $CLIENT_OS_VERSION_CODE <= $(version_code 9.100) )); then
			echo "stat $DIR/$tdir to cache it in el9.x"
			stat $DIR/$tdir
		fi
	fi

	strace ln -sf $DIR/$tfile $DIR/$tdir/ ||
		error "Failed to create symlink $DIR/$tfile under $DIR/$tdir/"
}
run_test 17p "symlink overwrite directory error message"

test_17q() {
	(( $MDS1_VERSION >= $(version_code v2_16_56-96-gd0c75da783) )) ||
		skip "Need MDS >= 2.16.56.96 for symlink xattr"
	local mdts=$(mdts_nodes)

	ln -s foo $DIR/$tfile
	setfattr -h -n trusted.test -v "$(head -200 /etc/services)" $DIR/$tfile ||
		error "setfattr large xattr on symlink failed"
	cancel_lru_locks mdc
	sysctl -w vm.drop_caches=3
	do_nodes $mdts sysctl -w vm.drop_caches=3
	ls -l $DIR/$tfile || error "ls -l failed"
}
run_test 17q "set large xattr on fast symlink"

test_18() {
	touch $DIR/$tfile || error "Failed to touch $DIR/$tfile: $?"
	ls $DIR || error "Failed to ls $DIR: $?"
}
run_test 18 "touch .../f ; ls ... =============================="

test_19a() {
	touch $DIR/$tfile
	ls -l $DIR
	rm $DIR/$tfile
	$CHECKSTAT -a $DIR/$tfile || error "$tfile was not removed"
}
run_test 19a "touch .../f19 ; ls -l ... ; rm .../f19 ==========="

test_19b() {
	ls -l $DIR/$tfile && error "ls -l $tfile failed"|| true
}
run_test 19b "ls -l .../f19 (should return error) =============="

test_19c() {
	[ $RUNAS_ID -eq $UID ] &&
		skip_env "RUNAS_ID = UID = $UID -- skipping"

	$RUNAS touch $DIR/$tfile && error "create non-root file failed" || true
}
run_test 19c "$RUNAS touch .../f19 (should return error) =="

test_19d() {
	cat $DIR/f19 && error || true
}
run_test 19d "cat .../f19 (should return error) =============="

test_20() {
	touch $DIR/$tfile
	rm $DIR/$tfile
	touch $DIR/$tfile
	rm $DIR/$tfile
	touch $DIR/$tfile
	rm $DIR/$tfile
	$CHECKSTAT -a $DIR/$tfile || error "$tfile was not removed"
}
run_test 20 "touch .../f ; ls -l ..."

test_21() {
	test_mkdir $DIR/$tdir
	[ -f $DIR/$tdir/dangle ] && rm -f $DIR/$tdir/dangle
	ln -s dangle $DIR/$tdir/link
	echo foo >> $DIR/$tdir/link
	cat $DIR/$tdir/dangle
	$CHECKSTAT -t link $DIR/$tdir/link || error "$tdir/link not a link"
	$CHECKSTAT -f -t file $DIR/$tdir/link ||
		error "$tdir/link not linked to a file"
}
run_test 21 "write to dangling link"

test_22() {
	local wdir=$DIR/$tdir
	test_mkdir $wdir
	chown $RUNAS_ID:$RUNAS_GID $wdir
	(cd $wdir || error "cd $wdir failed";
		$RUNAS tar cf - /etc/hosts /etc/sysconfig/network |
		$RUNAS tar xf -)
	ls -lR $wdir/etc || error "ls -lR $wdir/etc failed"
	$CHECKSTAT -t dir $wdir/etc || error "checkstat -t dir failed"
	$CHECKSTAT -u \#$RUNAS_ID -g \#$RUNAS_GID $wdir/etc ||
		error "checkstat -u failed"
}
run_test 22 "unpack tar archive as non-root user"

# was test_23
test_23a() {
	test_mkdir $DIR/$tdir
	local file=$DIR/$tdir/$tfile

	openfile -f O_CREAT:O_EXCL $file || error "$file create failed"
	openfile -f O_CREAT:O_EXCL $file &&
		error "$file recreate succeeded" || true
}
run_test 23a "O_CREAT|O_EXCL in subdir"

test_23b() { # bug 18988
	test_mkdir $DIR/$tdir
	local file=$DIR/$tdir/$tfile

	rm -f $file
	echo foo > $file || error "write filed"
	echo bar >> $file || error "append filed"
	$CHECKSTAT -s 8 $file || error "wrong size"
	rm $file
}
run_test 23b "O_APPEND check"

# LU-9409, size with O_APPEND and tiny writes
test_23c() {
	local file=$DIR/$tfile

	# single dd
	dd conv=notrunc oflag=append if=/dev/zero of=$file bs=8 count=800
	$CHECKSTAT -s 6400 $file || error "wrong size, expected 6400"
	rm -f $file

	# racing tiny writes
	dd conv=notrunc oflag=append if=/dev/zero of=$file bs=8 count=800 &
	dd conv=notrunc oflag=append if=/dev/zero of=$file bs=8 count=800 &
	wait
	$CHECKSTAT -s 12800 $file || error "wrong size, expected 12800"
	rm -f $file

	#racing tiny & normal writes
	dd conv=notrunc oflag=append if=/dev/zero of=$file bs=4096 count=4 &
	dd conv=notrunc oflag=append if=/dev/zero of=$file bs=8 count=100 &
	wait
	$CHECKSTAT -s 17184 $file || error "wrong size, expected 17184"
	rm -f $file

	#racing tiny & normal writes 2, ugly numbers
	dd conv=notrunc oflag=append if=/dev/zero of=$file bs=4099 count=11 &
	dd conv=notrunc oflag=append if=/dev/zero of=$file bs=17 count=173 &
	wait
	$CHECKSTAT -s 48030 $file || error "wrong size, expected 48030"
	rm -f $file
}
run_test 23c "O_APPEND size checks for tiny writes"

# LU-11069 file offset is correct after appending writes
test_23d() {
	local file=$DIR/$tfile
	local offset

	echo CentaurHauls > $file
	offset=$($MULTIOP $file oO_WRONLY:O_APPEND:w13Zp)
	if ((offset != 26)); then
		error "wrong offset, expected 26, got '$offset'"
	fi
}
run_test 23d "file offset is correct after appending writes"

# rename sanity
test_24a() {
	echo '-- same directory rename'
	test_mkdir $DIR/$tdir
	touch $DIR/$tdir/$tfile.1
	mv $DIR/$tdir/$tfile.1 $DIR/$tdir/$tfile.2
	$CHECKSTAT -t file $DIR/$tdir/$tfile.2 || error "$tfile.2 not a file"
}
run_test 24a "rename file to non-existent target"

test_24b() {
	test_mkdir $DIR/$tdir
	touch $DIR/$tdir/$tfile.{1,2}
	mv $DIR/$tdir/$tfile.1 $DIR/$tdir/$tfile.2
	$CHECKSTAT -a $DIR/$tdir/$tfile.1 || error "$tfile.1 exists"
	$CHECKSTAT -t file $DIR/$tdir/$tfile.2 || error "$tfile.2 not a file"
}
run_test 24b "rename file to existing target"

test_24c() {
	test_mkdir $DIR/$tdir
	test_mkdir $DIR/$tdir/d$testnum.1
	mv $DIR/$tdir/d$testnum.1 $DIR/$tdir/d$testnum.2
	$CHECKSTAT -a $DIR/$tdir/d$testnum.1 || error "d$testnum.1 exists"
	$CHECKSTAT -t dir $DIR/$tdir/d$testnum.2 || error "d$testnum.2 not dir"
}
run_test 24c "rename directory to non-existent target"

test_24d() {
	test_mkdir -c1 $DIR/$tdir
	test_mkdir -c1 $DIR/$tdir/d$testnum.1
	test_mkdir -c1 $DIR/$tdir/d$testnum.2
	mrename $DIR/$tdir/d$testnum.1 $DIR/$tdir/d$testnum.2
	$CHECKSTAT -a $DIR/$tdir/d$testnum.1 || error "d$testnum.1 exists"
	$CHECKSTAT -t dir $DIR/$tdir/d$testnum.2 || error "d$testnum.2 not dir"
}
run_test 24d "rename directory to existing target"

test_24e() {
	echo '-- cross directory renames --'
	test_mkdir $DIR/R5a
	test_mkdir $DIR/R5b
	touch $DIR/R5a/f
	mv $DIR/R5a/f $DIR/R5b/g
	$CHECKSTAT -a $DIR/R5a/f || error "$DIR/R5a/f exists"
	$CHECKSTAT -t file $DIR/R5b/g || error "$DIR/R5b/g not file type"
}
run_test 24e "touch .../R5a/f; rename .../R5a/f .../R5b/g ======"

test_24f() {
	test_mkdir $DIR/R6a
	test_mkdir $DIR/R6b
	touch $DIR/R6a/f $DIR/R6b/g
	mv $DIR/R6a/f $DIR/R6b/g
	$CHECKSTAT -a $DIR/R6a/f || error "$DIR/R6a/f exists"
	$CHECKSTAT -t file $DIR/R6b/g || error "$DIR/R6b/g not file type"
}
run_test 24f "touch .../R6a/f R6b/g; mv .../R6a/f .../R6b/g ===="

test_24g() {
	test_mkdir $DIR/R7a
	test_mkdir $DIR/R7b
	test_mkdir $DIR/R7a/d
	mv $DIR/R7a/d $DIR/R7b/e
	$CHECKSTAT -a $DIR/R7a/d || error "$DIR/R7a/d exists"
	$CHECKSTAT -t dir $DIR/R7b/e || error "$DIR/R7b/e not dir type"
}
run_test 24g "mkdir .../R7{a,b}/d; mv .../R7a/d .../R7b/e ======"

test_24h() {
	test_mkdir -c1 $DIR/R8a
	test_mkdir -c1 $DIR/R8b
	test_mkdir -c1 $DIR/R8a/d
	test_mkdir -c1 $DIR/R8b/e
	mrename $DIR/R8a/d $DIR/R8b/e
	$CHECKSTAT -a $DIR/R8a/d || error "$DIR/R8a/d exists"
	$CHECKSTAT -t dir $DIR/R8b/e || error "$DIR/R8b/e not dir type"
}
run_test 24h "mkdir .../R8{a,b}/{d,e}; rename .../R8a/d .../R8b/e"

test_24i() {
	echo "-- rename error cases"
	test_mkdir $DIR/R9
	test_mkdir $DIR/R9/a
	touch $DIR/R9/f
	mrename $DIR/R9/f $DIR/R9/a
	$CHECKSTAT -t file $DIR/R9/f || error "$DIR/R9/f not file type"
	$CHECKSTAT -t dir  $DIR/R9/a || error "$DIR/R9/a not dir type"
	$CHECKSTAT -a $DIR/R9/a/f || error "$DIR/R9/a/f exists"
}
run_test 24i "rename file to dir error: touch f ; mkdir a ; rename f a"

test_24j() {
	test_mkdir $DIR/R10
	mrename $DIR/R10/f $DIR/R10/g
	$CHECKSTAT -t dir $DIR/R10 || error "$DIR/R10 not dir type"
	$CHECKSTAT -a $DIR/R10/f || error "$DIR/R10/f exists"
	$CHECKSTAT -a $DIR/R10/g || error "$DIR/R10/g exists"
}
run_test 24j "source does not exist ============================"

test_24k() {
	test_mkdir $DIR/R11a
	test_mkdir $DIR/R11a/d
	touch $DIR/R11a/f
	mv $DIR/R11a/f $DIR/R11a/d
	$CHECKSTAT -a $DIR/R11a/f || error "$DIR/R11a/f exists"
	$CHECKSTAT -t file $DIR/R11a/d/f || error "$DIR/R11a/d/f not file type"
}
run_test 24k "touch .../R11a/f; mv .../R11a/f .../R11a/d ======="

# bug 2429 - rename foo foo foo creates invalid file
test_24l() {
	f="$DIR/f24l"
	$MULTIOP $f OcNs || error "rename of ${f} to itself failed"
}
run_test 24l "Renaming a file to itself ========================"

test_24m() {
	f="$DIR/f24m"
	$MULTIOP $f OcLN ${f}2 ${f}2 || error "link ${f}2 ${f}2 failed"
	# on ext3 this does not remove either the source or target files
	# though the "expected" operation would be to remove the source
	$CHECKSTAT -t file ${f} || error "${f} missing"
	$CHECKSTAT -t file ${f}2 || error "${f}2 missing"
}
run_test 24m "Renaming a file to a hard link to itself ========="

test_24n() {
    f="$DIR/f24n"
    # this stats the old file after it was renamed, so it should fail
    touch ${f}
    $CHECKSTAT ${f} || error "${f} missing"
    mv ${f} ${f}.rename
    $CHECKSTAT ${f}.rename || error "${f}.rename missing"
    $CHECKSTAT -a ${f} || error "${f} exists"
}
run_test 24n "Statting the old file after renaming (Posix rename 2)"

test_24o() {
	test_mkdir $DIR/$tdir
	rename_many -s random -v -n 10 $DIR/$tdir
}
run_test 24o "rename of files during htree split"

test_24p() {
	test_mkdir $DIR/R12a
	test_mkdir $DIR/R12b
	DIRINO=`ls -lid $DIR/R12a | awk '{ print $1 }'`
	mrename $DIR/R12a $DIR/R12b
	$CHECKSTAT -a $DIR/R12a || error "$DIR/R12a exists"
	$CHECKSTAT -t dir $DIR/R12b || error "$DIR/R12b not dir type"
	DIRINO2=`ls -lid $DIR/R12b | awk '{ print $1 }'`
	[ "$DIRINO" = "$DIRINO2" ] || error "R12a $DIRINO != R12b $DIRINO2"
}
run_test 24p "mkdir .../R12{a,b}; rename .../R12a .../R12b"

cleanup_multiop_pause() {
	trap 0
	kill -USR1 $MULTIPID
}

test_24q() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	test_mkdir $DIR/R13a
	test_mkdir $DIR/R13b
	local DIRINO=$(ls -lid $DIR/R13a | awk '{ print $1 }')
	multiop_bg_pause $DIR/R13b D_c || error "multiop failed to start"
	MULTIPID=$!

	trap cleanup_multiop_pause EXIT
	mrename $DIR/R13a $DIR/R13b
	$CHECKSTAT -a $DIR/R13a || error "R13a still exists"
	$CHECKSTAT -t dir $DIR/R13b || error "R13b does not exist"
	local DIRINO2=$(ls -lid $DIR/R13b | awk '{ print $1 }')
	[ "$DIRINO" = "$DIRINO2" ] || error "R13a $DIRINO != R13b $DIRINO2"
	cleanup_multiop_pause
	wait $MULTIPID || error "multiop close failed"
}
run_test 24q "mkdir .../R13{a,b}; open R13b rename R13a R13b ==="

test_24r() { #bug 3789
	test_mkdir $DIR/R14a
	test_mkdir $DIR/R14a/b
	mrename $DIR/R14a $DIR/R14a/b && error "rename to subdir worked!"
	$CHECKSTAT -t dir $DIR/R14a || error "$DIR/R14a missing"
	$CHECKSTAT -t dir $DIR/R14a/b || error "$DIR/R14a/b missing"
}
run_test 24r "mkdir .../R14a/b; rename .../R14a .../R14a/b ====="

test_24s() {
	test_mkdir $DIR/R15a
	test_mkdir $DIR/R15a/b
	test_mkdir $DIR/R15a/b/c
	mrename $DIR/R15a $DIR/R15a/b/c && error "rename to sub-subdir worked!"
	$CHECKSTAT -t dir $DIR/R15a || error "$DIR/R15a missing"
	$CHECKSTAT -t dir $DIR/R15a/b/c || error "$DIR/R15a/b/c missing"
}
run_test 24s "mkdir .../R15a/b/c; rename .../R15a .../R15a/b/c ="

test_24t() {
	test_mkdir $DIR/R16a
	test_mkdir $DIR/R16a/b
	test_mkdir $DIR/R16a/b/c
	mrename $DIR/R16a/b/c $DIR/R16a && error "rename to sub-subdir worked!"
	$CHECKSTAT -t dir $DIR/R16a || error "$DIR/R16a missing"
	$CHECKSTAT -t dir $DIR/R16a/b/c || error "$DIR/R16a/b/c missing"
}
run_test 24t "mkdir .../R16a/b/c; rename .../R16a/b/c .../R16a ="

test_24u() { # bug12192
	stack_trap "rm -f $DIR/$tfile"
	$MULTIOP $DIR/$tfile C2w$((2048 * 1024))c || error "multiop failed"
	$CHECKSTAT -s $((2048 * 1024)) $DIR/$tfile || error "wrong file size"
}
run_test 24u "create stripe file"

simple_cleanup_common() {
	local createmany=$1
	local rc=0

	[[ -z "$DIR" || -z "$tdir" || ! -d "$DIR/$tdir" ]] && return 0

	local start=$SECONDS

	[[ -n "$createmany" ]] && unlinkmany $DIR/$tdir/$tfile $createmany
	rm -rf $DIR/$tdir || error "cleanup $DIR/$tdir failed"
	rc=$?
	wait_delete_completed
	echo "cleanup time $((SECONDS - start))"
	return $rc
}

max_pages_per_rpc() {
	local mdtname="$(printf "MDT%04x" ${1:-0})"
	$LCTL get_param -n mdc.*$mdtname*.max_pages_per_rpc
}

test_24v() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	local nrfiles=${COUNT:-100000}
	local fname="$DIR/$tdir/$tfile"

	# Performance issue on ZFS see LU-4072 (c.f. LU-2887)
	[ "$mds1_FSTYPE" = "zfs" ] && nrfiles=${COUNT:-10000}

	test_mkdir "$(dirname $fname)"
	# assume MDT0000 has the fewest inodes
	local stripes=$($LFS getdirstripe -c $(dirname $fname))
	local free_inodes=$(($(mdt_free_inodes 0) * ${stripes/#0/1}))
	[[ $free_inodes -lt $nrfiles ]] && nrfiles=$free_inodes

	stack_trap "simple_cleanup_common $nrfiles"

	createmany -m "$fname" $nrfiles

	cancel_lru_locks mdc
	lctl set_param mdc.*.stats clear

	# was previously test_24D: LU-6101
	# readdir() returns correct number of entries after cursor reload
	local num_ls=$(ls $DIR/$tdir | wc -l)
	local num_uniq=$(ls $DIR/$tdir | sort -u | wc -l)
	local num_all=$(ls -a $DIR/$tdir | wc -l)
	if [ $num_ls -ne $nrfiles ] || [ $num_uniq -ne $nrfiles ] ||
		[ $num_all -ne $((nrfiles + 2)) ]; then
			error "Expected $nrfiles files, got $num_ls " \
				"($num_uniq unique $num_all .&..)"
	fi
	# LU-5 large readdir
	# dirent_size = 32 bytes for sizeof(struct lu_dirent) +
	#               N bytes for name (len($nrfiles) rounded to 8 bytes) +
	#               8 bytes for luda_type (4 bytes rounded to 8 bytes)
	# take into account of overhead in lu_dirpage header and end mark in
	# each page, plus one in rpc_num calculation.
	local dirent_size=$((32 + (${#tfile} | 7) + 1 + 8))
	local page_entries=$(((PAGE_SIZE - 24) / dirent_size))
	local mdt_idx=$($LFS getdirstripe -i $(dirname $fname))
	local rpc_pages=$(max_pages_per_rpc $mdt_idx)
	local rpc_max=$((nrfiles / (page_entries * rpc_pages) + stripes))
	local mds_readpage=$(calc_stats mdc.*.stats mds_readpage)
	echo "readpages: $mds_readpage rpc_max: $rpc_max-2/+1"
	(( $mds_readpage >= $rpc_max - 2 && $mds_readpage <= $rpc_max + 1)) ||
		error "large readdir doesn't take effect: " \
		      "$mds_readpage should be about $rpc_max"
}
run_test 24v "list large directory (test hash collision, b=17560)"

test_24w() { # bug21506
        SZ1=234852
	stack_trap "rm -f $DIR/$tfile"
        dd if=/dev/zero of=$DIR/$tfile bs=1M count=1 seek=4096 || return 1
        dd if=/dev/zero bs=$SZ1 count=1 >> $DIR/$tfile || return 2
        dd if=$DIR/$tfile of=$DIR/${tfile}_left bs=1M skip=4097 || return 3
        SZ2=`ls -l $DIR/${tfile}_left | awk '{print $5}'`
	[[ "$SZ1" -eq "$SZ2" ]] ||
                error "Error reading at the end of the file $tfile"
}
run_test 24w "Reading a file larger than 4Gb"

test_24x() {
	[[ $MDSCOUNT -lt 2 ]] && skip_env "needs >= 2 MDTs"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[[ $MDS1_VERSION -lt $(version_code 2.7.56) ]] &&
		skip "Need MDS version at least 2.7.56"

	local MDTIDX=1
	local remote_dir=$DIR/$tdir/remote_dir

	test_mkdir $DIR/$tdir
	$LFS mkdir -i $MDTIDX $remote_dir ||
		error "create remote directory failed"

	test_mkdir $DIR/$tdir/src_dir
	touch $DIR/$tdir/src_file
	test_mkdir $remote_dir/tgt_dir
	touch $remote_dir/tgt_file

	mrename $DIR/$tdir/src_dir $remote_dir/tgt_dir ||
		error "rename dir cross MDT failed!"

	mrename $DIR/$tdir/src_file $remote_dir/tgt_file ||
		error "rename file cross MDT failed!"

	touch $DIR/$tdir/ln_file
	ln $DIR/$tdir/ln_file $remote_dir/ln_name ||
		error "ln file cross MDT failed"

	rm -rf $DIR/$tdir || error "Can not delete directories"
}
run_test 24x "cross MDT rename/link"

test_24y() {
	[[ $MDSCOUNT -lt 2 ]] && skip_env "needs >= 2 MDTs"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	local remote_dir=$DIR/$tdir/remote_dir
	local mdtidx=1

	test_mkdir $DIR/$tdir
	$LFS mkdir -i $mdtidx $remote_dir ||
		error "create remote directory failed"

	test_mkdir $remote_dir/src_dir
	touch $remote_dir/src_file
	test_mkdir $remote_dir/tgt_dir
	touch $remote_dir/tgt_file

	mrename $remote_dir/src_dir $remote_dir/tgt_dir ||
		error "rename subdir in the same remote dir failed!"

	mrename $remote_dir/src_file $remote_dir/tgt_file ||
		error "rename files in the same remote dir failed!"

	ln $remote_dir/tgt_file $remote_dir/tgt_file1 ||
		error "link files in the same remote dir failed!"

	rm -rf $DIR/$tdir || error "Can not delete directories"
}
run_test 24y "rename/link on the same dir should succeed"

test_24z() {
	[[ $MDSCOUNT -lt 2 ]] && skip_env "needs >= 2 MDTs"
	[[ $MDS1_VERSION -lt $(version_code 2.12.51) ]] &&
		skip "Need MDS version at least 2.12.51"

	local index

	for index in 0 1; do
		$LFS mkdir -i $index $DIR/$tdir.$index || error "mkdir failed"
		touch $DIR/$tdir.0/$tfile.$index || error "touch failed"
	done

	mv $DIR/$tdir.0/$tfile.0 $DIR/$tdir.1 || error "mv $tfile.0 failed"

	index=$($LFS getstripe -m $DIR/$tdir.1/$tfile.0)
	[ $index -eq 0 ] || error "$tfile.0 is on MDT$index"

	local mdts=$(mdts_nodes)

	do_nodes $mdts $LCTL set_param mdt.*.enable_remote_rename=0
	stack_trap "do_nodes $mdts $LCTL \
		set_param mdt.*.enable_remote_rename=1" EXIT

	mv $DIR/$tdir.0/$tfile.1 $DIR/$tdir.1 || error "mv $tfile.1 failed"

	index=$($LFS getstripe -m $DIR/$tdir.1/$tfile.1)
	[ $index -eq 1 ] || error "$tfile.1 is on MDT$index"
}
run_test 24z "cross-MDT rename is done as cp"

test_24A() { # LU-3182
	local NFILES=5000

	test_mkdir $DIR/$tdir
	stack_trap "simple_cleanup_common $NFILES"
	createmany -m $DIR/$tdir/$tfile $NFILES
	local t=$(ls $DIR/$tdir | wc -l)
	local u=$(ls $DIR/$tdir | sort -u | wc -l)
	local v=$(ls -ai $DIR/$tdir | sort -u | wc -l)

	(( $t == $NFILES && $u == $NFILES && $v == NFILES + 2 )) ||
		error "Expected $NFILES files, got $t ($u unique $v .&..)"
}
run_test 24A "readdir() returns correct number of entries."

test_24B() { # LU-4805
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"

	local count

	test_mkdir $DIR/$tdir
	$LFS setdirstripe -i0 -c$MDSCOUNT $DIR/$tdir/striped_dir/ ||
		error "create striped dir failed"

	count=$(ls -ai $DIR/$tdir/striped_dir | wc -l)
	[ $count -eq 2 ] || error "Expected 2, got $count"

	touch $DIR/$tdir/striped_dir/a

	count=$(ls -ai $DIR/$tdir/striped_dir | wc -l)
	[ $count -eq 3 ] || error "Expected 3, got $count"

	touch $DIR/$tdir/striped_dir/.f

	count=$(ls -ai $DIR/$tdir/striped_dir | wc -l)
	[ $count -eq 4 ] || error "Expected 4, got $count"

	rm -rf $DIR/$tdir || error "Can not delete directories"
}
run_test 24B "readdir for striped dir return correct number of entries"

test_24C() {
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"

	mkdir $DIR/$tdir
	mkdir $DIR/$tdir/d0
	mkdir $DIR/$tdir/d1

	$LFS setdirstripe -i0 -c$MDSCOUNT $DIR/$tdir/d0/striped_dir ||
		error "create striped dir failed"

	cd $DIR/$tdir/d0/striped_dir

	local d0_ino=$(ls -i -l -a $DIR/$tdir | grep "d0" | awk '{print $1}')
	local d1_ino=$(ls -i -l -a $DIR/$tdir | grep "d1" | awk '{print $1}')
	local parent_ino=$(ls -i -l -a | grep "\.\." | awk '{print $1}')

	[ "$d0_ino" = "$parent_ino" ] ||
		error ".. wrong, expect $d0_ino, get $parent_ino"

	mv $DIR/$tdir/d0/striped_dir $DIR/$tdir/d1/ ||
		error "mv striped dir failed"

	parent_ino=$(ls -i -l -a | grep "\.\." | awk '{print $1}')

	[ "$d1_ino" = "$parent_ino" ] ||
		error ".. wrong after mv, expect $d1_ino, get $parent_ino"
}
run_test 24C "check .. in striped dir"

test_24E() {
	[[ $MDSCOUNT -lt 4 ]] && skip_env "needs >= 4 MDTs"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	mkdir -p $DIR/$tdir
	mkdir $DIR/$tdir/src_dir
	$LFS mkdir -i 1 $DIR/$tdir/src_dir/src_child ||
		error "create remote source failed"

	touch $DIR/$tdir/src_dir/src_child/a

	$LFS mkdir -i 2 $DIR/$tdir/tgt_dir ||
		error "create remote target dir failed"

	$LFS mkdir -i 3 $DIR/$tdir/tgt_dir/tgt_child ||
		error "create remote target child failed"

	mrename $DIR/$tdir/src_dir/src_child $DIR/$tdir/tgt_dir/tgt_child ||
		error "rename dir cross MDT failed!"

	find $DIR/$tdir

	$CHECKSTAT -t dir $DIR/$tdir/src_dir/src_child &&
		error "src_child still exists after rename"

	$CHECKSTAT -t file $DIR/$tdir/tgt_dir/tgt_child/a ||
		error "missing file(a) after rename"

	rm -rf $DIR/$tdir || error "Can not delete directories"
}
run_test 24E "cross MDT rename/link"

test_24F () {
	[ $MDSCOUNT -lt 2 ] && skip "needs >= 2 MDTs" && return 0

	local repeats=1000
	[ "$SLOW" = "no" ] && repeats=100

	mkdir -p $DIR/$tdir

	echo "$repeats repeats"
	for ((i = 0; i < repeats; i++)); do
		$LFS mkdir -i0 -c2 $DIR/$tdir/test || error "mkdir fails"
		touch $DIR/$tdir/test/a || error "touch fails"
		mkdir $DIR/$tdir/test/b || error "mkdir fails"
		rm -rf $DIR/$tdir/test || error "rmdir fails"
	done

	true
}
run_test 24F "hash order vs readdir (LU-11330)"

test_24G () {
	[ $MDSCOUNT -lt 2 ] && skip "needs >= 2 MDTs"

	(( $MDS1_VERSION >= $(version_code v2_13_56-59-g9adc02c016d2) )) ||
		skip "Need MDS >= v2_13_56-59-g9adc02c016d2 for symlink migration"

	local ino1
	local ino2

	$LFS mkdir -i 0 $DIR/$tdir-0 || error "mkdir $tdir-0"
	$LFS mkdir -i 1 $DIR/$tdir-1 || error "mkdir $tdir-1"
	touch $DIR/$tdir-0/f1 || error "touch f1"
	ln -s $DIR/$tdir-0/f1 $DIR/$tdir-0/s1 || error "ln s1"
	ino1=$(stat -c%i $DIR/$tdir-0/s1)
	mv $DIR/$tdir-0/s1 $DIR/$tdir-1 || error "mv s1"
	ino2=$(stat -c%i $DIR/$tdir-1/s1)
	[ $ino1 -ne $ino2 ] || error "s1 should be migrated"
}
run_test 24G "migrate symlink in rename"

test_24H() {
	[ $MDSCOUNT -lt 2 ] && skip "needs >= 2 MDTs"
	[[ $(hostname) != $(facet_active_host mds2) ]] ||
		skip "MDT1 should be on another node"

	test_mkdir -i 1 -c 1 $DIR/$tdir
#define OBD_FAIL_FLD_QUERY_REQ           0x1103
	do_facet mds2 $LCTL set_param fail_loc=0x80001103
	touch $DIR/$tdir/$tfile || error "touch failed"
}
run_test 24H "repeat FLD_QUERY rpc"

test_24I() {
	(( $MDSCOUNT > 1 )) || skip "needs >= 2 MDTs"

	# LMV_MAX_STRIPE_COUNT = 2000 should be verified
	$LFS mkdir -C 2001 $DIR/$tdir-2001 && error "mkdir 2001-stripe worked"
	$LFS mkdir -C 2000 $DIR/$tdir-2000 || error "mkdir 2000-stripe failed"
	local stripes=$($LFS getdirstripe -c $DIR/$tdir-2000)
	# LMV_OVERSTRIPE_COUNT_MAX = 5 limits actual stripe count
	(( $stripes >= $MDSCOUNT * 5)) ||
		error "mkdir stripes $stripes < $MDSCOUNT * 5"
}
run_test 24I "large striped mkdir with limit check"

test_25a() {
	echo '== symlink sanity ============================================='

	test_mkdir $DIR/d25
	ln -s d25 $DIR/s25
	touch $DIR/s25/foo ||
		error "File creation in symlinked directory failed"
}
run_test 25a "create file in symlinked directory ==============="

test_25b() {
	[ ! -d $DIR/d25 ] && test_25a
	$CHECKSTAT -t file $DIR/s25/foo || error "$DIR/s25/foo not file type"
}
run_test 25b "lookup file in symlinked directory ==============="

test_26a() {
	test_mkdir $DIR/d26
	test_mkdir $DIR/d26/d26-2
	ln -s d26/d26-2 $DIR/s26
	touch $DIR/s26/foo || error "File creation failed"
}
run_test 26a "multiple component symlink ======================="

test_26b() {
	test_mkdir -p $DIR/$tdir/d26-2
	ln -s $tdir/d26-2/foo $DIR/s26-2
	touch $DIR/s26-2 || error "File creation failed"
}
run_test 26b "multiple component symlink at end of lookup ======"

test_26c() {
	test_mkdir $DIR/d26.2
	touch $DIR/d26.2/foo
	ln -s d26.2 $DIR/s26.2-1
	ln -s s26.2-1 $DIR/s26.2-2
	ln -s s26.2-2 $DIR/s26.2-3
	chmod 0666 $DIR/s26.2-3/foo
}
run_test 26c "chain of symlinks"

# recursive symlinks (bug 439)
test_26d() {
	ln -s d26-3/foo $DIR/d26-3
}
run_test 26d "create multiple component recursive symlink"

test_26e() {
	[ ! -h $DIR/d26-3 ] && test_26d
	rm $DIR/d26-3
}
run_test 26e "unlink multiple component recursive symlink"

# recursive symlinks (bug 7022)
test_26f() {
	test_mkdir $DIR/$tdir
	test_mkdir $DIR/$tdir/$tfile
	cd $DIR/$tdir/$tfile           || error "cd $DIR/$tdir/$tfile failed"
	test_mkdir -p lndir/bar1
	test_mkdir $DIR/$tdir/$tfile/$tfile
	cd $tfile                || error "cd $tfile failed"
	ln -s .. dotdot          || error "ln dotdot failed"
	ln -s dotdot/lndir lndir || error "ln lndir failed"
	cd $DIR/$tdir                 || error "cd $DIR/$tdir failed"
	output=`ls $tfile/$tfile/lndir/bar1`
	[ "$output" = bar1 ] && error "unexpected output"
	rm -r $tfile             || error "rm $tfile failed"
	$CHECKSTAT -a $DIR/$tfile || error "$tfile not gone"
}
run_test 26f "rm -r of a directory which has recursive symlink"

test_27a() {
	test_mkdir $DIR/$tdir
	$LFS getstripe $DIR/$tdir
	$LFS setstripe -c 1 $DIR/$tdir/$tfile || error "setstripe failed"
	$CHECKSTAT -t file $DIR/$tdir/$tfile || error "checkstat failed"
	cp /etc/hosts $DIR/$tdir/$tfile || error "Can't copy to one stripe file"
}
run_test 27a "one stripe file"

test_27b() {
	[[ $OSTCOUNT -lt 2 ]] && skip_env "needs >= 2 OSTs"

	test_mkdir $DIR/$tdir
	$LFS setstripe -c 2 $DIR/$tdir/$tfile || error "setstripe failed"
	$LFS getstripe -c $DIR/$tdir/$tfile
	[ $($LFS getstripe -c $DIR/$tdir/$tfile) -eq 2 ] ||
		error "two-stripe file doesn't have two stripes"

	dd if=/dev/zero of=$DIR/$tdir/$tfile bs=4k count=4 || error "dd failed"
}
run_test 27b "create and write to two stripe file"

# 27c family tests specific striping, setstripe -o
test_27ca() {
	[[ $OSTCOUNT -lt 2 ]] && skip_env "skipping 2-stripe test"
	test_mkdir -p $DIR/$tdir
	local osts="1"

	$LFS setstripe -o $osts $DIR/$tdir/$tfile  || error "setstripe failed"
	$LFS getstripe -i $DIR/$tdir/$tfile
	[ $($LFS getstripe -i $DIR/$tdir/$tfile ) -eq $osts ] ||
		error "stripe not on specified OST"

	dd if=/dev/zero of=$DIR/$tdir/$tfile  bs=1M count=4 || error "dd failed"
}
run_test 27ca "one stripe on specified OST"

test_27cb() {
	[[ $OSTCOUNT -lt 2 ]] && skip_env "skipping 2-stripe test"
	test_mkdir -p $DIR/$tdir
	local osts="1,0"
	$LFS setstripe -o $osts $DIR/$tdir/$tfile || error "setstripe failed"
	local getstripe=$($LFS getstripe $DIR/$tdir/$tfile)
	echo "$getstripe"

	# Strip getstripe output to a space separated list of OSTs
	local getstripe_osts=$(echo "$getstripe" | sed -e '1,/obdidx/d' |\
		awk '{print $1}' | tr '\n' ' ' | sed -e 's/[[:space:]]*$//')
	[ "$getstripe_osts" = "${osts//,/ }" ] ||
		error "stripes not on specified OSTs"

	dd if=/dev/zero of=$DIR/$tdir/$tfile bs=1M count=4 || error "dd failed"
}
run_test 27cb "two stripes on specified OSTs"

test_27cc() {
	[[ $OSTCOUNT -lt 2 ]] && skip_env "skipping 2-stripe test"
	[[ $($LCTL get_param mdc.*.import) =~ connect_flags.*overstriping ]] ||
		skip "server does not support overstriping"

	test_mkdir -p $DIR/$tdir
	local osts="0,0"
	$LFS setstripe -o $osts $DIR/$tdir/$tfile || error "setstripe failed"
	local getstripe=$($LFS getstripe $DIR/$tdir/$tfile)
	echo "$getstripe"

	# Strip getstripe output to a space separated list of OSTs
	local getstripe_osts=$(echo "$getstripe" | sed -e '1,/obdidx/d' |\
		awk '{print $1}' | tr '\n' ' ' | sed -e 's/[[:space:]]*$//')
	[ "$getstripe_osts" = "${osts//,/ }" ] ||
		error "stripes not on specified OSTs"

	dd if=/dev/zero of=$DIR/$tdir/$tfile bs=1M count=4 || error "dd failed"
}
run_test 27cc "two stripes on the same OST"

test_27cd() {
	[[ $OSTCOUNT -lt 2 ]] && skip_env "skipping 2-stripe test"
	[[ $($LCTL get_param mdc.*.import) =~ connect_flags.*overstriping ]] ||
		skip "server does not support overstriping"
	test_mkdir -p $DIR/$tdir
	local osts="0,1,1,0"
	$LFS setstripe -o $osts $DIR/$tdir/$tfile || error "setstripe failed"
	local getstripe=$($LFS getstripe $DIR/$tdir/$tfile)
	echo "$getstripe"

	# Strip getstripe output to a space separated list of OSTs
	local getstripe_osts=$(echo "$getstripe" | sed -e '1,/obdidx/d' |\
		awk '{print $1}' | tr '\n' ' ' | sed -e 's/[[:space:]]*$//')
	[ "$getstripe_osts" = "${osts//,/ }" ] ||
		error "stripes not on specified OSTs"

	dd if=/dev/zero of=$DIR/$tdir/$tfile bs=1M count=4 || error "dd failed"
}
run_test 27cd "four stripes on two OSTs"

test_27ce() {
	[[ $OSTCOUNT -ge $(($LOV_MAX_STRIPE_COUNT / 2)) ]] &&
		skip_env "too many osts, skipping"
	[[ $($LCTL get_param mdc.*.import) =~ connect_flags.*overstriping ]] ||
		skip "server does not support overstriping"
	# We do one more stripe than we have OSTs
	[ $OSTCOUNT -lt 159 ] || large_xattr_enabled ||
		skip_env "ea_inode feature disabled"

	test_mkdir -p $DIR/$tdir
	local osts=""
	for i in $(seq 0 $OSTCOUNT);
	do
		osts=$osts"0"
		if [ $i -ne $OSTCOUNT ]; then
			osts=$osts","
		fi
	done

	echo "$LFS setstripe -o $osts $DIR/$tdir/$tfile"
	$LFS setstripe -o $osts $DIR/$tdir/$tfile || error "setstripe failed"
	local getstripe=$($LFS getstripe $DIR/$tdir/$tfile)
	echo "$getstripe"

	# Strip getstripe output to a space separated list of OSTs
	local getstripe_osts=$(echo "$getstripe" | sed -e '1,/obdidx/d' |\
		awk '{print $1}' | tr '\n' ' ' | sed -e 's/[[:space:]]*$//')
	[ "$getstripe_osts" = "${osts//,/ }" ] ||
		error "stripes '$getstripe_osts' not on given OSTs ${osts//,/ }"

	dd if=/dev/zero of=$DIR/$tdir/$tfile bs=1M count=4 || error "dd failed"
}
run_test 27ce "more stripes than OSTs with -o"

test_27cf() {
	local osp_proc="osp.$FSNAME-OST0000-osc-MDT000*.active"
	local pid=0

	test_mkdir -p $DIR/$tdir || error "failed to mkdir $DIR/$tdir"
	do_facet $SINGLEMDS "$LCTL set_param -n $osp_proc=0"
	stack_trap "do_facet $SINGLEMDS $LCTL set_param -n $osp_proc=1" EXIT
	wait_update_facet $SINGLEMDS "$LCTL get_param -n $osp_proc | grep 1" ||
		error "failed to set $osp_proc=0"

	$LFS setstripe -o 0 $DIR/$tdir/$tfile &
	pid=$!
	sleep 1
	do_facet $SINGLEMDS "$LCTL set_param -n $osp_proc=1"
	wait_update_facet $SINGLEMDS "$LCTL get_param -n $osp_proc | grep 0" ||
		error "failed to set $osp_proc=1"
	wait $pid
	[[ $pid -ne 0 ]] ||
		error "should return error due to $osp_proc=0"
}
run_test 27cf "'setstripe -o' on inactive OSTs should return error"

test_27cg() {
	[[ $($LCTL get_param mdc.*.import) =~ connect_flags.*overstriping ]] ||
		skip "server does not support overstriping"
	[[ $mds1_FSTYPE != "ldiskfs" ]] && skip_env "ldiskfs only test"
	large_xattr_enabled || skip_env "ea_inode feature disabled"

	local osts="0"

	for ((i=1;i<1000;i++)); do
		osts+=",$((i % OSTCOUNT))"
	done

	local mdts=$(mdts_nodes)
	local before=$(do_nodes $mdts \
		"$LCTL get_param -n osd-ldiskfs.*MDT*.stats" |
		awk '/many credits/{print $3}' |
		calc_sum)

	$LFS setstripe -o $osts $DIR/$tfile || {
		$LFS df
		$LFS df -i
		error "setstripe failed"
	}
	$LFS getstripe $DIR/$tfile | grep stripe

	rm -f $DIR/$tfile || error "can't unlink"

	# if running in a loop, don't run out of inodes on these OSTs
	(( $ONLY_REPEAT_ITER % 20 < 19 )) || {
		$LFS df
		$LFS df -i
		wait_delete_completed
		sleep 10
	}
	(( $ONLY_REPEAT_ITER < 100 )) || skip "too many iterations"

	after=$(do_nodes $mdts \
		"$LCTL get_param -n osd-ldiskfs.*MDT*.stats" |
		awk '/many credits/{print $3}' |
		calc_sum)

	(( before == after )) ||
		error "too many credits happened: $after > $before"
}
run_test 27cg "1000 shouldn't cause too many credits"

test_27d() {
	test_mkdir $DIR/$tdir
	$LFS setstripe -c 0 -i -1 -S 0 $DIR/$tdir/$tfile ||
		error "setstripe failed"
	$CHECKSTAT -t file $DIR/$tdir/$tfile || error "checkstat failed"
	dd if=/dev/zero of=$DIR/$tdir/$tfile bs=4k count=4 || error "dd failed"
}
run_test 27d "create file with default settings"

test_27e() {
	# LU-5839 adds check for existed layout before setting it
	[[ $MDS1_VERSION -lt $(version_code 2.7.56) ]] &&
		skip "Need MDS version at least 2.7.56"

	test_mkdir $DIR/$tdir
	$LFS setstripe -c 2 $DIR/$tdir/$tfile || error "setstripe failed"
	$LFS setstripe -c 2 $DIR/$tdir/$tfile && error "setstripe worked twice"
	$CHECKSTAT -t file $DIR/$tdir/$tfile || error "checkstat failed"
}
run_test 27e "setstripe existing file (should return error)"

test_27f() {
	test_mkdir $DIR/$tdir
	$LFS setstripe -S 100 -i 0 -c 1 $DIR/$tdir/$tfile &&
		error "$LFS setstripe $DIR/$tdir/$tfile failed"
	$CHECKSTAT -t file $DIR/$tdir/$tfile &&
		error "$CHECKSTAT -t file $DIR/$tdir/$tfile should fail"
	dd if=/dev/zero of=$DIR/$tdir/$tfile bs=4k count=4 || error "dd failed"
	$LFS getstripe $DIR/$tdir/$tfile || error "$LFS getstripe failed"
}
run_test 27f "setstripe with bad stripe size (should return error)"

test_27g() {
	test_mkdir $DIR/$tdir
	$MCREATE $DIR/$tdir/$tfile || error "mcreate failed"
	$LFS getstripe $DIR/$tdir/$tfile 2>&1 | grep "no stripe info" ||
		error "$DIR/$tdir/$tfile has object"
}
run_test 27g "$LFS getstripe with no objects"

test_27ga() {
	test_mkdir $DIR/$tdir
	touch $DIR/$tdir/$tfile || error "touch failed"
	ln -s bogus $DIR/$tdir/$tfile.2 || error "ln failed"
	$LFS getstripe -m $DIR/$tdir/$tfile $DIR/$tdir/$tfile.2
	local rc=$?
	(( rc == 2 )) || error "getstripe did not return ENOENT"

	local err_msg=$($LFS getstripe $DIR/$tdir/typo $DIR/$tdir/$tfile \
			2>&1 > /dev/null)
	[[ $err_msg =~ "typo" ]] ||
		error "expected message with correct filename, got '$err_msg'"
}
run_test 27ga "$LFS getstripe with missing file (should return error)"

test_27i() {
	test_mkdir $DIR/$tdir
	touch $DIR/$tdir/$tfile || error "touch failed"
	[[ $($LFS getstripe -c $DIR/$tdir/$tfile) -gt 0 ]] ||
		error "missing objects"
}
run_test 27i "$LFS getstripe with some objects"

test_27j() {
	test_mkdir $DIR/$tdir
	$LFS setstripe -i $OSTCOUNT $DIR/$tdir/$tfile &&
		error "setstripe failed" || true
}
run_test 27j "setstripe with bad stripe offset (should return error)"

test_27k() { # bug 2844
	test_mkdir $DIR/$tdir
	local file=$DIR/$tdir/$tfile
	local ll_max_blksize=$((4 * 1024 * 1024))
	$LFS setstripe -S 67108864 $file || error "setstripe failed"
	local blksize=$(stat $file | awk '/IO Block:/ { print $7 }')
	[ $blksize -le $ll_max_blksize ] || error "1:$blksize > $ll_max_blksize"
	dd if=/dev/zero of=$file bs=4k count=1
	blksize=$(stat $file | awk '/IO Block:/ { print $7 }')
	[ $blksize -le $ll_max_blksize ] || error "2:$blksize > $ll_max_blksize"
}
run_test 27k "limit i_blksize for broken user apps"

test_27l() {
	mcreate $DIR/$tfile || error "creating file"
	$RUNAS $LFS setstripe -c 1 $DIR/$tfile &&
		error "setstripe should have failed" || true
}
run_test 27l "check setstripe permissions (should return error)"

test_27m() {
	[[ $OSTCOUNT -lt 2 ]] && skip_env "needs >= 2 OSTs"

	[ -n "$RCLIENTS" -o -n "$MOUNT_2" ] &&
		skip_env "multiple clients -- skipping"

	ORIGFREE=$($LCTL get_param -n lov.$FSNAME-clilov-*.kbytesavail |
		   head -n1)
	if [[ $ORIGFREE -gt $MAXFREE ]]; then
		skip "$ORIGFREE > $MAXFREE skipping out-of-space test on OST0"
	fi
	stack_trap simple_cleanup_common
	test_mkdir $DIR/$tdir
	$LFS setstripe -i 0 -c 1 $DIR/$tdir/$tfile.1
	fast_file_write $DIR/$tdir/$tfile.1 1024K $MAXFREE &&
		error "write should fill OST0"
	i=2
	while $LFS setstripe -i 0 -c 1 $DIR/$tdir/$tfile.$i; do
		i=$((i + 1))
		[ $i -gt 256 ] && break
	done
	i=$((i + 1))
	touch $DIR/$tdir/$tfile.$i
	[ $($LFS getstripe $DIR/$tdir/$tfile.$i | grep -A 10 obdidx |
	    awk '{print $1}'| grep -w "0") ] &&
		error "OST0 was full but new created file still use it"
	i=$((i + 1))
	touch $DIR/$tdir/$tfile.$i
	[ $($LFS getstripe $DIR/$tdir/$tfile.$i | grep -A 10 obdidx |
	    awk '{print $1}'| grep -w "0") ] &&
		error "OST0 was full but new created file still use it" || true
}
run_test 27m "create file while OST0 was full"

# OSCs keep a NOSPC flag that will be reset after ~5s (qos_maxage)
# if the OST isn't full anymore.
reset_enospc() {
	local ostidx=${1:-""}
	local delay
	local ready
	local get_prealloc
	local osts

	[[ -n "$ostidx" ]] && osts=$(facet_host ost$((ostidx + 1))) ||
		osts=$(osts_nodes)

	do_nodes $osts lctl set_param fail_loc=0
	wait_delete_completed	# initiate all OST_DESTROYs from MDS to OST
	delay=$(do_facet $SINGLEMDS lctl get_param -n lov.*.qos_maxage |
		awk '{print $1 * 2;exit;}')
	get_prealloc="$LCTL get_param -n osc.*MDT*.prealloc_status |
			grep -v \"^0$\""
	wait_update_facet $SINGLEMDS "$get_prealloc" "" $delay
}

test_27n() {
	[[ $OSTCOUNT -lt 2 ]] && skip_env "needs >= 2 OSTs"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	remote_ost_nodsh && skip "remote OST with nodsh"

	reset_enospc
	rm -f $DIR/$tdir/$tfile
	exhaust_precreations 0 0x80000215
	$LFS setstripe -c -1 $DIR/$tdir || error "setstripe failed"
	touch $DIR/$tdir/$tfile || error "touch failed"
	$LFS getstripe $DIR/$tdir/$tfile
	reset_enospc
}
run_test 27n "create file with some full OSTs"

test_27o() {
	[[ $OSTCOUNT -lt 2 ]] && skip_env "needs >= 2 OSTs"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	remote_ost_nodsh && skip "remote OST with nodsh"

	reset_enospc
	rm -f $DIR/$tdir/$tfile
	exhaust_all_precreations 0x215

	touch $DIR/$tdir/$tfile && error "able to create $DIR/$tdir/$tfile"

	reset_enospc
	rm -rf $DIR/$tdir/*
}
run_test 27o "create file with all full OSTs (should error)"

function create_and_checktime() {
	local fname=$1
	local loops=$2
	local i

	for ((i=0; i < $loops; i++)); do
		local start=$SECONDS
		multiop $fname-$i Oc
		((SECONDS-start < TIMEOUT)) ||
			error "creation took " $((SECONDS-$start)) && return 1
	done
}

test_27oo() {
	local mdts=$(mdts_nodes)

	(( $MDS1_VERSION >= $(version_code 2.13.57) )) ||
		skip "Need MDS version at least 2.13.57"

	local f0=$DIR/${tfile}-0
	local f1=$DIR/${tfile}-1

	wait_delete_completed

	# refill precreated objects
	$LFS setstripe -i0 -c1 $f0

	saved=$(do_facet mds1 $LCTL get_param -n lov.*0000*.qos_threshold_rr)
	# force QoS allocation policy
	do_nodes $mdts $LCTL set_param lov.*.qos_threshold_rr=0%
	stack_trap "do_nodes $mdts $LCTL set_param \
		lov.*.qos_threshold_rr=$saved" EXIT
	sleep_maxage

	# one OST is unavailable, but still have few objects preallocated
	stop ost1
	stack_trap "start ost1 $(ostdevname 1) $OST_MOUNT_OPTS; \
		rm -rf $f1 $DIR/$tdir*" EXIT

	for ((i=0; i < 7; i++)); do
		mkdir $DIR/$tdir$i || error "can't create dir"
		$LFS setstripe -c$((OSTCOUNT-1)) $DIR/$tdir$i ||
			error "can't set striping"
	done
	for ((i=0; i < 7; i++)); do
		create_and_checktime $DIR/$tdir$i/$tfile 100 &
	done
	wait
}
run_test 27oo "don't let few threads to reserve too many objects"

test_27p() {
	[[ $OSTCOUNT -lt 2 ]] && skip_env "needs >= 2 OSTs"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	remote_ost_nodsh && skip "remote OST with nodsh"

	reset_enospc
	rm -f $DIR/$tdir/$tfile
	test_mkdir $DIR/$tdir || error "failed to mkdir $DIR/$tdir"

	$MCREATE $DIR/$tdir/$tfile || error "mcreate failed"
	$TRUNCATE $DIR/$tdir/$tfile 80000000 || error "truncate failed"
	$CHECKSTAT -s 80000000 $DIR/$tdir/$tfile || error "checkstat failed"

	exhaust_precreations 0 0x80000215
	echo foo >> $DIR/$tdir/$tfile || error "append failed"
	$CHECKSTAT -s 80000004 $DIR/$tdir/$tfile || error "checkstat failed"
	$LFS getstripe $DIR/$tdir/$tfile

	reset_enospc
}
run_test 27p "append to a truncated file with some full OSTs"

test_27q() {
	[[ $OSTCOUNT -lt 2 ]] && skip_env "needs >= 2 OSTs"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	remote_ost_nodsh && skip "remote OST with nodsh"

	reset_enospc
	rm -f $DIR/$tdir/$tfile

	mkdir_on_mdt0 $DIR/$tdir
	$MCREATE $DIR/$tdir/$tfile || error "mcreate $DIR/$tdir/$tfile failed"
	$TRUNCATE $DIR/$tdir/$tfile 80000000 ||
		error "truncate $DIR/$tdir/$tfile failed"
	$CHECKSTAT -s 80000000 $DIR/$tdir/$tfile || error "checkstat failed"

	exhaust_all_precreations 0x215

	echo foo >> $DIR/$tdir/$tfile && error "append succeeded"
	$CHECKSTAT -s 80000000 $DIR/$tdir/$tfile || error "checkstat 2 failed"

	reset_enospc
}
run_test 27q "append to truncated file with all OSTs full (should error)"

test_27r() {
	[[ $OSTCOUNT -lt 2 ]] && skip_env "needs >= 2 OSTs"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	remote_ost_nodsh && skip "remote OST with nodsh"

	reset_enospc
	rm -f $DIR/$tdir/$tfile
	exhaust_precreations 0 0x80000215

	$LFS setstripe -i 0 -c 2 $DIR/$tdir/$tfile || error "setstripe failed"

	reset_enospc
}
run_test 27r "stripe file with some full OSTs (shouldn't LBUG) ="

test_27s() { # bug 10725
	test_mkdir $DIR/$tdir
	local stripe_size=$((4096 * 1024 * 1024))	# 2^32
	local stripe_count=0
	[ $OSTCOUNT -eq 1 ] || stripe_count=2
	$LFS setstripe -S $stripe_size -c $stripe_count $DIR/$tdir &&
		error "stripe width >= 2^32 succeeded" || true

}
run_test 27s "lsm_xfersize overflow (should error) (bug 10725)"

test_27t() { # bug 10864
	WDIR=$(pwd)
	WLFS=$(which lfs)
	cd $DIR
	touch $tfile
	$WLFS getstripe $tfile
	cd $WDIR
}
run_test 27t "check that utils parse path correctly"

test_27u() { # bug 4900
	[[ $OSTCOUNT -lt 2 ]] && skip_env "needs >= 2 OSTs"
	remote_mds_nodsh && skip "remote MDS with nodsh"

	local index
	local mdts=$(mdts_nodes)

	#define OBD_FAIL_MDS_OSC_PRECREATE      0x139
	do_nodes $mdts "$LCTL set_param fail_loc=0x139"
	test_mkdir -p $DIR/$tdir
	stack_trap "simple_cleanup_common 1000"
	createmany -o $DIR/$tdir/$tfile 1000
	do_nodes $mdts "$LCTL set_param fail_loc=0"

	TLOG=$TMP/$tfile.getstripe
	$LFS getstripe $DIR/$tdir > $TLOG
	OBJS=$(awk -vobj=0 '($1 == 0) { obj += 1 } END { print obj; }' $TLOG)
	[[ $OBJS -gt 0 ]] &&
		error "$OBJS objects created on OST-0. See $TLOG" ||
		rm -f $TLOG
}
run_test 27u "skip object creation on OSC w/o objects"

test_27v() { # bug 4900
	[[ $OSTCOUNT -lt 2 ]] && skip_env "needs >= 2 OSTs"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	remote_ost_nodsh && skip "remote OST with nodsh"

	exhaust_all_precreations 0x215
	reset_enospc

	$LFS setstripe -c 1 $DIR/$tdir         # 1 stripe / file

        touch $DIR/$tdir/$tfile
        #define OBD_FAIL_TGT_DELAY_PRECREATE     0x705
        # all except ost1
        for (( i=1; i < OSTCOUNT; i++ )); do
                do_facet ost$i lctl set_param fail_loc=0x705
        done
        local START=`date +%s`
        createmany -o $DIR/$tdir/$tfile 32

        local FINISH=`date +%s`
        local TIMEOUT=`lctl get_param -n timeout`
        local PROCESS=$((FINISH - START))
        [ $PROCESS -ge $((TIMEOUT / 2)) ] && \
               error "$FINISH - $START >= $TIMEOUT / 2"
        sleep $((TIMEOUT / 2 - PROCESS))
        reset_enospc
}
run_test 27v "skip object creation on slow OST"

test_27w() { # bug 10997
	test_mkdir $DIR/$tdir
	$LFS setstripe -S 65536 $DIR/$tdir/f0 || error "setstripe failed"
	[ $($LFS getstripe -S $DIR/$tdir/f0) -ne 65536 ] &&
		error "stripe size $size != 65536" || true
	[ $($LFS getstripe -d $DIR/$tdir | grep -c "stripe_count") -eq 0 ] &&
		error "$LFS getstripe -d $DIR/$tdir no 'stripe_count'" || true
}
run_test 27w "check $LFS setstripe -S and getstrip -d options"

test_27wa() {
	[[ $OSTCOUNT -lt 2 ]] &&
		skip_env "skipping multiple stripe count/offset test"

	test_mkdir $DIR/$tdir
	for i in $(seq 1 $OSTCOUNT); do
		offset=$((i - 1))
		$LFS setstripe -c $i -i $offset $DIR/$tdir/f$i ||
			error "setstripe -c $i -i $offset failed"
		count=$($LFS getstripe -c $DIR/$tdir/f$i)
		index=$($LFS getstripe -i $DIR/$tdir/f$i)
		[ $count -ne $i ] && error "stripe count $count != $i" || true
		[ $index -ne $offset ] &&
			error "stripe offset $index != $offset" || true
	done
}
run_test 27wa "check $LFS setstripe -c -i options"

test_27x() {
	remote_ost_nodsh && skip "remote OST with nodsh"
	[[ $OSTCOUNT -lt 2 ]] && skip_env "needs >= 2 OSTs"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	OFFSET=$(($OSTCOUNT - 1))
	OSTIDX=0
	local OST=$(ostname_from_index $OSTIDX)

	test_mkdir $DIR/$tdir
	$LFS setstripe -c 1 $DIR/$tdir	# 1 stripe per file
	do_facet ost$((OSTIDX + 1)) lctl set_param -n obdfilter.$OST.degraded 1
	sleep_maxage
	createmany -o $DIR/$tdir/$tfile $OSTCOUNT
	for i in $(seq 0 $OFFSET); do
		[ $($LFS getstripe $DIR/$tdir/$tfile$i | grep -A 10 obdidx |
			awk '{print $1}' | grep -w "$OSTIDX") ] &&
		error "OST0 was degraded but new created file still use it"
	done
	do_facet ost$((OSTIDX + 1)) lctl set_param -n obdfilter.$OST.degraded 0
}
run_test 27x "create files while OST0 is degraded"

test_27y() {
	[[ $OSTCOUNT -lt 2 ]] && skip_env "needs >= 2 OSTs"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	remote_ost_nodsh && skip "remote OST with nodsh"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	local mdtosc=$(get_mdtosc_proc_path $SINGLEMDS $FSNAME-OST0000)
	local last_id=$(do_facet $SINGLEMDS lctl get_param -n \
		osp.$mdtosc.prealloc_last_id)
	local next_id=$(do_facet $SINGLEMDS lctl get_param -n \
		osp.$mdtosc.prealloc_next_id)
	local fcount=$((last_id - next_id))
	[[ $fcount -eq 0 ]] && skip "not enough space on OST0"
	[[ $fcount -gt $OSTCOUNT ]] && fcount=$OSTCOUNT

	local MDS_OSCS=$(do_facet $SINGLEMDS lctl dl |
			 awk '/[oO][sS][cC].*md[ts]/ { print $4 }')
	local OST_DEACTIVE_IDX=-1
	local OSC
	local OSTIDX
	local OST

	for OSC in $MDS_OSCS; do
		OST=$(osc_to_ost $OSC)
		OSTIDX=$(index_from_ostuuid $OST)
		if [ $OST_DEACTIVE_IDX == -1 ]; then
			OST_DEACTIVE_IDX=$OSTIDX
		fi
		if [ $OSTIDX != $OST_DEACTIVE_IDX ]; then
			echo $OSC "is Deactivated:"
			do_facet $SINGLEMDS lctl --device  %$OSC deactivate
		fi
	done

	OSTIDX=$(index_from_ostuuid $OST)
	test_mkdir $DIR/$tdir
	$LFS setstripe -c 1 $DIR/$tdir      # 1 stripe / file

	for OSC in $MDS_OSCS; do
		OST=$(osc_to_ost $OSC)
		OSTIDX=$(index_from_ostuuid $OST)
		if [ $OSTIDX == $OST_DEACTIVE_IDX ]; then
			echo $OST "is degraded:"
			do_facet ost$((OSTIDX+1)) lctl set_param -n \
						obdfilter.$OST.degraded=1
		fi
	done

	sleep_maxage
	createmany -o $DIR/$tdir/$tfile $fcount

	for OSC in $MDS_OSCS; do
		OST=$(osc_to_ost $OSC)
		OSTIDX=$(index_from_ostuuid $OST)
		if [ $OSTIDX == $OST_DEACTIVE_IDX ]; then
			echo $OST "is recovered from degraded:"
			do_facet ost$((OSTIDX+1)) lctl set_param -n \
						obdfilter.$OST.degraded=0
		else
			do_facet $SINGLEMDS lctl --device %$OSC activate
		fi
	done

	# all osp devices get activated, hence -1 stripe count restored
	local stripe_count=0

	# sleep 2*lod_qos_maxage seconds waiting for lod qos to notice osp
	# devices get activated.
	sleep_maxage
	$LFS setstripe -c -1 $DIR/$tfile
	stripe_count=$($LFS getstripe -c $DIR/$tfile)
	rm -f $DIR/$tfile
	[ $stripe_count -ne $OSTCOUNT ] &&
		error "Of $OSTCOUNT OSTs, only $stripe_count is available"
	return 0
}
run_test 27y "create files while OST0 is degraded and the rest inactive"

test_27z() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_ost_nodsh && skip "remote OST with nodsh"

	test_mkdir $DIR/$tdir
	$LFS setstripe -c 1 -i 0 -S 64k $DIR/$tdir/$tfile-1 ||
		{ error "setstripe -c -1 failed"; return 1; }
	# We need to send a write to every object to get parent FID info set.
	# This _should_ also work for setattr, but does not currently.
	# touch $DIR/$tdir/$tfile-1 ||
	dd if=/dev/zero of=$DIR/$tdir/$tfile-1 bs=1M count=1 ||
		{ error "dd $tfile-1 failed"; return 2; }
	$LFS setstripe -c -1 -i $((OSTCOUNT - 1)) -S 1M $DIR/$tdir/$tfile-2 ||
		{ error "setstripe -c -1 failed"; return 3; }
	dd if=/dev/zero of=$DIR/$tdir/$tfile-2 bs=1M count=$OSTCOUNT ||
		{ error "dd $tfile-2 failed"; return 4; }

	# make sure write RPCs have been sent to OSTs
	sync; sleep 5; sync

	check_seq_oid $DIR/$tdir/$tfile-1 || return 5
	check_seq_oid $DIR/$tdir/$tfile-2 || return 6
}
run_test 27z "check SEQ/OID on the MDT and OST filesystems"

test_27A() { # b=19102
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	save_layout_restore_at_exit $MOUNT
	$LFS setstripe -c 0 -i -1 -S 0 $MOUNT
	wait_update $HOSTNAME "$LFS getstripe -c $MOUNT | sed 's/  *//g'" "1" 20 ||
		error "stripe count $($LFS getstripe -c $MOUNT) != 1"
	local default_size=$($LFS getstripe -S $MOUNT)
	local default_offset=$($LFS getstripe -i $MOUNT)
	local dsize=$(do_facet $SINGLEMDS \
		"$LCTL get_param -n lod.$(facet_svc $SINGLEMDS)*.stripesize")
	[ $default_size -eq $dsize ] ||
		error "stripe size $default_size != $dsize"
	[ $default_offset -eq -1 ] ||
		error "stripe offset $default_offset != -1"
}
run_test 27A "check filesystem-wide default LOV EA values"

test_27B() { # LU-2523
	test_mkdir $DIR/$tdir
	rm -f $DIR/$tdir/f0 $DIR/$tdir/f1
	touch $DIR/$tdir/f0
	# open f1 with O_LOV_DELAY_CREATE
	# rename f0 onto f1
	# call setstripe ioctl on open file descriptor for f1
	# close
	multiop $DIR/$tdir/f1 oO_RDWR:O_CREAT:O_LOV_DELAY_CREATE:nB1c \
		$DIR/$tdir/f0

	rm -f $DIR/$tdir/f1
	# open f1 with O_LOV_DELAY_CREATE
	# unlink f1
	# call setstripe ioctl on open file descriptor for f1
	# close
	multiop $DIR/$tdir/f1 oO_RDWR:O_CREAT:O_LOV_DELAY_CREATE:uB1c

	# Allow multiop to fail in imitation of NFS's busted semantics.
	true
}
run_test 27B "call setstripe on open unlinked file/rename victim"

# 27C family tests full striping and overstriping
test_27Ca() { #LU-2871
	[[ $OSTCOUNT -lt 2 ]] && skip_env "needs >= 2 OSTs"

	declare -a ost_idx
	local index
	local found
	local i
	local j

	test_mkdir $DIR/$tdir
	cd $DIR/$tdir
	for i in $(seq 0 $((OSTCOUNT - 1))); do
		# set stripe across all OSTs starting from OST$i
		$LFS setstripe -i $i -c -1 $tfile$i
		# get striping information
		ost_idx=($($LFS getstripe $tfile$i |
		         tail -n $((OSTCOUNT + 1)) | awk '{print $1}'))
		echo "OST Index: ${ost_idx[*]}"

		# check the layout
		[ ${#ost_idx[@]} -eq $OSTCOUNT ] ||
			error "${#ost_idx[@]} != $OSTCOUNT"

		for index in $(seq 0 $((OSTCOUNT - 1))); do
			found=0
			for j in "${ost_idx[@]}"; do
				if [ $index -eq $j ]; then
					found=1
					break
				fi
			done
			[ $found = 1 ] ||
				error "Can not find $index in ${ost_idx[*]}"
		done
	done
}
run_test 27Ca "check full striping across all OSTs"

test_27Cb() {
	[[ $($LCTL get_param mdc.*.import) =~ connect_flags.*overstriping ]] ||
		skip "server does not support overstriping"
	[[ $OSTCOUNT -ge $(($LOV_MAX_STRIPE_COUNT / 2)) ]] &&
		skip_env "too many osts, skipping"

	test_mkdir -p $DIR/$tdir
	local setcount=$(($OSTCOUNT * 2))
	[ $setcount -lt 160 ] || large_xattr_enabled ||
		skip_env "ea_inode feature disabled"

	$LFS setstripe -C $setcount $DIR/$tdir/$tfile ||
		error "setstripe failed"

	local count=$($LFS getstripe -c $DIR/$tdir/$tfile)
	[ $count -eq $setcount ] ||
		error "stripe count $count, should be $setcount"

	$LFS getstripe $DIR/$tdir/$tfile 2>&1 | grep "overstriped" ||
		error "overstriped should be set in pattern"

	dd if=/dev/zero of=$DIR/$tdir/$tfile bs=1M count=4 conv=notrunc ||
		error "dd failed"
}
run_test 27Cb "more stripes than OSTs with -C"

test_27Cc() {
	[[ $($LCTL get_param mdc.*.import) =~ connect_flags.*overstriping ]] ||
		skip "server does not support overstriping"
	[[ $OSTCOUNT -lt 2 ]] && skip_env "need > 1 OST"

	test_mkdir -p $DIR/$tdir
	local setcount=$(($OSTCOUNT - 1))

	[ $setcount -lt 160 ] || large_xattr_enabled ||
		skip_env "ea_inode feature disabled"

	$LFS setstripe -C $setcount $DIR/$tdir/$tfile ||
		error "setstripe failed"

	local count=$($LFS getstripe -c $DIR/$tdir/$tfile)
	[ $count -eq $setcount ] ||
		error "stripe count $count, should be $setcount"

	$LFS getstripe $DIR/$tdir/$tfile 2>&1 | grep "overstriped" &&
		error "overstriped should not be set in pattern"

	dd if=/dev/zero of=$DIR/$tdir/$tfile bs=1M count=4 conv=notrunc ||
		error "dd failed"
}
run_test 27Cc "fewer stripes than OSTs does not set overstriping"

test_27Cd() {
	[[ $($LCTL get_param mdc.*.import) =~ connect_flags.*overstriping ]] ||
		skip "server does not support overstriping"
	[[ $OSTCOUNT -lt 2 ]] && skip_env "need > 1 OST"
	large_xattr_enabled || skip_env "ea_inode feature disabled"

	force_new_seq_all

	test_mkdir -p $DIR/$tdir
	local setcount=$LOV_MAX_STRIPE_COUNT

	$LFS setstripe -C $setcount $DIR/$tdir/$tfile ||
		error "setstripe failed"

	local count=$($LFS getstripe -c $DIR/$tdir/$tfile)
	[ $count -eq $setcount ] ||
		error "stripe count $count, should be $setcount"

	$LFS getstripe $DIR/$tdir/$tfile 2>&1 | grep "overstriped" ||
		error "overstriped should be set in pattern"

	dd if=/dev/zero of=$DIR/$tdir/$tfile bs=1M count=4 conv=notrunc ||
		error "dd failed"

	rm -f $DIR/$tdir/$tfile || error "Delete $tfile failed"
}
run_test 27Cd "test maximum stripe count"

test_27Ce() {
	[[ $($LCTL get_param mdc.*.import) =~ connect_flags.*overstriping ]] ||
		skip "server does not support overstriping"
	test_mkdir -p $DIR/$tdir

	pool_add $TESTNAME || error "Pool creation failed"
	pool_add_targets $TESTNAME 0 || error "pool_add_targets failed"

	local setcount=8

	$LFS setstripe  -C $setcount -p "$TESTNAME" $DIR/$tdir/$tfile ||
		error "setstripe failed"

	local count=$($LFS getstripe -c $DIR/$tdir/$tfile)
	[ $count -eq $setcount ] ||
		error "stripe count $count, should be $setcount"

	$LFS getstripe $DIR/$tdir/$tfile 2>&1 | grep "overstriped" ||
		error "overstriped should be set in pattern"

	dd if=/dev/zero of=$DIR/$tdir/$tfile bs=1M count=4 conv=notrunc ||
		error "dd failed"

	rm -f $DIR/$tdir/$tfile || error "Delete $tfile failed"
}
run_test 27Ce "test pool with overstriping"

test_27Cf() {
	[[ $($LCTL get_param mdc.*.import) =~ connect_flags.*overstriping ]] ||
		skip "server does not support overstriping"
	[[ $OSTCOUNT -ge $(($LOV_MAX_STRIPE_COUNT / 2)) ]] &&
		skip_env "too many osts, skipping"

	test_mkdir -p $DIR/$tdir

	local setcount=$(($OSTCOUNT * 2))
	[ $setcount -lt 160 ] || large_xattr_enabled ||
		skip_env "ea_inode feature disabled"

	$LFS setstripe  -C $setcount $DIR/$tdir/ ||
		error "setstripe failed"

	echo 1 > $DIR/$tdir/$tfile

	local count=$($LFS getstripe -c $DIR/$tdir/$tfile)
	[ $count -eq $setcount ] ||
		error "stripe count $count, should be $setcount"

	$LFS getstripe $DIR/$tdir/$tfile 2>&1 | grep "overstriped" ||
		error "overstriped should be set in pattern"

	dd if=/dev/zero of=$DIR/$tdir/$tfile bs=1M count=4 conv=notrunc ||
		error "dd failed"

	rm -f $DIR/$tdir/$tfile || error "Delete $tfile failed"
}
run_test 27Cf "test default inheritance with overstriping"

test_27Cg() {
	(( MDS1_VERSION >= $(version_code v2_15_55-80-gd96b98ee6b) )) ||
		skip "need MDS version at least v2_15_55-80-gd96b98ee6b for fix"

	$LFS setstripe -o 0,$OSTCOUNT $DIR/$tfile
	(( $? != 0 )) || error "must be an error for not existent OST#"
}
run_test 27Cg "test setstripe with wrong OST idx"

test_27Ci() {
	[[ $($LCTL get_param mdc.*.import) =~ connect_flags.*overstriping ]] ||
		skip "server does not support overstriping"
	local tf=$DIR/$tfile

	stack_trap "rm -f $DIR/$tfile"

	$LFS setstripe -E1M $tf || error "create $tf failed"
	$LFS setstripe -Eeof --component-add -C 100 $tf ||
		error "add component failed"

	$LFS getstripe -I2 $tf | awk '/lmm_pattern/ { print $2 }' |
		grep "overstriped" || {
		$LFS getstripe $tf
		echo "lose overstriping setting"
	}
	sc=$($LFS getstripe -I2 --stripe-count $tf)
	(( $sc == 100 )) || {
		$LFS getstripe $tf
		echo "lose overstriping setting"
	}

	stack_trap "rm -f $tf"
	dd if=/dev/zero of=$tf bs=1M count=10 || error "write $tf"
	sc=$($LFS getstripe -I2 --stripe-count $tf)
	(( $sc == 100 )) || {
		$LFS getstripe $tf
		echo "lose overstriping setting after instantiation"
	}
}
run_test 27Ci "add an overstriping component"

test_27Cj() {
	[[ $($LCTL get_param mdc.*.import) =~ connect_flags.*overstriping ]] ||
		skip "server does not support overstriping"
	(( $MDS1_VERSION >= $(version_code 2.15.61.76) )) ||
		skip "need MDS >= 2.15.61.76"

	stack_trap "rm -f $DIR/$tfile"

	#check that beyond -32 it fails
	echo "setstripe -C -33 should fail"
	$LFS setstripe -C -33 $DIR/$tfile && error "setstripe should fail"

	# start_full_debug_logging
	# number of stripes created will be 32*ost count
	$LFS setstripe  -C -32 $DIR/$tfile || error "create $tfile failed"
	local count=$($LFS getstripe -c $DIR/$tfile)
	local stripe_cnt=$(($OSTCOUNT * 32))
	(( $count == $stripe_cnt )) ||
		error "$DIR/$tfile stripe count $count != $stripe_cnt"
}
run_test 27Cj "overstriping with -C for max values in multiple of targets"

test_27D() {
	(( $OSTCOUNT >= 2 )) || skip_env "needs >= 2 OSTs"
	remote_mds_nodsh && skip "remote MDS with nodsh"

	local POOL=${POOL:-testpool}
	local first_ost=0
	local last_ost=$(($OSTCOUNT - 1))
	local ost_step=1
	local ost_list=$(seq $first_ost $ost_step $last_ost)
	local ost_range="$first_ost $last_ost $ost_step"
	local flr_ec_ver=v2_17_52-42-gf1b7ae0cc6

	test_mkdir $DIR/$tdir
	pool_add $POOL || error "pool_add failed"
	pool_add_targets $POOL $ost_range || error "pool_add_targets failed"

	(( $MDS1_VERSION >= $(version_code 2.8.55) )) ||
		SKIP27D+=" -s 29"
	(( $MDS1_VERSION >= $(version_code 2.9.55) &&
	   $CLIENT_VERSION >= $(version_code 2.9.55) )) ||
		SKIP27D+=" -s 30,31"
	[[ $($LCTL get_param mdc.*.import) =~ connect_flags.*overstriping ]] &&
	(( $OSTCOUNT < $LOV_MAX_STRIPE_COUNT / 2)) ||
		SKIP27D+=" -s 32,33"
	(( $MDS1_VERSION >= $(version_code $SEL_VER) )) ||
		SKIP27D+=" -s 34"
	(( $MDS1_VERSION >= $(version_code $flr_ec_ver) )) ||
		SKIP27D+=" -s 52,53,54,56,57,58,63,64,65,67"

	local ec_enable=$($LCTL get_param -n llite.*.enable_erasure_coding)
	$LCTL set_param llite.*.enable_erasure_coding=1
	stack_trap "$LCTL set_param -n \
		llite.*.enable_erasure_coding=$ec_enable"
	llapi_layout_test -d$DIR/$tdir -p$POOL -o$OSTCOUNT $SKIP27D ||
		error "llapi_layout_test failed"

	destroy_test_pools || error "destroy test pools failed"
}
run_test 27D "validate llapi_layout API"

# Verify that default_easize is increased from its initial value after
# accessing a widely striped file.
test_27E() {
	[ $OSTCOUNT -lt 2 ] && skip_env "needs >= 2 OSTs"
	[ $CLIENT_VERSION -lt $(version_code 2.5.57) ] &&
		skip "client does not have LU-3338 fix"

	# 72 bytes is the minimum space required to store striping
	# information for a file striped across one OST:
	# (sizeof(struct lov_user_md_v3) +
	#  sizeof(struct lov_user_ost_data_v1))
	local min_easize=72
	$LCTL set_param -n llite.*.default_easize $min_easize ||
		error "lctl set_param failed"
	local easize=$($LCTL get_param -n llite.*.default_easize)

	[ $easize -eq $min_easize ] ||
		error "failed to set default_easize"

	$LFS setstripe -c $OSTCOUNT $DIR/$tfile ||
		error "setstripe failed"
	# In order to ensure stat() call actually talks to MDS we need to
	# do something drastic to this file to shake off all lock, e.g.
	# rename it (kills lookup lock forcing cache cleaning)
	mv $DIR/$tfile $DIR/${tfile}-1
	ls -l $DIR/${tfile}-1
	rm $DIR/${tfile}-1

	easize=$($LCTL get_param -n llite.*.default_easize)

	[ $easize -gt $min_easize ] ||
		error "default_easize not updated"
}
run_test 27E "check that default extended attribute size properly increases"

test_27F() { # LU-5346/LU-7975
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[[ $OSTCOUNT -lt 2 ]] && skip "needs >= 2 OSTs"
	[[ $MDS1_VERSION -lt $(version_code 2.8.51) ]] &&
		skip "Need MDS version at least 2.8.51"
	remote_ost_nodsh && skip "remote OST with nodsh"

	test_mkdir $DIR/$tdir
	rm -f $DIR/$tdir/f0
	$LFS setstripe -c 2 $DIR/$tdir

	# stop all OSTs to reproduce situation for LU-7975 ticket
	for num in $(seq $OSTCOUNT); do
		stop ost$num
	done

	# open/create f0 with O_LOV_DELAY_CREATE
	# truncate f0 to a non-0 size
	# close
	multiop $DIR/$tdir/f0 oO_RDWR:O_CREAT:O_LOV_DELAY_CREATE:T1050000c

	$CHECKSTAT -s 1050000 $DIR/$tdir/f0 || error "checkstat failed"
	# open/write it again to force delayed layout creation
	cat /etc/hosts > $DIR/$tdir/f0 &
	catpid=$!

	# restart OSTs
	for num in $(seq $OSTCOUNT); do
		start ost$num $(ostdevname $num) $OST_MOUNT_OPTS ||
			error "ost$num failed to start"
	done

	wait $catpid || error "cat failed"

	cmp /etc/hosts $DIR/$tdir/f0 || error "cmp failed"
	[[ $($LFS getstripe -c $DIR/$tdir/f0) == 2 ]] ||
		error "wrong stripecount"

}
run_test 27F "Client resend delayed layout creation with non-zero size"

test_27G() { #LU-10629
	(( $MDS1_VERSION < $(version_code 2.11.51) )) &&
		skip "Need MDS version at least 2.11.51"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	local POOL=${POOL:-testpool}
	local ostrange="0 0 1"

	test_mkdir $DIR/$tdir
	touch $DIR/$tdir/$tfile.nopool
	pool_add $POOL || error "pool_add failed"
	pool_add_targets $POOL $ostrange || error "pool_add_targets failed"
	$LFS setstripe -p $POOL $DIR/$tdir

	local pool=$($LFS getstripe -p $DIR/$tdir)

	[ "$pool" = "$POOL" ] || error "Striping failed got '$pool' not '$POOL'"
	touch $DIR/$tdir/$tfile.default
	$LFS setstripe -E 1M --pool $POOL -c 1 -E eof -c 1 $DIR/$tdir/$tfile.pfl
	$LFS find $DIR/$tdir -type f --pool $POOL
	local found=$($LFS find $DIR/$tdir -type f --pool $POOL | wc -l)
	[[ "$found" == "2" ]] ||
		error "found $found != 2 files in '$DIR/$tdir' in '$POOL'"

	$LFS setstripe -d $DIR/$tdir

	pool=$($LFS getstripe -p -d $DIR/$tdir)

	[[ "$pool" != "$POOL" ]] || error "$DIR/$tdir is still '$pool'"
}
run_test 27G "Clear OST pool from stripe"

test_27H() {
	[[ $MDS1_VERSION -le $(version_code 2.11.54) ]] &&
		skip "Need MDS version newer than 2.11.54"
	[[ $OSTCOUNT -lt 3 ]] && skip_env "needs >= 3 OSTs"
	test_mkdir $DIR/$tdir
	$LFS setstripe -o 0 -o 2 $DIR/$tdir || error "setstripe failed"
	touch $DIR/$tdir/$tfile
	$LFS getstripe -c $DIR/$tdir/$tfile
	[ $($LFS getstripe -c $DIR/$tdir/$tfile) -eq 2 ] ||
		error "two-stripe file doesn't have two stripes"

	dd if=/dev/zero of=$DIR/$tdir/$tfile bs=4k count=4 || error "dd failed"
	$LFS getstripe -y $DIR/$tdir/$tfile
	(( $($LFS getstripe -y $DIR/$tdir/$tfile |
	     grep -E -c "l_ost_idx: [02]$") == "2" )) ||
		error "expected l_ost_idx: [02]$ not matched"

	# make sure ost list has been cleared
	local stripesize=$($LFS getstripe -S $DIR/$tdir)
	$LFS setstripe -S $((stripesize * 4)) -i 1 \
		-c $((OSTCOUNT - 1)) $DIR/$tdir || error "setstripe"
	touch $DIR/$tdir/f3
	$LVERIFY $DIR/$tdir $DIR/$tdir/f3 || error "lverify failed"
}
run_test 27H "Set specific OSTs stripe"

test_27I() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[[ $OSTCOUNT -lt 2 ]] && skip_env "needs >= 2 OSTs"
	[[ $MDS1_VERSION -gt $(version_code 2.12.52) ]] ||
		skip "Need MDS version newer than 2.12.52"
	local pool=$TESTNAME
	local ostrange="1 1 1"

	save_layout_restore_at_exit $MOUNT
	$LFS setstripe -c 2 -i 0 $MOUNT
	pool_add $pool || error "pool_add failed"
	pool_add_targets $pool $ostrange ||
		error "pool_add_targets failed"
	test_mkdir $DIR/$tdir
	$LFS setstripe -p $pool $DIR/$tdir
	$MULTIOP $DIR/$tdir/$tfile Oc || error "multiop failed"
	$LFS getstripe $DIR/$tdir/$tfile
}
run_test 27I "check that root dir striping does not break parent dir one"

test_27Ia() {
	(( $MDS1_VERSION >= $(version_code 2.15.61.225) )) ||
		skip "need MDS >= 2.15.61.255 for pool inheritance fix"

	(( $OSTCOUNT >= 2 )) || skip_env "needs >= 2 OSTs"

	save_layout_restore_at_exit $MOUNT
	pool_add $TESTNAME || error "pool_add failed"
	pool_add_targets $TESTNAME 1 || error "pool_add_targets failed"

	$LFS setstripe -p $TESTNAME $MOUNT

	test_mkdir $DIR/$tdir
	$LFS setstripe -i0 $DIR/$tdir
	$MULTIOP $DIR/$tdir/$tfile.1 Oc || error_noexit "multiop failed"
	$LFS getstripe $DIR/$tdir/$tfile.1

	$LFS setstripe -d $DIR/$tdir
	$LFS setstripe -o 0,1 $DIR/$tdir
	$MULTIOP $DIR/$tdir/$tfile.2 Oc || error_noexit "multiop failed"
	$LFS getstripe $DIR/$tdir/$tfile.2

	test_mkdir $DIR/$tdir/d1
	$MULTIOP $DIR/$tdir/d1/$tfile.3 Oc || error_noexit "multiop failed"
	$LFS getstripe $DIR/$tdir/d1/$tfile.3

	$LFS setstripe -d $DIR/$tdir
	$LFS setstripe -E 128G -o 0,1 -E-1 $DIR/$tdir
	test_mkdir $DIR/$tdir/d2
	$MULTIOP $DIR/$tdir/d2/$tfile.4 Oc || error_noexit "multiop failed"
	$LFS getstripe $DIR/$tdir/d2/$tfile.4
}
run_test 27Ia "check that root dir pool is dropped with conflict parent dir settings"

test_27J() {
	(( $MDS1_VERSION >= $(version_code v2_12_53-14-g6a20bdcc60) )) ||
		skip "Need MDS >= 2.12.53.15 for foreign layouts"

	test_mkdir $DIR/$tdir
	local uuid1=$(cat /proc/sys/kernel/random/uuid)
	local uuid2=$(cat /proc/sys/kernel/random/uuid)

	# create foreign file (raw way)
	! $LFS setstripe --flags 0xda08 $DIR/$tdir/$tfile ||
		error "creating $tfile w/ hex flags w/o --foreign should fail"

	! $LFS setstripe --foreign --flags foo \
		--xattr ${uuid1}@${uuid2} $DIR/$tdir/$tfile ||
			error "creating $tfile with '--flags foo' should fail"

	! $LFS setstripe --foreign --flags 0xffffffff \
		--xattr ${uuid1}@${uuid2} $DIR/$tdir/$tfile ||
			error "creating $tfile w/ 0xffffffff flags should fail"

	create_foreign_file -f $DIR/$tdir/$tfile -x "${uuid1}@${uuid2}" \
		-t 1 -F 0xda08 || error "create_foreign_file failed"

	# verify foreign file (raw way)
	parse_foreign_file -f $DIR/$tdir/$tfile |
		grep "lov_foreign_magic: 0x0BD70BD0" ||
		error "$DIR/$tdir/$tfile: invalid LOV EA foreign magic"
	parse_foreign_file -f $DIR/$tdir/$tfile | grep "lov_xattr_size: 89" ||
		error "$DIR/$tdir/$tfile: invalid LOV EA foreign size"
	parse_foreign_file -f $DIR/$tdir/$tfile |
		grep "lov_foreign_size: 73" ||
		error "$DIR/$tdir/$tfile: invalid LOV EA foreign size"
	parse_foreign_file -f $DIR/$tdir/$tfile |
		grep "lov_foreign_type:.*1$" ||
		error "$DIR/$tdir/$tfile: invalid LOV EA foreign type"
	parse_foreign_file -f $DIR/$tdir/$tfile |
		grep "lov_foreign_flags: 0x0000DA08" ||
		error "$DIR/$tdir/$tfile: invalid LOV EA foreign flags"
	local lov=$(parse_foreign_file -f $DIR/$tdir/$tfile |
		grep "lov_foreign_value: 0x" |
		sed -e 's/lov_foreign_value: 0x//')
	local lov2=$(echo -n "${uuid1}@${uuid2}" | od -A n -t x1 -w160)
	[[ $lov = ${lov2// /} ]] ||
		error "$DIR/$tdir/$tfile: invalid LOV EA foreign value"

	# create foreign file (lfs + API)
	$LFS setstripe --foreign=none --flags 0xda08 \
		-x "${uuid1}@${uuid2}" $DIR/$tdir/${tfile}2 ||
		error "$DIR/$tdir/${tfile}2: create failed"

	$LFS getstripe -v $DIR/$tdir/${tfile}2 |
		grep "lfm_magic:.*0x0BD70BD0" ||
		error "$DIR/$tdir/${tfile}2: invalid LOV EA foreign magic"
	# lfm_length is LOV EA size - sizeof(lfm_magic) - sizeof(lfm_length)
	$LFS getstripe -v $DIR/$tdir/${tfile}2 | grep "lfm_length:.*73" ||
		error "$DIR/$tdir/${tfile}2: invalid LOV EA foreign size"
	$LFS getstripe -v $DIR/$tdir/${tfile}2 | grep "lfm_type:.*none" ||
		error "$DIR/$tdir/${tfile}2: invalid LOV EA foreign type"
	$LFS getstripe -v $DIR/$tdir/${tfile}2 |
		grep "lfm_flags:.*0x0000DA08" ||
		error "$DIR/$tdir/${tfile}2: invalid LOV EA foreign flags"
	$LFS getstripe $DIR/$tdir/${tfile}2 |
		grep "lfm_value:.*${uuid1}@${uuid2}" ||
		error "$DIR/$tdir/${tfile}2: invalid LOV EA foreign value"

	# modify striping should fail
	$LFS setstripe -c 2 $DIR/$tdir/$tfile &&
		error "$DIR/$tdir/$tfile: setstripe should fail"
	$LFS setstripe -c 2 $DIR/$tdir/${tfile}2 &&
		error "$DIR/$tdir/${tfile}2: setstripe should fail"

	# skip basic ops on file with foreign LOV tests on >5.12 kernels
	(( $LINUX_VERSION_CODE < $(version_code 5.12.0) )) && {
		# kernel >= 5.12.0 would skip filemap_read() with 0 sized file
		# R/W should fail
		cat $DIR/$tdir/$tfile &&
			error "$DIR/$tdir/$tfile: read should fail"
		cat $DIR/$tdir/${tfile}2 &&
			error "$DIR/$tdir/${tfile}2: read should fail"
		cat /etc/passwd > $DIR/$tdir/$tfile &&
			error "$DIR/$tdir/$tfile: write should fail"
		cat /etc/passwd > $DIR/$tdir/${tfile}2 &&
			error "$DIR/$tdir/${tfile}2: write should fail"
	}

	# chmod should work
	chmod 222 $DIR/$tdir/$tfile ||
		error "$DIR/$tdir/$tfile: chmod failed"
	chmod 222 $DIR/$tdir/${tfile}2 ||
		error "$DIR/$tdir/${tfile}2: chmod failed"

	# chown should work
	chown $RUNAS_ID:$RUNAS_GID $DIR/$tdir/$tfile ||
		error "$DIR/$tdir/$tfile: chown failed"
	chown $RUNAS_ID:$RUNAS_GID $DIR/$tdir/${tfile}2 ||
		error "$DIR/$tdir/${tfile}2: chown failed"

	# rename should work
	mv $DIR/$tdir/$tfile $DIR/$tdir/${tfile}.new ||
		error "$DIR/$tdir/$tfile: rename of foreign file has failed"
	mv $DIR/$tdir/${tfile}2 $DIR/$tdir/${tfile}2.new ||
		error "$DIR/$tdir/${tfile}2: rename of foreign file has failed"

	#remove foreign file
	rm $DIR/$tdir/${tfile}.new ||
		error "$DIR/$tdir/${tfile}.new: remove foreign file has failed"
	rm $DIR/$tdir/${tfile}2.new ||
		error "$DIR/$tdir/${tfile}2.new: remove foreign file has failed"
}
run_test 27J "basic ops on file with foreign LOV"

test_27K() {
	(( $MDS1_VERSION >= $(version_code v2_12_53-15-gfdad38781c) )) ||
		skip "Need MDS >= 2.12.53.15 for foreign LVM directory"

	test_mkdir $DIR/$tdir
	local uuid1=$(cat /proc/sys/kernel/random/uuid)
	local uuid2=$(cat /proc/sys/kernel/random/uuid)
	local foreign_magic="lmv_foreign_magic:.*cd50cd0"

	# create foreign dir (raw way)
	! $LFS setdirstripe --flags 0xda08 $DIR/$tdir/$tdir ||
		error "creating $tdir w/ hex flags w/o --foreign should fail"

	! $LFS setdirstripe --foreign --flags foo \
		--xattr ${uuid1}@${uuid2} $DIR/$tdir/$tdir ||
			error "creating $tdir with '--flags foo' should fail"

	! $LFS setdirstripe --foreign --flags 0xffffffff \
		--xattr ${uuid1}@${uuid2} $DIR/$tdir/$tdir ||
			error "creating $tdir w/ 0xffffffff flags should fail"

	create_foreign_dir -d $DIR/$tdir/$tdir -x "${uuid1}@${uuid2}" -t 1 ||
		error "create_foreign_dir FAILED"

	# verify foreign dir (raw way)
	parse_foreign_dir -d $DIR/$tdir/$tdir | grep "$foreign_magic" ||
		error "$DIR/$tdir/$tfile: invalid LMV EA magic"
	parse_foreign_dir -d $DIR/$tdir/$tdir | grep "lmv_xattr_size:.*89$" ||
		error "$DIR/$tdir/$tdir: invalid LMV EA size"
	parse_foreign_dir -d $DIR/$tdir/$tdir | grep "lmv_foreign_type:.*1$" ||
		error "$DIR/$tdir/$tdir: invalid LMV EA type"
	parse_foreign_dir -d $DIR/$tdir/$tdir |
			grep -E "lmv_foreign_flags: (55813|0xda05)$" ||
		error "$DIR/$tdir/$tdir: invalid LMV EA flags"
	local lmv=$(parse_foreign_dir -d $DIR/$tdir/$tdir |
		grep "lmv_foreign_value: 0x" |
		sed 's/lmv_foreign_value: 0x//')
	local lmv2=$(echo -n "${uuid1}@${uuid2}" | od -A n -t x1 -w160 |
		sed 's/ //g')
	[[ $lmv == $lmv2 ]] || error "$DIR/$tdir/$tdir: invalid LMV EA value"

	# create foreign dir (lfs + API)
	$LFS mkdir --foreign=none --xattr="${uuid1}@${uuid2}" --flags=0xda05 \
		$DIR/$tdir/${tdir}2 ||
		error "$DIR/$tdir/${tdir}2: create failed"

	$LFS getdirstripe -v $DIR/$tdir/${tdir}2

	$LFS getdirstripe -v $DIR/$tdir/${tdir}2 |
		grep "lfm_magic:.*0x0CD50CD0" ||
		error "$DIR/$tdir/${tdir}2: invalid LMV EA magic"
	# lfm_length is LMV EA size - sizeof(lfm_magic) - sizeof(lfm_length)
	# - sizeof(lfm_type) - sizeof(lfm_flags)
	$LFS getdirstripe -v $DIR/$tdir/${tdir}2 | grep "lfm_length:.*73" ||
		error "$DIR/$tdir/${tdir}2: invalid LMV EA size"
	$LFS getdirstripe -v $DIR/$tdir/${tdir}2 | grep "lfm_type:.*none" ||
		error "$DIR/$tdir/${tdir}2: invalid LMV EA type"
	$LFS getdirstripe -v $DIR/$tdir/${tdir}2 |
		grep "lfm_flags:.*0x0000DA05" ||
		error "$DIR/$tdir/${tdir}2: invalid LMV EA flags"
	$LFS getdirstripe $DIR/$tdir/${tdir}2 |
		grep "lfm_value.*${uuid1}@${uuid2}" ||
		error "$DIR/$tdir/${tdir}2: invalid LMV EA value"

	# file create in dir should fail
	touch $DIR/$tdir/$tdir/$tfile &&
		error "$DIR/$tdir: file create should fail"
	touch $DIR/$tdir/${tdir}2/$tfile &&
		error "$DIR/${tdir}2: file create should fail"

	# chmod should work
	chmod 777 $DIR/$tdir/$tdir ||
		error "$DIR/$tdir: chmod failed"
	chmod 777 $DIR/$tdir/${tdir}2 ||
		error "$DIR/${tdir}2: chmod failed"

	# chown should work
	chown $RUNAS_ID:$RUNAS_GID $DIR/$tdir/$tdir ||
		error "$DIR/$tdir: chown failed"
	chown $RUNAS_ID:$RUNAS_GID $DIR/$tdir/${tdir}2 ||
		error "$DIR/${tdir}2: chown failed"

	# rename should work
	mv $DIR/$tdir/$tdir $DIR/$tdir/${tdir}.new ||
		error "$DIR/$tdir/$tdir: rename of foreign dir has failed"
	mv $DIR/$tdir/${tdir}2 $DIR/$tdir/${tdir}2.new ||
		error "$DIR/$tdir/${tdir}2: rename of foreign dir has failed"

	#remove foreign dir
	rmdir $DIR/$tdir/${tdir}.new ||
		error "$DIR/$tdir/${tdir}.new: remove of foreign dir failed"
	rmdir $DIR/$tdir/${tdir}2.new ||
		error "$DIR/$tdir/${tdir}2.new: remove of foreign dir failed"
}
run_test 27K "basic ops on dir with foreign LMV"

test_27Ke() {
	(( $MDS1_VERSION >= $(version_code v2_17_52-77-gaec30763f9) )) ||
		skip "need MDS >= 2.17.52.77 for enable_foreign_dir"


	local param=mdt.$FSNAME-*.enable_foreign_dir
	local param_gid=${param}_gid
	local foreign_old=($(do_facet mds1 $LCTL get_param -n $param))
	local foreign_gid_old=($(do_facet mds1 $LCTL get_param -n $param_gid))
	local foreign_magic="lmv_foreign_magic:.*cd50cd0"
	local uuid1=$(sysctl -n kernel.random.uuid)
	local testdir=$DIR/$tdir
	local mdts=$(mdts_nodes)

	mkdir_on_mdt0 -o 0777 $testdir

	stack_trap "do_nodes $mdts \
		$LCTL set_param $param=$foreign_old $param_gid=$foreign_gid_old"
	start_full_debug_logging
	stack_trap stop_full_debug_logging

	# test with enable_foreign_dir=0: it should fail for all users
	do_nodes $mdts "$LCTL set_param $param=0" || error "setting $param=0"

	create_foreign_dir -d $testdir/$tdir-0 -x $uuid1 -t 1 &&
		error "$tdir-0 foreign_dir worked as root with $param=0"
	[[ ! -e $testdir/$tdir-0 ]] || error "$tdir-0 was created for root"
	$RUNAS create_foreign_dir -d $testdir/$tdir-0u -x $uuid1 -t 1 &&
		error "$tdir-0u foreign_dir worked as user with $param=0"
	[[ ! -e $testdir/$tdir-0u ]] || error "$tdir-0u was created for user"

	# test with enable_foreign_dir=1: _gid=0, OK for root, not others
	do_nodes $mdts "$LCTL set_param $param=1 $param_gid=0" ||
		error "setting $param=1, $param_gid=0"

	create_foreign_dir -d $testdir/$tdir-gid0 -x $uuid1 -t 1 ||
		error "$tdir-gid0 foreign_dir failed for root with _gid=0"
	parse_foreign_dir -d $testdir/$tdir-gid0 | grep "$foreign_magic" ||
		error "$tdir-gid0: invalid LMV EA magic"
	$RUNAS create_foreign_dir -d $testdir/$tdir-gid0u -x $uuid1 -t 1 &&
		error "$tdir-gid0u foreign_dir worked for user GID=$RUNAS_GID"
	[[ ! -e $testdir/$tdir-gid0u ]] ||
		error "$tdir-gid0u created for non-root user"

	# test with enable_foreign_dir=1: _gid=$RUNAS_GID, OK for root,RUNAS_GID
	do_nodes $mdts "$LCTL set_param $param_gid=$RUNAS_GID" ||
		error "setting $param_gid=$RUNAS_GID"

	create_foreign_dir -d $testdir/$tdir-gidRG -x $uuid1 -t 1 ||
		error "$tdir-gidRG foreign_dir failed for root GID=$RUNAS_GID"
	parse_foreign_dir -d $testdir/$tdir-gidRG | grep "$foreign_magic" ||
		error "$tdir-gidRG: invalid LMV EA magic"
	$RUNAS create_foreign_dir -d $testdir/$tdir-gidRGu -x $uuid1 -t 1 ||
		error "$tdir-gidRGu foreign_dir failed for user GID=$RUNAS_GID"
	parse_foreign_dir -d $testdir/$tdir-gidRGu | grep "$foreign_magic" ||
		error "$tdir-gidRGu: invalid LMV EA magic"

	# test with wrong primary GID (no secondary groups) should fail
	local runas="$RUNAS -u $TSTUSR2 -g $TSTUSR2"
	$runas create_foreign_dir -d $testdir/$tdir-gidRGn -x $uuid1 -t 1 &&
		error "$tdir-gidRGn foreign_dir worked with GID!=$RUNAS_GID"
	[[ ! -e $testdir/$tdir-gidRGn ]] ||
		error "$tdir-gidRGn created for non-root user GID!=$RUNAS_GID"

	# test with wrong primary, but correct secondary GID should work
	local tst_gids=$(do_facet mds1 id -G $TSTUSR | tr ' ' ',')
	local new_gids="$tst_gids,$RUNAS_ID"
	local runas="$RUNAS -u $TSTUSR -g $TSTUSR -G$new_gids"

	stack_trap "do_nodes $mdts usermod -G $tst_gids $TSTUSR"
	do_nodes $mdts usermod -a -G $RUNAS_ID $TSTUSR ||
		error "can't add $TSTUSR to group $RUNAS_ID"

	echo "using $TSTUSR with secondary groups $new_gids"
	do_nodes $mdts "grep ':$RUNAS_ID:' /etc/group"
	do_nodes $mdts "id $TSTUSR"
	do_nodes $mdts "$L_GETIDENTITY -d $(id -u $TSTUSR)"

	$runas create_foreign_dir -d $testdir/$tdir-gidRGs -x $uuid1 -t 1 ||
		error "$tdir-gidRGs foreign_dir failed with secondary GID"
	parse_foreign_dir -d $testdir/$tdir-gidRGs | grep "$foreign_magic" ||
		error "$tdir-gidRGs: invalid LMV EA magic"

	# test with enable_foreign_dir=1: _gid=-1, OK for everyone
	do_nodes $mdts "$LCTL set_param $param_gid=-1" ||
		error "setting $param_gid=-1"

	create_foreign_dir -d $testdir/$tdir-gid-1 -x $uuid1 -t 1 ||
		error "$tdir-gid-1 foreign_dir failed as root with _gid=-1"
	parse_foreign_dir -d $testdir/$tdir-gid-1 | grep "$foreign_magic" ||
		error "$tdir-gid-1: invalid LMV EA magic"
	$RUNAS create_foreign_dir -d $testdir/$tdir-gid-1u -x $uuid1 -t 1 ||
		error "$tdir-gid-1u foreign_dir failed as user with _gid=-1"
	parse_foreign_dir -d $testdir/$tdir-gid-1u | grep "$foreign_magic"||
		error "$tdir-gid-1u: invalid LMV EA magic"
}
run_test 27Ke "test enable_foreign_dir and enable_foreign_dir_gid"

test_27L() {
	remote_mds_nodsh && skip "remote MDS with nodsh"

	local POOL=${POOL:-$TESTNAME}

	pool_add $POOL || error "pool_add failed"

	lfs pool_list $MOUNT | grep -Fx "${FSNAME}.${POOL}" ||
		 error "pool_list does not contain ${FSNAME}.${POOL}:" \
		       "$(lfs pool_list $MOUNT | grep -F "${POOL}")"
}
run_test 27L "lfs pool_list gives correct pool name"

test_27M() {
	(( $MDS1_VERSION >= $(version_code 2.12.57) )) ||
		skip "Need MDS version >= than 2.12.57"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	(( $OSTCOUNT > 1 )) || skip "need > 1 OST"

	# Set default striping on directory
	local setcount=4
	local stripe_opt
	local mdts=$(mdts_nodes)

	# if we run against a 2.12 server which lacks overstring support
	# then the connect_flag will not report overstriping, even if client
	# is 2.14+
	if [[ $($LCTL get_param mdc.*.connect_flags) =~ overstriping ]]; then
		stripe_opt="-C $setcount"
	elif (( $OSTCOUNT >= $setcount )); then
		stripe_opt="-c $setcount"
	else
		skip "server does not support overstriping"
	fi

	test_mkdir $DIR/$tdir

	# Validate existing append_* params and ensure restore
	local pool=$(do_facet mds1 $LCTL get_param -n mdd.$FSNAME-MDT0000.append_pool)
	[[ "$pool" == "" ]] || error "expected append_pool == '', got '$pool'"
	stack_trap "do_nodes $mdts $LCTL set_param mdd.*.append_pool=none"

	# Validate append_pool name length
	(( $MDS1_VERSION >= $(version_code 2.15.61) )) &&
		do_nodes $mdts $LCTL \
			set_param mdd.*.append_pool="LOV_MAXPOOLNAME*" &&
			error "Wrong pool name length should report error"

	local orig_count=$(do_facet mds1 $LCTL get_param -n mdd.$FSNAME-MDT0000.append_stripe_count)
	stack_trap "do_nodes $mdts $LCTL set_param mdd.*.append_stripe_count=$orig_count"
	do_nodes $mdts $LCTL set_param mdd.*.append_stripe_count=1

	$LFS setstripe $stripe_opt $DIR/$tdir

	echo 1 > $DIR/$tdir/${tfile}.1
	local count=$($LFS getstripe -c $DIR/$tdir/${tfile}.1)
	(( $count == $setcount )) ||
		error "(1) stripe count $count, should be $setcount"

	local appendcount=1
	echo 1 >> $DIR/$tdir/${tfile}.2_append
	count=$($LFS getstripe -c $DIR/$tdir/${tfile}.2_append)
	(( $count == $appendcount )) ||
		error "(2)stripe count $count, should be $appendcount for append"

	# Disable O_APPEND striping, verify it works
	do_nodes $mdts $LCTL set_param mdd.*.append_stripe_count=0

	# Should now get the default striping, which is 4
	setcount=4
	echo 1 >> $DIR/$tdir/${tfile}.3_append
	count=$($LFS getstripe -c $DIR/$tdir/${tfile}.3_append)
	(( $count == $setcount )) ||
		error "(3) stripe count $count, should be $setcount"

	# Try changing the stripe count for append files
	do_nodes $mdts $LCTL set_param mdd.*.append_stripe_count=2

	# Append striping is now 2 (directory default is still 4)
	appendcount=2
	echo 1 >> $DIR/$tdir/${tfile}.4_append
	count=$($LFS getstripe -c $DIR/$tdir/${tfile}.4_append)
	(( $count == $appendcount )) ||
		error "(4) stripe count $count, should be $appendcount for append"

	# Test append stripe count of -1
	# Exercise LU-16872 patch with specific striping, only if MDS has fix
	(( $MDS1_VERSION > $(version_code 2.15.56.46) )) &&
		$LFS setstripe -o 0,$((OSTCOUNT - 1)) $DIR/$tdir &&
		touch $DIR/$tdir/$tfile.specific.{1..128}
	stack_trap "rm -f $DIR/$tdir/$tfile.*"

	do_nodes $mdts $LCTL set_param mdd.*.append_stripe_count=-1
	appendcount=$OSTCOUNT
	echo 1 >> $DIR/$tdir/${tfile}.5
	count=$($LFS getstripe -c $DIR/$tdir/${tfile}.5)
	(( $count == $appendcount )) ||
		error "(5) stripe count $count, should be $appendcount for append"

	# Set append striping back to default of 1
	do_nodes $mdts $LCTL set_param mdd.*.append_stripe_count=1

	# Try a new default striping, PFL + DOM
	$LFS setstripe -L mdt -E 1M -E -1 -c 2 $DIR/$tdir

	# Create normal DOM file, DOM returns stripe count == 0
	setcount=0
	touch $DIR/$tdir/${tfile}.6
	count=$($LFS getstripe -c $DIR/$tdir/${tfile}.6)
	(( $count == $setcount )) ||
		error "(6) stripe count $count, should be $setcount"

	# Show
	appendcount=1
	echo 1 >> $DIR/$tdir/${tfile}.7_append
	count=$($LFS getstripe -c $DIR/$tdir/${tfile}.7_append)
	(( $count == $appendcount )) ||
		error "(7) stripe count $count, should be $appendcount for append"

	# Clean up DOM layout
	$LFS setstripe -d $DIR/$tdir

	# rest of tests don't work with FILESET
	[ -n "$FILESET" ] && exit

	save_layout_restore_at_exit $MOUNT
	# Now test that append striping works when layout is from root
	$LFS setstripe -c 2 $MOUNT
	# Make a special directory for this
	mkdir $DIR/${tdir}/${tdir}.2

	# Verify for normal file
	setcount=2
	echo 1 > $DIR/${tdir}/${tdir}.2/${tfile}.8
	count=$($LFS getstripe -c $DIR/$tdir/${tdir}.2/${tfile}.8)
	(( $count == $setcount )) ||
		error "(8) stripe count $count, should be $setcount"

	appendcount=1
	echo 1 >> $DIR/${tdir}/${tdir}.2/${tfile}.9_append
	count=$($LFS getstripe -c $DIR/${tdir}/${tdir}.2/${tfile}.9_append)
	(( $count == $appendcount )) ||
		error "(9) stripe count $count, should be $appendcount for append"

	# Now test O_APPEND striping with pools
	pool_add $TESTNAME || error "pool creation failed"
	pool_add_targets $TESTNAME 0 1 || error "Pool add targets failed"
	do_nodes $mdts $LCTL set_param mdd.*.append_pool="$TESTNAME"

	echo 1 >> $DIR/$tdir/${tfile}.10_append

	pool=$($LFS getstripe -p $DIR/$tdir/${tfile}.10_append)
	[[ "$pool" == "$TESTNAME" ]] || error "(10) incorrect pool: $pool"

	# Check that count is still correct
	appendcount=1
	echo 1 >> $DIR/$tdir/${tfile}.11_append
	count=$($LFS getstripe -c $DIR/$tdir/${tfile}.11_append)
	(( $count == $appendcount )) ||
		error "(11) stripe count $count, should be $appendcount for append"

	# Disable O_APPEND stripe count, verify pool works separately
	do_nodes $mdts $LCTL set_param mdd.*.append_stripe_count=0

	echo 1 >> $DIR/$tdir/${tfile}.12_append

	pool=$($LFS getstripe -p $DIR/$tdir/${tfile}.12_append)
	[[ "$pool" == "$TESTNAME" ]] || error "(12) incorrect pool: $pool"

	# Remove pool setting, verify it's not applied
	do_nodes $mdts $LCTL set_param mdd.*.append_pool='none'

	echo 1 >> $DIR/$tdir/${tfile}.13_append

	pool=$($LFS getstripe -p $DIR/$tdir/${tfile}.13_append)
	[[ -z "$pool" ]] || error "(13) pool found: $pool"
}
run_test 27M "test O_APPEND striping"

test_27N() {
	combined_mgs_mds && skip "needs separate MGS/MDT"

	pool_add $TESTNAME || error "pool_add failed"
	do_facet mgs "$LCTL pool_list $FSNAME" |
		grep -Fx "${FSNAME}.${TESTNAME}" ||
		error "lctl pool_list on MGS failed"
}
run_test 27N "lctl pool_list on separate MGS gives correct pool name"

clean_foreign_symlink() {
	trap 0
	lctl set_param llite/$FSNAME-*/foreign_symlink_enable=0
	for i in $DIR/$tdir/* ; do
		$LFS unlink_foreign $i || true
	done
}

test_27O() {
	[[ $(lustre_version_code $SINGLEMDS) -le $(version_code 2.12.51) ]] &&
		skip "Need MDS version newer than 2.12.51"

	test_mkdir $DIR/$tdir
	local uuid1=$(cat /proc/sys/kernel/random/uuid)
	local uuid2=$(cat /proc/sys/kernel/random/uuid)

	trap clean_foreign_symlink EXIT

	# enable foreign_symlink behaviour
	$LCTL set_param llite/$FSNAME-*/foreign_symlink_enable=1

	# foreign symlink LOV format is a partial path by default

	# create foreign file (lfs + API)
	$LFS setstripe --foreign=symlink --flags 0xda05 \
		-x "${uuid1}/${uuid2}" --mode 0600 $DIR/$tdir/${tfile} ||
		error "$DIR/$tdir/${tfile}: create failed"

	$LFS getstripe -v $DIR/$tdir/${tfile} |
		grep "lfm_magic:.*0x0BD70BD0" ||
		error "$DIR/$tdir/${tfile}: invalid LOV EA foreign magic"
	$LFS getstripe -v $DIR/$tdir/${tfile} | grep "lfm_type:.*symlink" ||
		error "$DIR/$tdir/${tfile}: invalid LOV EA foreign type"
	$LFS getstripe -v $DIR/$tdir/${tfile} |
		grep "lfm_flags:.*0x0000DA05" ||
		error "$DIR/$tdir/${tfile}: invalid LOV EA foreign flags"
	$LFS getstripe $DIR/$tdir/${tfile} |
		grep "lfm_value:.*${uuid1}/${uuid2}" ||
		error "$DIR/$tdir/${tfile}: invalid LOV EA foreign value"

	# modify striping should fail
	$LFS setstripe -c 2 $DIR/$tdir/$tfile &&
		error "$DIR/$tdir/$tfile: setstripe should fail"

	# R/W should fail ("/{foreign_symlink_prefix}/${uuid1}/" missing)
	cat $DIR/$tdir/$tfile && error "$DIR/$tdir/$tfile: read should fail"
	cat /etc/passwd > $DIR/$tdir/$tfile &&
		error "$DIR/$tdir/$tfile: write should fail"

	# rename should succeed
	mv $DIR/$tdir/$tfile $DIR/$tdir/${tfile}.new ||
		error "$DIR/$tdir/$tfile: rename has failed"

	#remove foreign_symlink file should fail
	rm $DIR/$tdir/${tfile}.new &&
		error "$DIR/$tdir/${tfile}.new: remove of foreign_symlink file should fail"

	#test fake symlink
	mkdir /tmp/${uuid1} ||
		error "/tmp/${uuid1}: mkdir has failed"
	echo FOOFOO > /tmp/${uuid1}/${uuid2} ||
		error "/tmp/${uuid1}/${uuid2}: echo has failed"
	$LCTL set_param llite/$FSNAME-*/foreign_symlink_prefix=/tmp/
	$CHECKSTAT -t link -l /tmp/${uuid1}/${uuid2} $DIR/$tdir/${tfile}.new ||
		error "$DIR/$tdir/${tfile}.new: not seen as a symlink"
	#read should succeed now
	cat $DIR/$tdir/${tfile}.new | grep FOOFOO ||
		error "$DIR/$tdir/${tfile}.new: symlink resolution has failed"
	#write should succeed now
	cat /etc/passwd > $DIR/$tdir/${tfile}.new ||
		error "$DIR/$tdir/${tfile}.new: write should succeed"
	diff /etc/passwd $DIR/$tdir/${tfile}.new ||
		error "$DIR/$tdir/${tfile}.new: diff has failed"
	diff /etc/passwd /tmp/${uuid1}/${uuid2} ||
		error "/tmp/${uuid1}/${uuid2}: diff has failed"

	#check that getstripe still works
	$LFS getstripe $DIR/$tdir/${tfile}.new ||
		error "$DIR/$tdir/${tfile}.new: getstripe should still work with foreign_symlink enabled"

	# chmod should still succeed
	chmod 644 $DIR/$tdir/${tfile}.new ||
		error "$DIR/$tdir/${tfile}.new: chmod has failed"

	# chown should still succeed
	chown $RUNAS_ID:$RUNAS_GID $DIR/$tdir/${tfile}.new ||
		error "$DIR/$tdir/${tfile}.new: chown has failed"

	# rename should still succeed
	mv $DIR/$tdir/${tfile}.new $DIR/$tdir/${tfile} ||
		error "$DIR/$tdir/${tfile}.new: rename has failed"

	#remove foreign_symlink file should still fail
	rm $DIR/$tdir/${tfile} &&
		error "$DIR/$tdir/${tfile}: remove of foreign_symlink file should fail"

	#use special ioctl() to unlink foreign_symlink file
	$LFS unlink_foreign $DIR/$tdir/${tfile} ||
		error "$DIR/$tdir/$tfile: unlink/ioctl failed"

}
run_test 27O "basic ops on foreign file of symlink type"

test_27P() {
	[[ $(lustre_version_code $SINGLEMDS) -le $(version_code 2.12.49) ]] &&
		skip "Need MDS version newer than 2.12.49"

	test_mkdir $DIR/$tdir
	local uuid1=$(cat /proc/sys/kernel/random/uuid)
	local uuid2=$(cat /proc/sys/kernel/random/uuid)

	trap clean_foreign_symlink EXIT

	# enable foreign_symlink behaviour
	$LCTL set_param llite/$FSNAME-*/foreign_symlink_enable=1

	# foreign symlink LMV format is a partial path by default

	# create foreign dir (lfs + API)
	$LFS mkdir --foreign=symlink --xattr="${uuid1}/${uuid2}" \
		--flags=0xda05 --mode 0750 $DIR/$tdir/${tdir} ||
		error "$DIR/$tdir/${tdir}: create failed"

	$LFS getdirstripe -v $DIR/$tdir/${tdir}

	$LFS getdirstripe -v $DIR/$tdir/${tdir} |
		grep "lfm_magic:.*0x0CD50CD0" ||
		error "$DIR/$tdir/${tdir}: invalid LMV EA magic"
	$LFS getdirstripe -v $DIR/$tdir/${tdir} | grep "lfm_type:.*symlink" ||
		error "$DIR/$tdir/${tdir}: invalid LMV EA type"
	$LFS getdirstripe -v $DIR/$tdir/${tdir} |
		grep "lfm_flags:.*0x0000DA05" ||
		error "$DIR/$tdir/${tdir}: invalid LMV EA flags"
	$LFS getdirstripe $DIR/$tdir/${tdir} |
		grep "lfm_value.*${uuid1}/${uuid2}" ||
		error "$DIR/$tdir/${tdir}: invalid LMV EA value"

	# file create in dir should fail
	# ("/{foreign_symlink_prefix}/${uuid1}/${uuid2}/" missing)
	touch $DIR/$tdir/$tdir/$tfile && error "$DIR/$tdir: file create should fail"

	# rename should succeed
	mv $DIR/$tdir/$tdir $DIR/$tdir/${tdir}.new ||
		error "$DIR/$tdir/$tdir: rename of foreign_symlink dir has failed"

	#remove foreign_symlink dir should fail
	rmdir $DIR/$tdir/${tdir}.new &&
		error "$DIR/$tdir/${tdir}.new: remove of foreign_symlink dir should fail"

	#test fake symlink
	mkdir -p /tmp/${uuid1}/${uuid2} ||
		error "/tmp/${uuid1}/${uuid2}: mkdir has failed"
	echo FOOFOO > /tmp/${uuid1}/${uuid2}/foo ||
		error "/tmp/${uuid1}/${uuid2}/foo: echo has failed"
	$LCTL set_param llite/$FSNAME-*/foreign_symlink_prefix=/tmp/
	$CHECKSTAT -t link -l /tmp/${uuid1}/${uuid2} $DIR/$tdir/${tdir}.new ||
		error "$DIR/$tdir/${tdir}.new: not seen as a symlink"
	cat $DIR/$tdir/${tdir}.new/foo | grep FOOFOO ||
		error "$DIR/$tdir/${tdir}.new: symlink resolution has failed"

	#check that getstripe fails now that foreign_symlink enabled
	$LFS getdirstripe $DIR/$tdir/${tdir}.new ||
		error "$DIR/$tdir/${tdir}.new: getdirstripe should still work with foreign_symlink enabled"

	# file create in dir should work now
	cp /etc/passwd $DIR/$tdir/${tdir}.new/$tfile ||
		error "$DIR/$tdir/${tdir}.new/$tfile: file create should fail"
	diff /etc/passwd $DIR/$tdir/${tdir}.new/$tfile ||
		error "$DIR/$tdir/${tdir}.new/$tfile: diff has failed"
	diff /etc/passwd /tmp/${uuid1}/${uuid2}/$tfile ||
		error "/tmp/${uuid1}/${uuid2}/$tfile: diff has failed"

	# chmod should still succeed
	chmod 755 $DIR/$tdir/${tdir}.new ||
		error "$DIR/$tdir/${tdir}.new: chmod has failed"

	# chown should still succeed
	chown $RUNAS_ID:$RUNAS_GID $DIR/$tdir/${tdir}.new ||
		error "$DIR/$tdir/${tdir}.new: chown has failed"

	# rename should still succeed
	mv $DIR/$tdir/${tdir}.new $DIR/$tdir/${tdir} ||
		error "$DIR/$tdir/${tdir}.new: rename of foreign_symlink dir has failed"

	#remove foreign_symlink dir should still fail
	rmdir $DIR/$tdir/${tdir} &&
		error "$DIR/$tdir/${tdir}: remove of foreign_symlink dir should fail"

	#use special ioctl() to unlink foreign_symlink file
	$LFS unlink_foreign $DIR/$tdir/${tdir} ||
		error "$DIR/$tdir/$tdir: unlink/ioctl failed"

	#created file should still exist
	[[ -f /tmp/${uuid1}/${uuid2}/$tfile ]] ||
		error "/tmp/${uuid1}/${uuid2}/$tfile has been removed"
	diff /etc/passwd /tmp/${uuid1}/${uuid2}/$tfile ||
		error "/tmp/${uuid1}/${uuid2}/$tfile: diff has failed"
}
run_test 27P "basic ops on foreign dir of foreign_symlink type"

test_27Q() {
	rm -f $TMP/$tfile $TMP/$tfile.loop $TMP/$tfile.none $TMP/$tfile.broken
	stack_trap "rm -f $TMP/$tfile*"

	test_mkdir $DIR/$tdir-1
	test_mkdir $DIR/$tdir-2

	echo 'It is what it is' > $DIR/$tdir-1/$tfile
	lov_getstripe_old $DIR/$tdir-1/$tfile || error "$DIR/$tdir-1/$tfile: rc = $?"

	ln -s $DIR/$tdir-1/$tfile $DIR/$tdir-2/$tfile
	lov_getstripe_old $DIR/$tdir-2/$tfile || error "$DIR/$tdir-2/$tfile: rc = $?"

	ln -s $DIR/$tdir-1/$tfile $TMP/$tfile
	lov_getstripe_old $TMP/$tfile || error "$TMP/$tfile: rc = $?"

	# Create some bad symlinks and ensure that we don't loop
	# forever or something. These should return ELOOP (40) and
	# ENOENT (2) but I don't want to test for that because there's
	# always some weirdo architecture that needs to ruin
	# everything by defining these error numbers differently.

	ln -s $TMP/$tfile.loop $TMP/$tfile.loop
	lov_getstripe_old $TMP/$tfile.loop && error "$TMP/$tfile.loop: rc = $?"

	ln -s $TMP/$tfile.none $TMP/$tfile.broken
	lov_getstripe_old $TMP/$tfile.broken && error "$TMP/$tfile.broken: rc = $?"

	return 0
}
run_test 27Q "llapi_file_get_stripe() works on symlinks"

test_27R() {
	(( $MDS1_VERSION >= $(version_code 2.14.55) )) ||
		skip "need MDS 2.14.55 or later"
	(( $OSTCOUNT >= 2 )) || skip_env "needs at least 2 OSTs"

	local testdir="$DIR/$tdir"
	test_mkdir -p $testdir
	stack_trap "rm -rf $testdir"
	$LFS setstripe -c -1 $testdir || error "setstripe failed"

	local f1="$testdir/f1"
	touch $f1 || error "failed to touch $f1"
	local count=$($LFS getstripe -c $f1)
	(( $count == $OSTCOUNT )) || error "wrong stripe count"

	do_facet $SINGLEMDS $LCTL set_param lod.*.max_stripecount=-1
	(( $? == 34 )) || error "setting max_stripecount to -1 should fail and return ERANGE"

	local maxcount=$(($OSTCOUNT - 1))
	local mdts=$(mdts_nodes)

	do_nodes $mdts "$LCTL set_param lod.*.max_stripecount=$maxcount"
	stack_trap "do_nodes $mdts $LCTL set_param lod.*.max_stripecount=0"

	local f2="$testdir/f2"
	touch $f2 || error "failed to touch $f2"
	local count=$($LFS getstripe -c $f2)
	(( $count == $maxcount )) || error "wrong stripe count"
}
run_test 27R "test max_stripecount limitation when stripe count is set to -1"

test_27T() {
	(( $OST1_VERSION >= $(version_code 2.15.65.18) )) ||
		skip "need ost1 >= v2_15_65-18-g8a865c65c691 for ENOSPC fix"
	[ $(facet_host client) == $(facet_host ost1) ] &&
		skip "need ost1 and client on different nodes"

	# CFS_FAIL_ONCE is needed to get cfs_fail_count reset
	#define OBD_FAIL_OSC_NO_GRANT            0x411
	#define CFS_FAIL_SKIP                    0x20000000
	#define CFS_FAIL_ONCE                    0x80000000
	$LCTL set_param fail_loc=0xa0000411 fail_val=1
	#define OBD_FAIL_OST_ENOSPC_VALID        0x255
	do_facet ost1 "$LCTL set_param fail_loc=0x80000255"
	$LFS setstripe -i 0 -c 1 $DIR/$tfile
	# DIO does not support partial writes to a single stripe - a write to
	# each stripe will fail or succeed entirely.  So we disable hybrid IO
	# so we can see the partial write behavior of buffered IO
	local hybrid=$($LCTL get_param -n llite.*.hybrid_io)
	$LCTL set_param llite.*.hybrid_io=0
	stack_trap "$LCTL set_param -n llite.*.hybrid_io=$hybrid" EXIT

	local pagesz=$(getconf PAGESIZE)
	local pagenr=$($LCTL get_param -n osc.*-OST0000-*.max_pages_per_rpc)

	$MULTIOP $DIR/$tfile oO_WRONLY:P$(((pagenr + 10) * pagesz))c ||
		error "multiop failed"
	(( $(stat -c '%s' $DIR/$tfile) == pagenr * pagesz )) ||
		error "wrong size"

	# this is to reset cfs_fail_count and to clear ar_force_sync flags
	$MULTIOP $DIR/$tfile oO_WRONLY:w${pagesz}c
}
run_test 27T "no eio on close on partial write due to enosp"

test_27U() {
	local dir=$DIR/$tdir
	local file=$dir/$tfile
	local append_pool=${TESTNAME}-append
	local normal_pool=${TESTNAME}-normal
	local pool
	local stripe_count
	local stripe_count2
	local mdts=$(mdts_nodes)

	(( $MDS1_VERSION >= $(version_code 2.15.51) )) ||
		skip "Need MDS version at least 2.15.51 for append pool feature"

	# Validate existing append_* params and ensure restore
	pool=$(do_facet mds1 $LCTL get_param -n mdd.$FSNAME-MDT0000.append_pool)
	[[ "$pool" == "" ]] || error "expected append_pool == '', got '$pool'"
	stack_trap "do_nodes $mdts $LCTL set_param mdd.*.append_pool=none"

	stripe_count=$(do_facet mds1 $LCTL get_param -n mdd.$FSNAME-MDT0000.append_stripe_count)
	stack_trap "do_nodes $mdts $LCTL set_param mdd.*.append_stripe_count=$stripe_count"
	do_nodes $mdts $LCTL set_param mdd.*.append_stripe_count=1

	pool_add $append_pool || error "pool creation failed"
	pool_add_targets $append_pool 0 1 || error "Pool add targets failed"

	pool_add $normal_pool || error "pool creation failed"
	pool_add_targets $normal_pool 0 1 || error "Pool add targets failed"

	test_mkdir $dir
	$LFS setstripe -E 1M -c 1 -p $normal_pool -E 2M -c 2 -p $normal_pool -E eof -c -1 $dir

	echo XXX >> $file.1
	$LFS getstripe $file.1

	pool=$($LFS getstripe -p $file.1)
	[[ "$pool" == "$normal_pool" ]] || error "got pool '$pool', expected '$normal_pool'"

	stripe_count2=$($LFS getstripe -c $file.1)
	((stripe_count2 == 1)) ||
		error "got stripe_count '$stripe_count2', expected 1"

	do_nodes $mdts $LCTL set_param mdd.*.append_pool=$append_pool

	echo XXX >> $file.2
	$LFS getstripe $file.2

	pool=$($LFS getstripe -p $file.2)
	[[ "$pool" == "$append_pool" ]] || error "got pool '$pool', expected '$append_pool'"

	do_nodes $mdts $LCTL set_param mdd.*.append_stripe_count=2

	echo XXX >> $file.3
	$LFS getstripe $file.3

	stripe_count2=$($LFS getstripe -c $file.3)
	((stripe_count2 == 2)) || error "got stripe_count '$stripe_count2', expected 2"
}
run_test 27U "append pool and stripe count work with composite default layout"

test_27V() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	(( $OSTCOUNT >= 4 )) || skip_env "needs >= 4 OSTs"

	local dir=$DIR/$tdir
	local osp_param=osp.$FSNAME-OST0000-osc-MDT0000.max_create_count
	local lod_param=lod.$FSNAME-MDT0000-mdtlov.qos_threshold_rr
	local saved_max=$(do_facet mds1 $LCTL get_param -n $osp_param)
	local saved_qos=$(do_facet mds1 $LCTL get_param -n $lod_param)
	local pid

	stack_trap "do_facet mds1 $LCTL set_param $osp_param=$saved_max"

	do_facet mds1 $LCTL set_param $lod_param=0
	stack_trap "do_facet mds1 $LCTL set_param $lod_param=$saved_qos"

	$LFS setdirstripe --mdt-count=1 --mdt-index=0 $dir
	stack_trap "rm -rf $dir"

	# exercise race in LU-16981 with deactivating OST while creating a file
	(
		while true; do
			do_facet mds1 $LCTL set_param $osp_param=0 > /dev/null
			sleep 0.1
			do_facet mds1 \
				$LCTL set_param $osp_param=$saved_max > /dev/null
		done
	) &

	pid=$!
	stack_trap "kill -9 $pid"

	# errors here are OK so ignore them (just don't want to crash)
	$LFS setstripe -c -1 $dir/f.{1..200} 2> /dev/null

	return 0
}
run_test 27V "creating widely striped file races with deactivating OST"

test_27W() {
	[[ $($LCTL get_param mdc.*.import) =~ connect_flags.*overstriping ]] ||
		skip "server does not support overstriping"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	local stripe_count
	local defcount=4

	# Set back to unrestricted
	stack_trap "$LCTL set_param llite.$FSNAME-*.enable_setstripe_gid=-1"

	mkdir $DIR/$tdir
	# Set a default layout
	$LFS setstripe -C $defcount $DIR/$tdir || error "(0) root failed to set default layout"

	chmod a+rw $DIR
	chmod a+rw $DIR/$tdir
	# Verify this works normally
	$RUNAS $LFS setstripe -c 1 $DIR/$tdir/$tfile || error "(1) failed to setstripe"
	rm -f $DIR/$tdir/$tfile

	# Limit to CAP_SYS_RESOURCE
	$LCTL set_param llite.$FSNAME-*.enable_setstripe_gid=0
	# Prints a messsage, but will use the default layout for the directory
	# This is so scripts which use setstripe and don't check error will not fail
	$RUNAS $LFS setstripe -c 1 $DIR/$tdir/$tfile || error "(2) setstripe failed"
	# Verify default layout was used on file:
	stripe_count=$($LFS getstripe -c $DIR/$tdir/$tfile)
	((stripe_count == defcount)) ||
		error "(3) got stripe_count '$stripe_count', expected $defcount"
	rm -f $DIR/$tdir/$tfile

	# Allow for RUNAS group
	$LCTL set_param llite.$FSNAME-*.enable_setstripe_gid=$RUNAS_GID
	$RUNAS $LFS setstripe -c 1 $DIR/$tdir/$tfile || error "(4) failed to setstripe"
	# Confirm we did not use the default layout
	stripe_count=$($LFS getstripe -c $DIR/$tdir/$tfile)
	((stripe_count == 1)) || error "(5) got stripe_count '$stripe_count', expected 1"
	rm -f $DIR/$tdir/$tfile

	# Set to some other GID
	$LCTL set_param llite.$FSNAME-*.enable_setstripe_gid=1
	# Should give warning and succeed
	$RUNAS $LFS setstripe -c 1 $DIR/$tdir/$tfile || error "(6) setstripe failed"
	# Confirm we used default layout
	stripe_count=$($LFS getstripe -c $DIR/$tdir/$tfile)
	((stripe_count == defcount)) ||
		error "(7) got stripe_count '$stripe_count', expected $defcount"
}
run_test 27W "test enable_setstripe_gid"

test_27X() {
	[[ $($LCTL get_param mdc.*.import) =~ connect_flags.*overstriping ]] ||
		skip "server does not support overstriping"

	local file=$DIR/$tfile
	local count
	local overstripe_count=$((OSTCOUNT * 2))

	# Create a small file
	dd if=/dev/zero of=$file bs=1K count=1 || error "dd failed"

	# Migrate with --overstripe-count=2*OSTCOUNT
	$LFS migrate --overstripe-count=$overstripe_count $file ||
		error "migrate failed"

	# Check that the stripe count is 2*OSTCOUNT
	count=$($LFS getstripe -c $file)
	[ $count -eq $overstripe_count ] ||
		error "stripe count is $count, expected $overstripe_count"

	# Check that the file has the overstriping flag set
	$LFS getstripe $file | grep -q "overstriped" ||
		error "overstriping flag not set"

	# Clean up
	rm -f $file
}
run_test 27X "lfs migrate honors --overstripe-count option"

# createtest also checks that device nodes are created and
# then visible correctly (#2091)
test_28() { # bug 2091
	test_mkdir $DIR/d28
	$CREATETEST $DIR/d28/ct || error "createtest failed"
}
run_test 28 "create/mknod/mkdir with bad file types ============"

test_29() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	[ $MDS1_VERSION -ge $(version_code 2.14.51) ] && {
		disable_opencache
		stack_trap "restore_opencache"
	}

	sync; sleep 1; sync # flush out any dirty pages from previous tests
	cancel_lru_locks
	test_mkdir $DIR/d29
	touch $DIR/d29/foo
	log 'first d29'
	ls -l $DIR/d29

	local locks_orig=$(total_used_locks mdc)
	(( $locks_orig != 0 )) || error "No mdc lock count"

	local locks_unused_orig=$(total_unused_locks mdc)

	log 'second d29'
	ls -l $DIR/d29
	log 'done'

	local locks_current=$(total_used_locks mdc)

	local locks_unused_current=$(total_unused_locks mdc)

	if (( $locks_current > $locks_orig )); then
		$LCTL set_param -n ldlm.dump_namespaces ""
		error "CURRENT: $locks_current > $locks_orig"
	fi
	if (( $locks_unused_current > $locks_unused_orig )); then
		error "UNUSED: $locks_unused_current > $locks_unused_orig"
	fi
}
run_test 29 "IT_GETATTR regression  ============================"

test_30a() { # was test_30
	cp $(which ls) $DIR || cp /bin/ls $DIR
	$DIR/ls / || error "Can't execute binary from lustre"
	rm $DIR/ls
}
run_test 30a "execute binary from Lustre (execve) =============="

test_30b() {
	cp `which ls` $DIR || cp /bin/ls $DIR
	chmod go+rx $DIR/ls
	$RUNAS $DIR/ls / || error "Can't execute binary from lustre as non-root"
	rm $DIR/ls
}
run_test 30b "execute binary from Lustre as non-root ==========="

test_30c() { # b=22376
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	cp $(which ls) $DIR || cp /bin/ls $DIR
	chmod a-rw $DIR/ls
	cancel_lru_locks mdc
	cancel_lru_locks osc
	$RUNAS $DIR/ls / || error "Can't execute binary from lustre"
	rm -f $DIR/ls
}
run_test 30c "execute binary from Lustre without read perms ===="

test_30d() {
	cp $(which dd) $DIR || error "failed to copy dd to $DIR/dd"

	for i in {1..10}; do
		$DIR/dd bs=1M count=128 if=/dev/zero of=$DIR/$tfile &
		local PID=$!
		sleep 1
		$LCTL set_param ldlm.namespaces.*MDT*.lru_size=clear
		wait $PID || error "executing dd from Lustre failed"
		rm -f $DIR/$tfile
	done

	rm -f $DIR/dd
}
run_test 30d "execute binary from Lustre while clear locks"

test_31a() {
	$OPENUNLINK $DIR/f31 $DIR/f31 || error "openunlink failed"
	$CHECKSTAT -a $DIR/f31 || error "$DIR/f31 exists"
}
run_test 31a "open-unlink file =================================="

test_31b() {
	touch $DIR/f31 || error "touch $DIR/f31 failed"
	ln $DIR/f31 $DIR/f31b || error "ln failed"
	$MULTIOP $DIR/f31b Ouc || error "multiop failed"
	$CHECKSTAT -t file $DIR/f31 || error "$DIR/f31 not file type"
}
run_test 31b "unlink file with multiple links while open ======="

test_31c() {
	touch $DIR/f31 || error "touch $DIR/f31 failed"
	ln $DIR/f31 $DIR/f31c || error "ln failed"
	multiop_bg_pause $DIR/f31 O_uc ||
		error "multiop_bg_pause for $DIR/f31 failed"
	MULTIPID=$!
	$MULTIOP $DIR/f31c Ouc
	kill -USR1 $MULTIPID
	wait $MULTIPID
}
run_test 31c "open-unlink file with multiple links ============="

test_31d() {
	opendirunlink $DIR/d31d $DIR/d31d || error "opendirunlink failed"
	$CHECKSTAT -a $DIR/d31d || error "$DIR/d31d exists"
}
run_test 31d "remove of open directory ========================="

test_31e() { # bug 2904
	openfilleddirunlink $DIR/d31e || error "openfilleddirunlink failed"
}
run_test 31e "remove of open non-empty directory ==============="

test_31f() { # bug 4554
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	set -vx
	test_mkdir $DIR/d31f
	$LFS setstripe -S 1048576 -c 1 $DIR/d31f
	cp /etc/hosts $DIR/d31f
	ls -l $DIR/d31f
	$LFS getstripe $DIR/d31f/hosts
	multiop_bg_pause $DIR/d31f D_c || return 1
	MULTIPID=$!

	rm -rv $DIR/d31f || error "first of $DIR/d31f"
	test_mkdir $DIR/d31f
	$LFS setstripe -S 1048576 -c 1 $DIR/d31f
	cp /etc/hosts $DIR/d31f
	ls -l $DIR/d31f
	$LFS getstripe $DIR/d31f/hosts
	multiop_bg_pause $DIR/d31f D_c || return 1
	MULTIPID2=$!

	kill -USR1 $MULTIPID || error "first opendir $MULTIPID not running"
	wait $MULTIPID || error "first opendir $MULTIPID failed"

	sleep 6

	kill -USR1 $MULTIPID2 || error "second opendir $MULTIPID not running"
	wait $MULTIPID2 || error "second opendir $MULTIPID2 failed"
	set +vx
}
run_test 31f "remove of open directory with open-unlink file ==="

test_31g() {
	echo "-- cross directory link --"
	test_mkdir -c1 $DIR/${tdir}ga
	test_mkdir -c1 $DIR/${tdir}gb
	touch $DIR/${tdir}ga/f
	ln $DIR/${tdir}ga/f $DIR/${tdir}gb/g
	$CHECKSTAT -t file $DIR/${tdir}ga/f || error "source"
	[ `stat -c%h $DIR/${tdir}ga/f` == '2' ] || error "source nlink"
	$CHECKSTAT -t file $DIR/${tdir}gb/g || error "target"
	[ `stat -c%h $DIR/${tdir}gb/g` == '2' ] || error "target nlink"
}
run_test 31g "cross directory link==============="

test_31h() {
	echo "-- cross directory link --"
	test_mkdir -c1 $DIR/${tdir}
	test_mkdir -c1 $DIR/${tdir}/dir
	touch $DIR/${tdir}/f
	ln $DIR/${tdir}/f $DIR/${tdir}/dir/g
	$CHECKSTAT -t file $DIR/${tdir}/f || error "source"
	[ `stat -c%h $DIR/${tdir}/f` == '2' ] || error "source nlink"
	$CHECKSTAT -t file $DIR/${tdir}/dir/g || error "target"
	[ `stat -c%h $DIR/${tdir}/dir/g` == '2' ] || error "target nlink"
}
run_test 31h "cross directory link under child==============="

test_31i() {
	echo "-- cross directory link --"
	test_mkdir -c1 $DIR/$tdir
	test_mkdir -c1 $DIR/$tdir/dir
	touch $DIR/$tdir/dir/f
	ln $DIR/$tdir/dir/f $DIR/$tdir/g
	$CHECKSTAT -t file $DIR/$tdir/dir/f || error "source"
	[ `stat -c%h $DIR/$tdir/dir/f` == '2' ] || error "source nlink"
	$CHECKSTAT -t file $DIR/$tdir/g || error "target"
	[ `stat -c%h $DIR/$tdir/g` == '2' ] || error "target nlink"
}
run_test 31i "cross directory link under parent==============="

test_31j() {
	test_mkdir -c1 -p $DIR/$tdir
	test_mkdir -c1 -p $DIR/$tdir/dir1
	ln $DIR/$tdir/dir1 $DIR/$tdir/dir2 && error "ln for dir"
	link $DIR/$tdir/dir1 $DIR/$tdir/dir3 && error "link for dir"
	link $DIR/$tdir/dir1 $DIR/$tdir/dir1 && error "link to the same dir"
	return 0
}
run_test 31j "link for directory"

test_31k() {
	test_mkdir -c1 -p $DIR/$tdir
	touch $DIR/$tdir/s
	touch $DIR/$tdir/exist
	link $DIR/$tdir/s $DIR/$tdir/t || error "link"
	link $DIR/$tdir/s $DIR/$tdir/exist && error "link to exist file"
	link $DIR/$tdir/s $DIR/$tdir/s && error "link to the same file"
	link $DIR/$tdir/s $DIR/$tdir && error "link to parent dir"
	link $DIR/$tdir $DIR/$tdir/s && error "link parent dir to target"
	link $DIR/$tdir/not-exist $DIR/$tdir/foo && error "link non-existing to new"
	link $DIR/$tdir/not-exist $DIR/$tdir/s && error "link non-existing to exist"
	return 0
}
run_test 31k "link to file: the same, non-existing, dir"

test_31l() {
	local ln_ver=$(ln --version | awk '/coreutils/ { print $4 }')

	(( $(version_code $ln_ver) < $(version_code 8.31) )) ||
	(( $(version_code $(uname -r)) >= $(version_code 5.18) )) ||
		skip "need coreutils < 8.31 or kernel >= 5.18 for ln"

	touch $DIR/$tfile || error "create failed"
	mkdir $DIR/$tdir || error "mkdir failed"
	ln $DIR/$tfile $DIR/$tdir/ || error "ln to '$tdir/' failed"
}
run_test 31l "link to file: target dir has trailing slash"

test_31m() {
	mkdir $DIR/d31m
	touch $DIR/d31m/s
	mkdir $DIR/d31m2
	touch $DIR/d31m2/exist
	link $DIR/d31m/s $DIR/d31m2/t || error "link"
	link $DIR/d31m/s $DIR/d31m2/exist && error "link to exist file"
	link $DIR/d31m/s $DIR/d31m2 && error "link to parent dir"
	link $DIR/d31m2 $DIR/d31m/s && error "link parent dir to target"
	link $DIR/d31m/not-exist $DIR/d31m2/foo && error "link non-existing to new"
	link $DIR/d31m/not-exist $DIR/d31m2/s && error "link non-existing to exist"
	return 0
}
run_test 31m "link to file: the same, non-existing, dir"

test_31n() {
	touch $DIR/$tfile || error "cannot create '$DIR/$tfile'"
	nlink=$(stat --format=%h $DIR/$tfile)
	[ ${nlink:--1} -eq 1 ] || error "nlink is $nlink, expected 1"
	local fd=$(free_fd)
	local cmd="exec $fd<$DIR/$tfile"
	eval $cmd
	cmd="exec $fd<&-"
	trap "eval $cmd" EXIT
	nlink=$(stat --dereference --format=%h /proc/self/fd/$fd)
	[ ${nlink:--1} -eq 1 ] || error "nlink is $nlink, expected 1"
	rm $DIR/$tfile || error "cannot remove '$DIR/$tfile'"
	nlink=$(stat --dereference --format=%h /proc/self/fd/$fd)
	[ ${nlink:--1} -eq 0 ] || error "nlink is $nlink, expected 0"
	eval $cmd
}
run_test 31n "check link count of unlinked file"

link_one() {
	local tempfile=$(mktemp $1_XXXXXX)
	link $tempfile $1 2> /dev/null &&
		echo "$BASHPID: link $tempfile to $1 succeeded"
	unlink $tempfile
}

test_31o() { # LU-2901
	test_mkdir $DIR/$tdir
	for LOOP in $(seq 100); do
		rm -f $DIR/$tdir/$tfile*
		for THREAD in $(seq 8); do
			link_one $DIR/$tdir/$tfile.$LOOP &
		done
		wait
		local LINKS=$(ls -1 $DIR/$tdir | grep -c $tfile.$LOOP)
		[[ $LINKS -gt 1 ]] && ls $DIR/$tdir &&
			error "$LINKS duplicate links to $tfile.$LOOP" &&
			break || true
	done
}
run_test 31o "duplicate hard links with same filename"

test_31p() {
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"

	test_mkdir $DIR/$tdir
	$LFS setdirstripe -i0 -c2 $DIR/$tdir/striped_dir
	$LFS setdirstripe -D -c2 -H all_char $DIR/$tdir/striped_dir

	opendirunlink $DIR/$tdir/striped_dir/test1 ||
		error "open unlink test1 failed"
	opendirunlink $DIR/$tdir/striped_dir/test2 ||
		error "open unlink test2 failed"

	$CHECKSTAT -a $DIR/$tdir/striped_dir/test1 ||
		error "test1 still exists"
	$CHECKSTAT -a $DIR/$tdir/striped_dir/test2 ||
		error "test2 still exists"
}
run_test 31p "remove of open striped directory"

test_31q() {
	[ $MDSCOUNT -lt 3 ] && skip_env "needs >= 3 MDTs"

	$LFS mkdir -i 3,1 $DIR/$tdir || error "mkdir failed"
	index=$($LFS getdirstripe -i $DIR/$tdir)
	[ $index -eq 3 ] || error "first stripe index $index != 3"
	index=$($LFS getdirstripe $DIR/$tdir | tail -1 | awk '{print $1}')
	[ $index -eq 1 ] || error "second stripe index $index != 1"

	# when "-c <stripe_count>" is set, the number of MDTs specified after
	# "-i" should equal to the stripe count
	$LFS mkdir -i 3,1 -c 3 $DIR/$tdir.2 && error "mkdir should fail" || true
}
run_test 31q "create striped directory on specific MDTs"

#LU-14949
test_31r() {
	touch $DIR/$tfile.target
	touch $DIR/$tfile.source

	#OBD_FAIL_LLITE_OPEN_DELAY 0x1419
	$LCTL set_param fail_loc=0x1419 fail_val=3
	cat $DIR/$tfile.target &
	CATPID=$!

	# Guarantee open is waiting before we get here
	sleep 1
	mv $DIR/$tfile.source $DIR/$tfile.target

	wait $CATPID
	RC=$?
	if [[ $RC -ne 0 ]]; then
		error "open with cat failed, rc=$RC"
	fi
}
run_test 31r "open-rename(replace) race"

cleanup_test32_mount() {
	local rc=0
	trap 0
	local loopdev=$(losetup -a | grep $EXT2_DEV | sed -ne 's/:.*$//p')
	$UMOUNT $DIR/$tdir/ext2-mountpoint || rc=$?
	losetup -d $loopdev || true
	rm -rf $DIR/$tdir
	return $rc
}

test_32a() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	echo "== more mountpoints and symlinks ================="
	[ -e $DIR/$tdir ] && rm -fr $DIR/$tdir
	trap cleanup_test32_mount EXIT
	test_mkdir -p $DIR/$tdir/ext2-mountpoint
	mount -t ext2 -o loop $EXT2_DEV $DIR/$tdir/ext2-mountpoint ||
		error "mount failed for $EXT2_DEV $DIR/$tdir/ext2-mountpoint"
	$CHECKSTAT -t dir $DIR/$tdir/ext2-mountpoint/.. ||
		error "$DIR/$tdir/ext2-mountpoint/.. not dir type"
	cleanup_test32_mount
}
run_test 32a "stat d32a/ext2-mountpoint/.. ====================="

test_32b() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	[ -e $DIR/$tdir ] && rm -fr $DIR/$tdir
	trap cleanup_test32_mount EXIT
	test_mkdir -p $DIR/$tdir/ext2-mountpoint
	mount -t ext2 -o loop $EXT2_DEV $DIR/$tdir/ext2-mountpoint ||
		error "mount failed for $EXT2_DEV $DIR/$tdir/ext2-mountpoint"
	ls -al $DIR/$tdir/ext2-mountpoint/.. ||
		error "Can't list $DIR/$tdir/ext2-mountpoint/.."
	cleanup_test32_mount
}
run_test 32b "open d32b/ext2-mountpoint/.. ====================="

test_32c() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	[ -e $DIR/$tdir ] && rm -fr $DIR/$tdir
	trap cleanup_test32_mount EXIT
	test_mkdir -p $DIR/$tdir/ext2-mountpoint
	mount -t ext2 -o loop $EXT2_DEV $DIR/$tdir/ext2-mountpoint ||
		error "mount failed for $EXT2_DEV $DIR/$tdir/ext2-mountpoint"
	test_mkdir -p $DIR/$tdir/d2/test_dir
	$CHECKSTAT -t dir $DIR/$tdir/ext2-mountpoint/../d2/test_dir ||
		error "$DIR/$tdir/ext2-mountpoint/../d2/test_dir not dir type"
	cleanup_test32_mount
}
run_test 32c "stat d32c/ext2-mountpoint/../d2/test_dir ========="

test_32d() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	[ -e $DIR/$tdir ] && rm -fr $DIR/$tdir
	trap cleanup_test32_mount EXIT
	test_mkdir -p $DIR/$tdir/ext2-mountpoint
	mount -t ext2 -o loop $EXT2_DEV $DIR/$tdir/ext2-mountpoint ||
		error "mount failed for $EXT2_DEV $DIR/$tdir/ext2-mountpoint"
	test_mkdir -p $DIR/$tdir/d2/test_dir
	ls -al $DIR/$tdir/ext2-mountpoint/../d2/test_dir ||
		error "Can't list $DIR/$tdir/ext2-mountpoint/../d2/test_dir"
	cleanup_test32_mount
}
run_test 32d "open d32d/ext2-mountpoint/../d2/test_dir"

test_32e() {
	rm -fr $DIR/$tdir
	test_mkdir -p $DIR/$tdir/tmp
	local tmp_dir=$DIR/$tdir/tmp
	ln -s $DIR/$tdir $tmp_dir/symlink11
	ln -s $tmp_dir/symlink11 $tmp_dir/../symlink01
	$CHECKSTAT -t link $DIR/$tdir/tmp/symlink11 || error "symlink11 bad"
	$CHECKSTAT -t link $DIR/$tdir/symlink01 || error "symlink01 bad"
}
run_test 32e "stat d32e/symlink->tmp/symlink->lustre-subdir"

test_32f() {
	rm -fr $DIR/$tdir
	test_mkdir -p $DIR/$tdir/tmp
	local tmp_dir=$DIR/$tdir/tmp
	ln -s $DIR/$tdir $tmp_dir/symlink11
	ln -s $tmp_dir/symlink11 $tmp_dir/../symlink01
	ls $DIR/$tdir/tmp/symlink11  || error "symlink11 bad"
	ls $DIR/$tdir/symlink01 || error "symlink01 bad"
}
run_test 32f "open d32f/symlink->tmp/symlink->lustre-subdir"

test_32g() {
	local tmp_dir=$DIR/$tdir/tmp
	test_mkdir -p $tmp_dir
	test_mkdir $DIR/${tdir}2
	ln -s $DIR/${tdir}2 $tmp_dir/symlink12
	ln -s $tmp_dir/symlink12 $tmp_dir/../symlink02
	$CHECKSTAT -t link $tmp_dir/symlink12 || error "symlink12 not a link"
	$CHECKSTAT -t link $DIR/$tdir/symlink02 || error "symlink02 not a link"
	$CHECKSTAT -t dir -f $tmp_dir/symlink12 || error "symlink12 not a dir"
	$CHECKSTAT -t dir -f $DIR/$tdir/symlink02 || error "symlink12 not a dir"
}
run_test 32g "stat d32g/symlink->tmp/symlink->lustre-subdir/${tdir}2"

test_32h() {
	rm -fr $DIR/$tdir $DIR/${tdir}2
	tmp_dir=$DIR/$tdir/tmp
	test_mkdir -p $tmp_dir
	test_mkdir $DIR/${tdir}2
	ln -s $DIR/${tdir}2 $tmp_dir/symlink12
	ln -s $tmp_dir/symlink12 $tmp_dir/../symlink02
	ls $tmp_dir/symlink12 || error "listing symlink12"
	ls $DIR/$tdir/symlink02  || error "listing symlink02"
}
run_test 32h "open d32h/symlink->tmp/symlink->lustre-subdir/${tdir}2"

test_32i() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	[ -e $DIR/$tdir ] && rm -fr $DIR/$tdir
	trap cleanup_test32_mount EXIT
	test_mkdir -p $DIR/$tdir/ext2-mountpoint
	mount -t ext2 -o loop $EXT2_DEV $DIR/$tdir/ext2-mountpoint ||
		error "mount failed for $EXT2_DEV $DIR/$tdir/ext2-mountpoint"
	touch $DIR/$tdir/test_file
	$CHECKSTAT -t file $DIR/$tdir/ext2-mountpoint/../test_file ||
		error "$DIR/$tdir/ext2-mountpoint/../test_file not file type"
	cleanup_test32_mount
}
run_test 32i "stat d32i/ext2-mountpoint/../test_file ==========="

test_32j() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	[ -e $DIR/$tdir ] && rm -fr $DIR/$tdir
	trap cleanup_test32_mount EXIT
	test_mkdir -p $DIR/$tdir/ext2-mountpoint
	mount -t ext2 -o loop $EXT2_DEV $DIR/$tdir/ext2-mountpoint ||
		error "mount failed for $EXT2_DEV $DIR/$tdir/ext2-mountpoint"
	touch $DIR/$tdir/test_file
	cat $DIR/$tdir/ext2-mountpoint/../test_file ||
		error "Can't open $DIR/$tdir/ext2-mountpoint/../test_file"
	cleanup_test32_mount
}
run_test 32j "open d32j/ext2-mountpoint/../test_file ==========="

test_32k() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	rm -fr $DIR/$tdir
	trap cleanup_test32_mount EXIT
	test_mkdir -p $DIR/$tdir/ext2-mountpoint
	mount -t ext2 -o loop $EXT2_DEV $DIR/$tdir/ext2-mountpoint ||
		error "mount failed for $EXT2_DEV $DIR/$tdir/ext2-mountpoint"
	test_mkdir -p $DIR/$tdir/d2
	touch $DIR/$tdir/d2/test_file || error "touch failed"
	$CHECKSTAT -t file $DIR/$tdir/ext2-mountpoint/../d2/test_file ||
		error "$DIR/$tdir/ext2-mountpoint/../d2/test_file not file type"
	cleanup_test32_mount
}
run_test 32k "stat d32k/ext2-mountpoint/../d2/test_file ========"

test_32l() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	rm -fr $DIR/$tdir
	trap cleanup_test32_mount EXIT
	test_mkdir -p $DIR/$tdir/ext2-mountpoint
	mount -t ext2 -o loop $EXT2_DEV $DIR/$tdir/ext2-mountpoint ||
		error "mount failed for $EXT2_DEV $DIR/$tdir/ext2-mountpoint"
	test_mkdir -p $DIR/$tdir/d2
	touch $DIR/$tdir/d2/test_file || error "touch failed"
	cat  $DIR/$tdir/ext2-mountpoint/../d2/test_file ||
		error "Can't open $DIR/$tdir/ext2-mountpoint/../d2/test_file"
	cleanup_test32_mount
}
run_test 32l "open d32l/ext2-mountpoint/../d2/test_file ========"

test_32m() {
	rm -fr $DIR/d32m
	test_mkdir -p $DIR/d32m/tmp
	TMP_DIR=$DIR/d32m/tmp
	ln -s $DIR $TMP_DIR/symlink11
	ln -s $TMP_DIR/symlink11 $TMP_DIR/../symlink01
	$CHECKSTAT -t link $DIR/d32m/tmp/symlink11 ||
		error "symlink11 not a link"
	$CHECKSTAT -t link $DIR/d32m/symlink01 ||
		error "symlink01 not a link"
}
run_test 32m "stat d32m/symlink->tmp/symlink->lustre-root ======"

test_32n() {
	rm -fr $DIR/d32n
	test_mkdir -p $DIR/d32n/tmp
	TMP_DIR=$DIR/d32n/tmp
	ln -s $DIR $TMP_DIR/symlink11
	ln -s $TMP_DIR/symlink11 $TMP_DIR/../symlink01
	ls -l $DIR/d32n/tmp/symlink11  || error "listing symlink11"
	ls -l $DIR/d32n/symlink01 || error "listing symlink01"
}
run_test 32n "open d32n/symlink->tmp/symlink->lustre-root ======"

test_32o() {
	touch $DIR/$tfile
	test_mkdir -p $DIR/d32o/tmp
	TMP_DIR=$DIR/d32o/tmp
	ln -s $DIR/$tfile $TMP_DIR/symlink12
	ln -s $TMP_DIR/symlink12 $TMP_DIR/../symlink02
	$CHECKSTAT -t link $DIR/d32o/tmp/symlink12 ||
		error "symlink12 not a link"
	$CHECKSTAT -t link $DIR/d32o/symlink02 || error "symlink02 not a link"
	$CHECKSTAT -t file -f $DIR/d32o/tmp/symlink12 ||
		error "$DIR/d32o/tmp/symlink12 not file type"
	$CHECKSTAT -t file -f $DIR/d32o/symlink02 ||
		error "$DIR/d32o/symlink02 not file type"
}
run_test 32o "stat d32o/symlink->tmp/symlink->lustre-root/$tfile"

test_32p() {
	log 32p_1
	rm -fr $DIR/d32p
	log 32p_2
	rm -f $DIR/$tfile
	log 32p_3
	touch $DIR/$tfile
	log 32p_4
	test_mkdir -p $DIR/d32p/tmp
	log 32p_5
	TMP_DIR=$DIR/d32p/tmp
	log 32p_6
	ln -s $DIR/$tfile $TMP_DIR/symlink12
	log 32p_7
	ln -s $TMP_DIR/symlink12 $TMP_DIR/../symlink02
	log 32p_8
	cat $DIR/d32p/tmp/symlink12 ||
		error "Can't open $DIR/d32p/tmp/symlink12"
	log 32p_9
	cat $DIR/d32p/symlink02 || error "Can't open $DIR/d32p/symlink02"
	log 32p_10
}
run_test 32p "open d32p/symlink->tmp/symlink->lustre-root/$tfile"

test_32q() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	[ -e $DIR/$tdir ] && rm -fr $DIR/$tdir
	trap cleanup_test32_mount EXIT
	test_mkdir -p $DIR/$tdir/ext2-mountpoint
	touch $DIR/$tdir/ext2-mountpoint/under_the_mount || error "touch failed"
	mount -t ext2 -o loop $EXT2_DEV $DIR/$tdir/ext2-mountpoint ||
		error "mount failed for $EXT2_DEV $DIR/$tdir/ext2-mountpoint"
	ls $DIR/$tdir/ext2-mountpoint | grep "\<under_the_mount\>" && error
	cleanup_test32_mount
}
run_test 32q "stat follows mountpoints in Lustre (should return error)"

test_32r() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	[ -e $DIR/$tdir ] && rm -fr $DIR/$tdir
	trap cleanup_test32_mount EXIT
	test_mkdir -p $DIR/$tdir/ext2-mountpoint
	touch $DIR/$tdir/ext2-mountpoint/under_the_mount || error "touch failed"
	mount -t ext2 -o loop $EXT2_DEV $DIR/$tdir/ext2-mountpoint ||
		error "mount failed for $EXT2_DEV $DIR/$tdir/ext2-mountpoint"
	ls $DIR/$tdir/ext2-mountpoint | grep -q under_the_mount && error || true
	cleanup_test32_mount
}
run_test 32r "opendir follows mountpoints in Lustre (should return error)"

test_33aa() {
	rm -f $DIR/$tfile
	touch $DIR/$tfile
	chmod 444 $DIR/$tfile
	chown $RUNAS_ID $DIR/$tfile
	log 33_1
	$RUNAS $OPENFILE -f O_RDWR $DIR/$tfile && error || true
	log 33_2
}
run_test 33aa "write file with mode 444 (should return error)"

test_33a() {
	rm -fr $DIR/$tdir
	test_mkdir $DIR/$tdir
	chown $RUNAS_ID $DIR/$tdir
	$RUNAS $OPENFILE -f O_RDWR:O_CREAT -m 0444 $DIR/$tdir/$tfile ||
		error "$RUNAS create $tdir/$tfile failed"
	$RUNAS $OPENFILE -f O_RDWR:O_CREAT -m 0444 $DIR/$tdir/$tfile &&
		error "open RDWR" || true
}
run_test 33a "test open file(mode=0444) with O_RDWR (should return error)"

test_33b() {
	rm -fr $DIR/$tdir
	test_mkdir $DIR/$tdir
	chown $RUNAS_ID $DIR/$tdir
	$RUNAS $OPENFILE -f 1286739555 $DIR/$tdir/$tfile || true
}
run_test 33b "test open file with malformed flags (No panic)"

test_33c() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_ost_nodsh && skip "remote OST with nodsh"

	local ostnum
	local ostname
	local write_bytes
	local all_zeros

	all_zeros=true
	test_mkdir $DIR/$tdir
	# Read: 0, Write: 4, create/destroy: 2/0, stat: 1, punch: 0

	sync
	for ostnum in $(seq $OSTCOUNT); do
		# test-framework's OST numbering is one-based, while Lustre's
		# is zero-based
		ostname=$(printf "$FSNAME-OST%.4x" $((ostnum - 1)))
		# check if at least some write_bytes stats are counted
		write_bytes=$(do_facet ost$ostnum lctl get_param -n \
			      obdfilter.$ostname.stats |
			      awk '/^write_bytes/ {print $7}' )
		echo "baseline_write_bytes@ost$ostnum/$ostname=$write_bytes"
		if (( ${write_bytes:-0} > 0 )); then
			all_zeros=false
			break
		fi
	done

	$all_zeros || return 0

	# Write four bytes
	echo foo > $DIR/$tdir/bar
	# Really write them
	sync

	# Total up write_bytes after writing.  We'd better find non-zeros.
	for ostnum in $(seq $OSTCOUNT); do
		ostname=$(printf "$FSNAME-OST%.4x" $((ostnum - 1)))
		write_bytes=$(do_facet ost$ostnum lctl get_param -n \
			      obdfilter/$ostname/stats |
			      awk '/^write_bytes/ {print $7}' )
		echo "write_bytes@ost$ostnum/$ostname=$write_bytes"
		if (( ${write_bytes:-0} > 0 )); then
			all_zeros=false
			break
		fi
	done

	if $all_zeros; then
		for ostnum in $(seq $OSTCOUNT); do
			ostname=$(printf "$FSNAME-OST%.4x" $((ostnum - 1)))
			echo "Check write_bytes is in obdfilter.*.stats:"
			do_facet ost$ostnum lctl get_param -n \
				obdfilter.$ostname.stats
		done
		error "OST not keeping write_bytes stats (b=22312)"
	fi
}
run_test 33c "test write_bytes stats"

test_33d() {
	[[ $MDSCOUNT -lt 2 ]] && skip_env "needs >= 2 MDTs"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	local MDTIDX=1
	local remote_dir=$DIR/$tdir/remote_dir

	test_mkdir $DIR/$tdir
	$LFS mkdir -i $MDTIDX $remote_dir ||
		error "create remote directory failed"

	touch $remote_dir/$tfile
	chmod 444 $remote_dir/$tfile
	chown $RUNAS_ID $remote_dir/$tfile

	$RUNAS $OPENFILE -f O_RDWR $DIR/$tfile && error || true

	chown $RUNAS_ID $remote_dir
	$RUNAS $OPENFILE -f O_RDWR:O_CREAT -m 0444 $remote_dir/f33 ||
					error "create" || true
	$RUNAS $OPENFILE -f O_RDWR:O_CREAT -m 0444 $remote_dir/f33 &&
				    error "open RDWR" || true
	$RUNAS $OPENFILE -f 1286739555 $remote_dir/f33 || true
}
run_test 33d "openfile with 444 modes and malformed flags under remote dir"

test_33e() {
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"

	mkdir $DIR/$tdir

	$LFS setdirstripe -i0 -c2 $DIR/$tdir/striped_dir
	$LFS setdirstripe -i1 -c2 $DIR/$tdir/striped_dir1
	mkdir $DIR/$tdir/local_dir

	local s0_mode=$(stat -c%f $DIR/$tdir/striped_dir)
	local s1_mode=$(stat -c%f $DIR/$tdir/striped_dir1)
	local l_mode=$(stat -c%f $DIR/$tdir/local_dir)

	[ "$l_mode" = "$s0_mode" -a "$l_mode" = "$s1_mode" ] ||
		error "mkdir $l_mode striped0 $s0_mode striped1 $s1_mode"

	rmdir $DIR/$tdir/* || error "rmdir failed"

	umask 777
	$LFS setdirstripe -i0 -c2 $DIR/$tdir/striped_dir
	$LFS setdirstripe -i1 -c2 $DIR/$tdir/striped_dir1
	mkdir $DIR/$tdir/local_dir

	s0_mode=$(stat -c%f $DIR/$tdir/striped_dir)
	s1_mode=$(stat -c%f $DIR/$tdir/striped_dir1)
	l_mode=$(stat -c%f $DIR/$tdir/local_dir)

	[ "$l_mode" = "$s0_mode" -a "$l_mode" = "$s1_mode" ] ||
		error "mkdir $l_mode striped0 $s0_mode striped1 $s1_mode 777"

	rmdir $DIR/$tdir/* || error "rmdir(umask 777) failed"

	umask 000
	$LFS setdirstripe -i0 -c2 $DIR/$tdir/striped_dir
	$LFS setdirstripe -i1 -c2 $DIR/$tdir/striped_dir1
	mkdir $DIR/$tdir/local_dir

	s0_mode=$(stat -c%f $DIR/$tdir/striped_dir)
	s1_mode=$(stat -c%f $DIR/$tdir/striped_dir1)
	l_mode=$(stat -c%f $DIR/$tdir/local_dir)

	[ "$l_mode" = "$s0_mode" -a "$l_mode" = "$s1_mode" ] ||
		error "mkdir $l_mode striped0 $s0_mode striped1 $s1_mode 0"
}
run_test 33e "mkdir and striped directory should have same mode"

cleanup_33f() {
	trap 0
	do_facet $SINGLEMDS $LCTL set_param mdt.*.enable_remote_dir_gid=0
}

test_33f() {
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"
	remote_mds_nodsh && skip "remote MDS with nodsh"

	mkdir $DIR/$tdir
	chmod go+rwx $DIR/$tdir
	do_facet $SINGLEMDS $LCTL set_param mdt.*.enable_remote_dir_gid=-1
	trap cleanup_33f EXIT

	$RUNAS lfs mkdir -i 0 -c$MDSCOUNT $DIR/$tdir/striped_dir ||
		error "cannot create striped directory"

	$RUNAS touch $DIR/$tdir/striped_dir/{0..16} ||
		error "cannot create files in striped directory"

	$RUNAS rm $DIR/$tdir/striped_dir/{0..16} ||
		error "cannot remove files in striped directory"

	$RUNAS rmdir $DIR/$tdir/striped_dir ||
		error "cannot remove striped directory"

	cleanup_33f
}
run_test 33f "nonroot user can create, access, and remove a striped directory"

test_33g() {
	mkdir -p $DIR/$tdir/dir2

	local err=$($RUNAS mkdir $DIR/$tdir/dir2 2>&1)
	echo $err
	[[ $err =~ "exists" ]] || error "Not exists error"
}
run_test 33g "nonroot user create already existing root created file"

sub_33h() {
	local hash_type=$1
	local count=250

	test_mkdir -c $MDSCOUNT -H $hash_type $DIR/$tdir ||
		error "lfs mkdir -H $hash_type $tdir failed"
	touch $DIR/$tdir/$tfile || error "touch $tfile failed"

	local index=$($LFS getstripe -m $DIR/$tdir/$tfile)
	local index2
	local fname

	for fname in $DIR/$tdir/$tfile.bak \
		     $DIR/$tdir/$tfile.SAV \
		     $DIR/$tdir/$tfile.orig \
		     $DIR/$tdir/$tfile~; do
		touch $fname || error "touch $fname failed"
		index2=$($LFS getstripe -m $fname)
		(( $index == $index2 )) ||
			error "$fname MDT index mismatch $index != $index2"
	done

	local failed=0
	local patterns=(".$tfile.XXXXXX" "$tfile.XXXXXXXX")
	local pattern
	local stat

	for pattern in ${patterns[*]}; do
		echo "pattern $pattern"
		fname=$DIR/$tdir/$pattern
		for (( i = 0; i < $count; i++ )); do
			fname=$(mktemp $DIR/$tdir/$pattern) ||
				error "mktemp $DIR/$tdir/$pattern failed"
			index2=$($LFS getstripe -m $fname)
			(( $index == $index2 )) && continue

			failed=$((failed + 1))
			echo "$fname MDT index mismatch $index != $index2"
		done
	done

	echo "$failed/$count MDT index mismatches, expect ~2-4"
	(( failed < 10 )) || error "MDT index mismatch $failed/$count times"

	local same=0
	local expect

	# verify that "crush" is still broken with all files on same MDT,
	# crush2 should have about 1/MDSCOUNT files on each MDT, with margin
	[[ "$hash_type" == "crush" ]] && expect=$count ||
		expect=$((count / MDSCOUNT))

	local tries=3

	for (( try = tries - 1; try >= 0; try-- )); do
		# crush2 doesn't put all-numeric suffixes on the same MDT,
		# filename like $tfile.12345678 should *not* be considered temp
		for pattern in ${patterns[*]}; do
			local base=${pattern%%X*}
			local suff=${pattern#$base}

			echo "pattern $pattern"
			for (( i = 0; i < $count; i++ )); do
				fname=$DIR/$tdir/$base$((${suff//X/1} + i))
				touch $fname || error "touch $fname failed"
				index2=$($LFS getstripe -m $fname)
				(( $index != $index2 )) && continue

				same=$((same + 1))
			done
		done

		stat="$((same/${#patterns[*]}))/$count"
		# the number of "bad" hashes is random, as it depends on the
		# random filenames generated by "mktemp". Allow some margin in
		# the results.
		echo "$stat matches, expect ~$expect for $1"
		(( same / ${#patterns[*]} <= expect * 9 / 7 &&
		   same / ${#patterns[*]} > expect * 5 / 7 )) && same=0 && break
		log "MDT index match $stat times, $try tries left"

		(( try > 0 )) ||
		error "MDT index match $stat times, after $tries tries"
		same=0
	done

	for (( try = tries - 1; try >= 0; try-- )); do
		# crush2 doesn't put suffixes with special chars on the same MDT
		# filenames like $tfile.txt.1234 should *not* be considered temp
		for pattern in ${patterns[*]}; do
			local base=${pattern%%X*}
			local suff=${pattern#$base}

			pattern=$base...${suff/XXX}
			echo "pattern=$pattern"
			for (( i = 0; i < $count; i++ )); do
				fname=$(mktemp $DIR/$tdir/$pattern) ||
					error "touch $fname failed"
				index2=$($LFS getstripe -m $fname)
				(( $index != $index2 )) && continue

				same=$((same + 1))
			done
		done

		stat="$((same/${#patterns[*]}))/$count"
		# the number of "bad" hashes is random, as it depends on the
		# filenames generated by "mktemp".  Allow some margin in results
		echo "$stat matches, expect ~$expect for $1"
		(( same / ${#patterns[*]} <= expect * 9 / 7 &&
		   same / ${#patterns[*]} > expect * 5 / 7 )) && break
		log "MDT index match $stat times, $try tries left"

		(( try > 0 )) ||
		error "MDT index match $stat times, after $tries tries"
		same=0
	done
}

test_33h() {
	(( $MDSCOUNT >= 2 )) || skip "needs >= 2 MDTs"
	(( $MDS1_VERSION >= $(version_code 2.13.50) )) ||
		skip "Need MDS version at least 2.13.50"

	sub_33h crush
}
run_test 33h "temp file is located on the same MDT as target (crush)"

test_33hh() {
	(( $MDSCOUNT >= 2 )) || skip "needs >= 2 MDTs"
	echo "MDS1_VERSION=$MDS1_VERSION version_code=$(version_code 2.15.0)"
	(( $MDS1_VERSION > $(version_code 2.15.0) )) ||
		skip "Need MDS version at least 2.15.0 for crush2"

	sub_33h crush2
}
run_test 33hh "temp file is located on the same MDT as target (crush2)"

test_33i()
{
	(( MDSCOUNT < 2 )) && skip "needs >= 2 MDTs"

	local FNAME=$(str_repeat 'f' 250)

	test_mkdir -i 0 -c $MDSCOUNT $DIR/$tdir || error "mkdir $tdir failed"
	createmany -o $DIR/$tdir/$FNAME 1000 || error "createmany failed"

	local count
	local total

	count=$($LFS getstripe -m $DIR/$tdir/* | grep -cw 1)

	local MDC=$(lctl dl | awk '/MDT0001-mdc-[^M]/ { print $4 }')

	lctl --device %$MDC deactivate
	stack_trap "lctl --device %$MDC activate"
	ls $DIR/$tdir > /dev/null && error "ls should return an error"
	total=$(\ls -l $DIR/$tdir | wc -l)
	# "ls -l" will list total in the first line
	total=$((total - 1))
	(( total + count == 1000 )) ||
		error "ls list $total files, $count files on MDT1"
}
run_test 33i "striped directory can be accessed when one MDT is down"

test_33j() {
	(( $MDSCOUNT >= 2 )) || skip "needs >= 2 MDTs"

	mkdir -p $DIR/$tdir/

	$LFS setdirstripe -D -i0,1 $DIR/$tdir/striped_dir_a &&
		error "setdirstripe -D -i0,1 incorrectly succeeded"

	$LFS setdirstripe -D -i0,1 -c1 $DIR/$tdir/striped_dir_b &&
		error "setdirstripe -D -i0,1 -c1 incorrectly succeeded"

	$LFS setdirstripe -D -i0,1 -c3 $DIR/$tdir/striped_dir_c &&
		error "setdirstripe -D -i0,1 -c3 incorrectly succeeded"

	$LFS setdirstripe -i0,1 $DIR/$tdir/striped_dir_e ||
		error "-D was not specified, but still failed"
}
run_test 33j "lfs setdirstripe -D -i x,y,x should fail"

TEST_34_SIZE=${TEST_34_SIZE:-2000000000000}
test_34a() {
	rm -f $DIR/f34
	$MCREATE $DIR/f34 || error "mcreate failed"
	$LFS getstripe $DIR/f34 2>&1 | grep -q "no stripe info" ||
		error "getstripe failed"
	$TRUNCATE $DIR/f34 $TEST_34_SIZE || error "truncate failed"
	$LFS getstripe $DIR/f34 2>&1 | grep -q "no stripe info" ||
		error "getstripe failed"
	$CHECKSTAT -s $TEST_34_SIZE $DIR/f34 ||
		error "Size of $DIR/f34 not equal to $TEST_34_SIZE bytes"
}
run_test 34a "truncate file that has not been opened ==========="

test_34b() {
	[ ! -f $DIR/f34 ] && test_34a
	$CHECKSTAT -s $TEST_34_SIZE $DIR/f34 ||
		error "Size of $DIR/f34 not equal to $TEST_34_SIZE bytes"
	$OPENFILE -f O_RDONLY $DIR/f34
	$LFS getstripe $DIR/f34 2>&1 | grep -q "no stripe info" ||
		error "getstripe failed"
	$CHECKSTAT -s $TEST_34_SIZE $DIR/f34 ||
		error "Size of $DIR/f34 not equal to $TEST_34_SIZE bytes"
}
run_test 34b "O_RDONLY opening file doesn't create objects ====="

test_34c() {
	[ ! -f $DIR/f34 ] && test_34a
	$CHECKSTAT -s $TEST_34_SIZE $DIR/f34 ||
		error "Size of $DIR/f34 not equal to $TEST_34_SIZE bytes"
	$OPENFILE -f O_RDWR $DIR/f34
	$LFS getstripe $DIR/f34 2>&1 | grep -q "no stripe info" &&
		error "$LFS getstripe failed"
	$CHECKSTAT -s $TEST_34_SIZE $DIR/f34 ||
		error "Size of $DIR/f34 not equal to $TEST_34_SIZE bytes"
}
run_test 34c "O_RDWR opening file-with-size works =============="

test_34d() {
	[ ! -f $DIR/f34 ] && test_34a
	dd if=/dev/zero of=$DIR/f34 conv=notrunc bs=4k count=1 ||
		error "dd failed"
	$CHECKSTAT -s $TEST_34_SIZE $DIR/f34 ||
		error "Size of $DIR/f34 not equal to $TEST_34_SIZE bytes"
	rm $DIR/f34
}
run_test 34d "write to sparse file ============================="

test_34e() {
	rm -f $DIR/f34e
	$MCREATE $DIR/f34e || error "mcreate failed"
	$TRUNCATE $DIR/f34e 1000 || error "truncate failed"
	$CHECKSTAT -s 1000 $DIR/f34e ||
		error "Size of $DIR/f34e not equal to 1000 bytes"
	$OPENFILE -f O_RDWR $DIR/f34e
	$CHECKSTAT -s 1000 $DIR/f34e ||
		error "Size of $DIR/f34e not equal to 1000 bytes"
}
run_test 34e "create objects, some with size and some without =="

test_34f() { # bug 6242, 6243
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	SIZE34F=48000
	rm -f $DIR/f34f
	$MCREATE $DIR/f34f || error "mcreate failed"
	$TRUNCATE $DIR/f34f $SIZE34F || error "truncating $DIR/f3f to $SIZE34F"
	dd if=$DIR/f34f of=$TMP/f34f
	$CHECKSTAT -s $SIZE34F $TMP/f34f || error "$TMP/f34f not $SIZE34F bytes"
	dd if=/dev/zero of=$TMP/f34fzero bs=$SIZE34F count=1
	cmp $DIR/f34f $TMP/f34fzero || error "$DIR/f34f not all zero"
	cmp $TMP/f34f $TMP/f34fzero || error "$TMP/f34f not all zero"
	rm $TMP/f34f $TMP/f34fzero $DIR/f34f
}
run_test 34f "read from a file with no objects until EOF ======="

test_34g() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	dd if=/dev/zero of=$DIR/$tfile bs=1 count=100 seek=$TEST_34_SIZE ||
		error "dd failed"
	$TRUNCATE $DIR/$tfile $((TEST_34_SIZE / 2))|| error "truncate failed"
	$CHECKSTAT -s $((TEST_34_SIZE / 2)) $DIR/$tfile ||
		error "Size of $DIR/$tfile not equal to $((TEST_34_SIZE / 2))"
	cancel_lru_locks osc
	$CHECKSTAT -s $((TEST_34_SIZE / 2)) $DIR/$tfile ||
		error "wrong size after lock cancel"

	$TRUNCATE $DIR/$tfile $TEST_34_SIZE || error "truncate failed"
	$CHECKSTAT -s $TEST_34_SIZE $DIR/$tfile ||
		error "expanding truncate failed"
	cancel_lru_locks osc
	$CHECKSTAT -s $TEST_34_SIZE $DIR/$tfile ||
		error "wrong expanded size after lock cancel"
}
run_test 34g "truncate long file ==============================="

test_34h() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	local gid=10
	local sz=1000

	dd if=/dev/zero of=$DIR/$tfile bs=1M count=10 || error "dd failed"
	sync # Flush the cache so that multiop below does not block on cache
	     # flush when getting the group lock
	$MULTIOP $DIR/$tfile OG${gid}T${sz}g${gid}c &
	MULTIPID=$!

	# Since just timed wait is not good enough, let's do a sync write
	# that way we are sure enough time for a roundtrip + processing
	# passed + 2 seconds of extra margin.
	dd if=/dev/zero of=$DIR/${tfile}-1 bs=$PAGE_SIZE oflag=direct count=1
	rm $DIR/${tfile}-1
	sleep 2

	if [[ `ps h -o comm -p $MULTIPID` == "multiop" ]]; then
		error "Multiop blocked on ftruncate, pid=$MULTIPID"
		kill -9 $MULTIPID
	fi
	wait $MULTIPID
	local nsz=`stat -c %s $DIR/$tfile`
	[[ $nsz == $sz ]] || error "New size wrong $nsz != $sz"
}
run_test 34h "ftruncate file under grouplock should not block"

test_35a() {
	cp /usr/bin/bash $DIR/f35a
	chmod 444 $DIR/f35a
	chown $RUNAS_ID $DIR/f35a
	$RUNAS $DIR/f35a && error || true
	rm $DIR/f35a
}
run_test 35a "exec file with mode 444 (should return and not leak)"

test_36a() {
	rm -f $DIR/f36
	utime $DIR/f36 || error "utime failed for MDS"
}
run_test 36a "MDS utime check (mknod, utime)"

test_36b() {
	echo "" > $DIR/f36
	utime $DIR/f36 || error "utime failed for OST"
}
run_test 36b "OST utime check (open, utime)"

test_36c() {
	rm -f $DIR/d36/f36
	test_mkdir $DIR/d36
	chown $RUNAS_ID $DIR/d36
	$RUNAS utime $DIR/d36/f36 || error "utime failed for MDS as non-root"
}
run_test 36c "non-root MDS utime check (mknod, utime)"

test_36d() {
	[ ! -d $DIR/d36 ] && test_36c
	echo "" > $DIR/d36/f36
	$RUNAS utime $DIR/d36/f36 || error "utime failed for OST as non-root"
}
run_test 36d "non-root OST utime check (open, utime)"

test_36e() {
	[ $RUNAS_ID -eq $UID ] && skip_env "RUNAS_ID = UID = $UID -- skipping"

	test_mkdir $DIR/$tdir
	touch $DIR/$tdir/$tfile
	$RUNAS utime $DIR/$tdir/$tfile &&
		error "utime worked, expected failure" || true
}
run_test 36e "utime on non-owned file (should return error)"

subr_36fh() {
	local fl="$1"
	local LANG_SAVE=$LANG
	local LC_LANG_SAVE=$LC_LANG
	export LANG=C LC_LANG=C # for date language

	DATESTR="Dec 20  2000"
	test_mkdir $DIR/$tdir
	lctl set_param fail_loc=$fl
	date; date +%s
	cp /etc/hosts $DIR/$tdir/$tfile
	sync & # write RPC generated with "current" inode timestamp, but delayed
	sleep 1
	touch --date="$DATESTR" $DIR/$tdir/$tfile # setattr timestamp in past
	LS_BEFORE="`ls -l $DIR/$tdir/$tfile`" # old timestamp from client cache
	cancel_lru_locks $OSC
	LS_AFTER="`ls -l $DIR/$tdir/$tfile`"  # timestamp from OST object
	date; date +%s
	[ "$LS_BEFORE" != "$LS_AFTER" ] && \
		echo "BEFORE: $LS_BEFORE" && \
		echo "AFTER : $LS_AFTER" && \
		echo "WANT  : $DATESTR" && \
		error "$DIR/$tdir/$tfile timestamps changed" || true

	export LANG=$LANG_SAVE LC_LANG=$LC_LANG_SAVE
}

test_36f() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	#define OBD_FAIL_OST_BRW_PAUSE_BULK 0x214
	subr_36fh "0x80000214"
}
run_test 36f "utime on file racing with OST BRW write =========="

test_36g() {
	remote_ost_nodsh && skip "remote OST with nodsh"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ $MDS1_VERSION -lt $(version_code 2.12.51) ] &&
		skip "Need MDS version at least 2.12.51"

	local fmd_max_age
	local fmd
	local facet="ost1"
	local tgt="obdfilter"

	[[ $OSC == "mdc" ]] && tgt="mdt" && facet="mds1"

	test_mkdir $DIR/$tdir
	fmd_max_age=$(do_facet $facet \
		"lctl get_param -n $tgt.*.tgt_fmd_seconds 2> /dev/null | \
		head -n 1")

	echo "FMD max age: ${fmd_max_age}s"
	touch $DIR/$tdir/$tfile
	fmd=$(do_facet $facet "lctl get_param -n $tgt.*.exports.*.fmd_count" |
		gawk '{cnt=cnt+$1}  END{print cnt}')
	echo "FMD before: $fmd"
	[[ $fmd == 0 ]] &&
		error "FMD wasn't create by touch"
	sleep $((fmd_max_age + 12))
	fmd=$(do_facet $facet "lctl get_param -n $tgt.*.exports.*.fmd_count" |
		gawk '{cnt=cnt+$1}  END{print cnt}')
	echo "FMD after: $fmd"
	[[ $fmd == 0 ]] ||
		error "FMD wasn't expired by ping"
}
run_test 36g "FMD cache expiry ====================="

test_36h() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	#define OBD_FAIL_OST_BRW_PAUSE_BULK2 0x227
	subr_36fh "0x80000227"
}
run_test 36h "utime on file racing with OST BRW write =========="

test_36i() {
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"

	test_mkdir $DIR/$tdir
	$LFS setdirstripe -i0 -c$MDSCOUNT $DIR/$tdir/striped_dir

	local mtime=$(stat -c%Y $DIR/$tdir/striped_dir)
	local new_mtime=$((mtime + 200))

	#change Modify time of striped dir
	touch -m -d @$new_mtime	$DIR/$tdir/striped_dir ||
			error "change mtime failed"

	local got=$(stat -c%Y $DIR/$tdir/striped_dir)

	[ "$new_mtime" = "$got" ] || error "expect $new_mtime got $got"
}
run_test 36i "change mtime on striped directory"

# test_37 - duplicate with tests 32q 32r

test_38() {
	local file=$DIR/$tfile
	touch $file
	openfile -f O_DIRECTORY $file
	local RC=$?
	local ENOTDIR=20
	[ $RC -eq 0 ] && error "opened file $file with O_DIRECTORY" || true
	[ $RC -eq $ENOTDIR ] || error "error $RC should be ENOTDIR ($ENOTDIR)"
}
run_test 38 "open a regular file with O_DIRECTORY should return -ENOTDIR ==="

test_39a() { # was test_39
	touch $DIR/$tfile
	touch $DIR/${tfile}2
#	ls -l  $DIR/$tfile $DIR/${tfile}2
#	ls -lu  $DIR/$tfile $DIR/${tfile}2
#	ls -lc  $DIR/$tfile $DIR/${tfile}2
	sleep 2
	$OPENFILE -f O_CREAT:O_TRUNC:O_WRONLY $DIR/${tfile}2
	if [[ ! $DIR/${tfile}2 -nt $DIR/$tfile ]]; then
		echo "mtime"
		ls -l --full-time $DIR/$tfile $DIR/${tfile}2
		echo "atime"
		ls -lu --full-time $DIR/$tfile $DIR/${tfile}2
		echo "ctime"
		ls -lc --full-time $DIR/$tfile $DIR/${tfile}2
		error "O_TRUNC didn't change timestamps"
	fi
}
run_test 39a "mtime changed on create"

test_39b() {
	test_mkdir -c1 $DIR/$tdir
	cp -p /etc/passwd $DIR/$tdir/fopen
	cp -p /etc/passwd $DIR/$tdir/flink
	cp -p /etc/passwd $DIR/$tdir/funlink
	cp -p /etc/passwd $DIR/$tdir/frename
	ln $DIR/$tdir/funlink $DIR/$tdir/funlink2

	sleep 1
	echo "aaaaaa" >> $DIR/$tdir/fopen
	echo "aaaaaa" >> $DIR/$tdir/flink
	echo "aaaaaa" >> $DIR/$tdir/funlink
	echo "aaaaaa" >> $DIR/$tdir/frename

	local open_new=$(stat -c %Y $DIR/$tdir/fopen)
	local link_new=$(stat -c %Y $DIR/$tdir/flink)
	local unlink_new=$(stat -c %Y $DIR/$tdir/funlink)
	local rename_new=$(stat -c %Y $DIR/$tdir/frename)

	cat $DIR/$tdir/fopen > /dev/null
	ln $DIR/$tdir/flink $DIR/$tdir/flink2
	rm -f $DIR/$tdir/funlink2
	mv -f $DIR/$tdir/frename $DIR/$tdir/frename2

	for (( i=0; i < 2; i++ )) ; do
		local open_new2=$(stat -c %Y $DIR/$tdir/fopen)
		local link_new2=$(stat -c %Y $DIR/$tdir/flink)
		local unlink_new2=$(stat -c %Y $DIR/$tdir/funlink)
		local rename_new2=$(stat -c %Y $DIR/$tdir/frename2)

		(( $open_new2 == $open_new )) ||
			error "open file reverses mtime"
		(( $link_new2 == $link_new )) ||
			error "link file reverses mtime"
		(( $unlink_new2 == $unlink_new )) ||
			error "unlink file reverses mtime"
		(( $rename_new2 == $rename_new )) ||
			error "rename file reverses mtime"

		cancel_lru_locks $OSC
		(( $i > 0 )) || echo "repeat after cancel_lru_locks"
	done
}
run_test 39b "mtime change on open, link, unlink, rename"

# this should be set to past
TEST_39_MTIME=$(date -d "1 year ago" +%s)

# bug 11063
test_39c() {
	touch $DIR1/$tfile
	sleep 2
	local mtime0=$(stat -c %Y $DIR1/$tfile)

	touch -m -d @$TEST_39_MTIME $DIR1/$tfile
	local mtime1=$(stat -c %Y $DIR1/$tfile)
	(( $mtime1 == $TEST_39_MTIME )) ||
		error "mtime not set to past: $mtime1, should be $TEST_39_MTIME"

	local d1=$(date +%s)
	sleep 0.5
	echo hello >> $DIR1/$tfile
	sleep 0.5
	local d2=$(date +%s)
	local mtime2=$(stat -c %Y $DIR1/$tfile)
	(( $d1 <= $mtime2 && $mtime2 <= $d2 )) ||
		error "mtime is not updated on write: $d1 <= $mtime2 <= $d2"

	mv $DIR1/$tfile $DIR1/$tfile-1

	for (( i=0; i < 2; i++ )) ; do
		local mtime3=$(stat -c %Y $DIR1/$tfile-1)
		(( $mtime2 == $mtime3 )) ||
			error "mtime ($mtime2) changed (to $mtime3) on rename"

		cancel_lru_locks $OSC
		(( $i > 0 )) || echo "repeat after cancel_lru_locks"
	done
}
run_test 39c "mtime change on rename"

# bug 21114
test_39d() {
	[[ $PARALLEL != "yes" ]] || skip "skip parallel run"

	touch $DIR1/$tfile
	touch -m -d @$TEST_39_MTIME $DIR1/$tfile

	for (( i=0; i < 2; i++ )) ; do
		local mtime=$(stat -c %Y $DIR1/$tfile)

		(( $mtime == $TEST_39_MTIME )) ||
			error "mtime($mtime) is not set to $TEST_39_MTIME"

		cancel_lru_locks $OSC
		(( $i > 0 )) || echo "repeat after cancel_lru_locks"
	done
}
run_test 39d "create, utime, stat"

# bug 21114
test_39e() {
	[[ $PARALLEL != "yes" ]] || skip "skip parallel run"

	touch $DIR1/$tfile
	local mtime1=$(stat -c %Y $DIR1/$tfile)

	touch -m -d @$TEST_39_MTIME $DIR1/$tfile

	for (( i=0; i < 2; i++ )) ; do
		local mtime2=$(stat -c %Y $DIR1/$tfile)
		(( $mtime2 == $TEST_39_MTIME )) ||
			error "mtime($mtime2) is not set to $TEST_39_MTIME"

		cancel_lru_locks $OSC
		(( $i > 0 )) || echo "repeat after cancel_lru_locks"
	done
}
run_test 39e "create, stat, utime, stat"

# bug 21114
test_39f() {
	[[ $PARALLEL != "yes" ]] || skip "skip parallel run"

	touch $DIR1/$tfile
	mtime1=$(stat -c %Y $DIR1/$tfile)

	sleep 2
	touch -m -d @$TEST_39_MTIME $DIR1/$tfile

	for (( i=0; i < 2; i++ )) ; do
		local mtime2=$(stat -c %Y $DIR1/$tfile)
		(( $mtime2 == $TEST_39_MTIME )) ||
			error "mtime($mtime2) is not set to $TEST_39_MTIME"

		cancel_lru_locks $OSC
		(( $i > 0 )) || echo "repeat after cancel_lru_locks"
	done
}
run_test 39f "create, stat, sleep, utime, stat"

# b=11063
test_39g() {
	[[ $PARALLEL != "yes" ]] || skip "skip parallel run"

	echo hello >> $DIR1/$tfile
	local mtime1=$(stat -c %Y $DIR1/$tfile)

	sleep 2
	chmod o+r $DIR1/$tfile

	for (( i=0; i < 2; i++ )) ; do
		local mtime2=$(stat -c %Y $DIR1/$tfile)
		(( $mtime1 == $mtime2 )) || \
			error "lost mtime: $mtime2, should be $mtime1"

		cancel_lru_locks $OSC
		(( $i > 0 )) || echo "repeat after cancel_lru_locks"
	done
}
run_test 39g "write, chmod, stat"

# bug 11063
test_39h() {
	[[ $PARALLEL != "yes" ]] || skip "skip parallel run"

	touch $DIR1/$tfile
	sleep 1

	local d1=$(date +%s)
	echo hello >> $DIR1/$tfile
	local mtime1=$(stat -c %Y $DIR1/$tfile)

	touch -m -d @$TEST_39_MTIME $DIR1/$tfile
	local d2=$(date +%s)
	if (( $d1 != $d2 )); then
		echo "write and touch not within one second"
	else
		for (( i=0; i < 2; i++ )) ; do
			local mtime2=$(stat -c %Y $DIR1/$tfile)
			(( $mtime2 == $TEST_39_MTIME )) ||
				error "lost mtime: $mtime2, should be $TEST_39_MTIME"

			cancel_lru_locks $OSC
			(( $i > 0 )) || echo "repeat after cancel_lru_locks"
		done
	fi
}
run_test 39h "write, utime within one second, stat"

test_39i() {
	touch $DIR1/$tfile
	sleep 1

	echo hello >> $DIR1/$tfile
	local mtime1=$(stat -c %Y $DIR1/$tfile)

	mv $DIR1/$tfile $DIR1/$tfile-1

	for (( i=0; i < 2; i++ )) ; do
		local mtime2=$(stat -c %Y $DIR1/$tfile-1)

		(( $mtime1 == $mtime2 )) ||
			error "lost mtime: $mtime2, should be $mtime1"

		cancel_lru_locks $OSC
		(( $i > 0 )) || echo "repeat after cancel_lru_locks"
	done
}
run_test 39i "write, rename, stat"

test_39j() {
	[[ $PARALLEL != "yes" ]] || skip "skip parallel run"

	start_full_debug_logging
	touch $DIR1/$tfile
	sleep 1
	stack_trap "rm -f $DIR1/$tfile"

	#define OBD_FAIL_OSC_DELAY_SETTIME	 0x412
	lctl set_param fail_loc=0x80000412
	multiop_bg_pause $DIR1/$tfile oO_RDWR:w2097152_c ||
		error "multiop failed"
	local multipid=$!
	local mtime1=$(stat -c %Y $DIR1/$tfile)

	mv $DIR1/$tfile $DIR1/$tfile-1

	kill -USR1 $multipid
	wait $multipid || error "multiop close failed"

	for (( i=0; i < 2; i++ )) ; do
		local mtime2=$(stat -c %Y $DIR1/$tfile-1)
		(( $mtime1 == $mtime2 )) ||
			error "mtime lost on close: $mtime2, should be $mtime1"

		cancel_lru_locks
		(( $i > 0 )) || echo "repeat after cancel_lru_locks"
	done
	lctl set_param fail_loc=0
	stop_full_debug_logging
}
run_test 39j "write, rename, close, stat"

test_39k() {
	[[ $PARALLEL != "yes" ]] || skip "skip parallel run"

	touch $DIR1/$tfile
	sleep 1
	stack_trap "rm -f $DIR1/$tfile"

	multiop_bg_pause $DIR1/$tfile oO_RDWR:w2097152_c || error "multiop failed"
	local multipid=$!
	local mtime1=$(stat -c %Y $DIR1/$tfile)

	touch -m -d @$TEST_39_MTIME $DIR1/$tfile

	kill -USR1 $multipid
	wait $multipid || error "multiop close failed"

	for (( i=0; i < 2; i++ )) ; do
		local mtime2=$(stat -c %Y $DIR1/$tfile)

		(( $mtime2 == $TEST_39_MTIME )) ||
			error "mtime lost on close: $mtime2, should be $TEST_39_MTIME"

		cancel_lru_locks
		(( $i > 0 )) || echo "repeat after cancel_lru_locks"
	done
}
run_test 39k "write, utime, close, stat"

# this should be set to future
TEST_39_ATIME=$(date -d "1 year" +%s)

test_39l() {
	[[ $PARALLEL != "yes" ]] || skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"

	local atime_diff=$(do_facet $SINGLEMDS \
			   $LCTL get_param -n mdd.*MDT0000*.atime_diff)
	rm -rf $DIR/$tdir
	mkdir_on_mdt0 $DIR/$tdir

	# test setting directory atime to future
	touch -a -d @$TEST_39_ATIME $DIR/$tdir
	local atime=$(stat -c %X $DIR/$tdir)
	(( $atime == $TEST_39_ATIME )) ||
		error "atime is not set to future: $atime, $TEST_39_ATIME"

	# test setting directory atime from future to now
	local now=$(date +%s)
	touch -a -d @$now $DIR/$tdir

	atime=$(stat -c %X $DIR/$tdir)
	(( $atime == $now  )) ||
		error "atime is not updated from future: $atime, $now"

	do_facet $SINGLEMDS lctl set_param -n mdd.*MDT0000*.atime_diff=2
	sleep 3

	# test setting directory atime when now > dir atime + atime_diff
	local d1=$(date +%s)
	sleep 0.5
	ls $DIR/$tdir
	sleep 0.5
	local d2=$(date +%s)
	cancel_lru_locks mdc
	atime=$(stat -c %X $DIR/$tdir)
	(( $d1 <= $atime && $atime <= $d2 )) ||
		error "atime is not updated  : $atime, should be $d2"

	do_facet $SINGLEMDS lctl set_param -n mdd.*MDT0000*.atime_diff=60
	sleep 3

	# test not setting directory atime when now < dir atime + atime_diff
	ls $DIR/$tdir
	cancel_lru_locks mdc
	atime=$(stat -c %X $DIR/$tdir)
	(( $d1 <= $atime && $atime <= $d2 )) ||
		error "atime is updated to $atime, should remain $d1<atime<$d2"

	do_facet $SINGLEMDS \
		$LCTL set_param -n mdd.*MDT0000*.atime_diff=$atime_diff
}
run_test 39l "directory atime update"

test_39m() {
	[[ $PARALLEL != "yes" ]] || skip "skip parallel run"

	touch $DIR1/$tfile
	sleep 2
	local far_past_mtime=$(date -d "May 29 1953" +%s)
	local far_past_atime=$(date -d "Dec 17 1903" +%s)

	touch -m -d @$far_past_mtime $DIR1/$tfile
	touch -a -d @$far_past_atime $DIR1/$tfile

	for (( i=0; i < 2; i++ )) ; do
		local timestamps=$(stat -c "%X %Y" $DIR1/$tfile)
		[[ "$timestamps" == "$far_past_atime $far_past_mtime" ]] ||
			error "atime or mtime set incorrectly"

		cancel_lru_locks $OSC
		(( $i > 0 )) || echo "repeat after cancel_lru_locks"
	done
}
run_test 39m "test atime and mtime before 1970"

test_39n() { # LU-3832
	remote_mds_nodsh && skip "remote MDS with nodsh"

	local atime_diff=$(do_facet $SINGLEMDS \
		$LCTL get_param -n mdd.*MDT0000*.atime_diff)
	local atime0
	local atime1
	local atime2

	do_facet $SINGLEMDS lctl set_param -n mdd.*MDT0000*.atime_diff=1

	rm -rf $DIR/$tfile
	dd if=/dev/zero of=$DIR/$tfile bs=4096 count=1 status=noxfer
	atime0=$(stat -c %X $DIR/$tfile)

	sleep 5
	$MULTIOP $DIR/$tfile oO_RDONLY:O_NOATIME:r4096c
	atime1=$(stat -c %X $DIR/$tfile)

	sleep 5
	cancel_lru_locks mdc
	cancel_lru_locks osc
	$MULTIOP $DIR/$tfile oO_RDONLY:O_NOATIME:r4096c
	atime2=$(stat -c %X $DIR/$tfile)

	do_facet $SINGLEMDS \
		lctl set_param -n mdd.*MDT0000*.atime_diff=$atime_diff

	(( "$atime0" == "$atime1" )) || error "atime0 $atime0 != atime1 $atime1"
	(( "$atime1" == "$atime2" )) || error "atime0 $atime0 != atime1 $atime1"
}
run_test 39n "check that O_NOATIME is honored"

test_39o() {
	TESTDIR=$DIR/$tdir/$tfile
	[ -e $TESTDIR ] && rm -rf $TESTDIR
	mkdir -p $TESTDIR
	cd $TESTDIR
	links1=2
	ls
	mkdir a b
	ls
	links2=$(stat -c %h .)
	[ $(($links1 + 2)) != $links2 ] &&
		error "wrong links count $(($links1 + 2)) != $links2"
	rmdir b
	links3=$(stat -c %h .)
	[ $(($links1 + 1)) != $links3 ] &&
		error "wrong links count $links1 != $links3"
	return 0
}
run_test 39o "directory cached attributes updated after create"

test_39p() {
	[[ $MDSCOUNT -lt 2 ]] && skip_env "needs >= 2 MDTs"

	local MDTIDX=1
	TESTDIR=$DIR/$tdir/$tdir
	[ -e $TESTDIR ] && rm -rf $TESTDIR
	test_mkdir -p $TESTDIR
	cd $TESTDIR
	links1=2
	ls
	test_mkdir -i $MDTIDX $TESTDIR/remote_dir1
	test_mkdir -i $MDTIDX $TESTDIR/remote_dir2
	ls
	links2=$(stat -c %h .)
	[ $(($links1 + 2)) != $links2 ] &&
		error "wrong links count $(($links1 + 2)) != $links2"
	rmdir remote_dir2
	links3=$(stat -c %h .)
	[ $(($links1 + 1)) != $links3 ] &&
		error "wrong links count $links1 != $links3"
	return 0
}
run_test 39p "remote directory cached attributes updated after create ========"

test_39r() {
	[ $OST1_VERSION -ge $(version_code 2.13.52) ] ||
		skip "no atime update on old OST"
	if [ "$ost1_FSTYPE" != ldiskfs ]; then
		skip_env "ldiskfs only test"
	fi

	local saved_adiff
	local ahost=$(facet_active_host ost1)
	saved_adiff=$(do_facet ost1 \
		lctl get_param -n obdfilter.*OST0000.atime_diff)
	stack_trap "do_facet ost1 \
		lctl set_param obdfilter.*.atime_diff=$saved_adiff"

	do_facet ost1 "lctl set_param obdfilter.*.atime_diff=5"

	$LFS setstripe -i 0 $DIR/$tfile
	dd if=/dev/zero of=$DIR/$tfile bs=4k count=1 ||
		error "can't write initial file"
	cancel_lru_locks osc

	# exceed atime_diff and access file
	sleep 10
	dd if=$DIR/$tfile of=/dev/null bs=4k count=1 ||
		error "can't udpate atime"

	# atime_cli value is in decimal
	local atime_cli=$(stat -c %X $DIR/$tfile)
	echo "client atime: $atime_cli"

	local ostdev=$(ostdevname 1)
	local fids=($($LFS getstripe $DIR/$tfile | grep 0x))
	local fid="${fids[3]}:${fids[2]}:0"
	local objpath=$(ost_fid2_objpath ost1 $fid)
	local cmd="debugfs -c -R \\\"stat $objpath\\\" $ostdev"

	# allow atime update to be written to device
	do_facet ost1 "$LCTL set_param -n osd*.*OST*.force_sync=1"
	echo "OST atime: $(do_facet ost1 "$cmd" |& grep atime)"

	# Give enough time for server to get updated. Until then
	# the value read is defaulted to "0x00000000:00000000"
	# Wait until atime read via debugfs is not equal to zero.
	# Max limit to wait is 30 seconds.
	wait_update_cond $ahost						\
		"$cmd |& awk -F'[: ]' '/atime:/ { print \\\$4 }'"	\
		"-gt" "0" 30 || error "atime on ost is still 0 after 30 seconds"
	# atime_ost value is in hex
	local atime_ost=$(do_facet ost1 "$cmd" |&
			  awk -F'[: ]' '/atime:/ { print $4 }')
	# debugfs returns atime in 0xNNNNNNNN:00000000 format
	# convert Hex to decimal before comparing
	local atime_ost_dec=$((atime_ost))

	# The test pass criteria is that the client time and server should
	# be same (2s gap accepted). This gap could arise due to VFS updating
	# the atime after the read(dd), stat and the updated time from the
	# inode
	(( $((atime_cli - atime_ost_dec)) <= 2 )) ||
		error "atime on client $atime_cli != ost $atime_ost_dec"
}
run_test 39r "lazy atime update on OST"

test_39q() { # LU-8041
	local testdir=$DIR/$tdir
	mkdir -p $testdir
	multiop_bg_pause $testdir D_c || error "multiop failed"
	local multipid=$!
	cancel_lru_locks mdc
	kill -USR1 $multipid
	local atime=$(stat -c %X $testdir)
	[ "$atime" -ne 0 ] || error "atime is zero"
}
run_test 39q "close won't zero out atime"

test_39s() {
	local atime0
	local atime1
	local atime2
	local atime3
	local atime4

	umount_client $MOUNT
	mount_client $MOUNT relatime

	dd if=/dev/zero of=$DIR/$tfile bs=4096 count=1 status=noxfer conv=fsync
	atime0=$(stat -c %X $DIR/$tfile)

	# First read updates atime
	sleep 1
	cat $DIR/$tfile >/dev/null
	atime1=$(stat -c %X $DIR/$tfile) # (atime = atime0 + 1)

	# Next reads do not update atime
	sleep 1
	cat $DIR/$tfile >/dev/null
	atime2=$(stat -c %X $DIR/$tfile) # (atime = atime0 + 1)

	# If mtime is greater than atime, atime is updated
	sleep 1
	touch -m $DIR/$tfile # (mtime = now)
	sleep 1
	cat $DIR/$tfile >/dev/null # (atime is updated because atime < mtime)
	atime3=$(stat -c %X $DIR/$tfile) # (atime = mtime = atime0 + 3)

	# Next reads do not update atime
	sleep 1
	cat $DIR/$tfile >/dev/null
	atime4=$(stat -c %X $DIR/$tfile)

	# Remount the client to clear 'relatime' option
	remount_client $MOUNT

	(( atime0 < atime1 )) ||
		error "atime $atime0 should be smaller than $atime1"
	(( atime1 == atime2 )) ||
		error "atime $atime1 was updated to $atime2"
	(( atime1 < atime3 )) || error "atime1 $atime1 != atime3 $atime3"
	(( atime3 == atime4 )) || error "atime3 $atime3 != atime4 $atime4"
}
run_test 39s "relatime is supported"

test_39u() {
	touch $DIR/$tfile
	stack_trap "rm -f $DIR/$tfile"
	sleep 2
	dd if=/dev/zero of=$DIR/$tfile bs=1M count=1 conv=notrunc ||
		error "dd failed"

	#define OBD_FAIL_LLITE_STAT_RACE1			0x1434
	$LCTL set_param fail_loc=0x80001434

	local mtimes=($(stat -c "%Y" $DIR/$tfile &
			sleep 1; stat -c "%Y" $DIR/$tfile; wait))

	(( ${mtimes[0]} == ${mtimes[1]} )) ||
		error "mtime mismatch ${mtimes[0]} != ${mtimes[1]}"
}
run_test 39u "stat race"

test_40() {
	dd if=/dev/zero of=$DIR/$tfile bs=4096 count=1
	$RUNAS $OPENFILE -f O_WRONLY:O_TRUNC $DIR/$tfile &&
		error "openfile O_WRONLY:O_TRUNC $tfile failed"
	$CHECKSTAT -t file -s 4096 $DIR/$tfile ||
		error "$tfile is not 4096 bytes in size"
}
run_test 40 "failed open(O_TRUNC) doesn't truncate ============="

test_41() {
	# bug 1553
	small_write $DIR/f41 18
}
run_test 41 "test small file write + fstat ====================="

count_ost_writes() {
	lctl get_param -n ${OSC}.*.stats |
		awk -vwrites=0 '/ost_write/ { writes += $2 } \
			END { printf("%0.0f", writes) }'
}

# decent default
WRITEBACK_SAVE=500
DIRTY_RATIO_SAVE=40
MAX_DIRTY_RATIO=50
BG_DIRTY_RATIO_SAVE=10
MAX_BG_DIRTY_RATIO=25

start_writeback() {
	sysctl -w vm.dirty_writeback_centisecs=$WRITEBACK_SAVE
	sysctl -w vm.dirty_background_ratio=$BG_DIRTY_RATIO_SAVE
	sysctl -w vm.dirty_ratio=$DIRTY_RATIO_SAVE
}

stop_writeback() {
	# setup the trap first, so someone cannot exit the test at the
	# exact wrong time and mess up a machine
	stack_trap start_writeback

	# save and zero /proc/sys/vm/dirty_writeback_centisecs
	WRITEBACK_SAVE=$(sysctl -n vm.dirty_writeback_centisecs)
	sysctl -w vm.dirty_writeback_centisecs=0
	sysctl -w vm.dirty_writeback_centisecs=0
	# save and increase /proc/sys/vm/dirty_ratio
	DIRTY_RATIO_SAVE=$(sysctl -n vm.dirty_ratio)
	sysctl -w vm.dirty_ratio=$MAX_DIRTY_RATIO
	# save and increase /proc/sys/vm/dirty_background_ratio
	BG_DIRTY_RATIO_SAVE=$(sysctl -n vm.dirty_background_ratio)
	sysctl -w vm.dirty_background_ratio=$MAX_BG_DIRTY_RATIO

	# disable sync_on_close if enabled
	local save="$($LCTL get_param llite.*.sync_on_close)"
	[[ ! $save =~ "=1" ]] || {
		stack_trap "$LCTL set_param $save"
		$LCTL set_param llite.*.sync_on_close=0
	}
}

# ensure that all stripes have some grant before we test client-side cache
setup_test42() {
	for ((i=1; i <= $OSTCOUNT; i++)); do
		local file=$DIR/$tfile-$i

		dd if=/dev/zero of=$file bs=4k count=1
		rm -f $file
	done
}

# Tests 42* verify that our behaviour is correct WRT caching, file closure,
# file truncation, and file removal.
test_42a() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	setup_test42
	cancel_lru_locks $OSC
	stop_writeback
	sync; sleep 1; sync # just to be safe
	BEFOREWRITES=`count_ost_writes`
        lctl get_param -n osc.*[oO][sS][cC][_-]*.cur_grant_bytes | grep "[0-9]"
        dd if=/dev/zero of=$DIR/f42a bs=1024 count=100
	AFTERWRITES=`count_ost_writes`
	[ $BEFOREWRITES -eq $AFTERWRITES ] || \
		error "$BEFOREWRITES < $AFTERWRITES"
	start_writeback
}
run_test 42a "ensure that we don't flush on close"

test_42b() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	setup_test42
	cancel_lru_locks $OSC
	stop_writeback
	sync
	dd if=/dev/zero of=$DIR/f42b bs=1024 count=100
	BEFOREWRITES=$(count_ost_writes)
	unlink $DIR/f42b || error "unlink $DIR/f42b: $?"
	AFTERWRITES=$(count_ost_writes)
	if [[ $BEFOREWRITES -lt $AFTERWRITES ]]; then
		error "$BEFOREWRITES < $AFTERWRITES on unlink"
	fi
	BEFOREWRITES=$(count_ost_writes)
	sync || error "sync: $?"
	AFTERWRITES=$(count_ost_writes)
	if [[ $BEFOREWRITES -lt $AFTERWRITES ]]; then
		error "$BEFOREWRITES < $AFTERWRITES on sync"
	fi
	dmesg | grep 'error from obd_brw_async' && error 'error writing back'
	start_writeback
	return 0
}
run_test 42b "test destroy of file with cached dirty data ======"

# if these tests just want to test the effect of truncation,
# they have to be very careful.  consider:
# - the first open gets a {0,EOF}PR lock
# - the first write conflicts and gets a {0, count-1}PW
# - the rest of the writes are under {count,EOF}PW
# - the open for truncate tries to match a {0,EOF}PR
#   for the filesize and cancels the PWs.
# any number of fixes (don't get {0,EOF} on open, match
# composite locks, do smarter file size management) fix
# this, but for now we want these tests to verify that
# the cancellation with truncate intent works, so we
# start the file with a full-file pw lock to match against
# until the truncate.
trunc_test() {
	test=$1
	file=$DIR/$test
	offset=$2
	cancel_lru_locks $OSC
	stop_writeback
	# prime the file with 0,EOF PW to match
	touch $file
        $TRUNCATE $file 0
        sync; sync
	# now the real test..
	dd if=/dev/zero of=$file bs=1024 count=100
	BEFOREWRITES=`count_ost_writes`
	$TRUNCATE $file $offset
	cancel_lru_locks $OSC
	AFTERWRITES=`count_ost_writes`
	start_writeback
}

test_42c() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	trunc_test 42c 1024
	[ $BEFOREWRITES -eq $AFTERWRITES ] &&
		error "beforewrites $BEFOREWRITES == afterwrites $AFTERWRITES on truncate"
	rm $file
}
run_test 42c "test partial truncate of file with cached dirty data"

test_42d() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	local olddebug="$($LCTL get_param -n debug 2> /dev/null)"
	stack_trap "$LCTL set_param -n debug='$olddebug'" EXIT
	$LCTL set_param debug=+cache

	trunc_test 42d 0
	[ $BEFOREWRITES -eq $AFTERWRITES ] ||
		error "beforewrites $BEFOREWRITES != afterwrites $AFTERWRITES on truncate"
	rm $file
}
run_test 42d "test complete truncate of file with cached dirty data"

test_42e() { # bug22074
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	local TDIR=$DIR/${tdir}e
	local pages=16 # hardcoded 16 pages, don't change it.
	local files=$((OSTCOUNT * 500)) # hopefully 500 files on each OST
	local proc_osc0="osc.${FSNAME}-OST0000-osc-[^MDT]*"
	local max_dirty_mb
	local warmup_files

	test_mkdir $DIR/${tdir}e
	$LFS setstripe -c 1 $TDIR
	createmany -o $TDIR/f $files

	max_dirty_mb=$($LCTL get_param -n $proc_osc0/max_dirty_mb)

	# we assume that with $OSTCOUNT files, at least one of them will
	# be allocated on OST0.
	warmup_files=$((OSTCOUNT * max_dirty_mb))
	createmany -o $TDIR/w $warmup_files

	# write a large amount of data into one file and sync, to get good
	# avail_grant number from OST.
	for ((i=0; i<$warmup_files; i++)); do
		idx=$($LFS getstripe -i $TDIR/w$i)
		[ $idx -ne 0 ] && continue
		dd if=/dev/zero of=$TDIR/w$i bs="$max_dirty_mb"M count=1
		break
	done
	[[ $i -gt $warmup_files ]] && error "OST0 is still cold"
	sync
	$LCTL get_param $proc_osc0/cur_dirty_bytes
	$LCTL get_param $proc_osc0/cur_grant_bytes

	# create as much dirty pages as we can while not to trigger the actual
	# RPCs directly. but depends on the env, VFS may trigger flush during this
	# period, hopefully we are good.
	for ((i=0; i<$warmup_files; i++)); do
		idx=$($LFS getstripe -i $TDIR/w$i)
		[ $idx -ne 0 ] && continue
		dd if=/dev/zero of=$TDIR/w$i bs=1M count=1 2>/dev/null
	done
	$LCTL get_param $proc_osc0/cur_dirty_bytes
	$LCTL get_param $proc_osc0/cur_grant_bytes

	# perform the real test
	$LCTL set_param $proc_osc0/rpc_stats 0
	for ((;i<$files; i++)); do
		[ $($LFS getstripe -i $TDIR/f$i) -eq 0 ] || continue
		dd if=/dev/zero of=$TDIR/f$i bs=$PAGE_SIZE count=$pages 2>/dev/null
	done
	sync
	$LCTL get_param $proc_osc0/rpc_stats

        local percent=0
        local have_ppr=false
        $LCTL get_param $proc_osc0/rpc_stats |
                while read PPR RRPC RPCT RCUM BAR WRPC WPCT WCUM; do
                        # skip lines until we are at the RPC histogram data
                        [ "$PPR" == "pages" ] && have_ppr=true && continue
                        $have_ppr || continue

                        # we only want the percent stat for < 16 pages
			[[ $(echo $PPR | tr -d ':') -ge $pages ]] && break

                        percent=$((percent + WPCT))
			if [[ $percent -gt 15 ]]; then
                                error "less than 16-pages write RPCs" \
                                      "$percent% > 15%"
                                break
                        fi
                done
        rm -rf $TDIR
}
run_test 42e "verify sub-RPC writes are not done synchronously"

test_43A() { # was test_43
	test_mkdir $DIR/$tdir
	cp -p /bin/ls $DIR/$tdir/$tfile
	$MULTIOP $DIR/$tdir/$tfile Ow_c &
	pid=$!
	# give multiop a chance to open
	sleep 1

	$DIR/$tdir/$tfile && error "execute $DIR/$tdir/$tfile succeeded" || true
	kill -USR1 $pid
	# Wait for multiop to exit
	wait $pid
}
run_test 43A "execution of file opened for write should return -ETXTBSY"

test_43a() {
	test_mkdir $DIR/$tdir
	cp -p $(which sleep) $DIR/$tdir/sleep || error "can't copy"
	$DIR/$tdir/sleep 60 &
	SLEEP_PID=$!
	# Make sure exec of $tdir/sleep wins race with truncate
	sleep 1
	$MULTIOP $DIR/$tdir/sleep Oc && error "expected error, got success"
	kill $SLEEP_PID
}
run_test 43a "open(RDWR) of file being executed should return -ETXTBSY"

test_43b() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	test_mkdir $DIR/$tdir
	cp -p $(which sleep) $DIR/$tdir/sleep || error "can't copy"
	$DIR/$tdir/sleep 60 &
	SLEEP_PID=$!
	# Make sure exec of $tdir/sleep wins race with truncate
	sleep 1
	$TRUNCATE $DIR/$tdir/sleep 0 && error "expected error, got success"
	kill $SLEEP_PID
}
run_test 43b "truncate of file being executed should return -ETXTBSY"

test_43c() {
	local testdir="$DIR/$tdir"
	test_mkdir $testdir
	cp $SHELL $testdir/
	( cd $(dirname $SHELL) && md5sum $(basename $SHELL) ) |
		( cd $testdir && md5sum -c )
}
run_test 43c "md5sum of copy into lustre"

test_44A() { # was test_44
	[[ $OSTCOUNT -lt 2 ]] && skip_env "needs >= 2 OSTs"

	dd if=/dev/zero of=$DIR/f1 bs=4k count=1 seek=1023
	dd if=$DIR/f1 bs=4k count=1 > /dev/null
}
run_test 44A "zero length read from a sparse stripe"

test_44a() {
	local nstripe=$($LFS getstripe -c -d $DIR)
	[ -z "$nstripe" ] && skip "can't get stripe info"
	[[ $nstripe -gt $OSTCOUNT ]] &&
		skip "Wrong default stripe_count: $nstripe OSTCOUNT: $OSTCOUNT"

	local stride=$($LFS getstripe -S -d $DIR)
	if [[ $nstripe -eq 0 || $nstripe -eq -1 ]]; then
		nstripe=$($LFS df -o $DIR | wc -l)
	fi

	OFFSETS="0 $((stride/2)) $((stride-1))"
	for offset in $OFFSETS; do
		for i in $(seq 0 $((nstripe-1))); do
			local GLOBALOFFSETS=""
			# size in Bytes
			local size=$((((i + 2 * $nstripe )*$stride + $offset)))
			local myfn=$DIR/d44a-$size
			echo "--------writing $myfn at $size"
			ll_sparseness_write $myfn $size ||
				error "ll_sparseness_write"
			GLOBALOFFSETS="$GLOBALOFFSETS $size"
			ll_sparseness_verify $myfn $GLOBALOFFSETS ||
				error "ll_sparseness_verify $GLOBALOFFSETS"

			for j in $(seq 0 $((nstripe-1))); do
				# size in Bytes
				size=$((((j + $nstripe )*$stride + $offset)))
				ll_sparseness_write $myfn $size ||
					error "ll_sparseness_write"
				GLOBALOFFSETS="$GLOBALOFFSETS $size"
			done
			ll_sparseness_verify $myfn $GLOBALOFFSETS ||
				error "ll_sparseness_verify $GLOBALOFFSETS"
			rm -f $myfn
		done
	done
}
run_test 44a "test sparse pwrite ==============================="

test_44b() {
	(( $OST1_VERSION >= $(version_code 2.15.61.137) )) ||
		skip "Need OST >= 2.15.61.137 for large object handling"

	$LFS setstripe -c 1 $DIR/$tfile || error "setstripe failed"
	local off=$((2**32*4096-8192))
	dd if=/dev/zero of=$DIR/$tfile bs=1 count=1 seek=$off conv=notrunc ||
		error "dd failed"
	cancel_lru_locks osc
	$CHECKSTAT -s $((2**32*4096-8192+1)) $DIR/$tfile || error "wrong size"
}
run_test 44b "write one byte at offset 0xfffffffe000"

test_44c() {
	(( $OST1_VERSION >= $(version_code 2.15.61.137) )) ||
		skip "Need OST >= 2.15.61.137 for large object handling"

	local osc_tgt="$FSNAME-OST0000-osc-$($LFS getname -i $DIR)"
	local max_object_bytes=$(import_param $osc_tgt max_object_bytes)

	$LFS setstripe -c 1 $DIR/$tfile || error "setstripe failed"

	dd if=/dev/zero of=$DIR/$tfile conv=notrunc bs=1 count=1 \
		seek=$((max_object_bytes - 1)) || error "dd failed"
	cancel_lru_locks osc
	$CHECKSTAT -s $max_object_bytes $DIR/$tfile || error "wrong size"
}
run_test 44c "write 1 byte at max_object_bytes - 1 offset"

test_44d() {
	(( $OST1_VERSION >= $(version_code 2.15.61.137) )) ||
		skip "Need OST >= 2.15.61.137 for large object handling"

	local osc_tgt="$FSNAME-OST0000-osc-$($LFS getname -i $DIR)"
	local max_object_bytes=$(import_param $osc_tgt max_object_bytes)

	$LFS setstripe -c 2 $DIR/$tfile || error "setstripe failed"

	local stripe_size=$($LFS getstripe -S $DIR/$tfile)
	local off=$((max_object_bytes & ~(stripe_size - 1)))

	$TRUNCATE $DIR/$tfile $off
	dd if=/dev/zero of=$DIR/$tfile bs=1 count=1 seek=$off
	local rc1=$?
	dd if=/dev/zero of=$DIR/$tfile oflag=append conv=notrunc bs=1 count=1 \
		seek=$off
	local rc2=$?
	[[ $rc1 -eq 0 && $rc2 -eq 0 ]] || error "one of dd commands failed"
}
run_test 44d "if write at position fails (EFBIG), so should do append"

# write file until maximal size is reached
max_file_size() {
	local file=$1

	off=1
	minoff=1
	while true; do
		echo a | dd of=$1 bs=1 count=1 conv=notrunc seek=$off status=progress \
			2>/dev/null
		[[ $? -ne 0 ]] && break
		minoff=$off
		off=$(echo "$off * 2" | bc)
	done
	maxoff=$off
	minoff_1=$(echo $off + 1 | bc)
	while [[ maxoff -ne minoff_1 ]]; do
		off=$(echo "($maxoff + $minoff) / 2" | bc)
		echo a | dd of=$1 bs=1 count=1 conv=notrunc seek=$off status=progress \
			2>/dev/null
		[[ $? -eq 0 ]] && minoff=$off || maxoff=$off
		minoff_1=$(echo $off + 1 | bc)
	done
	stat -c %s $file
}

test_44e_write_read()
{
	local ifile=$1
	local ofile=$2
	local stripe_count=$3
	local stripe_size=$($LFS getstripe -S $ofile)
	local file_size=$(max_file_size $ofile)
	local write_count=$((stripe_count * stripe_size))
	local offset=$((file_size - write_count))

	dd if=/dev/urandom of=$ifile bs=$write_count count=1 ||
		error "failed to write random data"

	dd if=$ifile of=$ofile bs=$write_count count=1 oflag=seek_bytes \
		seek=$offset conv=notrunc || error "dd failed"
	cancel_lru_locks osc
	cmp $ifile $ofile -i 0:$offset -n $write_count || error "cmp failed"
}

test_44e() {
	(( $OST1_VERSION >= $(version_code 2.15.61.137) )) ||
		    skip "Need OST >= 2.15.61.137 for large object handling"

	local TF="$(mktemp --tmpdir -u $tfile.XXXXXX)"

	$LFS setstripe -S 1M -c $OSTCOUNT $DIR/$tfile ||
		error "lfs setstripe -S 1M -c $OSTCOUNT failed"
	test_44e_write_read $TF $DIR/$tfile $OSTCOUNT
	rm -f $DIR/$tfile
	rm -f $TF

	$LFS setstripe -S 1M -c $OSTCOUNT -C $((OSTCOUNT * 2)) $DIR/$tfile ||
		error "lfs setstripe -S 1M -c $OSTCOUNT -C [* 2] failed"
	test_44e_write_read $TF $DIR/$tfile $((OSTCOUNT * 2))

	rm -f $DIR/$tfile
	rm -f $TF
}
run_test 44e "write and read maximal stripes"

test_44f() {
	[ "$FSTYPE" != "zfs" ] ||
		skip "ORI-366/LU-1941: FIEMAP unimplemented on ZFS"

	stack_trap "rm -f $DIR/$tfile-*"
	local i
	# required space: NUMFILES_44f * 20Mb
	local NUMFILES_44f=${NUMFILES_44f:-5}
	[[ "$SLOW" == "yes" ]] && NUMFILES_44f=50

	for (( i=0; i<NUMFILES_44f; i++ )); do
		multiop $DIR/$tfile-$i \
			Ow10485760Z10485760w10485760Ic ||
			error "multiop failed"
	done
}
run_test 44f "Check fiemap for sparse files"

test_44g() {
	# max stripe size is 4G - 64K
	$LFS setstripe -C 4 -S 4194240k $DIR/$tfile
	dd if=/dev/zero of=$DIR/$tfile conv=notrunc bs=64k count=1 \
	   seek=$((65535 * 3 + 65533))

	$LFS setstripe -c 2 -S 2g $DIR/$tfile-2
	dd if=/dev/zero of=$DIR/$tfile-2 conv=notrunc bs=64k count=1 \
	   seek=65535

	cancel_lru_locks osc

	$CHECKSTAT -s $(((65535 * 3 + 65534) * 65536)) $DIR/$tfile ||
	    error "wrong $DIR/$tfile size"
	$CHECKSTAT -s 4294967296 $DIR/$tfile-2 ||
	    error "wrong $DIR/$tfile-2 size"
}
run_test 44g "test overflow in lov_stripe_size"

dirty_osc_total() {
	tot=0
	for d in `lctl get_param -n ${OSC}.*.cur_dirty_bytes`; do
		tot=$(($tot + $d))
	done
	echo $tot
}
do_dirty_record() {
	before=`dirty_osc_total`
	echo executing "\"$*\""
	eval $*
	after=`dirty_osc_total`
	echo before $before, after $after
}
test_45() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	f="$DIR/f45"
	# Obtain grants from OST if it supports it
	echo blah > ${f}_grant
	stop_writeback
	sync

	# cur_dirty_bytes is related and modified by the OSC cache granting
	# code. It is possible for the grants to be freed during async IO
	# completion resulting in 0 vs 0 comparisons for truncates and sync.
	# Since it can't be reliably proven that the operation did lower the
	# count, the comparisons are changed to >= (ge) rather than > (gt).
	#
	# N.B. This whole test seems flawed as the process doesn't hold file
	# descriptors, syscalls are not explicit, and dirty data is subject to
	# async changes outside of the MM subsystem. Some consideration should
	# be given to removing/rewriting this test.
	do_dirty_record "echo blah > $f"
	(( before == after )) && error "write wasn't cached"
	do_dirty_record "> $f"
	(( before >= after )) || error "truncate didn't lower dirty count"
	do_dirty_record "echo blah > $f"
	(( before == after )) && error "write wasn't cached"
	do_dirty_record "sync"
	(( after == 0 )) || error "writeback didn't zero dirty count"
	do_dirty_record "echo blah > $f"
	(( before == after )) && error "write wasn't cached"
	do_dirty_record "cancel_lru_locks osc"
	(( before >= after )) ||
		error "lock cancellation didn't lower dirty count"
	start_writeback
}
run_test 45 "osc io page accounting"

# in a 2 stripe file (lov.sh), page 1023 maps to page 511 in its object.  this
# test tickles a bug where re-dirtying a page was failing to be mapped to the
# objects offset and an assert hit when an rpc was built with 1023's mapped
# offset 511 and 511's raw 511 offset. it also found general redirtying bugs.
test_46() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	f="$DIR/f46"
	stop_writeback
	sync
	dd if=/dev/zero of=$f bs=$PAGE_SIZE seek=511 count=1
	sync
	dd conv=notrunc if=/dev/zero of=$f bs=$PAGE_SIZE seek=1023 count=1
	dd conv=notrunc if=/dev/zero of=$f bs=$PAGE_SIZE seek=511 count=1
	sync
	start_writeback
}
run_test 46 "dirtying a previously written page ================"

# test_47 is removed "Device nodes check" is moved to test_28

test_48a() { # bug 2399
	[ "$mds1_FSTYPE" = "zfs" ] &&
	[ $MDS1_VERSION -lt $(version_code 2.3.63) ] &&
		skip "MDS prior to 2.3.63 handle ZFS dir .. incorrectly"

	test_mkdir $DIR/$tdir
	cd $DIR/$tdir
	mv $DIR/$tdir $DIR/$tdir.new || error "move directory failed"
	test_mkdir $DIR/$tdir
	touch foo || error "'touch foo' failed after recreating cwd"
	test_mkdir bar
	touch .foo || error "'touch .foo' failed after recreating cwd"
	test_mkdir .bar
	ls . > /dev/null || error "'ls .' failed after recreating cwd"
	ls .. > /dev/null || error "'ls ..' failed after removing cwd"
	cd . || error "'cd .' failed after recreating cwd"
	mkdir . && error "'mkdir .' worked after recreating cwd"
	rmdir . && error "'rmdir .' worked after recreating cwd"
	ln -s . baz || error "'ln -s .' failed after recreating cwd"
	cd .. || error "'cd ..' failed after recreating cwd"
}
run_test 48a "Access renamed working dir (should return errors)="

test_48b() { # bug 2399
	rm -rf $DIR/$tdir
	test_mkdir $DIR/$tdir
	cd $DIR/$tdir
	rmdir $DIR/$tdir || error "remove cwd $DIR/$tdir failed"
	touch foo && error "'touch foo' worked after removing cwd"
	mkdir foo && error "'mkdir foo' worked after removing cwd"
	touch .foo && error "'touch .foo' worked after removing cwd"
	mkdir .foo && error "'mkdir .foo' worked after removing cwd"
	ls . > /dev/null && error "'ls .' worked after removing cwd"
	ls .. > /dev/null || error "'ls ..' failed after removing cwd"
	mkdir . && error "'mkdir .' worked after removing cwd"
	rmdir . && error "'rmdir .' worked after removing cwd"
	ln -s . foo && error "'ln -s .' worked after removing cwd"
	cd .. || echo "'cd ..' failed after removing cwd `pwd`"  #bug 3517
}
run_test 48b "Access removed working dir (should return errors)="

test_48c() { # bug 2350
	#lctl set_param debug=-1
	#set -vx
	rm -rf $DIR/$tdir
	test_mkdir -p $DIR/$tdir/dir
	cd $DIR/$tdir/dir
	$TRACE rmdir $DIR/$tdir/dir || error "remove cwd $DIR/$tdir/dir failed"
	$TRACE touch foo && error "touch foo worked after removing cwd"
	$TRACE mkdir foo && error "'mkdir foo' worked after removing cwd"
	touch .foo && error "touch .foo worked after removing cwd"
	mkdir .foo && error "mkdir .foo worked after removing cwd"
	$TRACE ls . && error "'ls .' worked after removing cwd"
	$TRACE ls .. || error "'ls ..' failed after removing cwd"
	$TRACE mkdir . && error "'mkdir .' worked after removing cwd"
	$TRACE rmdir . && error "'rmdir .' worked after removing cwd"
	$TRACE ln -s . foo && error "'ln -s .' worked after removing cwd"
	$TRACE cd .. || echo "'cd ..' failed after removing cwd `pwd`" #bug 3415
}
run_test 48c "Access removed working subdir (should return errors)"

test_48d() { # bug 2350
	#lctl set_param debug=-1
	#set -vx
	rm -rf $DIR/$tdir
	test_mkdir -p $DIR/$tdir/dir
	cd $DIR/$tdir/dir
	$TRACE rmdir $DIR/$tdir/dir || error "remove cwd $DIR/$tdir/dir failed"
	$TRACE rmdir $DIR/$tdir || error "remove parent $DIR/$tdir failed"
	$TRACE touch foo && error "'touch foo' worked after removing parent"
	$TRACE mkdir foo && error "mkdir foo worked after removing parent"
	touch .foo && error "'touch .foo' worked after removing parent"
	mkdir .foo && error "mkdir .foo worked after removing parent"
	$TRACE ls . && error "'ls .' worked after removing parent"
	$TRACE ls .. && error "'ls ..' worked after removing parent"
	$TRACE mkdir . && error "'mkdir .' worked after removing parent"
	$TRACE rmdir . && error "'rmdir .' worked after removing parent"
	$TRACE ln -s . foo && error "'ln -s .' worked after removing parent"
	true
}
run_test 48d "Access removed parent subdir (should return errors)"

test_48e() { # bug 4134
	#lctl set_param debug=-1
	#set -vx
	rm -rf $DIR/$tdir
	test_mkdir -p $DIR/$tdir/dir
	cd $DIR/$tdir/dir
	$TRACE rmdir $DIR/$tdir/dir || error "remove cwd $DIR/$tdir/dir failed"
	$TRACE rmdir $DIR/$tdir || error "remove parent $DIR/$tdir failed"
	$TRACE touch $DIR/$tdir || error "'touch $DIR/$tdir' failed"
	$TRACE chmod +x $DIR/$tdir || error "'chmod +x $DIR/$tdir' failed"
	# On a buggy kernel addition of "touch foo" after cd .. will
	# produce kernel oops in lookup_hash_it
	touch ../foo && error "'cd ..' worked after recreate parent"
	cd $DIR
	$TRACE rm $DIR/$tdir || error "rm '$DIR/$tdir' failed"
}
run_test 48e "Access to recreated parent subdir (should return errors)"

test_48f() {
	[[ $MDS1_VERSION -ge $(version_code 2.13.55) ]] ||
		skip "need MDS >= 2.13.55"
	[[ $MDSCOUNT -ge 2 ]] || skip "needs >= 2 MDTs"
	[[ "$(facet_host mds1)" != "$(facet_host mds2)" ]] ||
		skip "needs different host for mdt1 mdt2"
	[[ $(facet_fstype mds1) == ldiskfs ]] || skip "ldiskfs only"

	$LFS mkdir -i0 $DIR/$tdir
	$LFS mkdir -i 1 $DIR/$tdir/sub1 $DIR/$tdir/sub2 $DIR/$tdir/sub3

	for d in sub1 sub2 sub3; do
		#define OBD_FAIL_OSD_REF_DEL	0x19c
		do_facet mds1 $LCTL set_param fail_loc=0x8000019c
		rm -rf $DIR/$tdir/$d && error "rm $d should fail"
	done

	rm -d --interactive=never $DIR/$tdir || error "rm $tdir fail"
}
run_test 48f "non-zero nlink dir unlink won't LBUG()"

test_49a() { # LU-1030 - was test_49
	[[ $PARALLEL == "yes" ]] && skip "skip parallel run"
	remote_ost_nodsh && skip "remote OST with nodsh"

	# get ost1 size - $FSNAME-OST0000
	ost1_size=$($LFS df --ost=0 --output btotal)
	# write 800M at maximum
	(( $ost1_size < 2 )) && ost1_size=2
	(( $ost1_size > 819200 )) && ost1_size=819200

	$LFS setstripe -c 1 -i 0 $DIR/$tfile
	dd if=/dev/zero of=$DIR/$tfile bs=4k count=$((ost1_size >> 2)) &
	local dd_pid=$!

	# change max_pages_per_rpc while writing the file
	local osc1_mppc=osc.$(get_osc_import_name client ost1).max_pages_per_rpc
	local orig_mppc=$($LCTL get_param -n $osc1_mppc)
	# loop until dd process exits
	while ps ax -opid | grep -wq $dd_pid; do
		$LCTL set_param $osc1_mppc=$((RANDOM % 256 + 1))
		sleep $((RANDOM % 5 + 1))
	done
	# restore original max_pages_per_rpc
	$LCTL set_param $osc1_mppc=$orig_mppc
	rm $DIR/$tfile || error "rm $DIR/$tfile failed"
}
run_test 49a "Change max_pages_per_rpc won't break osc extent"

test_49b() {
	local tgt="$FSNAME-OST0000-osc-*"
	local max_pages_per_rpc="osc.$tgt.max_pages_per_rpc"
	local max_mb_per_rpc_read="osc.$tgt.max_mb_per_rpc_read"
	local max_mb_per_rpc_write="osc.$tgt.max_mb_per_rpc_write"

	local old_brw=$(import_param "$tgt" max_brw_size)
	local old_pages=$($LCTL get_param -n "$max_mb_per_rpc_read")
	stack_trap "$LCTL set_param $max_mb_per_rpc_read=$old_pages"
	local old_pages=$($LCTL get_param -n "$max_mb_per_rpc_write")
	stack_trap "$LCTL set_param $max_mb_per_rpc_write=$old_pages"

	local expect="1"
	$LCTL set_param "$max_pages_per_rpc=1M"
	local actual=$($LCTL get_param -n "$max_mb_per_rpc_read")
	[[ "$expect" == "$actual" ]] ||
		error "wrong max_mb_per_rpc_read: $expect != $actual"
	local actual=$($LCTL get_param -n "$max_mb_per_rpc_write")
	[[ "$expect" == "$actual" ]] ||
		error "wrong max_mb_per_rpc_write: $expect != $actual"

	if [ "$ost1_FSTYPE" == ldiskfs ]; then
		expect="0.500"
		$LCTL set_param "$max_pages_per_rpc=512K"
		actual=$($LCTL get_param -n "$max_mb_per_rpc_read")
		[[ "$expect" == "$actual" ]] ||
			error "wrong max_mb_per_rpc_read: $expect != $actual"
		actual=$($LCTL get_param -n "$max_mb_per_rpc_write")
		[[ "$expect" == "$actual" ]] ||
			error "wrong max_mb_per_rpc_write: $expect != $actual"

		expect="3.500"
		$LCTL set_param "$max_pages_per_rpc=3.5M"
		actual=$($LCTL get_param -n "$max_mb_per_rpc_read")
		[[ "$expect" == "$actual" ]] ||
			error "wrong max_mb_per_rpc_read: $expect != $actual"
		actual=$($LCTL get_param -n "$max_mb_per_rpc_write")
		[[ "$expect" == "$actual" ]] ||
			error "wrong max_mb_per_rpc_write: $expect != $actual"

		expect="4"
		$LCTL set_param "$max_pages_per_rpc=0.00390625G"
		actual=$($LCTL get_param -n "$max_mb_per_rpc_read")
		[[ "$expect" == "$actual" ]] ||
			error "wrong max_mb_per_rpc_read: $expect != $actual"
		actual=$($LCTL get_param -n "$max_mb_per_rpc_write")
		[[ "$expect" == "$actual" ]] ||
			error "wrong max_mb_per_rpc_write: $expect != $actual"
	fi
}
run_test 49b "verify max_mb_per_rpc_read/write after setting max_pages_per_rpc"

test_49c() {
	local tgt="$FSNAME-OST0000-osc-*"
	local max_pages_per_rpc="osc.$tgt.max_pages_per_rpc"
	local max_mb_per_rpc_read="osc.$tgt.max_mb_per_rpc_read"
	local max_mb_per_rpc_write="osc.$tgt.max_mb_per_rpc_write"

	local old_brw=$(import_param "$tgt" max_brw_size)
	local old_pages=$($LCTL get_param -n "$max_mb_per_rpc_read")
	stack_trap "$LCTL set_param $max_mb_per_rpc_read=$old_pages"
	local old_pages=$($LCTL get_param -n "$max_mb_per_rpc_write")
	stack_trap "$LCTL set_param $max_mb_per_rpc_write=$old_pages"

	local expect="1"
	$LCTL set_param "$max_mb_per_rpc_read=1"
	local actual=$($LCTL get_param -n "$max_mb_per_rpc_read")
	[[ "$expect" == "$actual" ]] ||
		error "wrong max_mb_per_rpc_read: $expect != $actual"
	$LCTL set_param "$max_mb_per_rpc_write=1"
	local actual=$($LCTL get_param -n "$max_mb_per_rpc_write")
	[[ "$expect" == "$actual" ]] ||
		error "wrong max_mb_per_rpc_write: $expect != $actual"

	if [ "$ost1_FSTYPE" == ldiskfs ]; then
		local expect_r="2.500"
		local expect_w="0.500"
		$LCTL set_param "$max_mb_per_rpc_read=2560K"
		$LCTL set_param "$max_mb_per_rpc_write=0.5M"
		actual=$($LCTL get_param -n "$max_mb_per_rpc_read")
		[[ "$expect_r" == "$actual" ]] ||
			error "wrong max_mb_per_rpc_read: $expect_r != $actual"
		actual=$($LCTL get_param -n "$max_mb_per_rpc_write")
		[[ "$expect_w" == "$actual" ]] ||
			error "wrong max_mb_per_rpc_write: $expect_w != $actual"

		local expect_r="0.500"
		local expect_w="2.500"
		$LCTL set_param "$max_mb_per_rpc_read=0.5M"
		$LCTL set_param "$max_mb_per_rpc_write=2560K"
		actual=$($LCTL get_param -n "$max_mb_per_rpc_read")
		[[ "$expect_r" == "$actual" ]] ||
			error "wrong max_mb_per_rpc_read: $expect_r != $actual"
		actual=$($LCTL get_param -n "$max_mb_per_rpc_write")
		[[ "$expect_w" == "$actual" ]] ||
			error "wrong max_mb_per_rpc_write: $expect_w != $actual"
	fi
}
run_test 49c "verify max_mb_per_rpc_read/write"

test_50() {
	# bug 1485
	test_mkdir $DIR/$tdir
	cd $DIR/$tdir
	ls /proc/$$/cwd || error "ls /proc/$$/cwd failed"
}
run_test 50 "special situations: /proc symlinks  ==============="

test_51a() {	# was test_51
	# bug 1516 - create an empty entry right after ".." then split dir
	test_mkdir -c1 $DIR/$tdir
	touch $DIR/$tdir/foo
	$MCREATE $DIR/$tdir/bar
	rm $DIR/$tdir/foo
	createmany -m $DIR/$tdir/longfile 201
	FNUM=202
	while [[ $(ls -sd $DIR/$tdir | awk '{ print $1 }') -eq 4 ]]; do
		$MCREATE $DIR/$tdir/longfile$FNUM
		FNUM=$(($FNUM + 1))
		echo -n "+"
	done
	echo
	ls -l $DIR/$tdir > /dev/null || error "ls -l $DIR/$tdir failed"
}
run_test 51a "special situations: split htree with empty entry =="

cleanup_print_lfs_df () {
	$LFS df
	$LFS df -i
}

test_51b() {
	local dir=$DIR/$tdir
	local nrdirs=$((65536 + 100))

	# cleanup the directory
	rm -fr $dir

	mkdir_on_mdt -i $((RANDOM % MDSCOUNT)) $dir

	$LFS df
	$LFS df -i
	local mdtname=$(mdtname_from_index $($LFS getstripe -m $dir))
	local nproc=2 #$((lctl get_param -n mdc.$mdtname*.max_rpcs_in_flight/2))
	local numfree=$($LCTL get_param -n mdc.$mdtname*.filesfree)
	(( $numfree >= $nrdirs )) ||
		skip "not enough free inodes ($numfree) on $mdtname"

	# need to check free space for the directories as well
	local blkfree=$($LCTL get_param -n mdc.$mdtname*.kbytesavail)
	numfree=$(( blkfree / $(fs_inode_ksize) ))
	# round $nrdirs to an even multiple of the number of processes
	nrdirs=$((nrdirs / nproc * nproc))
	(( $numfree >= $nrdirs )) || skip "not enough blocks ($numfree)"

	stack_trap cleanup_print_lfs_df

	# create files
	local nrdirs_pp=$((nrdirs / nproc))
	for ((i = 0; i < $nproc; i++)); do
		stack_trap "unlinkmany -d $dir/d.$i. $nrdirs_pp || true"
		createmany -d $dir/d.$i. $nrdirs_pp &
	done
	wait || error "failed to create $nrdirs subdirs in $mdtname:/$dir"

	# really created :
	nrdirs=$(find $dir -maxdepth 1 | wc -l)

	# unlink all but ~100 subdirectories, then check it still works
	local left=$((100 / nproc * nproc))
	local delete=$((nrdirs - left))

	$LFS df
	$LFS df -i

	# for ldiskfs the nlink count should be 1, but this is OSD specific
	# and so this is listed for informational purposes only
	echo "nlink before: $(stat -c %h $dir), created before: $nrdirs"
	local delete_pp=$((delete / nproc))
	for ((i = 0; i < $nproc; i++)); do
		unlinkmany -d $dir/d.$i. $delete_pp &
	done
	wait || error "unlink of first $delete subdirs failed"

	echo "nlink between: $(stat -c %h $dir)"
	local found=$(ls -U $dir | wc -l)
	(( $found == $left )) ||
		error "can't find subdirs: found only $found, expected $left"

	local left_pp=$((left / nproc))
	for ((i = 0; i < $nproc; i++)); do
		unlinkmany -d $dir/d.$i. $delete_pp $left_pp &
	done
	wait || error "unlink of second $left subdirs failed"
	# regardless of whether the backing filesystem tracks nlink accurately
	# or not, the nlink count shouldn't be more than "." and ".." here
	local after=$(stat -c %h $dir)
	(( $after > 2 )) && error "nlink after: $after > 2" ||
		echo "nlink after: $after"
}
run_test 51b "exceed 64k subdirectory nlink limit on create, verify unlink"

test_51c() {
	(( MDSCOUNT > 1 )) || skip "needs >= 2 MDTs"
	local dir=$DIR/$tdir-c2
	local nrdirs=$((65536 * 2 + 2000))
	local nproc=$MDSCOUNT
	local mdtidx

	stack_trap cleanup_print_lfs_df

	$LFS mkdir -c 2 -H fnv_1a_64 $dir
	while read mdtidx rest; do
		local mdtname=$(mdtname_from_index $mdtidx)
		local numfree=$(lctl get_param -n mdc.$mdtname*.filesfree)
		local blkfree=$(lctl get_param -n mdc.$mdtname*.kbytesavail)

		((numfree > nrdirs/2 && blkfree/$(fs_inode_ksize) > nrdirs/2))||
			skip "not enough inodes or blocks for $mdtname"
	done < <($LFS getdirstripe $dir |
		 awk '{ if ($2 ~ /\[0x.*:0x.*:0x.*\]/) {  print $1; } }' )

	# round $nrdirs to an even multiple of the number of processes
	nrdirs=$((nrdirs / nproc * nproc))
	local nrdirs_pp=$((nrdirs / nproc))
	for ((i = 0; i < $nproc; i++)); do
		stack_trap "unlinkmany -d $dir/d.$i. $nrdirs_pp || true"
		createmany -d $dir/d.$i. $nrdirs_pp &
	done
	wait || error "failed to create $nrdirs subdirs in $dir"
	# nlink for the striped dir should be either 1
	# (ldiskfs, nlink is overflowed at least in one stripe)
	# or $ndirs + 2
	local nlinks=$(stat -c %h $dir)
	(( nlinks == 1 || nlinks == nrdirs + 2 )) ||
		error "Wrong nlink count of $nlinks"

	for ((i = 0; i < $nproc; i++)); do
		unlinkmany -d $dir/d.$i. $nrdirs_pp &
	done
	wait || error "Removal of $nrdirs subdirs failed"
	rmdir $dir && echo "removed emtpy $dir" || error "rmdir failed"
}
run_test 51c "exceed 64k subdirectory count per dir stripe, verify nlink count"

test_51d_sub() {
	local stripecount=$1
	local nfiles=$2

	log "create files with stripecount=$stripecount"
	$LFS setstripe -C $stripecount $DIR/$tdir
	createmany -o $DIR/$tdir/t- $nfiles
	$LFS getstripe $DIR/$tdir > $TMP/$tfile
	for ((n = 0; n < $OSTCOUNT; n++)); do
		objs[$n]=$(awk -vobjs=0 '($1 == '$n') { objs += 1 } \
			   END { printf("%0.0f", objs) }' $TMP/$tfile)
		objs0[$n]=$(grep -A 1 idx $TMP/$tfile | awk -vobjs=0 \
			    '($1 == '$n') { objs += 1 } \
			    END { printf("%0.0f", objs) }')
		log "OST$n has ${objs[$n]} objects, ${objs0[$n]} are index 0"
	done
	unlinkmany $DIR/$tdir/t- $nfiles
	rm  -f $TMP/$tfile

	# if running in a loop, don't run out of inodes on these OSTs
	(( $ONLY_REPEAT_ITER % 5 < 4 )) || {
		$LFS df
		$LFS df -i
		wait_delete_completed
		sleep 10
	}

	local nlast
	local min=4
	local max=6 # allow variance of (1 - $min/$max) = 33% by default

	# For some combinations of stripecount and OSTCOUNT current code
	# is not ideal, and allocates 50% fewer *first* objects to some OSTs
	# than others. Rather than skipping this test entirely, check that
	# and keep testing to ensure imbalance does not get worse. LU-15282
	(( (OSTCOUNT == 6 && stripecount == 4) ||
	   (OSTCOUNT == 10 && (stripecount == 4 || stripecount == 8)) ||
	   (OSTCOUNT == 12 && (stripecount == 8 || stripecount == 9)))) && max=9
	for ((nlast=0, n = 1; n < $OSTCOUNT; nlast=n,n++)); do
		(( ${objs[$n]} > ${objs[$nlast]} * 4 / 5 )) ||
			{ $LFS df && $LFS df -i &&
			error "stripecount=$stripecount: " \
			      "OST $n has fewer objects vs. OST $nlast " \
			      "(${objs[$n]} < ${objs[$nlast]} x 4/5)"; }
		(( ${objs[$n]} < ${objs[$nlast]} * 5 / 4 )) ||
			{ $LFS df && $LFS df -i &&
			error "stripecount=$stripecount: " \
			      "OST $n has more objects vs. OST $nlast " \
			      "(${objs[$n]} > ${objs[$nlast]} x 5/4)"; }

		(( ${objs0[$n]} > ${objs0[$nlast]} * $min / $max )) ||
			{ $LFS df && $LFS df -i &&
			error "stripecount=$stripecount: " \
			      "OST $n has fewer #0 objects vs. OST $nlast " \
			      "(${objs0[$n]} < ${objs0[$nlast]} x $min/$max)"; }
		(( ${objs0[$n]} < ${objs0[$nlast]} * $max / $min )) ||
			{ $LFS df && $LFS df -i &&
			error "stripecount=$stripecount: " \
			      "OST $n has more #0 objects vs. OST $nlast " \
			      "(${objs0[$n]} > ${objs0[$nlast]} x $max/$min)"; }
	done
}

test_51d() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[[ $OSTCOUNT -lt 3 ]] && skip_env "needs >= 3 OSTs"

	local stripecount
	local per_ost=100
	local nfiles=$((per_ost * OSTCOUNT))
	local mdts=$(comma_list $(mdts_nodes))
	local param="osp.*.create_count"
	local qos_old=$(do_facet mds1 \
		"$LCTL get_param -n lod.$FSNAME-*.qos_threshold_rr" | head -n 1)

	do_nodes $mdts \
		"$LCTL set_param lod.$FSNAME-*.qos_threshold_rr=100"
	stack_trap "do_nodes $mdts \
		'$LCTL set_param lod.$FSNAME-*.qos_threshold_rr=${qos_old%%%}'"

	test_mkdir $DIR/$tdir
	local dirstripes=$(lfs getdirstripe -c $DIR/$tdir)
	(( dirstripes > 0 )) || dirstripes=1

	# Ensure enough OST objects precreated for tests to pass without
	# running out of objects.  This is an LOV r-r OST algorithm test,
	# not an OST object precreation test.
	local old=$(do_facet mds1 "$LCTL get_param -n $param" | head -n 1)
	(( old >= nfiles )) ||
	{
		local create_count=$((nfiles * OSTCOUNT / dirstripes))

		do_nodes $mdts "$LCTL set_param $param=$create_count"
		stack_trap "do_nodes $mdts $LCTL set_param $param=$old"

		# trigger precreation from all MDTs for all OSTs
		for ((i = 0; i < $MDSCOUNT * 2; i++ )); do
			$LFS setstripe -c -1 $DIR/$tdir/wide.$i
		done
	}

	for ((stripecount = 3; stripecount <= $OSTCOUNT; stripecount++)); do
		sleep 8  # allow object precreation to catch up
		test_51d_sub $stripecount $nfiles
	done
}
run_test 51d "check LOV round-robin OST object distribution"

test_51e() {
	if [ "$mds1_FSTYPE" != ldiskfs ]; then
		skip_env "ldiskfs only test"
	fi

	test_mkdir -c1 $DIR/$tdir
	test_mkdir -c1 $DIR/$tdir/d0

	touch $DIR/$tdir/d0/foo
	createmany -l $DIR/$tdir/d0/foo $DIR/$tdir/d0/f- 65001 &&
		error "file exceed 65000 nlink limit!"
	unlinkmany $DIR/$tdir/d0/f- 65001
	return 0
}
run_test 51e "check file nlink limit"

test_51f() {
	test_mkdir $DIR/$tdir

	local max=100000
	local ulimit_old=$(ulimit -n)
	local spare=20 # number of spare fd's for scripts/libraries, etc.
	local mdt=$($LFS getstripe -m $DIR/$tdir)
	local numfree=$($LFS df --mdt=$mdt --output=ifree $DIR/$tdir)

	echo "MDT$mdt numfree=$numfree, max=$max"
	[[ $numfree -gt $max ]] && numfree=$max || numfree=$((numfree * 7 / 8))
	if [ $((numfree + spare)) -gt $ulimit_old ]; then
		while ! ulimit -n $((numfree + spare)); do
			numfree=$((numfree * 3 / 4))
		done
		echo "changed ulimit from $ulimit_old to $((numfree + spare))"
	else
		echo "left ulimit at $ulimit_old"
	fi

	createmany -o -k -t 120 $DIR/$tdir/f $numfree || {
		unlinkmany $DIR/$tdir/f $numfree
		error "create+open $numfree files in $DIR/$tdir failed"
	}
	ulimit -n $ulimit_old

	# if createmany exits at 120s there will be fewer than $numfree files
	unlinkmany $DIR/$tdir/f $numfree || true
}
run_test 51f "check many open files limit"

test_52a() {
	[ -f $DIR/$tdir/foo ] && chattr -a $DIR/$tdir/foo
	test_mkdir $DIR/$tdir
	touch $DIR/$tdir/foo
	chattr +a $DIR/$tdir/foo || error "chattr +a failed"
	echo bar >> $DIR/$tdir/foo || error "append bar failed"
	cp /etc/hosts $DIR/$tdir/foo && error "cp worked"
	rm -f $DIR/$tdir/foo 2>/dev/null && error "rm worked"
	link $DIR/$tdir/foo $DIR/$tdir/foo_link 2>/dev/null &&
					error "link worked"
	echo foo >> $DIR/$tdir/foo || error "append foo failed"
	mrename $DIR/$tdir/foo $DIR/$tdir/foo_ren && error "rename worked"
	lsattr $DIR/$tdir/foo | grep -E -q "^-+a[-e]+ $DIR/$tdir/foo" ||
						     error "lsattr"
	chattr -a $DIR/$tdir/foo || error "chattr -a failed"
	cp -r $DIR/$tdir $TMP/
	rm -fr $DIR/$tdir $TMP/$tdir || error "cleanup rm failed"
}
run_test 52a "append-only flag test (should return errors)"

test_52b() {
	[ -f $DIR/$tdir/foo ] && chattr -i $DIR/$tdir/foo
	test_mkdir $DIR/$tdir
	touch $DIR/$tdir/foo
	chattr +i $DIR/$tdir/foo || error "chattr +i failed"
	cat test > $DIR/$tdir/foo && error "cat test worked"
	cp /etc/hosts $DIR/$tdir/foo && error "cp worked"
	rm -f $DIR/$tdir/foo 2>/dev/null && error "rm worked"
	link $DIR/$tdir/foo $DIR/$tdir/foo_link 2>/dev/null &&
					error "link worked"
	echo foo >> $DIR/$tdir/foo && error "echo worked"
	mrename $DIR/$tdir/foo $DIR/$tdir/foo_ren && error "rename worked"
	[ -f $DIR/$tdir/foo ] || error "$tdir/foo is not a file"
	[ -f $DIR/$tdir/foo_ren ] && error "$tdir/foo_ren is not a file"
	lsattr $DIR/$tdir/foo | grep -E -q "^-+i[-e]+ $DIR/$tdir/foo" ||
							error "lsattr"
	chattr -i $DIR/$tdir/foo || error "chattr failed"

	rm -fr $DIR/$tdir || error "unable to remove $DIR/$tdir"
}
run_test 52b "immutable flag test (should return errors) ======="

test_53() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	remote_ost_nodsh && skip "remote OST with nodsh"

	local param
	local param_seq
	local ostname
	local mds_last
	local mds_last_seq
	local ost_last
	local ost_last_seq
	local ost_last_id
	local ostnum
	local node
	local found=false
	local support_last_seq=true

	[[ $MDS1_VERSION -ge $(version_code 2.3.60) ]] ||
		support_last_seq=false

	# only test MDT0000
	local mdtosc=$(get_mdtosc_proc_path $SINGLEMDS)
	local value
	for value in $(do_facet $SINGLEMDS \
		       $LCTL get_param osp.$mdtosc.prealloc_last_id) ; do
		param=$(echo ${value[0]} | cut -d "=" -f1)
		ostname=$(echo $param | cut -d "." -f2 | cut -d - -f 1-2)

		if $support_last_seq; then
			param_seq=$(echo $param |
				sed -e s/prealloc_last_id/prealloc_last_seq/g)
			mds_last_seq=$(do_facet $SINGLEMDS \
				       $LCTL get_param -n $param_seq)
		fi
		mds_last=$(do_facet $SINGLEMDS $LCTL get_param -n $param)

		ostnum=$(index_from_ostuuid ${ostname}_UUID)
		node=$(facet_active_host ost$((ostnum+1)))
		param="obdfilter.$ostname.last_id"
		for ost_last in $(do_node $node $LCTL get_param -n $param) ; do
			echo "$ostname.last_id=$ost_last; MDS.last_id=$mds_last"
			ost_last_id=$ost_last

			if $support_last_seq; then
				ost_last_id=$(echo $ost_last |
					      awk -F':' '{print $2}' |
					      sed -e "s/^0x//g")
				ost_last_seq=$(echo $ost_last |
					       awk -F':' '{print $1}')
				[[ $ost_last_seq = $mds_last_seq ]] || continue
			fi

			if [[ $ost_last_id != $mds_last ]]; then
				error "$ost_last_id != $mds_last"
			else
				found=true
				break
			fi
		done
	done
	$found || error "can not match last_seq/last_id for $mdtosc"
	return 0
}
run_test 53 "verify that MDS and OSTs agree on pre-creation ===="

test_54a() {
	$SOCKETSERVER $DIR/socket ||
		error "$SOCKETSERVER $DIR/socket failed: $?"
	$SOCKETCLIENT $DIR/socket ||
		error "$SOCKETCLIENT $DIR/socket failed: $?"
	unlink $DIR/socket || error "unlink $DIR/socket failed: $?"
}
run_test 54a "unix domain socket test"

test_54b() {
	f="$DIR/f54b"
	mknod $f c 1 3
	chmod 0666 $f
	dd if=/dev/zero of=$f bs=$PAGE_SIZE count=1
}
run_test 54b "char device works in lustre ======================"

find_loop_dev() {
	[ -b /dev/loop/0 ] && LOOPBASE=/dev/loop/
	[ -b /dev/loop0 ] && LOOPBASE=/dev/loop
	[ -z "$LOOPBASE" ] && echo "/dev/loop/0 and /dev/loop0 gone?" && return

	for i in $(seq 3 7); do
		losetup $LOOPBASE$i > /dev/null 2>&1 && continue
		LOOPDEV=$LOOPBASE$i
		LOOPNUM=$i
		break
	done
}

cleanup_54c() {
	local rc=0
	loopdev="$DIR/loop54c"

	trap 0
	$UMOUNT $DIR/$tdir || rc=$?
	losetup -d $loopdev || true
	losetup -d $LOOPDEV || true
	rm -rf $loopdev $DIR/$tfile $DIR/$tdir
	return $rc
}

test_54c() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	loopdev="$DIR/loop54c"

	find_loop_dev
	[ -z "$LOOPNUM" ] && skip_env "couldn't find empty loop device"
	trap cleanup_54c EXIT
	mknod $loopdev b 7 $LOOPNUM
	echo "make a loop file system with $DIR/$tfile on $loopdev ($LOOPNUM)."
	dd if=/dev/zero of=$DIR/$tfile bs=$PAGE_SIZE seek=1024 count=1 > /dev/null
	losetup $loopdev $DIR/$tfile ||
		error "can't set up $loopdev for $DIR/$tfile"
	mkfs.ext2 $loopdev || error "mke2fs on $loopdev"
	test_mkdir $DIR/$tdir
	mount -t ext2 $loopdev $DIR/$tdir ||
		error "error mounting $loopdev on $DIR/$tdir"
	dd if=/dev/zero of=$DIR/$tdir/tmp bs=$PAGE_SIZE count=30 ||
		error "dd write"
	df $DIR/$tdir
	dd if=$DIR/$tdir/tmp of=/dev/zero bs=$PAGE_SIZE count=30 ||
		error "dd read"
	cleanup_54c
}
run_test 54c "block device works in lustre ====================="

test_54d() {
	local pipe="$DIR/$tfile.pipe"
	local string="aaaaaa"

	mknod $pipe p
	echo -n "$string" > $pipe &
	local result=$(cat $pipe)
	[[ "$result" == "$string" ]] || error "$result != $string"
}
run_test 54d "fifo device works in lustre ======================"

test_54e() {
	f="$DIR/f54e"
	string="aaaaaa"
	cp -aL /dev/console $f
	echo $string > $f || error "echo $string to $f failed"
}
run_test 54e "console/tty device works in lustre ======================"

test_55a() {
	load_module kunit/obd_test verbose=2 || error "load_module failed"

	# This must be run in iteractive mode, since attach and setup
	# are stateful
	eval "$LCTL <<-EOF || error 'OBD device creation failed'
		attach obd_test obd_name obd_uuid
		setup obd_test
	EOF"

	echo "Devices:"
	$LCTL dl | tail -n 10

	$LCTL --device "obd_name" cleanup
	$LCTL --device "obd_name" detach

	dmesg | tail -n 25 | grep "Lustre: OBD:.*FAIL" &&
		error "OBD unit test failed"

	rmmod -v obd_test ||
		error "rmmod failed (may trigger a failure in a later test)"
}
run_test 55a "OBD device life cycle unit tests"

test_55b() {
	local dev_count="$($LCTL dl | wc -l)"

	# Set up a large number of devices, using the number
	# that can be set up in about a minute (based on prior
	# testing). We don't want to run this test forever.
	local num_dev_to_create="$(( 24000 - $dev_count))"

	load_module kunit/obd_test || error "load_module failed"

	local start=$SECONDS

	# This must be run in iteractive mode, since attach and setup
	# are stateful
	for ((i = 1; i <= num_dev_to_create; i++)); do
		echo "attach obd_test obd_name_$i obd_uuid_$i"
		echo "setup obd_test_$i"
	done | $LCTL || error "OBD device creation failed"

	echo "Load time: $((SECONDS - start))"
	echo "Devices:"
	$LCTL dl | tail -n 10

	for ((i = 1; i <= num_dev_to_create; i++)); do
		echo "--device obd_name_$i cleanup"
		echo "--device obd_name_$i detach"
	done | $LCTL || error "OBD device cleanup failed"

	echo "Unload time: $((SECONDS - start))"

	rmmod -v obd_test ||
		error "rmmod failed (may trigger a failure in a later test)"
}
run_test 55b "Load and unload max OBD devices"

test_55c()
{
	load_module kunit/obd_mod_rpcs_test ||
		error "load_module obd_mod_rpcs_test failed"
	dmesg | tail -n 25 | grep "obd_mod_rpcs_test"
	if [ $(dmesg | tail -n 25 | grep "Force grant RPC"| wc -l) -gt 1 ]; then
		error "Force granted more than once, failing."
	else
		echo "Force granted exactly once. Passed."
	fi
	rmmod -v obd_mod_rpcs_test ||
		error "rmmod failed (may trigger a failure in a later test)"
}
run_test 55c "obd_mod_rpcs_test"

test_56a() {
	local numfiles=3
	local numdirs=2
	local dir=$DIR/$tdir

	rm -rf $dir
	test_mkdir -p $dir/dir
	for i in $(seq $numfiles); do
		touch $dir/file$i
		touch $dir/dir/file$i
	done

	local numcomp=$($LFS getstripe --component-count $dir)

	[[ $numcomp == 0 ]] && numcomp=1

	# test lfs getstripe with --recursive
	local filenum=$($LFS getstripe -r $dir | grep -E -c "obdidx|l_ost_idx")

	[[ $filenum -eq $((numfiles * 2)) ]] ||
		error "$LFS getstripe -r: found $filenum != $((numfiles * 2))"
	filenum=$($LFS getstripe $dir | grep -E -c "obdidx|l_ost_idx")
	[[ $filenum -eq $numfiles ]] ||
		error "$LFS getstripe $dir: found $filenum, not $numfiles"
	echo "$LFS getstripe showed obdidx or l_ost_idx"

	# test lfs getstripe with file instead of dir
	filenum=$($LFS getstripe $dir/file1 | grep -E -c "obdidx|l_ost_idx")
	[[ $filenum -eq 1 ]] ||
		error "$LFS getstripe $dir/file1: found $filenum, not 1"
	echo "$LFS getstripe file1 passed"

	#test lfs getstripe with --verbose
	filenum=$($LFS getstripe --verbose $dir | grep -c lmm_magic)
	[[ $filenum -eq $((numfiles * numcomp)) ]] ||
		error "$LFS getstripe --verbose $dir: "\
		      "got $filenum want $((numfiles * numcomp)) lmm_magic"
	[[ $($LFS getstripe $dir | grep -c lmm_magic) -eq 0 ]] ||
		error "$LFS getstripe $dir: showed lmm_magic"

	#test lfs getstripe with -v prints lmm_fid
	filenum=$($LFS getstripe -v $dir | grep -c lmm_fid)
	local countfids=$(((numdirs + numfiles) * numcomp))
	[[ $filenum -eq $countfids ]] ||
		error "$LFS getstripe -v $dir: "\
		      "got $filenum want $countfids lmm_fid"
	[[ $($LFS getstripe $dir | grep -c lmm_fid) -eq 0 ]] ||
		error "$LFS getstripe $dir: showed lmm_fid by default"
	echo "$LFS getstripe --verbose passed"

	#check for FID information
	local fid1=$($LFS getstripe --fid $dir/file1)
	local fid2=$($LFS getstripe --verbose $dir/file1 |
		     awk '/lmm_fid: / { print $2; exit; }')
	local fid3=$($LFS path2fid $dir/file1)

	[ "$fid1" != "$fid2" ] &&
		error "getstripe --fid '$fid1' != getstripe --verbose '$fid2'"
	[ "$fid1" != "$fid3" ] &&
		error "getstripe --fid '$fid1' != lfs path2fid '$fid3'"
	echo "$LFS getstripe --fid passed"

	#test lfs getstripe with --obd
	$LFS getstripe --obd wrong_uuid $dir 2>&1 | grep -q "unknown obduuid" ||
		error "$LFS getstripe --obd wrong_uuid: should return error"

	[[ $OSTCOUNT -lt 2 ]] && skip_env "needs >= 2 OSTs"

	local ostidx=1
	local obduuid=$(ostuuid_from_index $ostidx)
	local found=$($LFS getstripe -r --obd $obduuid $dir |
		grep 'lmm_stripe_offset:' | grep -c " $ostidx\$")

	filenum=$($LFS getstripe -ir $dir | grep -c "^$ostidx\$")
	[[ $($LFS getstripe -id $dir) -ne $ostidx ]] ||
		((filenum--))
	[[ $($LFS getstripe -id $dir/dir) -ne $ostidx ]] ||
		((filenum--))

	[[ $found -eq $filenum ]] ||
		error "$LFS getstripe --obd: found $found expect $filenum"
	[[ $($LFS getstripe -r -v --obd $obduuid $dir |
		sed '/^[	 ]*'${ostidx}'[	 ]/d' |
		sed -n '/^[	 ]*[0-9][0-9]*[	 ]/p' | wc -l) -eq 0 ]] ||
		error "$LFS getstripe --obd: should not show file on other obd"
	echo "$LFS getstripe --obd passed"
}
run_test 56a "check $LFS getstripe"

test_56b() {
	local dir=$DIR/$tdir
	local numdirs=3

	test_mkdir $dir
	for i in $(seq $numdirs); do
		test_mkdir $dir/dir$i
	done

	# test lfs getdirstripe default mode is non-recursion, which is
	# different from lfs getstripe
	local dircnt=$($LFS getdirstripe $dir | grep -c lmv_stripe_count)

	[[ $dircnt -eq 1 ]] ||
		error "$LFS getdirstripe: found $dircnt, not 1"
	dircnt=$($LFS getdirstripe --recursive $dir |
		grep -c lmv_stripe_count)
	[[ $dircnt -eq $((numdirs + 1)) ]] ||
		error "$LFS getdirstripe -r: $dircnt, != $((numdirs + 1))"
}
run_test 56b "check $LFS getdirstripe"

test_56bb() {
	verify_yaml_available || skip_env "YAML verification not installed"
	local output_file=$DIR/$tfile.out

	$LFS getdirstripe -v -D -y $DIR 1> $output_file

	cat $output_file
	verify_yaml < $output_file ||
		error "default layout is not valid YAML"

# check non-default 1 stripe case
	test_mkdir -c 1 $DIR/$tdir
	$LFS getdirstripe -v -y $DIR 1> $output_file
	cat $output_file
	verify_yaml < $output_file || error "dir layout not valid YAML"
}
run_test 56bb "check $LFS getdirstripe layout is YAML"

test_56bc() {
	(( $MDSCOUNT >= 2 )) || skip "need >= 2 MDTs"
	verify_yaml_available || skip_env "YAML verification not installed"

	local src_dir=$DIR/$tdir.src
	local yaml_file=$DIR/$tfile.yaml

	$LFS setdirstripe -c 4 $src_dir ||
		error "failed to setstripe"
	$LFS getdirstripe --yaml -v $src_dir > $yaml_file ||
		error "failed to getdirstripe --yaml -v"

	cat $yaml_file
	verify_yaml < $yaml_file ||
		error "striped dir layout is not valid YAML"

	local orig=$(get_dir_layout_param $src_dir)
	local rest=$(cat $yaml_file | parse_layout_param)
	[[ "$orig" == "$rest" ]] ||
		error "failed to parse YAML layout"
}
run_test 56bc "check '$LFS getdirstripe --yaml' params are valid"

test_56bd() {
	(( $MDSCOUNT >= 2 )) || skip "need >= 2 MDTs"

	local dir1=$DIR/$tdir.dir1
	local dir2=$DIR/$tdir.dir2

	$LFS setdirstripe -c 1 $dir1 || error "failed to setstripe"
	$LFS setdirstripe -c 2 $dir2 || error "failed to setstripe"

	$LFS getdirstripe $dir1 | grep -q "mdtidx" &&
		error "getdirstripe printed component header when it should not have"

	$LFS getdirstripe $dir2 | grep -q "mdtidx" ||
		error "getdirstripe did not print component header when it should have"
}
run_test 56bd "check '$LFS getdirstripe' output contains header only when needed"

test_56c() {
	remote_ost_nodsh && skip "remote OST with nodsh"

	local ost_idx=0
	local ost_name=$(ostname_from_index $ost_idx)
	local old_status=$(ost_dev_status $ost_idx $MOUNT -v)
	local inst=$(lfs getname -i $DIR)
	local state="osc.$ost_name-osc-$inst.statfs_state"
	local old_state=$($LCTL get_param -n $state)
	local p="$TMP/$TESTSUITE-$TESTNAME.parameters"

	[[ "$old_status" == "$old_state" ]] ||
		error "old status '$old_status' != state '$old_state'"

	[[ -z "$old_status" || "$old_status" == "f" ]] ||
		skip_env "OST $ost_name is in $old_status status"

	local degraded="obdfilter.$ost_name.degraded"
	save_lustre_params ost1 $degraded > $p
	do_facet ost1 $LCTL set_param -n $degraded=1
	stack_trap "restore_lustre_params < $p; rm -f $p"

	if (( $OST1_VERSION >= $(version_code 2.12.55) )); then
		local no_precreate="obdfilter.$ost_name.no_precreate"

		save_lustre_params ost1 $no_precreate >> $p
		do_facet ost1 $LCTL set_param -n $no_precreate=1
	fi
	if (( $OST1_VERSION >= $(version_code 2.12.57) )) &&
	   [[ ! "$old_status" =~ "f" ]]; then
	   	local nonrotational="osd-*.$ost_name.nonrotational"

		save_lustre_params ost1 $nonrotational >> $p
		do_facet ost1 $LCTL set_param -n $nonrotational=1
	fi

	[[ ! $($LFS df -v $MOUNT 2>&1) =~ "inactive device" ]] ||
		error "$LFS df -v showing inactive devices"
	sleep_maxage

	$LFS df -v $MOUNT
	$LCTL get_param *.*.statfs_state

	local new_status=$(ost_dev_status $ost_idx $MOUNT -v)

	[[ "$new_status" =~ "D" ]] ||
		error "$ost_name status is '$new_status', missing 'D'"
	if (( $OST1_VERSION >= $(version_code 2.12.55) )) &&
	   [[ ! "$new_status" =~ "N" ]]; then
		error "$ost_name status is '$new_status', missing 'N'"
	fi
	if (( $OST1_VERSION >= $(version_code 2.12.57) )) &&
	   [[ ! "$new_status" =~ "f" ]]; then
		error "$ost_name status is '$new_status', missing 'f'"
	fi

	wait_update_facet client "$LCTL get_param -n $state" "$new_status" ||
		error "new state != new_status '$new_status'"

	restore_lustre_params < $p

	wait_update_facet client \
		"$LFS df -v --output=state --ost=$ost_idx" "$old_status" ||
	{
		new_status=$(ost_dev_status $ost_idx)

		error "new_status '$new_status' != old_status '$old_status'"
	}

	wait_update_facet client "$LCTL get_param -n $state" "$old_state" ||
	{
		local new_state=$($LCTL get_param -n $state)

		error "restored state '$new_state' != old_state '$old_state'"
	}
}
run_test 56c "check 'lfs df' showing device status"

test_56ca() {
	remote_ost_nodsh && skip "remote OST with nodsh"
	(( $OST1_VERSION >= $(version_code 2.16.53) )) ||
		skip "Need OST1 >= 2.16.53 for this test"

	local o_idx=0 # Target OST which will be set to readonly
	local ost_name=$(ostname_from_index $o_idx)

	# Force set OST0 as readonly
	do_facet ost${o_idx} $LCTL set_param -n obdfilter.$ost_name.readonly=1

	sleep_maxage # Give time for sync

	local new_status=$(ost_dev_status $o_idx $MOUNT -v) # Get new stats

	# revert to the normal state and wait for propagation
	do_facet ost${o_idx} $LCTL set_param -n obdfilter.$ost_name.readonly=0
	sleep_maxage

	[[ "$new_status" =~ "R" ]] ||
		error "$ost_name status is '$new_status', missing 'R'"
}
run_test 56ca "'lfs df -v' correctly reports 'R' flag when OST set as Readonly"

test_56d() {
	local mdts=$($LFS df -v -m $MOUNT | wc -l)
	local osts=$($LFS df -v -o $MOUNT | wc -l)

	$LFS df $MOUNT

	# Subtract 4 for the header line and summary information
	(( mdts - 4 == MDSCOUNT )) ||
		error "lfs df -v -m showed $((mdts - 4)) MDTs, not $MDSCOUNT"
	(( osts - 4 == OSTCOUNT )) ||
		error "lfs df -v -o showed $((osts - 4)) OSTs, not $OSTCOUNT"
}
run_test 56d "'lfs df -v' prints only configured devices"

test_56e() {
	err_enoent=2 # No such file or directory
	err_eopnotsupp=95 # Operation not supported

	enoent_mnt=/pmt1 # Invalid dentry. Path not present
	notsup_mnt=/tmp  # Valid dentry, but Not a lustreFS

	# Check for handling of path not exists
	output=$($LFS df $enoent_mnt 2>&1)
	ret=$?

	fs=$(echo $output | awk -F: '{print $2}' | awk '{print $3}' | tr -d \')
	[[ $fs = $enoent_mnt && $ret -eq $err_enoent ]] ||
		error "expect failure $err_enoent, not $ret"

	# Check for handling of non-Lustre FS
	output=$($LFS df $notsup_mnt)
	ret=$?

	fs=$(echo $output | awk '{print $1}' | awk -F: '{print $2}')
	[[ $fs = $notsup_mnt && $ret -eq $err_eopnotsupp ]] ||
		error "expect success $err_eopnotsupp, not $ret"

	# Check for multiple LustreFS argument
	output=$($LFS df $MOUNT $MOUNT $MOUNT --only-summary | wc -l)
	ret=$?

	[[ $output -eq 3 && $ret -eq 0 ]] ||
		error "expect success 3, not $output, rc = $ret"

	# Check for correct non-Lustre FS handling among multiple
	# LustreFS argument
	output=$($LFS df $MOUNT $notsup_mnt $MOUNT |
		grep -c "filesystem_summary:"; exit ${PIPESTATUS[0]})
	ret=$?

	[[ $output -eq 2 && $ret -eq $err_eopnotsupp ]] ||
		error "expect success 2, not $output, rc = $ret"
}
run_test 56e "'lfs df' Handle non LustreFS & multiple LustreFS"

NUMFILES=3
NUMDIRS=3
setup_56() {
	local local_tdir="$1"
	local local_numfiles="$2"
	local local_numdirs="$3"
	local dir_params="$4"
	local dir_stripe_params="$5"

	if [ ! -d "$local_tdir" ] ; then
		test_mkdir -p $dir_stripe_params $local_tdir
		[ "$dir_params" ] && $LFS setstripe $dir_params $local_tdir
		for i in $(seq $local_numfiles) ; do
			touch $local_tdir/file$i
		done
		for i in $(seq $local_numdirs) ; do
			test_mkdir $dir_stripe_params $local_tdir/dir$i
			for j in $(seq $local_numfiles) ; do
				touch $local_tdir/dir$i/file$j
			done
		done
	fi
}

setup_56_special() {
	local local_tdir=$1
	local local_numfiles=$2
	local local_numdirs=$3

	setup_56 $local_tdir $local_numfiles $local_numdirs

	if [ ! -e "$local_tdir/loop${local_numfiles}b" ] ; then
		for i in $(seq $local_numfiles) ; do
			mknod $local_tdir/loop${i}b b 7 $i
			mknod $local_tdir/null${i}c c 1 3
			ln -s $local_tdir/file1 $local_tdir/link${i}
		done
		for i in $(seq $local_numdirs) ; do
			mknod $local_tdir/dir$i/loop${i}b b 7 $i
			mknod $local_tdir/dir$i/null${i}c c 1 3
			ln -s $local_tdir/dir$i/file1 $local_tdir/dir$i/link${i}
		done
	fi
}

test_56g() {
	local dir=$DIR/d$(basetest $testnum)g.$TESTSUITE
	local expected=$(($NUMDIRS + 2))

	setup_56 $dir $NUMFILES $NUMDIRS

	# test lfs find with -name
	for i in $(seq $NUMFILES) ; do
		local nums=$($LFS find -name "*$i" $dir | wc -l)

		[ $nums -eq $expected ] ||
			error "lfs find -name '*$i' $dir wrong: "\
			      "found $nums, expected $expected"
	done
}
run_test 56g "check lfs find -name"

test_56h() {
	local dir=$DIR/d$(basetest $testnum)g.$TESTSUITE
	local expected=$(((NUMDIRS + 1) * (NUMFILES - 1) + NUMFILES))

	setup_56 $dir $NUMFILES $NUMDIRS

	# test lfs find with ! -name
	for i in $(seq $NUMFILES) ; do
		local nums=$($LFS find ! -name "*$i" $dir | wc -l)

		[ $nums -eq $expected ] ||
			error "lfs find ! -name '*$i' $dir wrong: "\
			      "found $nums, expected $expected"
	done
}
run_test 56h "check lfs find ! -name"

test_56i() {
	local dir=$DIR/$tdir

	test_mkdir $dir

	local cmd="$LFS find -ost $(ostuuid_from_index 0 $dir) $dir"
	local out=$($cmd)

	[ -z "$out" ] || error "'$cmd' returned directory '$out'"
}
run_test 56i "check 'lfs find -ost UUID' skips directories"

test_56ib() {
	local dir=$DIR/$tdir
	local file=$dir/$tfile
	local idx=$((RANDOM % $OSTCOUNT))
	local find_file
	local cmd

	test_mkdir $dir
	echo "create file $file on OST $idx"
	$LFS setstripe $file -o $idx||
		error "failed to create test file $file"

	cmd="$LFS find --ost 0,1-$idx,$idx $dir"
	echo "Command: $cmd"
	find_file=$($cmd)
	echo "lfs find result: $find_file"
	[[ "$find_file" == "$file" ]] ||
		error "file $file is NOT found"

	cmd="$LFS find ! --ost $idx-$((OSTCOUNT-1)),$idx $dir"
	echo "Command: $cmd"
	find_file=$($cmd)
	[[ -z "$find_file" ]]  ||
		error "should NOT find any file, but find $find_file"
}
run_test 56ib "check 'lfs find -ost INDEX_RANGE' command"

test_56j() {
	local dir=$DIR/d$(basetest $testnum)g.$TESTSUITE

	setup_56_special $dir $NUMFILES $NUMDIRS

	local expected=$((NUMDIRS + 1))
	local cmd="$LFS find -type d $dir"
	local nums=$($cmd | wc -l)

	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"
}
run_test 56j "check lfs find -type d"

test_56k() {
	local dir=$DIR/d$(basetest $testnum)g.$TESTSUITE

	setup_56_special $dir $NUMFILES $NUMDIRS

	local expected=$(((NUMDIRS + 1) * NUMFILES))
	local cmd="$LFS find -type f $dir"
	local nums=$($cmd | wc -l)

	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"
}
run_test 56k "check lfs find -type f"

test_56l() {
	local dir=$DIR/d$(basetest $testnum)g.$TESTSUITE

	setup_56_special $dir $NUMFILES $NUMDIRS

	local expected=$((NUMDIRS + NUMFILES))
	local cmd="$LFS find -type b $dir"
	local nums=$($cmd | wc -l)

	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"
}
run_test 56l "check lfs find -type b"

test_56m() {
	local dir=$DIR/d$(basetest $testnum)g.$TESTSUITE

	setup_56_special $dir $NUMFILES $NUMDIRS

	local expected=$((NUMDIRS + NUMFILES))
	local cmd="$LFS find -type c $dir"
	local nums=$($cmd | wc -l)
	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"
}
run_test 56m "check lfs find -type c"

test_56n() {
	local dir=$DIR/d$(basetest $testnum)g.$TESTSUITE
	setup_56_special $dir $NUMFILES $NUMDIRS

	local expected=$((NUMDIRS + NUMFILES))
	local cmd="$LFS find -type l $dir"
	local nums=$($cmd | wc -l)

	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"
}
run_test 56n "check lfs find -type l"

test_56o() {
	local dir=$DIR/$tdir

	setup_56 $dir $NUMFILES $NUMDIRS
	utime $dir/file1 > /dev/null || error "utime (1)"
	utime $dir/file2 > /dev/null || error "utime (2)"
	utime $dir/dir1 > /dev/null || error "utime (3)"
	utime $dir/dir2 > /dev/null || error "utime (4)"
	utime $dir/dir1/file1 > /dev/null || error "utime (5)"
	dd if=/dev/zero count=1 >> $dir/dir1/file1 && sync

	local expected=4
	local nums=$($LFS find -mtime +0 $dir | wc -l)

	[ $nums -eq $expected ] ||
		error "lfs find -mtime +0 $dir: found $nums expect $expected"

	expected=12
	cmd="$LFS find -mtime 0 $dir"
	nums=$($cmd | wc -l)
	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"
}
run_test 56o "check lfs find -mtime for old files"

test_56ob() {
	local dir=$DIR/$tdir
	local expected=1
	local count=0

	# just to make sure there is something that won't be found
	test_mkdir $dir
	touch $dir/$tfile.now

	for age in year week day hour min; do
		count=$((count + 1))

		touch $dir/$tfile-a.$age $dir/$tfile-m.$age
		touch --date="$count $age ago" -a $dir/$tfile-a.$age
		touch --date="$count $age ago" -m $dir/$tfile-m.$age

		local cmd="$LFS find $dir -mtime $count${age:0:1}"
		local nums=$($cmd | wc -l)
		(( $nums == $expected )) || {
			$LFS find $dir -ls
			error "'$cmd' wrong: found $nums, expected $expected"
		}

		cmd="$LFS find $dir -atime $count${age:0:1}"
		nums=$($cmd | wc -l)
		(( $nums == $expected )) || {
			$LFS find $dir -ls
			error "'$cmd' wrong: found $nums, expected $expected"
		}
	done

	sleep 2
	cmd="$LFS find $dir -ctime +1s -type f"
	nums=$($cmd | wc -l)
	(( $nums == $count * 2 + 1)) || {
		$LFS find $dir -ls
		error "'$cmd' wrong: found $nums, expected $((count * 2 + 1))"
	}
}
run_test 56ob "check lfs find -atime -mtime -ctime with units"

test_newerXY_base() {
	local x=$1
	local y=$2
	local dir=$DIR/$tdir
	local ref
	local negref

	stack_trap "rm -rf $DIR/$tdir $DIR/$tfile*" RETURN EXIT

	if [ $y == "t" ]; then
		if [ $x == "b" ]; then
			ref=\"$(do_facet mds1 date +"%Y-%m-%d\ %H:%M:%S")\"
		else
			ref=\"$(date +"%Y-%m-%d %H:%M:%S")\"
		fi
	else
		ref=$DIR/$tfile.newer.$x$y
		touch $ref || error "touch $ref failed"
	fi

	echo "before = $ref"
	sleep 2
	setup_56 $dir $NUMFILES $NUMDIRS "-i0 -c1" "-i0 -c1"
	sleep 2
	if [ $y == "t" ]; then
		if [ $x == "b" ]; then
			negref=\"$(do_facet mds1 date +"%Y-%m-%d\ %H:%M:%S")\"
		else
			negref=\"$(date +"%Y-%m-%d %H:%M:%S")\"
		fi
	else
		negref=$DIR/$tfile.negnewer.$x$y
		touch $negref || error "touch $negref failed"
	fi

	echo "after = $negref"
	local cmd="$LFS find $dir -newer$x$y $ref"
	local nums=$(eval $cmd | wc -l)
	local expected=$(((NUMFILES + 2) * NUMDIRS + 1))

	[ $nums -eq $expected ] || { ls -lauR --full-time $dir ;
		error "'$cmd' wrong: found $nums newer, expected $expected"  ; }

	cmd="$LFS find $dir ! -newer$x$y $negref"
	nums=$(eval $cmd | wc -l)
	[ $nums -eq $expected ] || { ls -lauR --full-time $dir ;
		error "'$cmd' wrong: found $nums older, expected $expected"  ; }

	cmd="$LFS find $dir -newer$x$y $ref ! -newer$x$y $negref"
	nums=$(eval $cmd | wc -l)
	[ $nums -eq $expected ] || { ls -lauR --full-time $dir ;
		error "'$cmd' wrong: found $nums between, expected $expected"; }
}

test_56oc() {
	test_newerXY_base "a" "a"
	test_newerXY_base "a" "m"
	test_newerXY_base "a" "c"
	test_newerXY_base "m" "a"
	test_newerXY_base "m" "m"
	test_newerXY_base "m" "c"
	test_newerXY_base "c" "a"
	test_newerXY_base "c" "m"
	test_newerXY_base "c" "c"

	test_newerXY_base "a" "t"
	test_newerXY_base "m" "t"
	test_newerXY_base "c" "t"

	(( $MDS1_VERSION >= $(version_code v2_13_53-145-g186b97e68a) &&
	   $CLIENT_VERSION >= $(version_code v2_13_53-145-g186b97e68a) )) ||
		{ echo "btime needs v2_13_53-145-g186b97e68a"; return 0; }

	test_newerXY_base "b" "b"
	test_newerXY_base "b" "t"
}
run_test 56oc "check lfs find -newerXY work"

test_56od() {
	(( $MDS1_VERSION >= $(version_code v2_13_53-145-g186b97e68a) )) ||
		skip "btime unsupported on MDS < v2_13_53-145-g186b97e68a"

	(( $CLIENT_VERSION >= $(version_code v2_13_53-145-g186b97e68a) )) ||
		skip "btime unsupported on clients < v2_13_53-145-g186b97e68a"

	local dir=$DIR/$tdir
	local ref=$DIR/$tfile.ref
	local negref=$DIR/$tfile.negref

	mkdir $dir || error "mkdir $dir failed"
	touch $dir/$tfile.n1 || error "touch $dir/$tfile.n1 failed"
	touch $dir/$tfile.n2 || error "touch $dir/$tfile.n2 failed"
	mkdir $dir/$tdir.n1 || error "mkdir $dir/$tdir.n1 failed"
	mkdir $dir/$tdir.n2 || error "mkdir $dir/$tdir.n2 failed"
	touch $ref || error "touch $ref failed"
	# sleep 3 seconds at least
	sleep 3

	local before=$(do_facet mds1 date +%s)
	local skew=$(($(date +%s) - before + 1))

	if (( skew < 0 && skew > -5 )); then
		sleep $((0 - skew + 1))
		skew=0
	fi

	# Set the dir stripe params to limit files all on MDT0,
	# otherwise we need to calc the max clock skew between
	# the client and MDTs.
	setup_56 $dir/d.btime $NUMFILES $NUMDIRS "-i0 -c1" "-i0 -c1"
	sleep 2
	touch $negref || error "touch $negref failed"

	local cmd="$LFS find $dir -newerbb $ref ! -newerbb $negref -type f"
	local nums=$($cmd | wc -l)
	local expected=$(((NUMFILES + 1) * NUMDIRS))

	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"

	cmd="$LFS find $dir -newerbb $ref ! -newerbb $negref -type d"
	nums=$($cmd | wc -l)
	expected=$((NUMFILES + 1))
	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"

	[ $skew -lt 0 ] && return

	local after=$(do_facet mds1 date +%s)
	local age=$((after - before + 1 + skew))

	cmd="$LFS find $dir -btime -${age}s -type f"
	nums=$($cmd | wc -l)
	expected=$(((NUMFILES + 1) * NUMDIRS))

	echo "Clock skew between client and server: $skew, age:$age"
	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"

	expected=$(($NUMDIRS + 1))
	cmd="$LFS find $dir -btime -${age}s -type d"
	nums=$($cmd | wc -l)
	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"
	rm -f $ref $negref || error "Failed to remove $ref $negref"
}
run_test 56od "check lfs find -btime with units"

test_56oe() {
	local dir=$DIR/$tdir
	local expected=5
	local unit=hour

	# just to make sure there is something that won't be found
	test_mkdir $dir
	touch $dir/$tfile.now

	for ((val = 1; val <= 10; val++)); do
		touch $dir/$tfile-a.$val $dir/$tfile-m.$val
		touch $dir/$tfile-c.$val
		echo -n "$tfile-c.$val	@ctime (Epoch):"
		stat -c "%Z" $dir/$tfile-c.$val
		touch --date="$val $unit ago" -a $dir/$tfile-a.$val
		touch --date="$val $unit ago" -m $dir/$tfile-m.$val
		(( val % 5 != 2 )) || sleep 60
	done

	local now=$(date +%s)
	local lower_bound=$(( now - $(stat -c "%Z" $dir/$tfile-c.8) + 30 ))
	local upper_bound=$(( now - $(stat -c "%Z" $dir/$tfile-c.2) - 30 ))

	cmd="$LFS find $dir -ctime -${upper_bound}s -ctime +${lower_bound}s"
	nums=$($cmd | grep -c c.*)

	(( nums == expected )) ||
		error "'$cmd' wrong: found $nums between $lower_bound and $upper_bound, expected $expected"

	local cmd="$LFS find $dir -atime +7h30m -atime -2h30m"
	local nums=$($cmd | wc -l)

	(( $($cmd | grep -c a.7) == 1 )) ||
		error "'$cmd' didn't capture file accessed 7 hours ago"
	(( $($cmd | grep -c a.3) == 1 )) ||
		error "'$cmd' didn't capture file accessed 3 hours ago"
	(( nums == expected )) ||
		error "'$cmd' wrong: found $nums, expected $expected"

	cmd="$LFS find $dir -mtime -7h30m -mtime +2h30m"
	nums=$($cmd | wc -l)

	(( $($cmd | grep -c m.7) == 1 )) ||
		error "'$cmd' didn't capture file modified 7 hours ago"
	(( $($cmd | grep -c m.3) == 1 )) ||
		error "'$cmd' didn't capture file modified 3 hours ago"
	(( nums == expected )) ||
		error "'$cmd' wrong: found $nums, expected $expected"
}
run_test 56oe "check lfs find with time range"

test_56p() {
	[ $RUNAS_ID -eq $UID ] &&
		skip_env "RUNAS_ID = UID = $UID -- skipping"

	local dir=$DIR/$tdir

	setup_56 $dir $NUMFILES $NUMDIRS
	chown $RUNAS_ID $dir/file* || error "chown $DIR/${tdir}g/file$i failed"

	local expected=$NUMFILES
	local cmd="$LFS find -uid $RUNAS_ID $dir"
	local nums=$($cmd | wc -l)

	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"

	expected=$(((NUMFILES + 1) * NUMDIRS + 1))
	cmd="$LFS find ! -uid $RUNAS_ID $dir"
	nums=$($cmd | wc -l)
	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"
}
run_test 56p "check lfs find -uid and ! -uid"

test_56q() {
	[ $RUNAS_ID -eq $UID ] &&
		skip_env "RUNAS_ID = UID = $UID -- skipping"

	local dir=$DIR/$tdir

	setup_56 $dir $NUMFILES $NUMDIRS
	chgrp $RUNAS_GID $dir/file* || error "chown $dir/file$i failed"

	local expected=$NUMFILES
	local cmd="$LFS find -gid $RUNAS_GID $dir"
	local nums=$($cmd | wc -l)

	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"

	expected=$(( ($NUMFILES+1) * $NUMDIRS + 1))
	cmd="$LFS find ! -gid $RUNAS_GID $dir"
	nums=$($cmd | wc -l)
	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"
}
run_test 56q "check lfs find -gid and ! -gid"

test_56r() {
	local dir=$DIR/$tdir

	setup_56 $dir $NUMFILES $NUMDIRS

	local expected=12
	local cmd="$LFS find -size 0 -type f -lazy $dir"
	local nums=$($cmd | wc -l)

	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"
	cmd="$LFS find -size 0 -type f $dir"
	nums=$($cmd | wc -l)
	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"

	expected=0
	cmd="$LFS find ! -size 0 -type f -lazy $dir"
	nums=$($cmd | wc -l)
	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"
	cmd="$LFS find ! -size 0 -type f $dir"
	nums=$($cmd | wc -l)
	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"

	echo "test" > $dir/$tfile
	echo "test2" > $dir/$tfile.2 && sync
	expected=1
	cmd="$LFS find -size 5c -type f -lazy $dir"
	nums=$($cmd | wc -l)
	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"
	cmd="$LFS find -size 5c -type f $dir"
	nums=$($cmd | wc -l)
	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"

	expected=1
	cmd="$LFS find -size +5c -type f -lazy $dir"
	nums=$($cmd | wc -l)
	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"
	cmd="$LFS find -size +5c -type f $dir"
	nums=$($cmd | wc -l)
	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"

	expected=2
	cmd="$LFS find -size +0 -type f -lazy $dir"
	nums=$($cmd | wc -l)
	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"
	cmd="$LFS find -size +0 -type f $dir"
	nums=$($cmd | wc -l)
	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"

	expected=2
	cmd="$LFS find ! -size -5c -type f -lazy $dir"
	nums=$($cmd | wc -l)
	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"
	cmd="$LFS find ! -size -5c -type f $dir"
	nums=$($cmd | wc -l)
	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"

	expected=12
	cmd="$LFS find -size -5c -type f -lazy $dir"
	nums=$($cmd | wc -l)
	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"
	cmd="$LFS find -size -5c -type f $dir"
	nums=$($cmd | wc -l)
	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"
}
run_test 56r "check lfs find -size works"

test_56ra_sub() {
	local expected=$1
	local glimpses=$2
	local cmd="$3"

	cancel_lru_locks $OSC

	local rpcs_before=$(calc_stats $OSC.*$OSC*.stats ldlm_glimpse_enqueue)
	local nums=$($cmd | wc -l)

	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"

	local rpcs_after=$(calc_stats $OSC.*$OSC*.stats ldlm_glimpse_enqueue)

	if (( rpcs_before + glimpses != rpcs_after )); then
		echo "Before: $rpcs_before After: $rpcs_after $NUMFILES"
		$LCTL get_param osc.*.stats | grep ldlm_glimpse_enqueue

		if [[ $glimpses == 0 ]]; then
			error "'$cmd' should not send glimpse RPCs to OST"
		else
			error "'$cmd' should send $glimpses glimpse RPCs to OST"
		fi
	fi
}

test_56ra() {
	[[ $MDS1_VERSION -gt $(version_code 2.12.58) ]] ||
		skip "MDS < 2.12.58 doesn't return LSOM data"
	local dir=$DIR/$tdir
	local old_agl=$($LCTL get_param -n llite.*.statahead_agl)

	[[ $OSC == "mdc" ]] && skip "statahead not needed for DoM files"

	# statahead_agl may cause extra glimpse which confuses results. LU-13017
	$LCTL set_param -n llite.*.statahead_agl=0
	stack_trap "$LCTL set_param -n llite.*.statahead_agl=$old_agl"

	setup_56 $dir $NUMFILES $NUMDIRS "-c 1"
	# open and close all files to ensure LSOM is updated
	cancel_lru_locks $OSC
	find $dir -type f | xargs cat > /dev/null

	#   expect_found  glimpse_rpcs  command_to_run
	test_56ra_sub 12  0 "$LFS find -size 0 -type f -lazy $dir"
	test_56ra_sub 12 12 "$LFS find -size 0 -type f $dir"
	test_56ra_sub  0  0 "$LFS find ! -size 0 -type f -lazy $dir"
	test_56ra_sub  0 12 "$LFS find ! -size 0 -type f $dir"

	echo "test" > $dir/$tfile
	echo "test2" > $dir/$tfile.2 && sync
	cancel_lru_locks $OSC
	cat $dir/$tfile $dir/$tfile.2 > /dev/null

	test_56ra_sub  1  0 "$LFS find -size 5c -type f -lazy $dir"
	test_56ra_sub  1 14 "$LFS find -size 5c -type f $dir"
	test_56ra_sub  1  0 "$LFS find -size +5c -type f -lazy $dir"
	test_56ra_sub  1 14 "$LFS find -size +5c -type f $dir"

	test_56ra_sub  2  0 "$LFS find -size +0 -type f -lazy $dir"
	test_56ra_sub  2 14 "$LFS find -size +0 -type f $dir"
	test_56ra_sub  2  0 "$LFS find ! -size -5c -type f -lazy $dir"
	test_56ra_sub  2 14 "$LFS find ! -size -5c -type f $dir"
	test_56ra_sub 12  0 "$LFS find -size -5c -type f -lazy $dir"
	test_56ra_sub 12 14 "$LFS find -size -5c -type f $dir"
}
run_test 56ra "check lfs find -size -lazy works for data on OSTs"

test_56rb() {
	local dir=$DIR/$tdir
	local tmp=$TMP/$tfile.log
	local mdt_idx;

	test_mkdir -p $dir || error "failed to mkdir $dir"
	$LFS setstripe -c 1 -i 0 $dir/$tfile ||
		error "failed to setstripe $dir/$tfile"
	mdt_idx=$($LFS getdirstripe -i $dir)
	dd if=/dev/zero of=$dir/$tfile bs=1M count=1

	stack_trap "rm -f $tmp $dir/$tfile" EXIT
	$LFS find --size +100K --ost 0 $dir |& tee $tmp
	! grep -q obd_uuid $tmp ||
		error "failed to find --size +100K --ost 0 $dir"
	$LFS find --size +100K --mdt $mdt_idx $dir |& tee $tmp
	! grep -q obd_uuid $tmp ||
		error "failed to find --size +100K --mdt $mdt_idx $dir"
}
run_test 56rb "check lfs find --size --ost/--mdt works"

test_56rc() {
	(( MDSCOUNT >= 2 )) || skip "needs at least 2 MDTs"
	local dir=$DIR/$tdir
	local found

	test_mkdir -c 2 -H all_char $dir || error "failed to mkdir $dir"
	$LFS mkdir -c 2 --mdt-hash all_char $dir/$tdir-all{1..10}
	(( $MDSCOUNT > 2 )) &&
		$LFS mkdir -c 3 --mdt-hash fnv_1a_64 $dir/$tdir-fnv{1..10}
	mkdir $dir/$tdir-{1..10}
	touch $dir/$tfile-{1..10}

	found=$($LFS find $dir --mdt-count 2 | wc -l)
	expect=11
	(( $found == $expect )) || error "found $found 2-stripe, expect $expect"

	found=$($LFS find $dir -T +1 | wc -l)
	(( $MDSCOUNT > 2 )) && expect=$((expect + 10))
	(( $found == $expect )) || error "found $found 2+stripe, expect $expect"

	found=$($LFS find $dir --mdt-hash all_char | wc -l)
	expect=11
	(( $found == $expect )) || error "found $found all_char, expect $expect"

	found=$($LFS find $dir --mdt-hash fnv_1a_64 | wc -l)
	(( $MDSCOUNT > 2 )) && expect=10 || expect=0
	(( $found == $expect )) || error "found $found all_char, expect $expect"
}
run_test 56rc "check lfs find --mdt-count/--mdt-hash works"

test_56rd() {
	local dir=$DIR/$tdir

	test_mkdir $dir
	rm -f $dir/*

	mkfifo $dir/fifo || error "failed to create fifo file"
	$LFS find $dir -t p --printf "%p %y %LP\n" ||
		error "should not fail when getting projid from pipe file"
	found=$($LFS find $dir -t p --printf "%y")
	[[ "p" == $found ]] || error "found $found, expect p"

	mknod $dir/chardev c 1 5 ||
		error "failed to create character device file"
	$LFS find $dir -t c --printf "%p %y %LP\n" ||
		error "should not fail when getting projid from chardev file"
	found=$($LFS find $dir -t c --printf "%y")
	[[ "c" == $found ]] || error "found $found, expect c"

	found=$($LFS find $dir ! -type d --printf "%p %y %LP\n" | wc -l)
	(( found == 2 )) || error "unable to list all files"
}
run_test 56rd "check lfs find --printf special files"

test_56re()
{
	local dir=$DIR/$tdir
	local file=$dir/a
	local test_cases=(
		"|%5s|" "|%05s|" "|%0s|" "|%-5s|" "|%-0s|"
		"|%5G|" "|%05G|" "|%0G|" "|%-5G|" "|%-0G|"
		"|%25i|" "|%025i|" "|%0i|" "|%-25i|" "|%-0i|"
		"|%5k|" "|%05k|" "|%0k|" "|%-5k|" "|%-0k|"
		"|%5y|" "|%05y|" "|%0y|" "|%-5y|" "|%-0y|"
		"|%5m|" "|%05m|" "|%0m|" "|%-5m|" "|%-0m|" "|%-05m|"
		"|%----5s|" "|%----00005s|" "|%00005s|"
		"|%020|" "|%20|" "|%-20|" "|%-020|" "|%---020|" "|%---20|"
	)

	test_mkdir "$dir"
	touch "$file"
	truncate -s 37 "$file"

	for format in ${test_cases[@]}; do
		local expected=$(find "$dir" -type f -printf "$format\n")
		local output=$($LFS find "$dir" -type f -printf "$format\n")

		[[ $output == $expected ]] ||
			error "Unexpected output to \"$format\", expected '$expected' got '$output'"
	done
}
run_test 56re "check lfs find -printf width format specifiers are consistant with regular find"

test_56rf()
{
	local dir=$DIR/$tdir
	local file=$dir/a
	local test_cases
	local poolname=testpool56rf
	local stripe_count
	local fid

	test_mkdir "$dir"
	pool_add $poolname || error "Could not create pool '$poolname'"

	lfs setstripe -c 2 -S 4M -p $poolname "$file"
	stripe_count=$(lfs getstripe -c "$file")
	fid=$($LFS path2fid "$file" | sed 's/\[\(.*\)\]/\1/')
	len=$((${#fid} + 5))

	test_cases=(
		"|%${len}LF|" "|     $fid|"
		"|%0${len}LF|" "|     $fid|"
		"|%0LF|" "|$fid|"
		"|%-${len}LF|" "|$fid     |"
		"|%-0LF|" "|$fid|"

		"|%14Lp|" "|  $poolname|"
		"|%014Lp|" "|  $poolname|"
		"|%0Lp|" "|$poolname|"
		"|%-14Lp|" "|$poolname  |"
		"|%-0Lp|" "|$poolname|"
		"|%07Lp|" "|$poolname|"
		"|%-7Lp|" "|$poolname|"

		"|%4Lc|" "|   $stripe_count|"
		"|%04Lc|" "|   $stripe_count|"
		"|%0Lc|" "|$stripe_count|"
		"|%-4Lc|" "|$stripe_count   |"
		"|%-0Lc|" "|$stripe_count|"

		"|%10LS|" "|   4194304|"
		"|%010LS|" "|   4194304|"
		"|%0LS|" "|4194304|"
		"|%-10LS|" "|4194304   |"
		"|%-0LS|" "|4194304|"
	)

	for (( i = 0; i < ${#test_cases[@]}; i += 2 )); do
		local format=${test_cases[i]}
		local expected=${test_cases[i + 1]}
		local output=$($LFS find "$dir" -type f -printf "$format\n")

		[[ $output == $expected ]] ||
			error "Unexpected output to \"$format\", expected '$expected' got '$output'"
	done
}
run_test 56rf "check lfs find -printf width format specifiers for lustre specific formats"

test_56s() { # LU-611 #LU-9369
	(( $OSTCOUNT >= 2 )) || skip_env "need at least 2 OSTs"

	local dir=$DIR/$tdir
	local onestripe=$(((NUMDIRS + 1) * NUMFILES))
	local count=$((OSTCOUNT > 2 ? OSTCOUNT - 1 : 2))

	setup_56 $dir $NUMFILES $NUMDIRS "-c 1"
	for ((i = 1; i <= $NUMDIRS; i++)); do
		$LFS setstripe -c $count $dir/dir$i/$tfile
	done

	local expected=$NUMDIRS
	local cmd="$LFS find -c $count $dir"
	local nums=$($cmd | wc -l)

	(( $nums == $expected )) || {
		$LFS getstripe -R $dir
		error "'$cmd' wrong: found $nums, expected $expected"
	}

	expected=$((NUMDIRS + onestripe))
	cmd="$LFS find -stripe-count +0 -type f $dir"
	nums=$($cmd | wc -l)
	(( $nums == $expected )) || {
		$LFS getstripe -R $dir
		error "'$cmd' wrong: found $nums, expected $expected"
	}

	expected=$onestripe
	cmd="$LFS find -stripe-count 1 -type f $dir"
	nums=$($cmd | wc -l)
	(( $nums == $expected )) || {
		$LFS getstripe -R $dir
		error "'$cmd' wrong: found $nums, expected $expected"
	}

	cmd="$LFS find -stripe-count -2 -type f $dir"
	nums=$($cmd | wc -l)
	(( $nums == $expected )) || {
		$LFS getstripe -R $dir
		error "'$cmd' wrong: found $nums, expected $expected"
	}

	expected=0
	cmd="$LFS find -stripe-count $((count + 1)) -type f $dir"
	nums=$($cmd | wc -l)
	(( $nums == $expected )) || {
		$LFS getstripe -R $dir
		error "'$cmd' wrong: found $nums, expected $expected"
	}
}
run_test 56s "check lfs find -stripe-count works"

test_56t() { # LU-611 #LU-9369
	local dir=$DIR/$tdir

	setup_56 $dir 0 $NUMDIRS
	for i in $(seq $NUMDIRS); do
		$LFS setstripe -S 8M $dir/dir$i/$tfile
	done

	local expected=$NUMDIRS
	local cmd="$LFS find -S 8M $dir"
	local nums=$($cmd | wc -l)

	[ $nums -eq $expected ] || {
		$LFS getstripe -R $dir
		error "'$cmd' wrong: found $nums, expected $expected"
	}
	rm -rf $dir

	setup_56 $dir $NUMFILES $NUMDIRS "--stripe-size 512k"

	$LFS setstripe -S 256k $dir/$tfile.{0,1,2,3}

	expected=$(((NUMDIRS + 1) * NUMFILES))
	cmd="$LFS find -stripe-size 512k -type f $dir"
	nums=$($cmd | wc -l)
	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"

	cmd="$LFS find -stripe-size +320k -type f $dir"
	nums=$($cmd | wc -l)
	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"

	expected=$(((NUMDIRS + 1) * NUMFILES + 4))
	cmd="$LFS find -stripe-size +200k -type f $dir"
	nums=$($cmd | wc -l)
	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"

	cmd="$LFS find -stripe-size -640k -type f $dir"
	nums=$($cmd | wc -l)
	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"

	expected=4
	cmd="$LFS find -stripe-size 256k -type f $dir"
	nums=$($cmd | wc -l)
	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"

	cmd="$LFS find -stripe-size -320k -type f $dir"
	nums=$($cmd | wc -l)
	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"

	expected=0
	cmd="$LFS find -stripe-size 1024k -type f $dir"
	nums=$($cmd | wc -l)
	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"
}
run_test 56t "check lfs find -stripe-size works"

test_56u() { # LU-611
	local dir=$DIR/$tdir

	setup_56 $dir $NUMFILES $NUMDIRS "-i 0 -c 1"

	if [[ $OSTCOUNT -gt 1 ]]; then
		$LFS setstripe -i 1 -c 1 $dir/$tfile.{0,1,2,3}
		onestripe=4
	else
		onestripe=0
	fi

	local expected=$(((NUMDIRS + 1) * NUMFILES))
	local cmd="$LFS find -stripe-index 0 -type f $dir"
	local nums=$($cmd | wc -l)

	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"

	expected=$onestripe
	cmd="$LFS find -stripe-index 1 -type f $dir"
	nums=$($cmd | wc -l)
	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"

	cmd="$LFS find ! -stripe-index 0 -type f $dir"
	nums=$($cmd | wc -l)
	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"

	expected=0
	# This should produce an error and not return any files
	cmd="$LFS find -stripe-index $OSTCOUNT -type f $dir"
	nums=$($cmd 2>/dev/null | wc -l)
	[ $nums -eq $expected ] ||
		error "'$cmd' wrong: found $nums, expected $expected"

	if [[ $OSTCOUNT -gt 1 ]]; then
		expected=$(((NUMDIRS + 1) * NUMFILES + onestripe))
		cmd="$LFS find -stripe-index 0,1 -type f $dir"
		nums=$($cmd | wc -l)
		[ $nums -eq $expected ] ||
			error "'$cmd' wrong: found $nums, expected $expected"
	fi
}
run_test 56u "check lfs find -stripe-index works"

test_56v() {
	local mdt_idx=0
	local dir=$DIR/$tdir

	setup_56 $dir $NUMFILES $NUMDIRS

	UUID=$(mdtuuid_from_index $mdt_idx $dir)
	[ -z "$UUID" ] && error "mdtuuid_from_index cannot find MDT $mdt_idx"

	for file in $($LFS find -m $UUID $dir); do
		file_midx=$($LFS getstripe -m $file)
		[ $file_midx -eq $mdt_idx ] ||
			error "lfs find -m $UUID != getstripe -m $file_midx"
	done
}
run_test 56v "check 'lfs find -m match with lfs getstripe -m'"

test_56wa() {
	(( $OSTCOUNT >= 2 )) || skip "needs >= 2 OSTs"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	local dir=$DIR/$tdir
	local expected=$((OSTCOUNT - 1))

	setup_56 $dir $NUMFILES $NUMDIRS "-c $expected" "-c1"
	stack_trap "rm -rf $dir"

	local stripe_size=$($LFS getstripe -S -d $dir) ||
		error "$LFS getstripe -S -d $dir failed"
	stripe_size=${stripe_size%% *}

	local file_size=$((stripe_size * expected))
	local file_num=$((NUMDIRS * NUMFILES + NUMFILES))
	local required_space=$((file_num * file_size))
	local free_space=$($LCTL get_param -n lov.$FSNAME-clilov-*.kbytesavail |
			   head -n1)
	(( free_space >= required_space / 1024 )) ||
		skip_env "need $required_space, have $free_space kbytes"

	local dd_bs=65536
	local dd_count=$((file_size / dd_bs))

	# write data into the files
	local i
	local j
	local file

	for ((i = 1; i <= NUMFILES; i++ )); do
		file=$dir/file$i
		yes | dd bs=$dd_bs count=$dd_count of=$file &>/dev/null ||
			error "write data into $file failed"
	done
	for ((i = 1; i <= NUMDIRS; i++ )); do
		for ((j = 1; j <= NUMFILES; j++ )); do
			file=$dir/dir$i/file$j
			yes|dd bs=$dd_bs count=$dd_count of=$file &>/dev/null ||
				error "write data into $file failed"
		done
	done

	# $LFS_MIGRATE will fail if hard link migration is unsupported
	if (( MDS1_VERSION > $(version_code 2.5.55) )); then
		createmany -l$dir/dir1/file1 $dir/dir1/link 200 ||
			error "creating links to $dir/dir1/file1 failed"
	fi

	# lfs migrate file
	local cmd="$LFS migrate -v -c $expected $dir/file1"

	echo "$cmd"
	eval $cmd || error "$cmd failed"

	check_stripe_count $dir/file1 $expected

	if (( $MDS1_VERSION >= $(version_code 2.6.90) )); then
		# lfs migrate file onto OST 0 if it is on OST 1, or onto
		# OST 1 if it is on OST 0. This file is small enough to
		# be on only one stripe.
		file=$dir/migr_1_ost
		dd bs=$dd_bs count=1 if=/dev/urandom of=$file >/dev/null 2>&1 ||
			error "write data into $file failed"
		local obdidx=$($LFS getstripe -i $file)
		local oldmd5=$(md5sum $file)
		local newobdidx=0

		(( obdidx != 0 )) || newobdidx=1
		cmd="$LFS migrate -i $newobdidx $file"
		echo $cmd
		eval $cmd || error "$cmd failed"

		local realobdix=$($LFS getstripe -i $file)
		local newmd5=$(md5sum $file)

		(( $newobdidx == $realobdix )) ||
			error "new OST is different (was=$obdidx, wanted=$newobdidx, got=$realobdix)"
		[[ "$oldmd5" == "$newmd5" ]] ||
			error "md5sum differ: $oldmd5, $newmd5"
	fi

	# lfs migrate works with lfs find
	cmd="$LFS find -stripe_count $expected -type f $dir -print0 |
	     $LFS migrate -0 -v -C $((expected * 2))"
	echo "$cmd"
	eval $cmd || error "$cmd failed"

	for (( i = 2; i <= NUMFILES; i++ )); do
		check_stripe_count $dir/file$i $((expected * 2))
	done
	for (( i = 2; i <= NUMDIRS; i++ )); do
		for (( j = 1; j <= NUMFILES; j++ )); do
			check_stripe_count $dir/dir$i/file$j $((expected * 2))
		done
	done
}
run_test 56wa "check 'lfs migrate -c stripe_count' works"

test_56wb() {
	local file1=$DIR/$tdir/file1
	local initial_pool=$($LFS getstripe -p $DIR)
	local pool_list=()
	local pool=""

	echo -n "Creating test dir..."
	test_mkdir $DIR/$tdir &> /dev/null || error "cannot create dir"
	echo "done."

	echo -n "Creating test file..."
	touch $file1 || error "cannot create file"
	echo "done."

	echo -n "Detecting existing pools..."
	pool_list=($($LFS pool_list $FSNAME | grep "$FSNAME\." | cut -d. -f2))

	if [ ${#pool_list[@]} -gt 0 ]; then
		echo "${pool_list[@]}"
		for thispool in "${pool_list[@]}"; do
			if [[ -z "$initial_pool" ||
			      "$initial_pool" != "$thispool" ]]; then
				pool="$thispool"
				echo "Using existing pool '$pool'"
				break
			fi
		done
	else
		echo "none detected."
	fi
	if [ -z "$pool" ]; then
		pool=${POOL:-testpool}
		[ "$initial_pool" = "$pool" ] && pool="testpool2"
		echo -n "Creating pool '$pool'..."
		create_pool $FSNAME.$pool ||
			error "create OST pool $pool failed"
		echo "done."

		echo -n "Adding target to pool..."
		pool_add_targets $pool 0 0 1 &> /dev/null ||
			error "pool_add_targets failed"
		echo "done."
	fi

	echo -n "Setting pool using -p option..."
	$LFS migrate -p $pool $file1 ||
		error "migrate failed rc = $?"
	echo "done."

	echo -n "Verifying test file is in pool after migrating..."
	[ "$($LFS getstripe -p $file1)" = $pool ] ||
		error "file was not migrated to pool $pool"
	echo "done."

	echo -n "Removing test file from pool '$pool'..."
	# "lfs migrate $file" won't remove the file from the pool
	# until some striping information is changed.
	$LFS migrate -c 1 $file1 &> /dev/null ||
		error "cannot remove from pool"
	[[ -z "$($LFS getstripe --pool $file1)" ]] ||
		error "pool still set"
	echo "done."

	echo -n "Setting pool using --pool option..."
	$LFS migrate --pool $pool $file1 ||
		error "migrate failed rc = $?"
	echo "done."

	# Clean up
	rm -f $file1
}
run_test 56wb "check 'lfs migrate' pool support"

test_56wc() {
	local file1="$DIR/$tdir/$tfile"
	local md5
	local parent_ssize
	local parent_scount
	local cur_ssize
	local cur_scount
	local orig_ssize
	local new_scount
	local cur_comp

	echo -n "Creating test dir..."
	test_mkdir $DIR/$tdir &> /dev/null || error "cannot create dir"
	$LFS setstripe -S 1M -c 1 "$DIR/$tdir" &> /dev/null ||
		error "cannot set stripe by '-S 1M -c 1'"
	echo "done"

	echo -n "Setting initial stripe for test file..."
	$LFS setstripe -S 512K -c 1 "$file1" &> /dev/null ||
		error "cannot set stripe"
	cur_ssize=$($LFS getstripe -S "$file1")
	(( cur_ssize == 524288 )) || error "setstripe -S $cur_ssize != 524288"
	echo "done."

	dd if=/dev/urandom of=$file1 bs=1M count=12 || error "dd $file1 failed"
	stack_trap "rm -f $file1"
	md5="$(md5sum $file1)"

	# File currently set to -S 512K -c 1

	# Ensure -c and -S options are rejected when --restripe is set
	echo -n "Verifying incompatible options are detected..."
	$LFS migrate --restripe -c 1 "$file1" &&
		error "incompatible --restripe and -c options not detected"
	$LFS migrate --restripe -S 1M "$file1" &&
		error "incompatible --restripe and -S options not detected"
	$LFS migrate --restripe -p pool "$file1" &&
		error "incompatible --restripe and -p options not detected"
	$LFS migrate --restripe -E eof -c 1 "$file1" &&
		error "incompatible --restripe and -E options not detected"
	$LFS migrate --restripe -A "$file1" &&
		error "incompatible --restripe and -A options not detected"
	$LFS migrate -A -c 1 "$file1" &&
		error "incompatible -A and -c options not detected"
	$LFS migrate -A -E eof -c 1 "$file1" &&
		error "incompatible -A and -E options not detected"
	echo "done."

	# Ensure unrecognized options are passed through to 'lfs migrate'
	echo -n "Verifying -S option is passed through to lfs migrate..."
	$LFS migrate -S 1M "$file1" || error "migration failed"
	cur_ssize=$($LFS getstripe -S "$file1")
	(( cur_ssize == 1048576 )) || error "migrate -S $cur_ssize != 1048576"
	[[ "$(md5sum $file1)" == "$md5" ]] || error "file data has changed (1)"
	echo "done."

	# File currently set to -S 1M -c 1

	# Ensure long options are supported
	echo -n "Verifying long options supported..."
	$LFS migrate --non-block "$file1" ||
		error "long option without argument not supported"
	$LFS migrate --stripe-size 512K "$file1" ||
		error "long option with argument not supported"
	cur_ssize=$($LFS getstripe -S "$file1")
	(( cur_ssize == 524288 )) ||
		error "migrate --stripe-size $cur_ssize != 524288"
	[[ "$(md5sum $file1)" == "$md5" ]] || error "file data has changed (2)"
	echo "done."

	# File currently set to -S 512K -c 1

	if (( OSTCOUNT > 1 )); then
		echo -n "Verifying explicit stripe count can be set..."
		$LFS migrate -c 2 "$file1" || error "migrate failed"
		cur_scount=$($LFS getstripe -c "$file1")
		(( cur_scount == 2 )) || error "migrate -c $cur_scount != 2"
		[[ "$(md5sum $file1)" == "$md5" ]] ||
			error "file data has changed (3)"
		echo "done."
	fi

	# File currently set to -S 512K -c 1 or -S 512K -c 2

	# Ensure parent striping is used if -R is set, and no stripe
	# count or size is specified
	echo -n "Setting stripe for parent directory..."
	$LFS setstripe -S 2M -c 1 "$DIR/$tdir" &> /dev/null ||
		error "cannot set stripe '-S 2M -c 1'"
	[[ "$(md5sum $file1)" == "$md5" ]] || error "file data has changed (4)"
	echo "done."

	echo -n "Verifying restripe option uses parent stripe settings..."
	parent_ssize=$($LFS getstripe -S $DIR/$tdir 2>/dev/null)
	parent_scount=$($LFS getstripe -c $DIR/$tdir 2>/dev/null)
	$LFS migrate --restripe "$file1" || error "migrate failed"
	cur_ssize=$($LFS getstripe -S "$file1")
	(( cur_ssize == parent_ssize )) ||
		error "migrate --restripe stripe_size $cur_ssize != $parent_ssize"
	cur_scount=$($LFS getstripe -c "$file1")
	(( cur_scount == parent_scount )) ||
		error "migrate -R stripe_count $cur_scount != $parent_scount"
	[[ "$(md5sum $file1)" == "$md5" ]] || error "file data has changed (5)"
	echo "done."

	# File currently set to -S 1M -c 1

	# Ensure striping is preserved if -R is not set, and no stripe
	# count or size is specified
	echo -n "Verifying striping size preserved when not specified..."
	orig_ssize=$($LFS getstripe -S "$file1" 2>/dev/null)
	$LFS setstripe -S 2M -c 1 "$DIR/$tdir" &> /dev/null ||
		error "cannot set stripe on parent directory"
	$LFS migrate "$file1" || error "migrate failed"
	cur_ssize=$($LFS getstripe -S "$file1")
	(( cur_ssize == orig_ssize )) ||
		error "migrate by default $cur_ssize != $orig_ssize"
	[[ "$(md5sum $file1)" == "$md5" ]] || error "file data has changed (6)"
	echo "done."

	# Ensure file name properly detected when final option has no argument
	echo -n "Verifying file name properly detected..."
	$LFS migrate "$file1" ||
		error "file name interpreted as option argument"
	[[ "$(md5sum $file1)" == "$md5" ]] || error "file data has changed (7)"
	echo "done."

	# Ensure PFL arguments are passed through properly
	echo -n "Verifying PFL options passed through..."
	new_scount=$(((OSTCOUNT + 1) / 2))
	$LFS migrate -E 1M -c 1 -E 16M -c $new_scount -E eof -c -1 "$file1" ||
		error "migrate PFL arguments failed"
	cur_comp=$($LFS getstripe --comp-count $file1)
	(( cur_comp == 3 )) || error "component count '$cur_comp' != 3"
	cur_scount=$($LFS getstripe --stripe-count $file1)
	(( cur_scount == new_scount)) ||
		error "PFL stripe count $cur_scount != $new_scount"
	[[ "$(md5sum $file1)" == "$md5" ]] || error "file data has changed (8)"
	echo "done."
}
run_test 56wc "check unrecognized options for lfs migrate are passed through"

test_56wd() {
	(( $CLIENT_VERSION < $(version_code 2.20.53) )) ||
		skip "lfs_migrate is not supported starting with Lustre 2.20.53"

	(( $OSTCOUNT >= 2 )) || skip "needs >= 2 OSTs"

	local file1=$DIR/$tdir/$tfile

	echo -n "Creating test dir..."
	test_mkdir $DIR/$tdir || error "cannot create dir"
	echo "done."

	echo -n "Creating test file..."
	echo "$tfile" > $file1
	echo "done."

	# Ensure 'lfs migrate' will fail by using a non-existent option,
	# and make sure rsync is not called to recover
	echo -n "Make sure --no-rsync option works..."
	$LFS_MIGRATE -y --no-rsync --invalid-opt $file1 2>&1 |
		grep -q 'refusing to fall back to rsync' ||
		error "rsync was called with --no-rsync set"
	echo "done."

	# Ensure rsync is called without trying 'lfs migrate' first
	echo -n "Make sure --rsync option works..."
	$LFS_MIGRATE -y --rsync --invalid-opt $file1 2>&1 |
		grep -q 'falling back to rsync' &&
		error "lfs migrate was called with --rsync set"
	echo "done."
}
run_test 56wd "check lfs_migrate --rsync and --no-rsync work"

test_56we() {
	local td=$DIR/$tdir
	local tf=$td/$tfile

	test_mkdir $td || error "cannot create $td"
	touch $tf || error "cannot touch $tf"

	echo -n "Make sure --non-direct|-D works..."
	$LFS migrate --non-direct -v $tf 2>&1 |
		grep -q "$tf" ||
		error "--non-direct option cannot work correctly"
	$LFS migrate -D -v $tf 2>&1 |
		grep -q "$tf" ||
		error "-D option cannot work correctly"
	echo "done."
}
run_test 56we "check lfs migrate --non-direct|-D support"

test_56x() {
	[[ $OSTCOUNT -lt 2 ]] && skip_env "needs >= 2 OSTs"
	check_swap_layouts_support

	local dir=$DIR/$tdir
	local ref1=/etc/passwd
	local file1=$dir/file1

	test_mkdir $dir || error "creating dir $dir"
	$LFS setstripe -c 2 $file1
	cp $ref1 $file1
	$LFS migrate -c 1 $file1 || error "migrate failed rc = $?"
	stripe=$($LFS getstripe -c $file1)
	[[ $stripe == 1 ]] || error "stripe of $file1 is $stripe != 1"
	cmp $file1 $ref1 || error "content mismatch $file1 differs from $ref1"

	# clean up
	rm -f $file1
}
run_test 56x "lfs migration support"

test_56xB() {
	local td=$DIR/$tdir
	local tf1=$td/${tfile}_1
	local tf2=$td/${tfile}_2
	local tf3=$td/${tfile}_3
	local flist=/tmp/flist.$$

	(( $OSTCOUNT >= 2 )) || skip "needs >= 2 OSTs"

	test_mkdir $td
	dd if=/dev/urandom of=$tf1 bs=1K count=1 || error "failed to create $tf1"
	dd if=/dev/urandom of=$tf2 bs=1K count=1 || error "failed to create $tf2"
	dd if=/dev/urandom of=$tf3 bs=1K count=1 || error "failed to create $tf3"

	stack_trap "rm -f $flist"

	$LFS find $td -type f > $flist || error "failed to generate list file"
	$LFS migrate -o 0 --files-from=$flist ||
		error "failed to run lfs migrate with --files-from"

	$LFS find $td -type f -print0 | $LFS migrate -o 1 --null ||
		error "failed to run lfs migrate from pipe"

	$LFS find $td -type f -print0 > $flist ||
		error "failed to generate 0-ending list file"
	$LFS migrate -o 0 -0 --files-from=$flist ||
		error "failed to run lfs migrate with -0 --files-from"
}
run_test 56xB "lfs migrate with -0, --null, --files-from arguments"

test_56xC() {
	local td=$DIR/$tdir
	local tf1=$td/${tfile}_1
	local tf2=$td/${tfile}_2
	local tf3=$td/${tfile}_3
	local fidlist=/tmp/fidlist.$$
	local stripe_count
	local stripe_size

	(( $OSTCOUNT >= 2 )) || skip "needs >= 2 OSTs"

	test_mkdir $td
	dd if=/dev/urandom of=$tf1 bs=1K count=1 || error "failed to create $tf1"
	dd if=/dev/urandom of=$tf2 bs=1K count=1 || error "failed to create $tf2"
	$LFS setstripe --stripe-size=3M -C 7 $tf3
	dd if=/dev/urandom of=$tf3 bs=1K count=1 || error "failed to create $tf3"
	$LFS getstripe $tf3

	stack_trap "rm -f $fidlist"
	$LFS path2fid $tf1 $tf2 $tf3 | awk '{print $2}' > $fidlist ||
		error "failed to get fids of $tf1 $tf2 $tf3"

	echo "================ fidlist ======================="
	cat $fidlist
	echo "================================================"
	$LFS migrate -o 0 --lustre-dir=$DIR --fid --files-from=$fidlist ||
		error "migrate -o 0 failed with --fid and --lustre-dir"

	mount
	echo "without --lustre-dir opiton"
	$LFS migrate --stripe-size=2M -o 1 --fid --files-from=$fidlist ||
		error "failed to run lfs migrate with --fid argument"

	$LFS getstripe $tf3
	stripe_count=$($LFS getstripe --stripe-count $tf3)
	stripe_size=$($LFS getstripe --stripe-size $tf3)

	(( $stripe_count == 1 )) ||
		error "unexpected stripe count $stripe_count"
	(( $stripe_size == 2 * 1024 * 1024 )) ||
		error "unexpected stripe size $stripe_size"
}
run_test 56xC "lfs migration can accept FID list file"

test_56xD() {
	local td=$DIR/$tdir
	local tf1=$td/${tfile}_1
	local tf2=$td/${tfile}_2
	local tf3=$td/${tfile}_3
	local fids
	local stripe_count
	local stripe_size

	(( $OSTCOUNT >= 2 )) || skip "needs >= 2 OSTs"

	test_mkdir $td
	dd if=/dev/urandom of=$tf1 bs=1K count=1 || error "failed to create $tf1"
	dd if=/dev/urandom of=$tf2 bs=1K count=1 || error "failed to create $tf2"
	dd if=/dev/urandom of=$tf3 bs=1K count=1 || error "failed to create $tf3"

	stack_trap "rm -f $fidlist"
	fids=$($LFS path2fid $tf1 $tf2 $tf3 | awk '{printf "%s ", $2}' |
		tr -d '[]') ||
		error "failed to get fids of $tf1 $tf2 $tf3"

	echo "FIDs: $fids"
	echo "with --lustre-dir option"
	$LFS migrate -o 0 --lustre-dir $DIR --fid $fids||
		error "failed to run lfs migrate with --fid and --lustre-dir argument"

	echo "without --lustre-dir option"
	$LFS migrate -o 1 -S 2M --fid $fids||
		error "failed to run lfs migrate with --fid argument"

	$LFS getstripe $tf3
	stripe_count=$($LFS getstripe --stripe-count $tf3)
	stripe_size=$($LFS getstripe --stripe-size $tf3)

	(( $stripe_count == 1 )) ||
		error "unexpected stripe count $stripe_count"
	(( $stripe_size == 2 * 1024 * 1024 )) ||
		error "unexpected stripe size $stripe_size"
}
run_test 56xD "lfs_migration can accept FIDs"

test_56xa() {
	(( $OSTCOUNT >= 2 )) || skip_env "needs >= 2 OSTs"
	check_swap_layouts_support

	local dir=$DIR/$tdir/$testnum

	test_mkdir -p $dir

	local ref1=/etc/passwd
	local file1=$dir/file1

	$LFS setstripe -c 2 $file1
	cp $ref1 $file1
	$LFS migrate --block -c 1 $file1 || error "migrate failed rc = $?"

	local stripe=$($LFS getstripe -c $file1)

	[[ $stripe == 1 ]] || error "stripe of $file1 is $stripe != 1"
	cmp $file1 $ref1 || error "content mismatch $file1 differs from $ref1"

	# clean up
	rm -f $file1
}
run_test 56xa "lfs migration --block support"

test_56xab() {
	local pid
	local dir=$DIR/$tdir/$testnum
	local file1=$dir/$tfile

	(( $OSTCOUNT >= 2 )) || skip_env "needs >= 2 OSTs"
	check_swap_layouts_support

	test_mkdir -p $dir
	$LFS setstripe -c 2 $file1

	dd if=/dev/urandom of=$file1 bs=1 oflag=sync & pid=$!
	kill -0 $pid ||
		error "failed to start dd to write to $file1 continously"
	stack_trap "kill $pid"
	sleep 1

	$LFS migrate --block -c 1 $file1 || error "migrate failed rc = $?"

	ls -l $file1
	$LFS getstripe $file1
}
run_test 56xab "lfs migration --block on changing file"

check_migrate_links() {
	[[ "$1" == "--rsync" ]] && local opts="--rsync -y" && shift
	local dir="$1"
	local file1="$dir/file1"
	local begin="$2"
	local count="$3"
	local runas="$4"
	local total_count=$(($begin + $count - 1))
	local symlink_count=10
	local uniq_count=10

	if [ ! -f "$file1" ]; then
		echo -n "creating initial file..."
		$LFS setstripe -c 1 -S "512k" "$file1" ||
			error "cannot setstripe initial file"
		echo "done"

		echo -n "creating symlinks..."
		for s in $(seq 1 $symlink_count); do
			ln -s "$file1" "$dir/slink$s" ||
				error "cannot create symlinks"
		done
		echo "done"

		echo -n "creating nonlinked files..."
		createmany -o "$dir/uniq" 1 10 &> /dev/null ||
			error "cannot create nonlinked files"
		echo "done"
	fi

	# create hard links
	if [ ! -f "$dir/file$total_count" ]; then
		echo -n "creating hard links $begin:$total_count..."
		createmany -l"$file1" "$dir/file" "$begin" "$count" &>	\
			/dev/null || error "cannot create hard links"
		echo "done"
	fi

	echo -n "checking number of hard links listed in xattrs..."
	local fid=$($LFS getstripe -F "$file1")
	local paths=($($LFS fid2path "$MOUNT" "$fid" 2> /dev/null))

	echo "${#paths[*]}"
	if [ ${#paths[*]} -lt $total_count -a "$begin" -eq 2  ]; then
			skip "hard link list has unexpected size, skipping test"
	fi
	if [ ${#paths[*]} -ge $total_count -a "$begin" -ne 2  ]; then
			error "link names should exceed xattrs size"
	fi

	echo -n "migrating files..."
	local migrate_out=$($runas $LFS_MIGRATE $opts -S '1m' $dir)
	local rc=$?
	[ $rc -eq 0 ] || error "migrate failed rc = $rc"
	echo "done"

	# make sure all links have been properly migrated
	echo -n "verifying files..."
	fid=$($LFS getstripe -F "$file1") ||
		error "cannot get fid for file $file1"
	for i in $(seq 2 $total_count); do
		local fid2=$($LFS getstripe -F $dir/file$i)

		[ "$fid2" == "$fid" ] ||
			error "migrated hard link has mismatched FID"
	done

	# make sure hard links were properly detected, and migration was
	# performed only once for the entire link set; nonlinked files should
	# also be migrated
	local actual=$(grep -c 'done' <<< "$migrate_out")
	local expected=$(($uniq_count + 1))

	[ "$actual" -eq  "$expected" ] ||
		error "hard links individually migrated ($actual != $expected)"

	# make sure the correct number of hard links are present
	local hardlinks=$(stat -c '%h' "$file1")

	[ $hardlinks -eq $total_count ] ||
		error "num hard links $hardlinks != $total_count"
	echo "done"

	return 0
}

test_56xb() {
	(( $CLIENT_VERSION < $(version_code 2.20.53) )) ||
		skip "lfs_migrate is not supported starting with Lustre 2.20.53"

	[ $MDS1_VERSION -lt $(version_code 2.10.55) ] &&
		skip "Need MDS version at least 2.10.55"

	local dir="$DIR/$tdir"

	test_mkdir "$dir" || error "cannot create dir $dir"

	echo "testing lfs migrate mode when all links fit within xattrs"
	check_migrate_links "$dir" 2 99

	echo "testing rsync mode when all links fit within xattrs"
	check_migrate_links --rsync "$dir" 2 99

	echo "testing lfs migrate mode when all links do not fit within xattrs"
	check_migrate_links "$dir" 101 100

	echo "testing rsync mode when all links do not fit within xattrs"
	check_migrate_links --rsync "$dir" 101 100

	chown -R $RUNAS_ID $dir
	echo "testing non-root lfs migrate mode when not all links are in xattr"
	check_migrate_links "$dir" 101 100 "$RUNAS -G0"

	# clean up
	rm -rf $dir
}
run_test 56xb "lfs migration hard link support"

test_56xc() {
	[[ $OSTCOUNT -lt 2 ]] && skip_env "needs >= 2 OSTs"

	local dir="$DIR/$tdir"

	test_mkdir "$dir" || error "cannot create dir $dir"

	# Test 1: ensure file < 1 GB is always migrated with 1 stripe
	echo -n "Setting initial stripe for 20MB test file..."
	$LFS setstripe -c 2 -i 0 "$dir/20mb" ||
		error "cannot setstripe 20MB file"
	echo "done"
	echo -n "Sizing 20MB test file..."
	$TRUNCATE "$dir/20mb" 20971520 || error "cannot create 20MB test file"
	echo "done"
	echo -n "Verifying small file autostripe count is 1..."
	$LFS migrate -A -K 1 "$dir/20mb" ||
		error "cannot migrate 20MB file"
	local stripe_count=$($LFS getstripe -c "$dir/20mb") ||
		error "cannot get stripe for $dir/20mb"
	[ $stripe_count -eq 1 ] ||
		error "unexpected stripe count $stripe_count for 20MB file"
	rm -f "$dir/20mb"
	echo "done"

	# Test 2: File is small enough to fit within the available space on
	# sqrt(size_in_gb) + 1 OSTs but is larger than 1GB.  The file must
	# have at least an additional 1KB for each desired stripe for test 3
	echo -n "Setting stripe for 1GB test file..."
	$LFS setstripe -c 1 -i 0 "$dir/1gb" || error "cannot setstripe 1GB file"
	echo "done"
	echo -n "Sizing 1GB test file..."
	# File size is 1GB + 3KB
	$TRUNCATE "$dir/1gb" 1073744896 || error "cannot create 1GB test file"
	echo "done"

	# need at least 512MB per OST for 1GB file to fit in 2 stripes
	local avail=$($LCTL get_param -n llite.$FSNAME*.kbytesavail)
	if (( avail > 524288 * OSTCOUNT )); then
		echo -n "Migrating 1GB file..."
		$LFS migrate -A -K 1 "$dir/1gb" ||
			error "cannot migrate 1GB file"
		echo "done"
		echo -n "Verifying autostripe count is sqrt(n) + 1..."
		stripe_count=$($LFS getstripe -c "$dir/1gb") ||
			error "cannot getstripe for 1GB file"
		[ $stripe_count -eq 2 ] ||
			error "unexpected stripe count $stripe_count != 2"
		echo "done"
	fi

	# Test 3: File is too large to fit within the available space on
	# sqrt(n) + 1 OSTs.  Simulate limited available space with -X
	if [ $OSTCOUNT -ge 3 ]; then
		# The required available space is calculated as
		# file size (1GB + 3KB) / OST count (3).
		local kb_per_ost=349526

		echo -n "Migrating 1GB file with limit..."
		$LFS migrate -A -K 1 -X $kb_per_ost "$dir/1gb" ||
			error "cannot migrate 1GB file with limit"
		echo "done"

		stripe_count=$($LFS getstripe -c "$dir/1gb")
		echo -n "Verifying 1GB autostripe count with limited space..."
		[ "$stripe_count" -a $stripe_count -ge 3 ] ||
			error "unexpected stripe count $stripe_count (min 3)"
		echo "done"
	fi

	# clean up
	rm -rf $dir
}
run_test 56xc "lfs migration autostripe"

test_56xd() {
	[[ $OSTCOUNT -lt 2 ]] && skip_env "needs >= 2 OSTs"

	local dir=$DIR/$tdir
	local f_mgrt=$dir/$tfile.mgrt
	local f_yaml=$dir/$tfile.yaml
	local f_copy=$dir/$tfile.copy
	local layout_yaml="-E 1M -S 512K -c 1 -E -1 -S 1M -c 2 -i 0"
	local layout_copy="-c 2 -S 2M -i 1"
	local yamlfile=$dir/yamlfile
	local layout_before;
	local layout_after;

	test_mkdir "$dir" || error "cannot create dir $dir"
	stack_trap "rm -rf $dir"
	$LFS setstripe $layout_yaml $f_yaml ||
		error "cannot setstripe $f_yaml with layout $layout_yaml"
	$LFS getstripe --yaml $f_yaml > $yamlfile
	$LFS setstripe $layout_copy $f_copy ||
		error "cannot setstripe $f_copy with layout $layout_copy"
	touch $f_mgrt
	dd if=/dev/zero of=$f_mgrt bs=1M count=4

	# 1. test option --yaml
	$LFS migrate --yaml $yamlfile $f_mgrt ||
		error "cannot migrate $f_mgrt with --yaml $yamlfile"
	layout_before=$(get_layout_param $f_yaml)
	layout_after=$(get_layout_param $f_mgrt)
	[ "$layout_after" == "$layout_before" ] ||
		error "lfs migrate --yaml: $layout_after != $layout_before"

	# 2. test option --copy
	$LFS migrate --copy $f_copy $f_mgrt ||
		error "cannot migrate $f_mgrt with --copy $f_copy"
	layout_before=$(SKIP_INDEX=yes get_layout_param $f_copy)
	layout_after=$(SKIP_INDEX=yes get_layout_param $f_mgrt)
	[ "$layout_after" == "$layout_before" ] ||
		error "lfs migrate --copy: $layout_after != $layout_before"
}
run_test 56xd "check lfs migrate --yaml and --copy support"

test_56xe() {
	(( $OSTCOUNT >= 2 )) || skip_env "needs >= 2 OSTs"

	local dir=$DIR/$tdir
	local f_comp=$dir/$tfile
	local layout="-E 1M -S 512K -E 2M -c 2 -E 3M -E eof -c $((OSTCOUNT-1))"
	local layout_before=""
	local layout_after=""

	test_mkdir "$dir" || error "cannot create dir $dir"
	stack_trap "rm -rf $dir"
	$LFS setstripe $layout $f_comp ||
		error "cannot setstripe $f_comp with layout $layout"
	layout_before=$(SKIP_INDEX=yes get_layout_param $f_comp)
	dd if=/dev/zero of=$f_comp bs=1M count=4

	# extract starting OST index of each component before migration
	idxs_before=$($LFS getstripe $f_comp | awk '$2 == "0:" { print $5 }' |
		      tr '\n' ' ')

	# migrate a comp layout file by lfs migrate
	$LFS migrate $f_comp || error "cannot migrate $f_comp by lfs migrate"
	layout_after=$(SKIP_INDEX=yes get_layout_param $f_comp)
	# extract starting OST index of each component after migration
	idxs_after=$($LFS getstripe $f_comp | awk '$2 == "0:" { print $5 }' |
		     tr '\n' ' ')
	[ "$layout_before" == "$layout_after" ] ||
		error "lfs migrate: layout $layout_before != $layout_after"

	# compare starting indexes of all components before/after migration.
	# this may not fail every time with a broken lfs migrate, but will fail
	# often enough to notice, and will not have false positives very often
	[[ "$idxs_before" != "$idxs_after" ]] ||
		error "lfs migrate: indexes $idxs_before == $idxs_after"
}
run_test 56xe "migrate a composite layout file"

test_56xf() {
	[[ $OSTCOUNT -ge 2 ]] || skip_env "needs >= 2 OSTs"

	[[ $MDS1_VERSION -ge $(version_code 2.13.53) ]] ||
		skip "Need server version at least 2.13.53"

	local dir=$DIR/$tdir
	local f_comp=$dir/$tfile
	local layout="-E 1M -c1 -E -1 -c2"
	local fid_before=""
	local fid_after=""

	test_mkdir "$dir" || error "cannot create dir $dir"
	stack_trap "rm -rf $dir"
	$LFS setstripe $layout $f_comp ||
		error "cannot setstripe $f_comp with layout $layout"
	fid_before=$($LFS getstripe --fid $f_comp)
	dd if=/dev/zero of=$f_comp bs=1M count=4

	# 1. migrate a comp layout file to a comp layout
	$LFS migrate $f_comp || error "cannot migrate $f_comp by lfs migrate"
	fid_after=$($LFS getstripe --fid $f_comp)
	[ "$fid_before" == "$fid_after" ] ||
		error "comp-to-comp migrate: $fid_before != $fid_after"

	# 2. migrate a comp layout file to a plain layout
	$LFS migrate -c2 $f_comp ||
		error "cannot migrate $f_comp by lfs migrate"
	fid_after=$($LFS getstripe --fid $f_comp)
	[ "$fid_before" == "$fid_after" ] ||
		error "comp-to-plain migrate: $fid_before != $fid_after"

	# 3. migrate a plain layout file to a comp layout
	$LFS migrate $layout $f_comp ||
		error "cannot migrate $f_comp by lfs migrate"
	fid_after=$($LFS getstripe --fid $f_comp)
	[ "$fid_before" == "$fid_after" ] ||
		error "plain-to-comp migrate: $fid_before != $fid_after"
}
run_test 56xf "FID is not lost during migration of a composite layout file"

check_file_ost_range() {
	local file="$1"
	shift
	local range="$*"
	local -a file_range
	local idx

	file_range=($($LFS getstripe -y "$file" |
		awk '/l_ost_idx:/ { print $NF }'))

	if [[ "${#file_range[@]}" = 0 ]]; then
		echo "No osts found for $file"
		return 1
	fi

	for idx in "${file_range[@]}"; do
		[[ " $range " =~ " $idx " ]] ||
			return 1
	done

	return 0
}

sub_test_56xg() {
	local stripe_opt="$1"
	local pool="$2"
	shift 2
	local pool_ostidx="$(seq $* | tr '\n' ' ')"

	$LFS migrate $stripe_opt -p $pool $DIR/$tfile ||
		error "Fail to migrate $tfile on $pool"
	[[ "$($LFS getstripe -p $DIR/$tfile)" = "$pool" ]] ||
		error "$tfile is not in pool $pool"
	check_file_ost_range "$DIR/$tfile" $pool_ostidx ||
		error "$tfile osts mismatch with pool $pool (osts $pool_ostidx)"
}

test_56xg() {
	[[ $PARALLEL != "yes" ]] || skip "skip parallel run"
	[[ $OSTCOUNT -ge 2 ]] || skip "needs >= 2 OSTs"
	[[ $MDS1_VERSION -gt $(version_code 2.14.52) ]] ||
		skip "Need MDS version newer than 2.14.52"

	local -a pool_names=("${TESTNAME}_0" "${TESTNAME}_1" "${TESTNAME}_2")
	local -a pool_ranges=("0 0" "1 1" "0 1")

	# init pools
	for i in "${!pool_names[@]}"; do
		pool_add ${pool_names[$i]} ||
			error "pool_add failed (pool: ${pool_names[$i]})"
		pool_add_targets ${pool_names[$i]} ${pool_ranges[$i]} ||
			error "pool_add_targets failed (pool: ${pool_names[$i]})"
	done

	# init the file to migrate
	$LFS setstripe -c1 -i1 $DIR/$tfile ||
		error "Unable to create $tfile on OST1"
	stack_trap "rm -f $DIR/$tfile"
	dd if=/dev/urandom of=$DIR/$tfile bs=1M count=4 status=none ||
		error "Unable to write on $tfile"

	echo "1. migrate $tfile on pool ${pool_names[0]}"
	sub_test_56xg "-c-1" "${pool_names[0]}" ${pool_ranges[0]}

	echo "2. migrate $tfile on pool ${pool_names[2]}"
	sub_test_56xg "-c-1 -S2M" "${pool_names[2]}" ${pool_ranges[2]}

	echo "3. migrate $tfile on pool ${pool_names[1]}"
	sub_test_56xg "-n -c-1" "${pool_names[1]}" ${pool_ranges[1]}

	echo "4. migrate $tfile on pool ${pool_names[2]} with default stripe parameters"
	sub_test_56xg "" "${pool_names[2]}" ${pool_ranges[2]}
	echo

	# Clean pools
	destroy_test_pools ||
		error "pool_destroy failed"
}
run_test 56xg "lfs migrate pool support"

test_56xh() {
	(( $OSTCOUNT >= 2 )) || skip "needs >= 2 OSTs"

	local size_mb=25
	local file1=$DIR/$tfile
	local tmp1=$TMP/$tfile.tmp

	$LFS setstripe -c 2 $file1

	stack_trap "rm -f $file1 $tmp1"
	dd if=/dev/urandom of=$tmp1 bs=1M count=$size_mb ||
			error "error creating $tmp1"
	ls -lsh $tmp1
	cp $tmp1 $file1

	local start=$SECONDS

	$LFS migrate --stats --stats-interval=1 -W 1M -c 1 $file1 ||
		error "migrate failed rc = $?"

	local elapsed=$((SECONDS - start))

	# with 1MB/s, elapsed should equal size_mb
	(( elapsed >= size_mb * 95 / 100 )) ||
		error "'lfs migrate -W' too fast ($elapsed < 0.95 * $size_mb)?"

	(( elapsed <= size_mb * 120 / 100 )) ||
		error_not_in_vm "'lfs migrate -W' slow ($elapsed > 1.2 * $size_mb)"

	(( elapsed <= size_mb * 350 / 100 )) ||
		error "'lfs migrate -W' too slow in VM ($elapsed > 3.5 * $size_mb)"

	stripe=$($LFS getstripe -c $file1)
	(( $stripe == 1 )) || error "stripe of $file1 is $stripe != 1"
	cmp $file1 $tmp1 || error "content mismatch $file1 differs from $tmp1"

	# Clean up file (since it is multiple MB)
	rm -f $file1 $tmp1
}
run_test 56xh "lfs migrate bandwidth limitation support"

test_56xi() {
	(( $OSTCOUNT >= 2 )) || skip "needs >= 2 OSTs"

	local size_mb=5
	local file1=$DIR/$tfile.1
	local file2=$DIR/$tfile.2
	local file3=$DIR/$tfile.3
	local output_file=$DIR/$tfile.out
	local tmp1=$TMP/$tfile.tmp

	$LFS setstripe -c 2 $file1
	$LFS setstripe -c 2 $file2
	$LFS setstripe -c 2 $file3

	stack_trap "rm -f $file1 $file2 $file3 $tmp1 $output_file"
	dd if=/dev/urandom of=$tmp1 bs=1M count=$size_mb ||
			error "error creating $tmp1"
	ls -lsh $tmp1
	cp $tmp1 $file1
	cp $tmp1 $file2
	cp $tmp1 $file3

	$LFS migrate --stats --stats-interval=1 \
		-c 1 $file1 $file2 $file3 1> $output_file ||
		error "migrate failed rc = $?"

	cat $output_file
	verify_yaml_available || skip_env "YAML verification not installed"
	verify_yaml < $output_file || error "rename_stats is not valid YAML"
}
run_test 56xi "lfs migrate stats support"

test_56xj() { # LU-16571 "lfs migrate -b" can cause thread starvation on OSS
	(( $OSTCOUNT >= 2 )) || skip "needs >= 2 OSTs"

	local file=$DIR/$tfile
	local linkdir=$DIR/$tdir

	test_mkdir $linkdir || error "fail to create $linkdir"
	$LFS setstripe -i 0 -c 1 -S1M $file
	stack_trap "rm -rf $file $linkdir"
	dd if=/dev/urandom of=$file bs=1M count=10 ||
		error "fail to create $file"

	# Create file links
	local cpts
	local threads_max
	local nlinks

	thread_max=$(do_facet ost1 "$LCTL get_param -n ost.OSS.ost.threads_max")
	cpts=$(do_facet ost1 "$LCTL get_param -n cpu_partition_table | wc -l")
	(( nlinks = thread_max * 3 / 2 / cpts))

	echo "create $nlinks hard links of $file"
	createmany -l $file $linkdir/link $nlinks

	# Parallel migrates (should not block)
	local i
	for ((i = 0; i < nlinks; i++)); do
		echo $linkdir/link$i
	done | xargs -n1 -P $nlinks $LFS migrate -c2

	local stripe_count
	stripe_count=$($LFS getstripe -c $file) ||
		error "fail to get stripe count on $file"

	((stripe_count == 2)) ||
		error "fail to migrate $file (stripe_count = $stripe_count)"
}
run_test 56xj "lfs migrate -b should not cause starvation of threads on OSS"

test_56xk() {
	(( $OSTCOUNT >= 2 )) || skip "needs >= 2 OSTs"

	local size_mb=5
	local file1=$DIR/$tfile

	stack_trap "rm -f $file1"
	$LFS setstripe -c 1 $file1
	dd if=/dev/zero of=$file1 bs=1M count=$size_mb ||
		error "error creating $file1"
	$LFS mirror extend -N $file1 || error "can't mirror"
	dd if=/dev/zero of=$file1 bs=4k count=1 conv=notrunc ||
		error "can't dd"
	$LFS getstripe $file1 | grep stale ||
		error "one component must be stale"

	local start=$SECONDS
	$LFS mirror resync --stats --stats-interval=1 -W 1M $file1 ||
		error "migrate failed rc = $?"
	local elapsed=$((SECONDS - start))
	$LFS getstripe $file1 | grep stale &&
		error "all components must be sync"

	# with 1MB/s, elapsed should equal size_mb
	(( elapsed >= size_mb * 95 / 100 )) ||
		error "'lfs mirror resync -W' too fast ($elapsed < 0.95 * $size_mb)?"

	(( elapsed <= size_mb * 120 / 100 )) ||
		error_not_in_vm "'lfs mirror resync -W' slow ($elapsed > 1.2 * $size_mb)"

	(( elapsed <= size_mb * 350 / 100 )) ||
		error "'lfs mirror resync -W' too slow in VM ($elapsed > 3.5 * $size_mb)"
}
run_test 56xk "lfs mirror resync bandwidth limitation support"

test_56xl() {
	(( $OSTCOUNT >= 2 )) || skip "needs >= 2 OSTs"

	local size_mb=5
	local file1=$DIR/$tfile.1
	local output_file=$DIR/$tfile.out

	stack_trap "rm -f $file1"
	$LFS setstripe -c 1 $file1
	dd if=/dev/zero of=$file1 bs=1M count=$size_mb ||
		error "error creating $file1"
	$LFS mirror extend -N $file1 || error "can't mirror"
	dd if=/dev/zero of=$file1 bs=4k count=1 conv=notrunc ||
		error "can't dd"
	$LFS getstripe $file1 | grep stale ||
		error "one component must be stale"
	$LFS getstripe $file1

	$LFS mirror resync --stats --stats-interval=1 $file1 >$output_file ||
		error "resync failed rc = $?"
	$LFS getstripe $file1 | grep stale &&
		error "all components must be sync"

	cat $output_file
	verify_yaml_available || skip_env "YAML verification not installed"
	verify_yaml < $output_file || error "stats is not valid YAML"
}
run_test 56xl "lfs mirror resync stats support"

test_56y() {
	[ $MDS1_VERSION -lt $(version_code 2.4.53) ] &&
		skip "No HSM $(lustre_build_version $SINGLEMDS) MDS < 2.4.53"

	local res=""
	local dir=$DIR/$tdir
	local f1=$dir/file1
	local f2=$dir/file2

	test_mkdir -p $dir || error "creating dir $dir"
	touch $f1 || error "creating std file $f1"
	$MULTIOP $f2 H2c || error "creating released file $f2"

	# a directory can be raid0, so ask only for files
	res=$($LFS find $dir -L raid0 -type f | wc -l)
	[[ $res == 2 ]] || error "search raid0: found $res files != 2"

	res=$($LFS find $dir \! -L raid0 -type f | wc -l)
	[[ $res == 0 ]] || error "search !raid0: found $res files != 0"

	# only files can be released, so no need to force file search
	res=$($LFS find $dir -L released)
	[[ $res == $f2 ]] || error "search released: found $res != $f2"

	res=$($LFS find $dir -type f \! -L released)
	[[ $res == $f1 ]] || error "search !released: found $res != $f1"
}
run_test 56y "lfs find -L raid0|released"

test_56z() { # LU-4824
	# This checks to make sure 'lfs find' continues after errors
	# There are two classes of errors that should be caught:
	# - If multiple paths are provided, all should be searched even if one
	#   errors out
	# - If errors are encountered during the search, it should not terminate
	#   early
	local dir=$DIR/$tdir
	local i

	test_mkdir $dir
	for i in d{0..9}; do
		test_mkdir $dir/$i
		touch $dir/$i/$tfile
	done
	$LFS find $DIR/non_existent_dir $dir &&
		error "$LFS find did not return an error"
	# Make a directory unsearchable. This should NOT be the last entry in
	# directory order.  Arbitrarily pick the 6th entry
	chmod 700 $($LFS find $dir -type d | sed '6!d')

	$RUNAS $LFS find $DIR/non_existent $dir
	local count=$($RUNAS $LFS find $DIR/non_existent $dir | wc -l)

	# The user should be able to see 10 directories and 9 files
	(( count == 19 )) ||
		error "$LFS find found $count != 19 entries after error"
}
run_test 56z "lfs find should continue after an error"

test_56Aa() { # was test_56aa, LU-5937
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"

	local dir=$DIR/$tdir

	mkdir $dir
	$LFS setdirstripe -c$MDSCOUNT $dir/striped_dir

	createmany -o $dir/striped_dir/${tfile}- 1024
	local dirs=$($LFS find --size +7k $dir/)

	[ -n "$dirs" ] || error "lfs find --size wrong under striped dir"
}
run_test 56Aa "lfs find --size under striped dir"

test_56ab() { # LU-10705
	test_mkdir $DIR/$tdir
	dd if=/dev/urandom of=$DIR/$tdir/$tfile.1 bs=8k count=1 seek=2k
	dd if=/dev/urandom of=$DIR/$tdir/$tfile.2 bs=4k count=1 seek=4k
	dd if=/dev/urandom of=$DIR/$tdir/$tfile.3 bs=1M count=2 seek=16
	# Flush writes to ensure valid blocks.  Need to be more thorough for
	# ZFS, since blocks are not allocated/returned to client immediately.
	sync_all_data
	wait_zfs_commit ost1 2
	cancel_lru_locks osc
	ls -ls $DIR/$tdir

	local files=$($LFS find --size +16M $DIR/$tdir | wc -l)

	[[ $files == 3 ]] || error ">16M size files $files isn't 3 as expected"

	files=$($LFS find --blocks +1M $DIR/$tdir | wc -l)
	[[ $files == 1 ]] || error ">1M blocks files $files isn't 1 as expected"

	rm -f $DIR/$tdir/$tfile.[123]
}
run_test 56ab "lfs find --blocks"

# LU-11188
test_56aca() {
	local dir="$DIR/$tdir"
	local perms=(001 002 003 004 005 006 007
		     010 020 030 040 050 060 070
		     100 200 300 400 500 600 700
		     111 222 333 444 555 666 777)
	local perm_minus=(8 8 4 8 4 4 2
			  8 8 4 8 4 4 2
			  8 8 4 8 4 4 2
			  4 4 2 4 2 2 1)
	local perm_slash=(8  8 12  8 12 12 14
			  8  8 12  8 12 12 14
			  8  8 12  8 12 12 14
			 16 16 24 16 24 24 28)

	test_mkdir "$dir"
	for perm in ${perms[*]}; do
		touch "$dir/$tfile.$perm"
		chmod $perm "$dir/$tfile.$perm"
	done

	for ((i = 0; i < ${#perms[*]}; i++)); do
		local num=$($LFS find $dir -perm ${perms[i]} | wc -l)
		(( $num == 1 )) ||
			error "lfs find -perm ${perms[i]}:"\
			      "$num != 1"

		num=$($LFS find $dir -perm -${perms[i]} -type f| wc -l)
		(( $num == ${perm_minus[i]} )) ||
			error "lfs find -perm -${perms[i]}:"\
			      "$num != ${perm_minus[i]}"

		num=$($LFS find $dir -perm /${perms[i]} -type f| wc -l)
		(( $num == ${perm_slash[i]} )) ||
			error "lfs find -perm /${perms[i]}:"\
			      "$num != ${perm_slash[i]}"
	done
}
run_test 56aca "check lfs find -perm with octal representation"

test_56acb() {
	local dir=$DIR/$tdir
	# p is the permission of write and execute for user, group and other
	# without the umask. It is used to test +wx.
	local p=$(printf "%o" "$((0333 & ~$(umask)))")
	local perms=(1000 000 2000 4000 $p 644 111 110 100 004)
	local symbolic=(+t  a+t u+t g+t o+t
			g+s u+s o+s +s o+sr
			o=r,ug+o,u+w
			u+ g+ o+ a+ ugo+
			u- g- o- a- ugo-
			u= g= o= a= ugo=
			o=r,ug+o,u+w u=r,a+u,u+w
			g=r,ugo=g,u+w u+x,+X +X
			u+x,u+X u+X u+x,g+X o+r,+X
			u+x,go+X +wx +rwx)

	test_mkdir $dir
	for perm in ${perms[*]}; do
		touch "$dir/$tfile.$perm"
		chmod $perm "$dir/$tfile.$perm"
	done

	for (( i = 0; i < ${#symbolic[*]}; i++ )); do
		local num=$($LFS find $dir -perm ${symbolic[i]} | wc -l)

		(( $num == 1 )) ||
			error "lfs find $dir -perm ${symbolic[i]}: $num != 1"
	done
}
run_test 56acb "check lfs find -perm with symbolic representation"

test_56acc() {
	local dir=$DIR/$tdir
	local tests="17777 787 789 abcd
		ug=uu ug=a ug=gu uo=ou urw
		u+xg+x a=r,u+x,"

	test_mkdir $dir
	for err in $tests; do
		if $LFS find $dir -perm $err 2>/dev/null; then
			error "lfs find -perm $err: parsing should have failed"
		fi
	done
}
run_test 56acc "check parsing error for lfs find -perm"

test_56Ba() { # was test_56ba
	[ $MDS1_VERSION -lt $(version_code 2.10.50) ] &&
		skip "Need MDS version at least 2.10.50"

	# Create composite files with one component
	local dir=$DIR/$tdir

	setup_56 $dir/1Mfiles 5 1 "-S 1M --component-end 1M"
	# Create composite files with three components
	setup_56 $dir/2Mfiles 5 2 "-E 2M -S 1M -E 4M -E 6M"
	# LU-16904 Create plain layout files
	lfs setstripe -c 1 $dir/$tfile-{1..10}

	local nfiles=$($LFS find --component-end 1M --type f $dir | wc -l)

	[[ $nfiles == 10 ]] ||
		error "lfs find -E 1M found $nfiles != 10 files"

	nfiles=$($LFS find ! -E 1M --type f $dir | wc -l)
	[[ $nfiles == 25 ]] ||
		error "lfs find ! -E 1M found $nfiles != 25 files"

	# All files have a component that starts at 0
	nfiles=$($LFS find --component-start 0 --type f $dir | wc -l)
	[[ $nfiles == 35 ]] ||
		error "lfs find --component-start 0 - $nfiles != 35 files"

	nfiles=$($LFS find --component-start 2M --type f $dir | wc -l)
	[[ $nfiles == 15 ]] ||
		error "lfs find --component-start 2M - $nfiles != 15 files"

	# All files created here have a componenet that does not starts at 2M
	nfiles=$($LFS find ! --component-start 2M --type f $dir | wc -l)
	[[ $nfiles == 35 ]] ||
		error "lfs find ! --component-start 2M - $nfiles != 35 files"

	# Find files with a specified number of components
	local nfiles=$($LFS find --component-count 3 --type f $dir | wc -l)
	[[ $nfiles == 15 ]] ||
		error "lfs find --component-count 3 - $nfiles != 15 files"

	# Remember non-composite files have a component count of zero
	local nfiles=$($LFS find --component-count 0 --type f $dir | wc -l)
	[[ $nfiles == 10 ]] ||
		error "lfs find --component-count 0 - $nfiles != 10 files"

	nfiles=$($LFS find ! --component-count 3 --type f $dir | wc -l)
	[[ $nfiles == 20 ]] ||
		error "lfs find ! --component-count 3 - $nfiles != 20 files"

	# All files have a flag called "init"
	local nfiles=$($LFS find --component-flags init --type f $dir | wc -l)
	[[ $nfiles == 35 ]] ||
		error "lfs find --component-flags init - $nfiles != 35 files"

	# Multi-component files will have a component not initialized
	local nfiles=$($LFS find ! --component-flags init --type f $dir | wc -l)
	[[ $nfiles == 15 ]] ||
		error "lfs find !--component-flags init - $nfiles != 15 files"

	rm -rf $dir

}
run_test 56Ba "test lfs find --component-end, -start, -count, and -flags"

test_56Ca() { # was (also) test_56ca
	[[ $MDS1_VERSION -ge $(version_code 2.10.57) ]] ||
		skip "Need MDS version at least 2.10.57"

	local td=$DIR/$tdir
	local tf=$td/$tfile
	local dir
	local nfiles
	local cmd
	local i
	local j

	# create mirrored directories and mirrored files
	mkdir $td || error "mkdir $td failed"
	$LFS mirror create -N3 $td || error "create mirrored dir $td failed"
	createmany -o $tf- 10 || error "create $tf- failed"

	for i in $(seq 2); do
		dir=$td/dir$i
		mkdir $dir || error "mkdir $dir failed"
		$LFS mirror create -N$((3 + i)) $dir ||
			error "create mirrored dir $dir failed"
		createmany -o $dir/$tfile- 10 ||
			error "create $dir/$tfile- failed"
	done

	# change the states of some mirrored files
	echo foo > $tf-6
	for i in $(seq 2); do
		dir=$td/dir$i
		for j in $(seq 4 9); do
			echo foo > $dir/$tfile-$j
		done
	done

	# find mirrored files with specific mirror count
	cmd="$LFS find --mirror-count 3 --type f $td"
	nfiles=$($cmd | wc -l)
	[[ $nfiles = 10 ]] || error "$cmd: $nfiles != 10 files"

	cmd="$LFS find ! --mirror-count 3 --type f $td"
	nfiles=$($cmd | wc -l)
	[[ $nfiles = 20 ]] || error "$cmd: $nfiles != 20 files"

	cmd="$LFS find --mirror-count +2 --type f $td"
	nfiles=$($cmd | wc -l)
	[[ $nfiles = 30 ]] || error "$cmd: $nfiles != 30 files"

	cmd="$LFS find --mirror-count -6 --type f $td"
	nfiles=$($cmd | wc -l)
	[[ $nfiles = 30 ]] || error "$cmd: $nfiles != 30 files"

	# find mirrored files with specific file state
	cmd="$LFS find --maxdepth 1 --mirror-state=^ro --type f $td"
	[[ $($cmd) = $tf-6 ]] || error "$cmd: didn't return $tf-6"

	cmd="$LFS find --mirror-state=ro --type f $td"
	nfiles=$($cmd | wc -l)
	[[ $nfiles = 17 ]] || error "$cmd: $nfiles != 17 files"

	cmd="$LFS find ! --mirror-state=ro --type f $td"
	nfiles=$($cmd | wc -l)
	[[ $nfiles = 13 ]] || error "$cmd: $nfiles != 13 files"

	cmd="$LFS find --mirror-state=wp --type f $td"
	nfiles=$($cmd | wc -l)
	[[ $nfiles = 13 ]] || error "$cmd: $nfiles != 13 files"

	cmd="$LFS find ! --mirror-state=sp --type f $td"
	nfiles=$($cmd | wc -l)
	[[ $nfiles = 30 ]] || error "$cmd: $nfiles != 30 files"
}
run_test 56Ca "check lfs find --mirror-count|-N and --mirror-state"

test_56Da() { # was test_56da, LU-14179
	local path=$DIR/$tdir

	test_mkdir $path
	cd $path

	local longdir=$(str_repeat 'a' 255)

	for i in {1..15}; do
		path=$path/$longdir
		test_mkdir $longdir
		cd $longdir
	done

	local len=${#path}
	local lastdir=$(str_repeat 'a' $((4096 - 1 - $len - 1)))

	test_mkdir $lastdir
	cd $lastdir
	# PATH_MAX-1
	(( ${#PWD} == 4095 )) || error "bad PWD length ${#PWD}, expect 4095"

	# NAME_MAX
	touch $(str_repeat 'f' 255)

	$LFS find $DIR/$tdir --type d |& grep "lfs find: error" &&
		error "lfs find reported an error"

	rm -rf $DIR/$tdir
}
run_test 56Da "test lfs find with long paths"

test_56Db() { # was test_56db
	local mdts=$($LFS df -m | grep -c MDT)
	local osts=$($LFS df -m | grep -c OST)

	$LFS df

	(( mdts == MDSCOUNT )) ||
		error "lfs df -m showed $mdts MDTs, not $MDSCOUNT"
	(( osts == 0 )) ||
		error "lfs df -m showed $osts OSTs, not 0"
}
run_test 56Db "test 'lfs df -m' only shows MDT devices"

test_56Dc() { # was test_56dc
	local mdts=$($LFS df -o | grep -c MDT)
	local osts=$($LFS df -o | grep -c OST)

	$LFS df

	(( osts == OSTCOUNT )) ||
		error "lfs df -o showed $osts OSTs, not $OSTCOUNT"
	(( mdts == 0 )) ||
		error "lfs df -o showed $mdts MDTs, not 0"
}
run_test 56Dc "test 'lfs df -o' only shows OST devices"

test_56Dd() { # was test_56dd
	local dir=$DIR/d$(basetest $testnum)g.$TESTSUITE

	setup_56 $dir $NUMFILES $NUMDIRS

	local lfscount=($($LFS find $dir -mindepth 1 -maxdepth 2 | sort))
	local findcount=($(find $dir -mindepth 1 -maxdepth 2 | sort))

	if [[ ${#lfscount[@]} != ${#findcount[@]} ]]; then
		error "lfs find returned ${#lfscount[@]} files, find returned ${#findcount[@]} files"
	fi

	for ((i = 0; i < ${#lfscount[@]}; i++)); do
		[[ "${lfscount[$i]}" == "${findcount[$i]}" ]] &&
			echo "${lfscount[$i]}" ||
			error "${#lfscount[@]} != ${#findcount[@]}"
	done
}
run_test 56Dd "test lfs find with mindepth argument"

test_56Ea() { #LU-10378
	local path=$DIR/$tdir
	local pool=$TESTNAME

	# Create ost pool
	pool_add $pool || error "pool_add $pool failed"
	pool_add_targets $pool 0 $((OSTCOUNT - 1)) 1 ||
		error "adding targets to $pool failed"

	# Set default pool on directory before creating file
	mkdir $path || error "mkdir $path failed"
	$LFS setstripe -p $pool $path ||
		error "set OST pool on $pool failed"
	touch $path/$tfile || error "touch $path/$tfile failed"

	# Compare basic file attributes from -printf and stat
	local attr_printf=$($LFS find $path/$tfile -printf "%A@ %T@ %C@ %U %G %n")
	local attr_stat=$(stat -c "%X %Y %Z %u %g %h" $path/$tfile)

	[[ "${attr_printf}" == "${attr_stat}" ]] ||
		error "Attrs from lfs find and stat don't match"

	# Compare Lustre attributes from lfs find and lfs getstripe
	local lattr_printf=$($LFS find $path/$tfile -printf "%Lc %LS %Li %Lp")
	local str_cnt=$($LFS getstripe --stripe-count $path/$tfile)
	local str_size=$($LFS getstripe --stripe-size $path/$tfile)
	local str_idx=$($LFS getstripe --stripe-index $path/$tfile)
	local fpool=$($LFS getstripe --pool $path/$tfile)
	local lattr_getstr="${str_cnt} ${str_size} ${str_idx} ${fpool}"

	[[ "${lattr_printf}" == "${lattr_getstr}" ]] ||
		error "Attrs from lfs find and lfs getstripe don't match"

	# Verify behavior for unknown escape/format sequences
	local esc_printf=$($LFS find $path/$tfile -printf '\\ %% \Q %Q')

	[[ "${esc_printf}" == '\ % \Q %Q' ]] ||
		error "Escape/format codes don't match"
}
run_test 56Ea "test lfs find -printf option"

test_56Eaa() {
	local lfs_find=($($LFS find $DIR -printf "%i %u %g %M %p\n" | sort -n))
	local normal_find=($(find $DIR -printf "%i %u %g %M %p\n" | sort -n))

	echo "comparing ${#normal_find[@]} elements starting with:"
	echo "lfs: ${lfs_find[0]} ${lfs_find[1]} ${lfs_find[2]} ${lfs_find[3]} ${lfs_find[4]}"
	echo "find: ${normal_find[0]} ${normal_find[1]} ${normal_find[2]} ${normal_find[3]} ${normal_find[4]}"

	for ((i = 0; i < ${#normal_find[@]}; i++)); do
		if [[ "${lfs_find[i]}" != "${normal_find[i]}" ]]; then
			error "expected '${normal_find[i]}' but got '${lfs_find[i]}' from file ${lfs_find[$((i - (i % 5) + 4))]}"
		fi
	done
}
run_test 56Eaa "test lfs find -printf added functions"

test_56Eab() {
	touch $DIR/$tfile
	local lfs_ls=($($LFS find $DIR -name $tfile -ls))
	local find_ls=($(find $DIR -name $tfile -ls))

# "-1" is last field, since dates are not printed exactly the same.
	for ((i = -1; i < 7; i++)); do
		[[ "${lfs_ls[i]}" == "${find_ls[i]}" ]] ||
			error "expected '${lfs_ls[i]}' but got '${find_ls[i]}'"
	done
}
run_test 56Eab "test lfs find -ls function"

test_56Eb() {
	local dir=$DIR/$tdir
	local subdir_1=$dir/subdir_1

	test_mkdir -p $subdir_1
	ln -s subdir_1 $dir/link_1

	$LFS getstripe $dir | grep "^$dir/link_1$" -A1 ||
		error "symlink is not followed"

	$LFS getstripe --no-follow $dir |
		grep "^$dir/link_1 has no stripe info$" ||
		error "symlink should not have stripe info"

	touch $dir/testfile
	ln -s testfile $dir/file_link_2

	$LFS getstripe $dir | grep "^$dir/file_link_2$" -A1 ||
		error "symlink is not followed"

	$LFS getstripe --no-follow $dir |
		grep "^$dir/file_link_2 has no stripe info$" ||
		error "symlink should not have stripe info"
}
run_test 56Eb "check lfs getstripe on symlink"

test_56Ebb() {

	mkdir $DIR/$tdir
	mkfifo $DIR/$tdir/$tfile-fifo
	$LFS getdirstripe -r $DIR/$tdir || error "$LFS getdirstripe -r: $DIR"
}
run_test 56Ebb "check $LFS getdirstripe for FIFO file"

test_56Ec() {
	[[ $OSTCOUNT -lt 2 ]] && skip_env "needs >= 2 OSTs"
	local dir=$DIR/$tdir
	local srcfile=$dir/srcfile
	local srcyaml=$dir/srcyaml
	local destfile=$dir/destfile

	test_mkdir -p $dir

	$LFS setstripe -i 1 $srcfile
	$LFS getstripe --hex-idx --yaml $srcfile > $srcyaml
	# if the setstripe yaml parsing fails for any reason, the command can
	# randomly assign the correct OST index, leading to an erroneous
	# success. but the chance of false success is low enough that a
	# regression should still be quickly caught.
	$LFS setstripe --yaml=$srcyaml $destfile

	local srcindex=$($LFS getstripe -i $srcfile)
	local destindex=$($LFS getstripe -i $destfile)

	if [[ ! $srcindex -eq $destindex ]]; then
		error "setstripe did not set OST index correctly"
	fi
}
run_test 56Ec "check lfs getstripe,setstripe --hex --yaml"

# LU-15565
test_56Ed() {
	local new=$DIR/$tdir/$tfile-layout-new
	local old=$DIR/$tdir/$tfile-layout-old

	test_mkdir $DIR/$tdir

	cat << PFL_LAYOUT_NEW > $new
lcm_layout_gen:    3
lcm_mirror_count:  1
lcm_entry_count:   3
components:
  - lcme_id:             1
    lcme_mirror_id:      0
    lcme_flags:          init
    lcme_extent.e_start: 0
    lcme_extent.e_end:   1073741824
    sub_layout:
      lmm_stripe_count:  1
      lmm_stripe_size:   4194304
      lmm_pattern:       raid0
      lmm_layout_gen:    0
      lmm_stripe_offset: 0
      lmm_objects:
      - l_ost_idx: 0
        l_fid:     0x280000400:0x2:0x0
  - lcme_id:             2
    lcme_mirror_id:      0
    lcme_flags:          0
    lcme_extent.e_start: 1073741824
    lcme_extent.e_end:   4294967296
    sub_layout:
      lmm_stripe_count:  4
      lmm_stripe_size:   4194304
      lmm_pattern:       raid0
      lmm_layout_gen:    0
      lmm_stripe_offset: -1
  - lcme_id:             3
    lcme_mirror_id:      0
    lcme_flags:          0
    lcme_extent.e_start: 4294967296
    lcme_extent.e_end:   EOF
    sub_layout:
      lmm_stripe_count:  4
      lmm_stripe_size:   4194304
      lmm_pattern:       raid0
      lmm_layout_gen:    0
      lmm_stripe_offset: -1
PFL_LAYOUT_NEW

# Layout changed in 2.16.0
	cat << PFL_LAYOUT_OLD > $old
  lcm_layout_gen:    3
  lcm_mirror_count:  1
  lcm_entry_count:   3
  component0:
    lcme_id:             1
    lcme_mirror_id:      0
    lcme_flags:          init
    lcme_extent.e_start: 0
    lcme_extent.e_end:   1073741824
    sub_layout:
      lmm_stripe_count:  1
      lmm_stripe_size:   4194304
      lmm_pattern:       raid0
      lmm_layout_gen:    0
      lmm_stripe_offset: 0
      lmm_objects:
      - l_ost_idx: 0
        l_fid:     0x280000400:0x2:0x0
  component1:
    lcme_id:             2
    lcme_mirror_id:      0
    lcme_flags:          0
    lcme_extent.e_start: 1073741824
    lcme_extent.e_end:   4294967296
    sub_layout:
      lmm_stripe_count:  4
      lmm_stripe_size:   4194304
      lmm_pattern:       raid0
      lmm_layout_gen:    0
      lmm_stripe_offset: -1
  component2:
    lcme_id:             3
    lcme_mirror_id:      0
    lcme_flags:          0
    lcme_extent.e_start: 4294967296
    lcme_extent.e_end:   EOF
    sub_layout:
      lmm_stripe_count:  4
      lmm_stripe_size:   4194304
      lmm_pattern:       raid0
      lmm_layout_gen:    0
      lmm_stripe_offset: -1
PFL_LAYOUT_OLD

	local yaml_file=$DIR/$tdir/layout.yaml
	local dir=$DIR/$tdir
	local test=$dir/$tfile.test

	$LFS setstripe -E 4M -c 2 -E EOF -c 4 $test ||
		error "failed to setstripe"
	$LFS getstripe --yaml $test > $yaml_file ||
		error "failed to getstripe --yaml"

	$LFS setstripe --yaml $old $dir/$tfile.new ||
		error "failed to setstripe from new YAML format"
	# test that the old format can still be used
	$LFS setstripe --yaml $old $dir/$tfile.old ||
		error "failed to setstripe from old YAML format"

	local orig=$(get_layout_param $test)
	local rest=$(cat $yaml_file | parse_layout_param)
	[[ "$orig" == "$rest" ]] ||
		error "failed to parse current YAML layout"

	orig=$(get_layout_param $dir/$tfile.old)
	rest=$(cat $old | parse_layout_param)
	[[ "$orig" == "$rest" ]] ||
		error "failed to parse old YAML layout"

	orig=$(get_layout_param $dir/$tfile.new)
	rest=$(cat $new | parse_layout_param)
	[[ "$orig" == "$rest" ]] ||
		error "failed to parse new YAML layout"

}
run_test 56Ed "verify new YAML format is valid and back-compatible"

test_56Eda() {
	local dir=$DIR/$tdir
	local subdir=$dir/subdir
	local file1=$dir/$tfile
	local file2=$dir/$tfile\2
	local link=$dir/$tfile-link
	local nfiles

	test_mkdir -p $dir
	$LFS setdirstripe -c1 $subdir
	touch $file1
	touch $file2
	ln $file2 $link

	nfiles=$($LFS find --links 1 $dir | wc -l)
	(( $nfiles == 1 )) ||
		error "lfs find --links expected 1 file, got $nfiles"

	nfiles=$($LFS find --type f --links 2 $dir | wc -l)
	(( $nfiles == 2 )) ||
		error "lfs find --links expected 2 files, got $nfiles"

	nfiles=$($LFS find --type d --links 2 $dir | wc -l)
	(( $nfiles == 1 )) ||
		error "lfs find --links expected 1 directory, got $nfiles"
}
run_test 56Eda "check lfs find --links"

test_56Edb() {
	[[ $MDSCOUNT -lt 2 ]] && skip_env "needs >= 2 MDTs"

	local dir=$DIR/$tdir
	local stripedir=$dir/stripedir
	local nfiles

	test_mkdir -p $dir

	$LFS setdirstripe -c2 $stripedir

	$LFS getdirstripe $stripedir

	nfiles=$($LFS find --type d --links 2 $stripedir | wc -l)
	(( $nfiles == 1 )) ||
		error "lfs find --links expected 1 directory, got $nfiles"
}
run_test 56Edb "check lfs find --links for directory striped on multiple MDTs"

test_56Ef() {
	local dir=$DIR/$tdir
	local dir1=$dir/d1
	local dir2=$dir/d2
	local nfiles
	local err_msg

	test_mkdir -p $dir

	mkdir $dir1
	mkdir $dir2

	touch $dir1/f
	touch $dir2/f

	nfiles=$($LFS find $dir1 $dir2 ! -type d | wc -l)
	(( $nfiles == 2 )) ||
		error "(1) lfs find expected 2 files, got $nfiles"

	nfiles=$($LFS find $dir1 $dir2 -type f | wc -l)
	(( $nfiles == 2 )) ||
		error "(2) lfs find expected 2 files, got $nfiles"

	nfiles=$($LFS find -type f $dir1 $dir2 | wc -l)
	(( $nfiles == 2 )) ||
		error "(3) lfs find expected 2 files, got $nfiles"

	err_msg=$($LFS find $dir1/typo $dir1/f 2>&1 > /dev/null)
	[[ $err_msg =~ "No such file or directory" ]] ||
		error "expected standard error message, got: '$err_msg'"
}
run_test 56Ef "lfs find with multiple paths"

test_56Eg() {
	local dir=$DIR/$tdir
	local found

	which setfattr > /dev/null 2>&1 || skip_env "no setfattr command"

	test_mkdir -p $dir

	touch $dir/$tfile
	ln -s $dir/$tfile $dir/$tfile.symlink
	setfattr -n "trusted.test" -v "test_target" $dir/$tfile
	setfattr --no-dereference -n "trusted.test" -v "test_link" \
		$dir/$tfile.symlink
	setfattr --no-dereference -n "trusted.common" \
		$dir/{$tfile,$tfile.symlink}

	found=$($LFS find -xattr "trusted.*=test_target" \
		-xattr "trusted.common" $dir)
	[[ "$found" == "$dir/$tfile" ]] || {
		getfattr -d -m trusted.* $dir/$tfile
		error "should have found '$tfile' with xattr 'trusted.test=test_target', got '$found'"
	}

	found=$($LFS find -xattr "trusted.*=test_link" \
		-xattr "trusted.common" $dir)
	[[ "$found" == "$dir/$tfile.symlink" ]] || {
		getfattr --no-dereference -d -m trusted.* $dir/$tfile.symlink
		error "should have found '$tfile.symlink' with xattr 'trusted.test=test_link', got '$found'"
	}

	rm -f $dir/*

	touch $dir/$tfile.1
	touch $dir/$tfile.2
	setfattr -n "user.test" -v "1" $dir/$tfile.1
	setfattr -n "user.test" -v "2" $dir/$tfile.2
	setfattr -n "user.test2" -v "common" $dir/$tfile.{1,2}

	found=$($LFS find -xattr "user.*=common" -xattr "user.test=1" $dir)
	[[ "$found" == "$dir/$tfile.1" ]] || {
		getfattr -d $dir/$tfile.1
		error "should have found '$tfile.1' with xattr user.test=1', got '$found'"
	}

	found=$($LFS find -xattr "user.*=common" ! -xattr "user.test=1" $dir)
	[[ "$found" == "$dir/$tfile.2" ]] || {
		getfattr -d $dir/$tfile.2
		error "should have found '$tfile.2' without xattr 'user.test=1', got '$found'"
	}

	setfattr -n "user.empty" $dir/$tfile.1
	found=$($LFS find -xattr "user.empty" $dir)
	[[ "$found" == "$dir/$tfile.1" ]] || {
		getfattr -d $dir/$tfile.1
		error "should have found '$tfile.1' with xattr 'user.empty=', got '$found'"
	}

	# setfattr command normally does not store terminating null byte
	# when writing a string as an xattr value.
	#
	# In order to test matching a value string that includes a terminating
	# null, explicitly encode the string "test\0" with the null terminator.
	setfattr -n "user.test" -v "0x7465737400" $dir/$tfile.1
	found=$($LFS find -xattr "user.test=test" $dir)
	[[ "$found" == "$dir/$tfile.1" ]] || {
		getfattr -d --encoding=hex $dir/$tfile.1
		error "should have found '$tfile.1' with xattr 'user.test=0x7465737400', got '$found'"
	}
}
run_test 56Eg "lfs find -xattr"

test_56Eh() {
	local dir=$DIR/d$(basetest $testnum)g.$TESTSUITE

	# Enough files to give us a statistically reliable sampling
	# setup_special is complicated, but this works out to about 2100 files
	setup_56_special $dir 400 $NUMDIRS

	local cmd="$LFS find $dir"
	local total=$($cmd | wc -l)
	local n=1

	local nums

	echo "Running tests on $dir, with $total total results."

	while (( $n < 100 )); do
		nums=$($LFS find --skip=$((100 - $n)) $dir | wc -l)
		(( $nums <= $(($total * ($n + 10) / 100)) &&
		   $nums >= $(($total * ($n - 10) / 100)) )) ||
			error "--skip=$((100 - $n)): expected" \
			      "$(($total * $n / 100)) results with 10% error" \
			      "margin, got $nums"
		(( n++ ))
	done
}
run_test 56Eh "check lfs find --skip"

test_56Ei() {
	(( $MDS1_VERSION >= $(version_code 2.15.64.110) )) ||
		skip "need MDS >= v2_15_64-110-g501e5b2c8a for special projid"
	local path=$DIR/$tdir
	local projid=1234
	local expected_count=3

	# Create test dir containing:
	# - regular file, with default projid
	# - regular file, with unique projid
	# - symbolic link, with unique projid
	# - special char dev file, with unique projid
	test_mkdir $path || error "mkdir $path failed"
	touch $path/file0 $path/file$projid || error "touch failed"
	ln -s $path/file$projid $path/link$projid
	mknod $path/char$projid c 1 3
	$LFS project -p $projid -s $path/file$projid
	$LFS project -p $projid -s $path/link$projid
	$LFS project -p $projid -s $path/char$projid
	stack_trap "rm -rf $path" EXIT

	$LFS project -r $path/
	echo -e "Actual output:\n$($LFS find $path --printf '%LP %p\n')"

	# Find all files and print their projids along with their path; count
	found_count=$($LFS find $path --printf "%LP %p\n" |
		grep -E "$projid $path/(link|char|file)$projid" | wc -l)
	echo -e "found_count: $found_count"
	[[ $found_count == $expected_count ]] ||
		error "Did not find any entries with expected projid $projid"
}
run_test 56Ei "test lfs find --printf prints correct projid for special files"

test_56Ej() {
	test_mkdir $DIR/$tdir.src ||
		error "mkdir failed on $DIR/$tdir.src"
	test_mkdir $DIR/$tdir.dest ||
		error "mkdir failed on $DIR/$tdir.dest"
	local f_mgrt=$DIR/$tdir.dest/$tfile.mgrt

	$LFS setstripe -o 1 $DIR/$tdir.src
	$LFS setstripe -o 0 $DIR/$tdir.dest
	dd if=/dev/random of=$f_mgrt bs=1M count=1

	$LFS migrate  --non-block --copy $DIR/$tdir.src $f_mgrt ||
		error "migrate remote dir error $DIR/$tdir.src $f_mgrt"
}
run_test 56Ej "lfs migration --non-block copy"

test_56Ek() {
	local dir=$DIR/$tdir
	local numfiles=10
	local numdirs=5

	# Setup test directory structure
	echo "Creating test directory structure..."
	mkdir -p $dir || error "Failed to create $dir"

	# Create test directories and files
	for ((i = 0; i < numdirs; i++)); do
		mkdir -p $dir/subdir$i || error "Failed to create subdir$i"
		createmany -o $dir/subdir$i/file $numfiles ||
			error "Failed to create files in subdir$i"
	done

	# Normal find should work
	echo "Verifying normal find works..."
	local count=$($LFS find $dir | wc -l)
	# dirs + files + root
	local expected=$(($numdirs + ($numfiles * $numdirs) + 1))
	[ $count -eq $expected ] ||
		error "Wrong file count: found $count, expected $expected"

	# Set failure injection
	echo "Testing error handling..."
	LLAPI_FAIL_LOC="LLAPI_FAIL_PFIND_SEM" \
		$LFS find $dir 2>&1 | grep -q "Input/output error" ||
		error "Expected I/O error not found with LLAPI_FAIL_LOC set"

	# Cleanup
	rm -rf $dir
	return 0
}
run_test 56Ek "Test lfs find error handling with LLAPI_FAIL_LOC"

test_57a() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	# note test will not do anything if MDS is not local
	if [ "$mds1_FSTYPE" != ldiskfs ]; then
		skip_env "ldiskfs only test"
	fi
	remote_mds_nodsh && skip "remote MDS with nodsh"

	local MNTDEV="osd*.*MDT*.mntdev"
	DEV=$(do_facet $SINGLEMDS lctl get_param -n $MNTDEV)
	[ -z "$DEV" ] && error "can't access $MNTDEV"
	for DEV in $(do_facet $SINGLEMDS lctl get_param -n $MNTDEV); do
		do_facet $SINGLEMDS $DUMPE2FS -h $DEV > $TMP/t57a.dump ||
			error "can't access $DEV"
		DEVISIZE=$(awk '/Inode size:/ { print $3 }' $TMP/t57a.dump)
		[[ $DEVISIZE -gt 128 ]] || error "inode size $DEVISIZE"
		rm $TMP/t57a.dump
	done
}
run_test 57a "verify MDS filesystem created with large inodes =="

test_57b() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	if [ "$mds1_FSTYPE" != ldiskfs ]; then
		skip_env "ldiskfs only test"
	fi
	remote_mds_nodsh && skip "remote MDS with nodsh"

	local dir=$DIR/$tdir
	local filecount=100
	local file1=$dir/f1
	local fileN=$dir/f$filecount

	rm -rf $dir || error "removing $dir"
	test_mkdir -c1 $dir
	local mdtidx=$($LFS getstripe -m $dir)
	local mdtname=MDT$(printf %04x $mdtidx)
	local facet=mds$((mdtidx + 1))

	echo "mcreating $filecount files"
	createmany -m $dir/f 1 $filecount || error "creating files in $dir"

	# verify that files do not have EAs yet
	$LFS getstripe $file1 2>&1 | grep -q "no stripe" ||
		error "$file1 has an EA"
	$LFS getstripe $fileN 2>&1 | grep -q "no stripe" ||
		error "$fileN has an EA"

	sync
	sleep 1
	df $dir  #make sure we get new statfs data
	local mdsfree=$(do_facet $facet \
			lctl get_param -n osd*.*$mdtname.kbytesfree)
	local mdcfree=$(lctl get_param -n mdc.*$mdtname-mdc-*.kbytesfree)
	local file

	echo "opening files to create objects/EAs"
	for file in $(seq -f $dir/f%g 1 $filecount); do
		$OPENFILE -f O_RDWR $file > /dev/null 2>&1 ||
			error "opening $file"
	done

	# verify that files have EAs now
	$LFS getstripe -y $file1 | grep -q "l_ost_idx" ||
		error "$file1 missing EA"
	$LFS getstripe -y $fileN | grep -q "l_ost_idx" ||
		error "$fileN missing EA"

	sleep 1  #make sure we get new statfs data
	df $dir
	local mdsfree2=$(do_facet $facet \
			 lctl get_param -n osd*.*$mdtname.kbytesfree)
	local mdcfree2=$(lctl get_param -n mdc.*$mdtname-mdc-*.kbytesfree)

	if [[ $mdcfree2 -lt $((mdcfree - 16)) ]]; then
		if [ "$mdsfree" != "$mdsfree2" ]; then
			error "MDC before $mdcfree != after $mdcfree2"
		else
			echo "MDC before $mdcfree != after $mdcfree2"
			echo "unable to confirm if MDS has large inodes"
		fi
	fi
	rm -rf $dir
}
run_test 57b "default LOV EAs are stored inside large inodes ==="

test_58() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ -z "$(which wiretest 2>/dev/null)" ] &&
			skip_env "could not find wiretest"

	wiretest
}
run_test 58 "verify cross-platform wire constants =============="

test_59() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	echo "touch 130 files"
	createmany -o $DIR/f59- 130
	echo "rm 130 files"
	unlinkmany $DIR/f59- 130
	sync
	# wait for commitment of removal
	wait_delete_completed
}
run_test 59 "verify cancellation of llog records async ========="

TEST60_HEAD="test_60 run $RANDOM"
test_60a() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mgs_nodsh && skip "remote MGS with nodsh"
	do_facet mgs "! which run-llog.sh &> /dev/null" &&
		do_facet mgs "! ls run-llog.sh &> /dev/null" &&
			skip_env "missing subtest run-llog.sh"

	log "$TEST60_HEAD - from kernel mode"
	do_facet mgs "$LCTL clear"
	local saved_debug=$(do_facet mgs $LCTL get_param -n debug)
	# ensure we get our records in the debug log
	do_facet mgs $LCTL set_param debug=all-trace-malloc-net-other-ha-info-inode
	do_facet mgs "bash run-llog.sh" || error "run-llog.sh failed"
	do_facet mgs "$LCTL set_param debug='$saved_debug'"
	do_facet mgs $LCTL dk > $TMP/$tfile

	# LU-6388: test llog_reader
	local llog_reader=$(do_facet mgs "which llog_reader 2> /dev/null")
	llog_reader=${llog_reader:-$LUSTRE/utils/llog_reader}
	[ -z $(do_facet mgs ls -d $llog_reader 2> /dev/null) ] &&
			skip_env "missing llog_reader"
	local fstype=$(facet_fstype mgs)
	[ $fstype != ldiskfs -a $fstype != zfs ] &&
		skip_env "Only for ldiskfs or zfs type mgs"

	local mntpt=$(facet_mntpt mgs)
	local mgsdev=$(mgsdevname 1)
	local fid_list
	local fid
	local rec_list
	local rec
	local rec_type
	local obj_file
	local path
	local seq
	local oid
	local pass=true

	#get fid and record list
	fid_list=($(awk '/9_sub.*record/ { print $NF }' $TMP/$tfile |
		tail -n 4))
	rec_list=($(awk '/9_sub.*record/ { print $((NF-3)) }' $TMP/$tfile |
		tail -n 4))
	#remount mgs as ldiskfs or zfs type
	stop mgs || error "stop mgs failed"
	mount_fstype mgs || error "remount mgs failed"
	echo "fid_list=${fid_list[@]}"
	for ((i = 0; i < ${#fid_list[@]}; i++)); do
		fid=${fid_list[i]}
		rec=${rec_list[i]}

		obj_file=$mntpt/$(ost_fid2_objpath mgs $fid)
		echo "obj_file is $obj_file"
		do_facet mgs $llog_reader $obj_file

		rec_type=$(do_facet mgs $llog_reader $obj_file | grep "type=" |
			awk '{ print $3 }' | sed -e "s/^type=//g")
		if [ $rec_type != $rec ]; then
			echo "FAILED test_60a wrong record type $rec_type," \
			      "should be $rec"
			pass=false
			break
		fi

		#check obj path if record type is LLOG_LOGID_MAGIC
		if [ "$rec" == "1064553b" ]; then
			path=$(do_facet mgs $llog_reader $obj_file |
				grep "path=" | awk '{ print $NF }' |
				sed -e "s/^path=//g")
			if [ $obj_file != $mntpt/$path ]; then
				echo "FAILED test_60a wrong obj path" \
				      "$montpt/$path, should be $obj_file"
				pass=false
				break
			fi
		fi
	done
	rm -f $TMP/$tfile
	#restart mgs before "error", otherwise it will block the next test
	stop mgs || error "stop mgs failed"
	start mgs $(mgsdevname) $MGS_MOUNT_OPTS || error "start mgs failed"
	$pass || error "test failed, see FAILED test_60a messages for specifics"
}
run_test 60a "llog_test run from kernel module and test llog_reader"

test_60b() { # bug 6411
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	dmesg > $DIR/$tfile
	LLOG_COUNT=$(do_facet mgs dmesg |
		     awk "/$TEST60_HEAD/ { marker = 1; from_marker = 0; }
			  /llog_[a-z]*.c:[0-9]/ {
				if (marker)
					from_marker++
				from_begin++
			  }
			  END {
				if (marker)
					print from_marker
				else
					print from_begin
			  }")

	(( LLOG_COUNT <= 140 )) ||
		error "CDEBUG_LIMIT not limiting messages ($LLOG_COUNT)" || true
}
run_test 60b "limit repeated messages from CERROR/CWARN"

test_60c() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	echo "create 5000 files"
	createmany -o $DIR/f60c- 5000
#define OBD_FAIL_MDS_LLOG_CREATE_FAILED  0x137
	lctl set_param fail_loc=0x80000137
	unlinkmany $DIR/f60c- 5000
	lctl set_param fail_loc=0
}
run_test 60c "unlink file when mds full"

test_60d() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	SAVEPRINTK=$(lctl get_param -n printk)
	# verify "lctl mark" is even working"
	MESSAGE="test message ID $RANDOM $$"
	$LCTL mark "$MESSAGE" || error "$LCTL mark failed"
	dmesg | grep -q "$MESSAGE" || error "didn't find debug marker in log"

	lctl set_param printk=0 || error "set lnet.printk failed"
	lctl get_param -n printk | grep emerg || error "lnet.printk dropped emerg"
	MESSAGE="new test message ID $RANDOM $$"
	# Assume here that libcfs_debug_mark_buffer() uses D_WARNING
	$LCTL mark "$MESSAGE" || error "$LCTL mark failed"
	dmesg | grep -q "$MESSAGE" && error "D_WARNING wasn't masked" || true

	lctl set_param -n printk="$SAVEPRINTK"
}
run_test 60d "test printk console message masking"

test_60e() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"

	touch $DIR/$tfile
#define OBD_FAIL_MDS_LLOG_CREATE_FAILED2  0x15b
	do_facet mds1 lctl set_param fail_loc=0x15b
	rm $DIR/$tfile
}
run_test 60e "no space while new llog is being created"

test_60f() {
	local old_path=$($LCTL get_param -n debug_path)

	stack_trap "$LCTL set_param debug_path=$old_path"
	stack_trap "rm -f $TMP/$tfile*"
	rm -f $TMP/$tfile* 2> /dev/null
	#define OBD_FAIL_PTLRPC_DUMP_LOG         0x50e
	$LCTL set_param debug_path=$TMP/$tfile fail_loc=0x8000050e
	test_mkdir $DIR/$tdir
	# retry in case the open is cached and not released
	for (( i = 0; i < 100 && $(ls $TMP/$tfile* | wc -l) == 0; i++ )); do
		echo $i > $DIR/$tdir/$tfile.$i && cat $DIR/$tdir/$tfile.$i
		sleep 0.1
	done
	ls $TMP/$tfile*
	(( $(ls $TMP/$tfile* | wc -l) > 0 )) || error "$TMP/$tfile not dumped"
}
run_test 60f "change debug_path works"

test_60g() {
	(( $MDS1_VERSION >= $(version_code v2_16_56-96-gd0c75da78301) )) ||
		skip "Need MDS >= v2_16_56-96-gd0c75da78301 for symlink fix"

	local pid
	local i

	test_mkdir -c $MDSCOUNT $DIR/$tdir

	(
		local index=0
		while true; do
			$LFS setdirstripe -i $(($index % $MDSCOUNT)) \
				-c $MDSCOUNT $DIR/$tdir/subdir$index \
				2>/dev/null
			mkdir $DIR/$tdir/subdir$index 2>/dev/null
			rmdir $DIR/$tdir/subdir$index 2>/dev/null
			index=$((index + 1))
		done
	) &

	pid=$!

	for i in {0..100}; do
		# define OBD_FAIL_OSD_TXN_START    0x19a
		local index=$((i % MDSCOUNT + 1))

		do_facet mds$index $LCTL set_param fail_loc=0x8000019a \
			> /dev/null
		sleep 0.01
	done

	kill -9 $pid

	for i in $(seq $MDSCOUNT); do
		do_facet mds$i $LCTL set_param fail_loc=0 > /dev/null
	done

	mkdir $DIR/$tdir/new || error "mkdir failed"
	rmdir $DIR/$tdir/new || error "rmdir failed"

	do_facet mds1 $LCTL lfsck_start -M $(facet_svc mds1) -A -C \
		-t namespace
	for i in $(seq $MDSCOUNT); do
		wait_update_facet mds$i "$LCTL get_param -n \
			mdd.$(facet_svc mds$i).lfsck_namespace |
			awk '/^status/ { print \\\$2 }'" "completed"
	done

	ls -R $DIR/$tdir
	rm -rf $DIR/$tdir || error "rmdir failed"
}
run_test 60g "transaction abort won't cause MDT hung"

test_60h() {
	[ $MDS1_VERSION -le $(version_code 2.12.52) ] &&
		skip "Need MDS version at least 2.12.52"
	[ $MDSCOUNT -lt 2 ] && skip "Need at least 2 MDTs"

	local f

	#define OBD_FAIL_MDS_STRIPE_CREATE	 0x188
	#define OBD_FAIL_MDS_STRIPE_FID		 0x189
	for fail_loc in 0x80000188 0x80000189; do
		do_facet mds1 "$LCTL set_param fail_loc=$fail_loc"
		$LFS mkdir -c $MDSCOUNT -i 0 $DIR/$tdir-$fail_loc ||
			error "mkdir $dir-$fail_loc failed"
		for i in {0..10}; do
			# create may fail on missing stripe
			echo $i > $DIR/$tdir-$fail_loc/$i
		done
		$LFS getdirstripe $DIR/$tdir-$fail_loc ||
			error "getdirstripe $tdir-$fail_loc failed"
		$LFS migrate -m 1 $DIR/$tdir-$fail_loc ||
			error "migrate $tdir-$fail_loc failed"
		$LFS getdirstripe $DIR/$tdir-$fail_loc ||
			error "getdirstripe $tdir-$fail_loc failed"
		pushd $DIR/$tdir-$fail_loc
		for f in *; do
			echo $f | cmp $f - || error "$f data mismatch"
		done
		popd
		rm -rf $DIR/$tdir-$fail_loc
	done
}
run_test 60h "striped directory with missing stripes can be accessed"

function t60i_load() {
	mkdir $DIR/$tdir
	#define OBD_FAIL_LLOG_PAUSE_AFTER_PAD		    0x131c
	$LCTL set_param fail_loc=0x131c fail_val=1
	for ((i=0; i<5000; i++)); do
		touch $DIR/$tdir/f$i
	done
}

test_60i() {
	changelog_register || error "changelog_register failed"
	local cl_user="${CL_USERS[$SINGLEMDS]%% *}"
	changelog_users $SINGLEMDS | grep -q $cl_user ||
		error "User $cl_user not found in changelog_users"
	changelog_chmask "ALL"
	t60i_load &
	local PID=$!
	for((i=0; i<100; i++)); do
		changelog_dump >/dev/null ||
			error "can't read changelog"
	done
	kill $PID
	wait $PID
	changelog_deregister || error "changelog_deregister failed"
	$LCTL set_param fail_loc=0
}
run_test 60i "llog: new record vs reader race"

test_60j() {
	(( $MDS1_VERSION >= $(version_code 2.15.50) )) ||
		skip "need MDS version at least 2.15.50"
	[[ $PARALLEL != "yes" ]] || skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	[[ "$mds1_FSTYPE" == "ldiskfs" ]] || skip "ldiskfs only test"

	changelog_users $SINGLEMDS | grep "^cl" &&
		skip "active changelog user"

	local llog_reader=$(do_facet $SINGLEMDS "which llog_reader 2> /dev/null")

	[[ -z $(do_facet $SINGLEMDS ls -d $llog_reader 2> /dev/null) ]] &&
		skip_env "missing llog_reader"

	mkdir_on_mdt0 $DIR/$tdir

	local f=$DIR/$tdir/$tfile
	local mdt_dev
	local tmpfile
	local plain

	changelog_register || error "cannot register changelog user"

	# set changelog_mask to ALL
	changelog_chmask "ALL"
	changelog_clear

	createmany -o ${f}- 100 || error "createmany failed as $RUNAS_ID"
	unlinkmany ${f}- 100 || error "unlinkmany failed"

	tmpfile="$(mktemp --tmpdir -u $tfile.XXXXXX)"
	mdt_dev=$(facet_device $SINGLEMDS)

	do_facet $SINGLEMDS sync
	plain=$(do_facet $SINGLEMDS "$DEBUGFS -c -R 'dump changelog_catalog \
		$tmpfile' $mdt_dev; $llog_reader $tmpfile" |
		awk '{match($0,"path=([^ ]+)",a)}END{print a[1]}')

	stack_trap "do_facet $SINGLEMDS rm -f $tmpfile"

	# if $tmpfile is not on EXT3 filesystem for some reason
	[[ ${plain:0:1} == 'O' ]] ||
		skip "path $plain is not in 'O/1/d<n>/<n>' format"

	size=$(do_facet $SINGLEMDS "$DEBUGFS -c -R 'dump $plain $tmpfile' \
		$mdt_dev; stat -c %s $tmpfile")
	echo "Truncate llog from $size to $((size - size % 8192))"
	size=$((size - size % 8192))
	do_facet $SINGLEMDS $TRUNCATE $tmpfile $size
	errs=$(do_facet $SINGLEMDS "$llog_reader $tmpfile" |
		grep -c 'in bitmap only')
	(( $errs > 0 )) || error "llog_reader didn't find lost records"

	size=$((size - 9000))
	echo "Corrupt llog in the middle at $size"
	do_facet $SINGLEMDS dd if=/dev/urandom of=$tmpfile bs=1 seek=$size \
		count=333 conv=notrunc
	errs=$(do_facet $SINGLEMDS "$llog_reader $tmpfile" |
		grep -c 'next chunk')
	(( $errs > 0 )) || error "llog_reader didn't skip bad chunk"
}
run_test 60j "llog_reader reports corruptions"

test_61a() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	f="$DIR/f61"
	dd if=/dev/zero of=$f bs=$PAGE_SIZE count=1 || error "dd $f failed"
	cancel_lru_locks osc
	$MULTIOP $f OSMWUc || error "$MULTIOP $f failed"
	sync
}
run_test 61a "mmap() writes don't make sync hang ================"

test_61b() {
	mmap_mknod_test $DIR/$tfile || error "mmap_mknod_test failed"
}
run_test 61b "mmap() of unstriped file is successful"

# bug 2319 - oig_wait() interrupted causes crash because of invalid waitq.
# Though this test is irrelevant anymore, it helped to reveal some
# other grant bugs (LU-4482), let's keep it.
test_63a() {   # was test_63
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	MAX_DIRTY_MB=$(lctl get_param -n osc.*.max_dirty_mb | head -n 1)

	for i in `seq 10` ; do
		dd if=/dev/zero of=$DIR/f63 bs=8k &
		sleep 5
		kill $!
		sleep 1
	done

	rm -f $DIR/f63 || true
}
run_test 63a "Verify oig_wait interruption does not crash ======="

# bug 2248 - async write errors didn't return to application on sync
# bug 3677 - async write errors left page locked
test_63b() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	debugsave
	lctl set_param debug=-1

	# ensure we have a grant to do async writes
	dd if=/dev/zero of=$DIR/$tfile bs=4k count=1
	rm $DIR/$tfile

	sync	# sync lest earlier test intercept the fail_loc

	#define OBD_FAIL_OSC_BRW_PREP_REQ        0x406
	lctl set_param fail_loc=0x80000406
	$MULTIOP $DIR/$tfile Owy && \
		error "sync didn't return ENOMEM"
	sync; sleep 2; sync	# do a real sync this time to flush page
	lctl get_param -n llite.*.dump_page_cache | grep locked && \
		error "locked page left in cache after async error" || true
	debugrestore
}
run_test 63b "async write errors should be returned to fsync ==="

test_63c() {
	stack_trap "$LCTL set_param $($LCTL get_param llite.*.sync_on_close)"
	$LCTL set_param llite.$FSNAME*.sync_on_close=1
	local count=20
	local dir=$DIR/$tdir

	mkdir $dir || error "mkdir $dir failed"
	# ensure only a single OST stripe per file so accounting works
	$LFS setstripe -c 1 $dir || error "setstripe $dir failed"

	# open+create files without writing, expect one MDT sync for each
	# MDT (N*open/create)
	local mdt_before=$(calc_stats mdc.*.stats mds_sync)
	local ost_before=$(calc_stats osc.*.stats ost_sync)
	createmany -o $dir/$tfile-empty- $count ||
		error "'createmany -o $tfile-empty $count' failed"
	local mdt_after=$(calc_stats mdc.*.stats mds_sync)
	local ost_after=$(calc_stats osc.*.stats ost_sync)
	(( $mdt_after == $mdt_before + $count )) ||
		error "expect MDT create $mdt_after == $mdt_before + $count"
	(( $ost_after == $ost_before )) ||
		error "expect OST create $ost_after == $ost_before"

	# append data to existing files, expect one OST sync for each
	# MDT(open) OST(N*setattr)
	mdt_before=$mdt_after
	ost_before=$ost_after
	for ((i = 0; i < count; i++)); do
		echo "foo-$i" >> $dir/$tfile-empty-$i ||
			error "write $tfile-empty-$i failed"
	done
	mdt_after=$(calc_stats mdc.*.stats mds_sync)
	ost_after=$(calc_stats osc.*.stats ost_sync)
	(( $mdt_after == $mdt_before )) ||
		error "expect MDT write $mdt_after == $mdt_before"
	(( $ost_after == $ost_before + $count )) ||
		error "expect OST write $ost_after == $ost_before + $count"

	# overwrite same file notrunc+fsync, expect only one OST sync for each
	# MDT (open/create), OST (N*write+sync)
	mdt_before=$mdt_after
	ost_before=$ost_after
	for ((i = 0; i < count; i++)); do
		dd if=/dev/zero of=$dir/$tfile-1 bs=4k count=2 \
			conv=notrunc,fsync status=none ||
			error "dd $tfile-1 $i failed"
	done
	mdt_after=$(calc_stats mdc.*.stats mds_sync)
	ost_after=$(calc_stats osc.*.stats ost_sync)
	(( $mdt_after == $mdt_before + 1 )) ||
		error "expect MDT write+sync $mdt_after == $mdt_before + 1"
	(( $ost_after == $ost_before + $count )) ||
		error "expect OST write+sync $ost_after == $ost_before + $count"

	# extend existing file, expect one OST sync for each
	# OST (write)
	mdt_before=$mdt_after
	ost_before=$ost_after
	for ((i = 0; i < count; i++)); do
		dd if=/dev/zero of=$dir/$tfile-1 bs=4k count=2 seek=$((i+1)) \
		   conv=notrunc status=none ||
			error "dd append $tfile-1 $i failed"
	done
	mdt_after=$(calc_stats mdc.*.stats mds_sync)
	ost_after=$(calc_stats osc.*.stats ost_sync)
	(( $mdt_after == $mdt_before )) ||
		error "expect MDT append $mdt_after == $mdt_before"
	(( $ost_after == $ost_before + $count )) ||
		error "expect OST append $ost_after == $ost_before + $count"

	# list directory, expect no MDT or OST sync
	# MDT (readdir,getattr), OST (getattr)
	mdt_before=$mdt_after
	ost_before=$ost_after
	ls -l $dir || error "ls -l $dir failed"
	mdt_after=$(calc_stats mdc.*.stats mds_sync)
	ost_after=$(calc_stats osc.*.stats ost_sync)
	(( $mdt_after == $mdt_before )) ||
		error "expect MDT ls $mdt_after == $mdt_before"
	(( $ost_after == $ost_before )) ||
		error "expect OST ls $ost_after == $ost_before"

	# truncate existing files, expect one MDT+OST sync for each
	# MDT (open+truncate) OST (truncate)
	mdt_before=$mdt_after
	ost_before=$ost_after
	for ((i = 0; i < count; i++)); do
		> $dir/$tfile-empty-$i || error "truncate $tfile-empty-$i fail"
	done
	mdt_after=$(calc_stats mdc.*.stats mds_sync)
	ost_after=$(calc_stats osc.*.stats ost_sync)
	(( $mdt_after == $mdt_before + $count)) ||
		error "expect MDT truncate $mdt_after == $mdt_before + $count"
	(( $ost_after == $ost_before + $count )) ||
		error "expect OST truncate $ost_after == $ost_before + $count"

	stack_trap "set_default_debug"
	set_default_debug "rpctrace+dlmtrace+inode+entry" "" 512
	# write to multi-striped file, expect one MDT+OSTCOUNT OST sync
	# MDT (create/setstripe+truncate), OST (8*OSTCOUNT*write)
	mdt_before=$mdt_after
	ost_before=$ost_after
	$LFS setstripe -c $OSTCOUNT -S 1M $dir/$tfile-striped
	local stripes=$($LFS getstripe -c $dir/$tfile-striped)
	stack_trap "rm -f $dir/$tfile-stripes"
	dd if=/dev/zero of=$dir/$tfile-striped bs=1M count=$((8 * $stripes)) ||
		error "dd striped $tfile-striped failed"
	mdt_after=$(calc_stats mdc.*.stats mds_sync)
	ost_after=$(calc_stats osc.*.stats ost_sync)
	(( $mdt_after == $mdt_before + 2 )) ||
		error "expect MDT striped $mdt_after == $mdt_before + 2"
	(( $ost_after >= $ost_before + $stripes &&
	   $ost_after < $ost_before + 2 * $stripes )) ||
		error "expect OST striped $ost_after == $ost_before + $stripes"

	# read file, expect no MDT or OST sync
	# MDT(open), OST(2*OSTCOUNT*read)
	mdt_before=$mdt_after
	ost_before=$ost_after
	dd if=$dir/$tfile-1 of=/dev/null bs=4k status=none ||
		error "dd read $tfile-1 failed"
	dd if=$dir/$tfile-striped of=/dev/null bs=1M status=none ||
		error "dd read $tfile-1 failed"
	mdt_after=$(calc_stats mdc.*.stats mds_sync)
	ost_after=$(calc_stats osc.*.stats ost_sync)
	(( $mdt_after == $mdt_before )) ||
		error "expect MDT read $mdt_after == $mdt_before"
	(( $ost_after == $ost_before )) ||
		error "expect OST read $ost_after == $ost_before"
}
run_test 63c "test sync_on_close=1"

test_64a () {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	lfs df $DIR
	lctl get_param osc.*[oO][sS][cC][_-]*.cur* | grep "=[1-9]"
}
run_test 64a "verify filter grant calculations (in kernel) ====="

test_64b () {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	bash oos.sh $MOUNT || error "oos.sh failed: $?"
}
run_test 64b "check out-of-space detection on client"

test_64c() {
	$LCTL set_param osc.*OST0000-osc-[^mM]*.cur_grant_bytes=0
}
run_test 64c "verify grant shrink"

# this does exactly what osc_request.c:osc_announce_cached() does in
# order to calculate max amount of grants to ask from server
want_grant() {
	local tgt=$1

	local nrpages=$($LCTL get_param -n osc.$tgt.max_pages_per_rpc)
	local rpc_in_flight=$($LCTL get_param -n osc.$tgt.max_rpcs_in_flight)

	((rpc_in_flight++));
	nrpages=$((nrpages * rpc_in_flight))

	local dirty_max_pages=$($LCTL get_param -n osc.$tgt.max_dirty_mb)

	dirty_max_pages=$((dirty_max_pages * 1024 * 1024 / PAGE_SIZE))

	[[ $dirty_max_pages -gt $nrpages ]] && nrpages=$dirty_max_pages
	local undirty=$((nrpages * PAGE_SIZE))

	local max_extent_pages
	max_extent_pages=$(import_param $tgt grant_max_extent_size)
	max_extent_pages=$((max_extent_pages / PAGE_SIZE))
	local nrextents=$(((nrpages + max_extent_pages - 1) / max_extent_pages))
	local grant_extent_tax
	grant_extent_tax=$(import_param $tgt grant_extent_tax)

	undirty=$((undirty + nrextents * grant_extent_tax))

	echo $undirty
}

# this is size of unit for grant allocation. It should be equal to
# what tgt_grant.c:tgt_grant_chunk() calculates
grant_chunk() {
	local tgt=$1
	local max_brw_size
	local grant_extent_tax

	max_brw_size=$(import_param $tgt max_brw_size)

	grant_extent_tax=$(import_param $tgt grant_extent_tax)

	echo $(((max_brw_size + grant_extent_tax) * 2))
}

test_64d() {
	[ $OST1_VERSION -ge $(version_code 2.10.56) ] ||
		skip "OST < 2.10.55 doesn't limit grants enough"

	local tgt=$($LCTL dl | awk '/OST0000-osc-[^mM]/ { print $4 }')

	[[ "$($LCTL get_param osc.${tgt}.import)" =~ "grant_param" ]] ||
		skip "no grant_param connect flag"

	local olddebug="$($LCTL get_param -n debug 2> /dev/null)"

	$LCTL set_param -n -n debug="$OLDDEBUG" || true
	stack_trap "$LCTL set_param -n debug='$olddebug'" EXIT


	local max_cur_granted=$(($(want_grant $tgt) + $(grant_chunk $tgt)))
	stack_trap "rm -f $DIR/$tfile && wait_delete_completed" EXIT

	$LFS setstripe $DIR/$tfile -i 0 -c 1
	dd if=/dev/zero of=$DIR/$tfile bs=1M count=1000 &
	ddpid=$!

	while kill -0 $ddpid; do
		local cur_grant=$($LCTL get_param -n osc.$tgt.cur_grant_bytes)

		if [[ $cur_grant -gt $max_cur_granted ]]; then
			kill $ddpid
			error "cur_grant $cur_grant > $max_cur_granted"
		fi

		sleep 1
	done
}
run_test 64d "check grant limit exceed"

check_grants() {
	local tgt=$1
	local expected=$2
	local msg=$3
	local cur_grants=$($LCTL get_param -n osc.$tgt.cur_grant_bytes)

	((cur_grants == expected)) ||
		error "$msg: grants mismatch: $cur_grants, expected $expected"
}

round_up_p2() {
	echo $((($1 + $2 - 1) & ~($2 - 1)))
}

test_64e() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ $OST1_VERSION -ge $(version_code 2.11.56) ] ||
		skip "Need OSS version at least 2.11.56"

	local olddebug="$($LCTL get_param -n debug 2> /dev/null)"
	stack_trap "$LCTL set_param -n debug='$olddebug'" EXIT
	$LCTL set_param debug=+cache

	# Remount client to reset grant
	remount_client $MOUNT || error "failed to remount client"
	local osc_tgt="$FSNAME-OST0000-osc-$($LFS getname -i $DIR)"

	local init_grants=$(import_param $osc_tgt initial_grant)

	check_grants $osc_tgt $init_grants "init grants"

	local extent_tax=$(import_param $osc_tgt grant_extent_tax)
	local max_brw_size=$(import_param $osc_tgt max_brw_size)
	local gbs=$(import_param $osc_tgt grant_block_size)

	# write random number of bytes from max_brw_size / 4 to max_brw_size
	local write_bytes=$(shuf -i $((max_brw_size / 4))-$max_brw_size -n 1)
	# align for direct io
	write_bytes=$(round_up_p2 $write_bytes PAGE_SIZE)
	# round to grant consumption unit
	local wb_round_up=$(round_up_p2 $write_bytes gbs)

	local grants=$((wb_round_up + extent_tax))

	$LFS setstripe -c 1 -i 0 $DIR/$tfile  || error "lfs setstripe failed"
	stack_trap "rm -f $DIR/$tfile"

	# define OBD_FAIL_TGT_NO_GRANT 0x725
	# make the server not grant more back
	do_facet ost1 $LCTL set_param fail_loc=0x725
	dd if=/dev/zero of=$DIR/$tfile bs=$write_bytes count=1 oflag=direct

	do_facet ost1 $LCTL set_param fail_loc=0

	check_grants $osc_tgt $((init_grants - grants)) "dio w/o grant alloc"

	rm -f $DIR/$tfile || error "rm failed"

	# Remount client to reset grant
	remount_client $MOUNT || error "failed to remount client"
	osc_tgt="$FSNAME-OST0000-osc-$($LFS getname -i $DIR)"

	$LFS setstripe -c 1 -i 0 $DIR/$tfile || error "lfs setstripe failed"

	# define OBD_FAIL_TGT_NO_GRANT 0x725
	# make the server not grant more back
	do_facet ost1 $LCTL set_param fail_loc=0x725
	$MULTIOP $DIR/$tfile "oO_WRONLY:w${write_bytes}yc"
	do_facet ost1 $LCTL set_param fail_loc=0

	check_grants $osc_tgt $((init_grants - grants)) "buf io w/o grant alloc"
}
run_test 64e "check grant consumption (no grant allocation)"

test_64f() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	local olddebug="$($LCTL get_param -n debug 2> /dev/null)"
	stack_trap "$LCTL set_param -n debug='$olddebug'" EXIT
	$LCTL set_param debug=+cache

	# Remount client to reset grant
	remount_client $MOUNT || error "failed to remount client"
	local osc_tgt="$FSNAME-OST0000-osc-$($LFS getname -i $DIR)"

	local init_grants=$(import_param $osc_tgt initial_grant)
	local extent_tax=$(import_param $osc_tgt grant_extent_tax)
	local max_brw_size=$(import_param $osc_tgt max_brw_size)
	local gbs=$(import_param $osc_tgt grant_block_size)
	local chunk=$(grant_chunk $osc_tgt)

	# write random number of bytes from max_brw_size / 4 to max_brw_size
	local write_bytes=$(shuf -i $((max_brw_size / 4))-$max_brw_size -n 1)
	# align for direct io
	write_bytes=$(round_up_p2 $write_bytes PAGE_SIZE)
	# round to grant consumption unit
	local wb_round_up=$(round_up_p2 $write_bytes gbs)

	local grants=$((wb_round_up + extent_tax))

	$LFS setstripe -c 1 -i 0 $DIR/$tfile || error "lfs setstripe failed"
	dd if=/dev/zero of=$DIR/$tfile bs=$write_bytes count=1 oflag=direct ||
		error "error writing to $DIR/$tfile"
	stack_trap "rm -f $DIR/$tfile"

	check_grants $osc_tgt $((init_grants - grants + chunk)) \
		"direct io with grant allocation"

	rm -f $DIR/$tfile || error "rm failed"

	# Remount client to reset grant
	remount_client $MOUNT || error "failed to remount client"
	osc_tgt="$FSNAME-OST0000-osc-$($LFS getname -i $DIR)"

	$LFS setstripe -c 1 -i 0 $DIR/$tfile || error "lfs setstripe failed"

	# Hybrid means this won't really be buffered IO, so we disable it for
	# this part of the test
	local hybrid=$($LCTL get_param -n llite.*.hybrid_io)
	$LCTL set_param llite.*.hybrid_io=0
	stack_trap "$LCTL set_param -n llite.*.hybrid_io=$hybrid" EXIT
	# Testing that buffered IO consumes grant on the client

	# Delay the RPC on the server so it's guaranteed to not complete even
	# if the RPC is sent from the client
	#define OBD_FAIL_PTLRPC_PAUSE_REQ        0x50a
	$LCTL set_param fail_loc=0x50a fail_val=3
	dd if=/dev/zero of=$DIR/$tfile bs=$write_bytes count=1 conv=notrunc ||
		error "error writing to $DIR/$tfile with buffered IO"

	check_grants $osc_tgt $((init_grants - grants)) \
		"buffered io, not write rpc"

	# Clear the fail loc and do a sync on the client
	$LCTL set_param fail_loc=0 fail_val=0
	sync

	# RPC is now known to have sent
	check_grants $osc_tgt $((init_grants - grants + chunk)) \
		"buffered io, one RPC"
}
run_test 64f "check grant consumption (with grant allocation)"

test_64g() {
	(( $MDS1_VERSION >= $(version_code 2.14.56) )) ||
		skip "Need MDS version at least 2.14.56"

	local mdts=$(mdts_nodes)

	local old=$($LCTL get_param mdc.$FSNAME-*.grant_shrink_interval |
			tr '\n' ' ')
	stack_trap "$LCTL set_param $old"

	# generate dirty pages and increase dirty granted on MDT
	stack_trap "rm -f $DIR/$tfile-*"
	for (( i = 0; i < 10; i++)); do
		$LFS setstripe -E 1M -L mdt $DIR/$tfile-$i ||
			error "can't set stripe"
		dd if=/dev/zero of=$DIR/$tfile-$i bs=128k count=1 ||
			error "can't dd"
		$LFS getstripe $DIR/$tfile-$i | grep -q pattern.*mdt || {
			$LFS getstripe $DIR/$tfile-$i
			error "not DoM file"
		}
	done

	# flush dirty pages
	sync

	# wait until grant shrink reset grant dirty on MDTs
	for ((i = 0; i < 120; i++)); do
		grant_dirty=$(do_nodes $mdts $LCTL get_param -n  mdt.*.tot_dirty |
			awk '{sum=sum+$1} END {print sum}')
		vm_dirty=$(awk '/Dirty:/{print $2}' /proc/meminfo)
		echo "$grant_dirty grants, $vm_dirty pages"
		(( grant_dirty + vm_dirty == 0 )) && break
		(( i == 3 )) && sync &&
			$LCTL set_param mdc.$FSNAME-*.grant_shrink_interval=5
		sleep 1
	done

	grant_dirty=$(do_nodes $mdts $LCTL get_param -n  mdt.*.tot_dirty |
		awk '{sum=sum+$1} END {print sum}')
	(( grant_dirty == 0 )) || error "$grant_dirty on MDT"
}
run_test 64g "grant shrink on MDT"

test_64h() {
	(( $OST1_VERSION >= $(version_code 2.14.56) )) ||
		skip "need OST at least 2.14.56 to avoid grant shrink on read"

	local instance=$($LFS getname -i $DIR)
	local osc_tgt="$FSNAME-OST0000-osc-$instance"
	local num_exps=$(do_facet ost1 \
	    $LCTL get_param -n obdfilter.*OST0000*.num_exports)
	local max_brw_size=$(import_param $osc_tgt max_brw_size)
	local avail=$($LCTL get_param -n osc.*OST0000-osc-$instance.kbytesavail)
	local p="$TMP/$TESTSUITE-$TESTNAME.parameters"

	# 10MiB is for file to be written, max_brw_size * 16 *
	# num_exps is space reserve so that tgt_grant_shrink() decided
	# to not shrink
	local expect=$((max_brw_size * 16 * num_exps + 10 * 1048576))
	(( avail * 1024 < expect )) &&
		skip "need $expect bytes on ost1, have $(( avail * 1024 )) only"

	save_lustre_params client "osc.*OST0000*.grant_shrink" > $p
	save_lustre_params client "osc.*OST0000*.grant_shrink_interval" >> $p
	stack_trap "restore_lustre_params < $p; rm -f $p" EXIT
	$LCTL set_param osc.*OST0000*.grant_shrink=1
	$LCTL set_param osc.*OST0000*.grant_shrink_interval=10

	$LFS setstripe -c 1 -i 0 $DIR/$tfile
	stack_trap "rm -f $DIR/$tfile"
	dd if=/dev/zero of=$DIR/$tfile bs=1M count=10 oflag=sync

	# drop cache so that coming read would do rpc
	cancel_lru_locks osc

	# shrink interval is set to 10, pause for 7 seconds so that
	# grant thread did not wake up yet but coming read entered
	# shrink mode for rpc (osc_should_shrink_grant())
	sleep 7

	declare -a cur_grant_bytes
	declare -a tot_granted
	cur_grant_bytes[0]=$($LCTL get_param -n osc.*OST0000*.cur_grant_bytes)
	tot_granted[0]=$(do_facet ost1 \
	    $LCTL get_param -n obdfilter.*OST0000*.tot_granted)

	dd if=$DIR/$tfile bs=4K count=1 of=/dev/null

	cur_grant_bytes[1]=$($LCTL get_param -n osc.*OST0000*.cur_grant_bytes)
	tot_granted[1]=$(do_facet ost1 \
	    $LCTL get_param -n obdfilter.*OST0000*.tot_granted)

	# grant change should be equal on both sides
	(( cur_grant_bytes[0] - cur_grant_bytes[1] ==
		tot_granted[0] - tot_granted[1])) ||
		error "grant change mismatch, "				       \
			"server: ${tot_granted[0]} to ${tot_granted[1]}, "     \
			"client: ${cur_grant_bytes[0]} to ${cur_grant_bytes[1]}"
}
run_test 64h "grant shrink on read"

test_64i() {
	(( $OST1_VERSION >= $(version_code 2.14.56) )) ||
		skip "need OST at least 2.14.56 to avoid grant shrink on replay"

	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_ost_nodsh && skip "remote OSTs with nodsh"

	$LFS setstripe -c 1 -i 0 $DIR/$tfile
	stack_trap "rm -f $DIR/$tfile"

	dd if=/dev/zero of=$DIR/$tfile bs=1M count=64

	# lustre-ffff9fc75e850800 /mnt/lustre -> ffff9fc75e850800
	local instance=$($LFS getname -i $DIR)

	local osc_tgt="$FSNAME-OST0000-osc-$instance"
	local cgb=$($LCTL get_param -n osc.$osc_tgt.cur_grant_bytes)

	# shrink grants and simulate rpc loss
	#define OBD_FAIL_PTLRPC_DROP_REQ_OPC	 0x513
	do_facet ost1 "$LCTL set_param fail_loc=0x80000513 fail_val=17"
	$LCTL set_param osc.$osc_tgt.cur_grant_bytes=$((cgb/2))B

	fail ost1

	dd if=/dev/zero of=$DIR/$tfile oflag=append bs=1M count=8 conv=notrunc

	local testid=$(echo $TESTNAME | tr '_' ' ')

	do_facet ost1 dmesg | tac | sed "/$testid/,$ d" |
		grep "GRANT, real grant" &&
		error "client has more grants then it owns" || true
}
run_test 64i "shrink on reconnect"

test_64j() {
	$LFS setstripe -c 1 -i 0 $DIR/$tfile

	# get rid of lost grants which could be formed on previous test
	$MULTIOP $DIR/$tfile oO_RDWR:O_SYNC:w4096c
#define OBD_FAIL_OST_GRANT_PREPARE      0x256
	do_facet ost1 "$LCTL set_param fail_loc=0x80000256"

	$MULTIOP $DIR/$tfile oO_RDWR:O_DIRECT:w4096c
}
run_test 64j "check grants on re-done rpc"

# bug 1414 - set/get directories' stripe info
test_65a() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	# LU-16904 check if the root is set as PFL layout
	local numcomp=$($LFS getstripe --component-count $MOUNT)
	[ $numcomp -eq 0 ] || skip "Skip test_65a for PFL layout"

	test_mkdir $DIR/$tdir
	touch $DIR/$tdir/f1
	$LVERIFY $DIR/$tdir $DIR/$tdir/f1 || error "lverify failed"
}
run_test 65a "directory with no stripe info"

test_65b() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	test_mkdir $DIR/$tdir
	local STRIPESIZE=$($LFS getstripe -S $DIR/$tdir)

	$LFS setstripe -S $((STRIPESIZE * 2)) -i 0 -c 1 $DIR/$tdir ||
						error "setstripe"
	touch $DIR/$tdir/f2
	$LVERIFY $DIR/$tdir $DIR/$tdir/f2 || error "lverify failed"
}
run_test 65b "directory setstripe -S stripe_size*2 -i 0 -c 1"

test_65c() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ $OSTCOUNT -lt 2 ] && skip_env "need at least 2 OSTs"

	test_mkdir $DIR/$tdir
	local stripesize=$($LFS getstripe -S $DIR/$tdir)

	$LFS setstripe -S $((stripesize * 4)) -i 1 \
		-c $((OSTCOUNT - 1)) $DIR/$tdir || error "setstripe"
	touch $DIR/$tdir/f3
	$LVERIFY $DIR/$tdir $DIR/$tdir/f3 || error "lverify failed"
}
run_test 65c "directory setstripe -S stripe_size*4 -i 1 -c $((OSTCOUNT-1))"

test_65d() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	test_mkdir $DIR/$tdir
	local STRIPECOUNT=$($LFS getstripe -c $DIR/$tdir)
	local STRIPESIZE=$($LFS getstripe -S $DIR/$tdir)

	if [[ $STRIPECOUNT -le 0 ]]; then
		sc=1
	elif [[ $STRIPECOUNT -gt $LOV_MAX_STRIPE_COUNT ]]; then
		[[ $OSTCOUNT -gt $LOV_MAX_STRIPE_COUNT ]] &&
			sc=$LOV_MAX_STRIPE_COUNT || sc=$(($OSTCOUNT - 1))
	else
		sc=$(($STRIPECOUNT - 1))
	fi
	$LFS setstripe -S $STRIPESIZE -c $sc $DIR/$tdir || error "setstripe"
	touch $DIR/$tdir/f4 $DIR/$tdir/f5
	$LVERIFY $DIR/$tdir $DIR/$tdir/f4 $DIR/$tdir/f5 ||
		error "lverify failed"
}
run_test 65d "directory setstripe -S stripe_size -c stripe_count"

test_65e() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	# LU-16904 delete layout when root is set as PFL layout
	save_layout_restore_at_exit $MOUNT
	$LFS setstripe -d $MOUNT || error "setstripe failed"

	test_mkdir $DIR/$tdir

	$LFS setstripe $DIR/$tdir || error "setstripe"
	$LFS getstripe -v $DIR/$tdir | grep "Default" ||
					error "no stripe info failed"
	touch $DIR/$tdir/f6
	$LVERIFY $DIR/$tdir $DIR/$tdir/f6 || error "lverify failed"
}
run_test 65e "directory setstripe defaults"

test_65f() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	test_mkdir $DIR/${tdir}f
	$RUNAS $LFS setstripe $DIR/${tdir}f &&
		error "setstripe succeeded" || true
}
run_test 65f "dir setstripe permission (should return error) ==="

test_65g() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	# LU-16904 delete layout when root is set as PFL layout
	save_layout_restore_at_exit $MOUNT
	$LFS setstripe -d $MOUNT || error "setstripe failed"

	test_mkdir $DIR/$tdir
	local STRIPESIZE=$($LFS getstripe -S $DIR/$tdir)

	$LFS setstripe -S $((STRIPESIZE * 2)) -i 0 -c 1 $DIR/$tdir ||
		error "setstripe -S failed"
	$LFS setstripe -d $DIR/$tdir || error "setstripe -d failed"
	$LFS getstripe -v $DIR/$tdir | grep "Default" ||
		error "delete default stripe failed"
}
run_test 65g "directory setstripe -d"

test_65h() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	test_mkdir $DIR/$tdir
	local STRIPESIZE=$($LFS getstripe -S $DIR/$tdir)

	$LFS setstripe -S $((STRIPESIZE * 2)) -i 0 -c 1 $DIR/$tdir ||
		error "setstripe -S failed"
	test_mkdir $DIR/$tdir/dd1
	[ $($LFS getstripe -c $DIR/$tdir) = $($LFS getstripe -c $DIR/$tdir/dd1) ] ||
		error "stripe info inherit failed"
}
run_test 65h "directory stripe info inherit ===================="

test_65i() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	save_layout_restore_at_exit $MOUNT

	# bug6367: set non-default striping on root directory
	$LFS setstripe -S 65536 -c -1 $MOUNT || error "error setting stripe"

	# bug12836: getstripe on -1 default directory striping
	$LFS getstripe $MOUNT || error "getstripe $MOUNT failed"

	# bug12836: getstripe -v on -1 default directory striping
	$LFS getstripe -v $MOUNT || error "getstripe -v $MOUNT failed"

	# bug12836: new find on -1 default directory striping
	$LFS find -mtime -1 $MOUNT > /dev/null || error "find $MOUNT failed"
}
run_test 65i "various tests to set root directory striping"

test_65j() { # bug6367
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	sync; sleep 1

	# if we aren't already remounting for each test, do so for this test
	if [ "$I_MOUNTED" = "yes" ]; then
		cleanup || error "failed to unmount"
		setup
	fi

	save_layout_restore_at_exit $MOUNT

	$LFS setstripe -d $MOUNT || error "setstripe failed"
}
run_test 65j "set default striping on root directory (bug 6367)="

cleanup_65k() {
	rm -rf $DIR/$tdir
	wait_delete_completed
	do_facet $SINGLEMDS "lctl set_param -n \
		osp.$ost*MDT0000.max_create_count=$max_count"
	do_facet $SINGLEMDS "lctl set_param -n \
		osp.$ost*MDT0000.create_count=$count"
	do_facet $SINGLEMDS lctl --device  %$INACTIVE_OSC activate
	echo $INACTIVE_OSC "is Activate"

	wait_osc_import_state mds ost$(( ostnum + 1 )) FULL
}

test_65k() { # bug11679
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[[ $OSTCOUNT -lt 2 ]] && skip_env "needs >= 2 OSTs"
	remote_mds_nodsh && skip "remote MDS with nodsh"

	local disable_precreate=true
	[ $MDS1_VERSION -le $(version_code 2.8.54) ] &&
		disable_precreate=false

	echo "Check OST status: "
	local MDS_OSCS=$(do_facet $SINGLEMDS lctl dl |
		awk '/[oO][sS][cC].*md[ts]/ { print $4 }')

	for OSC in $MDS_OSCS; do
		echo $OSC "is active"
		do_facet $SINGLEMDS lctl --device %$OSC activate
	done

	for INACTIVE_OSC in $MDS_OSCS; do
		local ost=$(osc_to_ost $INACTIVE_OSC)
		local ostnum=$(do_facet $SINGLEMDS lctl get_param -n \
			       lov.*md*.target_obd |
			       awk -F: /$ost/'{ print $1 }' | head -n 1)

		mkdir -p $DIR/$tdir
		$LFS setstripe -i $ostnum -c 1 $DIR/$tdir
		createmany -o $DIR/$tdir/$tfile.$ostnum. 1000

		echo "Deactivate: " $INACTIVE_OSC
		do_facet $SINGLEMDS lctl --device %$INACTIVE_OSC deactivate

		local count=$(do_facet $SINGLEMDS "lctl get_param -n \
			      osp.$ost*MDT0000.create_count")
		local max_count=$(do_facet $SINGLEMDS "lctl get_param -n \
				  osp.$ost*MDT0000.max_create_count")
		$disable_precreate &&
			do_facet $SINGLEMDS "lctl set_param -n \
				osp.$ost*MDT0000.max_create_count=0"

		for idx in $(seq 0 $((OSTCOUNT - 1))); do
			[ -f $DIR/$tdir/$idx ] && continue
			echo "$LFS setstripe -i $idx -c 1 $DIR/$tdir/$idx"
			$LFS setstripe -i $idx -c 1 $DIR/$tdir/$idx ||
				{ cleanup_65k;
				  error "setstripe $idx should succeed"; }
			rm -f $DIR/$tdir/$idx || error "rm $idx failed"
		done
		unlinkmany $DIR/$tdir/$tfile.$ostnum. 1000
		rmdir $DIR/$tdir

		do_facet $SINGLEMDS "lctl set_param -n \
			osp.$ost*MDT0000.max_create_count=$max_count"
		do_facet $SINGLEMDS "lctl set_param -n \
			osp.$ost*MDT0000.create_count=$count"
		do_facet $SINGLEMDS lctl --device  %$INACTIVE_OSC activate
		echo $INACTIVE_OSC "is Activate"

		wait_osc_import_state mds ost$(( ostnum + 1 )) FULL
	done
}
run_test 65k "validate manual striping works properly with deactivated OSCs"

test_65l() { # bug 12836
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	test_mkdir -p $DIR/$tdir/test_dir
	$LFS setstripe -c -1 $DIR/$tdir/test_dir
	$LFS find -mtime -1 $DIR/$tdir >/dev/null
}
run_test 65l "lfs find on -1 stripe dir ========================"

test_65m() {
	local layout=$(save_layout $MOUNT)
	$RUNAS $LFS setstripe -c 2 $MOUNT && {
		restore_layout $MOUNT $layout
		error "setstripe should fail by non-root users"
	}
	true
}
run_test 65m "normal user can't set filesystem default stripe"

test_65n() {
	[ -n "$FILESET" ] && skip "Not functional for FILESET set"
	[[ $MDS1_VERSION -ge $(version_code 2.12.50) ]] ||
		skip "Need MDS version at least 2.12.50"
	[[ $PARALLEL != "yes" ]] || skip "skip parallel run"

	[[ $OSTCOUNT -ge 2 ]] || skip_env "needs >= 2 OSTs"
	which getfattr > /dev/null 2>&1 || skip_env "no getfattr command"
	which setfattr > /dev/null 2>&1 || skip_env "no setfattr command"

	save_layout_restore_at_exit $MOUNT

	# new subdirectory under root directory should not inherit
	# the default layout from root
	# LU-16904 check if the root is set as PFL layout
	local numcomp=$($LFS getstripe --component-count $MOUNT)

	if [[ $numcomp -eq 0 ]]; then
		local dir1=$MOUNT/$tdir-1
		mkdir $dir1 || error "mkdir $dir1 failed"
		! getfattr -n trusted.lov $dir1 &> /dev/null ||
			error "$dir1 shouldn't have LOV EA"
	fi

	# delete the default layout on root directory
	$LFS setstripe -d $MOUNT || error "delete root default layout failed"

	local dir2=$MOUNT/$tdir-2
	mkdir $dir2 || error "mkdir $dir2 failed"
	! getfattr -n trusted.lov $dir2 &> /dev/null ||
		error "$dir2 shouldn't have LOV EA"

	# set a new striping pattern on root directory
	local def_stripe_size=$($LFS getstripe -S $MOUNT)
	local new_def_stripe_size=$((def_stripe_size * 2))
	$LFS setstripe -S $new_def_stripe_size $MOUNT ||
		error "set stripe size on $MOUNT failed"

	# new file created in $dir2 should inherit the new stripe size from
	# the filesystem default
	local file2=$dir2/$tfile-2
	touch $file2 || error "touch $file2 failed"

	local file2_stripe_size=$($LFS getstripe -S $file2)
	[[ $file2_stripe_size -eq $new_def_stripe_size ]] ||
	{
		echo "file2_stripe_size: '$file2_stripe_size'"
		echo "new_def_stripe_size: '$new_def_stripe_size'"
		error "$file2 didn't inherit stripe size $new_def_stripe_size"
	}

	local dir3=$MOUNT/$tdir-3
	mkdir $dir3 || error "mkdir $dir3 failed"
	# $dir3 shouldn't have LOV EA, but "lfs getstripe -d $dir3" should show
	# the root layout, which is the actual default layout that will be used
	# when new files are created in $dir3.
	local dir3_layout=$(get_layout_param $dir3)
	local root_dir_layout=$(get_layout_param $MOUNT)
	[[ "$dir3_layout" = "$root_dir_layout" ]] ||
	{
		echo "dir3_layout: '$dir3_layout'"
		echo "root_dir_layout: '$root_dir_layout'"
		error "$dir3 should show the default layout from $MOUNT"
	}

	# set OST pool on root directory
	local pool=$TESTNAME
	pool_add $pool || error "add $pool failed"
	pool_add_targets $pool 0 $((OSTCOUNT - 1)) 1 ||
		error "add targets to $pool failed"

	$LFS setstripe -p $pool $MOUNT ||
		error "set OST pool on $MOUNT failed"

	# new file created in $dir3 should inherit the pool from
	# the filesystem default
	local file3=$dir3/$tfile-3
	touch $file3 || error "touch $file3 failed"

	local file3_pool=$($LFS getstripe -p $file3)
	[[ "$file3_pool" = "$pool" ]] ||
		error "$file3 ('$file3_pool') didn't inherit OST pool '$pool'"

	local dir4=$MOUNT/$tdir-4
	mkdir $dir4 || error "mkdir $dir4 failed"
	local dir4_layout=$(get_layout_param $dir4)
	root_dir_layout=$(get_layout_param $MOUNT)
	echo "$LFS getstripe -d $dir4"
	$LFS getstripe -d $dir4
	echo "$LFS getstripe -d $MOUNT"
	$LFS getstripe -d $MOUNT
	[[ "$dir4_layout" = "$root_dir_layout" ]] ||
	{
		echo "dir4_layout: '$dir4_layout'"
		echo "root_dir_layout: '$root_dir_layout'"
		error "$dir4 should show the default layout from $MOUNT"
	}

	# new file created in $dir4 should inherit the pool from
	# the filesystem default
	local file4=$dir4/$tfile-4
	touch $file4 || error "touch $file4 failed"

	local file4_pool=$($LFS getstripe -p $file4)
	[[ "$file4_pool" = "$pool" ]] ||
		error "$file4 ('$file4_pool') didn't inherit OST pool $pool"

	# new subdirectory under non-root directory should inherit
	# the default layout from its parent directory
	$LFS setstripe -S $new_def_stripe_size -p $pool $dir4 ||
		error "set directory layout on $dir4 failed"

	local dir5=$dir4/$tdir-5
	mkdir $dir5 || error "mkdir $dir5 failed"

	dir4_layout=$(get_layout_param $dir4)
	local dir5_layout=$(get_layout_param $dir5)
	[[ "$dir4_layout" = "$dir5_layout" ]] ||
	{
		echo "dir4_layout: '$dir4_layout'"
		echo "dir5_layout: '$dir5_layout'"
		error "$dir5 should inherit the default layout from $dir4"
	}

	# though subdir under ROOT doesn't inherit default layout, but
	# its sub dir/file should be created with default layout.
	[[ $MDSCOUNT -ge 2 ]] || skip_env "needs >= 2 MDTs"
	[[ $MDS1_VERSION -ge $(version_code 2.12.59) ]] ||
		skip "Need MDS version at least 2.12.59"

	local default_lmv_count=$($LFS getdirstripe -D -c $MOUNT)
	local default_lmv_index=$($LFS getdirstripe -D -i $MOUNT)
	local default_lmv_hash=$($LFS getdirstripe -D -H $MOUNT)

	if [ $default_lmv_hash == "none" ]; then
		stack_trap "$LFS setdirstripe -D -d $MOUNT" EXIT
	else
		stack_trap "$LFS setdirstripe -D -i $default_lmv_index \
			-c $default_lmv_count -H $default_lmv_hash $MOUNT" EXIT
	fi

	$LFS setdirstripe -D -c 2 $MOUNT ||
		error "setdirstripe -D -c 2 failed"
	mkdir $MOUNT/$tdir-6 || error "mkdir $tdir-6 failed"
	local lmv_count=$($LFS getdirstripe -c $MOUNT/$tdir-6)
	[ $lmv_count -eq 2 ] || error "$tdir-6 stripe count $lmv_count"

	(( $MDS1_VERSION >= $(version_code v2_14_57-22-g6e59408f1a) )) ||
		skip "Need MDS >= 2.14.57.22 for proper pool inheritance"
	# $dir4 layout includes pool
	$LFS setstripe -S $((new_def_stripe_size * 2)) $dir4
	[[ "$pool" = $($LFS getstripe -p -d $dir4) ]] ||
		error "pool lost on setstripe"
	$LFS setstripe -E -1 -S $new_def_stripe_size $dir4
	[[ "$pool" = $($LFS getstripe -p -d $dir4) ]] ||
		error "pool lost on compound layout setstripe"
}
run_test 65n "don't inherit default layout from root for new subdirectories"

test_65o() {
	(( $MDS1_VERSION >= $(version_code 2.14.57) )) ||
		skip "need MDS version at least 2.14.57"

	# set OST pool on root directory
	local pool=$TESTNAME

	pool_add $pool || error "add $pool failed"
	pool_add_targets $pool 0 $((OSTCOUNT - 1)) 1 ||
		error "add targets to $pool failed"

	local dir1=$MOUNT/$tdir

	mkdir $dir1 || error "mkdir $dir1 failed"

	# set a new striping pattern on root directory
	local def_stripe_size=$($LFS getstripe -S $MOUNT)

	$LFS setstripe -p $pool $dir1 ||
		error "set directory layout on $dir1 failed"

	# $dir1 layout includes pool
	$LFS setstripe -S $((def_stripe_size * 2)) $dir1
	[[ "$pool" = $($LFS getstripe -p -d $dir1) ]] ||
		error "pool lost on setstripe"
	$LFS setstripe -E 1M -L mdt -E -1 -c 1 $dir1
	$LFS getstripe $dir1
	[[ "$pool" = $($LFS getstripe -p -d $dir1) ]] ||
		error "pool lost on compound layout setstripe"

	$LFS setdirstripe -i 0 -c 2 $dir1/dir2 ||
		error "setdirstripe failed on sub-dir with inherited pool"
	$LFS getstripe $dir1/dir2
	[[ "$pool" = $($LFS getstripe -p -d $dir1/dir2) ]] ||
		error "pool lost on compound layout setdirstripe"

	$LFS setstripe -E -1 -c 1 $dir1
	$LFS getstripe -d $dir1
	[[ "$pool" = $($LFS getstripe -p -d $dir1) ]] ||
		error "pool lost on setstripe"
}
run_test 65o "pool inheritance for mdt component"

test_65p () { # LU-16152
	local src_dir=$DIR/$tdir/src_dir
	local dst_dir=$DIR/$tdir/dst_dir
	local yaml_file=$DIR/$tdir/layout.yaml
	local border

	(( $CLIENT_VERSION >= $(version_code 2.15.51) )) ||
		skip "Need at least version 2.15.51"

	test_mkdir -p $src_dir
	$LFS setstripe -E 2048M -c 4 -E EOF -c 8 $src_dir ||
		error "failed to setstripe"
	$LFS getstripe --yaml -d $src_dir > $yaml_file ||
		error "failed to getstripe"

	test_mkdir -p $dst_dir
	$LFS setstripe --yaml $yaml_file $dst_dir ||
		error "failed to setstripe with yaml file"
	border=$($LFS getstripe -d $dst_dir |
		awk '/lcme_extent.e_end:/ { print $2; exit; }') ||
		error "failed to getstripe"

	# 2048M is 0x80000000, or 2147483648
	(( $border == 2147483648 )) ||
		error "failed to handle huge number in yaml layout"
}
run_test 65p "setstripe with yaml file and huge number"

test_65q () { # LU-16194
	local src_dir=$DIR/$tdir/src_dir

	(( $CLIENT_VERSION >= $(version_code 2.15.51) )) &&
	(( $MDS1_VERSION >= $(version_code 2.15.51) )) ||
		skip "Need at least version 2.15.51"

	test_mkdir -p $src_dir
	# 8E is 0x8000 0000 0000 0000, which is negative as s64
	$LFS setstripe -E 8E -c 4 -E EOF -c 8 $src_dir &&
		error "should fail if extent start/end >=8E"

	# EOF should work as before
	$LFS setstripe -E 8M -c 4 -E EOF -c 8 $src_dir ||
		error "failed to setstripe normally"
}
run_test 65q "setstripe with >=8E offset should fail"

65r_check_offsets() {
	local offsets
	local all_zeroes=1
	local pfl=$1

	offsets=$($LFS getstripe -y $pfl | awk '/stripe_offset:/ { print $2 }')
	for off in ${offsets[@]}; do
		((off == 0)) || all_zeroes=0
	done
	echo $all_zeroes
}

test_65r() { #LU-13062
	(( OSTCOUNT >= 2 )) || skip_env "needs >= 2 OSTs"

	local dir=$DIR/$tdir
	local pfl=$DIR/$tdir/$tfile

	test_mkdir -p $DIR/$tdir
	# lfs setstripe can set all 0 offsets directly
	$LFS setstripe -E1m -c1 -i0 -E2m -c2 -i0 -E4m -c4 -i0 -E -1 -i0 $pfl ||
		error "Create file $pfl failed"
	(( $(65r_check_offsets $pfl) == 1 )) ||
		error "lfs setstripe directions are ignored"

	# lfs setstripe --copy should reset specified offsets to default
	lfs setstripe --copy=$pfl ${pfl}.copy ||
		error "lfs setstripe --copy failed"
	(( $(65r_check_offsets ${pfl}.copy) == 0 )) ||
		error "lfs setstripe --copy keeps specific offsets"

	# directory layout copy should drop specific offsets
	$LFS setstripe -E1m -c1 -i0 -E2m -c2 -i0 -E4m -c4 -i0 -E -1 -i0 $dir ||
		error "Failed to set default layout for $dir"
	lfs setstripe --copy=$dir ${pfl}.dircopy ||
		error "lfs setstripe --copy from directory failed"
	(( $(65r_check_offsets ${pfl}.dircopy) == 0 )) ||
		error "lfs setstripe --copy for directory keeps offsets"
}
run_test 65r "prevent all-zero offsets"

# bug 2543 - update blocks count on client
test_66() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	local COUNT=${COUNT:-8}
	dd if=/dev/urandom of=$DIR/f66 bs=1k count=$COUNT
	sync; sync_all_data; sync; sync_all_data
	cancel_lru_locks osc
	local BLOCKS=$(ls -s --block-size=1k $DIR/f66 | awk '{ print $1 }')
	(( BLOCKS >= COUNT )) || error "$DIR/f66 blocks $BLOCKS < $COUNT"
}
run_test 66 "update inode blocks count on client ==============="

meminfo() {
	awk '($1 == "'$1':") { print $2 }' /proc/meminfo
}

swap_used() {
	swapon -s | awk '($1 == "'$1'") { print $4 }'
}

# bug5265, obdfilter oa2dentry return -ENOENT
# #define OBD_FAIL_SRV_ENOENT 0x217
test_69() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_ost_nodsh && skip "remote OST with nodsh"

	f="$DIR/$tfile"
	$LFS setstripe -c 1 -i 0 $f
	stack_trap "rm -f $f ${f}.2"

	$DIRECTIO write ${f}.2 0 1 || error "directio write error"

	do_facet ost1 lctl set_param fail_loc=0x217
	$TRUNCATE $f 1 # vmtruncate() will ignore truncate() error.
	$DIRECTIO write $f 0 2 && error "write succeeded, expect -ENOENT"

	do_facet ost1 lctl set_param fail_loc=0
	$DIRECTIO write $f 0 2 || error "write error"

	cancel_lru_locks osc
	$DIRECTIO read $f 0 1 || error "read error"

	do_facet ost1 lctl set_param fail_loc=0x217
	$DIRECTIO read $f 1 1 && error "read succeeded, expect -ENOENT"

	do_facet ost1 lctl set_param fail_loc=0
}
run_test 69 "verify oa2dentry return -ENOENT doesn't LBUG ======"

test_70a() {
	# Perform a really simple test of health write and health check
	(( $OST1_VERSION >= $(version_code 2.15.59) )) ||
		skip "OSTs < 2.15.59 doesn't have enable_health_write"

	local orig_value="$(do_facet ost1 $LCTL get_param -n enable_health_write)"

	stack_trap "do_facet ost1 $LCTL set_param enable_health_write $orig_value"

	# Test with health write off
	do_facet ost1 $LCTL set_param enable_health_write off ||
		error "can't set enable_health_write off"
	do_facet ost1 $LCTL get_param enable_health_write ||
		error "can't get enable_health_write"

	[[ "$(do_facet ost1 $LCTL get_param health_check)" =~ "healthy" ]] ||
		error "not healthy (1)"

	# Test with health write on
	do_facet ost1 $LCTL set_param enable_health_write on ||
		error "can't set enable_health_write on"
	do_facet ost1 $LCTL get_param enable_health_write ||
		error "can't get enable_health_write"

	[[ "$(do_facet ost1 $LCTL get_param health_check)" =~ "healthy" ]] ||
		error "not healthy (2)"
}
run_test 70a "verify health_check, health_write don't explode (on OST)"

test_71() {
	test_mkdir $DIR/$tdir
	$LFS setdirstripe -D -c$MDSCOUNT $DIR/$tdir
	bash rundbench -C -D $DIR/$tdir 2 || error "dbench failed!"
}
run_test 71 "Running dbench on lustre (don't segment fault) ===="

test_72a() { # bug 5695 - Test that on 2.6 remove_suid works properly
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ "$RUNAS_ID" = "$UID" ] &&
		skip_env "RUNAS_ID = UID = $UID -- skipping"
	# Check that testing environment is properly set up. Skip if not
	FAIL_ON_ERROR=false check_runas_id_ret $RUNAS_ID $RUNAS_GID $RUNAS ||
		skip_env "User $RUNAS_ID does not exist - skipping"

	touch $DIR/$tfile
	chmod 777 $DIR/$tfile
	chmod ug+s $DIR/$tfile
	$RUNAS dd if=/dev/zero of=$DIR/$tfile bs=512 count=1 ||
		error "$RUNAS dd $DIR/$tfile failed"
	# See if we are still setuid/sgid
	[ -u $DIR/$tfile ] || [ -g $DIR/$tfile ] &&
		error "S/gid is not dropped on write"
	# Now test that MDS is updated too
	cancel_lru_locks mdc
	[ -u $DIR/$tfile ] || [ -g $DIR/$tfile ] &&
		error "S/gid is not dropped on MDS"
	rm -f $DIR/$tfile
}
run_test 72a "Test that remove suid works properly (bug5695) ===="

test_72b() { # bug 24226 -- keep mode setting when size is not changing
	local perm

	[ "$RUNAS_ID" = "$UID" ] &&
		skip_env "RUNAS_ID = UID = $UID -- skipping"
	[ "$RUNAS_ID" -eq 0 ] &&
		skip_env "RUNAS_ID = 0 -- skipping"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	# Check that testing environment is properly set up. Skip if not
	FAIL_ON_ERROR=false check_runas_id_ret $RUNAS_ID $RUNAS_ID $RUNAS ||
		skip_env "User $RUNAS_ID does not exist - skipping"

	touch $DIR/${tfile}-f{g,u}
	test_mkdir $DIR/${tfile}-dg
	test_mkdir $DIR/${tfile}-du
	chmod 770 $DIR/${tfile}-{f,d}{g,u}
	chmod g+s $DIR/${tfile}-{f,d}g
	chmod u+s $DIR/${tfile}-{f,d}u
	for perm in 777 2777 4777; do
		$RUNAS chmod $perm $DIR/${tfile}-fg && error "S/gid file allowed improper chmod to $perm"
		$RUNAS chmod $perm $DIR/${tfile}-fu && error "S/uid file allowed improper chmod to $perm"
		$RUNAS chmod $perm $DIR/${tfile}-dg && error "S/gid dir allowed improper chmod to $perm"
		$RUNAS chmod $perm $DIR/${tfile}-du && error "S/uid dir allowed improper chmod to $perm"
	done
	true
}
run_test 72b "Test that we keep mode setting if without file data changed (bug 24226)"

# bug 3462 - multiple simultaneous MDC requests
test_73() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	test_mkdir $DIR/d73-1
	test_mkdir $DIR/d73-2
	multiop_bg_pause $DIR/d73-1/f73-1 O_c || return 1
	pid1=$!

	lctl set_param fail_loc=0x80000129
	$MULTIOP $DIR/d73-1/f73-2 Oc &
	sleep 1
	lctl set_param fail_loc=0

	$MULTIOP $DIR/d73-2/f73-3 Oc &
	pid3=$!

	kill -USR1 $pid1
	wait $pid1 || return 1

	sleep 25

	$CHECKSTAT -t file $DIR/d73-1/f73-1 || return 4
	$CHECKSTAT -t file $DIR/d73-1/f73-2 || return 5
	$CHECKSTAT -t file $DIR/d73-2/f73-3 || return 6

	rm -rf $DIR/d73-*
}
run_test 73 "multiple MDC requests (should not deadlock)"

test_74a() { # bug 6149, 6184
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	touch $DIR/f74a
	#define OBD_FAIL_LDLM_ENQUEUE_OLD_EXPORT 0x30e
	#
	# very important to OR with CFS_FAIL_ONCE (0x80000000) -- otherwise it
	# will spin in a tight reconnection loop
	$LCTL set_param fail_loc=0x8000030e
	# get any lock that won't be difficult - lookup works.
	ls $DIR/f74a
	$LCTL set_param fail_loc=0
	rm -f $DIR/f74a
	true
}
run_test 74a "ldlm_enqueue freed-export error path, ls (shouldn't LBUG)"

test_74b() { # bug 13310
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	#define OBD_FAIL_LDLM_ENQUEUE_OLD_EXPORT 0x30e
	#
	# very important to OR with CFS_FAIL_ONCE (0x80000000) -- otherwise it
	# will spin in a tight reconnection loop
	$LCTL set_param fail_loc=0x8000030e
	# get a "difficult" lock
	touch $DIR/f74b
	$LCTL set_param fail_loc=0
	rm -f $DIR/f74b
	true
}
run_test 74b "ldlm_enqueue freed-export error path, touch (shouldn't LBUG)"

test_74c() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	#define OBD_FAIL_LDLM_NEW_LOCK
	$LCTL set_param fail_loc=0x319
	touch $DIR/$tfile && error "touch successful"
	$LCTL set_param fail_loc=0
	true
}
run_test 74c "ldlm_lock_create error path, (shouldn't LBUG)"

slab_lic=/sys/kernel/slab/lustre_inode_cache
num_objects() {
	[ -f $slab_lic/shrink ] && echo 1 > $slab_lic/shrink
	[ -f $slab_lic/objects ] && awk '{ print $1 }' $slab_lic/objects ||
		awk '/lustre_inode_cache/ { print $2; exit }' /proc/slabinfo
}

test_76a() { # Now for b=20433, added originally in b=1443
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	cancel_lru_locks osc
	# there may be some slab objects cached per core
	local cpus=$(getconf _NPROCESSORS_ONLN 2>/dev/null)
	local before=$(num_objects)
	local count=$((512 * cpus))
	[ "$SLOW" = "no" ] && count=$((128 * cpus))
	local margin=$((count / 10))
	if [[ -f $slab_lic/aliases ]]; then
		local aliases=$(cat $slab_lic/aliases)
		(( aliases > 0 )) && margin=$((margin * aliases))
	fi

	echo "before slab objects: $before"
	for i in $(seq $count); do
		touch $DIR/$tfile
		rm -f $DIR/$tfile
	done
	cancel_lru_locks osc
	local after=$(num_objects)
	echo "created: $count, after slab objects: $after"
	# shared slab counts are not very accurate, allow significant margin
	# the main goal is that the cache growth is not permanently > $count
	while (( after > before + margin )); do
		sleep 1
		after=$(num_objects)
		wait=$((wait + 1))
		(( wait % 5 == 0 )) && echo "wait $wait seconds objects: $after"
		if (( wait > 60 )); then
			error "inode slab grew from $before+$margin to $after"
		fi
	done
}
run_test 76a "confirm clients recycle inodes properly ===="

test_76b() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ $CLIENT_VERSION -ge $(version_code 2.13.55) ] || skip "not supported"

	local count=512
	local before=$(num_objects)

	for i in $(seq $count); do
		mkdir $DIR/$tdir
		rmdir $DIR/$tdir
	done

	local after=$(num_objects)
	local wait=0

	while (( after > before )); do
		sleep 1
		after=$(num_objects)
		wait=$((wait + 1))
		(( wait % 5 == 0 )) && echo "wait $wait seconds objects: $after"
		if (( wait > 60 )); then
			error "inode slab grew from $before to $after"
		fi
	done

	echo "slab objects before: $before, after: $after"
}
run_test 76b "confirm clients recycle directory inodes properly ===="

export ORIG_CSUM=""
set_checksums()
{
	# Note: in sptlrpc modes which enable its own bulk checksum, the
	# original crc32_le bulk checksum will be automatically disabled,
	# and the OBD_FAIL_OSC_CHECKSUM_SEND/OBD_FAIL_OSC_CHECKSUM_RECEIVE
	# will be checked by sptlrpc code against sptlrpc bulk checksum.
	# In this case set_checksums() will not be no-op, because sptlrpc
	# bulk checksum will be enabled all through the test.

	[ "$ORIG_CSUM" ] || ORIG_CSUM=`lctl get_param -n osc.*.checksums | head -n1`
        lctl set_param -n osc.*.checksums $1
	return 0
}

export ORIG_CSUM_TYPE="`lctl get_param -n osc.*osc-[^mM]*.checksum_type |
                        sed 's/.*\[\(.*\)\].*/\1/g' | head -n1`"
CKSUM_TYPES=${CKSUM_TYPES:-$(lctl get_param -n osc.*osc-[^mM]*.checksum_type |
			     tr -d [] | head -n1)}
set_checksum_type()
{
	lctl set_param -n osc.*osc-[^mM]*.checksum_type $1
	rc=$?
	log "set checksum type to $1, rc = $rc"
	return $rc
}

get_osc_checksum_type()
{
	# arugment 1: OST name, like OST0000
	ost=$1
	checksum_type=$(lctl get_param -n osc.*${ost}-osc-[^mM]*.checksum_type |
			sed 's/.*\[\(.*\)\].*/\1/g')
	rc=$?
	[ $rc -ne 0 ] && error "failed to get checksum type of $ost, rc = $rc, output = $checksum_type"
	echo $checksum_type
}

F77_TMP=$TMP/f77-temp
F77SZ=8
setup_f77() {
	dd if=/dev/urandom of=$F77_TMP bs=1M count=$F77SZ || \
		error "error writing to $F77_TMP"
}

test_77a() { # bug 10889
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	$GSS && skip_env "could not run with gss"

	[ ! -f $F77_TMP ] && setup_f77
	set_checksums 1
	dd if=$F77_TMP of=$DIR/$tfile bs=1M count=$F77SZ || error "dd error"
	set_checksums 0
	rm -f $DIR/$tfile
}
run_test 77a "normal checksum read/write operation"

test_77b() { # bug 10889
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	$GSS && skip_env "could not run with gss"

	[ ! -f $F77_TMP ] && setup_f77
	#define OBD_FAIL_OSC_CHECKSUM_SEND       0x409
	$LCTL set_param fail_loc=0x80000409
	set_checksums 1

	dd if=$F77_TMP of=$DIR/$tfile bs=1M count=$F77SZ conv=sync ||
		error "dd error: $?"
	$LCTL set_param fail_loc=0

	for algo in $CKSUM_TYPES; do
		cancel_lru_locks osc
		set_checksum_type $algo
		#define OBD_FAIL_OSC_CHECKSUM_RECEIVE    0x408
		$LCTL set_param fail_loc=0x80000408
		cmp $F77_TMP $DIR/$tfile || error "file compare failed"
		$LCTL set_param fail_loc=0
	done
	set_checksums 0
	set_checksum_type $ORIG_CSUM_TYPE
	rm -f $DIR/$tfile
}
run_test 77b "checksum error on client write, read"

cleanup_77c() {
	trap 0
	set_checksums 0
	$LCTL set_param osc.*osc-[^mM]*.checksum_dump=0
	$check_ost &&
		do_facet ost1 $LCTL set_param obdfilter.*-OST*.checksum_dump=0
	[ -n "$osc_file_prefix" ] && rm -f ${osc_file_prefix}*
	$check_ost && [ -n "$ost_file_prefix" ] &&
		do_facet ost1 rm -f ${ost_file_prefix}\*
}

test_77c() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	$GSS && skip_env "could not run with gss"
	remote_ost_nodsh && skip "remote OST with nodsh"

	local bad1
	local osc_file_prefix
	local osc_file
	local check_ost=false
	local ost_file_prefix="$TMP/lustre-log"
	local ost_file
	local orig_cksum
	local dump_cksum
	local fid
	local old_ost_path=$(do_facet ost1 $LCTL get_param -n debug_path)

	stack_trap "do_facet ost1 $LCTL set_param debug_path=$old_ost_path"
	do_facet ost1 $LCTL set_param debug_path=${ost_file_prefix}

	# ensure corruption will occur on first OSS/OST
	$LFS setstripe -i 0 $DIR/$tfile

	[ ! -f $F77_TMP ] && setup_f77
	dd if=$F77_TMP of=$DIR/$tfile bs=1M count=$F77SZ conv=sync ||
		error "dd write error: $?"
	fid=$($LFS path2fid $DIR/$tfile)

	if [ $OST1_VERSION -ge $(version_code 2.9.57) ]
	then
		check_ost=true
		ost_file_prefix=${ost_file_prefix}-checksum_dump-ost-\\${fid}
	else
		echo "OSS do not support bulk pages dump upon error"
	fi

	osc_file_prefix=$($LCTL get_param -n debug_path)
	osc_file_prefix=${osc_file_prefix}-checksum_dump-osc-\\${fid}

	trap cleanup_77c EXIT

	set_checksums 1
	# enable bulk pages dump upon error on Client
	$LCTL set_param osc.*osc-[^mM]*.checksum_dump=1
	# enable bulk pages dump upon error on OSS
	$check_ost &&
		do_facet ost1 $LCTL set_param obdfilter.*-OST*.checksum_dump=1

	# flush Client cache to allow next read to reach OSS
	cancel_lru_locks osc

	#define OBD_FAIL_OSC_CHECKSUM_RECEIVE       0x408
	$LCTL set_param fail_loc=0x80000408
	dd if=$DIR/$tfile of=/dev/null bs=1M || error "dd read error: $?"
	$LCTL set_param fail_loc=0

	rm -f $DIR/$tfile

	# check cksum dump on Client
	osc_file=$(ls ${osc_file_prefix}*)
	[ -n "$osc_file" ] || error "no checksum dump file on Client"
	# OBD_FAIL_OSC_CHECKSUM_RECEIVE corrupts with "bad1" at start of file
	bad1=$(dd if=$osc_file bs=1 count=4 2>/dev/null) || error "dd error: $?"
	[ $bad1 == "bad1" ] || error "unexpected corrupt pattern"
	orig_cksum=$(dd if=$F77_TMP bs=1 skip=4 count=1048572 2>/dev/null |
		     cksum)
	dump_cksum=$(dd if=$osc_file bs=1 skip=4 2>/dev/null | cksum)
	[[ "$orig_cksum" == "$dump_cksum" ]] ||
		error "dump content does not match on Client"

	$check_ost || skip "No need to check cksum dump on OSS"

	# check cksum dump on OSS
	ost_file=$(do_facet ost1 ls ${ost_file_prefix}\*)
	[ -n "$ost_file" ] || error "no checksum dump file on OSS"
	orig_cksum=$(dd if=$F77_TMP bs=1048576 count=1 2>/dev/null | cksum)
	dump_cksum=$(do_facet ost1 dd if=$ost_file 2>/dev/null \| cksum)
	[[ "$orig_cksum" == "$dump_cksum" ]] ||
		error "dump content does not match on OSS"

	cleanup_77c
}
run_test 77c "checksum error on client read with debug"

test_77d() { # bug 10889
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	$GSS && skip_env "could not run with gss"

	stack_trap "rm -f $DIR/$tfile"
	#define OBD_FAIL_OSC_CHECKSUM_SEND       0x409
	$LCTL set_param fail_loc=0x80000409
	set_checksums 1
	$DIRECTIO write $DIR/$tfile 0 $F77SZ $((1024 * 1024)) ||
		error "direct write: rc=$?"
	$LCTL set_param fail_loc=0
	set_checksums 0

	#define OBD_FAIL_OSC_CHECKSUM_RECEIVE    0x408
	$LCTL set_param fail_loc=0x80000408
	set_checksums 1
	cancel_lru_locks osc
	$DIRECTIO read $DIR/$tfile 0 $F77SZ $((1024 * 1024)) ||
		error "direct read: rc=$?"
	$LCTL set_param fail_loc=0
	set_checksums 0
}
run_test 77d "checksum error on OST direct write, read"

test_77f() { # bug 10889
	[[ $PARALLEL == "yes" ]] && skip "skip parallel run"
	$GSS && skip_env "could not run with gss"

	stack_trap "$LCTL set_param $($LCTL get_param -b osc.*.resend_count)"
	$LCTL set_param osc.*.resend_count=1
	set_checksums 1
	stack_trap "set_checksum_type $ORIG_CSUM_TYPE"
	stack_trap "rm -f $DIR/$tfile.*"
	for algo in $CKSUM_TYPES; do
		cancel_lru_locks osc
		set_checksum_type $algo
		#define OBD_FAIL_OSC_CHECKSUM_SEND       0x409
		$LCTL set_param fail_loc=0x409
		$DIRECTIO write $DIR/$tfile.$algo 0 $F77SZ $((1024 * 1024)) &&
			error "direct write succeeded"
		$LCTL set_param fail_loc=0
	done
}
run_test 77f "repeat checksum error on write (expect error)"

test_77g() { # bug 10889
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	$GSS && skip_env "could not run with gss"
	remote_ost_nodsh && skip "remote OST with nodsh"

	[ ! -f $F77_TMP ] && setup_f77

	local file=$DIR/$tfile
	stack_trap "rm -f $file" EXIT

	$LFS setstripe -c 1 -i 0 $file
	#define OBD_FAIL_OST_CHECKSUM_RECEIVE       0x21a
	do_facet ost1 lctl set_param fail_loc=0x8000021a
	set_checksums 1
	dd if=$F77_TMP of=$file bs=1M count=$F77SZ ||
		error "write error: rc=$?"
	do_facet ost1 lctl set_param fail_loc=0
	set_checksums 0

	cancel_lru_locks osc
	#define OBD_FAIL_OST_CHECKSUM_SEND          0x21b
	do_facet ost1 lctl set_param fail_loc=0x8000021b
	set_checksums 1
	cmp $F77_TMP $file || error "file compare failed"
	do_facet ost1 lctl set_param fail_loc=0
	set_checksums 0
}
run_test 77g "checksum error on OST write, read"

test_77k() { # LU-10906
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	$GSS && skip_env "could not run with gss"

	local cksum_param="osc.$FSNAME*.checksums"
	local get_checksum="$LCTL get_param -n $cksum_param | head -n1"
	local checksum
	local i

	[ "$ORIG_CSUM" ] || ORIG_CSUM=$(eval $get_checksum)
	stack_trap "wait_update $HOSTNAME '$get_checksum' $ORIG_CSUM || true"
	stack_trap "do_facet mgs $LCTL set_param -P $cksum_param=$ORIG_CSUM"

	set_checksums 1 # so wait_update below will really wait for MGS
	for i in 0 1; do
		do_facet mgs $LCTL set_param -P $cksum_param=$i ||
			error "failed to set checksum=$i on MGS"
		wait_update $HOSTNAME "$get_checksum" $i
		#remount
		echo "remount client, checksum should be $i"
		remount_client $MOUNT || error "failed to remount client"
		sleep 1 # to don't race with setting from mount for sure
		checksum=$(eval $get_checksum)
		[ $checksum -eq $i ] || error "checksum($checksum) != $i"
	done
	# remove persistent param to avoid races with checksum mountopt below
	do_facet mgs $LCTL set_param -P -d $cksum_param ||
		error "failed to delete checksum on MGS"

	for opt in "checksum" "nochecksum"; do
		#remount with mount option
		echo "remount client with option $opt, checksum should be $i"
		umount_client $MOUNT || error "failed to umount client"
		mount_client $MOUNT "$MOUNT_OPTS,$opt" ||
			error "failed to mount client with option '$opt'"
		checksum=$(eval $get_checksum)
		[ $checksum -eq $i ] || error "checksum($checksum) != $i"
		i=$((i - 1))
	done

	remount_client $MOUNT || error "failed to remount client"
}
run_test 77k "enable/disable checksum correctly"

test_77l() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	$GSS && skip_env "could not run with gss"

	set_checksums 1
	stack_trap "set_checksums $ORIG_CSUM" EXIT
	stack_trap "set_checksum_type $ORIG_CSUM_TYPE" EXIT
	local old

	old=$($LCTL get_param -n osc.*.idle_timeout | head -n 1)
	$LCTL set_param osc.*.idle_timeout=10
	stack_trap "$LCTL set_param osc.*.idle_timeout=$old" EXIT

	set_checksum_type invalid && error "unexpected success of invalid checksum type"

	$LFS setstripe -c 1 -i 0 $DIR/$tfile
	for algo in $CKSUM_TYPES; do
		set_checksum_type $algo || error "fail to set checksum type $algo"
		osc_algo=$(get_osc_checksum_type OST0000)
		[ "$osc_algo" != "$algo" ] && error "checksum type is $osc_algo after setting it to $algo"

		# no locks, no reqs to let the connection idle
		cancel_lru_locks osc
		lru_resize_disable osc
		wait_osc_import_state client ost1 IDLE

		# ensure ost1 is connected
		stat $DIR/$tfile >/dev/null || error "can't stat"
		wait_osc_import_state client ost1 FULL

		osc_algo=$(get_osc_checksum_type OST0000)
		[ "$osc_algo" != "$algo" ] && error "checksum type changed from $algo to $osc_algo after reconnection"
	done
	return 0
}
run_test 77l "preferred checksum type is remembered after reconnected"

[ "$ORIG_CSUM" ] && set_checksums $ORIG_CSUM || true
rm -f $F77_TMP
unset F77_TMP

test_77m() {
	(( $CLIENT_VERSION >= $(version_code 2.14.52) )) ||
		skip "Need at least version 2.14.52"
	local param=checksum_speed

	$LCTL get_param $param || error "reading $param failed"

	csum_speeds=$($LCTL get_param -n $param)

	[[ "$csum_speeds" =~ "adler32" && "$csum_speeds" =~ "crc32" ]] ||
		error "known checksum types are missing"
}
run_test 77m "Verify checksum_speed is correctly read"

check_filefrag_77n() {
	local nr_ext=0
	local starts=()
	local ends=()

	while read extidx a b start end rest; do
		if [[ "${extidx}" =~ ^[0-9]+: ]]; then
			nr_ext=$(( $nr_ext + 1 ))
			starts+=( ${start%..} )
			ends+=( ${end%:} )
		fi
	done < <( filefrag -sv $1 )

	[[ $nr_ext -eq 2 ]] && [[ "${starts[-1]}" == $(( ${ends[0]} + 1 )) ]] && return 0
	return 1
}

test_77n() {
	local filefrag_op=$(filefrag -l 2>&1 | grep "invalid option")
	[[ -z "$filefrag_op" ]] || skip_env "filefrag missing logical ordering"
	[[ "$CKSUM_TYPES" =~ t10 ]] || skip "no T10 checksum support on osc"

	touch $DIR/$tfile
	$TRUNCATE $DIR/$tfile 0
	dd if=/dev/urandom of=$DIR/$tfile bs=4k conv=notrunc count=1 seek=0
	dd if=/dev/urandom of=$DIR/$tfile bs=4k conv=notrunc count=1 seek=2
	check_filefrag_77n $DIR/$tfile ||
		skip "$tfile blocks not contiguous around hole"

	set_checksums 1
	stack_trap "set_checksums $ORIG_CSUM" EXIT
	stack_trap "set_checksum_type $ORIG_CSUM_TYPE" EXIT
	stack_trap "rm -f $DIR/$tfile"

	for algo in $CKSUM_TYPES; do
		if [[ "$algo" =~ ^t10 ]]; then
			set_checksum_type $algo ||
				error "fail to set checksum type $algo"
			dd if=$DIR/$tfile of=/dev/null bs=12k count=1 iflag=direct ||
				error "fail to read $tfile with $algo"
		fi
	done
	rm -f $DIR/$tfile
	return 0
}
run_test 77n "Verify read from a hole inside contiguous blocks with T10PI"

test_77o() {
	(( $MDS1_VERSION >= $(version_code 2.14.55) )) ||
		skip "Need MDS version at least 2.14.55"
	(( $OST1_VERSION >= $(version_code 2.14.55) )) ||
		skip "Need OST version at least 2.14.55"
	local ofd=obdfilter
	local mdt=mdt

	# print OST checksum_type
	echo "$ofd.$FSNAME-*.checksum_type:"
	do_nodes $(osts_nodes) "$LCTL get_param -n $ofd.$FSNAME-*.checksum_type"

	# print MDT checksum_type
	echo "$mdt.$FSNAME-*.checksum_type:"
	do_nodes $(mdts_nodes) "$LCTL get_param -n $mdt.$FSNAME-*.checksum_type"

	local o_count=$(do_nodes $(osts_nodes) \
		   $LCTL get_param -n $ofd.$FSNAME-*.checksum_type | wc -l)

	(( $o_count == $OSTCOUNT )) ||
		error "found $o_count checksums, not \$OSTCOUNT=$OSTCOUNT"

	local m_count=$(do_nodes $(mdts_nodes) \
		   $LCTL get_param -n $mdt.$FSNAME-*.checksum_type | wc -l)

	(( $m_count == $MDSCOUNT )) ||
		error "found $m_count checksums, not \$MDSCOUNT=$MDSCOUNT"
}
run_test 77o "Verify checksum_type for server (mdt and ofd(obdfilter))"

cleanup_test_78() {
	trap 0
	rm -f $DIR/$tfile
}

test_78() { # bug 10901
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_ost || skip_env "local OST"

	NSEQ=5
	F78SIZE=$(($(awk '/MemFree:/ { print $2 }' /proc/meminfo) / 1024))
	echo "MemFree: $F78SIZE, Max file size: $MAXFREE"
	MEMTOTAL=$(($(awk '/MemTotal:/ { print $2 }' /proc/meminfo) / 1024))
	echo "MemTotal: $MEMTOTAL"

	# reserve 256MB of memory for the kernel and other running processes,
	# and then take 1/2 of the remaining memory for the read/write buffers.
	if [ $MEMTOTAL -gt 512 ] ;then
		MEMTOTAL=$(((MEMTOTAL - 256 ) / 2))
	else
		# for those poor memory-starved high-end clusters...
		MEMTOTAL=$((MEMTOTAL / 2))
	fi
	echo "Mem to use for directio: $MEMTOTAL"

	[[ $F78SIZE -gt $MEMTOTAL ]] && F78SIZE=$MEMTOTAL
	[[ $F78SIZE -gt 512 ]] && F78SIZE=512
	[[ $F78SIZE -gt $((MAXFREE / 1024)) ]] && F78SIZE=$((MAXFREE / 1024))
	SMALLESTOST=$($LFS df --output=avail --no-header -o $DIR | sort -n |
		      head -1)
	echo "Smallest OST: $SMALLESTOST"
	[[ $SMALLESTOST -lt 10240 ]] &&
		skip "too small OSTSIZE, useless to run large O_DIRECT test"

	trap cleanup_test_78 EXIT

	[[ $F78SIZE -gt $((SMALLESTOST * $OSTCOUNT / 1024 - 80)) ]] &&
		F78SIZE=$((SMALLESTOST * $OSTCOUNT / 1024 - 80))

	[ "$SLOW" = "no" ] && NSEQ=1 && [ $F78SIZE -gt 32 ] && F78SIZE=32
	echo "File size: $F78SIZE"
	$LFS setstripe -c $OSTCOUNT $DIR/$tfile || error "setstripe failed"
	for i in $(seq 1 $NSEQ); do
		FSIZE=$(($F78SIZE / ($NSEQ - $i + 1)))
		echo directIO rdwr round $i of $NSEQ
		$DIRECTIO rdwr $DIR/$tfile 0 $FSIZE 1048576||error "rdwr failed"
	done

	cleanup_test_78
}
run_test 78 "handle large O_DIRECT writes correctly ============"

test_79() { # bug 12743
	[[ $PARALLEL != "yes" ]] || skip "skip parallel run"

	wait_delete_completed

	local bktotal=$(calc_osc_kbytes kbytestotal)
	local bkfree=$(calc_osc_kbytes kbytesfree)
	local bkavail=$(calc_osc_kbytes kbytesavail)
	local string=($(df -P $MOUNT | tail -n 1))
	local dftotal=${string[1]}
	local dfused=${string[2]}
	local dfavail=${string[3]}
	local dffree=$(($dftotal - $dfused))
	local allowance=$((64 * $OSTCOUNT))

	$LFS df $MOUNT
	echo ${string[*]}

	(( dftotal >= bktotal - allowance && dftotal <= bktotal + allowance)) ||
		error "df total($dftotal) mismatch OST total($bktotal)"
	(( dffree >= bkfree - allowance && dffree <= bkfree + allowance )) ||
		error "df free($dffree) mismatch OST free($bkfree)"
	(( dfavail >= bkavail - allowance && dfavail <= bkavail + allowance)) ||
		error "df avail($dfavail) mismatch OST avail($bkavail)"

	$LCTL get_param *.$FSNAME-*.{maxbytes,namelen_max}
	(( $MDS1_VERSION < $(version_code 2.16.52-70) )) ||
		do_nodes $(mdts_nodes) \
			$LCTL get_param *.$FSNAME-*.{maxbytes,namelen_max}
	(( $OST1_VERSION < $(version_code 2.16.52-70) )) ||
		do_nodes $(osts_nodes) \
			$LCTL get_param *.$FSNAME-*.{maxbytes,namelen_max}
	local dfnamelen=$(stat -f -c %l $MOUNT)
	local lnamelen=($($LCTL get_param -n llite.$FSNAME-*.namelen_max))

	(( $dfnamelen == $lnamelen )) ||
		error "df namelen($dfnamelen) != llite namelen($lnamelen)"
}
run_test 79 "df report consistency check"

test_80() { # bug 10718
	remote_ost_nodsh && skip "remote OST with nodsh"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	# relax strong synchronous semantics for slow backends like ZFS
	if [ "$ost1_FSTYPE" != "ldiskfs" ]; then
		local soc="obdfilter.*.sync_lock_cancel"
		local save=$(do_facet ost1 $LCTL get_param -n $soc | head -n1)

		# "sync_on_lock_cancel" was broken by v2_11_55_0-26-g7059644e9a
		# Fixed in 2.13.51~79, so we'll keep it for interop with 2.12.x
		if [ -z "$save" ]; then
			soc="obdfilter.*.sync_on_lock_cancel"
			save=$(do_facet ost1 $LCTL get_param -n $soc | head -n1)
		fi

		if [ "$save" != "never" ]; then
			local osts=$(osts_nodes)

			do_nodes $osts $LCTL set_param $soc=never
			stack_trap "do_nodes $osts $LCTL set_param $soc=$save"
		fi
	fi

	dd if=/dev/zero of=$DIR/$tfile bs=1M count=1 seek=1M
	sync; sleep 1; sync
	local before=$(date +%s)
	cancel_lru_locks osc
	local after=$(date +%s)
	local diff=$((after - before))
	[ $diff -le 1 ] || error "elapsed for 1M@1T = $diff"

	rm -f $DIR/$tfile
}
run_test 80 "Page eviction is equally fast at high offsets too"

test_81a() { # LU-456
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_ost_nodsh && skip "remote OST with nodsh"

	# define OBD_FAIL_OST_MAPBLK_ENOSPC    0x228
	# MUST OR with the CFS_FAIL_ONCE (0x80000000)
	do_facet ost1 lctl set_param fail_loc=0x80000228

	# write should trigger a retry and success
	$LFS setstripe -i 0 -c 1 $DIR/$tfile
	$MULTIOP $DIR/$tfile oO_CREAT:O_RDWR:O_SYNC:w4096c
	RC=$?
	if [ $RC -ne 0 ] ; then
		error "write should success, but failed for $RC"
	fi
}
run_test 81a "OST should retry write when get -ENOSPC ==============="

test_81b() { # LU-456
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_ost_nodsh && skip "remote OST with nodsh"

	# define OBD_FAIL_OST_MAPBLK_ENOSPC    0x228
	# Don't OR with the CFS_FAIL_ONCE (0x80000000)
	do_facet ost1 lctl set_param fail_loc=0x228

	# write should retry several times and return -ENOSPC finally
	$LFS setstripe -i 0 -c 1 $DIR/$tfile
	$MULTIOP $DIR/$tfile oO_CREAT:O_RDWR:O_SYNC:w4096c
	RC=$?
	ENOSPC=28
	if [ $RC -ne $ENOSPC ] ; then
		error "dd should fail for -ENOSPC, but succeed."
	fi
}
run_test 81b "OST should return -ENOSPC when retry still fails ======="

test_99() {
	[ -z "$(which cvs 2>/dev/null)" ] && skip_env "could not find cvs"

	test_mkdir $DIR/$tdir.cvsroot
	chown $RUNAS_ID $DIR/$tdir.cvsroot

	cd $TMP
	$RUNAS cvs -d $DIR/$tdir.cvsroot init || error "cvs init failed"

	cd /etc/init.d
	# some versions of cvs import exit(1) when asked to import links or
	# files they can't read.  ignore those files.
	local toignore=$(find . -type l -printf '-I %f\n' -o \
			 ! -perm /4 -printf '-I %f\n')
	$RUNAS cvs -d $DIR/$tdir.cvsroot import -m "nomesg" $toignore \
		$tdir.reposname vtag rtag

	cd $DIR
	test_mkdir $DIR/$tdir.reposname
	chown $RUNAS_ID $DIR/$tdir.reposname
	$RUNAS cvs -d $DIR/$tdir.cvsroot co $tdir.reposname

	cd $DIR/$tdir.reposname
	$RUNAS touch foo99
	$RUNAS cvs add -m 'addmsg' foo99
	$RUNAS cvs update
	$RUNAS cvs commit -m 'nomsg' foo99
	rm -fr $DIR/$tdir.cvsroot
}
run_test 99 "cvs strange file/directory operations"

test_100() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[[ "$NETTYPE" =~ tcp ]] ||
		skip_env "TCP secure port test, not useful for NETTYPE=$NETTYPE"
	[[ -n "$(type -p ss)" ]] || skip_env "ss not available"
	remote_ost_nodsh && skip "remote OST with nodsh"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	remote_servers || skip "useless for local single node setup"

	ss -tna | ( rc=1; while read STATE SND RCV LOCAL REMOTE STAT; do
		[[ "${REMOTE/*:/}" == "$ACCEPTOR_PORT" ]] || continue

		rc=0
		if (( ${LOCAL/*:/} >= 1024 )); then
			echo "bad: $PROT $SND $RCV $LOCAL $REMOTE $STAT"
			ss -tna
			error "local: ${LOCAL/*:/} > 1024 remote: ${REMOTE/*:/}"
		fi
	done
	(( $rc == 0 )) || error "privileged port not found" )
}
run_test 100 "check local port using privileged port"

function get_named_value()
{
	local tag=$1

	grep -w "$tag" | sed "s/^$tag  *\([0-9]*\)  *.*/\1/"
}

test_101a() {
	[[ $PARALLEL != "yes" ]] || skip "skip parallel run"

	local s
	local discard
	local nreads=10000
	local cache_limit=32

	$LCTL set_param -n osc.*-osc*.rpc_stats=0
	$LCTL set_param -n llite.*.read_ahead_stats=0
	local max_cached_mb=$($LCTL get_param llite.*.max_cached_mb |
			      awk '/^max_cached_mb/ { print $2 }')
	stack_trap "$LCTL set_param -n llite.*.max_cached_mb=$max_cached_mb"
	$LCTL set_param -n llite.*.max_cached_mb=$cache_limit

	#
	# randomly read 10000 of 64K chunks from file 3x 32MB in size
	#
	echo "nreads: $nreads file size: $((cache_limit * 3))MB"
	$READS -f $DIR/$tfile -s$((cache_limit * 3192 * 1024)) -b65536 -C -n$nreads -t 180

	discard=0
	for s in $($LCTL get_param -n llite.*.read_ahead_stats |
		   get_named_value 'read.but.discarded'); do
			discard=$(($discard + $s))
	done

	$LCTL get_param osc.*-osc*.rpc_stats
	$LCTL get_param llite.*.read_ahead_stats

	# Discard is generally zero, but sometimes a few random reads line up
	# and trigger larger readahead, which is wasted & leads to discards.
	if (( $discard > $nreads )); then
		error "too many discarded pages ($discard > $nreads)"
	fi
	rm -f $DIR/$tfile || true
}
run_test 101a "check read-ahead for random reads"

setup_test101bc() {
	test_mkdir $DIR/$tdir
	local ssize=$1
	local FILE_LENGTH=$2
	STRIPE_OFFSET=0

	local FILE_SIZE_MB=$((FILE_LENGTH / ssize))

	local osts=$(osts_nodes)
	set_osd_param $osts '' read_cache_enable 0
	set_osd_param $osts '' writethrough_cache_enable 0

	trap cleanup_test101bc EXIT
	# prepare the read-ahead file
	$LFS setstripe -S $ssize -i $STRIPE_OFFSET -c $OSTCOUNT $DIR/$tfile

	dd if=/dev/zero of=$DIR/$tfile bs=$ssize \
				count=$FILE_SIZE_MB 2> /dev/null

}

cleanup_test101bc() {
	trap 0
	rm -rf $DIR/$tdir
	rm -f $DIR/$tfile

	local osts=$(osts_nodes)
	set_osd_param $osts '' read_cache_enable 1
	set_osd_param $osts '' writethrough_cache_enable 1
}

ra_check_101() {
	local read_size=$1
	local stripe_size=$2
	local stride_length=$((stripe_size / read_size))
	local stride_width=$((stride_length * OSTCOUNT))
	local discard_limit=$(( ((stride_length - 1) * 3 / stride_width) *
			        (stride_width - stride_length) ))
	local discard=$($LCTL get_param -n llite.*.read_ahead_stats |
		  get_named_value 'read.but.discarded' | calc_sum)

	if [[ $discard -gt $discard_limit ]]; then
		$LCTL get_param llite.*.read_ahead_stats
		error "($discard limit ${discard_limit}) discarded pages with size (${read_size})"
	else
		echo "Read-ahead success for size ${read_size}"
	fi
}

test_101b() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[[ $OSTCOUNT -lt 2 ]] && skip_env "needs >= 2 OSTs"

	local STRIPE_SIZE=1048576
	local STRIDE_SIZE=$((STRIPE_SIZE*OSTCOUNT))

	if [ $SLOW == "yes" ]; then
		local FILE_LENGTH=$((STRIDE_SIZE * 64))
	else
		local FILE_LENGTH=$((STRIDE_SIZE * 8))
	fi

	local ITERATION=$((FILE_LENGTH / STRIDE_SIZE))

	# prepare the read-ahead file
	setup_test101bc $STRIPE_SIZE $FILE_LENGTH
	cancel_lru_locks osc
	for BIDX in 2 4 8 16 32 64 128 256
	do
		local BSIZE=$((BIDX*4096))
		local READ_COUNT=$((STRIPE_SIZE/BSIZE))
		local STRIDE_LENGTH=$((STRIDE_SIZE/BSIZE))
		local OFFSET=$((STRIPE_SIZE/BSIZE*(OSTCOUNT - 1)))
		$LCTL set_param -n llite.*.read_ahead_stats=0
		$READS -f $DIR/$tfile  -l $STRIDE_LENGTH -o $OFFSET \
			      -s $FILE_LENGTH -b $STRIPE_SIZE -a $READ_COUNT -n $ITERATION
		cancel_lru_locks osc
		ra_check_101 $BSIZE $STRIPE_SIZE $FILE_LENGTH
	done
	cleanup_test101bc
	true
}
run_test 101b "check stride-io mode read-ahead ================="

test_101c() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	local STRIPE_SIZE=1048576
	local FILE_LENGTH=$((STRIPE_SIZE*100))
	local nreads=10000
	local rsize=65536
	local osc_rpc_stats

	setup_test101bc $STRIPE_SIZE $FILE_LENGTH

	cancel_lru_locks osc
	$LCTL set_param osc.*.rpc_stats=0
	$READS -f $DIR/$tfile -s$FILE_LENGTH -b$rsize -n$nreads -t 180
	$LCTL get_param osc.*.rpc_stats
	for osc_rpc_stats in $($LCTL get_param -N osc.*.rpc_stats); do
		local stats=$($LCTL get_param -n $osc_rpc_stats)
		local lines=$(echo "$stats" | awk 'END {print NR;}')
		local size

		if [ $lines -le 20 ]; then
			echo "continue debug"
			continue
		fi
		for size in 1 2 4 8; do
			local rpc=$(echo "$stats" |
				    awk '($1 == "'$size':") {print $2; exit; }')
			[ $rpc != 0 ] && ((size * PAGE_SIZE < rsize)) &&
				error "Small $((size*PAGE_SIZE)) read IO $rpc!"
		done
		echo "$osc_rpc_stats check passed!"
	done
	cleanup_test101bc
	true
}
run_test 101c "check stripe_size aligned read-ahead"

test_101d() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	local file=$DIR/$tfile
	local sz_MB=${FILESIZE_101d:-80}
	local ra_MB=${READAHEAD_MB:-40}

	local free_MB=$(($(df -P $DIR | tail -n 1 | awk '{ print $4 }') / 1024))
	[ $free_MB -lt $sz_MB ] &&
		skip "Need free space ${sz_MB}M, have ${free_MB}M"

	echo "Create test file $file size ${sz_MB}M, ${free_MB}M free"
	$LFS setstripe -c -1 $file || error "setstripe failed"

	dd if=/dev/zero of=$file bs=1M count=$sz_MB || error "dd failed"
	echo Cancel LRU locks on lustre client to flush the client cache
	cancel_lru_locks osc

	echo Disable read-ahead
	local old_RA=$($LCTL get_param -n llite.*.max_read_ahead_mb | head -n 1)
	$LCTL set_param -n llite.*.max_read_ahead_mb=0
	stack_trap "$LCTL set_param -n llite.*.max_read_ahead_mb=$old_RA" EXIT
	$LCTL get_param -n llite.*.max_read_ahead_mb

	echo "Reading the test file $file with read-ahead disabled"
	local sz_KB=$((sz_MB * 1024 / 4))
	# 10485760 bytes transferred in 0.000938 secs (11179579337 bytes/sec)
	# 104857600 bytes (105 MB) copied, 0.00876352 s, 12.0 GB/s
	# 83886080 bytes (84 MB, 80 MiB) copied, 16 s, 5.2 MB/s
	local raOFF=$(LANG=C dd if=$file of=/dev/null bs=4k count=$sz_KB |&
		      sed -e '/records/d' -e 's/.* \([0-9][0-9\.]*\) *s.*/\1/')

	echo "Cancel LRU locks on lustre client to flush the client cache"
	cancel_lru_locks osc
	echo Enable read-ahead with ${ra_MB}MB
	$LCTL set_param -n llite.*.max_read_ahead_mb=$ra_MB

	echo "Reading the test file $file with read-ahead enabled"
	local raON=$(LANG=C dd if=$file of=/dev/null bs=4k count=$sz_KB |&
		      sed -e '/records/d' -e 's/.* \([0-9][0-9\.]*\) *s.*/\1/')

	echo "read-ahead disabled time read '$raOFF'"
	echo "read-ahead enabled time read '$raON'"

	rm -f $file
	wait_delete_completed

	# use awk for this check instead of bash because it handles decimals
	awk "{ exit !($raOFF < 0.5 || $raOFF > $raON) }" <<<"ignore_me" ||
		error "readahead ${raON}s > no-readahead ${raOFF}s (${sz_MB}M)"
}
run_test 101d "file read with and without read-ahead enabled"

test_101e() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	local file=$DIR/$tfile
	local size_KB=500  #KB
	local count=100
	local bsize=1024

	local free_KB=$(df -P $DIR | tail -n 1 | awk '{ print $4 }')
	local need_KB=$((count * size_KB))
	[[ $free_KB -le $need_KB ]] &&
		skip_env "Need free space $need_KB, have $free_KB"

	echo "Creating $count ${size_KB}K test files"
	for ((i = 0; i < $count; i++)); do
		dd if=/dev/zero of=$file.$i bs=$bsize count=$size_KB 2>/dev/null
	done

	echo "Cancel LRU locks on lustre client to flush the client cache"
	cancel_lru_locks $OSC

	echo "Reset readahead stats"
	$LCTL set_param -n llite.*.read_ahead_stats=0

	for ((i = 0; i < $count; i++)); do
		dd if=$file.$i of=/dev/null bs=$bsize count=$size_KB 2>/dev/null
	done

	$LCTL get_param llite.*.max_cached_mb
	$LCTL get_param llite.*.read_ahead_stats
	local miss=$($LCTL get_param -n llite.*.read_ahead_stats |
		     get_named_value 'misses' | calc_sum)

	for ((i = 0; i < $count; i++)); do
		rm -rf $file.$i 2>/dev/null
	done

	#10000 means 20% reads are missing in readahead
	[[ $miss -lt 10000 ]] ||  error "misses too much for small reads"
}
run_test 101e "check read-ahead for small read(1k) for small files(500k)"

test_101f() {
	which iozone || skip_env "no iozone installed"

	local old_debug=$($LCTL get_param debug)
	old_debug=${old_debug#*=}
	$LCTL set_param debug="reada mmap"

	# create a test file
	iozone -i 0 -+n -r 1m -s 128m -w -f $DIR/$tfile > /dev/null 2>&1

	echo Cancel LRU locks on lustre client to flush the client cache
	cancel_lru_locks osc

	echo Reset readahead stats
	$LCTL set_param -n llite.*.read_ahead_stats=0

	echo mmap read the file with small block size
	iozone -i 1 -u 1 -l 1 -+n -r 32k -s 128m -B -f $DIR/$tfile \
		> /dev/null 2>&1

	echo checking missing pages
	$LCTL get_param llite.*.read_ahead_stats
	local miss=$($LCTL get_param -n llite.*.read_ahead_stats |
			get_named_value 'misses' | calc_sum)

	$LCTL set_param debug="$old_debug"
	[ $miss -lt 3 ] || error "misses too much pages ('$miss')!"
	rm -f $DIR/$tfile
}
run_test 101f "check mmap read performance"

test_101g_brw_size_test() {
	local mb=$1
	local pages=$((mb * 1048576 / PAGE_SIZE))
	local file=$DIR/$tfile

	$LCTL set_param osc.*.max_pages_per_rpc=${mb}M ||
		{ error "unable to set max_pages_per_rpc=${mb}M"; return 1; }
	for mp in $($LCTL get_param -n osc.*.max_pages_per_rpc); do
		[ $mp -ne $pages ] && error "max_pages_per_rpc $mp != $pages" &&
			return 2
	done

	stack_trap "rm -f $file; wait_delete_completed" EXIT
	$LCTL set_param -n osc.*.rpc_stats=0

	# 10 RPCs should be enough for the test
	local count=10
	dd if=/dev/zero of=$file bs=${mb}M count=$count ||
		{ error "dd write ${mb} MB blocks failed"; return 3; }
	cancel_lru_locks osc
	dd of=/dev/null if=$file bs=${mb}M count=$count ||
		{ error "dd write ${mb} MB blocks failed"; return 4; }

	# calculate number of full-sized read and write RPCs
	rpcs=($($LCTL get_param -n 'osc.*.rpc_stats' |
		sed -n '/pages per rpc/,/^$/p' |
		awk '/'$pages':/ { reads += $2; writes += $6 }; \
		END { print reads,writes }'))
	# allow one extra full-sized read RPC for async readahead
	[[ ${rpcs[0]} == $count || ${rpcs[0]} == $((count + 1)) ]] ||
		{ error "${rpcs[0]} != $count read RPCs"; return 5; }
	[[ ${rpcs[1]} == $count ]] ||
		{ error "${rpcs[1]} != $count write RPCs"; return 6; }
}

test_101g() {
	remote_ost_nodsh && skip "remote OST with nodsh"

	local rpcs
	local facets=$(get_facets OST)
	local p="$TMP/$TESTSUITE-$TESTNAME.parameters"
	local brw_size="obdfilter.*.brw_size"

	$LFS setstripe -i 0 -c 1 $DIR/$tfile

	local orig_mb=$(do_facet ost1 $LCTL get_param -n $brw_size | head -n 1)

	if (( $OST1_VERSION >= $(version_code 2.8.52) )); then
		local osts=$(osts_nodes)

		(( $OST1_VERSION < $(version_code 2.9.52) )) || suffix="M"

		if (( $orig_mb < 16 )); then
			save_lustre_params $facets "$brw_size" > $p
			stack_trap "rm -f $p"
			do_nodes $osts $LCTL set_param -n $brw_size=16$suffix ||
				error "set 16MB RPC size failed"

			echo "remount client to enable new RPC size"
			remount_client $MOUNT || error "remount_client failed"
		fi

		test_101g_brw_size_test 16 || error "16MB RPC test failed"
		# should be able to set brw_size=12, but no rpc_stats for that
		test_101g_brw_size_test 8 || error "8MB RPC test failed"
	fi

	test_101g_brw_size_test 4 || error "4MB RPC test failed"

	if (( $orig_mb < 16 )); then
		restore_lustre_params < $p
		remount_client $MOUNT || error "remount_client restore failed"
	fi
}
run_test 101g "Big bulk(4/16 MiB) readahead"

test_101h() {
	$LFS setstripe -i 0 -c 1 $DIR/$tfile
	local hybrid=$($LCTL get_param -n llite.*.hybrid_io)
	$LCTL set_param llite.*.hybrid_io=0
	stack_trap "$LCTL set_param -n llite.*.hybrid_io=$hybrid" EXIT

	dd if=/dev/zero of=$DIR/$tfile bs=1M count=70 ||
		error "dd 70M file failed"
	echo Cancel LRU locks on lustre client to flush the client cache
	cancel_lru_locks osc

	echo "Reset readahead stats"
	$LCTL set_param -n llite.*.read_ahead_stats 0

	echo "Read 10M of data but cross 64M bundary"
	dd if=$DIR/$tfile of=/dev/null bs=10M skip=6 count=1
	local miss=$($LCTL get_param -n llite.*.read_ahead_stats |
		     get_named_value 'misses' | calc_sum)
	[ $miss -eq 1 ] || error "expected miss 1 but got $miss"
	rm -f $p $DIR/$tfile
}
run_test 101h "Readahead should cover current read window"

test_101i() {
	dd if=/dev/zero of=$DIR/$tfile bs=1M count=10 ||
		error "dd 10M file failed"

	local max_per_file_mb=$($LCTL get_param -n \
		llite.*.max_read_ahead_per_file_mb 2>/dev/null)
	cancel_lru_locks osc
	stack_trap "$LCTL set_param llite.*.max_read_ahead_per_file_mb=$max_per_file_mb"
	$LCTL set_param llite.*.max_read_ahead_per_file_mb=1 ||
		error "set max_read_ahead_per_file_mb to 1 failed"

	echo "Reset readahead stats"
	$LCTL set_param llite.*.read_ahead_stats=0

	dd if=$DIR/$tfile of=/dev/null bs=2M

	$LCTL get_param llite.*.read_ahead_stats
	local miss=$($LCTL get_param -n llite.*.read_ahead_stats |
		     awk '/misses/ { print $2 }')
	[ $miss -eq 5 ] || error "expected misses 5 but got $miss"
	rm -f $DIR/$tfile
}
run_test 101i "allow current readahead to exceed reservation"

test_101j() {
	$LFS setstripe -i 0 -c 1 $DIR/$tfile ||
		error "setstripe $DIR/$tfile failed"
	local file_size=$((1048576 * 16))
	local old_ra=$($LCTL get_param -n llite.*.max_read_ahead_mb | head -n 1)
	stack_trap "$LCTL set_param -n llite.*.max_read_ahead_mb $old_ra" EXIT
	local hybrid=$($LCTL get_param -n llite.*.hybrid_io)
	$LCTL set_param llite.*.hybrid_io=0
	stack_trap "$LCTL set_param -n llite.*.hybrid_io=$hybrid" EXIT

	echo Disable read-ahead
	$LCTL set_param -n llite.*.max_read_ahead_mb=0

	dd if=/dev/zero of=$DIR/$tfile bs=1M count=$(($file_size / 1048576))
	for blk in $PAGE_SIZE 1048576 $file_size; do
		cancel_lru_locks osc
		echo "Reset readahead stats"
		$LCTL set_param -n llite.*.read_ahead_stats=0
		local count=$(($file_size / $blk))
		dd if=$DIR/$tfile bs=$blk count=$count of=/dev/null
		local miss=$($LCTL get_param -n llite.*.read_ahead_stats |
			     get_named_value 'failed.to.fast.read' | calc_sum)
		$LCTL get_param -n llite.*.read_ahead_stats
		[ $miss -eq $count ] || error "expected $count got $miss"
	done

	rm -f $p $DIR/$tfile
}
run_test 101j "A complete read block should be submitted when no RA"

test_readahead_base() {
	local file=$DIR/$tfile
	local size=$1
	local iosz
	local ramax
	local ranum

	$LCTL set_param -n llite.*.read_ahead_stats=0
	# The first page is not accounted into readahead
	ramax=$(((size + PAGE_SIZE - 1) / PAGE_SIZE - 1))
	iosz=$(((size + 1048575) / 1048576 * 1048576))
	echo "Test readahead: size=$size ramax=$ramx iosz=$iosz"

	$LCTL mark  "Test readahead: size=$size ramax=$ramx iosz=$iosz"
	fallocate -l $size $file || error "failed to fallocate $file"
	cancel_lru_locks osc
	$MULTIOP $file or${iosz}c || error "failed to read $file"
	$LCTL get_param -n llite.*.read_ahead_stats
	ranum=$($LCTL get_param -n llite.*.read_ahead_stats |
		awk '/readahead.pages/ { print $7 }' | calc_sum)
	(( $ranum <= $ramax )) ||
		error "read-ahead pages is $ranum more than $ramax"
	rm -rf $file || error "failed to remove $file"
}

test_101m()
{
	local file=$DIR/$tfile
	local ramax
	local ranum
	local size
	local iosz

	check_set_fallocate_or_skip
	stack_trap "rm -f $file" EXIT

	test_readahead_base 4096

	# file size: 16K = 16384
	test_readahead_base 16384
	test_readahead_base 16385
	test_readahead_base 16383

	# file size: 1M + 1 = 1048576 + 1
	test_readahead_base 1048577
	# file size: 1M + 16K
	test_readahead_base $((1048576 + 16384))

	# file size: stripe_size * (stripe_count - 1) + 16K
	$LFS setstripe -c -1 $file || error "failed to setstripe $file"
	test_readahead_base $((1048576 * (OSTCOUNT - 1) + 16384))
	# file size: stripe_size * stripe_count + 16K
	$LFS setstripe -c -1 $file || error "failed to setstripe $file"
	test_readahead_base $((1048576 * OSTCOUNT + 16384))
	# file size: 2 * stripe_size * stripe_count + 16K
	$LFS setstripe -c -1 $file || error "failed to setstripe $file"
	test_readahead_base $((2 * 1048576 * OSTCOUNT + 16384))
}
run_test 101m "read ahead for small file and last stripe of the file"

setup_test102() {
	test_mkdir $DIR/$tdir
	chown $RUNAS_ID $DIR/$tdir
	STRIPE_SIZE=65536
	STRIPE_OFFSET=1
	STRIPE_COUNT=$OSTCOUNT
	[[ $OSTCOUNT -gt 4 ]] && STRIPE_COUNT=4

	trap cleanup_test102 EXIT
	cd $DIR
	$1 $LFS setstripe -S $STRIPE_SIZE -i $STRIPE_OFFSET -c $STRIPE_COUNT $tdir
	cd $DIR/$tdir
	for num in 1 2 3 4; do
		for count in $(seq 1 $STRIPE_COUNT); do
			for idx in $(seq 0 $[$STRIPE_COUNT - 1]); do
				local size=`expr $STRIPE_SIZE \* $num`
				local file=file"$num-$idx-$count"
				$1 $LFS setstripe -S $size -i $idx -c $count $file
			done
		done
	done

	cd $DIR
	$1 tar cf $TMP/f102.tar $tdir --xattrs
}

cleanup_test102() {
	trap 0
	rm -f $TMP/f102.tar
	rm -rf $DIR/d0.sanity/d102
}

test_102a() {
	[ "$UID" != 0 ] && skip "must run as root"
	[ -z "$(lctl get_param -n mdc.*-mdc-*.connect_flags | grep xattr)" ] &&
		skip_env "must have user_xattr"

	[ -z "$(which setfattr 2>/dev/null)" ] &&
		skip_env "could not find setfattr"

	local testfile=$DIR/$tfile

	touch $testfile
	echo "set/get xattr..."
	setfattr -n trusted.name1 -v value1 $testfile ||
		error "setfattr -n trusted.name1=value1 $testfile failed"
	getfattr -n trusted.name1 $testfile 2> /dev/null |
	  grep "trusted.name1=.value1" ||
		error "$testfile missing trusted.name1=value1"

	setfattr -n user.author1 -v author1 $testfile ||
		error "setfattr -n user.author1=author1 $testfile failed"
	getfattr -n user.author1 $testfile 2> /dev/null |
	  grep "user.author1=.author1" ||
		error "$testfile missing trusted.author1=author1"

	echo "listxattr..."
	setfattr -n trusted.name2 -v value2 $testfile ||
		error "$testfile unable to set trusted.name2"
	setfattr -n trusted.name3 -v value3 $testfile ||
		error "$testfile unable to set trusted.name3"
	[ $(getfattr -d -m "^trusted" $testfile 2> /dev/null |
	    grep "trusted.name" | wc -l) -eq 3 ] ||
		error "$testfile missing 3 trusted.name xattrs"

	setfattr -n user.author2 -v author2 $testfile ||
		error "$testfile unable to set user.author2"
	setfattr -n user.author3 -v author3 $testfile ||
		error "$testfile unable to set user.author3"
	[ $(getfattr -d -m "^user" $testfile 2> /dev/null |
	    grep "user.author" | wc -l) -eq 3 ] ||
		error "$testfile missing 3 user.author xattrs"

	echo "remove xattr..."
	setfattr -x trusted.name1 $testfile ||
		error "$testfile error deleting trusted.name1"
	getfattr -d -m trusted $testfile 2> /dev/null | grep "trusted.name1" &&
		error "$testfile did not delete trusted.name1 xattr"

	setfattr -x user.author1 $testfile ||
		error "$testfile error deleting user.author1"
	echo "set lustre special xattr ..."
	$LFS setstripe -c1 $testfile
	local lovea=$(getfattr -n "trusted.lov" -e hex $testfile |
		awk -F "=" '/trusted.lov/ { print $2 }' )
	setfattr -n "trusted.lov" -v $lovea $testfile ||
		error "$testfile doesn't ignore setting trusted.lov again"
	setfattr -n "trusted.lov" -v "invalid_value" $testfile &&
		error "$testfile allow setting invalid trusted.lov"
	rm -f $testfile
}
run_test 102a "user xattr test =================================="

check_102b_layout() {
	local layout="$*"
	local testfile=$DIR/$tfile

	echo "test layout '$layout'"
	$LFS setstripe $layout $testfile || error "setstripe failed"
	$LFS getstripe -y $testfile

	echo "get/set/list trusted.lov xattr ..." # b=10930
	local value=$(getfattr -n trusted.lov -e hex $testfile | grep trusted)
	[[ "$value" =~ "trusted.lov" ]] ||
		error "can't get trusted.lov from $testfile"
	local stripe_count_orig=$($LFS getstripe -c $testfile) ||
		error "getstripe failed"

	$MCREATE $testfile.2 || error "mcreate $testfile.2 failed"

	value=$(cut -d= -f2 <<<$value)
	# LU-13168: truncated xattr should fail if short lov_user_md header
	[ $CLIENT_VERSION -lt $(version_code 2.13.53) ] &&
		lens="${#value}" || lens="$(seq 4 2 ${#value})"
	for len in $lens; do
		echo "setfattr $len $testfile.2"
		setfattr -n trusted.lov -v ${value:0:$len} $testfile.2 &&
			[ $len -lt 66 ] && error "short xattr len=$len worked"
	done
	local stripe_size=$($LFS getstripe -S $testfile.2)
	local stripe_count=$($LFS getstripe -c $testfile.2)
	[[ $stripe_size -eq 65536 ]] ||
		error "stripe size $stripe_size != 65536"
	[[ $stripe_count -eq $stripe_count_orig ]] ||
		error "stripe count $stripe_count != $stripe_count_orig"
	rm $testfile $testfile.2
}

test_102b() {
	[ -z "$(which setfattr 2>/dev/null)" ] &&
		skip_env "could not find setfattr"
	[[ $OSTCOUNT -lt 2 ]] && skip_env "needs >= 2 OSTs"

	# check plain layout
	check_102b_layout -S 65536 -i 1 -c $OSTCOUNT

	# and also check composite layout
	check_102b_layout -E 1M -S 65536 -i 1 -c $OSTCOUNT -Eeof -S4M

}
run_test 102b "getfattr/setfattr for trusted.lov EAs"

test_102c() {
	[ -z "$(which setfattr 2>/dev/null)" ] &&
		skip_env "could not find setfattr"
	[[ $OSTCOUNT -lt 2 ]] && skip_env "needs >= 2 OSTs"

	# b10930: get/set/list lustre.lov xattr
	echo "get/set/list lustre.lov xattr ..."
	test_mkdir $DIR/$tdir
	chown $RUNAS_ID $DIR/$tdir
	local testfile=$DIR/$tdir/$tfile
	$RUNAS $LFS setstripe -S 65536 -i 1 -c $OSTCOUNT $testfile ||
		error "setstripe failed"
	local STRIPECOUNT=$($RUNAS $LFS getstripe -c $testfile) ||
		error "getstripe failed"
	$RUNAS getfattr -d -m "^lustre" $testfile 2> /dev/null | \
	grep "lustre.lov" || error "can't get lustre.lov from $testfile"

	local testfile2=${testfile}2
	local value=`getfattr -n lustre.lov $testfile 2> /dev/null | \
		     grep "lustre.lov" |sed -e 's/[^=]\+=//'  `

	$RUNAS $MCREATE $testfile2
	$RUNAS setfattr -n lustre.lov -v $value $testfile2
	local stripe_size=$($RUNAS $LFS getstripe -S $testfile2)
	local stripe_count=$($RUNAS $LFS getstripe -c $testfile2)
	[ $stripe_size -eq 65536 ] || error "stripe size $stripe_size != 65536"
	[ $stripe_count -eq $STRIPECOUNT ] ||
		error "stripe count $stripe_count != $STRIPECOUNT"
}
run_test 102c "non-root getfattr/setfattr for lustre.lov EAs ==========="

compare_stripe_info1() {
	local stripe_index_all_zero=true

	for num in 1 2 3 4; do
		for count in $(seq 1 $STRIPE_COUNT); do
			for offset in $(seq 0 $[$STRIPE_COUNT - 1]); do
				local size=$((STRIPE_SIZE * num))
				local file=file"$num-$offset-$count"
				stripe_size=$($LFS getstripe -S $PWD/$file)
				[[ $stripe_size -ne $size ]] &&
				    error "$file: size $stripe_size != $size"
				stripe_count=$($LFS getstripe -c $PWD/$file)
				# allow fewer stripes to be created, ORI-601
				[[ $stripe_count -lt $(((3 * count + 3) / 4)) ]] &&
				    error "$file: count $stripe_count != $count"
				stripe_index=$($LFS getstripe -i $PWD/$file)
				[[ $stripe_index -ne 0 ]] &&
					stripe_index_all_zero=false
			done
		done
	done
	$stripe_index_all_zero &&
		error "all files are being extracted starting from OST index 0"
	return 0
}

have_xattrs_include() {
	tar --help | grep -q xattrs-include &&
		echo --xattrs-include="lustre.*"
}

test_102d() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[[ $OSTCOUNT -lt 2 ]] && skip_env "needs >= 2 OSTs"

	XINC=$(have_xattrs_include)
	setup_test102
	tar xf $TMP/f102.tar -C $DIR/$tdir --xattrs $XINC
	cd $DIR/$tdir/$tdir
	compare_stripe_info1
}
run_test 102d "tar restore stripe info from tarfile,not keep osts"

test_102f() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[[ $OSTCOUNT -lt 2 ]] && skip_env "needs >= 2 OSTs"

	XINC=$(have_xattrs_include)
	setup_test102
	test_mkdir $DIR/$tdir.restore
	cd $DIR
	tar cf - --xattrs $tdir | tar xf - \
		-C $DIR/$tdir.restore --xattrs $XINC
	cd $DIR/$tdir.restore/$tdir
	compare_stripe_info1
}
run_test 102f "tar copy files, not keep osts"

grow_xattr() {
	[ -z "$(lctl get_param -n mdc.*.connect_flags | grep xattr)" ] &&
		skip "must have user_xattr"
	[ -z "$(which setfattr 2>/dev/null)" ] &&
		skip_env "could not find setfattr"
	[ -z "$(which getfattr 2>/dev/null)" ] &&
		skip_env "could not find getfattr"

	local xsize=${1:-1024}	# in bytes
	local file=$DIR/$tfile
	local value="$(generate_string $xsize)"
	local xbig=trusted.big
	local toobig=$2

	touch $file
	log "save $xbig on $file"
	if [ -z "$toobig" ]
	then
		setfattr -n $xbig -v $value $file ||
			error "saving $xbig on $file failed"
	else
		setfattr -n $xbig -v $value $file &&
			error "saving $xbig on $file succeeded"
		return 0
	fi

	local orig=$(get_xattr_value $xbig $file)
	[[ "$orig" != "$value" ]] && error "$xbig different after saving $xbig"

	local xsml=trusted.sml
	log "save $xsml on $file"
	setfattr -n $xsml -v val $file || error "saving $xsml on $file failed"

	local new=$(get_xattr_value $xbig $file)
	[[ "$new" != "$orig" ]] && error "$xbig different after saving $xsml"

	log "grow $xsml on $file"
	setfattr -n $xsml -v "$value" $file ||
		error "growing $xsml on $file failed"

	new=$(get_xattr_value $xbig $file)
	[[ "$new" != "$orig" ]] && error "$xbig different after growing $xsml"
	log "$xbig still valid after growing $xsml"

	rm -f $file
}

test_102h() { # bug 15777
	grow_xattr 1024
}
run_test 102h "grow xattr from inside inode to external block"

test_102ha() {
	large_xattr_enabled || skip_env "ea_inode feature disabled"

	echo "setting xattr of max xattr size: $(max_xattr_size)"
	grow_xattr $(max_xattr_size)

	echo "setting xattr of > max xattr size: $(max_xattr_size) + 10"
	echo "This should fail:"
	grow_xattr $(($(max_xattr_size) + 10)) 1
}
run_test 102ha "grow xattr from inside inode to external inode"

test_102i() { # bug 17038
	[ -z "$(which getfattr 2>/dev/null)" ] &&
		skip "could not find getfattr"

	touch $DIR/$tfile
	ln -s $DIR/$tfile $DIR/${tfile}link
	getfattr -n trusted.lov $DIR/$tfile ||
		error "lgetxattr on $DIR/$tfile failed"
	getfattr -h -n trusted.lov $DIR/${tfile}link 2>&1 |
		grep -i "no such attr" ||
		error "error for lgetxattr on $DIR/${tfile}link is not ENODATA"
	rm -f $DIR/$tfile $DIR/${tfile}link
}
run_test 102i "lgetxattr test on symbolic link ============"

test_102j() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[[ $OSTCOUNT -lt 2 ]] && skip_env "needs >= 2 OSTs"

	XINC=$(have_xattrs_include)
	setup_test102 "$RUNAS"
	chown $RUNAS_ID $DIR/$tdir
	$RUNAS tar xf $TMP/f102.tar -C $DIR/$tdir --xattrs $XINC
	cd $DIR/$tdir/$tdir
	compare_stripe_info1 "$RUNAS"
}
run_test 102j "non-root tar restore stripe info from tarfile, not keep osts ==="

test_102k() {
	[ -z "$(which setfattr 2>/dev/null)" ] &&
		skip "could not find setfattr"

	touch $DIR/$tfile
	# b22187 just check that does not crash for regular file.
	setfattr -n trusted.lov $DIR/$tfile
	# b22187 'setfattr -n trusted.lov' should remove LOV EA for directories
	local test_kdir=$DIR/$tdir
	test_mkdir $test_kdir
	local default_size=$($LFS getstripe -S $test_kdir)
	local default_count=$($LFS getstripe -c $test_kdir)
	local default_offset=$($LFS getstripe -i $test_kdir)
	$LFS setstripe -S 65536 -i 0 -c $OSTCOUNT $test_kdir ||
		error 'dir setstripe failed'
	setfattr -n trusted.lov $test_kdir
	local stripe_size=$($LFS getstripe -S $test_kdir)
	local stripe_count=$($LFS getstripe -c $test_kdir)
	local stripe_offset=$($LFS getstripe -i $test_kdir)
	[ $stripe_size -eq $default_size ] ||
		error "stripe size $stripe_size != $default_size"
	[ $stripe_count -eq $default_count ] ||
		error "stripe count $stripe_count != $default_count"
	[ $stripe_offset -eq $default_offset ] ||
		error "stripe offset $stripe_offset != $default_offset"
	rm -rf $DIR/$tfile $test_kdir
}
run_test 102k "setfattr without parameter of value shouldn't cause a crash"

test_102l() {
	[ -z "$(which getfattr 2>/dev/null)" ] &&
		skip "could not find getfattr"

	# LU-532 trusted. xattr is invisible to non-root
	local testfile=$DIR/$tfile

	touch $testfile

	echo "listxattr as user..."
	chown $RUNAS_ID $testfile
	$RUNAS getfattr -d -m '.*' $testfile 2>&1 |
	    grep -q "trusted" &&
		error "$testfile trusted xattrs are user visible"

	return 0;
}
run_test 102l "listxattr size test =================================="

test_102m() { # LU-3403 llite: error of listxattr when buffer is small
	local path=$DIR/$tfile
	touch $path

	listxattr_size_check $path || error "listattr_size_check $path failed"
}
run_test 102m "Ensure listxattr fails on small bufffer ========"

cleanup_test102

getxattr() { # getxattr path name
	# Return the base64 encoding of the value of xattr name on path.
	local path=$1
	local name=$2

	# # getfattr --absolute-names --encoding=base64 --name=trusted.lov $path
	# file: $path
	# trusted.lov=0s0AvRCwEAAAAGAAAAAAAAAAAEAAACAAAAAAAQAAEAA...AAAAAAAAA=
	#
	# We print just 0s0AvRCwEAAAAGAAAAAAAAAAAEAAACAAAAAAAQAAEAA...AAAAAAAAA=

	getfattr --absolute-names --encoding=base64 --name=$name $path |
		awk -F= -v name=$name '$1 == name {
			print substr($0, index($0, "=") + 1);
	}'
}

test_102n() { # LU-4101 mdt: protect internal xattrs
	[ -z "$(which setfattr 2>/dev/null)" ] &&
		skip "could not find setfattr"
	if [ $MDS1_VERSION -lt $(version_code 2.5.50) ]
	then
		skip "MDT < 2.5.50 allows setxattr on internal trusted xattrs"
	fi

	local file0=$DIR/$tfile.0
	local file1=$DIR/$tfile.1
	local xattr0=$TMP/$tfile.0
	local xattr1=$TMP/$tfile.1
	local namelist="lov lma lmv link fid version som hsm"
	local name
	local value

	rm -rf $file0 $file1 $xattr0 $xattr1
	touch $file0 $file1

	# Get 'before' xattrs of $file1.
	getfattr --absolute-names --dump --match=- $file1 > $xattr0

	[ $MDS1_VERSION -lt $(version_code 2.8.53) ] &&
		namelist+=" lfsck_namespace"
	for name in $namelist; do
		# Try to copy xattr from $file0 to $file1.
		value=$(getxattr $file0 trusted.$name 2> /dev/null)

		setfattr --name=trusted.$name --value="$value" $file1 ||
			error "setxattr 'trusted.$name' failed"

		# Try to set a garbage xattr.
		value=0sVGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIGl0c2VsZi4=

		if [[ x$name == "xlov" ]]; then
			setfattr --name=trusted.lov --value="$value" $file1 &&
			error "setxattr invalid 'trusted.lov' success"
		else
			setfattr --name=trusted.$name --value="$value" $file1 ||
				error "setxattr invalid 'trusted.$name' failed"
		fi

		# Try to remove the xattr from $file1. We don't care if this
		# appears to succeed or fail, we just don't want there to be
		# any changes or crashes.
		setfattr --remove=$trusted.$name $file1 2> /dev/null
	done

	if [ $MDS1_VERSION -gt $(version_code 2.6.50) ]
	then
		name="lfsck_ns"
		# Try to copy xattr from $file0 to $file1.
		value=$(getxattr $file0 trusted.$name 2> /dev/null)

		setfattr --name=trusted.$name --value="$value" $file1 ||
			error "setxattr 'trusted.$name' failed"

		# Try to set a garbage xattr.
		value=0sVGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIGl0c2VsZi4=

		setfattr --name=trusted.$name --value="$value" $file1 ||
			error "setxattr 'trusted.$name' failed"

		# Try to remove the xattr from $file1. We don't care if this
		# appears to succeed or fail, we just don't want there to be
		# any changes or crashes.
		setfattr --remove=$trusted.$name $file1 2> /dev/null
	fi

	# Get 'after' xattrs of file1.
	getfattr --absolute-names --dump --match=- $file1 > $xattr1

	if ! diff $xattr0 $xattr1; then
		error "before and after xattrs of '$file1' differ"
	fi

	rm -rf $file0 $file1 $xattr0 $xattr1

	return 0
}
run_test 102n "silently ignore setxattr on internal trusted xattrs"

test_102p() { # LU-4703 setxattr did not check ownership
	[ $MDS1_VERSION -lt $(version_code 2.5.56) ] &&
		skip "MDS needs to be at least 2.5.56"

	local testfile=$DIR/$tfile

	touch $testfile

	echo "setfacl as user..."
	$RUNAS setfacl -m "u:$RUNAS_ID:rwx" $testfile
	[ $? -ne 0 ] || error "setfacl by $RUNAS_ID was allowed on $testfile"

	echo "setfattr as user..."
	setfacl -m "u:$RUNAS_ID:---" $testfile
	$RUNAS setfattr -x system.posix_acl_access $testfile
	[ $? -ne 0 ] || error "setfattr by $RUNAS_ID was allowed on $testfile"
}
run_test 102p "check setxattr(2) correctly fails without permission"

test_102q() {
	[ $MDS1_VERSION -lt $(version_code 2.6.92) ] &&
		skip "MDS needs to be at least 2.6.92"

	orphan_linkea_check $DIR/$tfile || error "orphan_linkea_check"
}
run_test 102q "flistxattr should not return trusted.link EAs for orphans"

test_102r() {
	[ $MDS1_VERSION -lt $(version_code 2.6.93) ] &&
		skip "MDS needs to be at least 2.6.93"

	touch $DIR/$tfile || error "touch"
	setfattr -n user.$(basename $tfile) $DIR/$tfile || error "setfattr"
	getfattr -n user.$(basename $tfile) $DIR/$tfile || error "getfattr"
	rm $DIR/$tfile || error "rm"

	#normal directory
	mkdir -p $DIR/$tdir || error "mkdir"
	setfattr -n user.$(basename $tdir) $DIR/$tdir || error "setfattr dir"
	getfattr -n user.$(basename $tdir) $DIR/$tdir || error "getfattr dir"
	setfattr -x user.$(basename $tdir) $DIR/$tdir ||
		error "$testfile error deleting user.author1"
	getfattr -d -m user.$(basename $tdir) 2> /dev/null |
		grep "user.$(basename $tdir)" &&
		error "$tdir did not delete user.$(basename $tdir)"
	rmdir $DIR/$tdir || error "rmdir"

	#striped directory
	test_mkdir $DIR/$tdir
	setfattr -n user.$(basename $tdir) $DIR/$tdir || error "setfattr dir"
	getfattr -n user.$(basename $tdir) $DIR/$tdir || error "getfattr dir"
	setfattr -x user.$(basename $tdir) $DIR/$tdir ||
		error "$testfile error deleting user.author1"
	getfattr -d -m user.$(basename $tdir) 2> /dev/null |
		grep "user.$(basename $tdir)" &&
		error "$tdir did not delete user.$(basename $tdir)"
	rmdir $DIR/$tdir || error "rm striped dir"
}
run_test 102r "set EAs with empty values"

test_102s() {
	[ $MDS1_VERSION -lt $(version_code 2.11.52) ] &&
		skip "MDS needs to be at least 2.11.52"

	local save="$TMP/$TESTSUITE-$TESTNAME.parameters"

	save_lustre_params client "llite.*.xattr_cache" > $save

	for cache in 0 1; do
		lctl set_param llite.*.xattr_cache=$cache

		rm -f $DIR/$tfile
		touch $DIR/$tfile || error "touch"
		for prefix in lustre security system trusted user; do
			# Note getxattr() may fail with 'Operation not
			# supported' or 'No such attribute' depending
			# on prefix and cache.
			getfattr -n $prefix.n102s $DIR/$tfile &&
				error "getxattr '$prefix.n102s' should fail (cache = $cache)"
		done
	done

	restore_lustre_params < $save
}
run_test 102s "getting nonexistent xattrs should fail"

test_102t() {
	[ $MDS1_VERSION -lt $(version_code 2.11.52) ] &&
		skip "MDS needs to be at least 2.11.52"

	local save="$TMP/$TESTSUITE-$TESTNAME.parameters"

	save_lustre_params client "llite.*.xattr_cache" > $save

	for cache in 0 1; do
		lctl set_param llite.*.xattr_cache=$cache

		for buf_size in 0 256; do
			rm -f $DIR/$tfile
			touch $DIR/$tfile || error "touch"
			setfattr -n user.multiop $DIR/$tfile
			$MULTIOP $DIR/$tfile oa$buf_size ||
				error "cannot get zero length xattr value (buf_size = $buf_size)"
		done
	done

	restore_lustre_params < $save
}
run_test 102t "zero length xattr values handled correctly"

run_acl_subtest()
{
	local test=$LUSTRE/tests/acl/$1.test
	local tmp=$(mktemp -t $1-XXXXXX).test
	local bin=$2
	local dmn=$3
	local grp=$4
	local nbd=$5
	export LANG=C


	local sedusers="-e s/bin/$bin/g -e s/daemon/$dmn/g"
	local sedgroups="-e s/:users/:$grp/g"
	[[ -z "$nbd" ]] || sedusers+=" -e s/nobody/$nbd/g"

	sed $sedusers $sedgroups < $test > $tmp
	stack_trap "rm -f $tmp"
	[[ -s $tmp ]] || error "sed failed to create test script"

	echo "performing $1 with bin='$bin' daemon='$dmn' users='$grp'..."
	$LUSTRE/tests/acl/run $tmp || error "run_acl_subtest '$1' failed"
}

test_103a() {
	[ "$UID" != 0 ] && skip "must run as root"
	$GSS && skip_env "could not run under gss"
	[[ "$(lctl get_param -n mdc.*-mdc-*.connect_flags)" =~ "acl" ]] ||
		skip_env "must have acl enabled"
	which setfacl || skip_env "could not find setfacl"
	remote_mds_nodsh && skip "remote MDS with nodsh"

	local mdts=$(mdts_nodes)
	local saved=$(do_facet mds1 $LCTL get_param -n mdt.$FSNAME-MDT0000.job_xattr)

	[[ -z "$saved" ]] || do_nodes $mdts $LCTL set_param mdt.*.job_xattr=NONE
	stack_trap "[[ -z \"$saved\" ]] || \
		    do_nodes $mdts $LCTL set_param mdt.*.job_xattr=$saved" EXIT

	ACLBIN=${ACLBIN:-"bin"}
	ACLDMN=${ACLDMN:-"daemon"}
	ACLGRP=${ACLGRP:-"users"}
	ACLNBD=${ACLNBD:-"nobody"}

	if ! id $ACLBIN ||
	   [[ "$(id -u $ACLBIN)" != "$(do_facet mds1 id -u $ACLBIN)" ]]; then
		echo "bad 'bin' user '$ACLBIN', using '$USER0'"
		ACLBIN=$USER0
		if ! id $ACLBIN ; then
			cat /etc/passwd
			skip_env "can't find suitable ACL 'bin' $ACLBIN"
		fi
	fi
	if ! id $ACLDMN || (( $(id -u $ACLDMN) < $(id -u $ACLBIN) )) ||
	   [[ "$(id -u $ACLDMN)" != "$(do_facet mds1 id -u $ACLDMN)" ]]; then
		echo "bad 'daemon' user '$ACLDMN', using '$USER1'"
		ACLDMN=$USER1
		if ! id $ACLDMN ; then
			cat /etc/passwd
			skip_env "can't find suitable ACL 'daemon' $ACLDMN"
		fi
	fi
	if ! getent group $ACLGRP; then
		echo "missing 'users' group '$ACLGRP', using '$TSTUSR'"
		ACLGRP="$TSTUSR"
		if ! getent group $ACLGRP; then
			echo "cannot find group '$ACLGRP', adding it"
			cat /etc/group
			add_group 60000 $ACLGRP
		fi
	fi

	local bingid=$(getent group $ACLBIN | cut -d: -f 3)
	local dmngid=$(getent group $ACLDMN | cut -d: -f 3)
	local grpgid=$(getent group $ACLGRP | cut -d: -f 3)

	if (( $bingid > $grpgid || $dmngid > $grpgid )); then
		echo "group '$ACLGRP' has low gid=$grpgid, use '$TSTUSR'"
		ACLGRP="$TSTUSR"
		if ! getent group $ACLGRP; then
			echo "cannot find group '$ACLGRP', adding it"
			cat /etc/group
			add_group 60000 $ACLGRP
		fi
		grpgid=$(getent group $ACLGRP | cut -d: -f 3)
		if (( $bingid > $grpgid || $dmngid > $grpgid )); then
			cat /etc/group
			skip_env "$ACLGRP gid=$grpgid less than $bingid|$dmngid"
		fi
	fi

	id -nGz "$ACLDMN" | grep -qzxF "$ACLBIN" || gpasswd -a $ACLDMN $ACLBIN ||
		error "setting client group failed"		# LU-5641
	if ! local_mode; then
		do_facet mds1 "id -nGz $ACLDMN | grep -qzxF $ACLBIN ||
				gpasswd -a $ACLDMN $ACLBIN" ||
			error "setting MDS group failed"	# LU-5641
	fi

	declare -a identity_old

	for ((num = 1; num <= $MDSCOUNT; num++)); do
		switch_identity $num true || identity_old[$num]=$?
	done

	SAVE_UMASK=$(umask)
	umask 0022
	$LFS mkdir -c1 -i0 $DIR/$tdir
	cd $DIR/$tdir

	run_acl_subtest cp $ACLBIN $ACLDMN $ACLGRP
	run_acl_subtest getfacl-noacl $ACLBIN $ACLDMN $ACLGRP
	run_acl_subtest misc $ACLBIN $ACLDMN $ACLGRP
	run_acl_subtest permissions $ACLBIN $ACLDMN $ACLGRP
	# LU-1482 mdd: Setting xattr are properly checked with and without ACLs
	# CentOS7- uses nobody=99, while newer distros use nobody=65534
	if ! id -u $ACLNBD ||
	   (( $(id -u nobody) != $(do_facet mds1 id -u nobody) )); then
		ACLNBD="nfsnobody"
		if ! id -u $ACLNBD; then
			ACLNBD=""
		fi
	fi
	if [[ -n "$ACLNBD" ]] && ! getent group $ACLNBD; then
		add_group $(id -u $ACLNBD) $ACLNBD
		if ! getent group $ACLNBD; then
			ACLNBD=""
		fi
	fi
	if (( $MDS1_VERSION > $(version_code 2.8.55) )) &&
	   [[ -n "$ACLNBD" ]] && which setfattr; then
		run_acl_subtest permissions_xattr \
			$ACLBIN $ACLDMN $ACLGRP $ACLNBD
	elif [[ -z "$ACLNBD" ]]; then
		echo "skip 'permission_xattr' test - missing 'nobody' user/grp"
	else
		echo "skip 'permission_xattr' test - missing setfattr command"
	fi
	run_acl_subtest setfacl $ACLBIN $ACLDMN $ACLGRP

	# inheritance test got from HP
	cp $LUSTRE/tests/acl/make-tree . || error "cannot copy make-tree"
	chmod +x make-tree || error "chmod +x failed"
	run_acl_subtest inheritance $ACLBIN $ACLDMN $ACLGRP
	rm -f make-tree

	echo "LU-974 ignore umask when acl is enabled..."
	run_acl_subtest 974 $ACLBIN $ACLDMN $ACLGRP
	if [ $MDSCOUNT -ge 2 ]; then
		run_acl_subtest 974_remote $ACLBIN $ACLDMN $ACLGRP
	fi

	echo "LU-2561 newly created file is same size as directory..."
	if [ "$mds1_FSTYPE" != "zfs" ]; then
		run_acl_subtest 2561 $ACLBIN $ACLDMN $ACLGRP
	else
		run_acl_subtest 2561_zfs $ACLBIN $ACLDMN $ACLGRP
	fi

	run_acl_subtest 4924 $ACLBIN $ACLDMN $ACLGRP

	cd $SAVE_PWD
	umask $SAVE_UMASK

	for ((num = 1; num <= $MDSCOUNT; num++)); do
		if [[ "${identity_old[$num]}" == 1 ]]; then
			switch_identity $num false || identity_old[$num]=$?
		fi
	done
}
run_test 103a "acl test"

test_103b() {
	declare -a pids
	local U

	stack_trap "rm -f $DIR/$tfile.*"
	for U in {0..511}; do
		{
		local O=$(printf "%04o" $U)

		umask $(printf "%04o" $((511 ^ $O)))
		$LFS setstripe -c 1 $DIR/$tfile.s$O
		local S=$(printf "%04o" 0$(stat -c%a $DIR/$tfile.s$O))

		(( $S == ($O & 0666) )) ||
			error "lfs setstripe $DIR/$tfile.s$O '$S' != '$O'"

		$LFS setstripe -E16M -c 1 -E1G -S4M $DIR/$tfile.p$O
		S=$(printf "%04o" 0$(stat -c%a $DIR/$tfile.p$O))
		(( $S == ($O & 0666) )) ||
			error "lfs setstripe -E $DIR/$tfile.p$O '$S' != '$O'"

		$LFS setstripe -N2 -c 1 $DIR/$tfile.m$O
		S=$(printf "%04o" 0$(stat -c%a $DIR/$tfile.m$O))
		(( $S == ($O & 0666) )) ||
			error "lfs setstripe -N2 $DIR/$tfile.m$O '$S' != '$O'"
		rm -f $DIR/$tfile.[smp]$0
		} &
		local pid=$!

		# limit the concurrently running threads to 64. LU-11878
		local idx=$((U % 64))
		[ -z "${pids[idx]}" ] || wait ${pids[idx]}
		pids[idx]=$pid
	done
	wait
}
run_test 103b "umask lfs setstripe"

test_103c() {
	mkdir -p $DIR/$tdir
	cp -rp $DIR/$tdir $DIR/$tdir.bak

	[ -n "$(getfattr -d -m. $DIR/$tdir | grep posix_acl_default)" ] &&
		error "$DIR/$tdir shouldn't contain default ACL"
	[ -n "$(getfattr -d -m. $DIR/$tdir.bak | grep posix_acl_default)" ] &&
		error "$DIR/$tdir.bak shouldn't contain default ACL"
	true
}
run_test 103c "'cp -rp' won't set empty acl"

test_103e() {
	local numacl
	local fileacl
	local saved_debug=$($LCTL get_param -n debug)

	(( $MDS1_VERSION >= $(version_code v2_14_50-1-gf3d03bc38a) )) ||
		skip "MDS needs to be at least 2.14.50.1"

	large_xattr_enabled || skip_env "ea_inode feature disabled"

	mkdir -p $DIR/$tdir
	# add big LOV EA to cause reply buffer overflow earlier
	$LFS setstripe -C 1000 $DIR/$tdir
	lctl set_param mdc.*-mdc*.stats=clear

	$LCTL set_param debug=0
	stack_trap "$LCTL set_param debug=\"$saved_debug\"" EXIT
	stack_trap "$LCTL get_param mdc.*-mdc*.stats" EXIT

	# add large number of default ACLs in $incr batches (8000+ for 2.13+)
	local incr=100
	for ((range=0; range < 7000/incr; range++)); do
		for ((U = range * incr + 2; U < (range+1) * incr; U++)); do
			echo "user:$U:rwx"
		done | setfacl -d -M /dev/stdin $DIR/$tdir ||
			error "Cannot add $U default ACLs"
	done
	numacl=$(getfacl $DIR/$tdir |& grep -c "default:user")
	echo "$numacl default ACLs created"

	stat $DIR/$tdir || error "Cannot stat directory"
	# check file creation
	touch $DIR/$tdir/$tfile ||
		error "failed to create $tfile with $numacl default ACLs"
	stat $DIR/$tdir/$tfile  || error "Cannot stat file"
	fileacl=$(getfacl $DIR/$tdir/$tfile |& grep -c "user:")
	echo "$fileacl ACLs were inherited"
	(( $fileacl == $numacl )) ||
		error "Not all default ACLs were inherited: $numacl != $fileacl"
	# check that new ACLs creation adds new ACLs to inherited ACLs
	setfacl -m user:19000:rwx $DIR/$tdir/$tfile ||
		error "Cannot set new ACL"
	numacl=$((numacl + 1))
	fileacl=$(getfacl $DIR/$tdir/$tfile |& grep -c "user:")
	(( $fileacl == $numacl )) ||
		error "failed to add new ACL: $fileacl != $numacl as expected"
	# add more ACLs in $incr batches to reach their maximum at 8000+
	numacl=0
	for ((range = 20000/incr; range < 25/incr; range++)); do
		for ((U = range * incr; U < (range+1) * incr; U++)); do
			echo "user:$U:rwx"
		done | setfacl -M /dev/stdin $DIR/$tdir/$tfile || break
		numacl=$((numacl + incr))
	done
	echo "Added $numacl more ACLs to the file"
	fileacl=$(getfacl $DIR/$tdir/$tfile |& grep -c "user:")
	echo "Total $fileacl ACLs in file"
	stat $DIR/$tdir/$tfile > /dev/null || error "Cannot stat file"
	rm -f $DIR/$tdir/$tfile || error "Cannot remove file"
	rmdir $DIR/$tdir || error "Cannot remove directory"
}
run_test 103e "inheritance of big amount of default ACLs"

test_103f() {
	(( $MDS1_VERSION >= $(version_code 2.14.51) )) ||
		skip "MDS needs to be at least 2.14.51"

	large_xattr_enabled || skip_env "ea_inode feature disabled"

	# enable changelog to consume more internal MDD buffers
	changelog_register

	mkdir -p $DIR/$tdir
	# add big LOV EA
	$LFS setstripe -C 1000 $DIR/$tdir
	setfacl -d -m user:$U:rwx $DIR/$tdir || error "Cannot add default ACLs"
	mkdir $DIR/$tdir/inherited || error "failed to create subdirectory"
	rmdir $DIR/$tdir/inherited || error "Cannot remove subdirectory"
	rmdir $DIR/$tdir || error "Cannot remove directory"
}
run_test 103f "changelog doesn't interfere with default ACLs buffers"

test_103g() {
	which getfacl || skip "missing getfacl"
	[[ "$(lctl get_param -n mdc.*-mdc-*.connect_flags)" =~ "acl" ]] ||
		skip_env "must have acl enabled"

	local mdc_stat_param="mdc.$FSNAME-MDT*.md_stats"
	local count
	local f=$DIR/$tfile

	touch $f
	chmod 755 $f
	cancel_lru_locks mdc
	$RUNAS test -r $DIR

	clear_stats $mdc_stat_param ||
		error "fail to clear mdc stats"

	# access(2) as a non-owner triggers acl_permission_check ->
	# check_acl -> get_inode_acl -> ll_get_acl_common
	$RUNAS test -r $f || error "test -r $f as $RUNAS_ID failed"

	count=$(calc_stats $mdc_stat_param "getxattr")
	echo "getxattr ACL RPCs: $count"

	# access should not send ACL getxattr (ACLs are returned by lock intent)
	(( !count )) ||
		error "client sent $count getxattr RPCs"

	# negative cache must be invalidated when an ACL is installed
	setfacl -m u:$RUNAS_ID:rwx $f || error "setfacl $f failed"
	$RUNAS getfacl -n $f 2>/dev/null | grep -q "^user:$RUNAS_ID:rwx$" ||
		error "ACL not visible after setfacl (negative cache stuck)"
}
run_test 103g "no MDS_GETXATTR storm for inodes without ACL_ACCESS (LU-17238)"

test_104a() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	touch $DIR/$tfile
	lfs df || error "lfs df failed"
	lfs df -ih || error "lfs df -ih failed"
	lfs df -h $DIR || error "lfs df -h $DIR failed"
	lfs df -i $DIR || error "lfs df -i $DIR failed"
	lfs df $DIR/$tfile || error "lfs df $DIR/$tfile failed"
	lfs df -ih $DIR/$tfile || error "lfs df -ih $DIR/$tfile failed"

	local OSC=$(lctl dl | grep OST0000-osc-[^M] | awk '{ print $4 }')
	lctl --device %$OSC deactivate
	lfs df || error "lfs df with deactivated OSC failed"
	lctl --device %$OSC activate
	# wait the osc back to normal
	wait_osc_import_ready client ost

	lfs df || error "lfs df with reactivated OSC failed"
	rm -f $DIR/$tfile
}
run_test 104a "lfs df [-ih] [path] test ========================="

test_104b() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ $RUNAS_ID -eq $UID ] &&
		skip_env "RUNAS_ID = UID = $UID -- skipping"

	denied_cnt=$(($($RUNAS $LFS check servers 2>&1 |
			grep "Permission denied" | wc -l)))
	if [ $denied_cnt -ne 0 ]; then
		error "lfs check servers test failed"
	fi
}
run_test 104b "$RUNAS lfs check servers test ===================="

#
# Verify $1 is within range of $2.
# Success when $1 is within range. That is, when $1 is >= 2% of $2 and
# $1 is <= 2% of $2. Else Fail.
#
value_in_range() {
	# Strip all units (M, G, T)
	actual=$(echo $1 | tr -d A-Z)
	expect=$(echo $2 | tr -d A-Z)

	expect_lo=$(($expect * 98 / 100)) # 2% below
	expect_hi=$(($expect * 102 / 100)) # 2% above

	# permit 2% drift above and below
	(( $actual >= $expect_lo && $actual <= $expect_hi ))
}

test_104c() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ "$ost1_FSTYPE" == "zfs" ] || skip "zfs only test"

	local ost_param="osd-zfs.$FSNAME-OST0000."
	local mdt_param="osd-zfs.$FSNAME-MDT0000."
	local ofacets=$(get_facets OST)
	local mfacets=$(get_facets MDS)
	local saved_ost_blocks=
	local saved_mdt_blocks=

	echo "Before recordsize change"
	lfs_df=($($LFS df -h | grep "filesystem_summary:"))
	df=($(df -h | grep "$MOUNT"$))

	# For checking.
	echo "lfs output : ${lfs_df[*]}"
	echo "df  output : ${df[*]}"

	for facet in ${ofacets//,/ }; do
		if [ -z $saved_ost_blocks ]; then
			saved_ost_blocks=$(do_facet $facet \
				lctl get_param -n $ost_param.blocksize)
			echo "OST Blocksize: $saved_ost_blocks"
		fi
		ost=$(do_facet $facet lctl get_param -n $ost_param.mntdev)
		do_facet $facet zfs set recordsize=32768 $ost
	done

	# BS too small. Sufficient for functional testing.
	for facet in ${mfacets//,/ }; do
		if [ -z $saved_mdt_blocks ]; then
			saved_mdt_blocks=$(do_facet $facet \
				lctl get_param -n $mdt_param.blocksize)
			echo "MDT Blocksize: $saved_mdt_blocks"
		fi
		mdt=$(do_facet $facet lctl get_param -n $mdt_param.mntdev)
		do_facet $facet zfs set recordsize=32768 $mdt
	done

	# Give new values chance to reflect change
	sleep 2

	echo "After recordsize change"
	lfs_df_after=($($LFS df -h | grep "filesystem_summary:"))
	df_after=($(df -h | grep "$MOUNT"$))

	# For checking.
	echo "lfs output : ${lfs_df_after[*]}"
	echo "df  output : ${df_after[*]}"

	# Verify lfs df
	value_in_range ${lfs_df_after[1]%.*} ${lfs_df[1]%.*} ||
		error "lfs_df bytes: ${lfs_df_after[1]%.*} != ${lfs_df[1]%.*}"
	value_in_range ${lfs_df_after[2]%.*} ${lfs_df[2]%.*} ||
		error "lfs_df used: ${lfs_df_after[2]%.*} != ${lfs_df[2]%.*}"
	value_in_range ${lfs_df_after[3]%.*} ${lfs_df[3]%.*} ||
		error "lfs_df avail: ${lfs_df_after[3]%.*} != ${lfs_df[3]%.*}"

	# Verify df
	value_in_range ${df_after[1]%.*} ${df[1]%.*} ||
		error "df bytes: ${df_after[1]%.*} != ${df[1]%.*}"
	value_in_range ${df_after[2]%.*} ${df[2]%.*} ||
		error "df used: ${df_after[2]%.*} != ${df[2]%.*}"
	value_in_range ${df_after[3]%.*} ${df[3]%.*} ||
		error "df avail: ${df_after[3]%.*} != ${df[3]%.*}"

	# Restore MDT recordize back to original
	for facet in ${mfacets//,/ }; do
		mdt=$(do_facet $facet lctl get_param -n $mdt_param.mntdev)
		do_facet $facet zfs set recordsize=$saved_mdt_blocks $mdt
	done

	# Restore OST recordize back to original
	for facet in ${ofacets//,/ }; do
		ost=$(do_facet $facet lctl get_param -n $ost_param.mntdev)
		do_facet $facet zfs set recordsize=$saved_ost_blocks $ost
	done

	return 0
}
run_test 104c "Verify df vs lfs_df stays same after recordsize change"

test_104d() {
	(( $RUNAS_ID != $UID )) ||
		skip_env "RUNAS_ID = UID = $UID -- skipping"

	(( $CLIENT_VERSION >= $(version_code 2.15.51) )) ||
		skip "lustre version doesn't support lctl dl with non-root"

	# debugfs only allows root users to access files, so the
	# previous move of the "devices" file to debugfs broke
	# "lctl dl" for non-root users. The LU-9680 Netlink
	# interface again allows non-root users to list devices.
	[ "$($RUNAS $LCTL dl | wc -l)" -ge 3 ] ||
		error "lctl dl doesn't work for non root"

	echo "=="
	$RUNAS $LCTL dl | grep "$FSNAME-OST*"
	echo "=="
	$RUNAS $LCTL dl | grep "obdfilter $FSNAME-OST*"
	echo "=="
	ost_count="$($RUNAS $LCTL dl | grep "osc $FSNAME-OST*" | wc -l)"
	[ "$ost_count" -eq $OSTCOUNT ]  ||
		error "lctl dl reports wrong number of OST devices"

	$RUNAS $LCTL dl | grep "mdt $FSNAME-MDT*"
	mdt_count="$($RUNAS $LCTL dl | grep "mdc $FSNAME-MDT*" | wc -l)"
	[ "$mdt_count" -eq $MDSCOUNT ]  ||
		error "lctl dl reports wrong number of MDT devices"
}
run_test 104d "$RUNAS lctl dl test"

test_105a() {
	# doesn't work on 2.4 kernels
	touch $DIR/$tfile
	if $(flock_is_enabled); then
		flocks_test 1 on -f $DIR/$tfile || error "fail flock on"
	else
		flocks_test 1 off -f $DIR/$tfile || error "fail flock off"
	fi
	rm -f $DIR/$tfile
}
run_test 105a "flock when mounted without -o flock test ========"

test_105b() {
	touch $DIR/$tfile
	if $(flock_is_enabled); then
		flocks_test 1 on -c $DIR/$tfile || error "fail flock on"
	else
		flocks_test 1 off -c $DIR/$tfile || error "fail flock off"
	fi
	rm -f $DIR/$tfile
}
run_test 105b "fcntl when mounted without -o flock test ========"

test_105c() {
	touch $DIR/$tfile
	if $(flock_is_enabled); then
		flocks_test 1 on -l $DIR/$tfile || error "fail flock on"
	else
		flocks_test 1 off -l $DIR/$tfile || error "fail flock off"
	fi
	rm -f $DIR/$tfile
}
run_test 105c "lockf when mounted without -o flock test"

test_105d() { # bug 15924
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	test_mkdir $DIR/$tdir
	flock_is_enabled || skip_env "mount w/o flock enabled"
	#define OBD_FAIL_LDLM_CP_CB_WAIT  0x315
	$LCTL set_param fail_loc=0x80000315
	flocks_test 2 $DIR/$tdir
}
run_test 105d "flock race (should not freeze) ========"

test_105e() { # bug 22660 && 22040
	flock_is_enabled || skip_env "mount w/o flock enabled"

	touch $DIR/$tfile
	flocks_test 3 $DIR/$tfile
}
run_test 105e "Two conflicting flocks from same process"

wait_end() {
	echo $*
	while :; do
		[ -f $TMP/${tfile}_sTOP ] && return
		sleep 1
	done
}

test_105f() {
	flock_is_enabled || skip_env "mount w/o flock enabled"

	local pmax=$(ulimit -u)
	local i=0
	touch $DIR/$tfile
	[ $pmax -gt 20 ] && pmax=20
	for((i=0; i <= $pmax; i++)) {
		wait_end "R4000, 5000" | flocks_test 6 $DIR/$tfile &
	}
	for((i=0; i <= 10; i++)) {
		local locks=$(do_facet $SINGLEMDS $LCTL get_param -n \
			ldlm.namespaces.mdt-${FSNAME}-MDT0000*.lock_count)
		[ $locks -ge $pmax ] && break
		[ $i -eq 10 ] && error "The locks cannot be added after 10 secs"
		sleep 1
	}
	touch $TMP/${tfile}_sTOP
	wait
	rm -r $DIR/$tfile $TMP/${tfile}_sTOP
}
run_test 105f "Enqueue same range flocks"

test_105g() {
	(( $CLIENT_VERSION >= $(version_code 2.15.64.117) )) ||
		skip "Need Client >= 2.15.63.127 for ldlm dump stack"

	flock_is_enabled || skip_env "mount w/o flock enabled"
	mkdir $DIR/$tdir
	#define OBD_FAIL_LDLM_LOCK_STACK  0x32f
	do_facet client $LCTL set_param -n \
		ldlm.namespaces.*.dump_stack_on_error=1
	stack_trap "do_facet client $LCTL set_param -n \
		ldlm.namespaces.*.dump_stack_on_error=0"
	$LCTL set_param fail_loc=0x8000032f
	flocks_test 2 $DIR/$tdir
	dmesg | tac | sed "/$(echo $TESTNAME | tr '_' ' ')/,$ d" |
		grep -q "dump_stack" || error "didn't find dump_stack"
}
run_test 105g "ldlm_lock_debug stack test"

test_105h() {
	local info
	touch $DIR/$tfile

	stack_trap "rm $DIR/$tfile" EXIT
	# enqueue 2 non-overlap locks
	info=$(echo -e "W20,40\nR100,200\nT0" | flocks_test 6 $DIR/$tfile)
	[ x$info == 'xW20,40;R100,200.' ] || error "flock error1-$info"
	# enqueue overlap locks
	info=$(echo -e "W20,400\nR100,2000\nR10,1000\nW500,1000\nT0" | flocks_test 6 $DIR/$tfile)
	[ x$info == 'xR10,490;W500,1000;R1500,600.' ] || error "flock error2-$info"
	# split a lock
	info=$(echo -e "W2000,1000\nR2200, 200\nT0" |flocks_test 6 $DIR/$tfile)
	[ x$info == 'xW2000,200;R2200,200;W2400,600.' ] || error "flock error3-$info"
	# merge 2 locks
	info=$(echo -e "R200,1000\nR9000,200\nW100,10000\nT0" | flocks_test 6 $DIR/$tfile)
	[ x$info == 'xW100,10000.' ] || error "flock error4-$info"
	# adjoining locks
	info=$(echo -e "R200,100\nR300, 200\nR500,100\nT0" | flocks_test 6 $DIR/$tfile)
	[ x$info == 'xR200,400.' ] || error "flock error5-$info"
	# adjoining locks with diff mode
	info=$(echo -e "R200,100\nW300, 200\nR500,100\nT0" | flocks_test 6 $DIR/$tfile)
	[ x$info == 'xR200,100;W300,200;R500,100.' ] || error "flock error6-$info"
	# split & merge
	info=$(echo -e "R200,1000\nW300, 200\nR100,200\nR300,200\nT0" | flocks_test 6 $DIR/$tfile)
	[ x$info == 'xR100,1100.' ] || error "flock error7-$info"
}
run_test 105h "Flock functional verify"

test_105i() {
	local tmpfile=$TMP/tmpf.$$
	touch $DIR/$tfile

	stack_trap "rm $tmpfile $DIR/$tfile" EXIT
	# enqueue 2 non-overlap locks
	>$tmpfile
	echo -e "R20,200\nP5\nW10,1000" | flocks_test 6 $DIR/$tfile 2>>$tmpfile &
	echo -e "R20,200\nP5\nW10,1000" | flocks_test 6 $DIR/$tfile 2>>$tmpfile &
	wait
	# Check for EDEADLK
	grep 'cannot set lock(35)' $tmpfile
}
run_test 105i "Flock deadlock verify"

test_106() { #bug 10921
	test_mkdir $DIR/$tdir
	$DIR/$tdir && error "exec $DIR/$tdir succeeded"
	chmod 777 $DIR/$tdir || error "chmod $DIR/$tdir failed"
}
run_test 106 "attempt exec of dir followed by chown of that dir"

test_107() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	CDIR=`pwd`
	local file=core

	cd $DIR
	rm -f $file

        local save_pattern=$(sysctl -n kernel.core_pattern)
        local save_uses_pid=$(sysctl -n kernel.core_uses_pid)
        sysctl -w kernel.core_pattern=$file
        sysctl -w kernel.core_uses_pid=0

        ulimit -c unlimited
        sleep 60 &
        SLEEPPID=$!

        sleep 1

        kill -s 11 $SLEEPPID
        wait $SLEEPPID
        if [ -e $file ]; then
                size=`stat -c%s $file`
                [ $size -eq 0 ] && error "Fail to create core file $file"
        else
                error "Fail to create core file $file"
        fi
        rm -f $file
        sysctl -w kernel.core_pattern=$save_pattern
        sysctl -w kernel.core_uses_pid=$save_uses_pid
        cd $CDIR
}
run_test 107 "Coredump on SIG"

test_110() {
	test_mkdir $DIR/$tdir
	test_mkdir $DIR/$tdir/$(str_repeat 'a' 255)
	$LFS mkdir -c $MDSCOUNT $DIR/$tdir/$(str_repeat 'b' 256) &&
		error "mkdir with 256 char should fail, but did not"
	touch $DIR/$tdir/$(str_repeat 'x' 255) ||
		error "create with 255 char failed"
	touch $DIR/$tdir/$(str_repeat 'y' 256) &&
		error "create with 256 char should fail, but did not"

	ls -l $DIR/$tdir
	rm -rf $DIR/$tdir
}
run_test 110 "filename length checking"

test_116a() { # was previously test_116()
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[[ $OSTCOUNT -lt 2 ]] && skip_env "needs >= 2 OSTs"
	remote_mds_nodsh && skip "remote MDS with nodsh"

	echo -n "Free space priority "
	do_facet $SINGLEMDS lctl get_param -n lo[vd].*-mdtlov.qos_prio_free |
		head -n1
	declare -a AVAIL
	free_min_max

	[ $MINV -eq 0 ] && skip "no free space in OST$MINI, skip"
	[ $MINV -gt 10000000 ] && skip "too much free space in OST$MINI, skip"
	stack_trap simple_cleanup_common

	# Check if we need to generate uneven OSTs
	test_mkdir -p $DIR/$tdir/OST${MINI}
	local FILL=$((MINV / 4))
	local DIFF=$((MAXV - MINV))
	local DIFF2=$((DIFF * 100 / MINV))

	local threshold=$(do_facet $SINGLEMDS \
		lctl get_param -n *.*MDT0000-mdtlov.qos_threshold_rr | head -n1)
	threshold=${threshold%%%}
	echo -n "Check for uneven OSTs: "
	echo -n "diff=${DIFF}KB (${DIFF2}%) must be > ${threshold}% ..."

	if [[ $DIFF2 -gt $threshold ]]; then
		echo "ok"
		echo "Don't need to fill OST$MINI"
	else
		# generate uneven OSTs. Write 2% over the QOS threshold value
		echo "no"
		DIFF=$((threshold - DIFF2 + 2))
		DIFF2=$((MINV * DIFF / 100))
		echo "Fill $DIFF% remaining space in OST$MINI with ${DIFF2}KB"
		$LFS setstripe -i $MINI -c 1 $DIR/$tdir/OST${MINI} ||
			error "setstripe failed"
		DIFF=$((DIFF2 / 2048))
		fast_file_write $DIR/$tdir/OST${MINI}/$tfile 2M $DIFF
		sync
		sleep_maxage
		free_min_max
	fi

	DIFF=$((MAXV - MINV))
	DIFF2=$((DIFF * 100 / MINV))
	echo -n "diff=$DIFF=$DIFF2% must be > $threshold% for QOS mode..."
	if [ $DIFF2 -gt $threshold ]; then
		echo "ok"
	else
		skip "QOS imbalance criteria not met"
	fi

	MINI1=$MINI
	MINV1=$MINV
	MAXI1=$MAXI
	MAXV1=$MAXV

	# now fill using QOS
	$LFS setstripe -c 1 $DIR/$tdir
	FILL=$((FILL / 200))
	if [ $FILL -gt 600 ]; then
		FILL=600
	fi
	echo "writing $FILL files to QOS-assigned OSTs"
	fast_file_write $DIR/$tdir/$tfile 200k $FILL
	echo "wrote $FILL 200k files"
	sync
	sleep_maxage

	echo "Note: free space may not be updated, so measurements might be off"
	free_min_max
	DIFF2=$((MAXV - MINV))
	echo "free space delta: orig $DIFF final $DIFF2"
	[ $DIFF2 -gt $DIFF ] && echo "delta got worse!"
	DIFF=$((MINV1 - ${AVAIL[$MINI1]}))
	echo "Wrote ${DIFF}KB to smaller OST $MINI1"
	DIFF2=$((MAXV1 - ${AVAIL[$MAXI1]}))
	echo "Wrote ${DIFF2}KB to larger OST $MAXI1"
	if [[ $DIFF -gt 0 ]]; then
		FILL=$((DIFF2 * 100 / DIFF - 100))
		echo "Wrote ${FILL}% more data to larger OST $MAXI1"
	fi

	# Figure out which files were written where
	UUID=$(lctl get_param -n lov.${FSNAME}-clilov-*.target_obd |
	       awk '/'$MINI1': / {print $2; exit}')
	echo $UUID
	MINC=$($LFS getstripe --ost $UUID $DIR/$tdir | grep $DIR | wc -l)
	echo "$MINC files created on smaller OST $MINI1"
	UUID=$(lctl get_param -n lov.${FSNAME}-clilov-*.target_obd |
	       awk '/'$MAXI1': / {print $2; exit}')
	echo $UUID
	MAXC=$($LFS getstripe --ost $UUID $DIR/$tdir | grep $DIR | wc -l)
	echo "$MAXC files created on larger OST $MAXI1"
	if [[ $MINC -gt 0 ]]; then
		FILL=$((MAXC * 100 / MINC - 100))
		echo "Wrote ${FILL}% more files to larger OST $MAXI1"
	fi
	[[ $MAXC -gt $MINC ]] ||
		error_ignore LU-9 "stripe QOS didn't balance free space"
}
run_test 116a "stripe QOS: free space balance ==================="

test_116b() { # LU-2093
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"

#define OBD_FAIL_MDS_OSC_CREATE_FAIL     0x147
	local old_rr=$(do_facet $SINGLEMDS lctl get_param -n \
		       lo[vd].$FSNAME-MDT0000-mdtlov.qos_threshold_rr | head -1)
	[ -z "$old_rr" ] && skip "no QOS"
	do_facet $SINGLEMDS lctl set_param \
		lo[vd].$FSNAME-MDT0000-mdtlov.qos_threshold_rr=0
	mkdir -p $DIR/$tdir
	do_facet $SINGLEMDS lctl set_param fail_loc=0x147
	createmany -o $DIR/$tdir/f- 20 || error "can't create"
	do_facet $SINGLEMDS lctl set_param fail_loc=0
	rm -rf $DIR/$tdir
	do_facet $SINGLEMDS lctl set_param \
		lo[vd].$FSNAME-MDT0000-mdtlov.qos_threshold_rr=$old_rr
}
run_test 116b "QoS shouldn't LBUG if not enough OSTs found on the 2nd pass"

test_117() # bug 10891
{
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	dd if=/dev/zero of=$DIR/$tfile bs=1M count=1
	#define OBD_FAIL_OST_SETATTR_CREDITS 0x21e
	lctl set_param fail_loc=0x21e
	> $DIR/$tfile || error "truncate failed"
	lctl set_param fail_loc=0
	echo "Truncate succeeded."
	rm -f $DIR/$tfile
}
run_test 117 "verify osd extend =========="

NO_SLOW_RESENDCOUNT=4
export OLD_RESENDCOUNT=""
set_resend_count () {
	local PROC_RESENDCOUNT="osc.${FSNAME}-OST*-osc-*.resend_count"
	OLD_RESENDCOUNT=$(lctl get_param -n $PROC_RESENDCOUNT | head -n1)
	lctl set_param -n $PROC_RESENDCOUNT $1
	echo resend_count is set to $(lctl get_param -n $PROC_RESENDCOUNT)
}

# for reduce test_118* time (b=14842)
[ "$SLOW" = "no" ] && set_resend_count $NO_SLOW_RESENDCOUNT

# Reset async IO behavior after error case
reset_async() {
	FILE=$DIR/reset_async

	# Ensure all OSCs are cleared
	$LFS setstripe -c -1 $FILE
	dd if=/dev/zero of=$FILE bs=64k count=$OSTCOUNT
	sync
	rm $FILE
}

test_118a() #bug 11710
{
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	reset_async

	$MULTIOP $DIR/$tfile oO_CREAT:O_RDWR:O_SYNC:w4096c
	DIRTY=$(lctl get_param -n llite.*.dump_page_cache | grep -c dirty)
        WRITEBACK=$(lctl get_param -n llite.*.dump_page_cache | grep -c writeback)

	if [[ $DIRTY -ne 0 || $WRITEBACK -ne 0 ]]; then
		error "Dirty pages not flushed to disk, dirty=$DIRTY, writeback=$WRITEBACK"
		return 1;
        fi
	rm -f $DIR/$tfile
}
run_test 118a "verify O_SYNC works =========="

test_118b()
{
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_ost_nodsh && skip "remote OST with nodsh"
	local osts=$(osts_nodes)

	reset_async

	#define OBD_FAIL_SRV_ENOENT 0x217
	set_nodes_failloc $osts 0x217
	$MULTIOP $DIR/$tfile oO_CREAT:O_RDWR:O_SYNC:w4096c
	RC=$?
	set_nodes_failloc $osts 0
        DIRTY=$(lctl get_param -n llite.*.dump_page_cache | grep -c dirty)
        WRITEBACK=$(lctl get_param -n llite.*.dump_page_cache |
                    grep -c writeback)

	if [[ $RC -eq 0 ]]; then
		error "Must return error due to dropped pages, rc=$RC"
		return 1;
	fi

	if [[ $DIRTY -ne 0 || $WRITEBACK -ne 0 ]]; then
		error "Dirty pages not flushed to disk, dirty=$DIRTY, writeback=$WRITEBACK"
		return 1;
	fi

	echo "Dirty pages not leaked on ENOENT"

	# Due to the above error the OSC will issue all RPCs syncronously
	# until a subsequent RPC completes successfully without error.
	$MULTIOP $DIR/$tfile Ow4096yc
	rm -f $DIR/$tfile

	return 0
}
run_test 118b "Reclaim dirty pages on fatal error =========="

test_118c()
{
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	# for 118c, restore the original resend count, LU-1940
	[ "$SLOW" = "no" ] && [ -n "$OLD_RESENDCOUNT" ] &&
				set_resend_count $OLD_RESENDCOUNT
	remote_ost_nodsh && skip "remote OST with nodsh"
	local osts=$(osts_nodes)

	reset_async

	#define OBD_FAIL_OST_EROFS               0x216
	set_nodes_failloc $osts 0x216

	# multiop should block due to fsync until pages are written
	$MULTIOP $DIR/$tfile oO_CREAT:O_RDWR:O_SYNC:w4096c &
	MULTIPID=$!
	sleep 1

	if [[ `ps h -o comm -p $MULTIPID` != "multiop" ]]; then
		error "Multiop failed to block on fsync, pid=$MULTIPID"
	fi

        WRITEBACK=$(lctl get_param -n llite.*.dump_page_cache |
                    grep -c writeback)
	if [[ $WRITEBACK -eq 0 ]]; then
		error "No page in writeback, writeback=$WRITEBACK"
	fi

	set_nodes_failloc $osts 0
        wait $MULTIPID
	RC=$?
	if [[ $RC -ne 0 ]]; then
		error "Multiop fsync failed, rc=$RC"
	fi

        DIRTY=$(lctl get_param -n llite.*.dump_page_cache | grep -c dirty)
        WRITEBACK=$(lctl get_param -n llite.*.dump_page_cache |
                    grep -c writeback)
	if [[ $DIRTY -ne 0 || $WRITEBACK -ne 0 ]]; then
		error "Dirty pages not flushed to disk, dirty=$DIRTY, writeback=$WRITEBACK"
	fi

	rm -f $DIR/$tfile
	echo "Dirty pages flushed via fsync on EROFS"
	return 0
}
run_test 118c "Fsync blocks on EROFS until dirty pages are flushed =========="

# continue to use small resend count to reduce test_118* time (b=14842)
[ "$SLOW" = "no" ] && set_resend_count $NO_SLOW_RESENDCOUNT

test_118d()
{
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_ost_nodsh && skip "remote OST with nodsh"
	local osts=$(osts_nodes)

	reset_async

	#define OBD_FAIL_OST_BRW_PAUSE_BULK
	set_nodes_failloc $osts 0x214
	# multiop should block due to fsync until pages are written
	$MULTIOP $DIR/$tfile oO_CREAT:O_RDWR:O_SYNC:w4096c &
	MULTIPID=$!
	sleep 1

	if [[ `ps h -o comm -p $MULTIPID` != "multiop" ]]; then
		error "Multiop failed to block on fsync, pid=$MULTIPID"
	fi

        WRITEBACK=$(lctl get_param -n llite.*.dump_page_cache |
                    grep -c writeback)
	if [[ $WRITEBACK -eq 0 ]]; then
		error "No page in writeback, writeback=$WRITEBACK"
	fi

        wait $MULTIPID || error "Multiop fsync failed, rc=$?"
	set_nodes_failloc $osts 0

        DIRTY=$(lctl get_param -n llite.*.dump_page_cache | grep -c dirty)
        WRITEBACK=$(lctl get_param -n llite.*.dump_page_cache |
                    grep -c writeback)
	if [[ $DIRTY -ne 0 || $WRITEBACK -ne 0 ]]; then
		error "Dirty pages not flushed to disk, dirty=$DIRTY, writeback=$WRITEBACK"
	fi

	rm -f $DIR/$tfile
	echo "Dirty pages gaurenteed flushed via fsync"
	return 0
}
run_test 118d "Fsync validation inject a delay of the bulk =========="

test_118f() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	reset_async

	#define OBD_FAIL_OSC_BRW_PREP_REQ2        0x40a
	lctl set_param fail_loc=0x8000040a

	# Should simulate EINVAL error which is fatal
        $MULTIOP $DIR/$tfile oO_CREAT:O_RDWR:O_SYNC:w4096c
        RC=$?
	if [[ $RC -eq 0 ]]; then
		error "Must return error due to dropped pages, rc=$RC"
	fi

        lctl set_param fail_loc=0x0

        LOCKED=$(lctl get_param -n llite.*.dump_page_cache | grep -c locked)
        DIRTY=$(lctl get_param -n llite.*.dump_page_cache | grep -c dirty)
        WRITEBACK=$(lctl get_param -n llite.*.dump_page_cache |
                    grep -c writeback)
	if [[ $LOCKED -ne 0 ]]; then
		error "Locked pages remain in cache, locked=$LOCKED"
	fi

	if [[ $DIRTY -ne 0 || $WRITEBACK -ne 0 ]]; then
		error "Dirty pages not flushed to disk, dirty=$DIRTY, writeback=$WRITEBACK"
	fi

	rm -f $DIR/$tfile
	echo "No pages locked after fsync"

        reset_async
	return 0
}
run_test 118f "Simulate unrecoverable OSC side error =========="

test_118g() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	reset_async

	#define OBD_FAIL_OSC_BRW_PREP_REQ        0x406
	lctl set_param fail_loc=0x406

	# simulate local -ENOMEM
	$MULTIOP $DIR/$tfile oO_CREAT:O_RDWR:O_SYNC:w4096c
	RC=$?

	lctl set_param fail_loc=0
	if [[ $RC -eq 0 ]]; then
		error "Must return error due to dropped pages, rc=$RC"
	fi

	LOCKED=$(lctl get_param -n llite.*.dump_page_cache | grep -c locked)
	DIRTY=$(lctl get_param -n llite.*.dump_page_cache | grep -c dirty)
	WRITEBACK=$(lctl get_param -n llite.*.dump_page_cache |
			grep -c writeback)
	if [[ $LOCKED -ne 0 ]]; then
		error "Locked pages remain in cache, locked=$LOCKED"
	fi

	if [[ $DIRTY -ne 0 || $WRITEBACK -ne 0 ]]; then
		error "Dirty pages not flushed to disk, dirty=$DIRTY, writeback=$WRITEBACK"
	fi

	rm -f $DIR/$tfile
	echo "No pages locked after fsync"

	reset_async
	return 0
}
run_test 118g "Don't stay in wait if we got local -ENOMEM  =========="

test_118h() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_ost_nodsh && skip "remote OST with nodsh"
	local osts=$(osts_nodes)

	reset_async

	#define OBD_FAIL_OST_BRW_WRITE_BULK      0x20e
        set_nodes_failloc $osts 0x20e
	# Should simulate ENOMEM error which is recoverable and should be handled by timeout
        $MULTIOP $DIR/$tfile oO_CREAT:O_RDWR:O_SYNC:w4096c
        RC=$?

        set_nodes_failloc $osts 0
	if [[ $RC -eq 0 ]]; then
		error "Must return error due to dropped pages, rc=$RC"
	fi

        LOCKED=$(lctl get_param -n llite.*.dump_page_cache | grep -c locked)
        DIRTY=$(lctl get_param -n llite.*.dump_page_cache | grep -c dirty)
        WRITEBACK=$(lctl get_param -n llite.*.dump_page_cache |
                    grep -c writeback)
	if [[ $LOCKED -ne 0 ]]; then
		error "Locked pages remain in cache, locked=$LOCKED"
	fi

	if [[ $DIRTY -ne 0 || $WRITEBACK -ne 0 ]]; then
		error "Dirty pages not flushed to disk, dirty=$DIRTY, writeback=$WRITEBACK"
	fi

	rm -f $DIR/$tfile
	echo "No pages locked after fsync"

	return 0
}
run_test 118h "Verify timeout in handling recoverables errors  =========="

[ "$SLOW" = "no" ] && [ -n "$OLD_RESENDCOUNT" ] && set_resend_count $OLD_RESENDCOUNT

test_118i() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_ost_nodsh && skip "remote OST with nodsh"
	local osts=$(osts_nodes)

	reset_async

	#define OBD_FAIL_OST_BRW_WRITE_BULK      0x20e
        set_nodes_failloc $osts 0x20e

	# Should simulate ENOMEM error which is recoverable and should be handled by timeout
        $MULTIOP $DIR/$tfile oO_CREAT:O_RDWR:O_SYNC:w4096c &
	PID=$!
	sleep 5
	set_nodes_failloc $osts 0

	wait $PID
        RC=$?
	if [[ $RC -ne 0 ]]; then
		error "got error, but should be not, rc=$RC"
	fi

        LOCKED=$(lctl get_param -n llite.*.dump_page_cache | grep -c locked)
        DIRTY=$(lctl get_param -n llite.*.dump_page_cache | grep -c dirty)
        WRITEBACK=$(lctl get_param -n llite.*.dump_page_cache | grep -c writeback)
	if [[ $LOCKED -ne 0 ]]; then
		error "Locked pages remain in cache, locked=$LOCKED"
	fi

	if [[ $DIRTY -ne 0 || $WRITEBACK -ne 0 ]]; then
		error "Dirty pages not flushed to disk, dirty=$DIRTY, writeback=$WRITEBACK"
	fi

	rm -f $DIR/$tfile
	echo "No pages locked after fsync"

	return 0
}
run_test 118i "Fix error before timeout in recoverable error  =========="

[ "$SLOW" = "no" ] && set_resend_count 4

test_118j() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_ost_nodsh && skip "remote OST with nodsh"
	local osts=$(osts_nodes)

	reset_async

	#define OBD_FAIL_OST_BRW_WRITE_BULK2     0x220
        set_nodes_failloc $osts 0x220

	# return -EIO from OST
        $MULTIOP $DIR/$tfile oO_CREAT:O_RDWR:O_SYNC:w4096c
        RC=$?
        set_nodes_failloc $osts 0x0
	if [[ $RC -eq 0 ]]; then
		error "Must return error due to dropped pages, rc=$RC"
	fi

        LOCKED=$(lctl get_param -n llite.*.dump_page_cache | grep -c locked)
        DIRTY=$(lctl get_param -n llite.*.dump_page_cache | grep -c dirty)
        WRITEBACK=$(lctl get_param -n llite.*.dump_page_cache | grep -c writeback)
	if [[ $LOCKED -ne 0 ]]; then
		error "Locked pages remain in cache, locked=$LOCKED"
	fi

	# in recoverable error on OST we want resend and stay until it finished
	if [[ $DIRTY -ne 0 || $WRITEBACK -ne 0 ]]; then
		error "Dirty pages not flushed to disk, dirty=$DIRTY, writeback=$WRITEBACK"
	fi

	rm -f $DIR/$tfile
	echo "No pages locked after fsync"

 	return 0
}
run_test 118j "Simulate unrecoverable OST side error =========="

test_118k()
{
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_ost_nodsh && skip "remote OSTs with nodsh"
	local osts=$(osts_nodes)

	#define OBD_FAIL_OST_BRW_WRITE_BULK      0x20e
	set_nodes_failloc $osts 0x20e
	test_mkdir $DIR/$tdir

	for ((i=0;i<10;i++)); do
		(dd if=/dev/zero of=$DIR/$tdir/$tfile-$i bs=1M count=10 || \
			error "dd to $DIR/$tdir/$tfile-$i failed" )&
		SLEEPPID=$!
		sleep 0.500s
		kill $SLEEPPID
		wait $SLEEPPID
	done

	set_nodes_failloc $osts 0
	rm -rf $DIR/$tdir
}
run_test 118k "bio alloc -ENOMEM and IO TERM handling ========="

test_118l() # LU-646
{
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	test_mkdir $DIR/$tdir
	$MULTIOP $DIR/$tdir Dy || error "fsync dir failed"
	rm -rf $DIR/$tdir
}
run_test 118l "fsync dir"

test_118m() # LU-3066
{
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	test_mkdir $DIR/$tdir
	$MULTIOP $DIR/$tdir DY || error "fdatasync dir failed"
	rm -rf $DIR/$tdir
}
run_test 118m "fdatasync dir ========="

[ "$SLOW" = "no" ] && [ -n "$OLD_RESENDCOUNT" ] && set_resend_count $OLD_RESENDCOUNT

test_118n()
{
	local begin
	local end

	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_ost_nodsh && skip "remote OSTs with nodsh"
	local osts=$(osts_nodes)

	# Sleep to avoid a cached response.
	#define OBD_STATFS_CACHE_SECONDS 1
	sleep 2

	# Inject a 10 second delay in the OST_STATFS handler.
	#define OBD_FAIL_OST_STATFS_DELAY 0x242
	set_nodes_failloc $osts 0x242

	begin=$SECONDS
	stat --file-system $MOUNT > /dev/null
	end=$SECONDS

	set_nodes_failloc $osts 0

	if ((end - begin > 20)); then
		error "statfs took $((end - begin)) seconds, expected 10"
	fi
}
run_test 118n "statfs() sends OST_STATFS requests in parallel"

# With unaligned_dio enabled there are no restrictions on dio.
unaligned_dio() {
	local udio=0

	$LCTL get_param osc.*.import | grep connect_flags: |
		grep -q "unaligned_dio" || udio=1

	return $udio
}

# With unaligned_dio enabled there are no restrictions on dio.
unaligned_dio_or_skip()
{
	if ! unaligned_dio; then
		skip "Need 'unaligned_dio' support"
	fi
}

dio_readv_writev_support()
{
	# Kernels after 3.16 work:
	(( $(version_code $(uname -r)) >= $(version_code 3.16) )) &&
		return 0
	# Lustre with LU-17524 works:
	(( $OST1_VERSION > $(version_code 2.15.61.196) )) &&
		return 0

	skip "need readv/writev with O_DIRECT support"
}

test_119a() # bug 11737
{
        BSIZE=$((512 * 1024))
        directio write $DIR/$tfile 0 1 $BSIZE
        # We ask to read two blocks, which is more than a file size.
        # directio will indicate an error when requested and actual
        # sizes aren't equeal (a normal situation in this case) and
        # print actual read amount.
        NOB=`directio read $DIR/$tfile 0 2 $BSIZE | awk '/error/ {print $6}'`
        if [ "$NOB" != "$BSIZE" ]; then
                error "read $NOB bytes instead of $BSIZE"
        fi
        rm -f $DIR/$tfile
}
run_test 119a "Short directIO read must return actual read amount"

test_119b() # bug 11737
{
	[[ $OSTCOUNT -lt 2 ]] && skip_env "needs >= 2 OSTs"

	$LFS setstripe -c 2 $DIR/$tfile || error "setstripe failed"
	dd if=/dev/zero of=$DIR/$tfile bs=1M count=1 seek=1 || error "dd failed"
	sync
	$MULTIOP $DIR/$tfile oO_RDONLY:O_DIRECT:r$((2048 * 1024)) ||
		error "direct read failed"
	rm -f $DIR/$tfile
}
run_test 119b "Sparse directIO read must return actual read amount"

test_119c() # bug 13099
{
        BSIZE=1048576
        directio write $DIR/$tfile 3 1 $BSIZE || error "direct write failed"
        directio readhole $DIR/$tfile 0 2 $BSIZE || error "reading hole failed"
        rm -f $DIR/$tfile
}
run_test 119c "Testing for direct read hitting hole"

# Note: test 119d was removed, skipping 119d for new tests to avoid polluting
# Maloo test history

test_119e()
{
	unaligned_dio_or_skip
	(( $OSTCOUNT >= 2 )) || skip "needs >= 2 OSTs"

	local stripe_size=$((1024 * 1024)) #1 MiB
	# Max i/o below is ~ 4 * stripe_size, so this gives ~5 i/os
	local file_size=$((25 * stripe_size))
	local bsizes

	$LFS setstripe -c 2 -S $stripe_size $DIR/$tfile.1
	stack_trap "rm -f $DIR/$tfile*"

	# Just a bit bigger than the largest size in the test set below
	dd if=/dev/urandom bs=$file_size count=1 of=$DIR/$tfile.1 ||
		error "buffered i/o to create file failed"

	# trivial test of unaligned DIO
	dd if=$DIR/$tfile.1 bs=4095 of=$DIR/$tfile.2 count=4 \
		iflag=direct oflag=direct ||
		error "trivial unaligned dio failed"

	# Test of disabling unaligned DIO support
	$LCTL set_param llite.*.unaligned_dio=0
	stack_trap "$LCTL set_param llite.*.unaligned_dio=1"
	echo "testing disabling unaligned DIO - 'invalid argument' expected:"
	dd if=$DIR/$tfile.1 bs=1024 of=$DIR/$tfile.2 count=4 \
		iflag=direct oflag=direct &&
		error "unaligned dio succeeded when disabled"
	$LCTL set_param llite.*.unaligned_dio=1

	# Clean up before next part of test
	rm -f $DIR/$tfile.2

	if zfs_or_rotational; then
		# DIO on ZFS can take up to 2 seconds per IO
		# rotational is better, but still slow.
		# Limit testing on those media to larger sizes
		if unaligned_dio; then
			bsizes="$((stripe_size - PAGE_SIZE)) $stripe_size \
				$((stripe_size + 1024))"
		else
			bsizes="$((stripe_size - PAGE_SIZE)) $stripe_size \
				$((stripe_size - 1))"
		fi
	elif unaligned_dio; then
		bsizes="$((PAGE_SIZE / 4)) $((PAGE_SIZE - 1024)) \
			$((PAGE_SIZE - 1)) $PAGE_SIZE $((PAGE_SIZE + 1024)) \
			$((PAGE_SIZE * 3/2)) $((PAGE_SIZE * 4)) \
			$((stripe_size - 1)) $stripe_size \
			$((stripe_size + 1)) $((stripe_size * 3/2)) \
			$((stripe_size * 4)) $((stripe_size * 4 + 1))"
	else
		bsizes="$((PAGE_SIZE / 4)) $((PAGE_SIZE - 1024)) \
			$((PAGE_SIZE - 1)) $PAGE_SIZE $((PAGE_SIZE + 1024)) \
			$((PAGE_SIZE * 3/2)) $((PAGE_SIZE * 4))"
	fi

	for bs in $bsizes; do
		$LFS setstripe -c 2 -S $stripe_size $DIR/$tfile.2
		echo "Read/write with DIO at size $bs"
		# Read and write with DIO from source to dest
		dd if=$DIR/$tfile.1 bs=$bs of=$DIR/$tfile.2 \
			iflag=direct oflag=direct ||
			error "dio failed"

		ls -la $DIR/$tfile.1 $DIR/$tfile.2
		$CHECKSTAT -t file -s $file_size $DIR/$tfile.2 ||
			error "size incorrect, file copy read/write bsize: $bs"
		cmp --verbose $DIR/$tfile.1 $DIR/$tfile.2 ||
			error "files differ, bsize $bs"
		rm -f $DIR/$tfile.2
	done
}
run_test 119e "Basic tests of dio read and write at various sizes"

test_119f()
{
	unaligned_dio_or_skip
	(( $OSTCOUNT >= 2 )) || skip "needs >= 2 OSTs"

	local stripe_size=$((1024 * 1024)) #1 MiB
	# Max i/o below is ~ 4 * stripe_size, so this gives ~5 i/os
	local file_size=$((25 * stripe_size))
	local bsizes

	$LFS setstripe -c 2 -S $stripe_size $DIR/$tfile.1
	stack_trap "rm -f $DIR/$tfile*"

	# Just a bit bigger than the largest size in the test set below
	dd if=/dev/urandom bs=$file_size count=1 of=$DIR/$tfile.1 ||
		error "buffered i/o to create file failed"

	if zfs_or_rotational; then
		# DIO on ZFS can take up to 2 seconds per IO
		# rotational is better, but still slow.
		# Limit testing on those media to larger sizes
		if unaligned_dio; then
			bsizes="$((stripe_size - PAGE_SIZE)) $stripe_size \
				$((stripe_size + 1024))"
		else
			bsizes="$((stripe_size - PAGE_SIZE)) $stripe_size \
				$((stripe_size - 1))"
		fi
	elif unaligned_dio; then
		bsizes="$((PAGE_SIZE / 4)) $((PAGE_SIZE - 1024)) \
			$((PAGE_SIZE - 1)) $PAGE_SIZE $((PAGE_SIZE + 1024)) \
			$((PAGE_SIZE * 3/2)) $((PAGE_SIZE * 4)) \
			$((stripe_size - 1)) $stripe_size \
			$((stripe_size + 1)) $((stripe_size * 3/2)) \
			$((stripe_size * 4)) $((stripe_size * 4 + 1))"
	else
		bsizes="$((PAGE_SIZE / 4)) $((PAGE_SIZE - 1024)) \
			$((PAGE_SIZE - 1)) $PAGE_SIZE $((PAGE_SIZE + 1024)) \
			$((PAGE_SIZE * 3/2)) $((PAGE_SIZE * 4))"
	fi

	for bs in $bsizes; do
		$LFS setstripe -c 2 -S $stripe_size $DIR/$tfile.2
		# Read and write with DIO from source to dest in two
		# threads - should give correct copy of file

		echo "bs: $bs"
		dd if=$DIR/$tfile.1 bs=$bs of=$DIR/$tfile.2 iflag=direct \
			oflag=direct conv=notrunc &
		pid_dio1=$!
		# Note block size is different here for a more interesting race
		dd if=$DIR/$tfile.1 bs=$((bs * 2)) of=$DIR/$tfile.2 \
			iflag=direct oflag=direct conv=notrunc &
		pid_dio2=$!
		wait $pid_dio1
		rc1=$?
		wait $pid_dio2
		rc2=$?
		if (( rc1 != 0 )); then
			error "dio copy 1 w/bsize $bs failed: $rc1"
		fi
		if (( rc2 != 0 )); then
			error "dio copy 2 w/bsize $bs failed: $rc2"
		fi


		$CHECKSTAT -t file -s $file_size $DIR/$tfile.2 ||
			error "size incorrect, file copy read/write bsize: $bs"
		cmp --verbose $DIR/$tfile.1 $DIR/$tfile.2 ||
			error "files differ, bsize $bs"
		rm -f $DIR/$tfile.2
	done
}
run_test 119f "dio vs dio race"

test_119g()
{
	unaligned_dio_or_skip
	(( $OSTCOUNT >= 2 )) || skip "needs >= 2 OSTs"

	local stripe_size=$((1024 * 1024)) #1 MiB
	# Max i/o below is ~ 4 * stripe_size, so this gives ~5 i/os
	local file_size=$((25 * stripe_size))
	local bsizes

	$LFS setstripe -c 2 -S $stripe_size $DIR/$tfile.1
	stack_trap "rm -f $DIR/$tfile*"

	# Just a bit bigger than the largest size in the test set below
	dd if=/dev/urandom bs=$file_size count=1 of=$DIR/$tfile.1 ||
		error "buffered i/o to create file failed"

	if zfs_or_rotational; then
		# DIO on ZFS can take up to 2 seconds per IO
		# rotational is better, but still slow.
		# Limit testing on those media to larger sizes
		if unaligned_dio; then
			bsizes="$((stripe_size - PAGE_SIZE)) $stripe_size \
				$((stripe_size + 1024))"
		else
			bsizes="$((stripe_size - PAGE_SIZE)) $stripe_size \
				$((stripe_size - 1))"
		fi
	elif unaligned_dio; then
		bsizes="$((PAGE_SIZE / 4)) $((PAGE_SIZE - 1024)) \
			$((PAGE_SIZE - 1)) $PAGE_SIZE $((PAGE_SIZE + 1024)) \
			$((PAGE_SIZE * 3/2)) $((PAGE_SIZE * 4)) \
			$((stripe_size - 1)) $stripe_size \
			$((stripe_size + 1)) $((stripe_size * 3/2)) \
			$((stripe_size * 4)) $((stripe_size * 4 + 1))"
	else
		bsizes="$((PAGE_SIZE / 4)) $((PAGE_SIZE - 1024)) \
			$((PAGE_SIZE - 1)) $PAGE_SIZE $((PAGE_SIZE + 1024)) \
			$((PAGE_SIZE * 3/2)) $((PAGE_SIZE * 4))"
	fi

	for bs in $bsizes; do
		$LFS setstripe -c 2 -S $stripe_size $DIR/$tfile.2
		echo "bs: $bs"
		dd if=$DIR/$tfile.1 bs=$bs of=$DIR/$tfile.2 iflag=direct \
			oflag=direct conv=notrunc &
		pid_dio1=$!
		# Buffered I/O with similar but not the same block size
		dd if=$DIR/$tfile.1 bs=$((bs * 2)) of=$DIR/$tfile.2 &
		pid_bio2=$!
		wait $pid_dio1
		rc1=$?
		wait $pid_bio2
		rc2=$?
		if (( rc1 != 0 )); then
			error "dio copy 1 w/bsize $bs failed: $rc1"
		fi
		if (( rc2 != 0 )); then
			error "buffered copy 2 w/bsize $bs failed: $rc2"
		fi

		$CHECKSTAT -t file -s $file_size $DIR/$tfile.2 ||
			error "size incorrect"
		cmp --verbose $DIR/$tfile.1 $DIR/$tfile.2 ||
			error "files differ, bsize $bs"
		rm -f $DIR/$tfile.2
	done
}
run_test 119g "dio vs buffered I/O race"

test_119h()
{
	unaligned_dio_or_skip
	(( $OSTCOUNT >= 2 )) || skip "needs >= 2 OSTs"

	local stripe_size=$((1024 * 1024)) #1 MiB
	# Max i/o below is ~ 4 * stripe_size, so this gives ~5 i/os
	local file_size=$((25 * stripe_size))
	local bsizes

	stack_trap "rm -f $DIR/$tfile.*"

	if zfs_or_rotational; then
		# DIO on ZFS can take up to 2 seconds per IO
		# rotational is better, but still slow.
		# Limit testing on those media to larger sizes
		if unaligned_dio; then
			bsizes="$((stripe_size - PAGE_SIZE)) $stripe_size \
				$((stripe_size + 1024))"
		else
			bsizes="$((stripe_size - PAGE_SIZE)) $stripe_size \
				$((stripe_size - 1))"
		fi
	elif unaligned_dio; then
		bsizes="$((PAGE_SIZE / 4)) $((PAGE_SIZE - 1024)) \
			$((PAGE_SIZE - 1)) $PAGE_SIZE $((PAGE_SIZE + 1024)) \
			$((PAGE_SIZE * 3/2)) $((PAGE_SIZE * 4)) \
			$((stripe_size - 1)) $stripe_size \
			$((stripe_size + 1)) $((stripe_size * 3/2)) \
			$((stripe_size * 4)) $((stripe_size * 4 + 1))"
	else
		bsizes="$((PAGE_SIZE / 4)) $((PAGE_SIZE - 1024)) \
			$((PAGE_SIZE - 1)) $PAGE_SIZE $((PAGE_SIZE + 1024)) \
			$((PAGE_SIZE * 3/2)) $((PAGE_SIZE * 4))"
	fi

	for bs in $bsizes; do
		$LFS setstripe -c 2 -S $stripe_size $DIR/$tfile.1
		$LFS setstripe -c 2 -S $stripe_size $DIR/$tfile.2
		echo "unaligned writes of blocksize: $bs"
		# Write a file with unaligned DIO and regular DIO, and compare
		# them
		# with 'u', multiop randomly unaligns the io from the buffer
		$MULTIOP $DIR/$tfile.1 \
		oO_CREAT:O_RDWR:O_DIRECT:wu${bs}wu${bs}wu${bs}wu${bs}wu${bs} ||
			error "multiop memory unaligned write failed, $bs"
		$MULTIOP $DIR/$tfile.2 \
		oO_CREAT:O_RDWR:O_DIRECT:w${bs}w${bs}w${bs}w${bs}w${bs} ||
			error "multiop memory aligned write failed, $bs"

		cmp --verbose $DIR/$tfile.1 $DIR/$tfile.2 ||
			error "files differ, bsize $bs"
		rm -f $DIR/$tfile.*
	done

	$LFS setstripe -c 2 -S $stripe_size $DIR/$tfile.1
	dd if=/dev/zero bs=$((stripe_size * 5)) of=$DIR/$tfile.1 count=5 ||
		error "dd to create source file for read failed"

	# Just a few quick tests to make sure unaligned DIO reads don't crash
	for bs in $bsizes; do

		echo "unaligned reads of blocksize: $bs"
		# with 'u', multiop randomly unaligns the io from the buffer
		$MULTIOP $DIR/$tfile.1 \
		oO_CREAT:O_RDWR:O_DIRECT:ru${bs}ru${bs}ru${bs}ru${bs}ru${bs} ||
			error "multiop memory unaligned read failed, $bs"

	done
	rm -f $DIR/$tfile*
}
run_test 119h "basic tests of memory unaligned dio"

# Unaligned AIO is disabled and may not be reenabled
# See LU-18032
# aiocp with the '-a' option makes testing memory unaligned aio trivial
test_119i()
{
	unaligned_dio_or_skip
	(( $OSTCOUNT >= 2 )) || skip "needs >= 2 OSTs"
	which aiocp || skip_env "no aiocp installed"
	skip "LU-18032: Unaligned AIO is disabled and may not be re-enabled"

	local stripe_size=$((1024 * 1024)) #1 MiB
	# Max i/o below is ~ 4 * stripe_size, so this gives ~5 i/os
	local file_size=$((25 * stripe_size))
	local bsizes

	$LFS setstripe -c 2 -S $stripe_size $DIR/$tfile.1
	stack_trap "rm -f $DIR/$tfile.*"

	# Just a bit bigger than the largest size in the test set below
	dd if=/dev/urandom bs=$file_size count=1 of=$DIR/$tfile.1 ||
		error "buffered i/o to create file failed"

	if zfs_or_rotational; then
		# DIO on ZFS can take up to 2 seconds per IO
		# rotational is better, but still slow.
		# Limit testing on those media to larger sizes
		if unaligned_dio; then
			bsizes="$((stripe_size - PAGE_SIZE)) $stripe_size \
				$((stripe_size + 1024))"
		else
			bsizes="$((stripe_size - PAGE_SIZE)) $stripe_size \
				$((stripe_size - 1))"
		fi
	elif unaligned_dio; then
		bsizes="$((PAGE_SIZE / 4)) $((PAGE_SIZE - 1024)) \
			$((PAGE_SIZE - 1)) $PAGE_SIZE $((PAGE_SIZE + 1024)) \
			$((PAGE_SIZE * 3/2)) $((PAGE_SIZE * 4)) \
			$((stripe_size - 1)) $stripe_size \
			$((stripe_size + 1)) $((stripe_size * 3/2)) \
			$((stripe_size * 4)) $((stripe_size * 4 + 1))"
	else
		bsizes="$((PAGE_SIZE / 4)) $((PAGE_SIZE - 1024)) \
			$((PAGE_SIZE - 1)) $PAGE_SIZE $((PAGE_SIZE + 1024)) \
			$((PAGE_SIZE * 3/2)) $((PAGE_SIZE * 4))"
	fi

	# Do page aligned and NOT page aligned AIO
	for align in 8 512 $((PAGE_SIZE)); do
	# Deliberately includes a few aligned sizes
	for bs in $bsizes; do
		$LFS setstripe -c 2 -S $stripe_size $DIR/$tfile.2

		echo "bs: $bs, align: $align, file_size $file_size"
		aiocp -a $align -b $bs -s $file_size -f O_DIRECT \
			$DIR/$tfile.1 $DIR/$tfile.2 ||
			error "unaligned aio failed, bs: $bs, align: $align"

		$CHECKSTAT -t file -s $file_size $DIR/$tfile.2 ||
			error "size incorrect"
		cmp --verbose $DIR/$tfile.1 $DIR/$tfile.2 ||
			error "files differ"
		rm -f $DIR/$tfile.2
	done
	done
}
run_test 119i "test unaligned aio at varying sizes"

test_119j()
{
	unaligned_dio_or_skip
	(( $LINUX_VERSION_CODE > $(version_code 4.5.0) )) ||
		skip "needs kernel > 4.5.0 for ki_flags support"

	local rpcs
	local pages=1
	local iosize=$((pages * PAGE_SIZE / 1024))k
	dd if=/dev/urandom of=$DIR/$tfile bs=$iosize count=1 ||
		error "(0) dd $iosize failed"
	sync

	# Warm the page cache and let any first-touch readahead RPC settle
	# before resetting the stats.  Otherwise an async readahead RPC from
	# the first read can race the measured read below and be miscounted
	# as a cache miss (seen as "(3) 1 != 0" on large-page clients).
	dd if=$DIR/$tfile of=/dev/null bs=$iosize count=1 ||
		error "(1) dd $iosize warmup failed"

	$LCTL set_param -n osc.*.rpc_stats=0
	# Read from page cache, does not generate an rpc
	dd if=$DIR/$tfile of=/dev/null bs=$iosize count=1 ||
		error "(2) dd $iosize failed"
	$LCTL get_param osc.*.rpc_stats
	rpcs=($($LCTL get_param -n 'osc.*.rpc_stats' |
		sed -n '/pages per rpc/,/^$/p' |
		awk '/'$pages':/ { reads += $2; writes += $6 }; \
		END { print reads,writes }'))
	(( ${rpcs[0]} == 0 )) || error "(3) ${rpcs[0]} != 0 read RPCs"

	# Test hybrid IO read
	# Force next BIO as DIO
	# This forces an RPC to the server
	#define OBD_FAIL_LLITE_FORCE_BIO_AS_DIO	0x1429
	$LCTL set_param fail_loc=0x1429
	# Drop the cache so this IO is not done by fast read.  Fast read runs
	# before the BIO->DIO switch, so unless the cached pages are gone it
	# will serve the read and no RPC is sent ("(5) 0 != 1").  vm.drop_caches
	# is best-effort and does not reliably evict pages pinned by OSC DLM
	# locks (racy on large-page clients), so cancel the locks instead to
	# deterministically invalidate this file's cached pages.
	cancel_lru_locks osc
	dd if=$DIR/$tfile of=/dev/null bs=8 count=1 || error "(4) dd failed"
	$LCTL get_param osc.*.rpc_stats
	rpcs=($($LCTL get_param -n 'osc.*.rpc_stats' |
		sed -n '/pages per rpc/,/^$/p' |
		awk '/'$pages':/ { reads += $2; writes += $6 }; \
		END { print reads,writes }'))
	(( ${rpcs[0]} == $pages )) || error "(5) ${rpcs[0]} != $pages read RPCs"

	# Test hybrid IO write
	#define OBD_FAIL_LLITE_FORCE_BIO_AS_DIO	0x1429
	$LCTL set_param fail_loc=0x1429
	#NB: We do not check for 0 write RPCs in the BIO case because that
	# would make the test racey vs cache flushing
	# but the DIO case is guaranteed to generate 1 write RPC
	cancel_lru_locks osc
	dd if=/dev/zero of=$DIR/$tfile bs=8 count=1 || error "(6) dd failed"
	$LCTL get_param osc.*.rpc_stats
	rpcs=($($LCTL get_param -n 'osc.*.rpc_stats' |
		sed -n '/pages per rpc/,/^$/p' |
		awk '/'$pages':/ { reads += $2; writes += $6 }; \
		END { print reads,writes }'))
	(( ${rpcs[1]} == $pages )) ||
		error "(7) ${rpcs[1]} != $pages write RPCs"
}
run_test 119j "basic tests of hybrid IO switching"

test_119k()
{
	(( $LINUX_VERSION_CODE > $(version_code 4.5.0) )) ||
		skip "needs kernel > 4.5.0 for ki_flags support"

	local hybrid_noswitch
	local hybrid_writes
	local hybrid_reads
	local wthresh=$($LCTL get_param -n \
			llite.*.hybrid_io_write_threshold_bytes | head -n1)
	local rthresh=$($LCTL get_param -n \
			llite.*.hybrid_io_read_threshold_bytes | head -n1)

	# Enable hybrid IO
	local hybrid=$($LCTL get_param -n llite.*.hybrid_io)
	$LCTL set_param llite.*.hybrid_io=1
	stack_trap "$LCTL set_param -n llite.*.hybrid_io=$hybrid" EXIT
	$LCTL set_param llite.*.stats=c

	# Writes below the write threshold should not switch to hybrid
	dd if=/dev/zero bs=$((wthresh / 2)) count=8 of=$DIR/$tfile ||
		error "(0) dd failed"
	hybrid_noswitch=($($LCTL get_param -n 'llite.*.stats' |
			  awk '/hybrid_noswitch/ {print $2}'))
	$LCTL get_param llite.*.stats
	[[ $hybrid_noswitch == 8 ]] ||
		error "(1) incorrect number of hybrid noswitch ($hybrid_noswitch), expected 8"
	# Writes at the write threshold should switch to hybrid/DIO
	dd if=/dev/zero bs=$wthresh count=8 of=$DIR/$tfile ||
		error "(2) dd failed"
	hybrid_writes=($($LCTL get_param -n 'llite.*.stats' |
			awk '/hybrid_writesize_switch/ {print $2}'))
	$LCTL get_param llite.*.stats
	[[ $hybrid_writes == 8 ]] ||
		error "(3) incorrect number of hybrid writes ($hybrid_writes), expected 8"

	$LCTL set_param llite.*.stats=c
	# Drop cached pages so reads go through the full IO path and
	# reach the hybrid switch check instead of being served by
	# ll_do_fast_read() from page cache.
	cancel_lru_locks osc
	# Reads below the read threshold should not switch to hybrid
	dd if=$DIR/$tfile bs=$((rthresh / 2)) count=2 of=/dev/null ||
		error "(4) dd failed"
	hybrid_noswitch=($($LCTL get_param -n 'llite.*.stats' |
			  awk '/hybrid_noswitch/ {print $2}'))
	$LCTL get_param llite.*.stats
	[[ $hybrid_noswitch == 2 ]] ||
		error "(5) incorrect number of hybrid noswitch ($hybrid_noswitch), expected 2"
	cancel_lru_locks osc
	# Reads at the read threshold should use hybrid IO
	dd if=$DIR/$tfile bs=$rthresh count=2 of=/dev/null ||
		error "(6) dd failed"
	hybrid_reads=($($LCTL get_param -n 'llite.*.stats' |
			awk '/hybrid_readsize_switch/ {print $2}'))
	$LCTL get_param llite.*.stats
	[[ $hybrid_reads == 2 ]] ||
		error "(7) incorrect number of hybrid reads ($hybrid_reads), expected 2"

	$LCTL set_param llite.*.stats=c
	# disable hybrid IO (original value restored by stack_trap above)
	$LCTL set_param llite.*.hybrid_io=0

	# Writes at the write threshold but hybrid IO is disabled
	dd if=/dev/zero bs=$wthresh count=8 of=$DIR/$tfile ||
		error "(8) dd failed"
	hybrid_writes=($($LCTL get_param -n 'llite.*.stats' |
			awk '/hybrid_writesize_switch/ {print $2}'))
	$LCTL get_param llite.*.stats
	[[ -z $hybrid_writes ]] ||
		error "(9) there should be no hybrid writes, but we have '$hybrid_writes'"

	cancel_lru_locks osc
	# Reads at the read threshold but hybrid IO is disabled
	dd if=$DIR/$tfile bs=$rthresh count=2 of=/dev/null ||
		error "(10) dd failed"
	hybrid_reads=($($LCTL get_param -n 'llite.*.stats' |
			awk '/hybrid_readsize_switch/ {print $2}'))
	$LCTL get_param llite.*.stats
	[[ -z $hybrid_reads ]] ||
		error "(11) there should be no hybrid reads, but we have '$hybrid_reads'"
}
run_test 119k "hybrid IO counting with stats and disabling"

test_119m() {
	dio_readv_writev_support

	timeout 90s rwv -f $DIR/$tfile -Dw -n 3 0x80000 0x100000 0x180000 ||
		error "DIO aligned writev test failed"
	timeout 90s rwv -f $DIR/$tfile -Dr -v -n 2 0x180000 0x100000 ||
		error "DIO aligned readv failed"
	rm -f $DIR/$tfile
}
run_test 119m "Test DIO readv/writev: exercise iter duplication"

test_119n()
{
	# zfs server should fail without unaligned_dio connect flag
	# and report EINVAL when attempting unaligned dio.
	dio_readv_writev_support

	[[ "${ost1_FSTYPE}" == "zfs" ]] ||
		skip "need ZFS server without unaligned_dio support"
	$LCTL get_param osc.*.import | grep connect_flags: |
		grep -q "unaligned_dio" &&
			skip "zfs server without 'unaligned_dio' support"

	error_string=$(rwv -f $DIR/$tfile -Dw -n2 1024 4096 2>&1) &&
		error "Allowed unaligned dio with ZFS with unpatched server"
	grep -q "Invalid argument" <<< $error_string ||
		error "Expected 'Invalid argument' failure: '$error_string'."

	rwv -f $DIR/$tfile -Dw -n2 65536 4096 ||
		error "DIO aligned writev test failed"

	error_string=$(rwv -f $DIR/$tfile -Dr -v -n2 1024 4096 2>&1) &&
		error "Allowed unaligned dio with ZFS with unpatched server"
	grep -q "Invalid argument" <<< $error_string ||
		error "Expected 'Invalid argument' failure: '$error_string'."

	rm -f $DIR/$tfile
}
run_test 119n "Test Unaligned DIO readv() and writev() with unpatched ZFS"

test_119o()
{
	dio_readv_writev_support

	[[ "${ost1_FSTYPE}" == "zfs" ]] ||
		skip "need ldiskfs without unaligned_dio support."
	$LCTL get_param osc.*.import | grep connect_flags: |
		grep -q "unaligned_dio" &&
			skip "need ldiskfs without 'unaligned_dio' support"

	error_string=$(timeout 200s \
	rwv -f $DIR/$tfile -Dw -n 3 0x7ffff 0x100001 0x180000 2>&1) &&
		error "Allowed 64k unaligned dio writev"
	grep -q -E 'Invalid argument|Write error:' <<< $error_string ||
		error "Expected 'Invalid argument' failure: '$error_string'."
	rwv -f $DIR/$tfile -Dw -n 3 0x80000 0x100000 0x180000 ||
		error "DIO aligned writev test failed"
	error_string=$(timeout 200s \
	rwv -f $DIR/$tfile -Dr -v -n 3 0x7ffff 0x100001 0x180000 2>&1) &&
		error "Allowed 64k unaligned dio readv"
	grep -q -E 'Invalid argument|Read error:' <<< $error_string ||
		error "Expected 'Invalid argument' failure: '$error_string'."

	rm -f $DIR/$tfile
}
run_test 119o "Test Unaligned DIO readv() and writev() with unpatched servers"

test_119p()
{
	# Patched servers, unaligned dio that needs interop page alignment
	dio_readv_writev_support

	$LCTL get_param osc.*.import | grep connect_flags: |
		grep -q "unaligned_dio" ||
			skip "need unaligned_dio support."
	rwv -f $DIR/$tfile -Dw -n 3 0x7ffff 0x100001 0x180000 ||
		error "DIO unaligned writev test failed"
	rwv -f $DIR/$tfile -Dr -v -n 3 0x7ffff 0x100001 0x180000 ||
		error "DIO unaligned readv failed"
	rm -f $DIR/$tfile
}
run_test 119p "Test Unaligned DIO readv() and writev() with patched servers"

test_119q()
{
	dio_readv_writev_support
	$LCTL get_param osc.*.import | grep connect_flags: |
		grep -q "unaligned_dio" ||
			skip "need unaligned_dio support."

	local page_size
	local off0
	local off1
	local off2

	#  4k:   0x1000,  8k:   0x2000,  32k:   0x8000   64k:  0x10000
	for page_size in 0x1000 0x2000 0x8000 0x10000; do
		echo "RWV interop with 64k + $page_size +/- 1"
		# short by 1 byte
		off0=$((page_size + 0xffff))
		echo "writev: $off0 0x100001 0x100000"
		timeout 90s rwv -f $DIR/$tfile -Dw -n 3 $off0 0x100001 0x100000 ||
			error "DIO unaligned writev test failed: $off0"
		echo "readv: 0x100001 $off0 0x100000"
		timeout 90s rwv -f $DIR/$tfile -Dr -v -n 3 0x100001 $off0 0x100000 ||
			error "DIO unaligned readv failed: $off0"
		rm -f $DIR/$tfile
		# page offset exactly
		off1=$((page_size + 0x10000))
		echo "writev: $off1 0x100001 0x100000"
		timeout 90s rwv -f $DIR/$tfile -Dw -n 3 $off1 0x100001 0x100000 ||
			error "DIO unaligned writev test failed: $off1"
		echo "readv: 0x100001 $off1 0x100000"
		timeout 90s rwv -f $DIR/$tfile -Dr -v -n 3 0x100001 $off1 0x100000 ||
			error "DIO unaligned readv failed: $off1"
		rm -f $DIR/$tfile
		# page offset over by 1 byte
		off2=$((page_size + 0x10001))
		echo "writev: $off2 0x100001 0x100000"
		timeout 90s rwv -f $DIR/$tfile -Dw -n 3 $off2 0x100001 0x100000 ||
			error "DIO unaligned writev test failed: $off2"
		echo "readv: 3 0x100001 $off2 0x100000"
		timeout 90s rwv -f $DIR/$tfile -Dr -v -n 3 0x100001 $off2 0x100000 ||
			error "DIO unaligned readv failed: $off2"
		rm -f $DIR/$tfile
	done
}
run_test 119q "Test patchded Unaligned DIO readv() and writev()"

test_119r() {
	unaligned_dio_or_skip

	# Test error handling in unaligned DIO user copy with racing threads
	local file=$DIR/$tfile

	$LFS setstripe -c 2 $file || error "setstripe failed"
	stack_trap "rm -f $file"

	# Create a file with some data
	dd if=/dev/urandom of=$file bs=1M count=1 || error "dd failed"

	# Set fail_loc to inject error in DIO copy
	#define OBD_FAIL_LLITE_DIO_COPY_ERR		    0x1437
	$LCTL set_param fail_loc=0x1437
	stack_trap "$LCTL set_param fail_loc=0"

	# Use rwv to do unaligned DIO write at offset 1024 with size 4096
	# This is unaligned because offset 1024 is not page-aligned
	local output
	output=$(rwv -f $file -Dw -n 1 1024 4096 2>&1) &&
		error "Unaligned DIO write should have failed but succeeded"

	echo "$output" | grep -q "Bad address" ||
		error "Expected 'Bad address' error, got: $output"

	# Clear fail_loc
	$LCTL set_param fail_loc=0

	# Verify normal aligned DIO works after error
	dd if=/dev/zero of=$file bs=4096 count=1 oflag=direct ||
		error "DIO write failed after clearing fail_loc"
}
run_test 119r "Test error handling in unaligned DIO user copy"

test_120a() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	test_mkdir -i0 -c1 $DIR/$tdir
	$LCTL get_param -n mdc.*.connect_flags | grep -q early_lock_cancel ||
		skip_env "no early lock cancel on server"

	lru_resize_disable mdc
	lru_resize_disable osc
	cancel_lru_locks mdc
	# asynchronous object destroy at MDT could cause bl ast to client
	cancel_lru_locks osc

	local old=$($LCTL get_param -n llite.*.dir_read_on_open)

	# statahead_agl may cause extra glimpse which confuses results. LU-13017
	$LCTL set_param -n llite.*.dir_read_on_open=0
	stack_trap "$LCTL set_param -n llite.*.dir_read_on_open=$old" EXIT

	stat $DIR/$tdir > /dev/null
	can1=$(do_facet mds1 \
	       "$LCTL get_param -n ldlm.services.ldlm_canceld.stats" |
	       awk '/ldlm_cancel/ {print $2}')
	blk1=$($LCTL get_param -n ldlm.services.ldlm_cbd.stats |
	       awk '/ldlm_bl_callback/ {print $2}')
	test_mkdir -i0 -c1 $DIR/$tdir/d1
	can2=$(do_facet mds1 \
	       "$LCTL get_param -n ldlm.services.ldlm_canceld.stats" |
	       awk '/ldlm_cancel/ {print $2}')
	blk2=$($LCTL get_param -n ldlm.services.ldlm_cbd.stats |
	       awk '/ldlm_bl_callback/ {print $2}')
	(( $can1 == $can2 )) || error "$((can2-can1)) cancel RPC occured."
	(( $blk1 == $blk2 )) || error "$((blk2-blk1)) blocking RPC occured."
}
run_test 120a "Early Lock Cancel: mkdir test"

test_120b() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	test_mkdir $DIR/$tdir
	$LCTL get_param -n mdc.*.connect_flags | grep -q early_lock_cancel ||
		skip_env "no early lock cancel on server"

	lru_resize_disable mdc
	lru_resize_disable osc
	cancel_lru_locks mdc
	stat $DIR/$tdir > /dev/null
	can1=$(do_facet $SINGLEMDS \
	       "$LCTL get_param -n ldlm.services.ldlm_canceld.stats" |
	       awk '/ldlm_cancel/ {print $2}')
	blk1=$($LCTL get_param -n ldlm.services.ldlm_cbd.stats |
	       awk '/ldlm_bl_callback/ {print $2}')
	touch $DIR/$tdir/f1
	can2=$(do_facet $SINGLEMDS \
	       "$LCTL get_param -n ldlm.services.ldlm_canceld.stats" |
	       awk '/ldlm_cancel/ {print $2}')
	blk2=$($LCTL get_param -n ldlm.services.ldlm_cbd.stats |
	       awk '/ldlm_bl_callback/ {print $2}')
	(( $can1 == $can2 )) || error "$((can2-can1)) cancel RPC occured."
	(( $blk1 == $blk2 )) || error "$((blk2-blk1)) blocking RPC occured."
}
run_test 120b "Early Lock Cancel: create test"

test_120c() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	test_mkdir -i0 -c1 $DIR/$tdir
	$LCTL get_param -n mdc.*.connect_flags | grep -q early_lock_cancel ||
		skip "no early lock cancel on server"

	lru_resize_disable mdc
	lru_resize_disable osc
	test_mkdir -i0 -c1 $DIR/$tdir/d1
	test_mkdir -i0 -c1 $DIR/$tdir/d2
	touch $DIR/$tdir/d1/f1
	cancel_lru_locks mdc
	stat $DIR/$tdir/d1 $DIR/$tdir/d2 $DIR/$tdir/d1/f1 > /dev/null
	can1=$(do_facet mds1 \
	       "$LCTL get_param -n ldlm.services.ldlm_canceld.stats" |
	       awk '/ldlm_cancel/ {print $2}')
	blk1=$($LCTL get_param -n ldlm.services.ldlm_cbd.stats |
	       awk '/ldlm_bl_callback/ {print $2}')
	ln $DIR/$tdir/d1/f1 $DIR/$tdir/d2/f2
	can2=$(do_facet mds1 \
	       "$LCTL get_param -n ldlm.services.ldlm_canceld.stats" |
	       awk '/ldlm_cancel/ {print $2}')
	blk2=$($LCTL get_param -n ldlm.services.ldlm_cbd.stats |
	       awk '/ldlm_bl_callback/ {print $2}')
	(( $can1 == $can2 )) || error "$((can2-can1)) cancel RPC occured."
	(( $blk1 == $blk2 )) || error "$((blk2-blk1)) blocking RPC occured."
}
run_test 120c "Early Lock Cancel: link test"

test_120d() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	test_mkdir -i0 -c1 $DIR/$tdir
	$LCTL get_param -n mdc.*.connect_flags | grep -q early_lock_cancel ||
		skip_env "no early lock cancel on server"

	lru_resize_disable mdc
	lru_resize_disable osc
	touch $DIR/$tdir
	cancel_lru_locks mdc
	stat $DIR/$tdir > /dev/null
	can1=$(do_facet mds1 \
	       "$LCTL get_param -n ldlm.services.ldlm_canceld.stats" |
	       awk '/ldlm_cancel/ {print $2}')
	blk1=$($LCTL get_param -n ldlm.services.ldlm_cbd.stats |
	       awk '/ldlm_bl_callback/ {print $2}')
	chmod a+x $DIR/$tdir
	can2=$(do_facet mds1 \
	       "$LCTL get_param -n ldlm.services.ldlm_canceld.stats" |
	       awk '/ldlm_cancel/ {print $2}')
	blk2=$($LCTL get_param -n ldlm.services.ldlm_cbd.stats |
	       awk '/ldlm_bl_callback/ {print $2}')
	(( $can1 == $can2 )) || error "$((can2-can1)) cancel RPC occured."
	(( $blk1 == $blk2 )) || error "$((blk2-blk1)) blocking RPC occured."
}
run_test 120d "Early Lock Cancel: setattr test"

test_120e() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	$LCTL get_param -n mdc.*.connect_flags | grep -q early_lock_cancel ||
		skip_env "no early lock cancel on server"
	remote_mds_nodsh && skip "remote MDS with nodsh"

	local dlmtrace_set=false

	test_mkdir -i0 -c1 $DIR/$tdir
	lru_resize_disable mdc
	lru_resize_disable osc
	! $LCTL get_param debug | grep -q dlmtrace &&
		$LCTL set_param debug=+dlmtrace &&
		stack_trap "$LCTL set_param debug=-dlmtrace"
	dd if=/dev/zero of=$DIR/$tdir/f1 count=1
	cancel_lru_locks mdc
	cancel_lru_locks osc
	dd if=$DIR/$tdir/f1 of=/dev/null
	stat $DIR/$tdir $DIR/$tdir/f1 > /dev/null
	# XXX client can not do early lock cancel of OST lock
	# during unlink (LU-4206), so cancel osc lock now.
	sleep 2
	cancel_lru_locks osc
	can1=$(do_facet mds1 \
	       "$LCTL get_param -n ldlm.services.ldlm_canceld.stats" |
	       awk '/ldlm_cancel/ {print $2}')
	blk1=$($LCTL get_param -n ldlm.services.ldlm_cbd.stats |
	       awk '/ldlm_bl_callback/ {print $2}')
	unlink $DIR/$tdir/f1
	sleep 5
	can2=$(do_facet mds1 \
	       "$LCTL get_param -n ldlm.services.ldlm_canceld.stats" |
	       awk '/ldlm_cancel/ {print $2}')
	blk2=$($LCTL get_param -n ldlm.services.ldlm_cbd.stats |
	       awk '/ldlm_bl_callback/ {print $2}')
	(( $can1 == $can2 )) || error "$((can2 - can1)) cancel RPC occured"
	(( $blk1 == $blk2 )) || error "$((blk2 - blk1)) blocking RPC occured"
}
run_test 120e "Early Lock Cancel: unlink test"

test_120f() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	$LCTL get_param -n mdc.*.connect_flags | grep -q early_lock_cancel ||
		skip_env "no early lock cancel on server"
	remote_mds_nodsh && skip "remote MDS with nodsh"

	test_mkdir -i0 -c1 $DIR/$tdir
	lru_resize_disable mdc
	lru_resize_disable osc
	test_mkdir -i0 -c1 $DIR/$tdir/d1
	test_mkdir -i0 -c1 $DIR/$tdir/d2
	dd if=/dev/zero of=$DIR/$tdir/d1/f1 count=1
	dd if=/dev/zero of=$DIR/$tdir/d2/f2 count=1
	cancel_lru_locks mdc
	cancel_lru_locks osc
	dd if=$DIR/$tdir/d1/f1 of=/dev/null
	dd if=$DIR/$tdir/d2/f2 of=/dev/null
	stat $DIR/$tdir/d1 $DIR/$tdir/d2 $DIR/$tdir/d1/f1 $DIR/$tdir/d2/f2 > /dev/null
	# XXX client can not do early lock cancel of OST lock
	# during rename (LU-4206), so cancel osc lock now.
	sleep 2
	cancel_lru_locks osc
	can1=$(do_facet mds1 \
	       "$LCTL get_param -n ldlm.services.ldlm_canceld.stats" |
	       awk '/ldlm_cancel/ {print $2}')
	blk1=$($LCTL get_param -n ldlm.services.ldlm_cbd.stats |
	       awk '/ldlm_bl_callback/ {print $2}')
	mrename $DIR/$tdir/d1/f1 $DIR/$tdir/d2/f2
	sleep 5
	can2=$(do_facet mds1 \
	       "$LCTL get_param -n ldlm.services.ldlm_canceld.stats" |
	       awk '/ldlm_cancel/ {print $2}')
	blk2=$($LCTL get_param -n ldlm.services.ldlm_cbd.stats |
	       awk '/ldlm_bl_callback/ {print $2}')
	(( $can1 == $can2 )) || error "$((can2-can1)) cancel RPC occured."
	(( $blk1 == $blk2 )) || error "$((blk2-blk1)) blocking RPC occured."
}
run_test 120f "Early Lock Cancel: rename test"

test_120g() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	$LCTL get_param -n mdc.*.connect_flags | grep -q early_lock_cancel ||
		skip_env "no early lock cancel on server"
	remote_mds_nodsh && skip "remote MDS with nodsh"

	lru_resize_disable mdc
	lru_resize_disable osc
	count=10000
	echo create $count files
	test_mkdir $DIR/$tdir
	cancel_lru_locks mdc
	cancel_lru_locks osc
	t0=$(date +%s)

	can0=$(do_facet $SINGLEMDS \
	       "$LCTL get_param -n ldlm.services.ldlm_canceld.stats" |
	       awk '/ldlm_cancel/ {print $2}')
	blk0=$($LCTL get_param -n ldlm.services.ldlm_cbd.stats |
	       awk '/ldlm_bl_callback/ {print $2}')
	createmany -o $DIR/$tdir/f $count
	sync
	can1=$(do_facet $SINGLEMDS \
	       "$LCTL get_param -n ldlm.services.ldlm_canceld.stats" |
	       awk '/ldlm_cancel/ {print $2}')
	blk1=$($LCTL get_param -n ldlm.services.ldlm_cbd.stats |
	       awk '/ldlm_bl_callback/ {print $2}')
	t1=$(date +%s)
	echo "total: $((can1-can0)) cancels, $((blk1-blk0)) blockings"
	echo "rm $count files"
	rm -r $DIR/$tdir
	sync
	can2=$(do_facet $SINGLEMDS \
	       "$LCTL get_param -n ldlm.services.ldlm_canceld.stats" |
	       awk '/ldlm_cancel/ {print $2}')
	blk2=$($LCTL get_param -n ldlm.services.ldlm_cbd.stats |
	       awk '/ldlm_bl_callback/ {print $2}')
	t2=$(date +%s)
	echo "total: $count removes in $((t2-t1))"
	echo "total: $((can2-can1)) cancels, $((blk2-blk1)) blockings"
	wait_delete_completed
}
run_test 120g "Early Lock Cancel: performance test"

test_121() { #bug #10589
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	rm -rf $DIR/$tfile
	writes=$(LANG=C dd if=/dev/zero of=$DIR/$tfile count=1 2>&1 | awk -F '+' '/out$/ {print $1}')
#define OBD_FAIL_LDLM_CANCEL_RACE        0x310
	lctl set_param fail_loc=0x310
	cancel_lru_locks osc > /dev/null
	reads=$(LANG=C dd if=$DIR/$tfile of=/dev/null 2>&1 | awk -F '+' '/in$/ {print $1}')
	lctl set_param fail_loc=0
	[[ $reads -eq $writes ]] ||
		error "read $reads blocks, must be $writes blocks"
}
run_test 121 "read cancel race ========="

test_123a_base() { # was test 123, statahead(b=11401)
	local lsx="$1"

	ost_set_temp_seq_width_all $DATA_SEQ_MAX_WIDTH

	local slow_is=error
	if ! grep -q "processor.*: 1" /proc/cpuinfo; then
		log "testing UP system. Performance may be lower than expected."
		slow_is=log
	fi
	running_in_vm && slow_is=log

	lru_resize_enable
	$LCTL set_param mdc.*.batch_stats=0

	rm -rf $DIR/$tdir
	test_mkdir $DIR/$tdir
	local numfree=$(df -i -P $DIR | tail -n 1 | awk '{ print $4 }')
	(( $numfree > 100000 )) && numfree=100000 || numfree=$((numfree-1000))
	stack_trap "unlinkmany $DIR/$tdir/$tfile $numfree 2> /dev/null || true"
	local mult=10
	for ((i=100, j=0; i<=$numfree; j=$i, i=$((i * mult)) )); do
		local stime=$SECONDS
		createmany -o $DIR/$tdir/$tfile $j $((i - j))
		local etime=$SECONDS
		local delta_cr=$((etime - stime))

		local max=($($LCTL get_param -n llite.*.statahead_max))
		$LCTL set_param llite.*.statahead_max=0
		cancel_lru_locks mdc
		cancel_lru_locks osc
		local stime=$SECONDS
		time $lsx $DIR/$tdir | wc -l
		local etime=$SECONDS
		local delta=$((etime - stime))
		log "'$lsx' $i files without statahead: $delta sec"
		$LCTL set_param llite.*.statahead_max=$max

		local swrong=$($LCTL get_param -n llite.*.statahead_stats |
			       awk '/statahead.wrong:/ { print $NF }')
		$LCTL get_param llite.*.statahead_max
		cancel_lru_locks mdc
		cancel_lru_locks osc
		stime=$SECONDS
		time $lsx $DIR/$tdir | wc -l
		etime=$SECONDS
		local delta_sa=$((etime - stime))
		log "'$lsx' $i files with statahead: $delta_sa sec"
		$LCTL get_param -n llite.*.statahead_stats
		local ewrong=$($LCTL get_param -n llite.*.statahead_stats |
			       awk '/statahead.wrong:/ { print $NF }')

		echo "swrong=$swrong ewrong=$ewrong"
		(( $swrong >= $ewrong )) ||
			log "statahead was stopped, maybe too many locks held!"
		(( $delta_cr <= 90 )) || [[ "$SLOW" == "yes" ]] || break
		(( $delta != 0 && $delta_sa != 0 )) || continue

		if (( $delta_sa*100 > $delta*105 && $delta_sa > $delta+2)); then
			max=($($LCTL get_param -n llite.*.statahead_max))
			$LCTL set_param llite.*.statahead_max=0
			cancel_lru_locks mdc
			cancel_lru_locks osc
			stime=$SECONDS
			time $lsx $DIR/$tdir | wc -l
			etime=$SECONDS
			delta=$((etime - stime))
			log "'$lsx' $i files again w/o statahead: $delta sec"
			$LCTL set_param llite.*.statahead_max=$max
			if (( $delta_sa * 100 > $delta * 105 &&
			      $delta_sa > $delta + 2 )); then
				$slow_is "'$lsx' $i files slower with statahead"
				break
			fi
		fi

		(( $delta <= 20 )) || break
		(( $delta <= 8 )) || mult=$((50 / delta))
		[[ "$SLOW" == "yes" ]] || (( $delta <= 5 )) || break
	done
	log "'$lsx' done"

	stime=$SECONDS
	find $DIR/$tdir -type f -print0 | xargs -0 -P 4 -r -n 1 unlink ||
		error "failed to unlink $DIR/$tdir $i"
	rm -r $DIR/$tdir
	sync
	etime=$SECONDS
	delta=$((etime - stime))
	log "unlink + rm -r $DIR/$tdir: $delta seconds"
	$LCTL get_param llite.*.statahead_stats
	$LCTL get_param mdc.*.batch_stats
}

test_123aa() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	test_123a_base "ls -l"
}
run_test 123aa "verify statahead work"

test_123ab() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	statx_supported || skip_env "Test must be statx() syscall supported"

	test_123a_base "$STATX -l"
}
run_test 123ab "verify statahead work by using statx"

test_123ac() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	statx_supported || skip_env "Test must be statx() syscall supported"

	local rpcs_before
	local rpcs_after
	local agl_before
	local agl_after

	cancel_lru_locks $OSC
	rpcs_before=$(calc_stats $OSC.*$OSC*.stats ldlm_glimpse_enqueue)
	agl_before=$($LCTL get_param -n llite.*.statahead_stats |
		     awk '/agl.total:/ { print $NF }')
	test_123a_base "$STATX -c \"%n %i %A %h %u %g %W %X %Z\" -D"
	test_123a_base "$STATX --cached=always -D"
	agl_after=$($LCTL get_param -n llite.*.statahead_stats |
		    awk '/agl.total:/ { print $NF }')
	(( $agl_before == $agl_after )) ||
		error "Should not trigger AGL thread - $agl_before:$agl_after"
	rpcs_after=$(calc_stats $OSC.*$OSC*.stats ldlm_glimpse_enqueue)
	(( $rpcs_after == $rpcs_before )) ||
		error "$STATX should not send glimpse RPCs to $OSC"
}
run_test 123ac "verify statahead work by using statx without glimpse RPCs"

test_batch_statahead() {
	local max=$1
	local batch_max=$2
	local num=10000
	local batch_rpcs
	local unbatch_rpcs
	local hit_total

	echo -e "\n\n\nbatch: statahead_max=$max statahead_batch_max=$batch_max"
	$LCTL set_param mdc.*.batch_stats=0
	$LCTL set_param llite.*.statahead_max=$max
	$LCTL set_param llite.*.statahead_batch_max=$batch_max
	# Verify that batched statahead is faster than one without statahead
	test_123a_base "ls -l"

	stack_trap "rm -rf $DIR/$tdir" EXIT
	mkdir $DIR/$tdir || error "failed to mkdir $DIR/$tdir"
	createmany -o $DIR/$tdir/$tfile $num || error "failed to create files"

	# unbatched statahead
	$LCTL set_param llite.*.statahead_batch_max=0
	$LCTL set_param llite.*.statahead_stats=clear
	$LCTL set_param mdc.*.stats=clear
	cancel_lru_locks mdc
	cancel_lru_locks osc
	echo -n "ls -l files in $tdir: "
	time ls -l $DIR/$tdir | wc -l
	unbatch_rpcs=$(calc_stats mdc.*.stats ldlm_ibits_enqueue)
	wait_update_facet client "pgrep ll_sa" "" 35 ||
		error "ll_sa thread is still running"
	hit_total=$($LCTL get_param -n llite.*.statahead_stats |
		    awk '/hit.total:/ { print $NF }')
	# hit ratio should be larger than 75% (7500).
	echo "unbatched statahead RPC=$unbatch_rpcs hit count=$hit_total"
	(( $hit_total > 7500 )) || {
		$LCTL get_param llite.*.statahead_stats
		error "unbatched statahead RPC=$unbatch_rpcs hit count=$hit_total too low"
	}

	# batched statahead
	$LCTL set_param llite.*.statahead_batch_max=$batch_max
	$LCTL set_param llite.*.statahead_stats=clear
	$LCTL set_param mdc.*.batch_stats=clear
	$LCTL set_param mdc.*.stats=clear
	cancel_lru_locks mdc
	cancel_lru_locks osc
	echo -n "ls -l files in $tdir: "
	time ls -l $DIR/$tdir | wc -l
	batch_rpcs=$(calc_stats mdc.*.stats mds_batch)
	# wait for statahead thread to quit and update statahead stats
	wait_update_facet client "pgrep ll_sa" "" 35 ||
		error "ll_sa thread is still running"
	hit_total=$($LCTL get_param -n llite.*.statahead_stats |
		    awk '/hit.total:/ { print $NF }')
	# hit ratio should be larger than 75% (7500).
	echo "batched statahead RPC=$batch_rpc hit count=$hit_total"
	(( $hit_total > 7500 )) || {
		$LCTL get_param llite.*.statahead_stats
		error "batched statahead RPC=$batch_rpc hit count=$hit_total too low"
	}

	(( $unbatch_rpcs > $batch_rpcs )) ||
		error "batched statahead does not reduce RPCs ($unbatch_rpcs < $batch_rpcs)"
	$LCTL get_param mdc.*.batch_stats
}

test_123ad() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	(( $MDS1_VERSION >= $(version_code 2.15.53) )) ||
		skip "Need server version at least 2.15.53"

	$LCTL get_param -n mdc.*.connect_flags | grep -q batch_rpc ||
		skip "Server does not support batch RPC"

	local max
	local batch_max

	max=$($LCTL get_param -n llite.*.statahead_max | head -n 1)
	batch_max=$($LCTL get_param -n llite.*.statahead_batch_max | head -n 1)

	stack_trap "$LCTL set_param llite.*.statahead_max=$max" EXIT
	stack_trap "$LCTL set_param llite.*.statahead_batch_max=$batch_max" EXIT

	test_batch_statahead 32 32
	test_batch_statahead 2048 256
}
run_test 123ad "Verify batching statahead works correctly"

test_123b () { # statahead(bug 15027)
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	test_mkdir $DIR/$tdir
	createmany -o $DIR/$tdir/$tfile-%d 1000

        cancel_lru_locks mdc
        cancel_lru_locks osc

#define OBD_FAIL_MDC_GETATTR_ENQUEUE     0x803
        lctl set_param fail_loc=0x80000803
        ls -lR $DIR/$tdir > /dev/null
        log "ls done"
        lctl set_param fail_loc=0x0
        lctl get_param -n llite.*.statahead_stats
        rm -r $DIR/$tdir
        sync

}
run_test 123b "not panic with network error in statahead enqueue (bug 15027)"

test_123c() {
	[[ $MDSCOUNT -lt 2 ]] && skip_env "needs >= 2 MDTs"

	test_mkdir -i 0 -c 1 $DIR/$tdir.0
	test_mkdir -i 1 -c 1 $DIR/$tdir.1
	touch $DIR/$tdir.1/{1..3}
	mv $DIR/$tdir.1/{1..3} $DIR/$tdir.0

	remount_client $MOUNT

	$MULTIOP $DIR/$tdir.0 Q

	# let statahead to complete
	ls -l $DIR/$tdir.0 > /dev/null

	testid=$(echo $TESTNAME | tr '_' ' ')
	dmesg | tac | sed "/$testid/,$ d" | grep "Can not initialize inode" &&
		error "statahead warning" || true
}
run_test 123c "Can not initialize inode warning on DNE statahead"

test_123d() {
	local num=100
	local swrong
	local ewrong

	test_mkdir -c -1 $DIR/$tdir || error "test_mkdir $DIR/$tdir failed"
	$LFS setdirstripe -D -c $MDSCOUNT $DIR/$tdir ||
		error "setdirstripe $DIR/$tdir failed"
	createmany -d $DIR/$tdir/$tfile $num || error "createmany $num failed"
	stack_trap "unlinkmany -d $DIR/$tdir/$tfile $num"
	remount_client $MOUNT
	$LCTL get_param llite.*.statahead_max
	$LCTL set_param llite.*.statahead_stats=0 ||
		error "clear statahead_stats failed"
	swrong=$(lctl get_param -n llite.*.statahead_stats |
		 awk '/statahead.wrong:/ { print $NF }')
	ls -l $DIR/$tdir || error "ls -l $DIR/$tdir failed"
	# wait for statahead thread finished to update hit/miss stats.
	sleep 1
	$LCTL get_param -n llite.*.statahead_stats
	ewrong=$(lctl get_param -n llite.*.statahead_stats |
		 awk '/statahead.wrong:/ { print $NF }')
	(( $swrong == $ewrong )) ||
		log "statahead was stopped, maybe too many locks held!"
}
run_test 123d "Statahead on striped directories works correctly"

test_123e() {
	local max
	local batch_max
	local dir=$DIR/$tdir

	$LCTL get_param -n mdc.*.connect_flags | grep -q batch_rpc ||
		skip "Server does not support batch RPC"

	mkdir $dir || error "mkdir $dir failed"
	$LFS setstripe -C 32 $dir || error "setstripe $dir failed"
	stack_trap "rm -rf $dir"

	touch $dir/$tfile.{0..1000} || error "touch 1000 files failed"

	max=$($LCTL get_param -n llite.*.statahead_max | head -n 1)
	batch_max=$($LCTL get_param -n llite.*.statahead_batch_max | head -n 1)
	stack_trap "$LCTL set_param llite.*.statahead_max=$max" EXIT
	stack_trap "$LCTL set_param llite.*.statahead_batch_max=$batch_max" EXIT

	$LCTL set_param llite.*.statahead_max=2048
	$LCTL set_param llite.*.statahead_batch_max=1024

	ls -l $dir
	$LCTL get_param mdc.*.batch_stats
	$LCTL get_param llite.*.statahead_*
}
run_test 123e "statahead with large wide striping"

test_123f() {
	local max
	local batch_max
	local dir=$DIR/$tdir

	$LCTL get_param -n mdc.*.connect_flags | grep -q batch_rpc ||
		skip "Server does not support batch RPC"

	mkdir $dir || error "mkdir $dir failed"
	$LFS setstripe -C 1000 $dir || error "setstripe $dir failed"
	stack_trap "rm -rf $dir"

	touch $dir/$tfile.{0..200} || error "touch 200 files failed"

	max=$($LCTL get_param -n llite.*.statahead_max | head -n 1)
	batch_max=$($LCTL get_param -n llite.*.statahead_batch_max | head -n 1)

	$LCTL set_param llite.*.statahead_max=64
	$LCTL set_param llite.*.statahead_batch_max=64

	ls -l $dir
	lctl get_param mdc.*.batch_stats
	lctl get_param llite.*.statahead_*

	$LCTL set_param llite.*.statahead_max=$max
	$LCTL set_param llite.*.statahead_batch_max=$batch_max
}
run_test 123f "Retry mechanism with large wide striping files"

test_123g() {
	local dir=$DIR/$tdir
	local num=1000

	$LCTL get_param -n mdc.*.connect_flags | grep -q batch_rpc ||
		skip "Server does not support batch RPC"

	mkdir $dir || error "failed to mkdir $dir"
	createmany -o $dir/$tfile $num || error "failed creatmany files"
	cancel_lru_locks mdc
	cancel_lru_locks osc

	$LCTL set_param llite.*.statahead_stats=clear
	$LCTL set_param mdc.*.batch_stats=clear
	aheadmany -c stat -s 0 -e $num -b $tfile -d $dir ||
		error "aheadmany $dir with $tfile failed"
	wait_update_facet client "pgrep ll_sa" "" 35 ||
		error "ll_sa thread is still running"
	$LCTL get_param -n llite.*.statahead_stats
	$LCTL get_param -n mdc.*.batch_stats

	local count

	count=$($LCTL get_param -n llite.*.statahead_stats |
		awk '/hit.total:/ {print $2}')
	echo "Hit total: $count"
	# Hit ratio should be >= 75%
	(( $count > num * 75 / 100 )) ||
		error "hit total $count is be > 75% of $num"
}
run_test 123g "Test for stat-ahead advise"

test_123h_base() {
	local dir=$DIR/$tdir
	local cmd="touch $dir/$tfile.{$1}"
	local fcnt=$2

	stack_trap "rm -rf $dir"
	mkdir -p $dir || error "failed to mkdir $dir"
	eval $cmd

	cancel_lru_locks mdc
	$LCTL set_param llite.*.statahead_stats=clear
	$LCTL set_param mdc.*.batch_stats=0
	$LCTL set_param llite.*.statahead_max=1024
	$LCTL set_param llite.*.statahead_batch_max=1024
	lctl get_param -n llite.*.statahead_stats
	du -a $dir > /dev/null
	echo "Wait statahead thread (ll_sa_xxx) to exit..."
	wait_update_facet client "pgrep ll_sa" "" 35 ||
		error "ll_sa statahead thread does not quit in 35s"
	$LCTL get_param -n llite.*.statahead_stats
	$LCTL get_param -n mdc.*.batch_stats

	local count=$($LCTL get_param -n llite.*.statahead_stats |
			awk '/fname.total:/ {print $2}')

	[ $count == 1 ] || error "File name pattern statahead not trigger"
	count=$($LCTL get_param -n llite.*.statahead_stats |
		awk '/hit.total:/ {print $2}')
	# Hit ratio should be >= 75%
	(( $count > fcnt * 75 / 100 )) ||
		error "hit total is too low: $count"
	rm -rf $dir || error "rm -rf $dir failed"
}

test_123h() {
	local max
	local batch_max
	local enabled

	$LCTL get_param -n mdc.*.connect_flags | grep -q batch_rpc ||
		skip "Server does not support batch RPC"

	max=$($LCTL get_param -n llite.*.statahead_max | head -n 1)
	batch_max=$($LCTL get_param -n llite.*.statahead_batch_max | head -n 1)
	enabled=$($LCTL get_param -n llite.*.enable_statahead_fname | head -n 1)
	stack_trap "$LCTL set_param llite.*.statahead_max=$max"
	stack_trap "$LCTL set_param llite.*.statahead_batch_max=$batch_max"
	stack_trap "$LCTL set_param llite.*.enable_statahead_fname=$enabled"

	$LCTL set_param llite.*.enable_statahead_fname=1

	echo "Scan a directory with number regularized fname"
	test_123h_base "0..10000" 10000

	echo "Scan a directory with zeroed padding number regularized fname"
	test_123h_base "000000..010000" 10000
}
run_test 123h "Verify statahead work with the fname pattern via du"

test_123i_base() {
	local fmt=$1
	local iocmd=$2
	local dir=$DIR/$tdir
	local cmd="createmany -m $fmt"

	echo "Command:"
	echo "- $cmd"
	echo "- $iocmd"
	stack_trap "unlinkmany $fmt"
	mkdir -p $dir || error "failed to mkdir $dir"
	eval $cmd

	cancel_lru_locks mdc
	$LCTL set_param llite.*.statahead_stats=clear
	$LCTL set_param mdc.*.batch_stats=0

	echo "statahead_stats (Pre):"
	$LCTL get_param -n llite.*.statahead_stats
	eval $iocmd || error "$iocmd failed"
	echo "statahead_stats (Post):"
	$LCTL get_param -n llite.*.statahead_stats
	$LCTL get_param -n mdc.*.batch_stats

	echo "Wait the statahead thread (ll_sa_xxx) to exit ..."
	wait_update_facet client "pgrep ll_sa" "" 35 ||
		error "ll_sa statahead thread does not quit in 35s"
	$LCTL get_param -n llite.*.statahead_stats
	$LCTL get_param -n mdc.*.batch_stats

	local count=$($LCTL get_param -n llite.*.statahead_stats |
			awk '/fname.total:/ {print $2}')

	[ $count == 1 ] || error "File name pattern statahead not trigger"
	count=$($LCTL get_param -n llite.*.statahead_stats |
		awk '/hit.total:/ {print $2}')
	# Hit ratio should be >= 75%
	(( $count > 750 )) || error "hit total is too low: $count"
}

test_123i() {
	local dir=$DIR/$tdir
	local cnt=1000
	local max
	local batch_max
	local enabled
	local min

	$LCTL get_param -n mdc.*.connect_flags | grep -q batch_rpc ||
		skip "Server does not support batch RPC"

	max=$($LCTL get_param -n llite.*.statahead_max | head -n 1)
	batch_max=$($LCTL get_param -n llite.*.statahead_batch_max | head -n 1)
	min=$($LCTL get_param -n llite.*.statahead_min | head -n 1)
	enabled=$($LCTL get_param -n llite.*.enable_statahead_fname | head -n 1)
	stack_trap "$LCTL set_param llite.*.statahead_max=$max"
	stack_trap "$LCTL set_param llite.*.statahead_batch_max=$batch_max"
	stack_trap "$LCTL set_param llite.*.statahead_min=$min"
	stack_trap "$LCTL set_param llite.*.enable_statahead_fname=$enabled"
	$LCTL set_param llite.*.statahead_max=1024
	$LCTL set_param llite.*.statahead_batch_max=32
	$LCTL set_param llite.*.statahead_min=64
	$LCTL set_param llite.*.enable_statahead_fname=1

	test_123i_base "$dir/$tfile.%06d $cnt" "ls $dir/* > /dev/null"
	test_123i_base "$dir/$tfile $cnt" \
		"aheadmany -c stat -N -s 0 -e $cnt -b $tfile -d $dir"
}
run_test 123i "Verify statahead work with the fname indexing pattern"

test_123j() {
	(( $MDSCOUNT > 1 )) || skip_env "needs >= 2 MDTs"

	$LCTL get_param -n mdc.*.connect_flags | grep -q batch_rpc ||
		skip "Server does not support batch RPC"

	local enabled

	enabled=$($LCTL get_param -n llite.*.enable_statahead_fname | head -n 1)
	stack_trap "$LCTL set_param llite.*.enable_statahead_fname=$enabled"
	$LCTL set_param llite.*.enable_statahead_fname=1

	stack_trap "rm -rf $DIR/${tdir}.{1..11}"

	mkdir $DIR/${tdir}.{1..10} ||
		error "failed to mkdir $DIR/${tdir}.{1..10}"
	cancel_lru_locks mdc

	for i in $(seq 1 10); do
		stat $DIR/${tdir}.$i || error "failed to stat $DIR/${tdir}.$i"
	done

	stat $DIR/${tdir}.11
	$LFS mkdir -i $((MDSCOUNT - 1)) -c 2 -H all_char $DIR/${tdir}.11 ||
		error "failed to mkdir $DIR/${tdir}.11"
	touch $DIR/${tdir}.11/$tfile ||
		error "failed to create file $DIR/${tdir}.11/$tfile"
}
run_test 123j "-ENOENT error from batched statahead be handled correctly"

test_123k() {
	MDTEST=${MDTEST:=$(which mdtest 2> /dev/null || true)}
	[[ -n "$MDTEST" ]] || skip_env "mdtest not found"

	$LCTL get_param -n mdc.*.connect_flags | grep -q batch_rpc ||
		skip "Server does not support batch RPC"

	local enabled

	enabled=$($LCTL get_param -n llite.*.enable_statahead_fname | head -n 1)
	stack_trap "$LCTL set_param llite.*.enable_statahead_fname=$enabled"
	$LCTL set_param llite.*.enable_statahead_fname=1

	local np=2

	mpi_run -np $np $MDTEST -C -F -n 1000 -d $DIR/$tdir
	cancel_lru_locks mdc
	$LCTL set_param llite.*.statahead_stats=clear
	$LCTL set_param mdc.*.batch_stats=0
	mpi_run -np $np $MDTEST -T -F -n 1000 -d $DIR/$tdir
	#umount_client $MOUNT || error "failed to umount client"
	echo "Sleep to wait statahead thread (ll_sa_xxx) to exit ..."
	wait_update_facet client "pgrep ll_sa" "" 35 ||
		error "ll_sa thread is still running"

	$LCTL get_param -n llite.*.statahead_stats
	$LCTL get_param -n mdc.*.batch_stats
	ps -el | grep ll_sa

	local count=$($LCTL get_param -n llite.*.statahead_stats |
			awk '/fname.total:/ {print $2}')

	[ $count == $np ] || error "File name pattern statahead not trigger"
	count=$($LCTL get_param -n llite.*.statahead_stats |
		awk '/hit.total:/ {print $2}')
	# Hit ratio should be >= 75%
	[ $count -gt $((np * 1000 * 75 / 100)) ] ||
		error "hit total is too low: $count"
}
run_test 123k "Verify statahead work with mdtest shared stat() mode"

test_123l() {
	local dir=$DIR/$tdir
	local cmd="touch $dir/$tfile.{000000..000100}"

	$LCTL get_param -n mdc.*.connect_flags | grep -q batch_rpc ||
		skip "Server does not support batch RPC"

	stack_trap "rm -rf $dir"
	mkdir -p $dir || error "failed to mkdir $dir"
	eval $cmd

	cancel_lru_locks mdc
	$LCTL set_param llite.*.statahead_stats=clear
	$LCTL set_param mdc.*.batch_stats=0

	local max
	local batch_max
	local enabled

	enabled=$($LCTL get_param -n llite.*.enable_statahead_fname | head -n 1)
	max=$($LCTL get_param -n llite.*.statahead_max | head -n 1)
	batch_max=$($LCTL get_param -n llite.*.statahead_batch_max | head -n 1)
	stack_trap "$LCTL set_param llite.*.statahead_max=$max"
	stack_trap "$LCTL set_param llite.*.statahead_batch_max=$batch_max"
	stack_trap "$LCTL set_param llite.*.enable_statahead_fname=$enabled"
	$LCTL set_param llite.*.enable_statahead_fname=1
	$LCTL set_param llite.*.statahead_max=1024
	$LCTL set_param llite.*.statahead_batch_max=32
	$LCTL get_param -n llite.*.statahead_stats
	#define OBD_FAIL_LLITE_STATAHEAD_PAUSE	0x1433
	$LCTL set_param fail_loc=0x80001433 fail_val=35
	ls $dir/* > /dev/null
	$LCTL get_param -n llite.*.statahead_stats
	$LCTL get_param -n mdc.*.batch_stats

	echo "Sleep to wait the statahead thread (ll_sa_xxx) to exit ..."
	wait_update_facet client "pgrep ll_sa" "" 35 ||
		error "ll_sa thread is still running"
	$LCTL get_param -n llite.*.statahead_stats
}
run_test 123l "Avoid panic when revalidate a local cached entry"

test_124a() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	$LCTL get_param -n mdc.*.connect_flags | grep -q lru_resize ||
		skip_env "no lru resize on server"

	local NR=2000

	test_mkdir $DIR/$tdir

	log "create $NR files at $DIR/$tdir"
	createmany -o $DIR/$tdir/f $NR ||
		error "failed to create $NR files in $DIR/$tdir"

	cancel_lru_locks mdc
	ls -l $DIR/$tdir > /dev/null

	local NSDIR=""
	local LRU_SIZE=0
	for VALUE in $($LCTL get_param ldlm.namespaces.*mdc-*.lru_size); do
		local PARAM=$(echo ${VALUE[0]} | cut -d "=" -f1)
		LRU_SIZE=$($LCTL get_param -n $PARAM)
		if [[ $LRU_SIZE -gt $(default_lru_size) ]]; then
			NSDIR=$(echo $PARAM | cut -d "." -f1-3)
			log "NSDIR=$NSDIR"
                        log "NS=$(basename $NSDIR)"
                        break
                fi
        done

	if [[ -z "$NSDIR" || $LRU_SIZE -lt $(default_lru_size) ]]; then
		skip "Not enough cached locks created!"
	fi
	log "LRU=$LRU_SIZE"

	local SLEEP=30

	# We know that lru resize allows one client to hold $LIMIT locks
	# for 10h. After that locks begin to be killed by client.
	local MAX_HRS=10
	local LIMIT=$($LCTL get_param -n $NSDIR.pool.limit)
	log "LIMIT=$LIMIT"
	if [ $LIMIT -lt $LRU_SIZE ]; then
		skip "Limit is too small $LIMIT"
	fi

	# Make LVF so higher that sleeping for $SLEEP is enough to _start_
	# killing locks. Some time was spent for creating locks. This means
	# that up to the moment of sleep finish we must have killed some of
	# them (10-100 locks). This depends on how fast ther were created.
	# Many of them were touched in almost the same moment and thus will
	# be killed in groups.
	local LVF=$(($MAX_HRS * 60 * 60 / $SLEEP * $LIMIT / $LRU_SIZE * 100))

	# Use $LRU_SIZE_B here to take into account real number of locks
	# created in the case of CMD, LRU_SIZE_B != $NR in most of cases
	local LRU_SIZE_B=$LRU_SIZE
	log "LVF=$LVF"
	local OLD_LVF=$($LCTL get_param -n $NSDIR.pool.lock_volume_factor)
	log "OLD_LVF=$OLD_LVF"
	$LCTL set_param -n $NSDIR.pool.lock_volume_factor $LVF

        # Let's make sure that we really have some margin. Client checks
        # cached locks every 10 sec.
        SLEEP=$((SLEEP+20))
        log "Sleep ${SLEEP} sec"
        local SEC=0
        while ((SEC<$SLEEP)); do
                echo -n "..."
                sleep 5
                SEC=$((SEC+5))
		LRU_SIZE=$($LCTL get_param -n $NSDIR/lru_size)
                echo -n "$LRU_SIZE"
        done
        echo ""
	$LCTL set_param -n $NSDIR.pool.lock_volume_factor $OLD_LVF
	local LRU_SIZE_A=$($LCTL get_param -n $NSDIR.lru_size)

	[[ $LRU_SIZE_B -gt $LRU_SIZE_A ]] || {
                error "No locks dropped in ${SLEEP}s. LRU size: $LRU_SIZE_A"
                unlinkmany $DIR/$tdir/f $NR
                return
        }

        log "Dropped "$((LRU_SIZE_B-LRU_SIZE_A))" locks in ${SLEEP}s"
        log "unlink $NR files at $DIR/$tdir"
        unlinkmany $DIR/$tdir/f $NR
}
run_test 124a "lru resize ======================================="

get_max_pool_limit()
{
	local limit=$($LCTL get_param \
		      -n ldlm.namespaces.*-MDT0000-mdc-*.pool.limit)
	local max=0
	for l in $limit; do
		if [[ $l -gt $max ]]; then
			max=$l
		fi
	done
	echo $max
}

test_124b() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	$LCTL get_param -n mdc.*.connect_flags | grep -q lru_resize ||
		skip_env "no lru resize on server"

	LIMIT=$(get_max_pool_limit)

	NR=$(($(default_lru_size)*20))
	if [[ $NR -gt $LIMIT ]]; then
		log "Limit lock number by $LIMIT locks"
		NR=$LIMIT
	fi

	IFree=$(mdsrate_inodes_available)
	if [ $IFree -lt $NR ]; then
		log "Limit lock number by $IFree inodes"
		NR=$IFree
	fi

	lru_resize_disable mdc
	stack_trap "lru_resize_enable mdc" EXIT
	test_mkdir -p $DIR/$tdir/disable_lru_resize

        createmany -o $DIR/$tdir/disable_lru_resize/f $NR
        log "doing ls -la $DIR/$tdir/disable_lru_resize 3 times"
        cancel_lru_locks mdc
        stime=$SECONDS
        PID=""
        ls -la $DIR/$tdir/disable_lru_resize > /dev/null &
        PID="$PID $!"
        sleep 2
        ls -la $DIR/$tdir/disable_lru_resize > /dev/null &
        PID="$PID $!"
        sleep 2
        ls -la $DIR/$tdir/disable_lru_resize > /dev/null &
        PID="$PID $!"
        wait $PID
        etime=$SECONDS
        nolruresize_delta=$((etime-stime))
        log "ls -la time: $nolruresize_delta seconds"
        log "lru_size = $(lctl get_param -n ldlm.namespaces.*mdc*.lru_size)"
        unlinkmany $DIR/$tdir/disable_lru_resize/f $NR

	lru_resize_enable mdc
	test_mkdir -p $DIR/$tdir/enable_lru_resize

        stack_trap "unlinkmany $DIR/$tdir/enable_lru_resize/f $NR"
        createmany -o $DIR/$tdir/enable_lru_resize/f $NR
        log "doing ls -la $DIR/$tdir/enable_lru_resize 3 times"
        cancel_lru_locks mdc
        stime=$SECONDS
        PID=""
        ls -la $DIR/$tdir/enable_lru_resize > /dev/null &
        PID="$PID $!"
        sleep 2
        ls -la $DIR/$tdir/enable_lru_resize > /dev/null &
        PID="$PID $!"
        sleep 2
        ls -la $DIR/$tdir/enable_lru_resize > /dev/null &
        PID="$PID $!"
        wait $PID
        etime=$SECONDS
        lruresize_delta=$((etime-stime))
        log "ls -la time: $lruresize_delta seconds"
        log "lru_size = $(lctl get_param -n ldlm.namespaces.*mdc*.lru_size)"

        if [ $lruresize_delta -gt $nolruresize_delta ]; then
                log "ls -la is $(((lruresize_delta - $nolruresize_delta) * 100 / $nolruresize_delta))% slower with lru resize enabled"
        elif [ $nolruresize_delta -gt $lruresize_delta ]; then
                log "ls -la is $(((nolruresize_delta - $lruresize_delta) * 100 / $nolruresize_delta))% faster with lru resize enabled"
        else
                log "lru resize performs the same with no lru resize"
        fi
}
run_test 124b "lru resize (performance test) ======================="

test_124c() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	$LCTL get_param -n mdc.*.connect_flags | grep -q lru_resize ||
		skip_env "no lru resize on server"

	# cache ununsed locks on client
	local nr=100
	cancel_lru_locks mdc
	test_mkdir $DIR/$tdir
	createmany -o $DIR/$tdir/f $nr ||
		error "failed to create $nr files in $DIR/$tdir"
	ls -l $DIR/$tdir > /dev/null

	local nsdir="ldlm.namespaces.*-MDT0000-mdc-*"
	local unused=$($LCTL get_param -n $nsdir.lock_unused_count)
	local max_age=$($LCTL get_param -n $nsdir.lru_max_age)
	local recalc_p=$($LCTL get_param -n $nsdir.pool.recalc_period)
	echo "unused=$unused, max_age=$max_age, recalc_p=$recalc_p"

	# set lru_max_age to 1 sec
	$LCTL set_param $nsdir.lru_max_age=1000 # milliseconds
	echo "sleep $((recalc_p * 2)) seconds..."
	sleep $((recalc_p * 2))

	# There's threshold of priv_list eviction each round, hence
	# priv_count here may larger than 0. And there maybe lru shrink
	# invoked just after $priv_count and before $remaining which
	# could cause $remaining smaller than 0
	local priv_count=$($LCTL get_param -n $nsdir.lock_unused_priv_count)
	local remaining=$($LCTL get_param -n $nsdir.lock_unused_count)
	local normal_count=$((remaining - priv_count))

	# restore lru_max_age
	$LCTL set_param -n $nsdir.lru_max_age $max_age
	(( normal_count <= 0 )) ||
		error "$normal_count locks are not canceled"
	unlinkmany $DIR/$tdir/f $nr
}
run_test 124c "LRUR cancel very aged locks"

test_124d() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	$LCTL get_param -n mdc.*.connect_flags | grep -q lru_resize ||
		skip_env "no lru resize on server"

	# cache unused locks on client
	local nr=100

	lru_resize_disable mdc

	cancel_lru_locks mdc

	# asynchronous object destroy at MDT could cause bl ast to client
	test_mkdir $DIR/$tdir
	stack_trap "unlinkmany $DIR/$tdir/f $nr" EXIT
	createmany -o $DIR/$tdir/f $nr ||
		error "failed to create $nr files in $DIR/$tdir"

	ls -l $DIR/$tdir > /dev/null

	local nsdir="ldlm.namespaces.*-MDT0000-mdc-*"
	local unused=$($LCTL get_param -n $nsdir.lock_unused_count)
	local max_age=$($LCTL get_param -n $nsdir.lru_max_age)
	local recalc_p=$($LCTL get_param -n $nsdir.pool.recalc_period)

	echo "unused=$unused, max_age=$max_age, recalc_p=$recalc_p"

	# set lru_max_age to 1 sec
	$LCTL set_param $nsdir.lru_max_age=1000 # milliseconds
	stack_trap "$LCTL set_param -n $nsdir.lru_max_age $max_age" EXIT

	echo "sleep $((recalc_p * 2)) seconds..."
	sleep $((recalc_p * 2))

	local priv_count=$($LCTL get_param -n $nsdir.lock_unused_priv_count)
	local remaining=$($LCTL get_param -n $nsdir.lock_unused_count)
	local normal_count=$((remaining - priv_count))

	(( normal_count <= 0 )) ||
		error "$normal_count locks are not canceled"
}
run_test 124d "cancel very aged locks if lru-resize disabled"

test_124e() {
	[[ $PARALLEL != "yes" ]] || skip "skip parallel run"

	local nsdir="ldlm.namespaces.*-MDT0000-mdc-*"
	local max_unused=$(default_lru_size)
	echo "max_unused=$max_unused"
	lru_resize_disable mdc $max_unused
	$LCTL set_param $nsdir.lru_priv_score_threshold=1 ||
		error "fail to set lru_priv_score_threshold"
	stack_trap "$LCTL set_param $nsdir.lru_priv_score_threshold=1"

	# cache unused locks on client
	local nr=$((max_unused * 2))
	mkdir_on_mdt0 $DIR/$tdir
	mkdir_on_mdt0 $DIR/$tdir/empty $DIR/$tdir/files
	stack_trap "unlinkmany $DIR/$tdir/files/f $nr"
	createmany -i0 -o $DIR/$tdir/files/f $nr ||
		error "failed to create $nr files in $DIR/$tdir/files"
	# clean cache
	cancel_lru_locks mdc
	sleep 5
	# dir lock should be placed in priv list
	for ((i = 0; i < 10; i++)); do
		stat $DIR/$tdir/empty > /dev/null
	done
	# try to overflow lru cache
	ls -l $DIR/$tdir/files > /dev/null

	local unused_cnt=$($LCTL get_param -n $nsdir.lock_unused_count)
	local priv_cnt=$($LCTL get_param -n $nsdir.lock_unused_priv_count)
	local priv_hits=$($LCTL get_param -n $nsdir.lock_lru_priv_hits)
	(( priv_cnt > 0 )) || error "priv_cnt is 0"
	(( priv_hits > 0 )) || error "priv_hits is 0"

	# lock should been in priv list
	stat $DIR/$tdir/empty > /dev/null
	sleep 2

	local new_unused_cnt=$($LCTL get_param -n $nsdir.lock_unused_count)
	local new_priv_cnt=$($LCTL get_param -n $nsdir.lock_unused_priv_count)
	local new_priv_hits=$($LCTL get_param -n $nsdir.lock_lru_priv_hits)
	(( new_unused_cnt == unused_cnt )) ||
		error "new_cnt($new_unused_cnt) != unused_cnt($unused_cnt)"
	(( priv_cnt == new_priv_cnt )) ||
		error "priv_cnt($priv_cnt) != new_priv_cnt($new_priv_cnt)"
	(( new_priv_hits > priv_hits )) ||
		error "new_priv_hits($new_priv_hits) <= priv_hits($priv_hits)"
}
run_test 124e "LFRU keep priv locks from eviction"

test_124f() {
	[[ $PARALLEL != "yes" ]] || skip "skip parallel run"

	local nsdir="ldlm.namespaces.*-MDT0000-mdc-*"
	local max_unused=$(default_lru_size)
	echo "max_unused=$max_unused"
	lru_resize_disable mdc $max_unused
	stack_trap "$LCTL set_param $nsdir.lru_priv_score_threshold=1"

	# threshold inc
	local priv_thres=1
	$LCTL set_param -n $nsdir.lru_priv_score_threshold=$priv_thres ||
		error "fail to set lru_priv_score_threshold"
	# cache unused locks on client
	local nr=$((max_unused * 4))
	mkdir_on_mdt0 $DIR/$tdir
	mkdir_on_mdt0 $DIR/$tdir/files
	stack_trap "unlinkmany $DIR/$tdir/files/f $nr"
	createmany -i0 -o $DIR/$tdir/files/f $nr ||
		error "failed to create $nr files in $DIR/$tdir/files"
	# clean cache
	cancel_lru_locks mdc
	sleep 5
	# try to overflow lru cache
	ls -l $DIR/$tdir/files > /dev/null
	local inc_priv_thres=$(
		$LCTL get_param -n $nsdir.lru_priv_score_threshold
	)
	(( inc_priv_thres > priv_thres )) ||
		error "new_thres($inc_priv_thres) <= threshold($priv_thres)"

	# threshold dec
	priv_thres=7
	$LCTL set_param $nsdir.lru_priv_score_threshold=$priv_thres ||
		error "failed to set lru_priv_score_threshold to $priv_thres"
	# clean cache
	cancel_lru_locks mdc
	sleep 5
	# try to overflow lru cache
	ls -l $DIR/$tdir/files > /dev/null
	local dec_priv_thres=$(
		$LCTL get_param -n $nsdir.lru_priv_score_threshold
	)
	(( dec_priv_thres < priv_thres )) ||
		error "new_thres($dec_priv_thres)>=priv_thres($priv_thres)"
}
run_test 124f "LFRU priv threshold inc/dec adjustment"

test_124g_run() {
	local client_nid="$1"
	local base_dir="$2/$4"
	local lru_size=$3
	local policy="$4"
	local -n ref_enq_res=$5
	local cold_nr=$lru_size
	local nr=$(( lru_size / 4 ))

	# clear the existing cache state before switching policy
	cancel_lru_locks mdc
	sleep 2
	local nsdir="ldlm.namespaces.*-MDT0000-mdc-*"
	$LCTL set_param $nsdir.lock_cache_policy="$policy" ||
		error "failed to set lock_cache_policy to $policy"

	mkdir_on_mdt0 "$base_dir"
	mkdir_on_mdt0 "$base_dir"/cold
	createmany -i0 -o "$base_dir"/cold/f $cold_nr ||
		error "failed to create $cold_nr files in $base_dir/cold"
	createmany -i0 -o "$base_dir"/f $nr ||
		error "failed to create $nr files"

	# record existing enqueue stats
	cancel_lru_locks mdc
	sleep 2
	$LCTL get_param $nsdir.lock_unused_count

	local nsservdir="mdt.*-MDT0000.exports.'$client_nid'.ldlm_stats"
	# res format as:
	# 	ldlm_enqueue              1022 samples [reqs]
	local o_enq=$(do_facet mds1 $LCTL get_param "$nsservdir" |\
		      awk '/ldlm_enqueue/ {print $2}') ||
		error "o_enq failed to get ldlm_enqueue count"
	local prev_enq=$o_enq

	do_facet mds1 $LCTL get_param "$nsservdir"
	echo "start stat & ls ops..."
	for ((i = 0; i < 10; i++)); do
		for ((j = 0; j < nr; j++)); do
			for ((cnt = 0; cnt < 10; cnt++)); do
				stat "$base_dir"/f$j > /dev/null
			done
		done

		local before_priv_cnt=$($LCTL get_param -n $nsdir.lock_unused_priv_count)
		for ((c = 0; c < cold_nr; c++)); do
			stat "$base_dir"/cold/f$c > /dev/null
		done
		# facilitate debugging output
		local priv_cnt=$($LCTL get_param -n $nsdir.lock_unused_priv_count)
		local temp_enq=$(do_facet mds1 $LCTL get_param "$nsservdir" |\
				     awk '/ldlm_enqueue/ {print $2}') ||
			error "temp_enq failed to get ldlm_enqueue count"
		echo "round$i done, before_priv_cnt=$before_priv_cnt, priv_cnt=$priv_cnt, inc_enq=$((temp_enq - prev_enq))"
		prev_enq=$temp_enq
	done

	local n_enq=$(do_facet mds1 $LCTL get_param "$nsservdir" |\
		      awk '/ldlm_enqueue/ {print $2}') ||
		error "n_enq failed to get ldlm_enqueue count"
	ref_enq_res=$(( n_enq - o_enq ))
	echo "base_dir=$base_dir, policy=$policy"
	echo "o_enq=$o_enq, n_enq=$n_enq, ref_enq_res=$ref_enq_res"

	rm -rf "$base_dir"; wait_delete_completed
}

test_124g() {
	[[ $PARALLEL != "yes" ]] || skip "skip parallel run"
	(( $MDS1_VERSION >= $(version_code 2.17.50.63) )) ||
		skip "Need MDS with LFRU support (LU-11509, >= 2.17.50.63)"

	local nsdir="ldlm.namespaces.*-MDT0000-mdc-*"
	local lru_size=$(default_lru_size)
	lru_resize_disable mdc $lru_size
	local save="$TMP/$TESTSUITE-$TESTNAME.parameters"
	save_lustre_params client "$nsdir.lock_cache_policy" > $save
	save_lustre_params client "llite.*.enable_statahead_fname" >> $save
	stack_trap "restore_lustre_params < $save; rm -f $save"
	# disable statehead fname to avoid additional threads' execution
	# which may affect the test result due to its random behavior.
	$LCTL set_param llite.*.enable_statahead_fname=0

	local cli_nid="0@lo"
	if remote_mds; then
		cli_nid=$($LCTL list_nids | grep -v "@lo" | head -1)
	fi
	mkdir_on_mdt0 $DIR/$tdir
	local enq_priv_enabled
	local enq_priv_disable
	# test with lfru
	test_124g_run "$cli_nid" "$DIR/$tdir" $lru_size "LFRU" enq_priv_enabled
	# test with lru
	test_124g_run "$cli_nid" "$DIR/$tdir" $lru_size "LRU" enq_priv_disable

	echo ">> lfru_enqueue=$enq_priv_enabled, lru_enqueue=$enq_priv_disable"
	(( enq_priv_enabled <= enq_priv_disable )) ||
	     error "lfru enqueue $enq_priv_enabled > lru $enq_priv_disable"
}
run_test 124g "LFRU performance test"

test_125() { # 13358
	$LCTL get_param -n llite.*.client_type | grep -q local ||
		skip "must run as local client"
	$LCTL get_param -n mdc.*-mdc-*.connect_flags | grep -q acl ||
		skip_env "must have acl enabled"
	[ -z "$(which setfacl)" ] && skip_env "must have setfacl tool"
	id $USER0 || skip_env "missing user $USER0"

	test_mkdir $DIR/$tdir
	$LFS setstripe -S 65536 -c -1 $DIR/$tdir || error "setstripe failed"
	setfacl -R -m u:$USER0:rwx $DIR/$tdir ||
		error "setfacl $DIR/$tdir failed"
	ls -ld $DIR/$tdir || error "cannot access $DIR/$tdir"
}
run_test 125 "don't return EPROTO when a dir has a non-default striping and ACLs"

test_126() { # bug 12829/13455
	$GSS && skip_env "must run as gss disabled"
	$LCTL get_param -n llite.*.client_type | grep -q local ||
		skip "must run as local client"
	[ "$UID" != 0 ] && skip "must run as root, not UID $UID"

	$RUNAS -u 0 -g 1 touch $DIR/$tfile || error "touch failed"
	gid=`ls -n $DIR/$tfile | awk '{print $4}'`
	rm -f $DIR/$tfile
	[ $gid -eq "1" ] || error "gid is set to" $gid "instead of 1"
}
run_test 126 "check that the fsgid provided by the client is taken into account"

test_127a() { # bug 15521
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	local name count samp unit min max sum sumsq
	local tmpfile=$TMP/$tfile.tmp

	# enable stats header if it is disabled
	$LCTL set_param enable_stats_header=1

	$LFS setstripe -i 0 -c 1 $DIR/$tfile || error "setstripe failed"
	echo "stats before reset"
	stack_trap "rm -f $DIR/$tfile $tmpfile"
	local now=$(date +%s)

	$LCTL get_param osc.*.stats | tee $tmpfile

	local snapshot_time=$(awk '/snapshot_time/ { print $2; exit }' $tmpfile)
	local start_time=$(awk '/start_time/ { print $2; exit }' $tmpfile)
	local elapsed=$(awk '/elapsed_time/ { print $2; exit }' $tmpfile)
	local uptime=$(awk '{ print $1 }' /proc/uptime)

	# snapshot_time should match POSIX epoch time, allow some delta for VMs
	(( ${snapshot_time%\.*} >= $now - 5 &&
	   ${snapshot_time%\.*} <= $now + 5 )) ||
		error "snapshot_time=$snapshot_time != now=$now"
	# elapsed _should_ be from mount, but at least less than uptime
	(( ${elapsed%\.*} < ${uptime%\.*} )) ||
		error "elapsed=$elapsed > uptime=$uptime"
	(( ${snapshot_time%\.*} - ${start_time%\.*} >= ${elapsed%\.*} - 2 &&
	   ${snapshot_time%\.*} - ${start_time%\.*} <= ${elapsed%\.*} + 2 )) ||
		error "elapsed=$elapsed != $snapshot_time - $start_time"

	$LCTL set_param osc.*.stats=0
	local reset=$(date +%s)
	local fsize=$((2048 * 1024))

	dd if=/dev/zero of=$DIR/$tfile bs=$fsize count=1
	cancel_lru_locks osc
	dd if=$DIR/$tfile of=/dev/null bs=$fsize

	now=$(date +%s)
	$LCTL get_param osc.*0000-osc-*.stats > $tmpfile
	while read name count samp unit min max sum sumsq; do
		[[ "$samp" == "samples" ]] || continue

		echo "got name=$name count=$count unit=$unit min=$min max=$max"
		[ ! $min ] && error "Missing min value for $name proc entry"
		eval $name=$count || error "Wrong proc format"

		case $name in
		read_bytes|write_bytes)
			[[ "$unit" =~ "bytes" ]] ||
				error "unit is not 'bytes': $unit"
			(( $min >= 4096 )) || error "min is too small: $min"
			(( $min <= $fsize )) || error "min is too big: $min"
			(( $max >= 4096 )) || error "max is too small: $max"
			(( $max <= $fsize )) || error "max is too big: $max"
			(( $sum == $fsize )) || error "sum is wrong: $sum"
			(( $sumsq >= ($fsize / 4096) * (4096 * 4096) )) ||
				error "sumsquare is too small: $sumsq"
			(( $sumsq <= $fsize * $fsize )) ||
				error "sumsquare is too big: $sumsq"
			;;
		ost_read|ost_write)
			[[ "$unit" =~ "usec" ]] ||
				error "unit is not 'usec': $unit"
			;;
		*)	;;
		esac
	done < $tmpfile

	#check that we actually got some stats
	[ "$read_bytes" ] || error "Missing read_bytes stats"
	[ "$write_bytes" ] || error "Missing write_bytes stats"
	[ "$read_bytes" != 0 ] || error "no read done"
	[ "$write_bytes" != 0 ] || error "no write done"

	snapshot_time=$(awk '/snapshot_time/ { print $2; exit }' $tmpfile)
	start_time=$(awk '/start_time/ { print $2; exit }' $tmpfile)
	elapsed=$(awk '/elapsed_time/ { print $2; exit }' $tmpfile)

	# snapshot_time should match POSIX epoch time, allow some delta for VMs
	(( ${snapshot_time%\.*} >= $now - 5 &&
	   ${snapshot_time%\.*} <= $now + 5 )) ||
		error "reset snapshot_time=$snapshot_time != now=$now"
	# elapsed should be from time of stats reset
	(( ${elapsed%\.*} >= $now - $reset - 2 &&
	   ${elapsed%\.*} <= $now - $reset + 2 )) ||
		error "reset elapsed=$elapsed > $now - $reset"
	(( ${snapshot_time%\.*} - ${start_time%\.*} >= ${elapsed%\.*} - 2 &&
	   ${snapshot_time%\.*} - ${start_time%\.*} <= ${elapsed%\.*} + 2 )) ||
		error "reset elapsed=$elapsed != $snapshot_time - $start_time"
}
run_test 127a "verify the client stats are sane"

test_127b() { # bug LU-333
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	local name count samp unit min max sum sumsq

	echo "stats before reset"
	$LCTL get_param llite.*.stats
	$LCTL set_param llite.*.stats=0

	# perform 2 reads and writes so MAX is different from SUM.
	dd if=/dev/zero of=$DIR/$tfile bs=$PAGE_SIZE count=1
	dd if=/dev/zero of=$DIR/$tfile bs=$PAGE_SIZE count=1
	cancel_lru_locks osc
	dd if=$DIR/$tfile of=/dev/null bs=$PAGE_SIZE count=1
	dd if=$DIR/$tfile of=/dev/null bs=$PAGE_SIZE count=1

	$LCTL get_param llite.*.stats | grep samples > $TMP/$tfile.tmp
	stack_trap "rm -f $TMP/$tfile.tmp"
	while read name count samp unit min max sum sumsq; do
		echo "got name=$name count=$count unit=$unit min=$min max=$max"
		eval $name=$count || error "Wrong proc format"

		case $name in
		read_bytes|write_bytes)
			[[ "$unit" =~ "bytes" ]] ||
				error "unit is not 'bytes': $unit"
			(( $count == 2 )) || error "count is not 2: $count"
			(( $min == $PAGE_SIZE )) ||
				error "min is not $PAGE_SIZE: $min"
			(( $max == $PAGE_SIZE )) ||
				error "max is not $PAGE_SIZE: $max"
			(( $sum == $PAGE_SIZE * 2 )) ||
				error "sum is not $((PAGE_SIZE * 2)): $sum"
			;;
		read|write)
			[[ "$unit" =~ "usec" ]] ||
				error "unit is not 'usec': $unit"
			;;
		*)	;;
		esac
	done < $TMP/$tfile.tmp

	#check that we actually got some stats
	[ "$read_bytes" ] || error "Missing read_bytes stats"
	[ "$write_bytes" ] || error "Missing write_bytes stats"
	[ "$read_bytes" != 0 ] || error "no read done"
	[ "$write_bytes" != 0 ] || error "no write done"
}
run_test 127b "verify the llite client stats are sane"

test_127c() { # LU-12394
	[ "$OSTCOUNT" -lt "2" ] && skip_env "needs >= 2 OSTs"
	local size
	local bsize
	local reads
	local writes
	local count

	$LCTL set_param llite.*.extents_stats=1
	stack_trap "$LCTL set_param llite.*.extents_stats=0" EXIT

	# Use two stripes so there is enough space in default config
	$LFS setstripe -c 2 $DIR/$tfile

	# Extent stats start at 0-4K and go in power of two buckets
	# LL_HIST_START = 12 --> 2^12 = 4K
	# We do 3K*2^i, so 3K, 6K, 12K, 24K... hitting each bucket.
	# We do not do buckets larger than 64 MiB to avoid ENOSPC issues on
	# small configs
	for size in 3K 6K 12K 24K 48K 96K 192K 384K 768K 1536K 3M 6M 12M 24M 48M;
		do
		# Write and read, 2x each, second time at a non-zero offset
		dd if=/dev/zero of=$DIR/$tfile bs=$size count=1
		dd if=/dev/zero of=$DIR/$tfile bs=$size count=1 seek=10
		dd if=$DIR/$tfile of=/dev/null bs=$size count=1
		dd if=$DIR/$tfile of=/dev/null bs=$size count=1 seek=10
		rm -f $DIR/$tfile
	done

	$LCTL get_param llite.*.extents_stats

	count=2
	for bsize in 4K 8K 16K 32K 64K 128K 256K 512K 1M 2M 4M 8M 16M 32M 64M;
		do
		local bucket=$($LCTL get_param -n llite.*.extents_stats |
				grep -m 1 $bsize)
		reads=$(echo $bucket | awk '{print $5}')
		writes=$(echo $bucket | awk '{print $9}')
		[ "$reads" -eq $count ] ||
			error "$reads reads in < $bsize bucket, expect $count"
		[ "$writes" -eq $count ] ||
			error "$writes writes in < $bsize bucket, expect $count"
	done

	# Test mmap write and read
	$LCTL set_param llite.*.extents_stats=c
	size=512
	dd if=/dev/zero of=$DIR/$tfile bs=${size}K count=1
	$MULTIOP $DIR/$tfile OSMRUc || error "$MULTIOP $DIR/$tfile failed"
	$MULTIOP $DIR/$tfile OSMWUc || error "$MULTIOP $DIR/$tfile failed"

	$LCTL get_param llite.*.extents_stats

	count=$(((size*1024) / PAGE_SIZE))

	bsize=$((2 * PAGE_SIZE / 1024))K

	bucket=$($LCTL get_param -n llite.*.extents_stats |
			grep -m 1 $bsize)
	reads=$(echo $bucket | awk '{print $5}')
	writes=$(echo $bucket | awk '{print $9}')
	# mmap writes fault in the page first, creating an additonal read
	[ "$reads" -eq $((2 * count)) ] ||
		error "$reads reads in < $bsize bucket, expect $count"
	[ "$writes" -eq $count ] ||
		error "$writes writes in < $bsize bucket, expect $count"
}
run_test 127c "test llite extent stats with regular & mmap i/o"

test_127d() {
	[[ $PARALLEL == "yes" ]] && skip "skip parallel run"

	(( CLIENT_VERSION >= $(version_code 2.16.56.105) )) ||
		skip "need client > 2.16.56.105 for osc latency stats"

	local size=10
	local file=$DIR/$tfile

	# Clear RPC stats
	$LCTL set_param osc.*.rpc_stats=clear

	# Generate write I/O
	dd if=/dev/urandom of=$file bs=1M count=$size conv=fsync ||
		error "dd write failed"
	stack_trap "rm -f $file"

	# Drop caches to ensure read goes to server
	cancel_lru_locks osc

	# Generate read I/O
	dd if=$file of=/dev/null bs=1M || error "dd read failed"

	# Get RPC stats for debugging
	local rpc_stats=$($LCTL get_param -n osc.*OST*.rpc_stats)
	echo "RPC stats after I/O:"
	echo "$rpc_stats"

	# Check for read RPC latency stats
	local read_latency=$(echo "$rpc_stats" |
		awk '/RPC latency/,/^$/ && $1 ~ /[0-9]+:/ && $2 > 0 \
		     { found = 1; exit }
		     END { print (found ? "1" : "0") }')

	# Check for write RPC latency stats
	local write_latency=$(echo "$rpc_stats" |
		awk '/RPC latency/,/^$/ && $1 ~ /[0-9]+:/ && $6 > 0 \
		     { found = 1; exit }
		     END { print (found ? "1" : "0") }')

	echo "Read latency found: $read_latency"
	echo "Write latency found: $write_latency"

	(( read_latency == 1 )) || error "No read RPC latency stats"
	(( write_latency == 1 )) || error "No write RPC latency stats"
}
run_test 127d "OSC RPC latency histograms for read and write latency"

test_127_io_latency_test() {
	[[ $PARALLEL == "yes" ]] && skip "skip parallel run"

	local facet=$1
	local io_latency_param=$2
	local dev=osc

	[[ $facet == *ost* ]] && {
		# disable cache to have read IO
		local rcc="osd-*.$FSNAME-OST0000.read_cache_enable"
		local wcc="osd-*.$FSNAME-OST0000.writethrough_cache_enable"
		local rsaved=$(do_facet $facet $LCTL get_param -n $rcc)
		local wsaved=$(do_facet $facet $LCTL get_param -n $wcc)
		do_facet $facet $LCTL set_param $rcc=0 $wcc=0
		stack_trap "do_facet $facet $LCTL set_param $rcc=$rsaved $wcc=$wsaved"
	}

	[[ $io_latency_param =~ "md[ct]" ]] && dev="mdc"

	# avoid leftovers after preceding tests
	cancel_lru_locks osc
	sleep 1

	# Clear RPC stats
	do_facet $facet $LCTL set_param $io_latency_param=clear
	[[ $facet == *ost* ]] &&
		do_facet $facet $LCTL set_param osd-*.*OST*.stats=clear

	# Generate I/O with different sizes to populate multiple histograms
	local file=$DIR/$tdir/$tfile
	local count=10
	local sizes=()
	local mppr=($($LCTL get_param -n $dev.*.max_pages_per_rpc))
	for size in 4 64 1024; do
		(( size >= $PAGE_SIZE / 1024 &&
		   size <= $mppr * $PAGE_SIZE / 1024 )) &&
			sizes+=(${size}K)
	done

	$LFS mkdir -i 0 $DIR/$tdir
	stack_trap "rm -f ${file}_*"

	for size in ${sizes[@]}; do
		echo "Generating I/O with size $size"

		# Write with current size
		[[ $dev == "mdc" ]] &&
			$LFS setstripe -E 4M -L mdt ${file}_${size} ||
			$LFS setstripe -c 1 -i 0 ${file}_${size}
		dd if=/dev/urandom of=${file}_${size} bs=$size count=$count \
			oflag=direct ||
			error "dd write failed for size $size"
		cancel_lru_locks osc

		# Read with current size
		dd if=${file}_${size} of=/dev/null bs=$size count=$count \
			iflag=direct ||
			error "dd read failed for size $size"
	done

	sleep 5
	# Get client IO latency stats for debugging
	local io_latency_stats=$(do_facet $facet $LCTL get_param $io_latency_param)
	echo "$io_latency_param stats after I/O:"
	echo "$io_latency_stats"

	# Check that we have entries for different sizes
	for size in ${sizes[@]}; do
		echo "$io_latency_stats" | grep -q _$size || {
			$LCTL get_param osc.*.{io_latency,rpc}_stats
			[[ $facet == *ost* ]] &&
				do_facet ost1 $LCTL get_param osd-*.*.{brw,io_latency}_stats &&
				do_facet ost1 $LCTL get_param osd-*.*OST*.stats
			error "No stats found for size $size"
		}
	done

	# sometimes stray writes are seen, filter to expected sizes
	local check_counts=$(echo "$io_latency_stats" |
		grep -E "$(sed -e 's/ /K|_/g' <<<${sizes[*]})" |
		awk -v count="$count" '/K: / {sum = 0
		while (match($0, /[0-9]+us: ([0-9]+),/, arr)) {
			sum += arr[1]
			$0 = substr($0, RSTART + RLENGTH)
		}
		{ if (sum < count) print "Expected "count" entries, found "sum}
		}')
	[[ -z "$check_counts" ]] || error "$check_counts"

	local has_read=$(echo "$io_latency_stats" | grep -c "rd_")
	local has_write=$(echo "$io_latency_stats" | grep -c "wr_")

	(( has_read >= ${#sizes[@]} )) ||
		error "Expected ${#sizes[@]} read stats, found $has_read"
	(( has_write >= ${#sizes[@]} )) ||
		error "Expected ${#sizes[@]} write stats, found $has_write"
}

test_127e() {
	test_127_io_latency_test client osc.$FSNAME-OST0000-*.io_latency_stats
}
run_test 127e "client IO latency histograms by size"

test_127f() {
	(( $OST1_VERSION >= $(version_code v2_17_50-123-gc688e33f11) )) ||
		skip "need OST > 2.17.50.123 for OST IO latency stats"
	[[ $(facet_fstype ost1) == ldiskfs ]] || skip "ldiskfs only"

	test_127_io_latency_test ost1 osd-*.$FSNAME-OST0000.io_latency_stats
}
run_test 127f "OST IO latency histograms by size"

test_128() { # bug 15212
	touch $DIR/$tfile
	$LFS 2>&1 <<-EOF | tee $TMP/$tfile.log
		find $DIR/$tfile
		find $DIR/$tfile
	EOF

	result=$(grep error $TMP/$tfile.log)
	rm -f $DIR/$tfile $TMP/$tfile.log
	[ -z "$result" ] ||
		error "consecutive find's under interactive lfs failed"
}
run_test 128 "interactive lfs for 2 consecutive find's"

set_dir_limits () {
	local mntdev
	local canondev
	local node

	local ldproc=/proc/fs/ldiskfs
	local facets=$(get_facets MDS)

	for facet in ${facets//,/ }; do
		canondev=$(ldiskfs_canon \
			   *.$(convert_facet2label $facet).mntdev $facet)
		do_facet $facet "test -e $ldproc/$canondev/max_dir_size" ||
			ldproc=/sys/fs/ldiskfs
		do_facet $facet "echo $1 >$ldproc/$canondev/max_dir_size"
		do_facet $facet "echo $2 >$ldproc/$canondev/warning_dir_size"
	done
}

check_mds_dmesg() {
	local facets=$(get_facets MDS)
	for facet in ${facets//,/ }; do
		do_facet $facet "dmesg | tail -3 | grep $1" && return 0
	done
	return 1
}

test_129() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[[ $MDS1_VERSION -ge $(version_code 2.5.56) ]] ||
		skip "Need MDS version with at least 2.5.56"
	if [ "$mds1_FSTYPE" != ldiskfs ]; then
		skip_env "ldiskfs only test"
	fi
	remote_mds_nodsh && skip "remote MDS with nodsh"

	local ENOSPC=28
	local has_warning=false

	rm -rf $DIR/$tdir
	mkdir -p $DIR/$tdir

	# block size of mds1
	local maxsize=$(($($LCTL get_param -n mdc.*MDT0000*.blocksize) * 8))
	set_dir_limits $maxsize $((maxsize * 6 / 8))
	stack_trap "set_dir_limits 0 0"
	stack_trap "unlinkmany $DIR/$tdir/file_base_ 2000 || true"
	local dirsize=$(stat -c%s "$DIR/$tdir")
	local nfiles=0
	while (( $dirsize <= $maxsize )); do
		$MCREATE $DIR/$tdir/file_base_$nfiles
		rc=$?
		# check two errors:
		# ENOSPC for ext4 max_dir_size, which has been used since
		# kernel v3.6-rc1-8-gdf981d03ee, lustre v2_4_50_0-79-gaed82035c0
		if (( rc == ENOSPC )); then
			set_dir_limits 0 0
			echo "rc=$rc returned as expected after $nfiles files"

			createmany -o $DIR/$tdir/file_extra_$nfiles. 5 ||
				error "create failed w/o dir size limit"

			# messages may be rate limited if test is run repeatedly
			check_mds_dmesg '"is approaching max"' ||
				echo "warning message should be output"
			check_mds_dmesg '"has reached max"' ||
				echo "reached message should be output"

			dirsize=$(stat -c%s "$DIR/$tdir")

			[[ $dirsize -ge $maxsize ]] && return 0
			error "dirsize $dirsize < $maxsize after $nfiles files"
		elif (( rc != 0 )); then
			break
		fi
		nfiles=$((nfiles + 1))
		dirsize=$(stat -c%s "$DIR/$tdir")
	done

	error "rc=$rc, size=$dirsize/$maxsize, mdt=$MDSCOUNT, nfiles=$nfiles"
}
run_test 129 "test directory size limit ========================"

OLDIFS="$IFS"
test_130a() {
	local filefrag_op=$(filefrag -l 2>&1 | grep "invalid option")
	[[ -z "$filefrag_op" ]] || skip_env "filefrag missing logical ordering"

	local fm_file=$DIR/$tfile

	$LFS setstripe -S 65536 -c 1 $fm_file || error "setstripe on $fm_file"
	stack_trap "rm -f $fm_file"
	dd if=/dev/zero of=$fm_file bs=65536 count=1 ||
		error "dd failed for $fm_file"

	# LU-1795: test filefrag/FIEMAP once, even if unsupported on ZFS
	filefrag -ves $fm_file
	local rc=$?
	[[ "$ost1_FSTYPE" != "zfs" ]] ||
		skip "LU-1941: FIEMAP unimplemented on ZFS"
	(( $rc == 0 )) || error "filefrag $fm_file failed"

	filefrag_op=$(filefrag -ve -k $fm_file |
		      sed -n '/ext:/,/found/{/ext:/d; /found/d; p}')
	local lun=$($LFS getstripe -i $fm_file)
	local start_blk=$(echo $filefrag_op | cut -d: -f2 | cut -d. -f1)
	local tot_len=0

	while read line; do
		local frag_lun=$(echo $line | cut -d: -f5)
		local ext_len=$(echo $line | cut -d: -f4)

		(( $frag_lun == $lun )) ||
			error "OST$lun was reported on OST$frag_lun"
		(( tot_len += ext_len ))
	done <<< "$filefrag_op"

	(( start_blk == 0 )) ||
		error "OST$last_lun start_blk $start_blk != 0"
	(( tot_len == 64 )) ||
		error "OST$last_lun $tot_len != 64"

	echo "FIEMAP on single striped file succeeded"
}
run_test 130a "FIEMAP (1-stripe file)"

test_130b() {
	(( $OSTCOUNT >= 2 )) || skip "needs >= 2 OSTs"

	local filefrag_op=$(filefrag -l 2>&1 | grep "invalid option")
	[[ -z "$filefrag_op" ]] || skip_env "filefrag missing logical ordering"
	[[ "$ost1_FSTYPE" != "zfs" ]] ||
		skip "LU-1941: FIEMAP unimplemented on ZFS"

	local fm_file=$DIR/$tfile
	$LFS setstripe -S 65536 -c $OSTCOUNT $fm_file ||
		error "setstripe on $fm_file"
	stack_trap "rm -f $fm_file"

	local actual_stripe_count=$($LFS getstripe -c $fm_file)
	dd if=/dev/zero of=$fm_file bs=1M count=$actual_stripe_count ||
		error "dd failed on $fm_file"

	filefrag -ves $fm_file || error "filefrag $fm_file failed"
	filefrag_op=$(filefrag -ve -k $fm_file |
		      sed -n '/ext:/,/found/{/ext:/d; /found/d; p}')

	local last_lun=$(echo $filefrag_op | cut -d: -f5 |
			 sed -e 's/^[ \t]*/0x/' | sed -e 's/0x0x/0x/')
	local tot_len=0
	local num_luns=1

	while read line; do
		local frag_lun=$(echo $line | cut -d: -f5 |
				 sed -e 's/^[ \t]*/0x/' | sed -e 's/0x0x/0x/')
		local ext_len=$(echo $line | cut -d: -f4)
		if (( $frag_lun != $last_lun )); then
			(( tot_len == 1024 )) ||
				error "OST$last_lun $tot_len != 1024"
			(( num_luns += 1 ))
			tot_len=0
		fi
		(( tot_len += ext_len ))
		last_lun=$frag_lun
	done <<< "$filefrag_op"

	(( num_luns == $actual_stripe_count )) ||
		error "OST$last_lun $num_luns != $actual_stripe_count"
	(( tot_len == 1024 )) ||
		error "OST$last_lun $tot_len != 1024"

	echo "FIEMAP on $OSTCOUNT-stripe file succeeded"
}
run_test 130b "FIEMAP ($OSTCOUNT-stripe file)"

test_130c() {
	(( $OSTCOUNT >= 2 )) || skip "needs >= 2 OSTs"

	local filefrag_op=$(filefrag -l 2>&1 | grep "invalid option")
	[[ -z "$filefrag_op" ]] || skip_env "filefrag missing logical ordering"
	[[ "$ost1_FSTYPE" != "zfs" ]] ||
		skip "LU-1941: FIEMAP unimplemented on ZFS"

	local fm_file=$DIR/$tfile
	$LFS setstripe -S 65536 -c 2 $fm_file || error "setstripe on $fm_file"
	stack_trap "rm -f $fm_file"

	dd if=/dev/zero of=$fm_file seek=1 bs=1M count=1 ||
		error "dd failed on $fm_file"

	filefrag -ves $fm_file || error "filefrag $fm_file failed"
	filefrag_op=$(filefrag -ve -k $fm_file |
		      sed -n '/ext:/,/found/{/ext:/d; /found/d; p}')

	local last_lun=$(echo $filefrag_op | cut -d: -f5 |
			 sed -e 's/^[ \t]*/0x/' | sed -e 's/0x0x/0x/')
	local tot_len=0
	local num_luns=1

	while read line; do
		local frag_lun=$(echo $line | cut -d: -f5 |
				 sed -e 's/^[ \t]*/0x/' | sed -e 's/0x0x/0x/')
		local ext_len=$(echo $line | cut -d: -f4)
		if (( $frag_lun != $last_lun )); then
			local logical=$(echo $line | cut -d: -f2 | cut -d. -f1)
			(( logical == 512 )) ||
				error "OST$last_lun logical start $logical != 512"
			(( tot_len == 512 )) ||
				error "OST$last_lun $tot_len != 512"
			(( num_luns += 1 ))
			tot_len=0
		fi
		(( tot_len += ext_len ))
		last_lun=$frag_lun
	done <<< "$filefrag_op"
	(( num_luns == 2 )) ||
		error "OST$last_lun $num_luns != 2"
	(( tot_len == 512 )) ||
		error "OST$last_lun $tot_len != 512"

	echo "FIEMAP on 2-stripe file with hole succeeded"
}
run_test 130c "FIEMAP (2-stripe file with hole)"

test_130d() {
	(( $OSTCOUNT >= 3 )) || skip "needs >= 3 OSTs"

	filefrag_op=$(filefrag -l 2>&1 | grep "invalid option")
	[[ -z "$filefrag_op" ]] || skip_env "filefrag missing logical ordering"
	[[ "$ost1_FSTYPE" != "zfs" ]] ||
		skip "LU-1941: FIEMAP unimplemented on ZFS"

	local fm_file=$DIR/$tfile
	$LFS setstripe -S 65536 -c $OSTCOUNT $fm_file ||
			error "setstripe on $fm_file"
	stack_trap "rm -f $fm_file"

	local actual_stripe_count=$($LFS getstripe -c $fm_file)
	dd if=/dev/zero of=$fm_file bs=1M count=$actual_stripe_count ||
		error "dd failed on $fm_file"

	filefrag -ves $fm_file || error "filefrag $fm_file failed"
	filefrag_op=$(filefrag -ve -k $fm_file |
		      sed -n '/ext:/,/found/{/ext:/d; /found/d; p}')

	local last_lun=$(echo $filefrag_op | cut -d: -f5 |
			 sed -e 's/^[ \t]*/0x/' | sed -e 's/0x0x/0x/')
	local tot_len=0
	local num_luns=1

	while read line; do
		local frag_lun=$(echo $line | cut -d: -f5 |
				 sed -e 's/^[ \t]*/0x/' | sed -e 's/0x0x/0x/')
		local ext_len=$(echo $line | cut -d: -f4)
		if (( $frag_lun != $last_lun )); then
			(( tot_len == 1024 )) ||
				error "OST$last_lun $tot_len != 1024"
			(( num_luns += 1 ))
			tot_len=0
		fi
		(( tot_len += ext_len ))
		last_lun=$frag_lun
	done <<< "$filefrag_op"

	(( num_luns == actual_stripe_count )) ||
		error "OST$last_lun $num_luns != $actual_stripe_count"
	(( tot_len == 1024 )) ||
		error "OST$last_lun $tot_len != 1024"

	echo "FIEMAP on N-stripe file succeeded"
}
run_test 130d "FIEMAP (N-stripe file)"

test_130e() {
	(( $OSTCOUNT >= 2 )) || skip "needs >= 2 OSTs"

	local filefrag_op=$(filefrag -l 2>&1 | grep "invalid option")
	[[ -z "$filefrag_op" ]] || skip_env "filefrag missing logical ordering"
	[[ "$ost1_FSTYPE" != "zfs" ]] ||
		skip "LU-1941: FIEMAP unimplemented on ZFS"

	local fm_file=$DIR/$tfile
	$LFS setstripe -S 131072 -c 2 $fm_file || error "setstripe on $fm_file"
	stack_trap "rm -f $fm_file"

	local num_blks=512
	local expected_len=$(( (num_blks / 2) * 64 ))
	for ((i = 0; i < $num_blks; i++)); do
		dd if=/dev/zero of=$fm_file count=1 bs=64k seek=$((2*$i)) \
			conv=notrunc > /dev/null 2>&1
	done

	filefrag -ves $fm_file || error "filefrag $fm_file failed"
	filefrag_op=$(filefrag -ve -k $fm_file |
		      sed -n '/ext:/,/found/{/ext:/d; /found/d; p}')

	local last_lun=$(echo $filefrag_op | cut -d: -f5)
	local tot_len=0
	local num_luns=1

	while read line; do
		local frag_lun=$(echo $line | cut -d: -f5)
		local ext_len=$(echo $line | cut -d: -f4)
		if (( $frag_lun != $last_lun )); then
			(( tot_len == $expected_len )) ||
				error "OST$last_lun $tot_len != $expected_len"
			(( num_luns += 1 ))
			tot_len=0
		fi
		(( tot_len += ext_len ))
		last_lun=$frag_lun
	done <<< "$filefrag_op"
	(( num_luns == 2 )) ||
		error "OST$last_lun $num_luns != 2"
	(( tot_len == $expected_len )) ||
		error "OST$last_lun $tot_len != $expected_len"

	echo "FIEMAP with continuation calls succeeded"
}
run_test 130e "FIEMAP (test continuation FIEMAP calls)"

test_130f() {
	local filefrag_op=$(filefrag -l 2>&1 | grep "invalid option")
	[[ -z "$filefrag_op" ]] || skip_env "filefrag missing logical ordering"
	[[ "$ost1_FSTYPE" != "zfs" ]] ||
		skip "LU-1941: FIEMAP unimplemented on ZFS"

	local fm_file=$DIR/$tfile
	$MULTIOP $fm_file oO_RDWR:O_CREAT:O_LOV_DELAY_CREATE:T33554432c ||
		error "multiop create with lov_delay_create on $fm_file"

	filefrag -ves $fm_file || error "filefrag $fm_file failed"
	filefrag_extents=$(filefrag -vek $fm_file |
			   awk '/extents? found/ { print $2 }')
	if (( $filefrag_extents != 0 )); then
		error "$fm_file: filefrag_extents=$filefrag_extents != 0"
	fi

	rm -f $fm_file
}
run_test 130f "FIEMAP (unstriped file)"

test_130g() {
	(( $MDS1_VERSION >= $(version_code 2.12.53) )) ||
		skip "Need MDS version with at least 2.12.53 for overstriping"
	local filefrag_op=$(filefrag -l 2>&1 | grep "invalid option")
	[[ -z "$filefrag_op" ]] || skip_env "filefrag missing logical ordering"
	[[ "$ost1_FSTYPE" != "zfs" ]] ||
		skip "LU-1941: FIEMAP unimplemented on ZFS"

	local file=$DIR/$tfile
	local nr=$((OSTCOUNT * 100))

	$LFS setstripe -C $nr -S1M $file ||
		error "failed to setstripe -C $nr $file"

	stack_trap "rm -f $file"
	dd if=/dev/zero of=$file count=$nr bs=1M
	sync
	nr=$($LFS getstripe -c $file)

	local extents=$(filefrag -v $file |
			sed -n '/ext:/,/found/{/ext:/d; /found/d; p}' | wc -l)

	echo "filefrag list $extents extents in file with stripecount $nr"
	if (( extents < nr )); then
		$LFS getstripe $file
		filefrag -v $file
		error "filefrag printed $extents < $nr extents"
	fi
}
run_test 130g "FIEMAP (overstripe file)"

test_130h() {
	(( OSTCOUNT < 2 )) && skip_env "need 2 OSTs"

	$LFS setstripe -o 0,1 -S 1M $DIR/$tfile
	$LFS getstripe $DIR/$tfile
	dd if=/dev/zero of=$DIR/$tfile bs=1M count=2
	stack_trap "rm -f $DIR/$tfile"
	$LCTL set_param ldlm.namespaces.*-OST0000-osc-*.lru_size=clear
	sleep 1
	local before=$(date +%s)
	##define OBD_FAIL_OSC_FIEMAP              0x418
	$LCTL set_param fail_loc=0x80000418 fail_val=5
	checkfiemap $DIR/$tfile $((2 * 1024 * 1024)) &
	sleep 1
	dd if=/dev/zero of=$DIR/$tfile bs=1M count=3
	wait
	$LCTL set_param fail_loc=0 fail_val=0
	# check for client eviction
	local evict=$($LCTL get_param osc.$FSNAME-OST0001-osc-f*.state |
          awk -F"[ [,]" '/EVICTED ]$/ { if (mx<$5) {mx=$5;} } END { print mx }')
	[ -z "$evict" ] || [[ $evict -le $before ]] || error "eviction happened"
}
run_test 130h "FIEMAP deadlock"

test_130i() {
	(( $MDS1_VERSION >= $(version_code 2.15.63.195) )) ||
		skip "Need MDS version at least 2.15.63.195 for DoM support"
	local filefrag_op=$(filefrag -l 2>&1 | grep "invalid option")
	[[ -z "$filefrag_op" ]] || skip_env "filefrag missing Lustre support"
	[[ "$ost1_FSTYPE" != "zfs" ]] ||
		skip "LU-1941: FIEMAP unimplemented on ZFS"

	local dom_file=$DIR/$tfile

	stack_trap "rm -f $dom_file"

	$LFS setstripe -E 1M -L mdt -E -1 -c2 -S 131072 -o1,0 $dom_file ||
		error "setstripe on $dom_file"

	local page_kb=$((PAGE_SIZE / 1024))
	# each component should be 1 MiB in size, 1/2 of it is written
	local blks=$((1024 * 3 / page_kb / 2))
	local expected=$(((blks / 3) * page_kb))

	echo "BLKS: $blks"
	echo "PAGE_SIZE: $PAGE_SIZE"
	echo "PAGE_KB: $page_kb"
	echo "EXPECTED: $expected"

	for ((i = 0; i < $blks; i++)); do
		dd if=/dev/zero of=$dom_file count=1 bs=${page_kb}k \
			seek=$((2 * i)) conv=notrunc > /dev/null 2>&1 ||
			error "dd failed to $dom_file"
	done

	filefrag -ves $dom_file | (head -7; echo ; tail -5)
	(( ! ${PIPESTATUS[0]} )) || error "filefrag $dom_file failed"

	filefrag_op=$(filefrag -ve -k $dom_file |
		      sed -n '/ext:/,/found/{/ext:/d; /found/d; p}')

	local last_lun=$(echo $filefrag_op | cut -d: -f5)
	local lun_len=0
	local num_luns=1

	while IFS=$'\n' read line; do
		local frag_lun=$(echo $line | cut -d: -f5)
		local ext_len=$(echo $line | cut -d: -f4)

		if (( $frag_lun != $last_lun )); then
			if (( lun_len != expected )); then
				error "dev #$last_lun: $lun_len != $expected"
			else
				(( num_luns += 1 ))
				lun_len=0
			fi
		fi
		(( lun_len += ext_len ))
		last_lun=$frag_lun
	done <<< "$filefrag_op"

	if (( num_luns != 3 )); then
		error "num devices: $num_luns, but 3 expected"
	fi

	echo "LUN_LEN: $lun_len"
	if (( lun_len != expected )); then
		error "dev #$last_lun: $lun_len != $expected"
	fi
	echo "FIEMAP on DoM file succeeded"
}
run_test 130i "FIEMAP (DoM file)"

# Test for writev/readv
test_131a() {
	rwv -f $DIR/$tfile -w -n 3 524288 1048576 1572864 ||
		error "writev test failed"
	rwv -f $DIR/$tfile -r -v -n 2 1572864 1048576 ||
		error "readv failed"
	rm -f $DIR/$tfile
}
run_test 131a "test iov's crossing stripe boundary for writev/readv"

test_131b() {
	local fsize=$((524288 + 1048576 + 1572864))
	rwv -f $DIR/$tfile -w -a -n 3 524288 1048576 1572864 &&
		$CHECKSTAT -t file $DIR/$tfile -s $fsize ||
			error "append writev test failed"

	((fsize += 1572864 + 1048576))
	rwv -f $DIR/$tfile -w -a -n 2 1572864 1048576 &&
		$CHECKSTAT -t file $DIR/$tfile -s $fsize ||
			error "append writev test failed"
	rm -f $DIR/$tfile
}
run_test 131b "test append writev"

test_131c() {
	rwv -f $DIR/$tfile -w -d -n 1 1048576 || return 0
	error "NOT PASS"
}
run_test 131c "test read/write on file w/o objects"

test_131d() {
	rwv -f $DIR/$tfile -w -n 1 1572864
	NOB=`rwv -f $DIR/$tfile -r -n 3 524288 524288 1048576 | awk '/error/ {print $6}'`
	if [ "$NOB" != 1572864 ]; then
		error "Short read filed: read $NOB bytes instead of 1572864"
	fi
	rm -f $DIR/$tfile
}
run_test 131d "test short read"

test_131e() {
	rwv -f $DIR/$tfile -w -s 1048576 -n 1 1048576
	rwv -f $DIR/$tfile -r -z -s 0 -n 1 524288 || \
	error "read hitting hole failed"
	rm -f $DIR/$tfile
}
run_test 131e "test read hitting hole"

check_stats() {
	local facet=$1
	local op=$2
	local want=${3:-0}
	local res

	# open             11 samples [usecs] 468 4793 13658 35791898
	case $facet in
	mds*) res=($(do_facet $facet \
		   $LCTL get_param mdt.$FSNAME-MDT0000.md_stats | grep "$op"))
		 ;;
	ost*) res=($(do_facet $facet \
		  $LCTL get_param obdfilter.$FSNAME-OST0000.stats | grep "$op"))
		 ;;
	*) error "Wrong facet '$facet'" ;;
	esac
	[[ -n "$res" ]] || error "counter for $op on $facet not incremented"
	# if $want is zero, it means any stat increment is ok.
	if (( $want > 0 )); then
		local count=${res[1]}

		if (( $count != $want )); then
			if [[ $facet =~ "mds" ]]; then
				do_nodes $(mdts_nodes) \
					$LCTL get_param mdt.*.md_stats
			else
				do_nodes $(osts_nodes) \
					$LCTL get_param obdfilter.*.stats
			fi
			error "The $op counter on $facet is $count, not $want"
		fi
	fi
}

test_133a() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_ost_nodsh && skip "remote OST with nodsh"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	do_facet $SINGLEMDS $LCTL list_param mdt.*.rename_stats ||
		skip_env "MDS doesn't support rename stats"

	local testdir=$DIR/${tdir}/stats_testdir

	mkdir_on_mdt0 $DIR/${tdir}

	# clear stats.
	do_facet $SINGLEMDS $LCTL set_param mdt.*.md_stats=clear
	do_facet ost1 $LCTL set_param obdfilter.*.stats=clear

	# verify mdt stats first.
	mkdir_on_mdt0 ${testdir} || error "mkdir_on_mdt0 failed"
	check_stats $SINGLEMDS "mkdir" 1

	# clear "open" from "lfs mkdir" above
	do_facet $SINGLEMDS $LCTL set_param mdt.*.md_stats=clear
	touch ${testdir}/${tfile} || error "touch failed"
	check_stats $SINGLEMDS "open" 1
	check_stats $SINGLEMDS "close" 1
	(( $MDS1_VERSION >= $(version_code 2.15.62) )) && {
		# open should match close
		ls -lR ${testdir}
		check_stats $SINGLEMDS "open" 2
		check_stats $SINGLEMDS "close" 2
	}
	[ $MDS1_VERSION -ge $(version_code 2.8.54) ] && {
		mknod ${testdir}/${tfile}-pipe p || error "mknod failed"
		check_stats $SINGLEMDS "mknod" 2
	}
	rm -f ${testdir}/${tfile}-pipe || error "pipe remove failed"
	check_stats $SINGLEMDS "unlink" 1
	rm -f ${testdir}/${tfile} || error "file remove failed"
	check_stats $SINGLEMDS "unlink" 2

	# remove working dir and check mdt stats again.
	rmdir ${testdir} || error "rmdir failed"
	check_stats $SINGLEMDS "rmdir" 1

	local testdir1=$DIR/${tdir}/stats_testdir1
	mkdir_on_mdt0 ${testdir}
	mkdir_on_mdt0 ${testdir1}
	touch ${testdir1}/test1
	mv ${testdir1}/test1 ${testdir} || error "file crossdir rename"
	check_stats $SINGLEMDS "crossdir_rename" 1

	mv ${testdir}/test1 ${testdir}/test0 || error "file samedir rename"
	check_stats $SINGLEMDS "samedir_rename" 1

	rm -rf $DIR/${tdir}
}
run_test 133a "Verifying MDT stats ========================================"

test_133b() {
	local res

	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_ost_nodsh && skip "remote OST with nodsh"
	remote_mds_nodsh && skip "remote MDS with nodsh"

	local testdir=$DIR/${tdir}/stats_testdir

	mkdir -p $DIR/$tdir || error "mkdir $tdir failed"
	mkdir_on_mdt0 ${testdir} || error "mkdir_on_mdt0 failed"
	touch ${testdir}/${tfile} || error "touch failed"
	cancel_lru_locks mdc

	# clear stats.
	do_facet $SINGLEMDS $LCTL set_param mdt.*.md_stats=clear
	do_facet ost1 $LCTL set_param obdfilter.*.stats=clear

	# extra mdt stats verification.
	chmod 444 ${testdir}/${tfile} || error "chmod failed"
	check_stats $SINGLEMDS "setattr" 1
	do_facet $SINGLEMDS $LCTL set_param mdt.*.md_stats=clear
	if [ $MDS1_VERSION -ne $(version_code 2.2.0) ]
	then		# LU-1740
		ls -l ${testdir}/${tfile} > /dev/null|| error "ls failed"
		check_stats $SINGLEMDS "getattr" 1
	fi
	rm -rf $DIR/${tdir}

	# when DNE is enabled, MDT uses STATFS RPC to ping other targets
	# so the check below is not reliable
	[ $MDSCOUNT -eq 1 ] || return 0

	# Sleep to avoid a cached response.
	#define OBD_STATFS_CACHE_SECONDS 1
	sleep 2
	do_facet $SINGLEMDS $LCTL set_param mdt.*.md_stats=clear
	do_facet ost1 $LCTL set_param obdfilter.*.exports.*.stats=clear
	$LFS df || error "lfs failed"
	check_stats $SINGLEMDS "statfs" 1

	# check aggregated statfs (LU-10018)
	[ $MDS1_VERSION -lt $(version_code 2.11.54) ] &&
		return 0
	[ $CLIENT_VERSION -lt $(version_code 2.11.54) ] &&
		return 0
	sleep 2
	do_facet $SINGLEMDS $LCTL set_param mdt.*.md_stats=clear
	do_facet ost1 $LCTL set_param obdfilter.*.exports.*.stats=clear
	df $DIR
	check_stats $SINGLEMDS "statfs" 1

	# We want to check that the client didn't send OST_STATFS to
	# ost1 but the MDT also uses OST_STATFS for precreate. So some
	# extra care is needed here.
	if remote_mds; then
		local nid=$($LCTL list_nids | head -1 | sed  "s/\./\\\./g")
		local param="obdfilter.$FSNAME-OST0000.exports.'$nid'.stats"

		res=$(do_facet ost1 $LCTL get_param $param | grep statfs)
		[ "$res" ] && error "OST got STATFS"
	fi

	return 0
}
run_test 133b "Verifying extra MDT stats =================================="

test_133c() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_ost_nodsh && skip "remote OST with nodsh"
	remote_mds_nodsh && skip "remote MDS with nodsh"

	local testdir=$DIR/$tdir/stats_testdir

	test_mkdir -p $testdir

	# verify obdfilter stats.
	$LFS setstripe -c 1 -i 0 $testdir/$tfile
	sync
	cancel_lru_locks osc
	wait_delete_completed

	# clear stats.
	do_facet $SINGLEMDS $LCTL set_param mdt.*.md_stats=clear
	do_facet ost1 $LCTL set_param obdfilter.*.stats=clear

	dd if=/dev/zero of=$testdir/$tfile conv=notrunc bs=512k count=1 ||
		error "dd failed"
	sync
	cancel_lru_locks osc
	check_stats ost1 "write" 1

	dd if=$testdir/$tfile of=/dev/null bs=1k count=1 || error "dd failed"
	check_stats ost1 "read" 1

	> $testdir/$tfile || error "truncate failed"
	check_stats ost1 "punch" 1

	rm -f $testdir/$tfile || error "file remove failed"
	wait_delete_completed
	check_stats ost1 "destroy" 1

	rm -rf $DIR/$tdir
}
run_test 133c "Verifying OST stats ========================================"

order_2() {
	local value=$1
	local orig=$value
	local order=1

	while [ $value -ge 2 ]; do
		order=$((order*2))
		value=$((value/2))
	done

	if [ $orig -gt $order ]; then
		order=$((order*2))
	fi
	echo $order
}

size_in_KMGT() {
    local value=$1
    local size=('K' 'M' 'G' 'T');
    local i=0
    local size_string=$value

    while [ $value -ge 1024 ]; do
        if [ $i -gt 3 ]; then
            #T is the biggest unit we get here, if that is bigger,
            #just return XXXT
            size_string=${value}T
            break
        fi
        value=$((value >> 10))
        if [ $value -lt 1024 ]; then
            size_string=${value}${size[$i]}
            break
        fi
        i=$((i + 1))
    done

    echo $size_string
}

get_rename_size() {
	local size=$1
	local context=${2:-.}
	local sample=$(do_facet $SINGLEMDS $LCTL \
		get_param mdt.$FSNAME-MDT0000.rename_stats |
		grep -A1 $context |
		awk '/ '${size}'/ {print $4}' | sed -e "s/,//g")
	echo $sample
}

test_133d() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_ost_nodsh && skip "remote OST with nodsh"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	do_facet $SINGLEMDS $LCTL list_param mdt.*.rename_stats ||
		skip_env "MDS doesn't support rename stats"

	local testdir1=$DIR/${tdir}/stats_testdir1
	local testdir2=$DIR/${tdir}/stats_testdir2
	mkdir -p $DIR/${tdir} || error "mkdir $tdir failed"

	do_facet $SINGLEMDS $LCTL set_param mdt.*.rename_stats=clear

	mkdir_on_mdt0 ${testdir1} || error "mkdir $testdir1 failed"
	mkdir_on_mdt0 ${testdir2} || error "mkdir $testdir2 failed"

	createmany -o $testdir1/test 512 || error "createmany failed"

	# check samedir rename size
	mv ${testdir1}/test0 ${testdir1}/test_0

	local testdir1_size=$(ls -l $DIR/${tdir} |
		awk '/stats_testdir1/ {print $5}')
	local testdir2_size=$(ls -l $DIR/${tdir} |
		awk '/stats_testdir2/ {print $5}')

	testdir1_size=$(order_2 $testdir1_size)
	testdir2_size=$(order_2 $testdir2_size)

	testdir1_size=$(size_in_KMGT $testdir1_size)
	testdir2_size=$(size_in_KMGT $testdir2_size)

	echo "source rename dir size: ${testdir1_size}"
	echo "target rename dir size: ${testdir2_size}"

	local cmd="do_facet $SINGLEMDS $LCTL "
	cmd+="get_param mdt.$FSNAME-MDT0000.rename_stats"

	eval $cmd || error "$cmd failed"
	local samedir=$($cmd | grep 'same_dir')
	local same_sample=$(get_rename_size $testdir1_size)
	[ -z "$samedir" ] && error "samedir_rename_size count error"
	[[ $same_sample -eq 1 ]] ||
		error "samedir_rename_size error $same_sample"
	echo "Check same dir rename stats success"

	do_facet $SINGLEMDS $LCTL set_param mdt.*.rename_stats=clear

	# check crossdir rename size
	mv ${testdir1}/test_0 ${testdir2}/test_0

	testdir1_size=$(ls -l $DIR/${tdir} |
		awk '/stats_testdir1/ {print $5}')
	testdir2_size=$(ls -l $DIR/${tdir} |
		awk '/stats_testdir2/ {print $5}')

	testdir1_size=$(order_2 $testdir1_size)
	testdir2_size=$(order_2 $testdir2_size)

	testdir1_size=$(size_in_KMGT $testdir1_size)
	testdir2_size=$(size_in_KMGT $testdir2_size)

	echo "source rename dir size: ${testdir1_size}"
	echo "target rename dir size: ${testdir2_size}"

	eval $cmd || error "$cmd failed"
	local crossdir=$($cmd | grep 'crossdir')
	local src_sample=$(get_rename_size $testdir1_size crossdir_src)
	local tgt_sample=$(get_rename_size $testdir2_size crossdir_tgt)
	[ -z "$crossdir" ] && error "crossdir_rename_size count error"
	[[ $src_sample -eq 1 ]] ||
		error "crossdir_rename_size error $src_sample"
	[[ $tgt_sample -eq 1 ]] ||
		error "crossdir_rename_size error $tgt_sample"
	echo "Check cross dir rename stats success"
	rm -rf $DIR/${tdir}
}
run_test 133d "Verifying rename_stats ========================================"

test_133e() {
	remote_mds_nodsh && skip "remote MDS with nodsh"
	remote_ost_nodsh && skip "remote OST with nodsh"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	local testdir=$DIR/${tdir}/stats_testdir
	local ctr f0 f1 bs=32768 count=42 sum

	mkdir -p ${testdir} || error "mkdir failed"

	$LFS setstripe -c 1 -i 0 ${testdir}/${tfile}

	for ctr in {write,read}_bytes; do
		sync
		cancel_lru_locks osc

		do_facet ost1 $LCTL set_param -n \
			"obdfilter.*.exports.clear=clear"

		if [ $ctr = write_bytes ]; then
			f0=/dev/zero
			f1=${testdir}/${tfile}
		else
			f0=${testdir}/${tfile}
			f1=/dev/null
		fi

		dd if=$f0 of=$f1 conv=notrunc bs=$bs count=$count || \
			error "dd failed"
		sync
		cancel_lru_locks osc

		sum=$(do_facet ost1 $LCTL get_param \
			"obdfilter.*.exports.*.stats" |
			awk -v ctr=$ctr 'BEGIN { sum = 0 }
				$1 == ctr { sum += $7 }
				END { printf("%0.0f", sum) }')

		if ((sum != bs * count)); then
			error "Bad $ctr sum, expected $((bs * count)), got $sum"
		fi
	done

	rm -rf $DIR/${tdir}
}
run_test 133e "Verifying OST {read,write}_bytes nid stats ================="

test_133f() {
	[[ $(lustre_version_code $facet) -ge $(version_code 2.7.65) ]] ||
		skip "too old lustre for get_param -R ($facet_ver)"

	# verifying readability.
	$LCTL get_param -R '*' &> /dev/null

	# Verifing writability with badarea_io.
	local proc_dirs=$(eval \ls -d $proc_regexp 2>/dev/null)
	local skipped_params='force_lbug|changelog_mask|daemon_file'
	$LCTL list_param -FR '*' | grep '=' | tr -d = |
		grep -E -v "$skipped_params" |
		xargs -n 1 find $proc_dirs -name |
		xargs -n 1 badarea_io ||
		error "client badarea_io failed"

	# remount the FS in case writes/reads /proc break the FS
	cleanup || error "failed to unmount"
	setup || error "failed to setup"
}
run_test 133f "Check reads/writes of client lustre proc files with bad area io"

test_133g() {
	remote_mds_nodsh && skip "remote MDS with nodsh"
	remote_ost_nodsh && skip "remote OST with nodsh"

	local proc_dirs=$(eval \ls -d $proc_regexp 2>/dev/null)
	local proc_dirs_str=$(eval echo $proc_dirs)
	local skipped_params="'force_lbug|daemon_file'"
	local facet
	for facet in mds1 ost1; do
		local facet_ver=$(lustre_version_code $facet)
		if [ $facet_ver -ge $(version_code 2.7.65) ]; then
			do_facet $facet "$LCTL get_param -R '*'" &> /dev/null
		else
			log "$facet: too old lustre for get_param -R"
		fi
		if [ $facet_ver -ge $(version_code 2.5.54) ]; then
			do_facet $facet "$LCTL list_param -FR '*' | grep '=' |
				tr -d = | grep -E -v $skipped_params |
				xargs -n 1 find $proc_dirs_str -name |
				xargs -n 1 badarea_io" ||
					error "$facet badarea_io failed"
		else
			skip_noexit "$facet: too old lustre for get_param -R"
		fi
	done

	# remount the FS in case writes/reads /proc break the FS
	cleanup || error "failed to unmount"
	setup || error "failed to setup"
}
run_test 133g "Check reads/writes of server lustre proc files with bad area io"

test_133h() {
	remote_mds_nodsh && skip "remote MDS with nodsh"
	remote_ost_nodsh && skip "remote OST with nodsh"
	[[ $MDS1_VERSION -lt $(version_code 2.9.54) ]] &&
		skip "Need MDS version at least 2.9.54"

	local facet
	for facet in client mds1 ost1; do
		# Get the list of files that are missing the terminating newline
		local plist=$(do_facet $facet
			$LCTL list_param -FR '*' | grep '=' | tr -d =)
		local ent
		for ent in $plist; do
			local missing=$(do_facet $facet $LCTL get_param $ent \|\
				awk -v FS='\v' -v RS='\v\v' \
				"'END { if(NR>0 && \\\$NF !~ /.*\\\n\$/) \
					print FILENAME}'" 2>/dev/null)
			[ -z $missing ] || {
				do_facet $facet $LCTL get_param $ent | od -An -tx1
				error "file does not end with newline: $facet-$ent"
			}
		done
	done
}
run_test 133h "Proc files should end with newlines"

test_134a() {
	remote_mds_nodsh && skip "remote MDS with nodsh"
	[[ $MDS1_VERSION -lt $(version_code 2.7.54) ]] &&
		skip "Need MDS version at least 2.7.54"

	mkdir_on_mdt0 $DIR/$tdir || error "failed to create $DIR/$tdir"
	cancel_lru_locks mdc

	local nsdir="ldlm.namespaces.*-MDT0000-mdc-*"
	local unused=$($LCTL get_param -n $nsdir.lock_unused_count)
	[ $unused -eq 0 ] || error "$unused locks are not cleared"

	local nr=1000
	createmany -o $DIR/$tdir/f $nr ||
		error "failed to create $nr files in $DIR/$tdir"
	unused=$($LCTL get_param -n $nsdir.lock_unused_count)

	#define OBD_FAIL_LDLM_WATERMARK_LOW     0x327
	do_facet mds1 $LCTL set_param fail_loc=0x327
	do_facet mds1 $LCTL set_param fail_val=500
	touch $DIR/$tdir/m

	echo "sleep 10 seconds ..."
	sleep 10
	local lck_cnt=$($LCTL get_param -n $nsdir.lock_unused_count)

	do_facet mds1 $LCTL set_param fail_loc=0
	do_facet mds1 $LCTL set_param fail_val=0
	[ $lck_cnt -lt $unused ] ||
		error "No locks reclaimed, before:$unused, after:$lck_cnt"

	rm $DIR/$tdir/m
	unlinkmany $DIR/$tdir/f $nr
}
run_test 134a "Server reclaims locks when reaching lock_reclaim_threshold"

test_134b() {
	remote_mds_nodsh && skip "remote MDS with nodsh"
	[[ $MDS1_VERSION -lt $(version_code 2.7.54) ]] &&
		skip "Need MDS version at least 2.7.54"

	mkdir_on_mdt0 $DIR/$tdir || error "failed to create $DIR/$tdir"
	cancel_lru_locks mdc

	local low_wm=$(do_facet mds1 $LCTL get_param -n \
			ldlm.lock_reclaim_threshold_mb)
	# disable reclaim temporarily
	do_facet mds1 $LCTL set_param ldlm.lock_reclaim_threshold_mb=0

	#define OBD_FAIL_LDLM_WATERMARK_HIGH     0x328
	do_facet mds1 $LCTL set_param fail_loc=0x328
	do_facet mds1 $LCTL set_param fail_val=500

	$LCTL set_param debug=+trace

	local nr=600
	createmany -o $DIR/$tdir/f $nr &
	local create_pid=$!

	echo "Sleep $TIMEOUT seconds ..."
	sleep $TIMEOUT
	if ! ps -p $create_pid  > /dev/null 2>&1; then
		do_facet mds1 $LCTL set_param fail_loc=0
		do_facet mds1 $LCTL set_param fail_val=0
		do_facet mds1 $LCTL set_param \
			ldlm.lock_reclaim_threshold_mb=${low_wm}m
		error "createmany finished incorrectly!"
	fi
	do_facet mds1 $LCTL set_param fail_loc=0
	do_facet mds1 $LCTL set_param fail_val=0
	do_facet mds1 $LCTL set_param ldlm.lock_reclaim_threshold_mb=${low_wm}m
	wait $create_pid || return 1

	unlinkmany $DIR/$tdir/f $nr
}
run_test 134b "Server rejects lock request when reaching lock_limit_mb"

test_134c() {
	remote_mds_nodsh && skip "remote MDS with nodsh"
	(( $MDS1_VERSION >= $(version_code 2.17.52) )) ||
		skip "Need MDS version at least 2.17.52"

	local slab=/sys/kernel/slab
	local lock_sz=$(do_facet mds1 \
		"cat $slab/ldlm_locks/object_size 2>/dev/null")
	local res_sz=$(do_facet mds1 \
		"cat $slab/ldlm_resources/object_size 2>/dev/null")
	local ibits_sz=$(do_facet mds1 \
		"cat $slab/ldlm_ibits_node/object_size 2>/dev/null")

	[[ -n "$lock_sz" && -n "$res_sz" && -n "$ibits_sz" ]] ||
		skip "slab metadata for ldlm caches unavailable"

	local overhead=$((lock_sz + res_sz + ibits_sz))

	echo "per-lock overhead: ${overhead}B" \
		"(lock=$lock_sz res=$res_sz ibits=$ibits_sz)"

	local orig_low=$(do_facet mds1 $LCTL get_param -n \
			 ldlm.lock_reclaim_threshold_mb)
	local orig_high=$(do_facet mds1 $LCTL get_param -n \
			  ldlm.lock_limit_mb)
	# kernel enforces threshold <= limit, so raise limit first on restore
	stack_trap "do_facet mds1 $LCTL set_param \
		ldlm.lock_limit_mb=$orig_high \
		ldlm.lock_reclaim_threshold_mb=$orig_low"

	local low_mb=20
	local high_mb=50
	do_facet mds1 $LCTL set_param \
		ldlm.lock_reclaim_threshold_mb=$low_mb \
		ldlm.lock_limit_mb=$high_mb

	local low=$(do_facet mds1 $LCTL get_param -n \
		    ldlm.lock_reclaim_threshold_count)
	local high=$(do_facet mds1 $LCTL get_param -n \
		     ldlm.lock_limit_count)

	(( low > 0 && high > 0 )) ||
		error "lock counters unset (low=$low high=$high)"

	# count × overhead should match the MB budget. Without the fix,
	# sizeof(ldlm_lock) alone is used and count overshoots by ~1.5x,
	# pushing the product well outside the tolerance band.
	local low_mb_actual=$((low * overhead / 1024 / 1024))
	local high_mb_actual=$((high * overhead / 1024 / 1024))
	local low_pct=$((low_mb_actual * 100 / low_mb))
	local high_pct=$((high_mb_actual * 100 / high_mb))

	echo "reclaim_threshold: $low locks ≈ ${low_mb_actual}MB" \
		"(set ${low_mb}MB, ${low_pct}%)"
	echo "lock_limit:        $high locks ≈ ${high_mb_actual}MB" \
		"(set ${high_mb}MB, ${high_pct}%)"

	(( low_pct >= 80 && low_pct <= 120 )) ||
		error "reclaim_threshold accounting off: ${low_mb_actual}MB vs ${low_mb}MB"
	(( high_pct >= 80 && high_pct <= 120 )) ||
		error "lock_limit accounting off: ${high_mb_actual}MB vs ${high_mb}MB"
}
run_test 134c "Lock memory accounting includes associated structures"

test_135() {
	remote_mds_nodsh && skip "remote MDS with nodsh"
	[[ $MDS1_VERSION -lt $(version_code 2.13.50) ]] &&
		skip "Need MDS version at least 2.13.50"
	local fname

	mkdir -p $DIR/$tdir || error "failed to create $DIR/$tdir"

#define OBD_FAIL_PLAIN_RECORDS 0x1319
	#set only one record at plain llog
	do_facet $SINGLEMDS $LCTL set_param fail_loc=0x1319 fail_val=1

	ost_set_temp_seq_width_all $DATA_SEQ_MAX_WIDTH

	#fill already existed plain llog each 64767
	#wrapping whole catalog
	createmany -o -u $DIR/$tdir/$tfile- $((64767 * 1))

	createmany -o $DIR/$tdir/$tfile_ 64700
	for (( i = 0; i < 64700; i = i + 2 ))
	do
		rm $DIR/$tdir/$tfile_$i &
		rm $DIR/$tdir/$tfile_$((i + 1)) &
		local pid=$!
		wait $pid
	done

	#waiting osp synchronization
	wait_delete_completed
}
run_test 135 "Race catalog processing"

test_136() {
	remote_mds_nodsh && skip "remote MDS with nodsh"
	[[ $MDS1_VERSION -lt $(version_code 2.13.50) ]] &&
		skip "Need MDS version at least 2.13.50"
	local fname

	mkdir -p $DIR/$tdir || error "failed to create $DIR/$tdir"
	$LFS setstripe -c 1 -i 0 $DIR/$tdir || error "failed to set striping"
	#set only one record at plain llog
#define OBD_FAIL_CATALOG_FULL_CHECK                0x131a
	do_facet $SINGLEMDS $LCTL set_param fail_loc=0x131a fail_val=1

	ost_set_temp_seq_width_all $DATA_SEQ_MAX_WIDTH

	# fill already existed 2 plain llogs each 64767 wrapping whole catalog,
	# drop server memory periodically only on ZFS to avoid OOM during test
	local items=1000
	for ((created = 0; created < 64767 * 5 / 2; created += items)); do
		echo "$(date +%s): create $created-$((created + items - 1))"
		createmany -o -u $DIR/$tdir/$tfile- $created $items
		if [[ "$mds1_FSTYPE" == "zfs" ]]; then
			wait_delete_completed
			do_facet mds1 "echo 1 > /proc/sys/vm/drop_caches"
		fi
	done
	[[ "$FSTYPE" == "zfs" ]] || wait_delete_completed

	createmany -o $DIR/$tdir/$tfile_ 10
	sleep 25

	do_facet $SINGLEMDS $LCTL set_param fail_val=3
	for (( i = 0; i < 10; i = i + 3 )); do
		rm $DIR/$tdir/$tfile_$i &
		rm $DIR/$tdir/$tfile_$((i + 1)) &
		local pid=$!
		wait $pid
		sleep 7
		rm $DIR/$tdir/$tfile_$((i + 2)) &
	done

	#waiting osp synchronization
	wait_delete_completed
}
run_test 136 "Race catalog processing 2"

test_140() { #bug-17379
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	test_mkdir $DIR/$tdir
	cd $DIR/$tdir || error "Changing to $DIR/$tdir"
	cp $(which stat) . || error "Copying stat to $DIR/$tdir"

	# VFS limits max symlink depth to 5(4KSTACK) or 7(8KSTACK) or 8
	# For kernel > 3.5, bellow only tests consecutive symlink (MAX 40)
	local i=0
	while i=$((i + 1)); do
		test_mkdir $i
		cd $i || error "Changing to $i"
		ln -s ../stat stat || error "Creating stat symlink"
		# Read the symlink until ELOOP present,
		# not LBUGing the system is considered success,
		# we didn't overrun the stack.
		$OPENFILE -f O_RDONLY stat >/dev/null 2>&1; ret=$?
		if [ $ret -ne 0 ]; then
			if [ $ret -eq 40 ]; then
				break  # -ELOOP
			else
				error "Open stat symlink"
					return
			fi
		fi
	done
	i=$((i - 1))
	echo "The symlink depth = $i"
	[ $i -eq 5 ] || [ $i -eq 7 ] || [ $i -eq 8 ] || [ $i -eq 40 ] ||
		error "Invalid symlink depth"

	# Test recursive symlink
	ln -s symlink_self symlink_self
	$OPENFILE -f O_RDONLY symlink_self >/dev/null 2>&1; ret=$?
	echo "open symlink_self returns $ret"
	[ $ret -eq 40 ] || error "recursive symlink doesn't return -ELOOP"
}
run_test 140 "Check reasonable stack depth (shouldn't LBUG) ===="

test_150a() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	local TF="$TMP/$tfile"

	stack_trap "rm -f $DIR/$tfile; wait_delete_completed"
	dd if=/dev/urandom of=$TF bs=6096 count=1 || error "dd failed"
	cp $TF $DIR/$tfile
	cancel_lru_locks $OSC
	cmp $TF $DIR/$tfile || error "$TMP/$tfile $DIR/$tfile differ"
	remount_client $MOUNT
	df -P $MOUNT
	cmp $TF $DIR/$tfile || error "$TF $DIR/$tfile differ (remount)"

	$TRUNCATE $TF 6000
	$TRUNCATE $DIR/$tfile 6000
	cancel_lru_locks $OSC
	cmp $TF $DIR/$tfile || error "$TF $DIR/$tfile differ (truncate1)"

	echo "12345" >>$TF
	echo "12345" >>$DIR/$tfile
	cancel_lru_locks $OSC
	cmp $TF $DIR/$tfile || error "$TF $DIR/$tfile differ (append1)"

	echo "12345" >>$TF
	echo "12345" >>$DIR/$tfile
	cancel_lru_locks $OSC
	cmp $TF $DIR/$tfile || error "$TF $DIR/$tfile differ (append2)"
}
run_test 150a "truncate/append tests"

test_150b() {
	check_set_fallocate_or_skip
	local out

	touch $DIR/$tfile
	stack_trap "rm -f $DIR/$tfile; wait_delete_completed"
	out=$(check_fallocate $DIR/$tfile 2>&1) ||
		skip_eopnotsupp "$out|check_fallocate failed"
}
run_test 150b "Verify fallocate (prealloc) functionality"

test_150bb() {
	check_set_fallocate_or_skip

	touch $DIR/$tfile
	stack_trap "rm -f $DIR/$tfile; wait_delete_completed"
	dd if=/dev/urandom of=$DIR/$tfile bs=1M count=20 || error "dd failed"
	> $DIR/$tfile
	fallocate -l $((1048576 * 20)) $DIR/$tfile || error "fallocate failed"
	# precomputed md5sum for 20MB of zeroes
	local expect="8f4e33f3dc3e414ff94e5fb6905cba8c"
	local sum=($(md5sum $DIR/$tfile))

	[[ "${sum[0]}" == "$expect" ]] || error "fallocate unwritten is not zero"

	check_set_fallocate 1

	> $DIR/$tfile
	fallocate -l $((1048576 * 20)) $DIR/$tfile || error "fallocate failed"
	sum=($(md5sum $DIR/$tfile))

	[[ "${sum[0]}" == "$expect" ]] || error "fallocate zero is not zero"
}
run_test 150bb "Verify fallocate modes both zero space"

test_150c() {
	check_set_fallocate_or_skip
	local striping="-c2"

	stack_trap "rm -f $DIR/$tfile; wait_delete_completed"
	$LFS setstripe -c $OSTCOUNT -S1M $DIR/$tfile || error "setstripe failed"
	fallocate -l ${OSTCOUNT}m $DIR/$tfile || error "fallocate failed"
	local bytes=$(($(stat -c '%b * %B' $DIR/$tfile)))
	local want=$((OSTCOUNT * 1048576))

	# Must allocate all requested space, not more than 5% extra
	(( $bytes >= $want && $bytes < $want * 105 / 100 )) ||
		error "bytes $bytes is not $want"

	rm -f $DIR/$tfile

	echo "verify fallocate on PFL file"

	[[ "x$DOM" == "xyes" ]] && striping="-L mdt"

	$LFS setstripe -E1M $striping -E16M -c3 -Eeof -c 4 $DIR/$tfile ||
		error "Create $DIR/$tfile failed"
	fallocate -l $((1048576 * 512)) $DIR/$tfile || error "fallocate failed"
	bytes=$(($(stat -c '%b * %B' $DIR/$tfile)))
	want=$((512 * 1048576))

	# Must allocate all requested space, not more than 5% extra
	(( $bytes >= $want && $bytes < $want * 105 / 100 )) ||
		error "bytes $bytes is not $want"
}
run_test 150c "Verify fallocate Size and Blocks"

test_150d() {
	check_set_fallocate_or_skip
	local striping="-c2"

	[[ "x$DOM" == "xyes" ]] && striping="-L mdt"

	stack_trap "rm -f $DIR/$tdir; wait_delete_completed"
	$LFS setstripe -E1M $striping -E eof -c $OSTCOUNT -S1M $DIR/$tdir ||
		error "setstripe failed"
	fallocate -o 1G -l ${OSTCOUNT}m $DIR/$tdir || error "fallocate failed"
	local bytes=$(($(stat -c '%b * %B' $DIR/$tdir)))
	local want=$((OSTCOUNT * 1048576))

	# Must allocate all requested space, not more than 5% extra
	(( $bytes >= $want && $bytes < $want * 105 / 100 )) ||
		error "bytes $bytes is not $want"
}
run_test 150d "Verify fallocate Size and Blocks - Non zero start"

test_150e() {
	check_set_fallocate_or_skip

	echo "df before:"
	$LFS df
	stack_trap "rm -f $DIR/$tfile; wait_delete_completed"
	$LFS setstripe -c${OSTCOUNT} $DIR/$tfile ||
		error "$LFS setstripe -c${OSTCOUNT} $DIR/$tfile failed"

	# Find OST with Minimum Size
	min_size_ost=$($LFS df --output=avail -o --no-header $DIR |
		       sort -un | head -1)

	# Get 100MB per OST of the available space to reduce run time
	# else 60% of the available space if we are running SLOW tests
	if [ $SLOW == "no" ]; then
		local space=$((1024 * 100 * OSTCOUNT))
	else
		local space=$(((min_size_ost * 60)/100 * OSTCOUNT))
	fi

	fallocate -l${space}k $DIR/$tfile ||
		error "fallocate ${space}k $DIR/$tfile failed"
	echo "'fallocate -l ${space}k $DIR/$tfile' succeeded"

	# get size immediately after fallocate. This should be correctly
	# updated
	local size=$(stat -c '%s' $DIR/$tfile)
	local used=$(( $(stat -c '%b * %B' $DIR/$tfile) / 1024))

	# Sleep for a while for statfs to get updated. And not pull from cache.
	sleep 2

	echo "df after fallocate:"
	$LFS df

	(( size / 1024 == space )) || error "size $size != requested $space"
	[ "$ost1_FSTYPE" != ldiskfs ] || (( used >= space )) ||
		error "used $used < space $space"

	rm $DIR/$tfile || error "rm failed"
	sync
	wait_delete_completed

	echo "df after unlink:"
	$LFS df
}
run_test 150e "Verify 60% of available OST space consumed by fallocate"

test_150f() {
	local size
	local blocks
	local want_size_before=20480 # in bytes
	local want_blocks_before=40 # 512 sized blocks
	local want_blocks_after=24  # 512 sized blocks
	local length=$(((want_blocks_before - want_blocks_after) * 512))

	[[ $OST1_VERSION -ge $(version_code 2.14.0) ]] ||
		skip "need at least 2.14.0 for fallocate punch"

	if [ "$ost1_FSTYPE" = "zfs" ] || [ "$mds1_FSTYPE" = "zfs" ]; then
		skip "LU-14160: punch mode is not implemented on OSD ZFS"
	fi

	check_set_fallocate_or_skip
	stack_trap "rm -f $DIR/$tfile; wait_delete_completed"

	[[ "x$DOM" == "xyes" ]] &&
		$LFS setstripe -E1M -L mdt -E eof $DIR/$tfile

	echo "Verify fallocate punch: Range within the file range"
	yes 'A' | dd of=$DIR/$tfile bs=4096 count=5 ||
		error "dd failed for bs 4096 and count 5"

	# Call fallocate with punch range which is within the file range
	out=$(fallocate -p --offset 4096 -l $length $DIR/$tfile 2>&1) ||
		skip_eopnotsupp "$out|fallocate: offset 4096 and length $length"
	# client must see changes immediately after fallocate
	size=$(stat -c '%s' $DIR/$tfile)
	blocks=$(stat -c '%b' $DIR/$tfile)

	# Verify punch worked.
	(( blocks == want_blocks_after )) ||
		error "punch failed: blocks $blocks != $want_blocks_after"

	(( size == want_size_before )) ||
		error "punch failed: size $size != $want_size_before"

	# Verify there is hole in file
	local data_off=$(lseek_test -d 4096 $DIR/$tfile)
	# precomputed md5sum
	local expect="4a9a834a2db02452929c0a348273b4aa"

	cksum=($(md5sum $DIR/$tfile))
	[[ "${cksum[0]}" == "$expect" ]] ||
		error "unexpected MD5SUM after punch: ${cksum[0]}"

	# Start second sub-case for fallocate punch.
	echo "Verify fallocate punch: Range overlapping and less than blocksize"
	yes 'A' | dd of=$DIR/$tfile bs=4096 count=5 ||
		error "dd failed for bs 4096 and count 5"

	# Punch range less than block size will have no change in block count
	want_blocks_after=40  # 512 sized blocks

	# Punch overlaps two blocks and less than blocksize
	out=$(fallocate -p --offset 4000 -l 3000 $DIR/$tfile 2>&1) ||
		skip_eopnotsupp "$out|fallocate: offset 4000 length 3000"
	size=$(stat -c '%s' $DIR/$tfile)
	blocks=$(stat -c '%b' $DIR/$tfile)

	# Verify punch worked.
	(( blocks == want_blocks_after )) ||
		error "punch failed: blocks $blocks != $want_blocks_after"

	(( size == want_size_before )) ||
		error "punch failed: size $size != $want_size_before"

	# Verify if range is really zero'ed out. We expect Zeros.
	# precomputed md5sum
	expect="c57ec5d769c3dbe3426edc3f7d7e11d3"
	cksum=($(md5sum $DIR/$tfile))
	[[ "${cksum[0]}" == "$expect" ]] ||
		error "unexpected MD5SUM after punch: ${cksum[0]}"
}
run_test 150f "Verify fallocate punch functionality"

test_150g() {
	local space
	local size
	local blocks
	local blocks_after
	local size_after
	local BS=4096 # Block size in bytes

	[[ $OST1_VERSION -ge $(version_code 2.14.0) ]] ||
		skip "need at least 2.14.0 for fallocate punch"

	if [ "$ost1_FSTYPE" = "zfs" ] || [ "$mds1_FSTYPE" = "zfs" ]; then
		skip "LU-14160: punch mode is not implemented on OSD ZFS"
	fi

	check_set_fallocate_or_skip
	stack_trap "rm -f $DIR/$tfile; wait_delete_completed"

	if [[ "x$DOM" == "xyes" ]]; then
		$LFS setstripe -E2M -L mdt -E eof -c${OSTCOUNT} $DIR/$tfile ||
			error "$LFS setstripe DoM + ${OSTCOUNT} OST failed"
	else
		$LFS setstripe -c${OSTCOUNT} $DIR/$tfile ||
			error "$LFS setstripe -c${OSTCOUNT} $DIR/$tfile failed"
	fi

	# Get 100MB per OST of the available space to reduce run time
	# else 60% of the available space if we are running SLOW tests
	if [ $SLOW == "no" ]; then
		space=$((1024 * 100 * OSTCOUNT))
	else
		# Find OST with Minimum Size
		space=$($LFS df --output=avail --no-header -o $DIR |
			sort -un | head -1)
		echo "min size OST: $space"
		space=$(((space * 60)/100 * OSTCOUNT))
	fi
	# space in 1k units, round to 4k blocks
	local blkcount=$((space * 1024 / $BS))

	echo "Verify fallocate punch: Very large Range"
	fallocate -l${space}k $DIR/$tfile ||
		error "fallocate ${space}k $DIR/$tfile failed"
	# write 1M at the end, start and in the middle
	yes 'A' | dd of=$DIR/$tfile bs=$BS count=256 ||
		error "dd failed: bs $BS count 256"
	yes 'A' | dd of=$DIR/$tfile bs=$BS seek=$((blkcount - 256)) count=256 ||
		error "dd failed: bs $BS count 256 seek $((blkcount - 256))"
	yes 'A' | dd of=$DIR/$tfile bs=$BS seek=$((blkcount / 2)) count=1024 ||
		error "dd failed: bs $BS count 256 seek $((blkcount / 2))"

	# Gather stats.
	size=$(stat -c '%s' $DIR/$tfile)

	# gather punch length.
	local punch_size=$((size - (BS * 2)))

	echo "punch_size = $punch_size"
	echo "size - punch_size: $((size - punch_size))"
	echo "size - punch_size in blocks: $(((size - punch_size)/BS))"

	# Call fallocate to punch all except 2 blocks. We leave the
	# first and the last block
	echo "fallocate -p --offset $BS -l $punch_size $DIR/$tfile"
	out=$(fallocate -p --offset $BS -l $punch_size $DIR/$tfile 2>&1) ||
		skip_eopnotsupp "$out|fallocate: offset $BS length $punch_size"

	size_after=$(stat -c '%s' $DIR/$tfile)
	blocks_after=$(stat -c '%b' $DIR/$tfile)

	# Verify punch worked.
	# Size should be kept
	(( size == size_after )) ||
		error "punch failed: size $size != $size_after"

	# two 4k data blocks to remain plus possible 1 extra extent block
	(( blocks_after <= ((BS / 512) * 3) )) ||
		error "too many blocks remains: $blocks_after"

	# Verify that file has hole between the first and the last blocks
	local hole_start=$(lseek_test -l 0 $DIR/$tfile)
	local hole_end=$(lseek_test -d $BS $DIR/$tfile)

	echo "Hole at [$hole_start, $hole_end)"
	(( hole_start == BS )) ||
		error "no hole at offset $BS after punch"

	(( hole_end == BS + punch_size )) ||
		error "data at offset $hole_end < $((BS + punch_size))"
}
run_test 150g "Verify fallocate punch on large range"

test_150h() {
	local file=$DIR/$tfile
	local size

	check_set_fallocate_or_skip
	statx_supported || skip_env "Test must be statx() syscall supported"

	# fallocate() does not update the size information on the MDT
	fallocate -l 16K $file || error "failed to fallocate $file"
	cancel_lru_locks $OSC
	# STATX with cached-always mode will not send glimpse RPCs to OST,
	# it uses the caching attrs on the client side as much as possible.
	size=$($STATX --cached=always -c %s $file)
	[ $size == 16384 ] ||
		error "size after fallocate() is $size, expected 16384"
}
run_test 150h "Verify extend fallocate updates the file size"

test_150ia() {
	(( $MDS1_VERSION >= $(version_code 2.16.50) )) ||
		skip "need MDS1 version >= 2.16.50 for falloc zero-range"

	if [[ "$ost1_FSTYPE" = "zfs" || "$mds1_FSTYPE" = "zfs" ]]; then
		skip "zero-range mode is not implemented on OSD ZFS"
	fi

	check_set_fallocate_or_skip
	stack_trap "rm -f $DIR/$tfile; wait_delete_completed"

	[[ "$DOM" == "yes" ]] &&
		$LFS setstripe -E1M -L mdt -E eof $DIR/$tfile

	local BLOCK_SIZE=65536
	echo "Verify fallocate(zero): range within the file"
	yes 'A' | dd of=$DIR/$tfile bs=$BLOCK_SIZE count=8 iflag=fullblock ||
		error "dd failed for bs $BLOCK_SIZE and count 8"

	# zero range page aligned
	local offset=$((2 * BLOCK_SIZE))
	local length=$((4 * BLOCK_SIZE))
	out=$(fallocate -z --offset $offset -l $length $DIR/$tfile 2>&1) ||
		skip_eopnotsupp "$out|falloc(zero): off $offset, len $length"

	# precomputed md5sum
	local expect="879e6c3bf37da2014adda326c8d5db73"
	cksum=($(md5sum $DIR/$tfile))
	[[ "${cksum[0]}" == "$expect" ]] ||
		error "unexpected MD5SUM after zero: ${cksum[0]}"

	# zero range partial page
	local offset=2000
	local length=1000
	out=$(fallocate -z --offset $offset -l $length $DIR/$tfile 2>&1) ||
		skip_eopnotsupp "$out|falloc(zero): off $offset, len $length"

	expect="2ff89a843b5a656ca21036a2472a0aac"
	cksum=($(md5sum $DIR/$tfile))
	[[ "${cksum[0]}" == "$expect" ]] ||
		error "unexpected MD5SUM after zero(partial): ${cksum[0]}"
}
run_test 150ia "Verify fallocate zero-range ZERO functionality"

test_150ib() {
	(( $MDS1_VERSION >= $(version_code v2_17_50-71-g2cbe29c282) )) ||
		skip "need MDS1 version >= 2.17.50 for falloc zero-range"

	if [[ "$ost1_FSTYPE" = "zfs" || "$mds1_FSTYPE" = "zfs" ]]; then
		skip "zero-range mode is not implemented on OSD ZFS"
	fi

	check_set_fallocate_or_skip
	stack_trap "rm -f $DIR/$tfile; wait_delete_completed"

	[[ "$DOM" == "yes" ]] &&
		$LFS setstripe -E1M -L mdt -E eof $DIR/$tfile

	local features=$(do_facet mds1 "$DEBUGFS -c -R stats $(mdsdevname 1)" |
			 grep "Filesystem features:")
	echo "filesystem features: $features"

	# Allow one 4K extent metadata block beyond the data blocks.
	local blocks_after_zero_fill_min=$((8 * PAGE_SIZE / 512))
	local blocks_after_zero_fill_max=$((8 * PAGE_SIZE / 512 + 8))
	local blocks_after_extend_min=$((16 * PAGE_SIZE / 512))
	local blocks_after_extend_max=$((16 * PAGE_SIZE / 512 + 8))
	local expect_len=$((8 * PAGE_SIZE))

	# file size [0, 32K)
	echo "Verify fallocate(zero): range within the file"
	yes 'A' | dd of=$DIR/$tfile bs=$PAGE_SIZE count=8 ||
		error "dd failed for bs $PAGE_SIZE and count 8"

	# punch across [8K,24K)
	local offset=$((2 * PAGE_SIZE))
	local length=$((4 * PAGE_SIZE))
	out=$(fallocate -p --offset $offset -l $length $DIR/$tfile 2>&1) ||
		skip_eopnotsupp "$out|falloc(zero): off $offset, len $length"
	# Verify punch worked as expected
	p=$(lseek_test -l 0 $DIR/$tfile)
	(( p == offset )) ||
		error "punch failed: hole at $p != $offset"
	p=$(lseek_test -d $offset $DIR/$tfile)
	(( p == offset + length )) ||
		error "punch failed: data at $p != $((offset + length))"

	# zero prealloc fill the hole just punched
	out=$(fallocate -z --offset $offset -l $length $DIR/$tfile 2>&1) ||
		skip_eopnotsupp "$out|falloc(zero): off $offset, len $length"
	# Verify zero prealloc worked.
	blocks=$(stat -c '%b' $DIR/$tfile)
	(( blocks >= blocks_after_zero_fill_min &&
	   blocks <= blocks_after_zero_fill_max )) ||
		error "zero prealloc failed:$blocks not in [$blocks_after_zero_fill_min,$blocks_after_zero_fill_max]"

	# zero prealloc with KEEP_SIZE on
	offset=$((8 * PAGE_SIZE))
	length=$((8 * PAGE_SIZE))
	out=$(fallocate -z -n --offset $offset -l $length $DIR/$tfile 2>&1) ||
		skip_eopnotsupp "$out|falloc(zero): off $offset, len $length"
	# block allocate, size remains
	blocks=$(stat -c '%b' $DIR/$tfile)
	(( blocks >= blocks_after_extend_min &&
	   blocks <= blocks_after_extend_max )) ||
		error "extend failed:$blocks not in [$blocks_after_extend_min,$blocks_after_extend_max]"
	lsz=$(stat -c '%s' $DIR/$tfile)
	(( lsz == expect_len)) ||
		error "zero extend failed(len):$lsz!=$expect_len"
}
run_test 150ib "Verify fallocate zero-range PREALLOC functionality"

test_150ic() {
	(( $MDS1_VERSION >= $(version_code 2.16.54) )) ||
		skip "need MDS1 version >= 2.16.54 for falloc zero-range"

	if [[ "$ost1_FSTYPE" = "zfs" || "$mds1_FSTYPE" = "zfs" ]]; then
		skip "zero-range mode is not implemented on OSD ZFS"
	fi

	[[ "$DOM" == "yes" ]] ||
		skip "only check on DoM component"
	check_set_fallocate_or_skip

	# set a larger dom-size for test
	local MB1=1048576
	local mdtname=${FSNAME}-MDT0000-mdtlov
	local dom_limit_saved=$(do_facet mds1 $LCTL get_param -n \
						lod.$mdtname.dom_stripesize)
	local dom_limit=$((256 * MB1))
	do_facet mds1 $LCTL set_param -n \
		lod.$mdtname.dom_stripesize=$dom_limit
	stack_trap "do_facet mds1 $LCTL set_param -n \
		lod.$mdtname.dom_stripesize=$dom_limit_saved"
	stack_trap "rm -f $DIR/$tfile; wait_delete_completed"

	echo "Verify fallocate zero-range: range extending the file"
	$LFS setstripe -E 256M -L mdt -E eof $DIR/$tfile ||
		error "$LFS setstripe DoM failed"
	# now let's extend the range to [0, 128M), to trigger BRWs
	local offset=0
	local length=$((128 * MB1))

	touch $DIR/$tfile
	out=$(fallocate -z --offset $offset -l $length $DIR/$tfile 2>&1) ||
		skip_eopnotsupp "$out|fallocate: offset $offset and len $length"

	local features=$(do_facet mds1 "$DEBUGFS -c -R stats $(mdsdevname 1)" |
			grep "Filesystem features:")

	# Verify zero prealloc worked.
	local blocks=$(stat -c '%b' $DIR/$tfile)

	if [[ "$features" == *extent* ]]; then
		local want_blocks=$((128 * MB1 / 512))
		(( blocks >= want_blocks && blocks <= want_blocks + 16 * 8 )) ||
			error "zero prealloc failed:$blocks!=$want_blocks"
	else
		# Given per block 4KB size, per index block could hold
		# 1024 block index. 128MB needs data block 32768,
		# index block 1(L2) + 32(L1)
		local want_blocks=$((128 * MB1 / 512 + 33 * 8))
		(( blocks == want_blocks )) ||
			error "zero prealloc failed:$blocks!=$want_blocks"
	fi

	local expect="fde9e0818281836e4fc0edfede2b8762"
	local cksum=($(md5sum $DIR/$tfile))
	[[ "${cksum[0]}" == "$expect" ]] ||
		error "unexpected MD5SUM after fallo(large-zero): ${cksum[0]}"
}
run_test 150ic "Verify fallocate LARGE zero PREALLOC functionality"

#LU-2902 roc_hit was not able to read all values from lproc
function roc_hit_init() {
	local osts=${1:-$(osts_nodes)}
	local dir=$DIR/$tdir-check
	local file=$dir/$tfile
	local BEFORE
	local AFTER
	local idx

	test_mkdir $dir
	#use setstripe to do a write to every ost
	for ((i=0; i < OSTCOUNT; i++)); do
		$LFS setstripe -c 1 -i $i $dir || error "$LFS setstripe $file failed"
		dd if=/dev/urandom of=$file bs=4k count=4 2>&1 > /dev/null
		idx=$(printf %04x $i)
		BEFORE=$(get_osd_param $osts *OST$idx stats |
			awk '$1 == "cache_access" {sum += $7}
				END { printf("%0.0f", sum) }')

		cancel_lru_locks osc
		cat $file >/dev/null

		AFTER=$(get_osd_param $osts *OST$idx stats |
			awk '$1 == "cache_access" {sum += $7}
				END { printf("%0.0f", sum) }')

		echo BEFORE:$BEFORE AFTER:$AFTER
		if ! let "AFTER - BEFORE == 4"; then
			rm -rf $dir
			error "roc_hit is not safe to use"
		fi
		rm $file
	done

	rm -rf $dir
}

function roc_hit() {
	local osts=${1:-$(osts_nodes)}

	echo $(get_osd_param $osts '' stats |
		awk '$1 == "cache_hit" {sum += $7}
			END { printf("%0.0f", sum) }')
}

function set_cache() {
	local osts=$1
	local type=$2
	local param=$3
	local on=1

	if [ "$param" == "off" ]; then
		on=0;
	fi
	set_osd_param $osts '' ${type}_cache_enable $on

	cancel_lru_locks osc
}

test_151() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_ost_nodsh && skip "remote OST with nodsh"
	(( CLIENT_VERSION == OST1_VERSION )) ||
		skip "LU-13081: no interop testing for OSS cache"

	local CPAGES=3
	local osts=$(osts_nodes)

	# check whether obdfilter is cache capable at all
	if ! get_osd_param $osts '' read_cache_enable >/dev/null; then
		skip "not cache-capable obdfilter"
	fi

	# check cache is enabled on all obdfilters
	if get_osd_param $osts '' read_cache_enable | grep 0; then
		skip "oss cache is disabled"
	fi

	set_osd_param $osts '' writethrough_cache_enable 1

	# check write cache is enabled on all obdfilters
	if get_osd_param $osts '' writethrough_cache_enable | grep 0; then
		skip "oss write cache is NOT enabled"
	fi

	roc_hit_init $osts

	#define OBD_FAIL_OBD_NO_LRU  0x609
	do_nodes $osts $LCTL set_param fail_loc=0x609

	# pages should be in the case right after write
	dd if=/dev/urandom of=$DIR/$tfile bs=4k count=$CPAGES ||
		error "dd failed"

	local BEFORE=$(roc_hit $osts)
	cancel_lru_locks osc
	cat $DIR/$tfile >/dev/null
	local AFTER=$(roc_hit $osts)

	do_nodes $osts $LCTL set_param fail_loc=0

	if ! let "AFTER - BEFORE == CPAGES"; then
		error "NOT IN CACHE: before: $BEFORE, after: $AFTER"
	fi

	cancel_lru_locks osc
	# invalidates OST cache
	do_nodes $osts "echo 1 > /proc/sys/vm/drop_caches"
	set_osd_param $osts '' read_cache_enable 0
	cat $DIR/$tfile >/dev/null

	# now data shouldn't be found in the cache
	BEFORE=$(roc_hit $osts)
	cancel_lru_locks osc
	cat $DIR/$tfile >/dev/null
	AFTER=$(roc_hit $osts)
	if let "AFTER - BEFORE != 0"; then
		error "IN CACHE: before: $BEFORE, after: $AFTER"
	fi

	set_osd_param $osts '' read_cache_enable 1
	rm -f $DIR/$tfile
}
run_test 151 "test cache on oss and controls ==============================="

test_152() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	local TF="$TMP/$tfile"

	# simulate ENOMEM during write
#define OBD_FAIL_OST_NOMEM      0x226
        lctl set_param fail_loc=0x80000226
        dd if=/dev/urandom of=$TF bs=6096 count=1 || error "dd failed"
        cp $TF $DIR/$tfile
        sync || error "sync failed"
        lctl set_param fail_loc=0

        # discard client's cache
        cancel_lru_locks osc

        # simulate ENOMEM during read
        lctl set_param fail_loc=0x80000226
        cmp $TF $DIR/$tfile || error "cmp failed"
        lctl set_param fail_loc=0

        rm -f $TF
}
run_test 152 "test read/write with enomem ============================"

test_153() {
        $MULTIOP $DIR/$tfile Ow4096Ycu || error "multiop failed"
}
run_test 153 "test if fdatasync does not crash ======================="

dot_lustre_fid_permission_check() {
	local fid=$1
	local ffid=$MOUNT/.lustre/fid/$fid
	local test_dir=$2

	echo "stat fid $fid"
	stat $ffid || error "stat $ffid failed."
	echo "touch fid $fid"
	touch $ffid || error "touch $ffid failed."
	echo "write to fid $fid"
	cat /etc/hosts > $ffid || error "write $ffid failed."
	echo "read fid $fid"
	diff /etc/hosts $ffid || error "read $ffid failed."
	echo "append write to fid $fid"
	cat /etc/hosts >> $ffid || error "append write $ffid failed."
	echo "rename fid $fid"
	mv $ffid $test_dir/$tfile.1 &&
		error "rename $ffid to $tfile.1 should fail."
	touch $test_dir/$tfile.1
	mv $test_dir/$tfile.1 $ffid &&
		error "rename $tfile.1 to $ffid should fail."
	rm -f $test_dir/$tfile.1
	echo "truncate fid $fid"
	$TRUNCATE $ffid 777 || error "truncate $ffid failed."
	echo "link fid $fid"
	ln -f $ffid $test_dir/tfile.lnk || error "link $ffid failed."
	if [[ $($LCTL get_param -n mdc.*-mdc-*.connect_flags) =~ acl ]]; then
		id $USER0 || skip_env "missing user $USER0"
		echo "setfacl fid $fid"
		setfacl -R -m u:$USER0:rwx $ffid ||
			error "setfacl $ffid failed"
		echo "getfacl fid $fid"
		getfacl $ffid || error "getfacl $ffid failed."
	fi
	echo "unlink fid $fid"
	unlink $MOUNT/.lustre/fid/$fid && error "unlink $ffid should fail."
	echo "mknod fid $fid"
	mknod $ffid c 1 3 && error "mknod $ffid should fail."

	fid=[0xf00000400:0x1:0x0]
	ffid=$MOUNT/.lustre/fid/$fid

	echo "stat non-exist fid $fid"
	stat $ffid > /dev/null && error "stat non-exist $ffid should fail."
	echo "write to non-exist fid $fid"
	cat /etc/hosts > $ffid && error "write non-exist $ffid should fail."
	echo "link new fid $fid"
	ln $test_dir/$tfile $ffid && error "link $ffid should fail."

	mkdir -p $test_dir/$tdir
	touch $test_dir/$tdir/$tfile
	fid=$($LFS path2fid $test_dir/$tdir)
	rc=$?
	[ $rc -ne 0 ] &&
		error "error: could not get fid for $test_dir/$dir/$tfile."

	ffid=$MOUNT/.lustre/fid/$fid

	echo "ls $fid"
	ls $ffid || error "ls $ffid failed."
	echo "touch $fid/$tfile.1"
	touch $ffid/$tfile.1 || error "touch $ffid/$tfile.1 failed."

	echo "touch $MOUNT/.lustre/fid/$tfile"
	touch $MOUNT/.lustre/fid/$tfile && \
		error "touch $MOUNT/.lustre/fid/$tfile should fail."

	echo "setxattr to $MOUNT/.lustre/fid"
	setfattr -n trusted.name1 -v value1 $MOUNT/.lustre/fid

	echo "listxattr for $MOUNT/.lustre/fid"
	getfattr -d -m "^trusted" $MOUNT/.lustre/fid

	echo "delxattr from $MOUNT/.lustre/fid"
	setfattr -x trusted.name1 $MOUNT/.lustre/fid

	echo "touch invalid fid: $MOUNT/.lustre/fid/[0x200000400:0x2:0x3]"
	touch $MOUNT/.lustre/fid/[0x200000400:0x2:0x3] &&
		error "touch invalid fid should fail."

	echo "touch non-normal fid: $MOUNT/.lustre/fid/[0x1:0x2:0x0]"
	touch $MOUNT/.lustre/fid/[0x1:0x2:0x0] &&
		error "touch non-normal fid should fail."

	echo "rename $tdir to $MOUNT/.lustre/fid"
	mrename $test_dir/$tdir $MOUNT/.lustre/fid &&
		error "rename to $MOUNT/.lustre/fid should fail."

	if [ $MDS1_VERSION -ge $(version_code 2.3.51) ]
	then		# LU-3547
		local old_obf_mode=$(stat --format="%a" $DIR/.lustre/fid)
		local new_obf_mode=777

		echo "change mode of $DIR/.lustre/fid to $new_obf_mode"
		chmod $new_obf_mode $DIR/.lustre/fid ||
			error "chmod $new_obf_mode $DIR/.lustre/fid failed"

		local obf_mode=$(stat --format=%a $DIR/.lustre/fid)
		[ $obf_mode -eq $new_obf_mode ] ||
			error "stat $DIR/.lustre/fid returned wrong mode $obf_mode"

		echo "restore mode of $DIR/.lustre/fid to $old_obf_mode"
		chmod $old_obf_mode $DIR/.lustre/fid ||
			error "chmod $old_obf_mode $DIR/.lustre/fid failed"
	fi

	$OPENFILE -f O_LOV_DELAY_CREATE:O_CREAT $test_dir/$tfile-2
	fid=$($LFS path2fid $test_dir/$tfile-2)

	if [ $MDS1_VERSION -ge $(version_code 2.6.50) ]
	then # LU-5424
		echo "cp /etc/passwd $MOUNT/.lustre/fid/$fid"
		cp /etc/passwd $MOUNT/.lustre/fid/$fid ||
			error "create lov data thru .lustre failed"
	fi
	echo "cp /etc/passwd $test_dir/$tfile-2"
	cp /etc/passwd $test_dir/$tfile-2 ||
		error "copy to $test_dir/$tfile-2 failed."
	echo "diff /etc/passwd $MOUNT/.lustre/fid/$fid"
	diff /etc/passwd $MOUNT/.lustre/fid/$fid ||
		error "diff /etc/passwd $MOUNT/.lustre/fid/$fid failed."

	rm -rf $test_dir/tfile.lnk
	rm -rf $test_dir/$tfile-2
}

test_154A() {
	[[ $MDS1_VERSION -lt $(version_code 2.4.1) ]] &&
		skip "Need MDS version at least 2.4.1"

	local tf=$DIR/$tfile
	touch $tf

	local fid=$($LFS path2fid $tf)
	[ -z "$fid" ] && error "path2fid unable to get $tf FID"

	# check that we get the same pathname back
	local rootpath
	local found
	for rootpath in "$MOUNT" "$MOUNT///" "$MOUNT/$tfile"; do
		echo "$rootpath $fid"
		found=$($LFS fid2path $rootpath "$fid")
		[ -z "$found" ] && error "fid2path unable to get '$fid' path"
		[ "$found" == "$tf" ] || error "fid2path $found != $tf"
	done

	# check wrong root path format
	rootpath=$MOUNT"_wrong"
	found=$($LFS fid2path $rootpath "$fid")
	[ -z "$found" ] || error "should fail ($rootpath != $MOUNT)"
}
run_test 154A "lfs path2fid and fid2path basic checks"

test_154B() {
	[[ $MDS1_VERSION -lt $(version_code 2.4.1) ]] &&
		skip "Need MDS version at least 2.4.1"

	mkdir -p $DIR/$tdir || error "mkdir $tdir failed"
	touch $DIR/$tdir/$tfile || error "touch $DIR/$tdir/$tfile failed"
	local linkea=$($LL_DECODE_LINKEA $DIR/$tdir/$tfile | grep 'pfid')
	[ -z "$linkea" ] && error "decode linkea $DIR/$tdir/$tfile failed"

	local name=$(echo $linkea | awk '/pfid/ {print $5}' | sed -e "s/'//g")
	local PFID=$(echo $linkea | awk '/pfid/ {print $3}' | sed -e "s/,//g")

	# check that we get the same pathname
	echo "PFID: $PFID, name: $name"
	local FOUND=$($LFS fid2path $MOUNT "$PFID")
	[ -z "$FOUND" ] && error "fid2path unable to get $PFID path"
	[ "$FOUND/$name" != "$DIR/$tdir/$tfile" ] &&
		error "ll_decode_linkea has $FOUND/$name != $DIR/$tdir/$tfile"

	rm -rf $DIR/$tdir || error "Can not delete directory $DIR/$tdir"
}
run_test 154B "verify the ll_decode_linkea tool"

test_154C() {
	(( $MDS1_VERSION >= $(version_code 2.16.54) )) ||
		skip "need MDS1 version >= 2.16.54 for OST FID lookup"
	(( $OSTCOUNT >= 2 )) || skip_env "needs >= 2 OSTs"

	local tf=$DIR/$tfile
	$LFS setstripe -c2 -i0 -S1M $tf
	dd if=/dev/zero of=$tf bs=1M count=8

	stack_trap "rm -rf $tf; wait_delete_completed"

	local stripe_info=$($LFS getstripe $tf)
	# for each OST object, execute fid2path
	while read -r lfid ofid; do
		# keep only valid lines to parse
		[[ "$lfid" == "l_fid:" ]] || continue

		found=$($LFS fid2path "$MOUNT" "$ofid")
		echo "ost_fid=$ofid with outpath=$found"
		[[ -n "$found" ]] ||
			error "fid2path failed on $ofid"
		[[ "$found" == "$tf" ]] || error "fid2path $found != $tf"
	done < <($LFS getstripe -y $tf)
}
run_test 154C "lfs fid2path on OST FID"

test_154a() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ -n "$FILESET" ] && skip "SKIP due to FILESET set"
	(( $MDS1_VERSION >= $(version_code 2.2.51) )) ||
		skip "Need MDS version at least 2.2.51"
	[ -z "$(which setfacl)" ] && skip_env "must have setfacl tool"

	cp /etc/hosts $DIR/$tfile

	fid=$($LFS path2fid $DIR/$tfile)
	rc=$?
	[ $rc -ne 0 ] && error "error: could not get fid for $DIR/$tfile."

	dot_lustre_fid_permission_check "$fid" $DIR ||
		error "dot lustre permission check $fid failed"

	ls -a $MOUNT | grep "\.lustre" && error ".lustre should not be listed"

	rm -rf $MOUNT/.lustre && error ".lustre is not allowed to be unlinked"

	touch $MOUNT/.lustre/file &&
		error "creation is not allowed under .lustre"

	mkdir $MOUNT/.lustre/dir &&
		error "mkdir is not allowed under .lustre"

	rm -rf $DIR/$tfile
}
run_test 154a "Open-by-FID"

test_154b() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ -n "$FILESET" ] && skip "SKIP due to FILESET set"
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"
	[[ $MDS1_VERSION -ge $(version_code 2.2.51) ]] ||
		skip "Need MDS version at least 2.2.51"

	local remote_dir=$DIR/$tdir/remote_dir
	local MDTIDX=1
	local rc=0

	mkdir -p $DIR/$tdir
	$LFS mkdir -i $MDTIDX $remote_dir ||
		error "create remote directory failed"

	cp /etc/hosts $remote_dir/$tfile

	fid=$($LFS path2fid $remote_dir/$tfile)
	rc=$?
	[ $rc -ne 0 ] && error "error: could not get fid for $remote_dir/$tfile"

	dot_lustre_fid_permission_check "$fid" $remote_dir ||
		error "dot lustre permission check $fid failed"
	rm -rf $DIR/$tdir
}
run_test 154b "Open-by-FID for remote directory"

test_154c() {
	[[ $MDS1_VERSION -lt $(version_code 2.4.1) ]] &&
		skip "Need MDS version at least 2.4.1"

	touch $DIR/$tfile.1 $DIR/$tfile.2 $DIR/$tfile.3
	local FID1=$($LFS path2fid $DIR/$tfile.1)
	local FID2=$($LFS path2fid $DIR/$tfile.2)
	local FID3=$($LFS path2fid $DIR/$tfile.3)

	local N=1
	$LFS path2fid $DIR/$tfile.[123] | while read PATHNAME FID; do
		[ "$PATHNAME" = "$DIR/$tfile.$N:" ] ||
			error "path2fid pathname $PATHNAME != $DIR/$tfile.$N:"
		local want=FID$N
		[ "$FID" = "${!want}" ] ||
			error "path2fid $PATHNAME FID $FID != FID$N ${!want}"
		N=$((N + 1))
	done

	$LFS fid2path $MOUNT "$FID1" "$FID2" "$FID3" | while read PATHNAME;
	do
		[ "$PATHNAME" = "$DIR/$tfile.$N" ] ||
			error "fid2path pathname $PATHNAME != $DIR/$tfile.$N:"
		N=$((N + 1))
	done
}
run_test 154c "lfs path2fid and fid2path multiple arguments"

test_154d() {
	remote_mds_nodsh && skip "remote MDS with nodsh"
	[[ $MDS1_VERSION -lt $(version_code 2.5.53) ]] &&
		skip "Need MDS version at least 2.5.53"

	if remote_mds; then
		nid=$($LCTL list_nids | sed  "s/\./\\\./g")
	else
		nid="0@lo"
	fi
	local proc_ofile="mdt.*.exports.'$nid'.open_files"
	local fd
	local cmd

	rm -f $DIR/$tfile
	touch $DIR/$tfile

	local fid=$($LFS path2fid $DIR/$tfile)
	# Open the file
	fd=$(free_fd)
	cmd="exec $fd<$DIR/$tfile"
	eval $cmd
	local fid_list=$(do_facet $SINGLEMDS $LCTL get_param $proc_ofile)
	echo "$fid_list" | grep "$fid"
	rc=$?

	cmd="exec $fd>/dev/null"
	eval $cmd
	if [ $rc -ne 0 ]; then
		error "FID $fid not found in open files list $fid_list"
	fi
}
run_test 154d "Verify open file fid"

test_154e()
{
	[[ $MDS1_VERSION -lt $(version_code 2.6.50) ]] &&
		skip "Need MDS version at least 2.6.50"

	if ls -a $MOUNT | grep -q '^\.lustre$'; then
		error ".lustre returned by readdir"
	fi
}
run_test 154e ".lustre is not returned by readdir"

test_154ea()
{
	stack_trap "rm -rf $MOUNT/[abcdeg]*" EXIT

	# long specially selected names are to displace .lustre out of
	# first directory block
	touch $MOUNT/$(printf "a%0100x" 6)
	for i in 11 15
	do
	    touch $MOUNT/$(printf "a%0254x" $i)
	done
	touch $MOUNT/$(printf "b%0254x" $i)
	for i in 16 6 7
	do
	    touch $MOUNT/$(printf "c%0254x" $i)
	done
	for i in 4 10 8
	do
	    touch $MOUNT/$(printf "d%0254x" $i)
	done
	for i in 1 14
	do
	    touch /mnt/lustre/$(printf "e%0254x" $i)
	done
	for i in 13 14
	do
	    touch /mnt/lustre/$(printf "g%0254x" $i)
	done
	if ls -a $MOUNT | grep -q '^\.lustre$'; then
	    error ".lustre returned by readdir"
	fi
}
run_test 154ea ".lustre is not returned by readdir (2)"

test_154f() {
	# create parent directory on a single MDT to avoid cross-MDT hardlinks
	mkdir_on_mdt0 $DIR/$tdir
	# test dirs inherit from its stripe
	mkdir -p $DIR/$tdir/foo1 || error "mkdir error"
	mkdir -p $DIR/$tdir/foo2 || error "mkdir error"
	cp /etc/hosts $DIR/$tdir/foo1/$tfile
	ln $DIR/$tdir/foo1/$tfile $DIR/$tdir/foo2/link
	touch $DIR/f

	# get fid of parents
	local FID0=$($LFS path2fid $DIR/$tdir)
	local FID1=$($LFS path2fid $DIR/$tdir/foo1)
	local FID2=$($LFS path2fid $DIR/$tdir/foo2)
	local FID3=$($LFS path2fid $DIR)

	# check that path2fid --parents returns expected <parent_fid>/name
	# 1) test for a directory (single parent)
	local parent=$($LFS path2fid --parents $DIR/$tdir/foo1)
	[ "$parent" == "$FID0/foo1" ] ||
		error "expected parent: $FID0/foo1, got: $parent"

	# 2) test for a file with nlink > 1 (multiple parents)
	parent=$($LFS path2fid --parents $DIR/$tdir/foo1/$tfile)
	echo "$parent" | grep -F "$FID1/$tfile" ||
		error "$FID1/$tfile not returned in parent list"
	echo "$parent" | grep -F "$FID2/link" ||
		error "$FID2/link not returned in parent list"

	# 3) get parent by fid
	local file_fid=$($LFS path2fid $DIR/$tdir/foo1/$tfile)
	parent=$($LFS path2fid --parents $MOUNT/.lustre/fid/$file_fid)
	echo "$parent" | grep -F "$FID1/$tfile" ||
		error "$FID1/$tfile not returned in parent list (by fid)"
	echo "$parent" | grep -F "$FID2/link" ||
		error "$FID2/link not returned in parent list (by fid)"

	# 4) test for entry in root directory
	parent=$($LFS path2fid --parents $DIR/f)
	echo "$parent" | grep -F "$FID3/f" ||
		error "$FID3/f not returned in parent list"

	# 5) test it on root directory
	[ -z "$FILESET" ] && {
		# LU_ROOT_FID is wrong for fileset
		[ -z "$($LFS path2fid --parents $MOUNT 2>/dev/null)" ] ||
			error "$MOUNT should not have parents"
	}

	# enable xattr caching and check that linkea is correctly updated
	local save="$TMP/$TESTSUITE-$TESTNAME.parameters"
	save_lustre_params client "llite.*.xattr_cache" > $save
	lctl set_param llite.*.xattr_cache 1

	# 6.1) linkea update on rename
	mv $DIR/$tdir/foo1/$tfile $DIR/$tdir/foo2/$tfile.moved

	# get parents by fid
	parent=$($LFS path2fid --parents $MOUNT/.lustre/fid/$file_fid)
	# foo1 should no longer be returned in parent list
	echo "$parent" | grep -F "$FID1" &&
		error "$FID1 should no longer be in parent list"
	# the new path should appear
	echo "$parent" | grep -F "$FID2/$tfile.moved" ||
		error "$FID2/$tfile.moved is not in parent list"

	# 6.2) linkea update on unlink
	rm -f $DIR/$tdir/foo2/link
	parent=$($LFS path2fid --parents $MOUNT/.lustre/fid/$file_fid)
	# foo2/link should no longer be returned in parent list
	echo "$parent" | grep -F "$FID2/link" &&
		error "$FID2/link should no longer be in parent list"
	true

	rm -f $DIR/f
	restore_lustre_params < $save
	rm -f $save
}
run_test 154f "get parent fids by reading link ea"

test_154g()
{
	[[ $MDS1_VERSION -ge $(version_code 2.6.92) &&
	   $CLIENT_VERSION -gt $(version_code 2.6.99) ]] ||
		skip "Need MDS version at least 2.6.92"

	mkdir_on_mdt0 $DIR/$tdir
	llapi_fid_test -d $DIR/$tdir
}
run_test 154g "various llapi FID tests"

test_154h()
{
	(( $CLIENT_VERSION >= $(version_code 2.15.55.1) )) ||
		skip "Need client at least version 2.15.55.1"

	# Create an empty file
	touch $DIR/$tfile

	# Get FID (interactive mode) and save under $TMP/$tfile.log
	$LFS 2>&1 <<-EOF | tee $TMP/$tfile.log
		path2fid $DIR/$tfile
	EOF

	fid=$(cat $TMP/$tfile.log)
	# $fid should not be empty
	[[ ! -z $fid ]] || error "FID is empty"
	$LFS rmfid $DIR "$fid" || error "rmfid failed for $fid"
}
run_test 154h "Verify interactive path2fid"

test_154i()
{
	local long=thislongpathnameisforaverydeepsubdirthatwewanttotestagainst
	local depth
	local path
	local max
	local fid

	(( $MDS1_VERSION >= $(version_code v2_15_65-55-gf5251cb7af) )) ||
		skip "need MDS >= 2.15.65.55 for fid2path > PATH_MAX handling"

	mkdir -p $DIR/$tdir
	cd $DIR/$tdir

	# create a directory tree with full path longer than PATH_MAX=4096
	max=$((4096 / $(wc -c <<< $long) + 5))
	for (( depth = 0; depth <= max; depth++)); do
		mkdir -v $long$depth || error "mkdir $long$depth failed"
		cd $long$depth
	done

	fid=$($LFS path2fid .) || error "path2fid failed"
	path=$($LFS fid2path $MOUNT $fid) || error "fid2path failed (1)"
	echo -e "Path for fid $fid is:\n$path"

	path=$($LFS fid2path $(cd ..; pwd) $fid) || error "fid2path failed (2)"
	echo -e "Path for fid $fid is:\n$path"
}
run_test 154i "fid2path for path longer than PATH_MAX"

test_154j()
{
	(( $MDSCOUNT >= 2 )) || skip_env "needs >= 2 MDTs"
	(( $MDS1_VERSION >= $(version_code v2_15_65-55-gf5251cb7af) )) ||
		skip "need MDS >= 2.15.65.55 for fid2path > PATH_MAX handling"

	local long=thislongpathnameisforaverydeepsubdirthatwewanttotestagainst
	local depth
	local path
	local fid

	# place $tdir on MDT0 and create a remote dir on MDT1 so that
	# fid2path has to cross the MDT boundary
	$LFS mkdir -i 0 $DIR/$tdir || error "mkdir MDT0 failed"
	$LFS mkdir -i 1 $DIR/$tdir/remote || error "lfs mkdir -i 1 failed"

	cd $DIR/$tdir/remote

	# Create 66 nested dirs. Each ~60 chars, total MDT1 path ~4088.
	# Combined with MDT0 path ($tdir ~12+ chars), exceeds PATH_MAX.
	for (( depth = 0; depth <= 65; depth++ )); do
		mkdir $long$depth || error "mkdir $long$depth failed"
		cd $long$depth
	done

	fid=$($LFS path2fid .) || error "path2fid failed"
	path=$($LFS fid2path $MOUNT $fid) || error "fid2path failed"
	echo -e "Path for fid $fid is:\n$path"
}
run_test 154j "fid2path for long path crossing MDT boundary"

test_155_small_load() {
    local temp=$TMP/$tfile
    local file=$DIR/$tfile

    dd if=/dev/urandom of=$temp bs=6096 count=1 || \
        error "dd of=$temp bs=6096 count=1 failed"
    cp $temp $file
    cancel_lru_locks $OSC
    cmp $temp $file || error "$temp $file differ"

    $TRUNCATE $temp 6000
    $TRUNCATE $file 6000
    cmp $temp $file || error "$temp $file differ (truncate1)"

    echo "12345" >>$temp
    echo "12345" >>$file
    cmp $temp $file || error "$temp $file differ (append1)"

    echo "12345" >>$temp
    echo "12345" >>$file
    cmp $temp $file || error "$temp $file differ (append2)"

    rm -f $temp $file
    true
}

test_155_big_load() {
	remote_ost_nodsh && skip "remote OST with nodsh"

	local temp=$TMP/$tfile
	local file=$DIR/$tfile

	free_min_max
	local cache_size=$(do_facet ost$((MAXI+1)) \
		"awk '/cache/ {sum+=\\\$4} END {print sum}' /proc/cpuinfo")

	# LU-16042: can not get the cache size on Arm64 VM here, fallback to a
	# pre-set value
	if [ -z "$cache_size" ]; then
		cache_size=256
	fi
	local large_file_size=$((cache_size * 2))

	echo "OSS cache size: $cache_size KB"
	echo "Large file size: $large_file_size KB"

	[ $MAXV -le $large_file_size ] &&
		skip_env "max available OST size needs > $large_file_size KB"

	$LFS setstripe $file -c 1 -i $MAXI || error "$LFS setstripe $file failed"

	dd if=/dev/urandom of=$temp bs=$large_file_size count=1k ||
		error "dd of=$temp bs=$large_file_size count=1k failed"
	cp $temp $file
	ls -lh $temp $file
	cancel_lru_locks osc
	cmp $temp $file || error "$temp $file differ"

	rm -f $temp $file
	true
}

save_writethrough() {
	local facets=$(get_facets OST)

	save_lustre_params $facets "osd-*.*.writethrough_cache_enable" > $1
}

test_155a() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	local p="$TMP/$TESTSUITE-$TESTNAME.parameters"
	local osts=$(osts_nodes)

	save_writethrough $p

	set_cache $osts read on
	set_cache $osts writethrough on
	test_155_small_load
	restore_lustre_params < $p
	rm -f $p
}
run_test 155a "Verify small file correctness: read cache:on write_cache:on"

test_155b() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	local p="$TMP/$TESTSUITE-$TESTNAME.parameters"
	local osts=$(osts_nodes)

	save_writethrough $p

	set_cache $osts read on
	set_cache $osts writethrough off
	test_155_small_load
	restore_lustre_params < $p
	rm -f $p
}
run_test 155b "Verify small file correctness: read cache:on write_cache:off"

test_155c() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	local p="$TMP/$TESTSUITE-$TESTNAME.parameters"
	local osts=$(osts_nodes)

	save_writethrough $p

	set_cache $osts read off
	set_cache $osts writethrough on
	test_155_small_load
	restore_lustre_params < $p
	rm -f $p
}
run_test 155c "Verify small file correctness: read cache:off write_cache:on"

test_155d() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	local p="$TMP/$TESTSUITE-$TESTNAME.parameters"
	local osts=$(osts_nodes)

	save_writethrough $p

	set_cache $osts read off
	set_cache $osts writethrough off
	test_155_small_load
	restore_lustre_params < $p
	rm -f $p
}
run_test 155d "Verify small file correctness: read cache:off write_cache:off"

test_155e() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	local p="$TMP/$TESTSUITE-$TESTNAME.parameters"
	local osts=$(osts_nodes)

	save_writethrough $p

	set_cache $osts read on
	set_cache $osts writethrough on
	test_155_big_load
	restore_lustre_params < $p
	rm -f $p
}
run_test 155e "Verify big file correctness: read cache:on write_cache:on"

test_155f() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	local p="$TMP/$TESTSUITE-$TESTNAME.parameters"
	local osts=$(osts_nodes)

	save_writethrough $p

	set_cache $osts read on
	set_cache $osts writethrough off
	test_155_big_load
	restore_lustre_params < $p
	rm -f $p
}
run_test 155f "Verify big file correctness: read cache:on write_cache:off"

test_155g() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	local p="$TMP/$TESTSUITE-$TESTNAME.parameters"
	local osts=$(osts_nodes)

	save_writethrough $p

	set_cache $osts read off
	set_cache $osts writethrough on
	test_155_big_load
	restore_lustre_params < $p
	rm -f $p
}
run_test 155g "Verify big file correctness: read cache:off write_cache:on"

test_155h() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	local p="$TMP/$TESTSUITE-$TESTNAME.parameters"
	local osts=$(osts_nodes)

	save_writethrough $p

	set_cache $osts read off
	set_cache $osts writethrough off
	test_155_big_load
	restore_lustre_params < $p
	rm -f $p
}
run_test 155h "Verify big file correctness: read cache:off write_cache:off"

test_156() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_ost_nodsh && skip "remote OST with nodsh"
	[ $OST1_VERSION -lt $(version_code 2.6.93) ] &&
		skip "stats not implemented on old servers"
	[ "$ost1_FSTYPE" = "zfs" ] &&
		skip "LU-1956/LU-2261: stats not implemented on OSD ZFS"
	(( CLIENT_VERSION == OST1_VERSION )) ||
		skip "LU-13081: no interop testing for OSS cache"

	local CPAGES=3
	local BEFORE
	local AFTER
	local file="$DIR/$tfile"
	local p="$TMP/$TESTSUITE-$TESTNAME.parameters"
	local osts=$(osts_nodes)

	save_writethrough $p
	roc_hit_init $osts

	log "Turn on read and write cache"
	set_cache $osts read on
	set_cache $osts writethrough on

	log "Write data and read it back."
	log "Read should be satisfied from the cache."
	dd if=/dev/urandom of=$file bs=4k count=$CPAGES || error "dd failed"
	BEFORE=$(roc_hit $osts)
	cancel_lru_locks osc
	cat $file >/dev/null
	AFTER=$(roc_hit $osts)
	if ! let "AFTER - BEFORE == CPAGES"; then
		error "NOT IN CACHE (2): before: $BEFORE, after: $AFTER"
	else
		log "cache hits: before: $BEFORE, after: $AFTER"
	fi

	log "Read again; it should be satisfied from the cache."
	BEFORE=$AFTER
	cancel_lru_locks osc
	cat $file >/dev/null
	AFTER=$(roc_hit $osts)
	if ! let "AFTER - BEFORE == CPAGES"; then
		error "NOT IN CACHE (3): before: $BEFORE, after: $AFTER"
	else
		log "cache hits:: before: $BEFORE, after: $AFTER"
	fi

	log "Turn off the read cache and turn on the write cache"
	set_cache $osts read off
	set_cache $osts writethrough on

	log "Read again; it should be satisfied from the cache."
	BEFORE=$(roc_hit $osts)
	cancel_lru_locks osc
	cat $file >/dev/null
	AFTER=$(roc_hit $osts)
	if ! let "AFTER - BEFORE == CPAGES"; then
		error "NOT IN CACHE (4): before: $BEFORE, after: $AFTER"
	else
		log "cache hits:: before: $BEFORE, after: $AFTER"
	fi

	if [ $OST1_VERSION -lt $(version_code 2.12.55) ]; then
		# > 2.12.56 uses pagecache if cached
		log "Read again; it should not be satisfied from the cache."
		BEFORE=$AFTER
		cancel_lru_locks osc
		cat $file >/dev/null
		AFTER=$(roc_hit $osts)
		if ! let "AFTER - BEFORE == 0"; then
			error "IN CACHE (5): before: $BEFORE, after: $AFTER"
		else
			log "cache hits:: before: $BEFORE, after: $AFTER"
		fi
	fi

	log "Write data and read it back."
	log "Read should be satisfied from the cache."
	dd if=/dev/urandom of=$file bs=4k count=$CPAGES || error "dd failed"
	BEFORE=$(roc_hit $osts)
	cancel_lru_locks osc
	cat $file >/dev/null
	AFTER=$(roc_hit $osts)
	if ! let "AFTER - BEFORE == CPAGES"; then
		error "NOT IN CACHE (6): before: $BEFORE, after: $AFTER"
	else
		log "cache hits:: before: $BEFORE, after: $AFTER"
	fi

	if [ $OST1_VERSION -lt $(version_code 2.12.55) ]; then
		# > 2.12.56 uses pagecache if cached
		log "Read again; it should not be satisfied from the cache."
		BEFORE=$AFTER
		cancel_lru_locks osc
		cat $file >/dev/null
		AFTER=$(roc_hit $osts)
		if ! let "AFTER - BEFORE == 0"; then
			error "IN CACHE (7): before: $BEFORE, after: $AFTER"
		else
			log "cache hits:: before: $BEFORE, after: $AFTER"
		fi
	fi

	log "Turn off read and write cache"
	set_cache $osts read off
	set_cache $osts writethrough off

	log "Write data and read it back"
	log "It should not be satisfied from the cache."
	rm -f $file
	dd if=/dev/urandom of=$file bs=4k count=$CPAGES || error "dd failed"
	cancel_lru_locks osc
	BEFORE=$(roc_hit $osts)
	cat $file >/dev/null
	AFTER=$(roc_hit $osts)
	if ! let "AFTER - BEFORE == 0"; then
		error_ignore bz20762 "IN CACHE (8):before:$BEFORE,after:$AFTER"
	else
		log "cache hits:: before: $BEFORE, after: $AFTER"
	fi

	log "Turn on the read cache and turn off the write cache"
	set_cache $osts read on
	set_cache $osts writethrough off

	log "Write data and read it back"
	log "It should not be satisfied from the cache."
	rm -f $file
	dd if=/dev/urandom of=$file bs=4k count=$CPAGES || error "dd failed"
	BEFORE=$(roc_hit $osts)
	cancel_lru_locks osc
	cat $file >/dev/null
	AFTER=$(roc_hit $osts)
	if ! let "AFTER - BEFORE == 0"; then
		error_ignore bz20762 "IN CACHE (9):before:$BEFORE,after:$AFTER"
	else
		log "cache hits:: before: $BEFORE, after: $AFTER"
	fi

	log "Read again; it should be satisfied from the cache."
	BEFORE=$(roc_hit $osts)
	cancel_lru_locks osc
	cat $file >/dev/null
	AFTER=$(roc_hit $osts)
	if ! let "AFTER - BEFORE == CPAGES"; then
		error "NOT IN CACHE (1): before: $BEFORE, after: $AFTER"
	else
		log "cache hits:: before: $BEFORE, after: $AFTER"
	fi

	restore_lustre_params < $p
	rm -f $p $file
}
run_test 156 "Verification of tunables"

test_157a()
{
	(( $MDS1_VERSION >= $(version_code v2_16_51-30-g84100d7f7d) )) ||
		skip "Need MDS >= 2.16.52 for lustre.pin support"

	mkdir_on_mdt0 $DIR/$tdir
	llapi_pool_test -d $DIR/$tdir ||
		error "llapi_pool_test failed"
}
run_test 157a "llapi pool pinning API tests"

test_157b()
{
	[ "$UID" != 0 ] && skip "must run as root"
	[ -z "$(lctl get_param -n mdc.*-mdc-*.connect_flags | grep xattr)" ] &&
		skip_env "must have user_xattr"
	[ -z "$(which setfattr 2>/dev/null)" ] &&
		skip_env "could not find setfattr"
	[ -z "$(which getfattr 2>/dev/null)" ] &&
		skip_env "could not find getfattr"

	(( $MDS1_VERSION >= $(version_code v2_17_53-1-g1bf8713c57) )) ||
		skip "Need MDS >= 2.17.53 for lustre.pin support"

	local dir=$DIR/$tdir
	local file=$dir/$tfile
	local subdir=$dir/subdir
	local noxatrr_file=$dir/$tfile.noxattr
	local pinval="[pool: pininherit]"
	local parent_val file_val subdir_val noxatrr_file_val

	test_mkdir $dir
	touch $noxatrr_file || error "touch $noxatrr_file failed"

	setfattr -n lustre.pin -v "$pinval" $dir ||
		error "failed to set lustre.pin on $dir"

	touch $file || error "touch $file failed"
	mkdir $subdir || error "mkdir $subdir failed"

	parent_val=$(getfattr --only-values -n lustre.pin $dir 2> /dev/null) ||
		error "getfattr lustre.pin on parent failed"
	file_val=$(getfattr --only-values -n lustre.pin $file 2> /dev/null) ||
		error "getfattr lustre.pin on file failed"
	subdir_val=$(getfattr --only-values -n lustre.pin $subdir 2> /dev/null) ||
		error "getfattr lustre.pin on subdir failed"
	noxatrr_file_val=$(getfattr --only-values -n lustre.pin $noxatrr_file 2>/dev/null)

	[ "$file_val" = "$parent_val" ] ||
		error "file lustre.pin '$file_val' != parent '$parent_val'"
	[ "$subdir_val" = "$parent_val" ] ||
		error "subdir lustre.pin '$subdir_val' != parent '$parent_val'"
	[ -z "$noxatrr_file_val" ] ||
		error "noxatrr_file lustre.pin '$noxatrr_file_val' != ''"
}
run_test 157b "lustre.pin inheritance on create"

test_160a() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	[ $MDS1_VERSION -ge $(version_code 2.2.0) ] ||
		skip "Need MDS version at least 2.2.0"

	changelog_register || error "changelog_register failed"
	local cl_user="${CL_USERS[$SINGLEMDS]%% *}"
	changelog_users $SINGLEMDS | grep -q $cl_user ||
		error "User $cl_user not found in changelog_users"

	mkdir_on_mdt0 $DIR/$tdir

	# change something
	test_mkdir -p $DIR/$tdir/pics/2008/zachy
	changelog_clear 0 || error "changelog_clear failed"
	touch $DIR/$tdir/pics/2008/zachy/$tfile			# open 1
	cp /etc/hosts $DIR/$tdir/pics/2008/zachy/pic1.jpg	# open 2
	mv $DIR/$tdir/pics/2008/zachy $DIR/$tdir/pics/zach
	ln $DIR/$tdir/pics/zach/pic1.jpg $DIR/$tdir/pics/2008/portland.jpg
	ln -s $DIR/$tdir/pics/2008/portland.jpg $DIR/$tdir/pics/desktop.jpg
	rm $DIR/$tdir/pics/desktop.jpg

	echo "verifying changelog mask"
	changelog_chmask "-MKDIR"
	changelog_chmask "-CLOSE"

	test_mkdir -p $DIR/$tdir/pics/zach/sofia		# not logged
	echo "zzzzzz" > $DIR/$tdir/pics/zach/file		# not logged

	changelog_chmask "+MKDIR"
	changelog_chmask "+CLOSE"

	test_mkdir -p $DIR/$tdir/pics/2008/sofia		# mkdir 1
	echo "zzzzzz" > $DIR/$tdir/pics/zach/file		# open 3

	MKDIRS=$(changelog_dump | grep -c "MKDIR")
	CLOSES=$(changelog_dump | grep -c "CLOSE")
	[ $MKDIRS -eq 1 ] || error "MKDIR changelog mask count $MKDIRS != 1"
	[ $CLOSES -eq 3 ] || error "CLOSE changelog mask count $CLOSES != 3"

	# verify contents
	echo "verifying target fid"
	local fidc=$(changelog_extract_field "CREAT" "$tfile" "t=")
	local fidf=$($LFS path2fid $DIR/$tdir/pics/zach/$tfile)
	[ "$fidc" == "$fidf" ] ||
		error "changelog '$tfile' fid $fidc != file fid $fidf"
	echo "verifying parent fid"
	# The FID returned from the Changelog may be the directory shard on
	# a different MDT, and not the FID returned by path2fid on the parent.
	# Instead of comparing FIDs, verify that fid2path(fidp) is correct,
	# since this is what will matter when recreating this file in the tree.
	local fidp=$(changelog_extract_field "CREAT" "$tfile" "p=")
	local pathp=$($LFS fid2path $MOUNT "$fidp")
	[ "${pathp%/}" == "$DIR/$tdir/pics/zach" ] ||
		error "changelog fid2path($fidc) $pathp != $DIR/$tdir/pics/zach"

	echo "getting records for $cl_user"
	changelog_users $SINGLEMDS
	local user_rec1=$(changelog_user_rec $SINGLEMDS $cl_user)
	local nclr=3
	__changelog_clear $SINGLEMDS $cl_user +$nclr ||
		error "changelog_clear failed"
	local user_rec2=$(changelog_user_rec $SINGLEMDS $cl_user)
	echo "verifying user clear: $user_rec1 + $nclr == $user_rec2"
	[ $user_rec2 == $((user_rec1 + nclr)) ] ||
		error "user index expect $user_rec1 + $nclr != $user_rec2"

	local min0_rec=$(changelog_users $SINGLEMDS |
		awk 'min == "" || $2 < min { min = $2 }; END { print min }')
	local first_rec=$($LFS changelog $(facet_svc $SINGLEMDS) |
			  awk '{ print $1; exit; }')

	changelog_dump | tail -n 5
	echo "verifying user min purge: $min0_rec + 1 == $first_rec"
	[ $first_rec == $((min0_rec + 1)) ] ||
		error "first index should be $min0_rec + 1 not $first_rec"

	# LU-3446 changelog index reset on MDT restart
	local cur_rec1=$(changelog_users $SINGLEMDS |
			 awk '/^current.index:/ { print $NF }')
	changelog_clear 0 ||
		error "clear all changelog records for $cl_user failed"
	stop $SINGLEMDS || error "Fail to stop $SINGLEMDS"
	start $SINGLEMDS $(mdsdevname ${SINGLEMDS//mds/}) $MDS_MOUNT_OPTS ||
		error "Fail to start $SINGLEMDS"
	local cur_rec2=$(changelog_users $SINGLEMDS |
			 awk '/^current.index:/ { print $NF }')
	echo "verifying index survives MDT restart: $cur_rec1 == $cur_rec2"
	[ $cur_rec1 == $cur_rec2 ] ||
		error "current index should be $cur_rec1 not $cur_rec2"

	echo "verifying users from this test are deregistered"
	changelog_deregister || error "changelog_deregister failed"
	changelog_users $SINGLEMDS | grep -q $cl_user &&
		error "User '$cl_user' still in changelog_users"

	# lctl get_param -n mdd.*.changelog_users
	# current_index: 144
	# ID    index (idle seconds)
	# cl3   144   (2) mask=<list>
	if [ -z "$(changelog_users $SINGLEMDS | grep -v current.index)" ]; then
		# this is the normal case where all users were deregistered
		# make sure no new records are added when no users are present
		local last_rec1=$(changelog_users $SINGLEMDS |
				  awk '/^current.index:/ { print $NF }')
		touch $DIR/$tdir/chloe
		local last_rec2=$(changelog_users $SINGLEMDS |
				  awk '/^current.index:/ { print $NF }')
		echo "verify changelogs are off: $last_rec1 == $last_rec2"
		[ $last_rec1 == $last_rec2 ] || error "changelogs not off"
	else
		# any changelog users must be leftovers from a previous test
		changelog_users $SINGLEMDS
		echo "other changelog users; can't verify off"
	fi
}
run_test 160a "changelog sanity"

test_160b() { # LU-3587
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	[ $MDS1_VERSION -ge $(version_code 2.2.0) ] ||
		skip "Need MDS version at least 2.2.0"

	changelog_register || error "changelog_register failed"
	local cl_user="${CL_USERS[$SINGLEMDS]%% *}"
	changelog_users $SINGLEMDS | grep -q $cl_user ||
		error "User '$cl_user' not found in changelog_users"

	local longname1=$(str_repeat a 255)
	local longname2=$(str_repeat b 255)

	cd $DIR
	echo "creating very long named file"
	touch $longname1 || error "create of '$longname1' failed"
	echo "renaming very long named file"
	mv $longname1 $longname2

	changelog_dump | grep RENME | tail -n 5
	rm -f $longname2
}
run_test 160b "Verify that very long rename doesn't crash in changelog"

test_160c() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"

	[[ $MDS1_VERSION -gt $(version_code 2.5.57) ]] ||
		[[ $MDS1_VERSION -gt $(version_code 2.5.1) &&
		   $MDS1_VERSION -lt $(version_code 2.5.50) ]] ||
		skip "Need MDS version at least 2.5.58 or 2.5.2+"

	local rc=0

	# Registration step
	changelog_register || error "changelog_register failed"

	rm -rf $DIR/$tdir
	mkdir -p $DIR/$tdir
	$MCREATE $DIR/$tdir/foo_160c
	changelog_chmask "-TRUNC"
	$TRUNCATE $DIR/$tdir/foo_160c 200
	changelog_chmask "+TRUNC"
	$TRUNCATE $DIR/$tdir/foo_160c 199
	changelog_dump | tail -n 5
	local truncs=$(changelog_dump | tail -n 5 | grep -c TRUNC)
	[ $truncs -eq 1 ] || error "TRUNC changelog mask count $truncs != 1"
}
run_test 160c "verify that changelog log catch the truncate event"

test_160d() {
	remote_mds_nodsh && skip "remote MDS with nodsh"
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[[ $MDS1_VERSION -ge $(version_code 2.7.60) ]] ||
		skip "Need MDS version at least 2.7.60"

	# Registration step
	changelog_register || error "changelog_register failed"

	mkdir -p $DIR/$tdir/migrate_dir

	local src_mdt=$($LFS getdirstripe -m $DIR/$tdir/migrate_dir)
	local tgt_mdt=1

	[[ "$src_mdt" == "$tgt_mdt" ]] && tgt_mdt=0

	changelog_clear 0 || error "changelog_clear failed"

	$LFS migrate -m $tgt_mdt $DIR/$tdir/migrate_dir || error "migrate fails"
	changelog_dump | tail -n 5
	local migrates=$(changelog_dump | grep -c "MIGRT")
	[ $migrates -eq 1 ] || error "MIGRATE changelog count $migrates != 1"
}
run_test 160d "verify that changelog log catch the migrate event"

test_160e() {
	remote_mds_nodsh && skip "remote MDS with nodsh"

	# Create a user
	changelog_register || error "changelog_register failed"

	local MDT0=$(facet_svc $SINGLEMDS)
	local rc

	# No user (expect fail)
	do_facet $SINGLEMDS $LCTL --device $MDT0 changelog_deregister
	rc=$?
	if [ $rc -eq 0 ]; then
		error "Should fail without user"
	elif [ $rc -ne 4 ]; then
		error "changelog_deregister failed with $rc, expect 4(CMD_HELP)"
	fi

	# Delete a future user (expect fail)
	do_facet $SINGLEMDS $LCTL --device $MDT0 changelog_deregister "cl77"
	rc=$?
	if [ $rc -eq 0 ]; then
		error "Deleted non-existant user cl77"
	elif [ $rc -ne 2 ]; then
		error "changelog_deregister failed with $rc, expect 2 (ENOENT)"
	fi

	# Clear to a bad index (1 billion should be safe)
	$LFS changelog_clear $MDT0 "${CL_USERS[$SINGLEMDS]%% *}" 1000000000
	rc=$?

	if [ $rc -eq 0 ]; then
		error "Successfully cleared to invalid CL index"
	elif [ $rc -ne 22 ]; then
		error "changelog_clear failed with $rc, expected 22 (EINVAL)"
	fi
}
run_test 160e "changelog negative testing (should return errors)"

test_160f() {
	remote_mds_nodsh && skip "remote MDS with nodsh" && return
	(( $MDS1_VERSION >= $(version_code 2.10.56) )) ||
		skip "Need MDS version at least 2.10.56"

	local mdts=$(mdts_nodes)

	# Create a user
	changelog_register || error "first changelog_register failed"
	changelog_register || error "second changelog_register failed"
	local cl_users
	declare -A cl_user1
	declare -A cl_user2
	local user_rec1
	local user_rec2
	local i

	# generate some changelog records to accumulate on each MDT
	# use all_char because created files should be evenly distributed
	test_mkdir -c $MDSCOUNT -H all_char $DIR/$tdir ||
		error "test_mkdir $tdir failed"
	log "$(date +%s): creating first dirs"
	for ((idx = 0; idx < MDSCOUNT * 2; idx++)); do
		local d=$DIR/$tdir/d$idx.$((idx/MDSCOUNT))
		$LFS mkdir -i $((idx%MDSCOUNT)) $d ||
			error "create $d on MDT$idx failed"
	done

	# check changelogs have been generated
	local start=$SECONDS
	local idle_time=$((MDSCOUNT * 5 + 5))
	local nbcl=$(changelog_dump | wc -l)
	(( $nbcl != 0 )) || error "no changelogs found"

	for param in "changelog_max_idle_time=$idle_time" \
		     "changelog_gc=1" \
		     "changelog_min_gc_interval=2" \
		     "changelog_min_free_cat_entries=3"; do
		local MDT0=$(facet_svc $SINGLEMDS)
		local var="${param%=*}"
		local old=$(do_facet mds1 "$LCTL get_param -n mdd.$MDT0.$var")

		stack_trap "do_nodes $mdts $LCTL set_param mdd.*.$var=$old" EXIT
		do_nodes $mdts $LCTL set_param mdd.*.$param
	done

	# force cl_user2 to be idle (1st part), but also cancel the
	# cl_user1 records so that it is not evicted later in the test.
	local sleep1=$((idle_time / 2))
	echo "$(date +%s): sleep1 $sleep1/${idle_time}s"
	sleep $sleep1

	# simulate changelog catalog almost full
	#define OBD_FAIL_CAT_FREE_RECORDS	0x1313
	do_nodes $mdts "$LCTL set_param fail_loc=0x1313 fail_val=3"

	for ((i = 1; i <= $MDSCOUNT; i++)); do
		cl_users=(${CL_USERS[mds$i]})
		cl_user1[mds$i]="${cl_users[0]}"
		cl_user2[mds$i]="${cl_users[1]}"

		[ -n "${cl_user1[mds$i]}" ] ||
			error "mds$i: no user registered"
		[ -n "${cl_user2[mds$i]}" ] ||
			error "mds$i: only ${cl_user2[mds$i]} is registered"

		user_rec1=$(changelog_user_rec mds$i ${cl_user1[mds$i]})
		[ -n "$user_rec1" ] ||
			error "mds$i: User ${cl_user1[mds$i]} not registered"
		__changelog_clear mds$i ${cl_user1[mds$i]} +2
		user_rec2=$(changelog_user_rec mds$i ${cl_user1[mds$i]})
		[ -n "$user_rec2" ] ||
			error "mds$i: User ${cl_user1[mds$i]} not registered"
		echo "mds$i: verifying user ${cl_user1[mds$i]} clear: " \
		     "$user_rec1 + 2 == $user_rec2"
		[ $((user_rec1 + 2)) == $user_rec2 ] ||
			error "mds$i: user ${cl_user1[mds$i]} index expected " \
			      "$user_rec1 + 2, but is $user_rec2"
		user_rec2=$(changelog_user_rec mds$i ${cl_user2[mds$i]})
		[ -n "$user_rec2" ] ||
			error "mds$i: User ${cl_user2[mds$i]} not registered"
		[ $user_rec1 == $user_rec2 ] ||
			error "mds$i: user ${cl_user2[mds$i]} index expected " \
			      "$user_rec1, but is $user_rec2"
	done

	# force cl_user2 idle (2nd part) to just exceed changelog_max_idle_time
	local sleep2=$((idle_time - (SECONDS - start) + 1))
	echo "$(date +%s): sleep2 $sleep2/${idle_time}s"
	sleep $sleep2

	# Generate one more changelog to trigger GC at fail_loc for cl_user2.
	# cl_user1 should be OK because it recently processed records.
	echo "$(date +%s): creating $((MDSCOUNT * 2)) dirs"
	for ((idx = 0; idx < MDSCOUNT * 2; idx++)); do
		local d=$DIR/$tdir/d$idx.$((idx/MDSCOUNT+2))

		$LFS mkdir -i $((idx%MDSCOUNT)) $d ||
			error "create dir $d on MDT$idx failed"
	done

	# sleep again to allow GC to trigger
	local sleep3=4
	echo "$(date +%s): sleep3 $sleep3/${idle_time}s"
	sleep $sleep3

	# ensure gc thread is done
	for mds in ${mdts//,/ }; do
		wait_update $mds "ps -e -o comm= | grep chlg_gc_thread" "" ||
			error "$mds: GC-thread not done"
	done

	local first_rec
	for (( i = 1; i <= MDSCOUNT; i++ )); do
		# check cl_user1 still registered
		changelog_users mds$i | grep -q "${cl_user1[mds$i]}" ||
			error "mds$i: User ${cl_user1[mds$i]} not registered"
		# check cl_user2 unregistered
		changelog_users mds$i | grep -q "${cl_user2[mds$i]}" &&
			error "mds$i: User ${cl_user2[mds$i]} still registered"

		# check changelogs are present and starting at $user_rec1 + 1
		user_rec1=$(changelog_user_rec mds$i ${cl_user1[mds$i]})
		[ -n "$user_rec1" ] ||
			error "mds$i: User ${cl_user1[mds$i]} not registered"
		first_rec=$($LFS changelog $(facet_svc mds$i) |
			    awk '{ print $1; exit; }')

		echo "mds$i: $(date +%s) verify rec $user_rec1+1 == $first_rec"
		[ $((user_rec1 + 1)) == $first_rec ] ||
			error "mds$i: rec $first_rec != $user_rec1 + 1"
	done
}
run_test 160f "changelog garbage collect (timestamped users)"

test_160g() {
	remote_mds_nodsh && skip "remote MDS with nodsh"
	(( $MDS1_VERSION >= $(version_code 2.14.55) )) ||
		skip "Need MDS version at least 2.14.55"

	local mdts=$(mdts_nodes)

	# Create a user
	changelog_register || error "first changelog_register failed"
	changelog_register || error "second changelog_register failed"
	local cl_users
	declare -A cl_user1
	declare -A cl_user2
	local user_rec1
	local user_rec2
	local i

	# generate some changelog records to accumulate on each MDT
	# use all_char because created files should be evenly distributed
	test_mkdir -c $MDSCOUNT -H all_char $DIR/$tdir ||
		error "test_mkdir $tdir failed"
	for ((idx = 0; idx < MDSCOUNT; idx++)); do
		$LFS mkdir -i $idx $DIR/$tdir/d$idx.1 $DIR/$tdir/d$idx.2 ||
			error "create $DIR/$tdir/d$idx.1 failed"
	done

	# check changelogs have been generated
	local nbcl=$(changelog_dump | wc -l)
	(( $nbcl > 0 )) || error "no changelogs found"

	# reduce the max_idle_indexes value to make sure we exceed it
	for param in "changelog_max_idle_indexes=2" \
		     "changelog_gc=1" \
		     "changelog_min_gc_interval=2"; do
		local MDT0=$(facet_svc $SINGLEMDS)
		local var="${param%=*}"
		local old=$(do_facet mds1 "$LCTL get_param -n mdd.$MDT0.$var")

		stack_trap "do_nodes $mdts $LCTL set_param mdd.*.$var=$old" EXIT
		do_nodes $mdts $LCTL set_param mdd.*.$param ||
			error "unable to set mdd.*.$param"
	done

	local start=$SECONDS
	for ((i=1; i <= $MDSCOUNT; i++)); do
		cl_users=(${CL_USERS[mds$i]})
		cl_user1[mds$i]="${cl_users[0]}"
		cl_user2[mds$i]="${cl_users[1]}"

		[ -n "${cl_user1[mds$i]}" ] ||
			error "mds$i: user1 is not registered"
		[ -n "${cl_user2[mds$i]}" ] ||
			error "mds$i: only ${cl_user1[mds$i]} is registered"

		user_rec1=$(changelog_user_rec mds$i ${cl_user1[mds$i]})
		[ -n "$user_rec1" ] ||
			error "mds$i: user1 ${cl_user1[mds$i]} not found"
		__changelog_clear mds$i ${cl_user1[mds$i]} +2
		user_rec2=$(changelog_user_rec mds$i ${cl_user1[mds$i]})
		[ -n "$user_rec2" ] ||
			error "mds$i: user1 ${cl_user1[mds$i]} not found (2)"
		echo "mds$i: verifying user1 ${cl_user1[mds$i]} clear: " \
		     "$user_rec1 + 2 == $user_rec2"
		[ $((user_rec1 + 2)) == $user_rec2 ] ||
			error "mds$i: user1 ${cl_user1[mds$i]} index " \
			      "expected $user_rec1 + 2, but is $user_rec2"
		user_rec2=$(changelog_user_rec mds$i ${cl_user2[mds$i]})
		[ -n "$user_rec2" ] ||
			error "mds$i: user2 ${cl_user2[mds$i]} not found"
		[ $user_rec1 == $user_rec2 ] ||
			error "mds$i: user2 ${cl_user2[mds$i]} index " \
			      "expected $user_rec1, but is $user_rec2"
	done

	# ensure we are past the previous changelog_min_gc_interval set above
	local sleep2=$((start + 2 - SECONDS))
	(( sleep2 > 0 )) && echo "sleep $sleep2 for interval" && sleep $sleep2
	# Generate one more changelog to trigger GC at fail_loc for cl_user2.
	# cl_user1 should be OK because it recently processed records.
	for ((idx = 0; idx < MDSCOUNT; idx++)); do
		$LFS mkdir -i $idx $DIR/$tdir/d$idx.3 ||
			error "create $DIR/$tdir/d$idx.3 failed"
	done

	# ensure gc thread is done
	for mds in ${mdts//,/ }; do
		wait_update $mds "ps -e -o comm= | grep chlg_gc_thread" "" 20 ||
			error "$mds: GC-thread not done"
	done

	local first_rec
	for (( i = 1; i <= MDSCOUNT; i++ )); do
		# check cl_user1 still registered
		changelog_users mds$i | grep -q "${cl_user1[mds$i]}" ||
			error "mds$i: user1 ${cl_user1[mds$i]} not found (3)"
		# check cl_user2 unregistered
		changelog_users mds$i | grep -q "${cl_user2[mds$i]}" &&
			error "mds$i: user2 ${cl_user2[mds$i]} is registered"

		# check changelogs are present and starting at $user_rec1 + 1
		user_rec1=$(changelog_user_rec mds$i ${cl_user1[mds$i]})
		[ -n "$user_rec1" ] ||
			error "mds$i: user1 ${cl_user1[mds$i]} not found (4)"
		first_rec=$($LFS changelog $(facet_svc mds$i) |
			    awk '{ print $1; exit; }')

		echo "mds$i: $(date +%s) verify rec $user_rec1+1 == $first_rec"
		[ $((user_rec1 + 1)) == $first_rec ] ||
			error "mds$i: rec $first_rec != $user_rec1 + 1"
	done
}
run_test 160g "changelog garbage collect on idle records"

test_160h() {
	remote_mds_nodsh && skip "remote MDS with nodsh" && return
	(( $MDS1_VERSION >= $(version_code 2.10.56) )) ||
		skip "Need MDS version at least 2.10.56"

	local mdts=$(mdts_nodes)

	# Create a user
	changelog_register || error "first changelog_register failed"
	changelog_register || error "second changelog_register failed"
	local cl_users
	declare -A cl_user1
	declare -A cl_user2
	local user_rec1
	local user_rec2
	local i

	# generate some changelog records to accumulate on each MDT
	# use all_char because created files should be evenly distributed
	test_mkdir -c $MDSCOUNT -H all_char $DIR/$tdir ||
		error "test_mkdir $tdir failed"
	for ((idx = 0; idx < MDSCOUNT; idx++)); do
		$LFS mkdir -i $idx $DIR/$tdir/d$idx.1 $DIR/$tdir/d$idx.2 ||
			error "create $DIR/$tdir/d$idx.1 failed"
	done

	# check changelogs have been generated
	local nbcl=$(changelog_dump | wc -l)
	[[ $nbcl -eq 0 ]] && error "no changelogs found"

	for param in "changelog_max_idle_time=10" \
		     "changelog_gc=1" \
		     "changelog_min_gc_interval=2"; do
		local MDT0=$(facet_svc $SINGLEMDS)
		local var="${param%=*}"
		local old=$(do_facet mds1 "$LCTL get_param -n mdd.$MDT0.$var")

		stack_trap "do_nodes $mdts $LCTL set_param mdd.*.$var=$old" EXIT
		do_nodes $mdts $LCTL set_param mdd.*.$param
	done

	# force cl_user2 to be idle (1st part)
	sleep 9

	for ((i=1; i <= $MDSCOUNT; i++)); do
		cl_users=(${CL_USERS[mds$i]})
		cl_user1[mds$i]="${cl_users[0]}"
		cl_user2[mds$i]="${cl_users[1]}"

		[ -n "${cl_user1[mds$i]}" ] ||
			error "mds$i: no user registered"
		[ -n "${cl_user2[mds$i]}" ] ||
			error "mds$i: only ${cl_user2[mds$i]} is registered"

		user_rec1=$(changelog_user_rec mds$i ${cl_user1[mds$i]})
		[ -n "$user_rec1" ] ||
			error "mds$i: User ${cl_user1[mds$i]} not registered"
		__changelog_clear mds$i ${cl_user1[mds$i]} +2
		user_rec2=$(changelog_user_rec mds$i ${cl_user1[mds$i]})
		[ -n "$user_rec2" ] ||
			error "mds$i: User ${cl_user1[mds$i]} not registered"
		echo "mds$i: verifying user ${cl_user1[mds$i]} clear: " \
		     "$user_rec1 + 2 == $user_rec2"
		[ $((user_rec1 + 2)) == $user_rec2 ] ||
			error "mds$i: user ${cl_user1[mds$i]} index expected " \
			      "$user_rec1 + 2, but is $user_rec2"
		user_rec2=$(changelog_user_rec mds$i ${cl_user2[mds$i]})
		[ -n "$user_rec2" ] ||
			error "mds$i: User ${cl_user2[mds$i]} not registered"
		[ $user_rec1 == $user_rec2 ] ||
			error "mds$i: user ${cl_user2[mds$i]} index expected " \
			      "$user_rec1, but is $user_rec2"
	done

	# force cl_user2 to be idle (2nd part) and to reach
	# changelog_max_idle_time
	sleep 2

	# force each GC-thread start and block then
	# one per MDT/MDD, set fail_val accordingly
	#define OBD_FAIL_FORCE_GC_THREAD 0x1316
	do_nodes $mdts $LCTL set_param fail_loc=0x1316

	# generate more changelogs to trigger fail_loc
	createmany -m $DIR/$tdir/${tfile}bis $((MDSCOUNT * 2)) ||
		error "create $DIR/$tdir/${tfile}bis failed"

	# stop MDT to stop GC-thread, should be done in back-ground as it will
	# block waiting for the thread to be released and exit
	declare -A stop_pids
	for ((i=1; i <= $MDSCOUNT; i++)); do
		stop mds$i &
		stop_pids[mds$i]=$!
	done

	for mds in ${mdts//,/ }; do
		local facet
		local nb=0
		local facets=$(facets_up_on_host $mds)

		for facet in ${facets//,/ }; do
			if [[ $facet == mds* ]]; then
				nb=$((nb + 1))
			fi
		done
		# ensure each MDS's gc threads are still present and all in "R"
		# state (OBD_FAIL_FORCE_GC_THREAD effect!)
		[[ $(do_node $mds pgrep chlg_gc_thread | wc -l) -eq $nb ]] ||
			error "$mds: expected $nb GC-thread"
		wait_update $mds \
			"ps -C chlg_gc_thread -o state --no-headers | uniq" \
			"R" 20 ||
			error "$mds: GC-thread not found in R-state"
		# check umounts of each MDT on MDS have reached kthread_stop()
		[[ $(do_node $mds pgrep umount | wc -l) -eq $nb ]] ||
			error "$mds: expected $nb umount"
		wait_update $mds \
			"ps -C umount -o state --no-headers | uniq" "D" 20 ||
			error "$mds: umount not found in D-state"
	done

	# release all GC-threads
	do_nodes $mdts $LCTL set_param fail_loc=0

	# wait for MDT stop to complete
	for ((i=1; i <= $MDSCOUNT; i++)); do
		wait ${stop_pids[mds$i]} || error "mds$i: stop failed"
	done

	# XXX
	# may try to check if any orphan changelog records are present
	# via ldiskfs/zfs and llog_reader...

	# re-start/mount MDTs
	for ((i=1; i <= $MDSCOUNT; i++)); do
		start mds$i $(mdsdevname $i) $MDS_MOUNT_OPTS ||
			error "Fail to start mds$i"
	done

	local first_rec
	for ((i=1; i <= $MDSCOUNT; i++)); do
		# check cl_user1 still registered
		changelog_users mds$i | grep -q "${cl_user1[mds$i]}" ||
			error "mds$i: User ${cl_user1[mds$i]} not registered"
		# check cl_user2 unregistered
		changelog_users mds$i | grep -q "${cl_user2[mds$i]}" &&
			error "mds$i: User ${cl_user2[mds$i]} still registered"

		# check changelogs are present and starting at $user_rec1 + 1
		user_rec1=$(changelog_user_rec mds$i ${cl_user1[mds$i]})
		[ -n "$user_rec1" ] ||
			error "mds$i: User ${cl_user1[mds$i]} not registered"
		first_rec=$($LFS changelog $(facet_svc mds$i) |
			    awk '{ print $1; exit; }')

		echo "mds$i: verifying first index $user_rec1 + 1 == $first_rec"
		[ $((user_rec1 + 1)) == $first_rec ] ||
			error "mds$i: first index should be $user_rec1 + 1, " \
			      "but is $first_rec"
	done
}
run_test 160h "changelog gc thread stop upon umount, orphan records delete " \
	      "during mount"

test_160i() {
	local mdts=$(mdts_nodes)

	changelog_register || error "first changelog_register failed"

	# generate some changelog records to accumulate on each MDT
	# use all_char because created files should be evenly distributed
	test_mkdir -c $MDSCOUNT -H all_char $DIR/$tdir ||
		error "test_mkdir $tdir failed"
	for ((i = 0; i < MDSCOUNT; i++)); do
		$LFS mkdir -i $i $DIR/$tdir/d$i.1 $DIR/$tdir/d$i.2 ||
			error "create $DIR/$tdir/d$i.1 failed"
	done

	# check changelogs have been generated
	local nbcl=$(changelog_dump | wc -l)
	[[ $nbcl -eq 0 ]] && error "no changelogs found"

	# simulate race between register and unregister
	# XXX as fail_loc is set per-MDS, with DNE configs the race
	# simulation will only occur for one MDT per MDS and for the
	# others the normal race scenario will take place
	#define CFS_FAIL_CHLOG_USER_REG_UNREG_RACE          0x1315
	do_nodes $mdts $LCTL set_param fail_loc=0x10001315
	do_nodes $mdts $LCTL set_param fail_val=1

	# unregister 1st user
	changelog_deregister &
	local pid1=$!
	# wait some time for deregister work to reach race rdv
	sleep 2
	# register 2nd user
	changelog_register || error "2nd user register failed"

	wait $pid1 || error "1st user deregister failed"

	local i
	local last_rec
	declare -A LAST_REC
	for ((i=1; i <= $MDSCOUNT; i++)); do
		if changelog_users mds$i | grep "^cl"; then
			# make sure new records are added with one user present
			LAST_REC[mds$i]=$(changelog_users $SINGLEMDS |
					  awk '/^current.index:/ { print $NF }')
		else
			error "mds$i has no user registered"
		fi
	done

	# generate more changelog records to accumulate on each MDT
	createmany -m $DIR/$tdir/${tfile}bis $((MDSCOUNT * 2)) ||
		error "create $DIR/$tdir/${tfile}bis failed"

	for ((i=1; i <= $MDSCOUNT; i++)); do
		last_rec=$(changelog_users $SINGLEMDS |
			   awk '/^current.index:/ { print $NF }')
		echo "verify changelogs are on: $last_rec != ${LAST_REC[mds$i]}"
		[ $last_rec != ${LAST_REC[mds$i]} ] ||
			error "changelogs are off on mds$i"
	done
}
run_test 160i "changelog user register/unregister race"

test_160j() {
	remote_mds_nodsh && skip "remote MDS with nodsh"
	[[ $MDS1_VERSION -lt $(version_code 2.12.56) ]] &&
		skip "Need MDS version at least 2.12.56"

	mount_client $MOUNT2 || error "mount_client on $MOUNT2 failed"
	stack_trap "umount $MOUNT2" EXIT

	changelog_register || error "first changelog_register failed"
	stack_trap "changelog_deregister" EXIT

	# generate some changelog
	# use all_char because created files should be evenly distributed
	test_mkdir -c $MDSCOUNT -H all_char $DIR/$tdir ||
		error "mkdir $tdir failed"
	for ((i = 0; i < MDSCOUNT; i++)); do
		$LFS mkdir -i $i $DIR/$tdir/d$i.1 $DIR/$tdir/d$i.2 ||
			error "create $DIR/$tdir/d$i.1 failed"
	done

	# open the changelog device
	exec 3>/dev/changelog-$FSNAME-MDT0000
	stack_trap "exec 3>&-" EXIT
	exec 4</dev/changelog-$FSNAME-MDT0000
	stack_trap "exec 4<&-" EXIT

	# umount the first lustre mount
	umount $MOUNT
	stack_trap "mount_client $MOUNT" EXIT

	# read changelog, which may or may not fail, but should not crash
	cat <&4 >/dev/null

	# clear changelog
	local cl_user="${CL_USERS[$SINGLEMDS]%% *}"
	changelog_users $SINGLEMDS | grep -q $cl_user ||
		error "User $cl_user not found in changelog_users"

	printf 'clear:'$cl_user':0' >&3
}
run_test 160j "client can be umounted while its chanangelog is being used"

test_160k() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"

	mkdir -p $DIR/$tdir/1/1

	changelog_register || error "changelog_register failed"
	local cl_user="${CL_USERS[$SINGLEMDS]%% *}"

	changelog_users $SINGLEMDS | grep -q $cl_user ||
		error "User '$cl_user' not found in changelog_users"
#define OBD_FAIL_MDS_CHANGELOG_REORDER 0x15d
	do_facet mds1 $LCTL set_param fail_loc=0x8000015d fail_val=3
	rmdir $DIR/$tdir/1/1 & sleep 1
	mkdir $DIR/$tdir/2
	touch $DIR/$tdir/2/2
	rm -rf $DIR/$tdir/2

	wait
	sleep 4

	changelog_dump | grep rmdir || error "rmdir not recorded"
}
run_test 160k "Verify that changelog records are not lost"

# Verifies that a file passed as a parameter has recently had an operation
# performed on it that has generated an MTIME changelog which contains the
# correct parent FID. As files might reside on a different MDT from the
# parent directory in DNE configurations, the FIDs are translated to paths
# before being compared, which should be identical
compare_mtime_changelog() {
	local file="${1}"
	local mdtidx
	local mtime
	local cl_fid
	local pdir
	local dir

	mdtidx=$($LFS getstripe --mdt-index $file)
	mdtidx=$(printf "%04x" $mdtidx)

	# Obtain the parent FID from the MTIME changelog
	mtime=$($LFS changelog $FSNAME-MDT$mdtidx | tail -n 1 | grep MTIME)
	[ -z "$mtime" ] && error "MTIME changelog not recorded"

	cl_fid=$(sed -e 's/.* p=//' -e 's/ .*//' <<<$mtime)
	[ -z "$cl_fid" ] && error "parent FID not present"

	# Verify that the path for the parent FID is the same as the path for
	# the test directory
	pdir=$($LFS fid2path $MOUNT "$cl_fid")

	dir=$(dirname $1)

	[[ "${pdir%/}" == "$dir" ]] ||
		error "MTIME changelog parent FID is wrong, expected $dir, got $pdir"
}

test_160l() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	remote_mds_nodsh && skip "remote MDS with nodsh"
	[[ $MDS1_VERSION -ge $(version_code 2.13.55) ]] ||
		skip "Need MDS version at least 2.13.55"

	local cl_user

	changelog_register || error "changelog_register failed"
	cl_user="${CL_USERS[$SINGLEMDS]%% *}"

	changelog_users $SINGLEMDS | grep -q $cl_user ||
		error "User '$cl_user' not found in changelog_users"

	# Clear some types so that MTIME changelogs are generated
	changelog_chmask "-CREAT"
	changelog_chmask "-CLOSE"

	test_mkdir $DIR/$tdir || error "failed to mkdir $DIR/$tdir"

	# Test CL_MTIME during setattr
	touch $DIR/$tdir/$tfile
	compare_mtime_changelog $DIR/$tdir/$tfile

	# Test CL_MTIME during close
	$MULTIOP $DIR/$tdir/${tfile}_2 O_2w4096c || error "multiop failed"
	compare_mtime_changelog $DIR/$tdir/${tfile}_2
}
run_test 160l "Verify that MTIME changelog records contain the parent FID"

test_160m() {
	remote_mds_nodsh && skip "remote MDS with nodsh" && return
	[[ $MDS1_VERSION -ge $(version_code 2.14.51) ]] ||
		skip "Need MDS version at least 2.14.51"
	local cl_users
	local cl_user1
	local cl_user2
	local pid1

	# Create a user
	changelog_register || error "first changelog_register failed"
	changelog_register || error "second changelog_register failed"

	cl_users=(${CL_USERS[mds1]})
	cl_user1="${cl_users[0]}"
	cl_user2="${cl_users[1]}"
	# generate some changelog records to accumulate on MDT0
	test_mkdir -p -i0 -c1 $DIR/$tdir || error "test_mkdir $tdir failed"
	createmany -m $DIR/$tdir/$tfile 50 ||
		error "create $DIR/$tdir/$tfile failed"
	unlinkmany $DIR/$tdir/$tfile 50 || error "unlinkmany failed"
	rm -f $DIR/$tdir

	# check changelogs have been generated
	local nbcl=$(changelog_dump | wc -l)
	[[ $nbcl -eq 0 ]] && error "no changelogs found"

#define OBD_FAIL_MDS_CHANGELOG_RACE	 0x15f
	do_facet mds1 $LCTL set_param fail_loc=0x8000015f fail_val=0

	__changelog_clear mds1 $cl_user1 +10
	__changelog_clear mds1 $cl_user2 0 &
	pid1=$!
	sleep 2
	__changelog_clear mds1 $cl_user1 0 ||
		error "fail to cancel record for $cl_user1"
	wait $pid1
	[[ $? -eq 0 ]] || error "fail to cancel record for $cl_user2"
}
run_test 160m "Changelog clear race"

test_160n() {
	remote_mds_nodsh && skip "remote MDS with nodsh" && return
	[[ $MDS1_VERSION -ge $(version_code 2.14.51) ]] ||
		skip "Need MDS version at least 2.14.51"
	local cl_users
	local cl_user1
	local pid1
	local first_rec
	local last_rec=0

	# Create a user
	changelog_register || error "first changelog_register failed"

	cl_users=(${CL_USERS[mds1]})
	cl_user1="${cl_users[0]}"

	# generate some changelog records to accumulate on MDT0
	test_mkdir -i0 -c1 $DIR/$tdir || error "test_mkdir $tdir failed"
	first_rec=$(changelog_users $SINGLEMDS |
			awk '/^current.index:/ { print $NF }')
	while (( last_rec < (( first_rec + 65000)) )); do
		createmany -m $DIR/$tdir/$tfile 10000 ||
			error "create $DIR/$tdir/$tfile failed"

		for i in $(seq 0 10000); do
			mrename $DIR/$tdir/$tfile$i $DIR/$tdir/$tfile-new$i \
				> /dev/null
		done

		unlinkmany $DIR/$tdir/$tfile-new 10000 ||
			error "unlinkmany failed unlink"
		last_rec=$(changelog_users $SINGLEMDS |
			awk '/^current.index:/ { print $NF }')
		echo last record $last_rec
		(( last_rec == 0 )) && error "no changelog found"
	done

#define OBD_FAIL_MDS_CHANGELOG_DEL	 0x16c
	do_facet mds1 $LCTL set_param fail_loc=0x8000016c fail_val=0

	__changelog_clear mds1 $cl_user1 0 &
	pid1=$!
	sleep 2
	__changelog_clear mds1 $cl_user1 0 ||
		error "fail to cancel record for $cl_user1 (forground)"
	wait $pid1
	[[ $? -eq 0 ]] || error "fail to cancel record for $cl_user1 (background)"
}
run_test 160n "Changelog destroy race"

test_160o() {
	local mdt="$(facet_svc $SINGLEMDS)"

	[[ $PARALLEL != "yes" ]] || skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	[ $MDS1_VERSION -ge $(version_code 2.14.52) ] ||
		skip "Need MDS version at least 2.14.52"

	changelog_register --user test_160o -m unlnk+close+open ||
		error "changelog_register failed"

	do_facet $SINGLEMDS $LCTL --device $mdt \
				changelog_register -u "Tt3_-#" &&
		error "bad symbols in name should fail"

	do_facet $SINGLEMDS $LCTL --device $mdt \
				changelog_register -u test_160o &&
		error "the same name registration should fail"

	do_facet $SINGLEMDS $LCTL --device $mdt \
			changelog_register -u test_160toolongname &&
		error "too long name registration should fail"

	changelog_chmask "MARK+HSM"
	lctl get_param mdd.*.changelog*mask
	local cl_user="${CL_USERS[$SINGLEMDS]%% *}"
	changelog_users $SINGLEMDS | grep -q $cl_user ||
		error "User $cl_user not found in changelog_users"
	#verify username
	echo $cl_user | grep -q test_160o ||
		error "User $cl_user has no specific name 'test160o'"

	# change something
	changelog_clear 0 || error "changelog_clear failed"
	# generate some changelog records to accumulate on MDT0
	test_mkdir -p -i0 -c1 $DIR/$tdir || error "test_mkdir $tdir failed"
	touch $DIR/$tdir/$tfile			# open 1

	OPENS=$(changelog_dump | grep -c "OPEN")
	[[ $OPENS -eq 1 ]] || error "OPEN changelog mask count $OPENS != 1"

	# must be no MKDIR it wasn't set as user mask
	MKDIR=$(changelog_dump | grep -c "MKDIR")
	[[ $MKDIR -eq 0 ]] || error "MKDIR changelog mask found $MKDIR > 0"

	oldmask=$(do_facet $SINGLEMDS $LCTL get_param \
				mdd.$mdt.changelog_current_mask -n)
	# register maskless user
	changelog_register || error "changelog_register failed"
	# effective mask should be not changed because it is not minimal
	mask=$(do_facet $SINGLEMDS $LCTL get_param \
				mdd.$mdt.changelog_current_mask -n)
	[[ $mask == $oldmask ]] || error "mask was changed: $mask vs $oldmask"
	# set server mask to minimal value
	changelog_chmask "MARK"
	# check effective mask again, should be treated as DEFMASK now
	mask=$(do_facet $SINGLEMDS $LCTL get_param \
				mdd.$mdt.changelog_current_mask -n)
	[[ $mask == *"HLINK"* ]] || error "mask is not DEFMASK as expected"

	if (( $MDS1_VERSION >= $(version_code 2.15.52) )) ; then
		# set server mask back to some value
		changelog_chmask "CLOSE,UNLNK"
		# check effective mask again, should not remain as DEFMASK
		mask=$(do_facet $SINGLEMDS $LCTL get_param \
				mdd.$mdt.changelog_current_mask -n)
		[[ $mask != *"HLINK"* ]] || error "mask is still DEFMASK"
	fi

	do_facet $SINGLEMDS $LCTL --device $mdt \
				changelog_deregister -u test_160o ||
		error "cannot deregister by name"
}
run_test 160o "changelog user name and mask"

test_160p() {
	remote_mds_nodsh && skip "remote MDS with nodsh" && return
	[[ $MDS1_VERSION -ge $(version_code 2.14.51) ]] ||
		skip "Need MDS version at least 2.14.51"
	[[ "$mds1_FSTYPE" == "ldiskfs" ]] || skip "ldiskfs only test"
	local cl_users
	local cl_user1
	local entry_count

	# Create a user
	changelog_register || error "first changelog_register failed"

	cl_users=(${CL_USERS[mds1]})
	cl_user1="${cl_users[0]}"

	test_mkdir -p -i0 -c1 $DIR/$tdir || error "test_mkdir $tdir failed"
	createmany -m $DIR/$tdir/$tfile 50 ||
		error "create $DIR/$tdir/$tfile failed"
	unlinkmany $DIR/$tdir/$tfile 50 || error "unlinkmany failed"
	rm -rf $DIR/$tdir

	# check changelogs have been generated
	entry_count=$(changelog_dump | wc -l)
	((entry_count != 0)) || error "no changelog entries found"

	# remove changelog_users and check that orphan entries are removed
	stop mds1
	local dev=$(mdsdevname 1)
	do_facet mds1 "$DEBUGFS -w -R 'rm changelog_users' $dev"
	start mds1 $dev $MDS_MOUNT_OPTS || error "cannot start mds1"
	entry_count=$(changelog_dump | wc -l)
	((entry_count == 0)) ||
		error "found $entry_count changelog entries, expected none"
}
run_test 160p "Changelog orphan cleanup with no users"

test_160q() {
	local mdt="$(facet_svc $SINGLEMDS)"
	local clu

	[[ $PARALLEL != "yes" ]] || skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	[ $MDS1_VERSION -ge $(version_code 2.14.54) ] ||
		skip "Need MDS version at least 2.14.54"

	# set server mask to minimal value like server init does
	changelog_chmask "MARK"
	clu=$(do_facet $SINGLEMDS $LCTL --device $mdt changelog_register -n) ||
		error "changelog_register failed"
	# check effective mask again, should be treated as DEFMASK now
	mask=$(do_facet $SINGLEMDS $LCTL get_param \
				mdd.$mdt.changelog_current_mask -n)
	do_facet $SINGLEMDS $LCTL --device $mdt changelog_deregister $clu ||
		error "changelog_deregister failed"
	[[ $mask == *"HLINK"* ]] || error "mask is not DEFMASK as expected"
}
run_test 160q "changelog effective mask is DEFMASK if not set"

test_160s() {
	remote_mds_nodsh && skip "remote MDS with nodsh"
	(( $MDS1_VERSION >= $(version_code 2.14.55) )) ||
		skip "Need MDS version at least 2.14.55"

	local mdts=$(mdts_nodes)

	#define OBD_FAIL_TIME_IN_CHLOG_USER     0x1314
	do_nodes $mdts $LCTL set_param fail_loc=0x1314 \
				       fail_val=$((24 * 3600 * 10))

	# Create a user which is 10 days old
	changelog_register || error "first changelog_register failed"
	local cl_users
	declare -A cl_user1
	local i

	# generate some changelog records to accumulate on each MDT
	# use all_char because created files should be evenly distributed
	test_mkdir -c $MDSCOUNT -H all_char $DIR/$tdir ||
		error "test_mkdir $tdir failed"
	for ((idx = 0; idx < MDSCOUNT; idx++)); do
		$LFS mkdir -i $idx $DIR/$tdir/d$idx.1 $DIR/$tdir/d$idx.2 ||
			error "create $DIR/$tdir/d$idx.1 on MDT$idx failed"
	done

	# check changelogs have been generated
	local nbcl=$(changelog_dump | wc -l)
	(( nbcl > 0 )) || error "no changelogs found"

	# reduce the max_idle_indexes value to make sure we exceed it
	local gc_interval=2
	for param in "changelog_max_idle_indexes=2097446912" \
		     "changelog_max_idle_time=2592000" \
		     "changelog_gc=1" \
		     "changelog_min_gc_interval=$gc_interval"; do
		local MDT0=$(facet_svc $SINGLEMDS)
		local var="${param%=*}"
		local old=$(do_facet mds1 "$LCTL get_param -n mdd.$MDT0.$var")

		stack_trap "do_nodes $mdts $LCTL set_param mdd.*.$var=$old" EXIT
		do_nodes $mdts $LCTL set_param mdd.*.$param ||
			error "unable to set mdd.*.$param"
	done

	local start=$SECONDS
	for ((i=1; i <= $MDSCOUNT; i++)); do
		cl_users=(${CL_USERS[mds$i]})
		cl_user1[mds$i]="${cl_users[0]}"

		[[ -n "${cl_user1[mds$i]}" ]] ||
			error "mds$i: no user registered"
	done

	#define OBD_FAIL_MDS_CHANGELOG_IDX_PUMP   0x16d
	do_nodes $mdts $LCTL set_param fail_loc=0x16d fail_val=500000000

	# ensure we are past the previous changelog_min_gc_interval set above
	local sleep2=$((start + gc_interval + 1 - SECONDS))
	(( sleep2 > 0 )) && echo "sleep $sleep2 for interval" && sleep $sleep2

	# Generate one more changelog to trigger GC
	for ((i = 0; i < MDSCOUNT; i++)); do
		$LFS mkdir -i $i $DIR/$tdir/d$i.3 $DIR/$tdir/d$i.4 ||
			error "create $DIR/$tdir/d$i.3 failed"
	done

	# ensure gc thread is done
	for mds in ${mdts//,/ }; do
		wait_update $mds "pgrep chlg_gc_thread" "" 20 ||
			error "$mds: GC-thread not done"
	done

	do_nodes $mdts $LCTL set_param fail_loc=0

	for ((i = 1; i <= MDSCOUNT; i++)); do
		# check cl_user1 is purged
		changelog_users mds$i | grep -q "${cl_user1[mds$i]}" &&
			error "mds$i: User ${cl_user1[mds$i]} is registered"
	done
	return 0
}
run_test 160s "changelog garbage collect on idle records * time"

test_160t() {
	remote_mds_nodsh && skip "remote MDS with nodsh"
	(( $MDS1_VERSION >= $(version_code 2.15.50) )) ||
		skip "Need MDS version at least 2.15.50"

	local MDT0=$(facet_svc $SINGLEMDS)
	local cl_users
	local cl_user1
	local cl_user2
	local start

	changelog_register --user user1 -m all ||
		error "user1 failed to register"

	mkdir_on_mdt0 $DIR/$tdir
	# create default overstripe to maximize changelog size
	$LFS setstripe  -C 8 $DIR/$tdir || error "setstripe failed"
	createmany -o $DIR/$tdir/u1_ 2000 || error "createmany for user1 failed"
	stack_trap "unlinkmany $DIR/$tdir/u1_ 2000"
	llog_size1=$(do_facet mds1 $LCTL get_param -n mdd.$MDT0.changelog_size)

	# user2 consumes less records so less space
	changelog_register --user user2 || error "user2 failed to register"
	createmany -o $DIR/$tdir/u2_ 500 || error "createmany for user2 failed"
	llog_size2=$(do_facet mds1 $LCTL get_param -n mdd.$MDT0.changelog_size)

	# check changelogs have been generated
	local nbcl=$(changelog_dump | wc -l)
	(( nbcl > 0 )) || error "no changelogs found"

	# reduce the changelog_min_gc_interval to force check
	for param in "changelog_gc=1" "changelog_min_gc_interval=2"; do
		local var="${param%=*}"
		local old=$(do_facet mds1 "$LCTL get_param -n mdd.$MDT0.$var")

		stack_trap "do_facet mds1 $LCTL set_param mdd.$MDT0.$var=$old"
		do_facet mds1 $LCTL set_param mdd.$MDT0.$param ||
			error "unable to set mdd.*.$param"
	done

	start=$SECONDS
	cl_users=(${CL_USERS[mds1]})
	cl_user1="${cl_users[0]}"
	cl_user2="${cl_users[1]}"

	[[ -n $cl_user1 ]] ||
		error "mds1: user #1 isn't registered"
	[[ -n $cl_user2 ]] ||
		error "mds1: user #2 isn't registered"

	# ensure we are past the previous changelog_min_gc_interval set above
	local sleep2=$((start + 2 - SECONDS))
	(( sleep2 > 0 )) && echo "sleep $sleep2 for interval" && sleep $sleep2

	#define OBD_FAIL_MDS_CHANGELOG_ENOSPC 0x018c
	do_facet mds1 $LCTL set_param fail_loc=0x018c \
			fail_val=$(((llog_size1 + llog_size2) / 2))

	# Generate more changelog to trigger GC
	createmany -o $DIR/$tdir/u3_ 4 ||
		error "create failed for more files"

	# ensure gc thread is done
	wait_update_facet mds1 "pgrep chlg_gc_thread" "" 20 ||
		error "mds1: GC-thread not done"

	do_facet mds1 $LCTL set_param fail_loc=0

	# check cl_user1 is purged
	changelog_users mds1 | grep -q "$cl_user1" &&
		error "User $cl_user1 is registered"
	# check cl_user2 is not purged
	changelog_users mds1 | grep -q "$cl_user2" ||
		error "User $cl_user2 is not registered"
}
run_test 160t "changelog garbage collect on lack of space"

test_160u() { # LU-17400
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	[ $MDS1_VERSION -ge $(version_code 2.2.0) ] ||
		skip "Need MDS version at least 2.2.0"

	cd $DIR || error "cd $DIR failed"

	# ensure changelog has a clean view if tests are run multiple times
	[ -d rename ] && rm -rf rename

	changelog_register || error "changelog_register failed"
	local cl_user="${CL_USERS[$SINGLEMDS]%% *}"

	changelog_users $SINGLEMDS | grep -q $cl_user ||
		error "User '$cl_user' not found in changelog_users"

	local longname1=$(str_repeat a 255)

	echo "creating simple directory tree"
	mkdir -p rename/a || error "create of simple directory tree failed"
	echo "creating rename/hw file"
	echo "hello world" > rename/hw || error "create of rename/hw failed"
	echo "creating very long named file"
	touch rename/$longname1 || error "create of 'rename/$longname1' failed"
	echo "move rename/hw to rename/a/a.hw"
	mv rename/hw rename/a/a.hw || error "mv failed"

	RENME=($(changelog_dump | grep "RENME"))
	#declare -p RENME # for debugging captured value with indexes

	[[ "${RENME[11]}" == "a.hw" && "${RENME[14]}" == "hw" ]] ||
		error "changelog rename record type name/sname error"
}
run_test 160u "changelog rename record type name and sname strings are correct"

test_160v() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	(( CLIENTCOUNT >= 2 )) || skip "need >= 2 clients"
	[[ $MDS1_VERSION -ge $(version_code 2.17.50) ]] ||
		skip "Need MDS version at least 2.17.50"

	local target_mtime
	local mtime_after
	local saved_date

	test_mkdir $DIR/$tdir || error "failed to mkdir $DIR/$tdir"
	touch $DIR/$tdir/$tfile

	# Advance CLIENT2 clock so its touch sets ctime ahead
	saved_date=$(do_node $CLIENT2 date +%s)
	do_node $CLIENT2 date -s @$((saved_date + 5))
	stack_trap "do_node $CLIENT2 date -s @\$(date +%s)" EXIT

	do_node $CLIENT2 touch $MOUNT/$tdir/$tfile
	do_node $CLIENT2 date -s @$(date +%s)

	target_mtime=$(date -d "2020-01-01" +%s)

	# Local client sets mtime; ctime < file's ctime from CLIENT2
	touch -m -d @$target_mtime $DIR/$tdir/$tfile

	cancel_lru_locks mdc
	mtime_after=$(stat -c %Y $DIR/$tdir/$tfile)
	[[ "$mtime_after" == "$target_mtime" ]] ||
		error "mtime not updated: expected $target_mtime, got $mtime_after"
}
run_test 160v "setattr preserves mtime update despite inter-client clock skew"

test_160w() {
	[[ $PARALLEL == "yes" ]] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"

	(( $MDS1_VERSION >= $(version_code 2.17.50) )) ||
		skip "Need MDS >= 2.17.50 for changelog filtering"

	local mdt="$(facet_svc $SINGLEMDS)"
	local u1="u1"_$testnum
	local u2="u2"_$testnum
	local u1_id u2_id
	local count
	local logs

	mkdir_on_mdt0 $DIR/$tdir || error "mkdir $tdir failed"

	# Register two users with different masks
	changelog_register --user $u1 -m creat+unlnk ||
		error "changelog_register u1 failed"
	u1_id="${CL_USERS[$SINGLEMDS]%% *}"

	changelog_register --user $u2 -m mkdir+rmdir ||
		error "changelog_register u2 failed"
	u2_id="$(awk '{print $NF}' <<<"${CL_USERS[$SINGLEMDS]}")"

	changelog_users $SINGLEMDS
	changelog_clear $u1_id 0 || error "changelog_clear $u1 failed"
	changelog_clear $u2_id 0 || error "changelog_clear $u2 failed"

	# CREAT
	touch $DIR/$tdir/f1 || error "touch f1 failed"
	touch $DIR/$tdir/f2 || error "touch f2 failed"
	# MKDIR
	mkdir $DIR/$tdir/d1 || error "mkdir d1 failed"
	mkdir $DIR/$tdir/d2 || error "mkdir d2 failed"
	# UNLINK
	rm $DIR/$tdir/f1 || error "rm f1 failed"
	# RMDIR
	rmdir $DIR/$tdir/d1 || error "rmdir d1 failed"

	echo "lfs changelog --user (with different user formats)"
	logs=$($LFS changelog --user $u1 $mdt | head -10)
	[[ -n "$logs" ]] || error "$u1 should see changelog records"
	logs=$($LFS changelog --user $u2_id $mdt 0 | head -5)
	[[ -n "$logs" ]] || error "Startrec should work"

	echo "lfs changelog --user (should show all registered records)"
	# Show all records u1 registered
	logs=$($LFS changelog --user $u1 $mdt | tee >(cat >&2))
	count=$(grep -c -o -E "CREAT|UNLNK|MKDIR|RMDIR" <<< $logs)
	(( $count == 3 )) ||
		error "$u1 should see 3 total records, but got $count"
	# No MKDIR|RMDIR for u1
	count=$(echo $logs | grep -c -E "RMDIR|MKDIR")
	(( $count == 0 )) ||
		error "$u1 should see 0 MKDIR|RMDIR record, but got $count"

	echo "lfs changelog --user --mask (with registered mask)"
	logs=$($LFS changelog --user $u2_id --mask "mkdir+rmdir" $mdt |
		tee >(cat >&2))
	# MKDIR
	count=$(grep -c -o "MKDIR" <<< $logs)
	(( $count == 2 )) ||
		error "$u2_id should see 2 MKDIR records, but got $count"
	# RMDIR
	count=$(grep -c -o "RMDIR" <<< $logs)
	(( $count == 1 )) ||
		error "$u2_id should see 1 RMDIR record, bug got $count"
	# No CREAT|UNLNK for u2
	count=$(grep -c -E "CREAT|UNLNK" <<< $logs)
	(( $count == 0 )) ||
		error "$u2_id should see 0 CREAT|UNLNK record, but got $count"

	echo "lfs changelog --user --mask (including unregistered mask)"
	logs=$($LFS changelog --user $u1 --mask creat+rmdir $mdt |
		tee >(cat >&2))
	# CREAT
	count=$(grep -c -o "CREAT" <<< $logs)
	(( $count == 2 )) ||
		error "$u1 should see 2 CREAT records, but got $count"
	# No RMDIR for u1
	count=$(grep -c -o "RMDIR" <<< $logs)
	(( $count == 0 )) ||
		error "$u1 should see 0 RMDIR record, but got $count"

	rm -rf $DIR/$tdir
	changelog_deregister $u1 || error "cannot deregister $u1"
	changelog_deregister $u2 || error "cannot deregister $u2"
}
run_test 160w "lfs changelog --user --mask"

test_161a() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	test_mkdir -c1 $DIR/$tdir
	cp /etc/hosts $DIR/$tdir/$tfile
	test_mkdir -c1 $DIR/$tdir/foo1
	test_mkdir -c1 $DIR/$tdir/foo2
	ln $DIR/$tdir/$tfile $DIR/$tdir/foo1/sofia
	ln $DIR/$tdir/$tfile $DIR/$tdir/foo2/zachary
	ln $DIR/$tdir/$tfile $DIR/$tdir/foo1/luna
	ln $DIR/$tdir/$tfile $DIR/$tdir/foo2/thor
	local FID=$($LFS path2fid $DIR/$tdir/$tfile | tr -d '[]')
	if [ "$($LFS fid2path $DIR $FID | wc -l)" != "5" ]; then
		$LFS fid2path $DIR $FID
		error "bad link ea"
	fi
	# middle
	rm $DIR/$tdir/foo2/zachary
	# last
	rm $DIR/$tdir/foo2/thor
	# first
	rm $DIR/$tdir/$tfile
	# rename
	mv $DIR/$tdir/foo1/sofia $DIR/$tdir/foo2/maggie
	[ "$($LFS fid2path $FSNAME --link 1 $FID)" != "$tdir/foo2/maggie" ] &&
		{ $LFS fid2path $DIR $FID; error "bad link rename"; }
	rm $DIR/$tdir/foo2/maggie

	# overflow the EA
	local longname=$tfile.avg_len_is_thirty_two_
	stack_trap "unlinkmany $DIR/$tdir/foo2/$longname 1000 || \
		error_noexit 'failed to unlink many hardlinks'" EXIT
	createmany -l$DIR/$tdir/foo1/luna $DIR/$tdir/foo2/$longname 1000 ||
		error "failed to hardlink many files"
	links=$($LFS fid2path $DIR $FID | wc -l)
	echo -n "${links}/1000 links in link EA"
	[[ $links -gt 60 ]] || error "expected at least 60 links in link EA"
}
run_test 161a "link ea sanity"

test_161b() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ $MDSCOUNT -lt 2 ] && skip_env "skipping remote directory test"

	local MDTIDX=1
	local remote_dir=$DIR/$tdir/remote_dir

	mkdir -p $DIR/$tdir
	$LFS mkdir -i $MDTIDX $remote_dir ||
		error "create remote directory failed"

	cp /etc/hosts $remote_dir/$tfile
	mkdir -p $remote_dir/foo1
	mkdir -p $remote_dir/foo2
	ln $remote_dir/$tfile $remote_dir/foo1/sofia
	ln $remote_dir/$tfile $remote_dir/foo2/zachary
	ln $remote_dir/$tfile $remote_dir/foo1/luna
	ln $remote_dir/$tfile $remote_dir/foo2/thor

	local FID=$($LFS path2fid $remote_dir/$tfile | tr -d '[' |
		     tr -d ']')
	if [ "$($LFS fid2path $DIR $FID | wc -l)" != "5" ]; then
		$LFS fid2path $DIR $FID
		error "bad link ea"
	fi
	# middle
	rm $remote_dir/foo2/zachary
	# last
	rm $remote_dir/foo2/thor
	# first
	rm $remote_dir/$tfile
	# rename
	mv $remote_dir/foo1/sofia $remote_dir/foo2/maggie
	local link_path=$($LFS fid2path $FSNAME --link 1 $FID)
	if [ "$DIR/$link_path" != "$remote_dir/foo2/maggie" ]; then
		$LFS fid2path $DIR $FID
		error "bad link rename"
	fi
	rm $remote_dir/foo2/maggie

	# overflow the EA
	local longname=filename_avg_len_is_thirty_two_
	createmany -l$remote_dir/foo1/luna $remote_dir/foo2/$longname 1000 ||
		error "failed to hardlink many files"
	links=$($LFS fid2path $DIR $FID | wc -l)
	echo -n "${links}/1000 links in link EA"
	[[ ${links} -gt 60 ]] ||
		error "expected at least 60 links in link EA"
	unlinkmany $remote_dir/foo2/$longname 1000 ||
	error "failed to unlink many hardlinks"
}
run_test 161b "link ea sanity under remote directory"

test_161c() {
	remote_mds_nodsh && skip "remote MDS with nodsh"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[[ $MDS1_VERSION -lt $(version_code 2.1.5) ]] &&
		skip "Need MDS version at least 2.1.5"

	# define CLF_RENAME_LAST 0x0001
	# rename overwrite a target having nlink = 1 (changelog flag 0x1)
	changelog_register || error "changelog_register failed"

	rm -rf $DIR/$tdir
	test_mkdir -i $((MDSCOUNT - 1)) $DIR/$tdir
	touch $DIR/$tdir/foo_161c
	touch $DIR/$tdir/bar_161c
	mv -f $DIR/$tdir/foo_161c $DIR/$tdir/bar_161c
	changelog_dump | grep RENME | tail -n 5
	local flags=$(changelog_dump | grep "RENME.*bar_161c" | cut -f5 -d' ')
	changelog_clear 0 || error "changelog_clear failed"
	if [ x$flags != "x0x1" ]; then
		error "flag $flags is not 0x1"
	fi

	echo "rename overwrite target with nlink = 1, changelog flags=$flags"
	# rename overwrite a target having nlink > 1 (changelog flag 0x0)
	touch $DIR/$tdir/foo_161c
	touch $DIR/$tdir/bar_161c
	ln $DIR/$tdir/bar_161c $DIR/$tdir/foobar_161c
	mv -f $DIR/$tdir/foo_161c $DIR/$tdir/bar_161c
	changelog_dump | grep RENME | tail -n 5
	flags=$(changelog_dump | grep "RENME.*bar_161c" | cut -f5 -d' ')
	changelog_clear 0 || error "changelog_clear failed"
	if [ x$flags != "x0x0" ]; then
		error "flag $flags is not 0x0"
	fi
	echo "rename overwrite a target having nlink > 1," \
		"changelog record has flags of $flags"

	# rename doesn't overwrite a target (changelog flag 0x0)
	touch $DIR/$tdir/foo_161c
	mv -f $DIR/$tdir/foo_161c $DIR/$tdir/foo2_161c
	changelog_dump | grep RENME | tail -n 5
	flags=$(changelog_dump | grep RENME | tail -1 | cut -f5 -d' ')
	changelog_clear 0 || error "changelog_clear failed"
	if [ x$flags != "x0x0" ]; then
		error "flag $flags is not 0x0"
	fi
	echo "rename doesn't overwrite a target," \
		"changelog record has flags of $flags"

	# define CLF_UNLINK_LAST 0x0001
	# unlink a file having nlink = 1 (changelog flag 0x1)
	rm -f $DIR/$tdir/foo2_161c
	changelog_dump | grep UNLNK | tail -n 5
	flags=$(changelog_dump | grep UNLNK | tail -1 | cut -f5 -d' ')
	changelog_clear 0 || error "changelog_clear failed"
	if [ x$flags != "x0x1" ]; then
		error "flag $flags is not 0x1"
	fi
	echo "unlink a file having nlink = 1," \
		"changelog record has flags of $flags"

	# unlink a file having nlink > 1 (changelog flag 0x0)
	ln -f $DIR/$tdir/bar_161c $DIR/$tdir/foobar_161c
	rm -f $DIR/$tdir/foobar_161c
	changelog_dump | grep UNLNK | tail -n 5
	flags=$(changelog_dump | grep UNLNK | tail -1 | cut -f5 -d' ')
	changelog_clear 0 || error "changelog_clear failed"
	if [ x$flags != "x0x0" ]; then
		error "flag $flags is not 0x0"
	fi
	echo "unlink a file having nlink > 1, changelog record flags '$flags'"

	(( MDS1_VERSION >= $(version_code v2_16_53-39) )) ||
		{ echo "CLF_UNLINK_LAST is not set with open file (LU-18860)";
		return 0; }

	# unlink a file open having nlink = 1 (changelog flag 0x1)
	local pid
	touch $DIR/$tdir/open_161c
	tail -f $DIR/$tdir/open_161c & pid=$!
	sleep 0.2
	unlink $DIR/$tdir/open_161c
	kill $pid
	changelog_dump | grep UNLNK | tail -n 5
	flags=$(changelog_dump | awk '/UNLNK/ {f=$5} END {print f}')
	changelog_clear 0 || error "changelog_clear failed"
	[[ "$flags" == "0x1" ]] || error "flag $flags is not 0x1"
	echo "unlink a open file having nlink = 1, changelog record has flags of $flags"
}
run_test 161c "check CL_RENME[UNLINK] changelog record flags"

test_161d() {
	remote_mds_nodsh && skip "remote MDS with nodsh"

	local pid
	local fid

	changelog_register || error "changelog_register failed"

	# work in a standalone dir to avoid locking on $DIR/$MOUNT to
	# interfer with $MOUNT/.lustre/fid/ access
	mkdir $DIR/$tdir
	[[ $? -eq 0 ]] || error "mkdir failed"

	#define OBD_FAIL_LLITE_CREATE_NODE_PAUSE 0x140c | CFS_FAIL_ONCE
	$LCTL set_param fail_loc=0x8000140c
	# 5s pause
	$LCTL set_param fail_val=5

	# create file
	echo foofoo > $DIR/$tdir/$tfile &
	pid=$!

	# wait for create to be delayed
	sleep 2

	ps -p $pid
	[[ $? -eq 0 ]] || error "create should be blocked"

	local tempfile="$(mktemp --tmpdir $tfile.XXXXXX)"
	stack_trap "rm -f $tempfile"
	fid=$(changelog_extract_field "CREAT" "$tfile" "t=")
	$MULTIOP $MOUNT/.lustre/fid/$fid orp16384c >$tempfile || error "read failed"
	# some delay may occur during ChangeLog publishing and file read just
	# above, that could allow file write to happen finally
	[[ -s $tempfile ]] && echo "file should be empty"

	$LCTL set_param fail_loc=0

	wait $pid
	[[ $? -eq 0 ]] || error "create failed"
}
run_test 161d "create with concurrent .lustre/fid access"

check_path() {
	local expected="$1"
	shift
	local fid="$2"

	local path
	path=$($LFS fid2path "$@")
	local rc=$?

	if [ $rc -ne 0 ]; then
		error "path looked up of '$expected' failed: rc=$rc"
	elif [ "$path" != "$expected" ]; then
		error "path looked up '$path' instead of '$expected'"
	else
		echo "FID '$fid' resolves to path '$path' as expected"
	fi
}

test_162a() { # was test_162
	test_mkdir -p -c1 $DIR/$tdir/d2
	touch $DIR/$tdir/d2/$tfile
	touch $DIR/$tdir/d2/x1
	touch $DIR/$tdir/d2/x2
	test_mkdir -p -c1 $DIR/$tdir/d2/a/b/c
	test_mkdir -p -c1 $DIR/$tdir/d2/p/q/r
	# regular file
	local fid=$($LFS path2fid $DIR/$tdir/d2/$tfile | tr -d '[]')
	check_path "$tdir/d2/$tfile" $FSNAME "$fid" --link 0

	# softlink
	ln -s $DIR/$tdir/d2/$tfile $DIR/$tdir/d2/p/q/r/slink
	fid=$($LFS path2fid $DIR/$tdir/d2/p/q/r/slink | tr -d '[]')
	check_path "$tdir/d2/p/q/r/slink" $FSNAME "$fid" --link 0

	# softlink to wrong file
	ln -s /this/is/garbage $DIR/$tdir/d2/p/q/r/slink.wrong
	fid=$($LFS path2fid $DIR/$tdir/d2/p/q/r/slink.wrong | tr -d '[]')
	check_path "$tdir/d2/p/q/r/slink.wrong" $FSNAME "$fid" --link 0

	# hardlink
	ln $DIR/$tdir/d2/$tfile $DIR/$tdir/d2/p/q/r/hlink
	mv $DIR/$tdir/d2/$tfile $DIR/$tdir/d2/a/b/c/new_file
	fid=$($LFS path2fid $DIR/$tdir/d2/a/b/c/new_file | tr -d '[]')
	# fid2path dir/fsname should both work
	check_path "$tdir/d2/a/b/c/new_file" $FSNAME "$fid" --link 1
	check_path "$DIR/$tdir/d2/p/q/r/hlink" $DIR "$fid" --link 0

	# hardlink count: check that there are 2 links
	local nlinks=$($LFS fid2path $DIR "$fid" | wc -l)
	[ $nlinks -eq 2 ] || error "expect 2 links, found $nlinks"

	# hardlink indexing: remove the first link
	rm $DIR/$tdir/d2/p/q/r/hlink
	check_path "$tdir/d2/a/b/c/new_file" $FSNAME $fid --link 0
}
run_test 162a "path lookup sanity"

test_162b() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"

	mkdir $DIR/$tdir
	$LFS setdirstripe -i0 -c$MDSCOUNT -H all_char $DIR/$tdir/striped_dir ||
				error "create striped dir failed"

	local FID=$($LFS getdirstripe $DIR/$tdir/striped_dir |
					tail -n 1 | awk '{print $2}')
	stat $MOUNT/.lustre/fid/$FID && error "sub_stripe can be accessed"

	touch $DIR/$tdir/striped_dir/f{0..4} || error "touch f0..4 failed"
	mkdir $DIR/$tdir/striped_dir/d{0..4} || error "mkdir d0..4 failed"

	# regular file
	for ((i=0;i<5;i++)); do
		FID=$($LFS path2fid $DIR/$tdir/striped_dir/f$i | tr -d '[]') ||
			error "get fid for f$i failed"
		check_path "$tdir/striped_dir/f$i" $FSNAME $FID --link 0

		FID=$($LFS path2fid $DIR/$tdir/striped_dir/d$i | tr -d '[]') ||
			error "get fid for d$i failed"
		check_path "$tdir/striped_dir/d$i" $FSNAME $FID --link 0
	done

	return 0
}
run_test 162b "striped directory path lookup sanity"

# LU-4239: Verify fid2path works with paths 100 or more directories deep
test_162c() {
	[[ $MDS1_VERSION -lt $(version_code 2.7.51) ]] &&
		skip "Need MDS version at least 2.7.51"

	local lpath=$tdir.local
	local rpath=$tdir.remote

	test_mkdir $DIR/$lpath
	test_mkdir $DIR/$rpath
	stack_trap "rm -rf $DIR/$lpath $DIR/$rpath"

	for ((i = 0; i <= 101; i++)); do
		lpath="$lpath/$i"
		mkdir $DIR/$lpath
		FID=$($LFS path2fid $DIR/$lpath | tr -d '[]') ||
			error "get fid for local directory $DIR/$lpath failed"
		check_path "$DIR/$lpath" $MOUNT $FID --link 0

		rpath="$rpath/$i"
		test_mkdir $DIR/$rpath
		FID=$($LFS path2fid $DIR/$rpath | tr -d '[]') ||
			error "get fid for remote directory $DIR/$rpath failed"
		check_path "$DIR/$rpath" $MOUNT $FID --link 0
	done

	return 0
}
run_test 162c "fid2path works with paths 100 or more directories deep"

oalr_event_count() {
	local event="${1}"
	local trace="${2}"

	awk -v name="${FSNAME}-OST0000" \
	    -v event="${event}" \
	    '$1 == "TRACE" && $2 == event && $3 == name' \
	    "${trace}" |
	wc -l
}

oalr_expect_event_count() {
	local event="${1}"
	local trace="${2}"
	local expect="${3}"
	local count

	count=$(oalr_event_count "${event}" "${trace}")
	if ((count == expect)); then
		return 0
	fi

	error_noexit "${event} event count was '${count}', expected ${expect}"
	cat "${trace}" >&2
	exit 1
}

cleanup_165() {
	do_facet ost1 killall --quiet -KILL ofd_access_log_reader || true
	stop ost1
	start ost1 "$(ostdevname 1)" $OST_MOUNT_OPTS
}

setup_165() {
	sync # Flush previous IOs so we can count log entries.
	do_facet ost1 $LCTL set_param "obdfilter.${FSNAME}-OST0000.access_log_size=4096"
	stack_trap cleanup_165 EXIT
}

test_165a() {
	local trace="/tmp/${tfile}.trace"
	local rc
	local count

	(( $OST1_VERSION >= $(version_code 2.13.54) )) ||
		skip "OFD access log unsupported"

	setup_165
	do_facet ost1 ofd_access_log_reader --debug=- --trace=- > "${trace}" &
	sleep 5

	do_facet ost1 ofd_access_log_reader --list
	stop ost1

	do_facet ost1 killall -TERM ofd_access_log_reader
	wait
	rc=$?

	if ((rc != 0)); then
		error "ofd_access_log_reader exited with rc = '${rc}'"
	fi

	# Parse trace file for discovery events:
	oalr_expect_event_count alr_log_add "${trace}" 1
	oalr_expect_event_count alr_log_eof "${trace}" 1
	oalr_expect_event_count alr_log_free "${trace}" 1
}
run_test 165a "ofd access log discovery"

test_165b() {
	local trace="/tmp/${tfile}.trace"
	local file="${DIR}/${tfile}"
	local pfid1
	local pfid2
	local -a entry
	local rc
	local count
	local size
	local flags

	(( $OST1_VERSION >= $(version_code 2.13.54) )) ||
		skip "OFD access log unsupported"

	setup_165
	do_facet ost1 ofd_access_log_reader --debug=- --trace=- > "${trace}" &
	sleep 5

	do_facet ost1 ofd_access_log_reader --list

	lfs setstripe -c 1 -i 0 "${file}"
	$MULTIOP "${file}" oO_CREAT:O_DIRECT:O_WRONLY:w1048576c ||
		error "cannot create '${file}'"

	sleep 5
	do_facet ost1 killall -TERM ofd_access_log_reader
	wait
	rc=$?

	if ((rc != 0)); then
		error "ofd_access_log_reader exited with rc = '${rc}'"
	fi

	oalr_expect_event_count alr_log_entry "${trace}" 1

	pfid1=$($LFS path2fid "${file}")

	# 1     2             3   4    5     6   7    8    9     10
	# TRACE alr_log_entry OST PFID BEGIN END TIME SIZE COUNT FLAGS
	entry=( - $(awk -v pfid="${pfid}" '$1 == "TRACE" && $2 == "alr_log_entry"' "${trace}" ) )

	echo "entry = '${entry[*]}'" >&2

	pfid2=${entry[4]}
	if [[ "${pfid1}" != "${pfid2}" ]]; then
		error "entry '${entry[*]}' has invalid PFID '${pfid2}', expected ${pfid1}"
	fi

	size=${entry[8]}
	if ((size != 1048576)); then
		error "entry '${entry[*]}' has invalid io size '${size}', expected 1048576"
	fi

	flags=${entry[10]}
	if [[ "${flags}" != "w" ]]; then
		error "entry '${entry[*]}' has invalid io flags '${flags}', expected 'w'"
	fi

	do_facet ost1 ofd_access_log_reader --debug=- --trace=- > "${trace}" &
	sleep 5

	$MULTIOP "${file}" oO_CREAT:O_DIRECT:O_RDONLY:r524288c ||
		error "cannot read '${file}'"
	sleep 5

	do_facet ost1 killall -TERM ofd_access_log_reader
	wait
	rc=$?

	if ((rc != 0)); then
		error "ofd_access_log_reader exited with rc = '${rc}'"
	fi

	oalr_expect_event_count alr_log_entry "${trace}" 1

	entry=( - $(awk -v pfid="${pfid}" '$1 == "TRACE" && $2 == "alr_log_entry"' "${trace}" ) )
	echo "entry = '${entry[*]}'" >&2

	pfid2=${entry[4]}
	if [[ "${pfid1}" != "${pfid2}" ]]; then
		error "entry '${entry[*]}' has invalid PFID '${pfid2}', expected ${pfid1}"
	fi

	size=${entry[8]}
	if ((size != 524288)); then
		error "entry '${entry[*]}' has invalid io size '${size}', 524288"
	fi

	flags=${entry[10]}
	if [[ "${flags}" != "r" ]]; then
		error "entry '${entry[*]}' has invalid io flags '${flags}', expected 'r'"
	fi
}
run_test 165b "ofd access log entries are produced and consumed"

test_165c() {
	local trace="/tmp/${tfile}.trace"
	local file="${DIR}/${tdir}/${tfile}"

	(( $OST1_VERSION >= $(version_code 2.13.54) )) ||
		skip "OFD access log unsupported"

	test_mkdir "${DIR}/${tdir}"

	setup_165
	do_facet ost1 ofd_access_log_reader --debug=- --trace=- > "${trace}" &
	sleep 5

	lfs setstripe -c 1 -i 0 "${DIR}/${tdir}"

	# 4096 / 64 = 64. Create twice as many entries.
	for ((i = 0; i < 128; i++)); do
		$MULTIOP "${file}-${i}" oO_CREAT:O_WRONLY:w512c ||
			error "cannot create file"
	done

	sync

	do_facet ost1 killall -TERM ofd_access_log_reader
	wait
	rc=$?
	if ((rc != 0)); then
		error "ofd_access_log_reader exited with rc = '${rc}'"
	fi

	unlinkmany  "${file}-%d" 128
}
run_test 165c "full ofd access logs do not block IOs"

oal_get_read_count() {
	local stats="$1"

	# STATS lustre-OST0001 alr_read_count 1

	do_facet ost1 cat "${stats}" |
	awk '$1 == "STATS" && $3 == "alr_read_count" { count = $4; }
	     END { print count; }'
}

oal_expect_read_count() {
	local stats="$1"
	local count
	local expect="$2"

	# Ask ofd_access_log_reader to write stats.
	do_facet ost1 killall -USR1 ofd_access_log_reader

	# Allow some time for things to happen.
	sleep 1

	count=$(oal_get_read_count "${stats}")
	if ((count == expect)); then
		return 0
	fi

	error_noexit "bad read count, got ${count}, expected ${expect}"
	do_facet ost1 cat "${stats}" >&2
	exit 1
}

test_165d() {
	local stats="/tmp/${tfile}.stats"
	local file="${DIR}/${tdir}/${tfile}"
	local param="obdfilter.${FSNAME}-OST0000.access_log_mask"

	(( $OST1_VERSION >= $(version_code 2.13.54) )) ||
		skip "OFD access log unsupported"

	test_mkdir "${DIR}/${tdir}"

	setup_165
	do_facet ost1 ofd_access_log_reader --stats="${stats}" &
	sleep 5

	lfs setstripe -c 1 -i 0 "${file}"

	do_facet ost1 lctl set_param "${param}=rw"
	$MULTIOP "${file}" oO_CREAT:O_DIRECT:O_WRONLY:w1048576c ||
		error "cannot create '${file}'"
	oal_expect_read_count "${stats}" 1

	$MULTIOP "${file}" oO_CREAT:O_DIRECT:O_RDONLY:r1048576c ||
		error "cannot read '${file}'"
	oal_expect_read_count "${stats}" 2

	do_facet ost1 lctl set_param "${param}=r"
	$MULTIOP "${file}" oO_CREAT:O_DIRECT:O_WRONLY:w1048576c ||
		error "cannot create '${file}'"
	oal_expect_read_count "${stats}" 2

	$MULTIOP "${file}" oO_CREAT:O_DIRECT:O_RDONLY:r1048576c ||
		error "cannot read '${file}'"
	oal_expect_read_count "${stats}" 3

	do_facet ost1 lctl set_param "${param}=w"
	$MULTIOP "${file}" oO_CREAT:O_DIRECT:O_WRONLY:w1048576c ||
		error "cannot create '${file}'"
	oal_expect_read_count "${stats}" 4

	$MULTIOP "${file}" oO_CREAT:O_DIRECT:O_RDONLY:r1048576c ||
		error "cannot read '${file}'"
	oal_expect_read_count "${stats}" 4

	do_facet ost1 lctl set_param "${param}=0"
	$MULTIOP "${file}" oO_CREAT:O_DIRECT:O_WRONLY:w1048576c ||
		error "cannot create '${file}'"
	oal_expect_read_count "${stats}" 4

	$MULTIOP "${file}" oO_CREAT:O_DIRECT:O_RDONLY:r1048576c ||
		error "cannot read '${file}'"
	oal_expect_read_count "${stats}" 4

	do_facet ost1 killall -TERM ofd_access_log_reader
	wait
	rc=$?
	if ((rc != 0)); then
		error "ofd_access_log_reader exited with rc = '${rc}'"
	fi
}
run_test 165d "ofd_access_log mask works"

test_165e() {
	local stats="/tmp/${tfile}.stats"
	local file0="${DIR}/${tdir}-0/${tfile}"
	local file1="${DIR}/${tdir}-1/${tfile}"

	(( $OST1_VERSION >= $(version_code 2.13.54) )) ||
		skip "OFD access log unsupported"

	[[ $MDSCOUNT -lt 2 ]] && skip_env "needs >= 2 MDTs"

	test_mkdir -c 1 -i 0 "${DIR}/${tdir}-0"
	test_mkdir -c 1 -i 1 "${DIR}/${tdir}-1"

	lfs setstripe -c 1 -i 0 "${file0}"
	lfs setstripe -c 1 -i 0 "${file1}"

	setup_165
	do_facet ost1 ofd_access_log_reader -I 1 --stats="${stats}" &
	sleep 5

	$MULTIOP "${file0}" oO_CREAT:O_WRONLY:w512c ||
		error "cannot create '${file0}'"
	sync
	oal_expect_read_count "${stats}" 0

	$MULTIOP "${file1}" oO_CREAT:O_WRONLY:w512c ||
		error "cannot create '${file1}'"
	sync
	oal_expect_read_count "${stats}" 1

	do_facet ost1 killall -TERM ofd_access_log_reader
	wait
	rc=$?
	if ((rc != 0)); then
		error "ofd_access_log_reader exited with rc = '${rc}'"
	fi
}
run_test 165e "ofd_access_log MDT index filter works"

test_165f() {
	local trace="/tmp/${tfile}.trace"
	local rc
	local count

	setup_165
	do_facet ost1 timeout 60 ofd_access_log_reader \
		--exit-on-close --debug=- --trace=- > "${trace}" &
	sleep 5
	stop ost1

	wait
	rc=$?

	if ((rc != 0)); then
		error_noexit "ofd_access_log_reader exited with rc = '${rc}'"
		cat "${trace}"
		exit 1
	fi
}
run_test 165f "ofd_access_log_reader --exit-on-close works"

test_165g() {
	local count
	local trace=$TMP/${tfile}.trace
	local ofd_keepalive=$(do_facet ost1 ofd_access_log_reader --help |
				grep keepalive)

	[[ -n "$ofd_keepalive" ]] || skip "ALR keepalive message unsupported"

	setup_165
	do_facet ost1 timeout 60 ofd_access_log_reader \
		--keepalive=3 --batch-interval=4 --debug=- > "${trace}" &
	sleep 40
	stop ost1

	do_facet ost1 killall -TERM ofd_access_log_reader
	wait
	rc=$?

	if ((rc != 0)); then
		error "ofd_access_log_reader exited with rc = '${rc}'"
	fi

	count=$(grep -c "send keepalive" ${trace})

	# Normal duration 40 seconds / 4 secs interval = 10 times or so.
	# But sometimes the duration may be unpredictably long
	(( count >= 7 )) || error "keepalive msg received $count. Expected >= 7"

	echo "keepalive msg received $count"
}
run_test 165g "ofd_access_log_reader --keepalive works"

test_169() {
	# do directio so as not to populate the page cache
	log "creating a 10 Mb file"
	$MULTIOP $DIR/$tfile oO_CREAT:O_DIRECT:O_RDWR:w$((10*1048576))c ||
		error "multiop failed while creating a file"
	log "starting reads"
	dd if=$DIR/$tfile of=/dev/null bs=4096 &
	log "truncating the file"
	$MULTIOP $DIR/$tfile oO_TRUNC:c ||
		error "multiop failed while truncating the file"
	log "killing dd"
	kill %+ || true # reads might have finished
	echo "wait until dd is finished"
	wait
	log "removing the temporary file"
	rm -rf $DIR/$tfile || error "tmp file removal failed"
}
run_test 169 "parallel read and truncate should not deadlock"

test_170a() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	$LCTL clear	# bug 18514
	$LCTL debug_daemon start $TMP/${tfile}_log_good
	touch $DIR/$tfile
	$LCTL debug_daemon stop
	sed -e "s/^...../a/g" $TMP/${tfile}_log_good > $TMP/${tfile}_log_bad ||
		error "sed failed to read log_good"

	$LCTL debug_daemon start $TMP/${tfile}_log_good
	rm -rf $DIR/$tfile
	$LCTL debug_daemon stop

        $LCTL df $TMP/${tfile}_log_bad > $TMP/${tfile}_log_bad.out 2>&1 ||
               error "lctl df log_bad failed"

        local bad_line=$(tail -n 1 $TMP/${tfile}_log_bad.out | awk '{print $9}')
        local good_line1=$(tail -n 1 $TMP/${tfile}_log_bad.out | awk '{print $5}')

        $LCTL df $TMP/${tfile}_log_good > $TMP/${tfile}_log_good.out 2>&1
        local good_line2=$(tail -n 1 $TMP/${tfile}_log_good.out | awk '{print $5}')

	[ "$bad_line" ] && [ "$good_line1" ] && [ "$good_line2" ] ||
		error "bad_line good_line1 good_line2 are empty"

        cat $TMP/${tfile}_log_good >> $TMP/${tfile}_logs_corrupt
        cat $TMP/${tfile}_log_bad >> $TMP/${tfile}_logs_corrupt
        cat $TMP/${tfile}_log_good >> $TMP/${tfile}_logs_corrupt

        $LCTL df $TMP/${tfile}_logs_corrupt > $TMP/${tfile}_log_bad.out 2>&1
        local bad_line_new=$(tail -n 1 $TMP/${tfile}_log_bad.out | awk '{print $9}')
        local good_line_new=$(tail -n 1 $TMP/${tfile}_log_bad.out | awk '{print $5}')

	[ "$bad_line_new" ] && [ "$good_line_new" ] ||
		error "bad_line_new good_line_new are empty"

        local expected_good=$((good_line1 + good_line2*2))

        rm -f $TMP/${tfile}*
	# LU-231, short malformed line may not be counted into bad lines
        if [ $bad_line -ne $bad_line_new ] &&
		   [ $bad_line -ne $((bad_line_new - 1)) ]; then
                error "expected $bad_line bad lines, but got $bad_line_new"
                return 1
        fi

        if [ $expected_good -ne $good_line_new ]; then
                error "expected $expected_good good lines, but got $good_line_new"
                return 2
        fi
        true
}
run_test 170a "test lctl df to handle corrupted log"

test_170b() {
	# enable filename encoding on one client, ost and mdt respectively
	declare -a old_fl
	local param="enable_fname_encoding"
	local nodes_list=$HOSTNAME
	local log=$TMP/sanity.$testnum
	local i=0

	(( $MDS1_VERSION >= $(version_code 2.16.52) )) &&
		nodes_list="$nodes_list,$(facet_active_host mds1)"
	(( $OST1_VERSION >= $(version_code 2.16.52) )) &&
		nodes_list="$nodes_list,$(facet_active_host ost1)"
	local_mode && nodes_list=$HOSTNAME

	old_fl=($(do_nodes $nodes_list $LCTL get_param -n $param))

	# Test with filename encoding on
	set_params_nodes $nodes_list "$param=on"
	for node in ${nodes_list//,/ }; do
		stack_trap "set_params_nodes $node "$param=${old_fl[$i]}""
		i=$((i+1))
	done
	do_nodes $nodes_list "$LCTL get_param -n $param" | grep 0 &&
		error "Failed to enable filename encoding on all the nodes"

	# Start full debug to collect the logs
	start_full_debug_logging $nodes_list
	do_nodes $nodes_list "$LCTL clear"

	# Do some operations on $tfile
	touch $DIR/$tfile || error "Failed to touch $tfile"
	cp $DIR/$tfile $DIR/$testnum.cp || error "Failed to cp $tfile"
	ln -s $DIR/$tfile $DIR/$testnum.ln || error "Failed to ln -s $tfile"
	$LFS migrate -c $OSTCOUNT $DIR/$tfile ||
		error "Failed to migrate $tfile"
	$LFS mirror extend -N $DIR/$tfile ||
		error "Failed to extend mirrored $tfile"
	mv $DIR/$tfile $DIR/$testnum.mv || error "Failed to mv $tfile"
	rm -f $DIR/$tfile $DIR/$testnum.* || error "Failed to rm $tfile"

	# Do some operations on $tdir
	mkdir -p $DIR/$tdir || error "Failed to mkdir $tdir"
	cp -r $DIR/$tdir $DIR/$testnum.cp || error "Failed to cp $tdir"
	ln -s $DIR/$tdir $DIR/$testnum.ln || error "Failed to ln -s $tdir"
	$LFS migrate -d -m 0 -c $MDSCOUNT $DIR/$tdir ||
		error "Failed to migrate $tdir"
	mv $DIR/$tdir $DIR/$testnum.mv || error "Failed to mv $tdir"
	rm -rf $DIR/$tdir $DIR/$testnum.* || error "Failed to rm $tdir"

	# Stop the full debug
	do_nodes $nodes_list "$LCTL dk > $log"
	stack_trap "do_nodes $nodes_list rm -f $log"
	stop_full_debug_logging

	# Verify if $tfile and $tdir names are encoded in the logs
	do_nodes $nodes_list "grep -E '$tfile|$tdir' $log" &&
		error "Still found '$tfile' and '$tdir' in the logs"
	return 0
}
run_test 170b "check filename encoding"

test_171() { # bug20592
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	#define OBD_FAIL_PTLRPC_DUMP_LOG         0x50e
	$LCTL set_param fail_loc=0x50e
	$LCTL set_param fail_val=3000
	multiop_bg_pause $DIR/$tfile O_s || true
	local MULTIPID=$!
	kill -USR1 $MULTIPID
	# cause log dump
	sleep 3
	wait $MULTIPID
	if dmesg | grep "recursive fault"; then
		error "caught a recursive fault"
	fi
	$LCTL set_param fail_loc=0
	true
}
run_test 171 "test libcfs_debug_dumplog_thread stuck in do_exit() ======"

test_172() {

	#define OBD_FAIL_OBD_CLEANUP  0x60e
	$LCTL set_param fail_loc=0x60e
	umount $MOUNT || error "umount $MOUNT failed"
	stack_trap "mount_client $MOUNT"

	(( $($LCTL dl | grep -E -c " osc | lov | lmv | mdc ") > 0 )) ||
		error "no client OBDs are remained"

	$LCTL dl | while read devno state type name foo; do
		case $type in
		lov|osc|lmv|mdc)
			$LCTL --device $name cleanup
			$LCTL --device $name detach
			;;
		*)
			# skip server devices
			;;
		esac
	done

	if (( $($LCTL dl | grep -E -c " osc | lov | lmv | mdc ") > 0 )); then
		$LCTL dl | grep -E " osc | lov | lmv | mdc "
		error "some client OBDs are still remained"
	fi

}
run_test 172 "manual device removal with lctl cleanup/detach ======"

# it would be good to share it with obdfilter-survey/iokit-libecho code
setup_obdecho_osc () {
        local rc=0
        local ost_nid=$1
        local obdfilter_name=$2
        echo "Creating new osc for $obdfilter_name on $ost_nid"
        # make sure we can find loopback nid
        $LCTL add_uuid $ost_nid $ost_nid >/dev/null 2>&1

        [ $rc -eq 0 ] && { $LCTL attach osc ${obdfilter_name}_osc     \
                           ${obdfilter_name}_osc_UUID || rc=2; }
        [ $rc -eq 0 ] && { $LCTL --device ${obdfilter_name}_osc setup \
                           ${obdfilter_name}_UUID  $ost_nid || rc=3; }
        return $rc
}

cleanup_obdecho_osc () {
        local obdfilter_name=$1
        $LCTL --device ${obdfilter_name}_osc cleanup >/dev/null
        $LCTL --device ${obdfilter_name}_osc detach  >/dev/null
        return 0
}

obdecho_test() {
        local OBD=$1
        local node=$2
	local pages=${3:-64}
        local rc=0
        local id

	local count=10
	local obd_size=$(get_obd_size $node $OBD)
	local page_size=$(get_page_size $node)
	if [[ -n "$obd_size" ]]; then
		local new_count=$((obd_size / (pages * page_size / 1024)))
		[[ $new_count -ge $count ]] || count=$new_count
	fi

        do_facet $node "$LCTL attach echo_client ec ec_uuid" || rc=1
        [ $rc -eq 0 ] && { do_facet $node "$LCTL --device ec setup $OBD" ||
                           rc=2; }
        if [ $rc -eq 0 ]; then
            id=$(do_facet $node "$LCTL --device ec create 1"  | awk '/object id/ {print $6}')
            [ ${PIPESTATUS[0]} -eq 0 -a -n "$id" ] || rc=3
        fi
        echo "New object id is $id"
	[ $rc -eq 0 ] && { do_facet $node "$LCTL --device ec getattr $id" ||
			   rc=4; }
	[ $rc -eq 0 ] && { do_facet $node "$LCTL --device ec "		       \
			   "test_brw $count w v $pages $id" || rc=4; }
	[ $rc -eq 0 ] && { do_facet $node "$LCTL --device ec destroy $id 1" ||
			   rc=4; }
	[ $rc -eq 0 ] || [ $rc -gt 2 ] &&
		{ do_facet $node "$LCTL --device ec cleanup" || rc=5; }
	[ $rc -eq 0 ] || [ $rc -gt 1 ] &&
		{ do_facet $node "$LCTL --device ec detach" || rc=6; }
	[ $rc -ne 0 ] && echo "obecho_create_test failed: $rc"
	return $rc
}

test_180a() {
	skip "obdecho on osc is no longer supported"
}
run_test 180a "test obdecho on osc"

test_180b() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_ost_nodsh && skip "remote OST with nodsh"

	do_rpc_nodes $(facet_active_host ost1) load_module obdecho/obdecho &&
		stack_trap "do_facet ost1 rmmod obdecho" EXIT ||
		error "failed to load module obdecho"

	local target=$(do_facet ost1 $LCTL dl |
		       awk '/obdfilter/ { print $4; exit; }')

	if [ -n "$target" ]; then
		obdecho_test $target ost1 || error "obdecho_test failed with $?"
	else
		do_facet ost1 $LCTL dl
		error "there is no obdfilter target on ost1"
	fi
}
run_test 180b "test obdecho directly on obdfilter"

test_180c() { # LU-2598
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_ost_nodsh && skip "remote OST with nodsh"
	[[ $MDS1_VERSION -lt $(version_code 2.4.0) ]] &&
		skip "Need MDS version at least 2.4.0"

	do_rpc_nodes $(facet_active_host ost1) load_module obdecho/obdecho &&
		stack_trap "do_facet ost1 rmmod obdecho" EXIT ||
		error "failed to load module obdecho"

	local target=$(do_facet ost1 $LCTL dl |
		       awk '/obdfilter/ { print $4; exit; }')

	if [ -n "$target" ]; then
		local pages=16384 # 64MB bulk I/O RPC size

		obdecho_test "$target" ost1 "$pages" ||
			error "obdecho_test with pages=$pages failed with $?"
	else
		do_facet ost1 $LCTL dl
		error "there is no obdfilter target on ost1"
	fi
}
run_test 180c "test huge bulk I/O size on obdfilter, don't LASSERT"

test_181() { # bug 22177
	test_mkdir $DIR/$tdir
	# create enough files to index the directory
	createmany -o $DIR/$tdir/foobar 4000
	# print attributes for debug purpose
	lsattr -d .
	# open dir
	multiop_bg_pause $DIR/$tdir D_Sc || return 1
	MULTIPID=$!
	# remove the files & current working dir
	unlinkmany $DIR/$tdir/foobar 4000
	rmdir $DIR/$tdir
	kill -USR1 $MULTIPID
	wait $MULTIPID
	stat $DIR/$tdir && error "open-unlinked dir was not removed!"
	return 0
}
run_test 181 "Test open-unlinked dir ========================"

test_182a() {
	local fcount=1000
	local tcount=10

	mkdir -p $DIR/$tdir || error "creating dir $DIR/$tdir"

	$LCTL set_param mdc.*.rpc_stats=clear

	for (( i = 0; i < $tcount; i++ )) ; do
		mkdir $DIR/$tdir/$i
	done

	for (( i = 0; i < $tcount; i++ )) ; do
		createmany -o $DIR/$tdir/$i/f- $fcount &
	done
	wait

	for (( i = 0; i < $tcount; i++ )) ; do
		unlinkmany $DIR/$tdir/$i/f- $fcount &
	done
	wait

	$LCTL get_param mdc.*.rpc_stats

	rm -rf $DIR/$tdir
}
run_test 182a "Test parallel modify metadata operations from mdc"

test_182b() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run" && return
	[ $MDSCOUNT -lt 2 ] && skip "needs >= 2 MDTs" && return
	local dcount=1000
	local tcount=10
	local stime
	local etime
	local delta

	do_facet mds1 $LCTL list_param \
		osp.$FSNAME-MDT*-osp-MDT*.rpc_stats ||
		skip "MDS lacks parallel RPC handling"

	$LFS mkdir -i 0 $DIR/$tdir || error "creating dir $DIR/$tdir"

	rpc_count=$(do_facet mds1 $LCTL get_param -n \
		    osp.$FSNAME-MDT0001-osp-MDT0000.max_mod_rpcs_in_flight)

	stime=$(date +%s)
	createmany -i 0 -d $DIR/$tdir/t- $tcount

	for (( i = 0; i < $tcount; i++ )) ; do
		createmany -i 0 -d $DIR/$tdir/t-$i/d- 0 $dcount &
	done
	wait
	etime=$(date +%s)
	delta=$((etime - stime))
	echo "Time for file creation $delta sec for $rpc_count parallel RPCs"

	stime=$(date +%s)
	for (( i = 0; i < $tcount; i++ )) ; do
		unlinkmany -d $DIR/$tdir/$i/d- $dcount &
	done
	wait
	etime=$(date +%s)
	delta=$((etime - stime))
	echo "Time for file removal $delta sec for $rpc_count parallel RPCs"

	rm -rf $DIR/$tdir

	$LFS mkdir -i 0 $DIR/$tdir || error "creating dir $DIR/$tdir"

	do_facet mds1 $LCTL set_param osp.$FSNAME-MDT0001-osp-MDT0000.max_mod_rpcs_in_flight=1

	stime=$(date +%s)
	createmany -i 0 -d $DIR/$tdir/t- $tcount

	for (( i = 0; i < $tcount; i++ )) ; do
		createmany -i 0 -d $DIR/$tdir/t-$i/d- 0 $dcount &
	done
	wait
	etime=$(date +%s)
	delta=$((etime - stime))
	echo "Time for file creation $delta sec for 1 RPC sent at a time"

	stime=$(date +%s)
	for (( i = 0; i < $tcount; i++ )) ; do
		unlinkmany -d $DIR/$tdir/t-$i/d- $dcount &
	done
	wait
	etime=$(date +%s)
	delta=$((etime - stime))
	echo "Time for file removal $delta sec for 1 RPC sent at a time"

	do_facet mds1 $LCTL set_param osp.$FSNAME-MDT0001-osp-MDT0000.max_mod_rpcs_in_flight=$rpc_count
}
run_test 182b "Test parallel modify metadata operations from osp"

test_183() { # LU-2275
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	[[ $MDS1_VERSION -lt $(version_code 2.3.56) ]] &&
		skip "Need MDS version at least 2.3.56"

	mkdir_on_mdt0 $DIR/$tdir || error "creating dir $DIR/$tdir"
	echo aaa > $DIR/$tdir/$tfile

#define OBD_FAIL_MDS_NEGATIVE_POSITIVE  0x148
	do_facet $SINGLEMDS $LCTL set_param fail_loc=0x148

	ls -l $DIR/$tdir && error "ls succeeded, should have failed"
	cat $DIR/$tdir/$tfile && error "cat succeeded, should have failed"

	do_facet $SINGLEMDS $LCTL set_param fail_loc=0

	# Flush negative dentry cache
	touch $DIR/$tdir/$tfile

	# We are not checking for any leaked references here, they'll
	# become evident next time we do cleanup with module unload.
	rm -rf $DIR/$tdir
}
run_test 183 "No crash or request leak in case of strange dispositions ========"

# test suite 184 is for LU-2016, LU-2017
test_184a() {
	check_swap_layouts_support

	dir0=$DIR/$tdir/$testnum
	test_mkdir -p -c1 $dir0
	ref1=/etc/passwd
	ref2=/etc/group
	file1=$dir0/f1
	file2=$dir0/f2
	$LFS setstripe -c1 $file1
	cp $ref1 $file1
	$LFS setstripe -c2 $file2
	cp $ref2 $file2
	gen1=$($LFS getstripe -g $file1)
	gen2=$($LFS getstripe -g $file2)

	$LFS swap_layouts $file1 $file2 || error "swap of file layout failed"
	gen=$($LFS getstripe -g $file1)
	[[ $gen1 != $gen ]] ||
		error "Layout generation on $file1 does not change"
	gen=$($LFS getstripe -g $file2)
	[[ $gen2 != $gen ]] ||
		error "Layout generation on $file2 does not change"

	cmp $ref1 $file2 || error "content compare failed ($ref1 != $file2)"
	cmp $ref2 $file1 || error "content compare failed ($ref2 != $file1)"

	lfsck_verify_pfid $file1 $file2 || error "PFID are not transferred"
}
run_test 184a "Basic layout swap"

test_184b() {
	check_swap_layouts_support

	dir0=$DIR/$tdir/$testnum
	mkdir -p $dir0 || error "creating dir $dir0"
	file1=$dir0/f1
	file2=$dir0/f2
	file3=$dir0/f3
	dir1=$dir0/d1
	dir2=$dir0/d2
	mkdir $dir1 $dir2
	$LFS setstripe -c1 $file1
	$LFS setstripe -c2 $file2
	$LFS setstripe -c1 $file3
	chown $RUNAS_ID $file3
	gen1=$($LFS getstripe -g $file1)
	gen2=$($LFS getstripe -g $file2)

	$LFS swap_layouts $dir1 $dir2 &&
		error "swap of directories layouts should fail"
	$LFS swap_layouts $dir1 $file1 &&
		error "swap of directory and file layouts should fail"
	$RUNAS $LFS swap_layouts $file1 $file2 &&
		error "swap of file we cannot write should fail"
	$LFS swap_layouts $file1 $file3 &&
		error "swap of file with different owner should fail"
	/bin/true # to clear error code
}
run_test 184b "Forbidden layout swap (will generate errors)"

test_184c() {
	local cmpn_arg=$(cmp -n 2>&1 | grep "invalid option")
	[ -n "$cmpn_arg" ] && skip_env "cmp does not support -n"
	check_swap_layouts_support
	check_swap_layout_no_dom $DIR

	local dir0=$DIR/$tdir/$testnum
	mkdir -p $dir0 || error "creating dir $dir0"

	local ref1=$dir0/ref1
	local ref2=$dir0/ref2
	local file1=$dir0/file1
	local file2=$dir0/file2
	# create a file large enough for the concurrent test
	dd if=/dev/urandom of=$ref1 bs=1M count=$((RANDOM % 50 + 20))
	dd if=/dev/urandom of=$ref2 bs=1M count=$((RANDOM % 50 + 20))
	echo "ref file size: ref1($(stat -c %s $ref1))," \
	     "ref2($(stat -c %s $ref2))"

	cp $ref2 $file2
	dd if=$ref1 of=$file1 bs=16k &
	local DD_PID=$!

	# Make sure dd starts to copy file, but wait at most 5 seconds
	local loops=0
	while [ ! -s $file1 -a $((loops++)) -lt 50 ]; do sleep 0.1; done

	$LFS swap_layouts $file1 $file2
	local rc=$?
	wait $DD_PID
	[[ $? == 0 ]] || error "concurrent write on $file1 failed"
	[[ $rc == 0 ]] || error "swap of $file1 and $file2 failed"

	# how many bytes copied before swapping layout
	local copied=$(stat -c %s $file2)
	local remaining=$(stat -c %s $ref1)
	remaining=$((remaining - copied))
	echo "Copied $copied bytes before swapping layout..."

	cmp -n $copied $file1 $ref2 | grep differ &&
		error "Content mismatch [0, $copied) of ref2 and file1"
	cmp -n $copied $file2 $ref1 ||
		error "Content mismatch [0, $copied) of ref1 and file2"
	cmp -i $copied:$copied -n $remaining $file1 $ref1 ||
		error "Content mismatch [$copied, EOF) of ref1 and file1"

	# clean up
	rm -f $ref1 $ref2 $file1 $file2
}
run_test 184c "Concurrent write and layout swap"

test_184d() {
	check_swap_layouts_support
	check_swap_layout_no_dom $DIR
	[ -z "$(which getfattr 2>/dev/null)" ] &&
		skip_env "no getfattr command"

	local file1=$DIR/$tdir/$tfile-1
	local file2=$DIR/$tdir/$tfile-2
	local file3=$DIR/$tdir/$tfile-3
	local lovea1
	local lovea2

	mkdir -p $DIR/$tdir
	touch $file1 || error "create $file1 failed"
	$OPENFILE -f O_CREAT:O_LOV_DELAY_CREATE $file2 ||
		error "create $file2 failed"
	$OPENFILE -f O_CREAT:O_LOV_DELAY_CREATE $file3 ||
		error "create $file3 failed"
	lovea1=$(get_layout_param $file1)

	$LFS swap_layouts $file2 $file3 ||
		error "swap $file2 $file3 layouts failed"
	$LFS swap_layouts $file1 $file2 ||
		error "swap $file1 $file2 layouts failed"

	lovea2=$(get_layout_param $file2)
	echo "$lovea1"
	echo "$lovea2"
	[ "$lovea1" == "$lovea2" ] || error "lovea $lovea1 != $lovea2"

	lovea1=$(getfattr -n trusted.lov $file1 | grep ^trusted)
	[[ -z "$lovea1" ]] || error "$file1 shouldn't have lovea"
}
run_test 184d "allow stripeless layouts swap"

test_184e() {
	[[ $MDS1_VERSION -ge $(version_code 2.6.94) ]] ||
		skip "Need MDS version at least 2.6.94"
	check_swap_layouts_support
	check_swap_layout_no_dom $DIR
	[ -z "$(which getfattr 2>/dev/null)" ] &&
		skip_env "no getfattr command"

	local file1=$DIR/$tdir/$tfile-1
	local file2=$DIR/$tdir/$tfile-2
	local file3=$DIR/$tdir/$tfile-3
	local lovea

	mkdir -p $DIR/$tdir
	touch $file1 || error "create $file1 failed"
	$OPENFILE -f O_CREAT:O_LOV_DELAY_CREATE $file2 ||
		error "create $file2 failed"
	$OPENFILE -f O_CREAT:O_LOV_DELAY_CREATE $file3 ||
		error "create $file3 failed"

	$LFS swap_layouts $file1 $file2 ||
		error "swap $file1 $file2 layouts failed"

	lovea=$(getfattr -n trusted.lov $file1 | grep ^trusted)
	[[ -z "$lovea" ]] || error "$file1 shouldn't have lovea"

	echo 123 > $file1 || error "Should be able to write into $file1"

	$LFS swap_layouts $file1 $file3 ||
		error "swap $file1 $file3 layouts failed"

	echo 123 > $file1 || error "Should be able to write into $file1"

	rm -rf $file1 $file2 $file3
}
run_test 184e "Recreate layout after stripeless layout swaps"

test_184f() {
	# Create a file with name longer than sizeof(struct stat) ==
	# 144 to see if we can get chars from the file name to appear
	# in the returned striping. Note that 'f' == 0x66.
	local file=$(for ((i = 0; i < 200; i++)); do echo -n f; done)

	mkdir -p $DIR/$tdir
	mcreate $DIR/$tdir/$file
	if lfs find --stripe-count 0x6666 $DIR/$tdir | grep $file; then
		error "IOC_MDC_GETFILEINFO returned garbage striping"
	fi
}
run_test 184f "IOC_MDC_GETFILEINFO for files with long names but no striping"

test_185() { # LU-2441
	# LU-3553 - no volatile file support in old servers
	[[ $MDS1_VERSION -ge $(version_code 2.3.60) ]] ||
		skip "Need MDS version at least 2.3.60"

	mkdir -p $DIR/$tdir || error "creating dir $DIR/$tdir"
	touch $DIR/$tdir/spoo
	local mtime1=$(stat -c "%Y" $DIR/$tdir)
	local fid=$($MULTIOP $DIR/$tdir VFw4096c) ||
		error "cannot create/write a volatile file"
	$CHECKSTAT -t file $MOUNT/.lustre/fid/$fid 2>/dev/null &&
		error "FID is still valid after close"

	multiop_bg_pause $DIR/$tdir Vw4096_c
	local multi_pid=$!

	local OLD_IFS=$IFS
	IFS=":"
	local fidv=($fid)
	IFS=$OLD_IFS
	# assume that the next FID for this client is sequential, since stdout
	# is unfortunately eaten by multiop_bg_pause
	local n=$((${fidv[1]} + 1))
	local next_fid="${fidv[0]}:$(printf "0x%x" $n):${fidv[2]}"
	$CHECKSTAT -t file $MOUNT/.lustre/fid/$next_fid ||
		error "FID is missing before close"
	kill -USR1 $multi_pid
	# 1 second delay, so if mtime change we will see it
	sleep 1
	local mtime2=$(stat -c "%Y" $DIR/$tdir)
	[[ $mtime1 == $mtime2 ]] || error "mtime has changed"
}
run_test 185 "Volatile file support"

function create_check_volatile() {
	local idx=$1
	local tgt

	$MULTIOP $MOUNT/.lustre/fid V${idx}Fw4096_c >&/tmp/${tfile}.fid &
	local PID=$!
	sleep 1
	local FID=$(cat /tmp/${tfile}.fid)
	[ "$FID" == "" ] && error "can't get FID for volatile"
	$CHECKSTAT -t file $MOUNT/.lustre/fid/$FID || error "can't stat $FID"
	tgt=$($LFS getstripe -m $MOUNT/.lustre/fid/$FID)
	[ "$tgt" != "$idx" ] && error "wrong MDS $tgt, expected $idx"
	kill -USR1 $PID
	wait
	sleep 1
	cancel_lru_locks mdc # flush opencache
	$CHECKSTAT -t file $MOUNT/.lustre/fid/$FID && error "can stat $FID"
	return 0
}

test_185a(){
	# LU-12516 - volatile creation via .lustre
	(( $MDS1_VERSION >= $(version_code 2.12.55) )) ||
		skip "Need MDS version at least 2.12.55"
	[ -n "$FILESET" ] && skip "SKIP due to FILESET set"

	create_check_volatile 0
	[ $MDSCOUNT -lt 2 ] && return 0

	# DNE case
	create_check_volatile 1

	return 0
}
run_test 185a "Volatile file creation in .lustre/fid/"

test_187a() {
	remote_mds_nodsh && skip "remote MDS with nodsh"
	[ $MDS1_VERSION -lt $(version_code 2.3.0) ] &&
		skip "Need MDS version at least 2.3.0"

	local dir0=$DIR/$tdir/$testnum
	mkdir -p $dir0 || error "creating dir $dir0"

	local file=$dir0/file1
	dd if=/dev/urandom of=$file count=10 bs=1M conv=fsync
	stack_trap "rm -f $file"
	local dv1=$($LFS data_version $file)
	dd if=/dev/urandom of=$file seek=10 count=1 bs=1M conv=fsync
	local dv2=$($LFS data_version $file)
	[[ $dv1 != $dv2 ]] ||
		error "data version did not change on write $dv1 == $dv2"
}
run_test 187a "Test data version change"

test_187b() {
	remote_mds_nodsh && skip "remote MDS with nodsh"
	[ $MDS1_VERSION -lt $(version_code 2.3.0) ] &&
		skip "Need MDS version at least 2.3.0"

	local dir0=$DIR/$tdir/$testnum
	mkdir -p $dir0 || error "creating dir $dir0"

	declare -a DV=$($MULTIOP $dir0 Vw1000xYw1000xY | cut -f3 -d" ")
	[[ ${DV[0]} != ${DV[1]} ]] ||
		error "data version did not change on write"\
		      " ${DV[0]} == ${DV[1]}"

	# clean up
	rm -f $file1
}
run_test 187b "Test data version change on volatile file"

test_190a() {
	local test_dir="$DIR/$tdir"
	local test_file="$test_dir/$tfile"

	local prj=($(get_test_project))
	echo "proj - ${prj[0]} ${prj[1]}"
	[[ -n "$LIBLUSTREAPI_PROJID_FILE" ]] ||
		error "\$LIBLUSTREAPI_PROJID_FILE unset"
	[[ -f "$LIBLUSTREAPI_PROJID_FILE" ]] ||
		error "$LIBLUSTREAPI_PROJID_FILE does not exist"

	mkdir -p $test_dir || error "Failed to create test directory"
	touch $test_file || error "Failed to create test file"
	stack_trap "rm -rf $test_dir"

	# Set project using project name
	$LFS project -p ${prj[0]} $test_file || {
		cat $LIBLUSTREAPI_PROJID_FILE
		error "Failed to set project using name ${prj[0]}"
	}

	local set_id=$($LFS project -d $test_file | awk '{print $1}')
	[[ "$set_id" == "${prj[1]}" ]] ||
		error "Project ID mismatch: expected ${prj[1]}, got $set_id"
}
run_test 190a "check lfs project -p works with project name"

test_190b() {
	local test_dir="$DIR/$tdir"
	local MAX_FILES=100
	local fc

	[[ $SLOW == "yes" ]] && MAX_FILES=50000
	local prj=($(get_test_project))
	echo "proj - ${prj[0]} ${prj[1]}"

	mkdir -p $test_dir || error "Failed to create test directory"
	stack_trap "rm -rf $test_dir"

	local start=$SECONDS
	local end=$((start + 300))
	for ((fc = 1; fc <= MAX_FILES; fc++)); do
		echo "projid$fc:$fc:$tfile.$fc" >> $LIBLUSTREAPI_PROJID_FILE
		touch $test_dir/$tfile.$fc
		$LFS project -p projid$fc $test_dir/$tfile.$fc || {
			head -n 10 $LIBLUSTREAPI_PROJID_FILE
			error "Failed to set project 'projid$fc' on $tfile.$fc"
		}
		(( SECONDS < end )) || break
		(( fc % (MAX_FILES/10) == 0 )) &&
			echo "created $fc/$MAX_FILES files/projid in $((SECONDS-start))/$((end-start))s"
	done
	(( fc == MAX_FILES + 1 )) && fc=$MAX_FILES
	echo "created $fc/$MAX_FILES files/projid in $((SECONDS-start))/$((end-start))s"

	for i in {1..5}; do
		touch $test_dir/noproject_$i
	done

	# lfs find ! --projid files
	local count_usr=$($LFS find ! --projid 0 $test_dir | wc -l)
	(( count_usr == fc )) ||
		error "lfs find ! --projid 0 found $count_usr files != $fc"

	# lfs find --projid files
	count_usr=$($LFS find --projid 0 $test_dir | wc -l)
	(( count_usr == 6 )) ||
		error "lfs find --projid 0 found $count_usr files != 6"

	echo "lookup projid$fc timing:"
        time $LFS project -p projid$fc $MOUNT

	# lfs find --projid ID
	start=$SECONDS
	[[ "$SLOW" == "yes" ]] && end=600 || end=120
	(( end += start ))
	for ((i = 1; i < fc; i += fc / 5)); do
		echo "start scan for projid$i/$fc at $((end - SECONDS))"

		[[ -n $($LFS find --projid "projid$i" $test_dir) ]] ||
			error "lfs find --projid projid$i did not find result"

		((SECONDS < end)) || echo "timeout $((end - SECONDS))s" && break
	done
}
run_test 190b "check lfs find --project works with project name"

test_190c() {
	local test_dir="$DIR/$tdir"
	local test_file="$test_dir/$tfile"
	local TSTID=${TSTID:-"$(id -u $TSTUSR)"}

	mkdir -p $test_dir || error "Failed to create test directory"
	touch $test_file || error "Failed to create test file"

	# Set project using user name
	$LFS project -p u:$TSTUSR $test_file ||
		error "Failed to set project using username $TSTUSR"

	local set_id=$($LFS project -d $test_file | awk '{print $1}')
	(( set_id == TSTID )) ||
		error "Project ID mismatch: expect $TSTID, got $set_id"

	$LFS project -p 0 $test_file ||
		error "Failed to reset project"
	local set_id=$($LFS project -d $test_file | awk '{print $1}')
	(( set_id == 0 )) ||
		error "Project ID mismatch: expected 0, got $set_id"

	# Set project using uid
	$LFS project -p u:$TSTID $test_file ||
		error "Failed to set project using username $TSTUSR"

	set_id=$($LFS project -d $test_file | awk '{print $1}')
	(( set_id == TSTID )) ||
		error "Project ID mismatch: expect $TSTID, got $set_id"
}
run_test 190c "check lfs project -p works with u:USERNAME"

test_200() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mgs_nodsh && skip "remote MGS with nodsh"

	local POOL=${POOL:-cea1}
	local POOL_ROOT=${POOL_ROOT:-$DIR/$tdir}
	local POOL_DIR_NAME=${POOL_DIR_NAME:-dir_tst}
	# Pool OST targets
	local first_ost=0
	local last_ost=$(($OSTCOUNT - 1))
	local ost_step=2
	local ost_list=$(seq $first_ost $ost_step $last_ost)
	local ost_range="$first_ost $last_ost $ost_step"
	local test_path=$POOL_ROOT/$POOL_DIR_NAME
	local file_dir=$POOL_ROOT/file_tst
	local subdir=$test_path/subdir
	local rc=0

	while : ; do
		# former test_200a test_200b
		pool_add $POOL				|| { rc=$? ; break; }
		pool_add_targets  $POOL $ost_range	|| { rc=$? ; break; }
		# former test_200c test_200d
		mkdir -p $test_path
		pool_set_dir      $POOL $test_path	|| { rc=$? ; break; }
		pool_check_dir    $POOL $test_path	|| { rc=$? ; break; }
		mkdir -p $subdir
		pool_check_dir    $POOL $subdir		|| { rc=$? ; break; }
		pool_dir_rel_path $POOL $POOL_DIR_NAME $POOL_ROOT \
							|| { rc=$? ; break; }
		# former test_200e test_200f
		local files=$((OSTCOUNT*3))
		pool_alloc_files  $POOL $test_path $files "$ost_list" \
							|| { rc=$? ; break; }
		pool_create_files $POOL $file_dir $files "$ost_list" \
							|| { rc=$? ; break; }
		# former test_200g test_200h
		pool_lfs_df $POOL			|| { rc=$? ; break; }
		pool_file_rel_path $POOL $test_path	|| { rc=$? ; break; }

		# former test_201a test_201b test_201c
		pool_remove_first_target $POOL		|| { rc=$? ; break; }

		local f=$test_path/$tfile
		pool_remove_all_targets $POOL $f	|| { rc=$? ; break; }
		pool_remove $POOL $f			|| { rc=$? ; break; }
		break
	done

	destroy_test_pools

	return $rc
}
run_test 200 "OST pools"

# usage: default_attr <count | size | offset>
default_attr() {
	$LCTL get_param -n lov.$FSNAME-clilov-\*.stripe${1}
}

# usage: check_default_stripe_attr
check_default_stripe_attr() {
	ACTUAL=$($LFS getstripe $* $DIR/$tdir)
	case $1 in
	--stripe-count|-c)
		[ -n "$2" ] && EXPECTED=0 || EXPECTED=$(default_attr count);;
	--stripe-size|-S)
		[ -n "$2" ] && EXPECTED=0 || EXPECTED=$(default_attr size);;
	--stripe-index|-i)
		EXPECTED=-1;;
	*)
		error "unknown getstripe attr '$1'"
	esac

	[ $ACTUAL == $EXPECTED ] ||
		error "$DIR/$tdir has $1 '$ACTUAL', not '$EXPECTED'"
}

test_204a() {
	test_mkdir $DIR/$tdir
	$LFS setstripe --stripe-count 0 --stripe-size 0 --stripe-index -1 $DIR/$tdir

	check_default_stripe_attr --stripe-count
	check_default_stripe_attr --stripe-size
	check_default_stripe_attr --stripe-index
}
run_test 204a "Print default stripe attributes"

test_204b() {
	test_mkdir $DIR/$tdir
	$LFS setstripe --stripe-count 1 $DIR/$tdir

	check_default_stripe_attr --stripe-size
	check_default_stripe_attr --stripe-index
}
run_test 204b "Print default stripe size and offset"

test_204c() {
	test_mkdir $DIR/$tdir
	$LFS setstripe --stripe-size 65536 $DIR/$tdir

	check_default_stripe_attr --stripe-count
	check_default_stripe_attr --stripe-index
}
run_test 204c "Print default stripe count and offset"

test_204d() {
	test_mkdir $DIR/$tdir
	$LFS setstripe --stripe-index 0 $DIR/$tdir

	check_default_stripe_attr --stripe-count
	check_default_stripe_attr --stripe-size
}
run_test 204d "Print default stripe count and size"

test_204e() {
	test_mkdir $DIR/$tdir
	$LFS setstripe -d $DIR/$tdir

	# LU-16904 check if root is set as PFL layout
	local numcomp=$($LFS getstripe --component-count $MOUNT)

	if [[ $numcomp -gt 0 ]]; then
		check_default_stripe_attr --stripe-count
	else
		check_default_stripe_attr --stripe-count --raw
	fi
	check_default_stripe_attr --stripe-size --raw
	check_default_stripe_attr --stripe-index --raw
}
run_test 204e "Print raw stripe attributes"

test_204f() {
	test_mkdir $DIR/$tdir
	$LFS setstripe --stripe-count 1 $DIR/$tdir

	check_default_stripe_attr --stripe-size --raw
	check_default_stripe_attr --stripe-index --raw
}
run_test 204f "Print raw stripe size and offset"

test_204g() {
	test_mkdir $DIR/$tdir
	$LFS setstripe --stripe-size 65536 $DIR/$tdir

	check_default_stripe_attr --stripe-count --raw
	check_default_stripe_attr --stripe-index --raw
}
run_test 204g "Print raw stripe count and offset"

test_204h() {
	test_mkdir $DIR/$tdir
	$LFS setstripe --stripe-index 0 $DIR/$tdir

	check_default_stripe_attr --stripe-count --raw
	check_default_stripe_attr --stripe-size --raw
}
run_test 204h "Print raw stripe count and size"

# Figure out which job scheduler is being used, if any,
# or use a fake one
if [ -n "$SLURM_JOB_ID" ]; then # SLURM
	JOBENV=SLURM_JOB_ID
elif [ -n "$LSB_JOBID" ]; then # Load Sharing Facility
	JOBENV=LSB_JOBID
elif [ -n "$PBS_JOBID" ]; then # PBS/Maui/Moab
	JOBENV=PBS_JOBID
elif [ -n "$LOADL_STEPID" ]; then # LoadLeveller
	JOBENV=LOADL_STEP_ID
elif [ -n "$JOB_ID" ]; then # Sun Grid Engine
	JOBENV=JOB_ID
else
	$LCTL list_param jobid_name > /dev/null 2>&1
	if [ $? -eq 0 ]; then
		JOBENV=nodelocal
	else
		JOBENV=FAKE_JOBID
	fi
fi
LUSTRE_JOBID_SIZE=31 # plus NUL terminator

verify_jobstats() {
	local cmd=($1)
	shift
	local facets="$@"

# we don't really need to clear the stats for this test to work, since each
# command has a unique jobid, but it makes debugging easier if needed.
#	for facet in $facets; do
#		local dev=$(convert_facet2label $facet)
#		# clear old jobstats
#		do_facet $facet lctl set_param *.$dev.job_stats="clear"
#	done

	# use a new JobID for each test, or we might see an old one
	[ "$JOBENV" = "FAKE_JOBID" ] &&
		FAKE_JOBID=id.$testnum.$(basename ${cmd[0]}).$RANDOM

	JOBVAL=${!JOBENV:0:$LUSTRE_JOBID_SIZE}

	[ "$JOBENV" = "nodelocal" ] && {
		FAKE_JOBID=id.$testnum.%e.$RANDOM
		$LCTL set_param jobid_name=$FAKE_JOBID
		JOBVAL=${FAKE_JOBID/\%e/$(basename ${cmd[0]})}
	}

	log "Test: ${cmd[*]}"
	log "Using JobID environment $($LCTL get_param -n jobid_var)=$JOBVAL"

	if [ $JOBENV = "FAKE_JOBID" ]; then
		FAKE_JOBID=$JOBVAL ${cmd[*]}
	else
		${cmd[*]}
	fi

	# all files are created on OST0000
	for facet in $facets; do
		local stats="*.$(convert_facet2label $facet).job_stats"

		# strip out libtool wrappers for in-tree executables
		if (( $(do_facet $facet lctl get_param $stats |
			sed -e 's/\.lt-/./' | grep -cw $JOBVAL) != 1 )); then
			do_facet $facet lctl get_param $stats
			error "No jobstats for $JOBVAL found on $facet::$stats"
		fi
	done
}

jobstats_set() {
	local new_jobenv=$1

	set_persistent_param_and_check client "jobid_var" \
		"$FSNAME.sys.jobid_var" $new_jobenv
}

test_205a() { # Job stats
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[[ $MDS1_VERSION -ge $(version_code 2.7.1) ]] ||
		skip "Need MDS version with at least 2.7.1"
	remote_mgs_nodsh && skip "remote MGS with nodsh"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	remote_ost_nodsh && skip "remote OST with nodsh"
	[ -z "$(lctl get_param -n mdc.*.connect_flags | grep jobstats)" ] &&
		skip "Server doesn't support jobstats"
	[[ $JOBID_VAR = disable ]] && skip_env "jobstats is disabled"

	local old_jobenv=$($LCTL get_param -n jobid_var)
	[ $old_jobenv != $JOBENV ] && jobstats_set $JOBENV
	stack_trap "jobstats_set $old_jobenv" EXIT

	changelog_register

	local old_jobid_name=$($LCTL get_param jobid_name)
	stack_trap "$LCTL set_param $old_jobid_name" EXIT

	local old_interval=$(do_facet $SINGLEMDS lctl get_param -n \
				mdt.*.job_cleanup_interval | head -n 1)
	local new_interval=5
	do_facet $SINGLEMDS \
		$LCTL set_param mdt.*.job_cleanup_interval=$new_interval
	stack_trap "do_facet $SINGLEMDS \
		$LCTL set_param mdt.*.job_cleanup_interval=$old_interval" EXIT
	local start=$SECONDS

	local cmd
	# mkdir
	cmd="$LFS mkdir -i 0 -c 1 $DIR/$tdir"
	verify_jobstats "$cmd" "$SINGLEMDS"
	# rmdir
	cmd="rmdir $DIR/$tdir"
	verify_jobstats "$cmd" "$SINGLEMDS"
	# mkdir on secondary MDT
	if [ $MDSCOUNT -gt 1 ]; then
		cmd="lfs mkdir -i 1 $DIR/$tdir.remote"
		verify_jobstats "$cmd" "mds2"
	fi
	# mknod
	cmd="mknod $DIR/$tfile c 1 3"
	verify_jobstats "$cmd" "$SINGLEMDS"
	# unlink
	cmd="rm -f $DIR/$tfile"
	verify_jobstats "$cmd" "$SINGLEMDS"
	# create all files on OST0000 so verify_jobstats can find OST stats
	# open & close
	cmd="$LFS setstripe -i 0 -c 1 $DIR/$tfile"
	verify_jobstats "$cmd" "$SINGLEMDS"
	# setattr
	cmd="touch $DIR/$tfile"
	verify_jobstats "$cmd" "$SINGLEMDS ost1"
	# write
	cmd="dd if=/dev/zero of=$DIR/$tfile bs=1M count=1 oflag=sync"
	verify_jobstats "$cmd" "ost1"
	# read
	cancel_lru_locks osc
	cmd="dd if=$DIR/$tfile of=/dev/null bs=1M count=1 iflag=direct"
	verify_jobstats "$cmd" "ost1"
	# truncate
	cmd="$TRUNCATE $DIR/$tfile 0"
	verify_jobstats "$cmd" "$SINGLEMDS ost1"
	# rename
	cmd="mv -f $DIR/$tfile $DIR/$tdir.rename"
	verify_jobstats "$cmd" "$SINGLEMDS"
	# jobstats expiry - sleep until old stats should be expired
	local left=$((new_interval + 5 - (SECONDS - start)))
	[ $left -ge 0 ] && wait_update_facet $SINGLEMDS \
		"lctl get_param *.*.job_stats | grep -c 'job_id.*mkdir'" \
			"0" $left
	cmd="$LFS mkdir -i 0 -c 1 $DIR/$tdir.expire"
	verify_jobstats "$cmd" "$SINGLEMDS"
	[ $(do_facet $SINGLEMDS lctl get_param *.*.job_stats |
	    grep -c "job_id.*mkdir") -gt 1 ] && error "old jobstats not expired"

	# Ensure that jobid are present in changelog (if supported by MDS)
	if [ $MDS1_VERSION -ge $(version_code 2.6.52) ];then
		changelog_dump | tail -10
		jobids=$(changelog_dump | tail -9 | grep -c "j=")
		[ $jobids -eq 9 ] ||
			error "Wrong changelog jobid count $jobids != 9"

		# LU-5862
		JOBENV="disable"
		jobstats_set $JOBENV
		touch $DIR/$tfile
		changelog_dump | grep $tfile
		jobids=$(changelog_dump | grep $tfile | tail -1 | grep -c "j=")
		[ $jobids -eq 0 ] ||
			error "Unexpected jobids when jobid_var=$JOBENV"
	fi

	# test '%j' access to environment variable - if supported
	if lctl set_param jobid_var=USER jobid_name="S.%j.%e.%u.%h.E"; then
		JOBENV="JOBCOMPLEX"
		JOBCOMPLEX="S.$USER.touch.$(id -u).$(hostname).E"

		verify_jobstats "touch $DIR/$tfile" $SINGLEMDS
	fi

	if lctl set_param jobid_var=USER jobid_name="S.%j.%e.%u.%H.E"; then
		JOBENV="JOBCOMPLEX"
		JOBCOMPLEX="S.$USER.touch.$(id -u).$(hostname -s).E"

		verify_jobstats "touch $DIR/$tfile" $SINGLEMDS
	fi

	# test '%j' access to per-session jobid - if supported
	if lctl list_param jobid_this_session > /dev/null 2>&1
	then
		lctl set_param jobid_var=session jobid_name="S.%j.%e.%u.%h.E"
		lctl set_param jobid_this_session=$USER

		JOBENV="JOBCOMPLEX"
		JOBCOMPLEX="S.$USER.touch.$(id -u).$(hostname).E"

		verify_jobstats "touch $DIR/$tfile" $SINGLEMDS
	fi
}
run_test 205a "Verify job stats"

# LU-13117, LU-13597, LU-16599
test_205b() {
	(( $MDS1_VERSION >= $(version_code 2.13.54.91) )) ||
		skip "Need MDS version at least 2.13.54.91"

	local job_stats="mdt.*.job_stats"
	local old_jobid=$(do_facet mds1 $LCTL get_param jobid_var)

	do_facet mds1 $LCTL set_param $job_stats=clear

	# Setting jobid_var to USER might not be supported
	[[ -n "$old_jobid" ]] && stack_trap "$LCTL set_param $old_jobid"
	$LCTL set_param jobid_var=USER || true
	stack_trap "$LCTL set_param $($LCTL get_param jobid_name)"
	$LCTL set_param jobid_name="%j.%e.%u"

	env -i USERTESTJOBSTATS=foolish touch $DIR/$tfile.1
	do_facet mds1 $LCTL get_param $job_stats | grep "job_id:.*foolish" &&
		{ do_facet mds1 $LCTL get_param $job_stats;
		  error "Unexpected jobid found"; }
	do_facet mds1 $LCTL get_param $job_stats | grep "open:.*min.*max.*sum"||
		{ do_facet mds1 $LCTL get_param $job_stats;
		  error "wrong job_stats format found"; }

	(( $MDS1_VERSION <= $(version_code 2.15.0) )) &&
		echo "MDS does not yet escape jobid" && return 0

	mkdir_on_mdt0 $DIR/$tdir
	$LCTL set_param jobid_var=TEST205b
	env -i TEST205b="has sp" touch $DIR/$tdir/$tfile.2
	local jobid=$(do_facet mds1 $LCTL get_param $job_stats |
		      awk '/has\\x20sp/ {print $3}')
	[[ -n "$jobid" ]] || { do_facet mds1 $LCTL get_param $job_stats;
		  error "jobid not escaped"; }

	if (( $MDS1_VERSION >= $(version_code 2.15.53.139) )); then
		# need to run such a command on mds1:
		# lctl set_param mdt.$FSNAME-MDT0000.job_stats='"has\x20sp.touch.0"'
		#
		# there might be multiple MDTs on single mds server, so need to
		# specifiy MDT0000. Or the command will fail due to other MDTs
		do_facet_vp mds1 $LCTL set_param mdt.$FSNAME-MDT0000.job_stats=$jobid ||
			error "cannot clear escaped jobid in job_stats";
	else
		echo "MDS does not support clearing escaped jobid"
	fi
}
run_test 205b "Verify job stats jobid and output format"

# LU-13733
test_205c() {
	$LCTL set_param llite.*.stats=0
	dd if=/dev/zero of=$DIR/$tfile.1 bs=4k count=1
	$LCTL get_param llite.*.stats
	$LCTL get_param llite.*.stats | grep \
		"write_bytes *1 samples \[bytes\] 4096 4096 4096 16777216" ||
			error "wrong client stats format found"
}
run_test 205c "Verify client stats format"

test_205d() {
	local file=$DIR/$tdir/$tfile

	(( $MDS1_VERSION >= $(version_code 2.15.53) )) ||
		skip "need lustre >= 2.15.53 for lljobstat"
	(( $OST1_VERSION >= $(version_code 2.15.53) )) ||
		skip "need lustre >= 2.15.53 for lljobstat"
	verify_yaml_available || skip_env "YAML verification not installed"

	test_mkdir -i 0 $DIR/$tdir
	$LFS setstripe -E 1M -L mdt -E -1 $file || error "create file failed"
	stack_trap "rm -rf $DIR/$tdir"

	dd if=/dev/zero of=$file bs=1M count=10 conv=sync ||
		error "failed to write data to $file"
	mv $file $file.2

	do_facet mds1 "$LCTL get_param -n mdt.$FSNAME-MDT0000.rename_stats"
	echo -n 'verify rename_stats...'
	do_facet mds1 "$LCTL get_param -n mdt.$FSNAME-MDT0000.rename_stats" |
		verify_yaml || error "rename_stats is not valid YAML"
	echo " OK"

	echo -n 'verify mdt job_stats...'
	do_facet mds1 "$LCTL get_param -n mdt.$FSNAME-MDT0000.job_stats" |
		verify_yaml || error "job_stats on mds1 is not valid YAML"
	echo " OK"

	echo -n 'verify ost job_stats...'
	do_facet ost1 "$LCTL get_param -n obdfilter.$FSNAME-OST0000.job_stats" |
		verify_yaml || error "job_stats on ost1 is not valid YAML"
	echo " OK"
}
run_test 205d "verify the format of some stats files"

test_205e() {
	local ops_comma
	local file=$DIR/$tdir/$tfile
	local -a cli_params

	(( $MDS1_VERSION >= $(version_code 2.15.53) )) ||
		skip "need lustre >= 2.15.53 for lljobstat"
	(( $OST1_VERSION >= $(version_code 2.15.53) )) ||
		skip "need lustre >= 2.15.53 for lljobstat"
	verify_yaml_available || skip_env "YAML verification not installed"

	cli_params=( $($LCTL get_param jobid_name jobid_var) )
	$LCTL set_param jobid_var=nodelocal jobid_name=205e.%e.%u
	stack_trap "$LCTL set_param ${cli_params[*]}" EXIT

	mkdir_on_mdt0 $DIR/$tdir || error "failed to create dir"
	stack_trap "rm -rf $DIR/$tdir"

	$LFS setstripe -E EOF -i 0 -c 1 $file ||
		error "failed to create $file on ost1"
	dd if=/dev/zero of=$file bs=1M count=10 oflag=sync ||
		error "failed to write data to $file"

	do_facet mds1 "$LCTL get_param *.*.job_stats"
	do_facet ost1 "$LCTL get_param *.*.job_stats"

	do_facet ost1 "lljobstat -n 1 -i 0 -c 1000"
	do_facet ost1 "lljobstat -n 1 -i 0 -c 1000" | verify_yaml ||
		error "The output of lljobstat is not an valid YAML"

	# verify that job dd.0 does exist and has some ops on ost1
	# typically this line is like:
	# - 205e.dd.0:            {ops: 20, ...}
	ops_comma=$(do_facet ost1 "lljobstat -n 1 -i 0 -c 1000" |
		    awk '$2=="205e.dd.0:" {print $4}')

	(( ${ops_comma%,} >= 10 )) ||
		error "cannot find job 205e.dd.0 with ops >= 10"
}
run_test 205e "verify the output of lljobstat"

test_205f() {
	verify_yaml_available || skip_env "YAML verification not installed"

	# check both qos_ost_weights and qos_mdt_weights
	do_facet mds1 $LCTL get_param -n lod.*.qos*weights
	do_facet mds1 $LCTL get_param -n lod.*.qos*weights | verify_yaml ||
		error "qos_ost_weights is not valid YAML"
}
run_test 205f "verify qos_ost_weights YAML format "

__test_205_jobstats_dump() {
	local -a pids
	local nbr_instance=$1

	while true; do
		if (( ${#pids[@]} >= nbr_instance )); then
			wait ${pids[@]}
			pids=()
		fi

		do_facet mds1 "$LCTL get_param mdt.*.job_stats > /dev/null" &
		pids+=( $! )
	done
}

__test_205_cleanup() {
	kill $@
	# Clear all job entries
	do_facet mds1 "$LCTL set_param mdt.*.job_stats=clear"
}

test_205g() {
	local -a mds1_params
	local -a cli_params
	local pids
	local interval=5

	mds1_params=( $(do_facet mds1 $LCTL get_param mdt.*.job_cleanup_interval) )
	do_facet mds1 $LCTL set_param mdt.*.job_cleanup_interval=$interval
	stack_trap "do_facet mds1 $LCTL set_param ${mds1_params[*]}" EXIT

	cli_params=( $($LCTL get_param jobid_name jobid_var) )
	$LCTL set_param jobid_var=TEST205G_ID jobid_name=%j.%p
	stack_trap "$LCTL set_param ${cli_params[*]}" EXIT

	# start jobs loop
	export TEST205G_ID=205g
	stack_trap "unset TEST205G_ID" EXIT
	while true; do
		printf $DIR/$tfile.{0001..1000} | xargs -P10 -n1 touch
	done & pids="$! "

	__test_205_jobstats_dump 4 & pids+="$! "
	stack_trap "__test_205_cleanup $pids" EXIT INT

	[[ $SLOW == "no" ]] && sleep 90 || sleep 240
}
run_test 205g "stress test for job_stats procfile"

test_205h() {
	(( $MDS1_VERSION >= $(version_code 2.15.57.7) )) ||
		skip "Need MDS >= v2_15_57-7-g23a2db28dc for jobid xattr"
	which getfattr > /dev/null 2>&1 || skip_env "no getfattr command"

	local dir=$DIR/$tdir
	local f=$dir/$tfile
	local f2=$dir/$tfile-2
	local f3=$dir/$tfile-3
	local subdir=$DIR/dir
	local val

	local mdts=$(mdts_nodes)
	local mds_saved=$(do_facet mds1 $LCTL get_param -n mdt.$FSNAME-MDT0000.job_xattr)
	local client_saved=$($LCTL get_param -n jobid_var)

	stack_trap "do_nodes $mdts $LCTL set_param mdt.*.job_xattr=$mds_saved" EXIT
	stack_trap "$LCTL set_param jobid_var=$client_saved" EXIT

	do_nodes $mdts $LCTL set_param mdt.*.job_xattr=user.job ||
		error "failed to set job_xattr parameter to user.job"
	$LCTL set_param jobid_var=procname.uid ||
		error "failed to set jobid_var parameter"

	test_mkdir $dir

	touch $f
	val=$(getfattr -n user.job $f | grep user.job)
	[[ $val = user.job=\"touch.0\" ]] ||
		error "expected user.job=\"touch.0\", got '$val'"

	mkdir $subdir
	val=$(getfattr -n user.job $subdir | grep user.job)
	[[ $val = user.job=\"mkdir.0\" ]] ||
		error "expected user.job=\"mkdir.0\", got '$val'"

	do_nodes $mdts $LCTL set_param mdt.*.job_xattr=NONE ||
		error "failed to set job_xattr parameter to NONE"

	touch $f2
	val=$(getfattr -d $f2)
	[[ -z $val ]] ||
		error "expected no user xattr, got '$val'"

	do_nodes $mdts $LCTL set_param mdt.*.job_xattr=trusted.job ||
		error "failed to set job_xattr parameter to trusted.job"

	touch $f3
	val=$(getfattr -n trusted.job $f3 | grep trusted.job)
	[[ $val = trusted.job=\"touch.0\" ]] ||
		error "expected trusted.job=\"touch.0\", got '$val'"
}
run_test 205h "check jobid xattr is stored correctly"

test_205i() {
	(( $MDS1_VERSION >= $(version_code 2.15.57.7) )) ||
		skip "Need MDS >= v2_15_57-7-g23a2db28dc for jobid xattr"

	local mdts=$(mdts_nodes)
	local mds_saved=$(do_facet mds1 $LCTL get_param -n mdt.$FSNAME-MDT0000.job_xattr)

	stack_trap "do_nodes $mdts $LCTL set_param mdt.*.job_xattr=$mds_saved" EXIT

	do_nodes $mdts $LCTL set_param mdt.*.job_xattr=user.1234567 ||
		error "failed to set mdt.*.job_xattr to user.1234567"

	do_nodes $mdts $LCTL set_param mdt.*.job_xattr=user.12345678 &&
		error "failed to reject too long job_xattr name"

	do_nodes $mdts $LCTL set_param mdt.*.job_xattr=userjob &&
		error "failed to reject job_xattr name in bad format"

	do_nodes $mdts $LCTL set_param mdt.*.job_xattr=user.job/ &&
		error "failed to reject job_xattr name with invalid character"

	do_nodes $mdts "printf 'mdt.*.job_xattr=user.job\x80' |
			xargs $LCTL set_param" &&
		error "failed to reject job_xattr name with non-ascii character"

	return 0
}
run_test 205i "check job_xattr parameter accepts and rejects values correctly"

	# LU-17512
	# test '?' operator
test_205k(){
	(( MDS1_VERSION >= $(version_code 2.15.64.85) )) ||
		skip "need MDS >= v2_15_64-85-gecdcaa3986 for jobstats fix"

	# copied from test_205a
	[[ $PARALLEL == "yes" ]] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	[[ "$($LCTL get_param -n mdc.*.connect_flags)" =~ jobstats ]] ||
		skip "Server doesn't support jobstats"
	[[ "$JOBID_VAR" == "disable" ]] && skip_env "jobstats is disabled"

	local jobid_save=$($LCTL get_param jobid_var jobid_name)
	stack_trap "$LCTL set_param $jobid_save"

	do_facet mds1 $LCTL set_param mdt.*.job_stats=clear
	$LCTL set_param jobid_var=FAKE jobid_name=%j?%H:%e:%u
	cp -a /etc/hosts $DIR;
	job_id_name=($(do_facet mds1 $LCTL get_param mdt.*.job_stats |
		awk '/job_id:/ { print $3 }' | tr -d '"'))
	[[ "$job_id_name" == "$(hostname -s):cp:0" ]] ||
		error "expected $(hostname -s):cp:0, got $job_id_name instead"

	do_facet mds1 $LCTL set_param mdt.*.job_stats=clear
	$LCTL set_param jobid_var=USER jobid_name=%j?%H:%e:%u
	cp -a /etc/hosts $DIR;
	job_id_name=($(do_facet mds1 $LCTL get_param mdt.*.job_stats |
			awk '/job_id:/ { print $3 }' | tr -d '"'))
	[[ "$job_id_name" == "$USER:cp:0" ]] ||
		error "expected $USER:cp:0 but got $job_id_name instead"
}
run_test 205k "Verify '?' operator on job stats"

test_205l() {
	[[ $PARALLEL != "yes" ]] || skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	[[ "$($LCTL get_param -n mdc.*.connect_flags)" =~ jobstats ]] ||
		skip "Server doesn't support jobstats"
	[[ "$JOBID_VAR" != "disable" ]] || skip_env "jobstats is disabled"

	local jobid_save=$($LCTL get_param jobid_var jobid_name)
	stack_trap "$LCTL set_param $jobid_save"
	local tmpdir=$(mktemp -d /tmp/jobstat-XXXXXX)
	local jobs=$tmpdir/jobs.txt
	local mv_save=${tmpdir}/local_mv
	local mdts=$(mdts_nodes)
	local mv_job
	local n=1
	local limit=500
	[[ $SLOW == "no" ]] || limit=50000

	cp -a /etc/hosts $DIR/hosts
	cp $(which mv) ${mv_save}
	do_nodes $mdts "$LCTL set_param jobid_var=procname_uid jobid_name=%e.%u mdt.*.job_cleanup_interval=5"
	sleep 5
	do_nodes $mdts "$LCTL set_param mdt.*.job_stats=clear mdt.*.job_cleanup_interval=0"
	sleep 5
	# Add a series of easily identifyable jobs
	for ((n = 0; n < limit; n++)); do
		mv_job=${tmpdir}/mv.$(printf %08d $n)
		mv ${mv_save} ${mv_job}
		${mv_job} $DIR/hosts $DIR/hosts.$(printf %08d $n)
		${mv_job} $DIR/hosts.$(printf %08d $n) $DIR/hosts
		mv ${mv_job} ${mv_save}
	done
	# Duplicates indicate restart issues
	do_nodes $mdts \
		"$LCTL get_param mdt.*.job_stats | grep job_id: | cut -d. -f2" \
		> ${jobs}
	local dupes=$(grep -v -e "^${RUNAS_ID}\$" -e '^0$' ${jobs} | sort |
		      uniq -d | wc -l)
	(( ${dupes} == 0 )) ||
		error "seq_write wrote ${dupes} duplicate entries."
	# Unexpected jobs indicate cleanup issues
	local njobs=$(grep -v -e "^${RUNAS_ID}\$" -e '^0$' ${jobs} | wc -l)
	(( ${njobs} == ${limit} )) ||
		error "seq_write wrote ${njobs} jobs expected ${limit}."
	do_nodes $mdts "$LCTL set_param mdt.*.job_cleanup_interval=5"
	sleep 5
	do_nodes $mdts "$LCTL set_param mdt.*.job_stats=clear"
	# On success the scrach files are not interesting
	rm -fr ${tmpdir}
}
run_test 205l "Verify job stats can scale"

test_205m() {
	local trunc_hostname=${HOSTNAME:0:2}
	local dir=$DIR/205m/
	local tests=(
	    "%.3e.%u"       "cp /etc/hosts $dir" "cp.500"
	    "%.3e.%u"       "touch $dir/1"       "tou.500"
	    "%.3e.%u.%.2h"  "touch $dir/2"       "tou.500.${trunc_hostname}"
	    "%.3e"          "touch $dir/3"       "tou"
	    "%.1e.%u.%.2h"  "touch $dir/4"       "t.500.${trunc_hostname}"
	    "%.2p"          "touch $dir/8"       '${pid:0:2}'
	)

	cli_params=( $($LCTL get_param jobid_name jobid_var) )
	stack_trap "$LCTL set_param ${cli_params[*]}" EXIT
	stack_trap "do_facet mds1 $LCTL set_param mdt.*.job_stats=clear" EXIT

	mkdir $DIR/205m
	chown $RUNAS_ID $DIR/205m
	chgrp $RUNAS_ID $DIR/205m
	for (( i = 0; i < ${#tests[@]} ; i += 3 )); do
		local jobid_name=${tests[i]}
		local cmd=${tests[i+1]}

		do_facet mds1 $LCTL set_param mdt.*.job_stats=clear
		$LCTL set_param jobid_var=nodelocal jobid_name=${jobid_name}

		runas -u 500 $cmd & pid=$!
		wait $pid
		eval "expected=${tests[i+2]}"

		do_facet mds1 $LCTL get_param mdt.*.job_stats |
		awk '/job_id:/ {print} /job_id:/ && $3 == "'$expected'"
		{found=1} END {exit(!found)}' ||
			error "expected ${expected}, got ${job_id_name} instead"
	done
}
run_test 205m "Test width parsing of job_stats"

# LU-1480, LU-1773 and LU-1657
test_206() {
	mkdir -p $DIR/$tdir
	$LFS setstripe -c -1 $DIR/$tdir
#define OBD_FAIL_LOV_INIT 0x1403
	$LCTL set_param fail_loc=0xa0001403
	$LCTL set_param fail_val=1
	touch $DIR/$tdir/$tfile || true
}
run_test 206 "fail lov_init_raid0() doesn't lbug"

test_207a() {
	dd if=/dev/zero of=$DIR/$tfile bs=4k count=$((RANDOM%10+1))
	local fsz=`stat -c %s $DIR/$tfile`
	cancel_lru_locks mdc

	# do not return layout in getattr intent
#define OBD_FAIL_MDS_NO_LL_GETATTR 0x170
	$LCTL set_param fail_loc=0x170
	local sz=`stat -c %s $DIR/$tfile`

	[ $fsz -eq $sz ] || error "file size expected $fsz, actual $sz"

	rm -rf $DIR/$tfile
}
run_test 207a "can refresh layout at glimpse"

test_207b() {
	dd if=/dev/zero of=$DIR/$tfile bs=4k count=$((RANDOM%10+1))
	local cksum=`md5sum $DIR/$tfile`
	local fsz=`stat -c %s $DIR/$tfile`
	cancel_lru_locks mdc
	cancel_lru_locks osc

	# do not return layout in getattr intent
#define OBD_FAIL_MDS_NO_LL_OPEN 0x171
	$LCTL set_param fail_loc=0x171

	# it will refresh layout after the file is opened but before read issues
	echo checksum is "$cksum"
	echo "$cksum" |md5sum -c --quiet || error "file differs"

	rm -rf $DIR/$tfile
}
run_test 207b "can refresh layout at open"

test_208() {
	# FIXME: in this test suite, only RD lease is used. This is okay
	# for now as only exclusive open is supported. After generic lease
	# is done, this test suite should be revised. - Jinshan

	remote_mds_nodsh && skip "remote MDS with nodsh"
	[[ $MDS1_VERSION -ge $(version_code 2.4.52) ]] ||
		skip "Need MDS version at least 2.4.52"

	echo "==== test 1: verify get lease work"
	$MULTIOP $DIR/$tfile oO_CREAT:O_RDWR:eRE+eU || error "get lease error"

	echo "==== test 2: verify lease can be broken by upcoming open"
	$MULTIOP $DIR/$tfile oO_RDWR:eR_E-eUc &
	local PID=$!
	sleep 2

	$MULTIOP $DIR/$tfile oO_RDWR:c
	kill -USR1 $PID && wait $PID || error "break lease error"

	echo "==== test 3: verify lease can't be granted if an open already exists"
	$MULTIOP $DIR/$tfile oO_RDWR:_c &
	local PID=$!
	sleep 2

	$MULTIOP $DIR/$tfile oO_RDWR:eReUc && error "apply lease should fail"
	kill -USR1 $PID && wait $PID || error "open file error"

	echo "==== test 4: lease can sustain over recovery"
	$MULTIOP $DIR/$tfile oO_RDWR:eR_E+eUc &
	PID=$!
	sleep 2

	fail mds1

	kill -USR1 $PID && wait $PID || error "lease broken over recovery"

	echo "==== test 5: lease broken can't be regained by replay"
	$MULTIOP $DIR/$tfile oO_RDWR:eR_E-eUc &
	PID=$!
	sleep 2

	# open file to break lease and then recovery
	$MULTIOP $DIR/$tfile oO_RDWR:c || error "open file error"
	fail mds1

	kill -USR1 $PID && wait $PID || error "lease not broken over recovery"

	rm -f $DIR/$tfile
}
run_test 208 "Exclusive open"

test_209() {
	[ -z "$(lctl get_param -n mdc.*.connect_flags | grep disp_stripe)" ] &&
		skip_env "must have disp_stripe"

	touch $DIR/$tfile
	sync; sleep 5; sync;

	echo 3 > /proc/sys/vm/drop_caches
	[ -f /sys/kernel/slab/ptlrpc_cache/shrink ] &&
		echo 1 > /sys/kernel/slab/ptlrpc_cache/shrink
	req_before=$(awk '/ptlrpc_cache / { print $2 }' /proc/slabinfo)

	# open/close 500 times
	for i in $(seq 500); do
		cat $DIR/$tfile
	done

	echo 3 > /proc/sys/vm/drop_caches
	[ -f /sys/kernel/slab/ptlrpc_cache/shrink ] &&
		echo 1 > /sys/kernel/slab/ptlrpc_cache/shrink
	req_after=$(awk '/ptlrpc_cache / { print $2 }' /proc/slabinfo)

	echo "before: $req_before, after: $req_after"
	[ $((req_after - req_before)) -ge 300 ] &&
		error "open/close requests are not freed"
	return 0
}
run_test 209 "read-only open/close requests should be freed promptly"

test_210() {
	local pid

	$MULTIOP $DIR/$tfile oO_CREAT:O_RDWR:eW_E+eUc &
	pid=$!
	sleep 1

	$LFS getstripe $DIR/$tfile
	kill -USR1 $pid
	wait $pid || error "multiop failed"

	$MULTIOP $DIR/$tfile oO_RDONLY:eR_E+eUc &
	pid=$!
	sleep 1

	$LFS getstripe $DIR/$tfile
	kill -USR1 $pid
	wait $pid || error "multiop failed"
}
run_test 210 "lfs getstripe does not break leases"

test_212() {
	size=`date +%s`
	size=$((size % 8192 + 1))
	dd if=/dev/urandom of=$DIR/f212 bs=1k count=$size
	# check path2fid does not trigger nosplice operations
	$LFS path2fid $DIR/f212
	sendfile $DIR/f212 $DIR/f212.xyz || error "sendfile wrong"
	rm -f $DIR/f212 $DIR/f212.xyz
}
run_test 212 "Sendfile test"

test_213() {
	dd if=/dev/zero of=$DIR/$tfile bs=4k count=4
	cancel_lru_locks osc
	lctl set_param fail_loc=0x8000040f
	# generate a read lock
	cat $DIR/$tfile > /dev/null
	# write to the file, it will try to cancel the above read lock.
	cat /etc/hosts >> $DIR/$tfile
}
run_test 213 "OSC lock completion and cancel race don't crash - bug 18829"

test_214() { # for bug 20133
	mkdir -p $DIR/$tdir/d214c || error "mkdir $DIR/$tdir/d214c failed"
	for (( i=0; i < 340; i++ )) ; do
		touch $DIR/$tdir/d214c/a$i
	done

	ls -l $DIR/$tdir || error "ls -l $DIR/d214p failed"
	mv $DIR/$tdir/d214c $DIR/ || error "mv $DIR/d214p/d214c $DIR/ failed"
	ls $DIR/d214c || error "ls $DIR/d214c failed"
	rm -rf $DIR/$tdir || error "rm -rf $DIR/d214* failed"
	rm -rf $DIR/d214* || error "rm -rf $DIR/d214* failed"
}
run_test 214 "hash-indexed directory test - bug 20133"

# having "abc" as 1st arg, creates $TMP/lnet_abc.out and $TMP/lnet_abc.sys
create_lnet_proc_files() {
	lctl get_param -n $1 >$TMP/lnet_$1.sys || error "cannot read lnet.$1"
}

# counterpart of create_lnet_proc_files
remove_lnet_proc_files() {
	rm -f $TMP/lnet_$1.sys
}

# uses 1st arg as trailing part of filename, 2nd arg as description for reports,
# 3rd arg as regexp for body
check_lnet_proc_stats() {
	local l=$(cat "$TMP/lnet_$1" |wc -l)
	[ $l = 1 ] || (cat "$TMP/lnet_$1" && error "$2 is not of 1 line: $l")

	grep -E "$3" "$TMP/lnet_$1" ||
		(cat "$TMP/lnet_$1" && error "$2 misformatted")
}

# uses 1st arg as trailing part of filename, 2nd arg as description for reports,
# 3rd arg as regexp for body, 4th arg as regexp for 1st line, 5th arg is
# optional and can be regexp for 2nd line (lnet.routes case)
check_lnet_proc_entry() {
	local blp=2          # blp stands for 'position of 1st line of body'
	[ -z "$5" ] || blp=3 # lnet.routes case

	local l=$(cat "$TMP/lnet_$1" |wc -l)
	# subtracting one from $blp because the body can be empty
	[ "$l" -ge "$(($blp - 1))" ] || (cat "$TMP/lnet_$1" && error "$2 is too short: $l")

	sed -n '1 p' "$TMP/lnet_$1" |grep -E "$4" >/dev/null ||
		(cat "$TMP/lnet_$1" && error "1st line of $2 misformatted")

	[ "$5" = "" ] || sed -n '2 p' "$TMP/lnet_$1" |grep -E "$5" >/dev/null ||
		(cat "$TMP/lnet_$1" && error "2nd line of $2 misformatted")

	# bail out if any unexpected line happened
	sed -n "$blp p" "$TMP/lnet_$1" | grep -Ev "$3"
	[ "$?" != 0 ] || error "$2 misformatted"
}

test_215() { # for bugs 18102, 21079, 21517
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	local N='(0|[1-9][0-9]*)'       # non-negative numeric
	local P='[1-9][0-9]*'           # positive numeric
	local I='(0|-?[1-9][0-9]*|NA)'  # any numeric (0 | >0 | <0) or NA if no value
	local NET='[a-z][a-z0-9]*'      # LNet net like o2ib2
	local ADDR='[0-9.]+'            # LNet addr like 10.0.0.1
	local ADDR6='([0-9a-f]{0,4}:){2,7}[0-9a-f]{0,4}' # IPv6 LNet addr
	local NID="$ADDR@$NET"          # LNet nid like 10.0.0.1@o2ib2
	local NID6="$ADDR6@$NET"        # LNet nid like 2601:8c1:c180::cbdd@tcp

	local L1 # regexp for 1st line
	local L2 # regexp for 2nd line (optional)
	local BR # regexp for the rest (body)

	# lnet.stats should look as 11 space-separated non-negative numerics
	BR="^$N $N $N $N $N $N $N $N $N $N $N$"
	create_lnet_proc_files "stats"
	check_lnet_proc_stats "stats.sys" "lnet.stats" "$BR"
	remove_lnet_proc_files "stats"

	# lnet.routes should look like this:
	# Routing disabled/enabled/starting/stopping
	# net hops priority state router
	# where net is a string like tcp0, hops > 0, priority >= 0,
	# state is up/down,
	# router is a string like 192.168.1.1@tcp2
	L1="^Routing (disabled|enabled|starting|stopping)$"
	L2="^net +hops +priority +state +router$"
	BR="^$NET +$N +(0|1) +(up|down) +($NID|$NID6)$"
	create_lnet_proc_files "routes"
	check_lnet_proc_entry "routes.sys" "lnet.routes" "$BR" "$L1" "$L2"
	remove_lnet_proc_files "routes"

	# lnet.routers should look like this:
	# ref rtr_ref alive_cnt state last_ping ping_sent deadline down_ni router
	# where ref > 0, rtr_ref > 0, alive_cnt >= 0, state is up/down,
	# last_ping >= 0, ping_sent is boolean (0/1), deadline and down_ni are
	# numeric (0 or >0 or <0), router is a string like 192.168.1.1@tcp2
	L1="^ref +rtr_ref +alive +router$"
	BR="^$P +$P +(up|down) +($NID|$NID6)$"
	create_lnet_proc_files "routers"
	check_lnet_proc_entry "routers.sys" "lnet.routers" "$BR" "$L1"
	remove_lnet_proc_files "routers"

	# lnet.peers should look like this:
	# nid refs state last max rtr min tx min queue
	# where nid is a string like 192.168.1.1@tcp2, refs > 0,
	# state is up/down/NA, max >= 0. last, rtr, min, tx, min are
	# numeric (0 or >0 or <0), queue >= 0.
	L1="^nid +refs +state +last +max +rtr +min +tx +min +queue$"
	BR="^($NID|$NID6) +$P +(up|down|NA) +$I +$N +$I +$I +$I +$I +$N$"
	create_lnet_proc_files "peers"
	check_lnet_proc_entry "peers.sys" "lnet.peers" "$BR" "$L1"
	remove_lnet_proc_files "peers"

	# lnet.buffers  should look like this:
	# pages count credits min
	# where pages >=0, count >=0, credits and min are numeric (0 or >0 or <0)
	L1="^pages +count +credits +min$"
	BR="^ +$N +$N +$I +$I$"
	create_lnet_proc_files "buffers"
	check_lnet_proc_entry "buffers.sys" "lnet.buffers" "$BR" "$L1"
	remove_lnet_proc_files "buffers"

	# lnet.nis should look like this:
	# nid status alive refs peer rtr max tx min
	# where nid is a string like 192.168.1.1@tcp2, status is up/down,
	# alive is numeric (0 or >0 or <0), refs >= 0, peer >= 0,
	# rtr >= 0, max >=0, tx and min are numeric (0 or >0 or <0).
	L1="^nid +status +alive +refs +peer +rtr +max +tx +min$"
	BR="^($NID|$NID6) +(up|down) +$I +$N +$N +$N +$N +$I +$I$"
	create_lnet_proc_files "nis"
	check_lnet_proc_entry "nis.sys" "lnet.nis" "$BR" "$L1"
	remove_lnet_proc_files "nis"

	# can we successfully write to lnet.stats?
	lctl set_param -n stats=0 || error "cannot write to lnet.stats"
}
run_test 215 "lnet exists and has proper content - bugs 18102, 21079, 21517"

test_216() { # bug 20317
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_ost_nodsh && skip "remote OST with nodsh"

	local node
	local facets=$(get_facets OST)
	local p="$TMP/$TESTSUITE-$TESTNAME.parameters"

	save_lustre_params $facets \
		"ldlm.namespaces.filter-*.max_nolock_bytes" > $p
	save_lustre_params $facets \
		"ldlm.namespaces.filter-*.contended_locks" >> $p
	save_lustre_params $facets \
		"ldlm.namespaces.filter-*.contention_seconds" >> $p
	clear_stats osc.*.osc_stats
	local osts=$(osts_nodes)

	# agressive lockless i/o settings
	do_nodes $osts \
		"lctl set_param -n ldlm.namespaces.*.max_nolock_bytes=2000000 \
			ldlm.namespaces.filter-*.contended_locks=0 \
			ldlm.namespaces.filter-*.contention_seconds=60"

	$DIRECTIO write $DIR/$tfile 0 10 4096
	$CHECKSTAT -s 40960 $DIR/$tfile

	# disable lockless i/o
	do_nodes $osts \
		"lctl set_param -n ldlm.namespaces.filter-*.max_nolock_bytes=0 \
			ldlm.namespaces.filter-*.contended_locks=32 \
			ldlm.namespaces.filter-*.contention_seconds=0"
	clear_stats osc.*.osc_stats

	dd if=/dev/zero of=$DIR/$tfile count=0
	$CHECKSTAT -s 0 $DIR/$tfile

	restore_lustre_params <$p
	rm -f $p
	rm $DIR/$tfile
}
run_test 216 "check lockless direct write updates file size and kms correctly"

test_217() { # bug 22430
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	local nodes=$(nodes_list)
	local node

	for node in ${nodes//,/ }; do
		local nid=$(host_nids_address $node $NETTYPE)
		local node_ip=$(do_node $node getent ahostsv4 $node |
				awk '{ print $1; exit; }')

		echo "node: '$node', nid: '$nid', node_ip='$node_ip'"
		# if hostname matches any NID, use hostname for better testing
		if [[ -z "$nid" || "$nid" =~ "$node_ip" ]]; then
			echo "lctl ping node $node@$NETTYPE"
			lctl ping $node@$NETTYPE ||
				error "ping $node@$NETTYPE failed rc=$?"
		else # otherwise, at least test 'lctl ping' is working
			echo "lctl ping nid $(h2nettype $nid)"
			lctl ping $(h2nettype $nid) ||
				error "ping $(h2nettype $nid) failed rc=$?"
			echo "skipping $node (no hyphen detected)"
		fi
	done

	return 0
}
run_test 217 "check lctl ping for hostnames with embedded hyphen ('-')"

test_218() {
	# do directio so as not to populate the page cache
	log "creating a 10 Mb file"
	$MULTIOP $DIR/$tfile oO_CREAT:O_DIRECT:O_RDWR:w$((10*1048576))c ||
		error "multiop failed while creating a file"
	log "starting reads"
	dd if=$DIR/$tfile of=/dev/null bs=4096 &
	log "truncating the file"
	$MULTIOP $DIR/$tfile oO_TRUNC:c ||
		error "multiop failed while truncating the file"
	log "killing dd"
	kill %+ || true # reads might have finished
	echo "wait until dd is finished"
	wait
	log "removing the temporary file"
	rm -rf $DIR/$tfile || error "tmp file removal failed"
}
run_test 218 "parallel read and truncate should not deadlock"

test_219() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	# write one partial page
	dd if=/dev/zero of=$DIR/$tfile bs=1024 count=1
	# set no grant so vvp_io_commit_write will do sync write
	$LCTL set_param fail_loc=0x411
	# write a full page at the end of file
	dd if=/dev/zero of=$DIR/$tfile bs=4096 count=1 seek=1 conv=notrunc

	$LCTL set_param fail_loc=0
	dd if=/dev/zero of=$DIR/$tfile bs=4096 count=1 seek=3
	$LCTL set_param fail_loc=0x411
	dd if=/dev/zero of=$DIR/$tfile bs=1024 count=1 seek=2 conv=notrunc

	# LU-4201
	dd if=/dev/zero of=$DIR/$tfile-2 bs=1024 count=1
	$CHECKSTAT -s 1024 $DIR/$tfile-2 || error "checkstat wrong size"
}
run_test 219 "LU-394: Write partial won't cause uncontiguous pages vec at LND"

test_220() { #LU-325
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_ost_nodsh && skip "remote OST with nodsh"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	remote_mgs_nodsh && skip "remote MGS with nodsh"

	local OSTIDX=0

	# create on MDT0000 so the last_id and next_id are correct
	mkdir_on_mdt0 $DIR/$tdir
	local OST=$($LFS df --ost=$OSTIDX $DIR | awk '{ print $1 }')
	OST=${OST%_UUID}

	# on the mdt's osc
	local mdtosc_proc1=$(get_mdtosc_proc_path $SINGLEMDS $OST)
	local last_id=$(do_facet $SINGLEMDS lctl get_param -n \
			osp.$mdtosc_proc1.prealloc_last_id)
	local next_id=$(do_facet $SINGLEMDS lctl get_param -n \
			osp.$mdtosc_proc1.prealloc_next_id)

	$LFS df -i

	do_facet ost$((OSTIDX + 1)) lctl set_param fail_val=-1
	#define OBD_FAIL_OST_ENOINO              0x229
	do_facet ost$((OSTIDX + 1)) lctl set_param fail_loc=0x229
	create_pool $FSNAME.$TESTNAME || return 1
	do_facet mgs $LCTL pool_add $FSNAME.$TESTNAME $OST || return 2

	$LFS setstripe $DIR/$tdir -i $OSTIDX -c 1 -p $FSNAME.$TESTNAME

	MDSOBJS=$((last_id - next_id))
	echo "preallocated objects on MDS is $MDSOBJS" "($last_id - $next_id)"

	blocks=$($LFS df $MOUNT | awk '($1 == '$OSTIDX') { print $4 }')
	echo "OST still has $count kbytes free"

	echo "create $MDSOBJS files @next_id..."
	createmany -o $DIR/$tdir/f $MDSOBJS || return 3

	local last_id2=$(do_facet mds${MDSIDX} lctl get_param -n \
			osp.$mdtosc_proc1.prealloc_last_id)
	local next_id2=$(do_facet mds${MDSIDX} lctl get_param -n \
			osp.$mdtosc_proc1.prealloc_next_id)

	echo "after creation, last_id=$last_id2, next_id=$next_id2"
	$LFS df -i

	echo "cleanup..."

	do_facet ost$((OSTIDX + 1)) lctl set_param fail_val=0
	do_facet ost$((OSTIDX + 1)) lctl set_param fail_loc=0

	do_facet mgs $LCTL pool_remove $FSNAME.$TESTNAME $OST ||
		error "$LCTL pool_remove $FSNAME.$TESTNAME $OST failed"
	do_facet mgs $LCTL pool_destroy $FSNAME.$TESTNAME ||
		error "$LCTL pool_destroy $FSNAME.$TESTNAME failed"
	echo "unlink $MDSOBJS files @$next_id..."
	unlinkmany $DIR/$tdir/f $MDSOBJS || error "unlinkmany failed"
}
run_test 220 "preallocated MDS objects still used if ENOSPC from OST"

test_221() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	dd if=`which date` of=$MOUNT/date oflag=sync
	chmod +x $MOUNT/date

	#define OBD_FAIL_LLITE_FAULT_TRUNC_RACE  0x1401
	$LCTL set_param fail_loc=0x80001401

	$MOUNT/date > /dev/null
	rm -f $MOUNT/date
}
run_test 221 "make sure fault and truncate race to not cause OOM"

test_222a () {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	rm -rf $DIR/$tdir
	test_mkdir $DIR/$tdir
	$LFS setstripe -c 1 -i 0 $DIR/$tdir
	createmany -o $DIR/$tdir/$tfile 10
	cancel_lru_locks mdc
	cancel_lru_locks osc
	#define OBD_FAIL_LDLM_AGL_DELAY           0x31a
	$LCTL set_param fail_loc=0x31a
	ls -l $DIR/$tdir > /dev/null || error "AGL for ls failed"
	$LCTL set_param fail_loc=0
	rm -r $DIR/$tdir
}
run_test 222a "AGL for ls should not trigger CLIO lock failure"

test_222b () {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	rm -rf $DIR/$tdir
	test_mkdir $DIR/$tdir
	$LFS setstripe -c 1 -i 0 $DIR/$tdir
	createmany -o $DIR/$tdir/$tfile 10
	cancel_lru_locks mdc
	cancel_lru_locks osc
	#define OBD_FAIL_LDLM_AGL_DELAY           0x31a
	$LCTL set_param fail_loc=0x31a
	rm -r $DIR/$tdir || error "AGL for rmdir failed"
	$LCTL set_param fail_loc=0
}
run_test 222b "AGL for rmdir should not trigger CLIO lock failure"

test_223 () {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	rm -rf $DIR/$tdir
	test_mkdir $DIR/$tdir
	$LFS setstripe -c 1 -i 0 $DIR/$tdir
	createmany -o $DIR/$tdir/$tfile 10
	cancel_lru_locks mdc
	cancel_lru_locks osc
	#define OBD_FAIL_LDLM_AGL_NOLOCK          0x31b
	$LCTL set_param fail_loc=0x31b
	ls -l $DIR/$tdir > /dev/null || error "reenqueue failed"
	$LCTL set_param fail_loc=0
	rm -r $DIR/$tdir
}
run_test 223 "osc reenqueue if without AGL lock granted ======================="

test_224a() { # LU-1039, MRP-303
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	#define OBD_FAIL_PTLRPC_CLIENT_BULK_CB   0x508
	$LCTL set_param fail_loc=0x508
	dd if=/dev/zero of=$DIR/$tfile bs=1M count=1 conv=fsync
	stack_trap "rm -f $DIR/$tfile"
	$LCTL set_param fail_loc=0
	df $DIR
}
run_test 224a "Don't panic on bulk IO failure"

test_224bd_sub() { # LU-1039, MRP-303
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	local timeout=$1

	shift
	dd if=/dev/urandom of=$TMP/$tfile bs=1M count=1

	$LFS setstripe -c 1 -i 0 $DIR/$tfile

	dd if=$TMP/$tfile of=$DIR/$tfile bs=1M count=1
	stack_trap "rm -f $DIR/$tfile"
	cancel_lru_locks osc
	set_checksums 0
	stack_trap "set_checksums $ORIG_CSUM" EXIT
	local at_max_saved=0

	# adaptive timeouts may prevent seeing the issue
	if at_is_enabled; then
		at_max_saved=$(at_max_get mds)
		at_max_set 0 mds client
		stack_trap "at_max_set $at_max_saved mds client" EXIT
	fi

	#define OBD_FAIL_PTLRPC_CLIENT_BULK_CB2   0x515
	do_facet ost1 $LCTL set_param fail_val=$timeout fail_loc=0x80000515
	dd of=$TMP/$tfile.new if=$DIR/$tfile bs=1M count=1 || "$@"

	do_facet ost1 $LCTL set_param fail_loc=0
	cmp $TMP/$tfile $TMP/$tfile.new || error "file contents wrong"
	df $DIR
}

test_224b() {
	test_224bd_sub 3 error "dd failed"
}
run_test 224b "Don't panic on bulk IO failure"

test_224c() { # LU-6441
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"

	local p="$TMP/$TESTSUITE-$TESTNAME.parameters"
	local osts=$(osts_nodes)

	save_writethrough $p
	set_cache $osts writethrough on

	local pages_per_rpc=$($LCTL get_param osc.*.max_pages_per_rpc)
	local at_max=$($LCTL get_param -n at_max)
	local timeout=$($LCTL get_param -n timeout)
	local test_at="at_max"
	local param_at="$FSNAME.sys.at_max"
	local test_timeout="timeout"
	local param_timeout="$FSNAME.sys.timeout"

	$LCTL set_param -n osc.*.max_pages_per_rpc=1024

	set_persistent_param_and_check client "$test_at" "$param_at" 0
	set_persistent_param_and_check client "$test_timeout" "$param_timeout" 5

	#define OBD_FAIL_PTLRPC_CLIENT_BULK_CB3 0x520
	do_facet ost1 "$LCTL set_param fail_loc=0x520"
	$LFS setstripe -c 1 -i 0 $DIR/$tfile
	stack_trap "rm -f $DIR/$tfile"
	dd if=/dev/zero of=$DIR/$tfile bs=8MB count=1
	sync
	do_facet ost1 "$LCTL set_param fail_loc=0"

	set_persistent_param_and_check client "$test_at" "$param_at" $at_max
	set_persistent_param_and_check client "$test_timeout" "$param_timeout" \
		$timeout

	$LCTL set_param -n $pages_per_rpc
	restore_lustre_params < $p
	rm -f $p
}
run_test 224c "Don't hang if one of md lost during large bulk RPC"

test_224d() { # LU-11169
	test_224bd_sub $((TIMEOUT + 2)) error "dd failed"
}
run_test 224d "Don't corrupt data on bulk IO timeout"

MDSSURVEY=${MDSSURVEY:-$(which mds-survey 2>/dev/null || true)}
test_225a () {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	if [ -z ${MDSSURVEY} ]; then
		skip_env "mds-survey not found"
	fi
	[ $MDS1_VERSION -ge $(version_code 2.2.51) ] ||
		skip "Need MDS version at least 2.2.51"

	local mds=$(facet_host $SINGLEMDS)
	local target=$(do_nodes $mds 'lctl dl' |
		       awk '{ if ($2 == "UP" && $3 == "mdt") { print $4 }}')

	local cmd1="file_count=1000 thrhi=4"
	local cmd2="dir_count=2 layer=mdd stripe_count=0"
	local cmd3="rslt_loc=${TMP} targets=\"$mds:$target\" $MDSSURVEY"
	local cmd="$cmd1 $cmd2 $cmd3"

	rm -f ${TMP}/mds_survey*
	echo + $cmd
	eval $cmd || error "mds-survey with zero-stripe failed"
	cat ${TMP}/mds_survey*
	rm -f ${TMP}/mds_survey*
}
run_test 225a "Metadata survey sanity with zero-stripe"

test_225b () {
	if [ -z ${MDSSURVEY} ]; then
		skip_env "mds-survey not found"
	fi
	[ $MDS1_VERSION -ge $(version_code 2.2.51) ] ||
		skip "Need MDS version at least 2.2.51"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	if [ $($LCTL dl | grep -c osc) -eq 0 ]; then
		skip_env "Need to mount OST to test"
	fi

	local mds=$(facet_host $SINGLEMDS)
	local target=$(do_nodes $mds 'lctl dl' |
		       awk '{ if ($2 == "UP" && $3 == "mdt") { print $4 }}')

	local cmd1="file_count=1000 thrhi=4"
	local cmd2="dir_count=2 layer=mdd stripe_count=1"
	local cmd3="rslt_loc=${TMP} targets=\"$mds:$target\" $MDSSURVEY"
	local cmd="$cmd1 $cmd2 $cmd3"

	rm -f ${TMP}/mds_survey*
	echo + $cmd
	eval $cmd || error "mds-survey with stripe_count failed"
	cat ${TMP}/mds_survey*
	rm -f ${TMP}/mds_survey*
}
run_test 225b "Metadata survey sanity with stripe_count = 1"

mcreate_path2fid () {
	local mode=$1
	local major=$2
	local minor=$3
	local name=$4
	local desc=$5
	local path=$DIR/$tdir/$name
	local fid
	local rc
	local fid_path

	$MCREATE --mode=$1 --major=$2 --minor=$3 $path ||
		error "cannot create $desc"

	fid=$($LFS path2fid $path | tr -d '[' | tr -d ']')
	rc=$?
	[ $rc -ne 0 ] && error "cannot get fid of a $desc"

	fid_path=$($LFS fid2path $MOUNT $fid)
	rc=$?
	[ $rc -ne 0 ] && error "cannot get path of $desc by $DIR $path $fid"

	[ "$path" == "$fid_path" ] ||
		error "fid2path returned $fid_path, expected $path"

	echo "pass with $path and $fid"
}

test_226a () {
	rm -rf $DIR/$tdir
	mkdir -p $DIR/$tdir

	mcreate_path2fid 0010666 0 0 fifo "FIFO"
	mcreate_path2fid 0020666 1 3 null "character special file (null)"
	mcreate_path2fid 0020666 1 255 none "character special file (no device)"
	mcreate_path2fid 0040666 0 0 dir "directory"
	mcreate_path2fid 0060666 7 0 loop0 "block special file (loop)"
	mcreate_path2fid 0100666 0 0 file "regular file"
	mcreate_path2fid 0120666 0 0 link "symbolic link"
	mcreate_path2fid 0140666 0 0 sock "socket"
}
run_test 226a "call path2fid and fid2path on files of all type"

test_226b () {
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"

	local MDTIDX=1

	rm -rf $DIR/$tdir
	mkdir -p $DIR/$tdir
	$LFS setdirstripe -i $MDTIDX $DIR/$tdir/remote_dir ||
		error "create remote directory failed"
	mcreate_path2fid 0010666 0 0 "remote_dir/fifo" "FIFO"
	mcreate_path2fid 0020666 1 3 "remote_dir/null" \
				"character special file (null)"
	mcreate_path2fid 0020666 1 255 "remote_dir/none" \
				"character special file (no device)"
	mcreate_path2fid 0040666 0 0 "remote_dir/dir" "directory"
	mcreate_path2fid 0060666 7 0 "remote_dir/loop0" \
				"block special file (loop)"
	mcreate_path2fid 0100666 0 0 "remote_dir/file" "regular file"
	mcreate_path2fid 0120666 0 0 "remote_dir/link" "symbolic link"
	mcreate_path2fid 0140666 0 0 "remote_dir/sock" "socket"
}
run_test 226b "call path2fid and fid2path on files of all type under remote dir"

test_226c () {
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"
	[[ $MDS1_VERSION -ge $(version_code 2.13.55) ]] ||
		skip "Need MDS version at least 2.13.55"

	local submnt=/mnt/submnt
	local srcfile=/etc/passwd
	local dstfile=$submnt/passwd
	local path
	local fid

	rm -rf $DIR/$tdir
	rm -rf $submnt
	$LFS setdirstripe -c -1 -i 1 $DIR/$tdir ||
		error "create remote directory failed"
	mkdir -p $submnt || error "create $submnt failed"
	FILESET="$FILESET/$tdir" mount_client $submnt ||
		error "mount $submnt failed"
	stack_trap "umount $submnt;rm -rf $submit" EXIT

	cp $srcfile $dstfile
	fid=$($LFS path2fid $dstfile)
	path=$($LFS fid2path $submnt "$fid")
	[ "$path" = "$dstfile" ] ||
		error "fid2path $submnt $fid failed ($path != $dstfile)"
}
run_test 226c "call path2fid and fid2path under remote dir with subdir mount"

test_226d () {
	(( $CLIENT_VERSION >= $(version_code 2.15.57) )) ||
		skip "Need client at least version 2.15.57"

	# Define First test dataset
	local testdirs_01=$DIR/$tdir
	local testdata_01=$testdirs_01/${tdir}_01
	local testresult_01=${tdir}_01
	# Define Second test dataset
	local testdirs_02=$DIR/$tdir/$tdir
	local testdata_02=$testdirs_02/${tdir}_02
	local testresult_02=${tdir}_02
	# Define third test dataset (top level)
	local testdata_03=$DIR/${tdir}_03
	local testresult_03=${tdir}_03

	# Create first test dataset
	mkdir -p $testdirs_01 || error "cannot create dir $testdirs_01"
	touch $testdata_01 || error "cannot create file $testdata_01"

	# Create second test dataset
	mkdir -p $testdirs_02 || error "cannot create dir $testdirs_02"
	touch $testdata_02 || error "cannot create file $testdata_02"

	# Create third test dataset
	touch $testdata_03 || error "cannot create file $testdata_03"

	local fid01=$($LFS getstripe -F "$testdata_01") ||
		error "getstripe failed on $testdata_01"
	local fid02=$($LFS getstripe -F "$testdata_02") ||
		error "getstripe failed on $testdata_01"
	local fid03=$($LFS getstripe -F "$testdata_03") ||
		error "getstripe failed on $testdata_03"

	# Verify only -n option
	local out1=$($LFS fid2path -n $DIR $fid01) ||
		error "fid2path failed on $fid01"
	local out2=$($LFS fid2path -n $DIR $fid02) ||
		error "fid2path failed on $fid02"
	local out3=$($LFS fid2path -n $DIR $fid03) ||
		error "fid2path failed on $fid03"

	[[ "$out1" == "$testresult_01" ]] ||
		error "fid2path failed: Expected $testresult_01 got $out1"
	[[ "$out2" == "$testresult_02" ]] ||
		error "fid2path failed: Expected $testresult_02 got $out2"
	[[ "$out3" == "$testresult_03" ]] ||
		error "fid2path failed: Expected $testresult_03 got $out3"

	# Verify with option -fn together
	out1=$($LFS fid2path -fn $DIR $fid01) ||
		error "fid2path -fn failed on $fid01"
	out2=$($LFS fid2path -fn $DIR $fid02) ||
		error "fid2path -fn failed on $fid02"
	out3=$($LFS fid2path -fn $DIR $fid03) ||
		error "fid2path -fn failed on $fid03"

	local tmpout=$(echo $out1 | cut -d" " -f2)
	[[ "$tmpout" == "$testresult_01" ]] ||
		error "fid2path -fn failed: Expected $testresult_01 got $out1"

	tmpout=$(echo $out2 | cut -d" " -f2)
	[[ "$tmpout" == "$testresult_02" ]] ||
		error "fid2path -fn failed: Expected $testresult_02 got $out2"

	tmpout=$(echo $out3 | cut -d" " -f2)
	[[ "$tmpout" == "$testresult_03" ]] ||
		error "fid2path -fn failed: Expected $testresult_03 got $out3"
}
run_test 226d "verify fid2path with -n and -fn option"

test_226e () {
	(( $CLIENT_VERSION >= $(version_code 2.15.56) )) ||
		skip "Need client at least version 2.15.56"

	# Define filename with 'newline' and a space
	local testfile="Test"$'\n'"file 01"
	# Define link name with multiple 'newline' and a space
	local linkfile="Link"$'\n'"file "$'\n'"01"
	# Remove prior hard link
	rm -f $DIR/"$linkfile"

	# Create file
	touch $DIR/"$testfile"
	# Create link
	ln $DIR/"$testfile" $DIR/"$linkfile"

	local fid=$($LFS getstripe -F "$DIR/$testfile") ||
		error "getstripe failed on $DIR/$testfile"

	# Call with -0 option
	local out1=$($LFS fid2path -0 $DIR $fid | xargs --null -n1 \
		echo "FILE:" | grep -c "FILE:")

	# With -0 option the output should be exactly 2 lines.
	(( $out1 == 2 )) || error "fid2path -0 failed on $fid, $out1"
}
run_test 226e "Verify path2fid -0 option with newline and space"

# LU-1299 Executing or running ldd on a truncated executable does not
# cause an out-of-memory condition.
test_227() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ -z "$(which ldd)" ] && skip_env "should have ldd tool"

	dd if=$(which date) of=$MOUNT/date bs=1k count=1
	chmod +x $MOUNT/date

	$MOUNT/date > /dev/null
	ldd $MOUNT/date > /dev/null
	rm -f $MOUNT/date
}
run_test 227 "running truncated executable does not cause OOM"

# LU-1512 try to reuse idle OI blocks
test_228a() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	[ "$mds1_FSTYPE" != "ldiskfs" ] && skip_env "ldiskfs only test"

	local MDT_DEV=$(mdsdevname ${SINGLEMDS//mds/})
	local myDIR=$DIR/$tdir

	mkdir -p $myDIR
	#define OBD_FAIL_SEQ_EXHAUST             0x1002
	$LCTL set_param fail_loc=0x80001002
	createmany -o $myDIR/t- 10000
	$LCTL set_param fail_loc=0
	# The guard is current the largest FID holder
	touch $myDIR/guard
	local SEQ=$($LFS path2fid $myDIR/guard | awk -F ':' '{print $1}' |
		    tr -d '[')
	local IDX=$(($SEQ % 64))

	do_facet $SINGLEMDS sync
	# Make sure journal flushed.
	sleep 6
	local blk1=$(do_facet $SINGLEMDS \
		     "$DEBUGFS -c -R \\\"stat oi.16.${IDX}\\\" $MDT_DEV" |
		     grep Blockcount | awk '{print $4}')

	# Remove old files, some OI blocks will become idle.
	unlinkmany $myDIR/t- 10000
	# Create new files, idle OI blocks should be reused.
	createmany -o $myDIR/t- 2000
	do_facet $SINGLEMDS sync
	# Make sure journal flushed.
	sleep 6
	local blk2=$(do_facet $SINGLEMDS \
		     "$DEBUGFS -c -R \\\"stat oi.16.${IDX}\\\" $MDT_DEV" |
		     grep Blockcount | awk '{print $4}')

	[ $blk1 == $blk2 ] || error "old blk1=$blk1, new blk2=$blk2, unmatched!"
}
run_test 228a "try to reuse idle OI blocks"

test_228b() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	[ "$mds1_FSTYPE" != "ldiskfs" ] && skip_env "ldiskfs only test"

	local MDT_DEV=$(mdsdevname ${SINGLEMDS//mds/})
	local myDIR=$DIR/$tdir

	mkdir -p $myDIR
	#define OBD_FAIL_SEQ_EXHAUST             0x1002
	$LCTL set_param fail_loc=0x80001002
	createmany -o $myDIR/t- 10000
	$LCTL set_param fail_loc=0
	# The guard is current the largest FID holder
	touch $myDIR/guard
	local SEQ=$($LFS path2fid $myDIR/guard | awk -F ':' '{print $1}' |
		    tr -d '[')
	local IDX=$(($SEQ % 64))

	do_facet $SINGLEMDS sync
	# Make sure journal flushed.
	sleep 6
	local blk1=$(do_facet $SINGLEMDS \
		     "$DEBUGFS -c -R \\\"stat oi.16.${IDX}\\\" $MDT_DEV" |
		     grep Blockcount | awk '{print $4}')

	# Remove old files, some OI blocks will become idle.
	unlinkmany $myDIR/t- 10000

	# stop the MDT
	stop $SINGLEMDS || error "Fail to stop MDT."
	# remount the MDT
	start $SINGLEMDS $(facet_device $SINGLEMDS) $MDS_MOUNT_OPTS ||
		error "Fail to start MDT."

	client_up || error "Fail to df."
	# Create new files, idle OI blocks should be reused.
	createmany -o $myDIR/t- 2000
	do_facet $SINGLEMDS sync
	# Make sure journal flushed.
	sleep 6
	local blk2=$(do_facet $SINGLEMDS \
		     "$DEBUGFS -c -R \\\"stat oi.16.${IDX}\\\" $MDT_DEV" |
		     grep Blockcount | awk '{print $4}')

	[ $blk1 == $blk2 ] || error "old blk1=$blk1, new blk2=$blk2, unmatched!"
}
run_test 228b "idle OI blocks can be reused after MDT restart"

#LU-1881
test_228c() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	[ "$mds1_FSTYPE" != "ldiskfs" ] && skip_env "ldiskfs only test"

	local MDT_DEV=$(mdsdevname ${SINGLEMDS//mds/})
	local myDIR=$DIR/$tdir

	mkdir -p $myDIR
	#define OBD_FAIL_SEQ_EXHAUST             0x1002
	$LCTL set_param fail_loc=0x80001002
	# 20000 files can guarantee there are index nodes in the OI file
	createmany -o $myDIR/t- 20000
	$LCTL set_param fail_loc=0
	# The guard is current the largest FID holder
	touch $myDIR/guard
	local SEQ=$($LFS path2fid $myDIR/guard | awk -F ':' '{print $1}' |
		    tr -d '[')
	local IDX=$(($SEQ % 64))

	do_facet $SINGLEMDS sync
	# Make sure journal flushed.
	sleep 6
	local blk1=$(do_facet $SINGLEMDS \
		     "$DEBUGFS -c -R \\\"stat oi.16.${IDX}\\\" $MDT_DEV" |
		     grep Blockcount | awk '{print $4}')

	# Remove old files, some OI blocks will become idle.
	unlinkmany $myDIR/t- 20000
	rm -f $myDIR/guard
	# The OI file should become empty now

	# Create new files, idle OI blocks should be reused.
	createmany -o $myDIR/t- 2000
	do_facet $SINGLEMDS sync
	# Make sure journal flushed.
	sleep 6
	local blk2=$(do_facet $SINGLEMDS \
		     "$DEBUGFS -c -R \\\"stat oi.16.${IDX}\\\" $MDT_DEV" |
		     grep Blockcount | awk '{print $4}')

	[ $blk1 == $blk2 ] || error "old blk1=$blk1, new blk2=$blk2, unmatched!"
}
run_test 228c "NOT shrink the last entry in OI index node to recycle idle leaf"

test_229() { # LU-2482, LU-3448
	[[ $PARALLEL == "yes" ]] && skip "skip parallel run"
	(( $OSTCOUNT >= 2 )) || skip_env "needs >= 2 OSTs"
	(( $MDS1_VERSION >= $(version_code 2.4.50.0-53-ga61ff5914b) )) ||
		skip "need MDS >= 2.4.50.53 for HSM released file"

	rm -f $DIR/$tfile

	# Create a file with a released layout and stripe count 2.
	$MULTIOP $DIR/$tfile H2c ||
		error "failed to create file with released layout"

	$LFS getstripe -v $DIR/$tfile

	local pattern=$($LFS getstripe -L $DIR/$tfile)
	[[ "$pattern" =~ "released" ]] || error "pattern error ($pattern)"

	local stripe_count=$($LFS getstripe -c $DIR/$tfile) ||
		error "getstripe"
	(( $stripe_count == 2 )) || error "stripe count not 2 ($stripe_count)"
	stat $DIR/$tfile || error "failed to stat released file"

	chown $RUNAS_ID $DIR/$tfile ||
		error "chown $RUNAS_ID $DIR/$tfile failed"

	chgrp $RUNAS_ID $DIR/$tfile ||
		error "chgrp $RUNAS_ID $DIR/$tfile failed"

	touch $DIR/$tfile || error "touch $DIR/$tfile failed"
	rm $DIR/$tfile || error "failed to remove released file"
}
run_test 229 "getstripe/stat/rm/attr changes work on released files"

test_230a() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"
	[ $MDS1_VERSION -lt $(version_code 2.11.52) ] &&
		skip "Need MDS version at least 2.11.52"

	local MDTIDX=1

	test_mkdir $DIR/$tdir
	test_mkdir -i0 -c1 $DIR/$tdir/test_230_local
	local mdt_idx=$($LFS getstripe -m $DIR/$tdir/test_230_local)
	[ $mdt_idx -ne 0 ] &&
		error "create local directory on wrong MDT $mdt_idx"

	$LFS mkdir -i $MDTIDX $DIR/$tdir/test_230 ||
			error "create remote directory failed"
	local mdt_idx=$($LFS getstripe -m $DIR/$tdir/test_230)
	[ $mdt_idx -ne $MDTIDX ] &&
		error "create remote directory on wrong MDT $mdt_idx"

	createmany -o $DIR/$tdir/test_230/t- 10 ||
		error "create files on remote directory failed"
	mdt_idx=$($LFS getstripe -m $DIR/$tdir/test_230/t-0)
	[ $mdt_idx -ne $MDTIDX ] && error "create files on wrong MDT $mdt_idx"
	rm -r $DIR/$tdir || error "unlink remote directory failed"
}
run_test 230a "Create remote directory and files under the remote directory"

test_230b() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"
	[ $MDS1_VERSION -lt $(version_code 2.11.52) ] &&
		skip "Need MDS version at least 2.11.52"

	local MDTIDX=1
	local mdt_index
	local i
	local file
	local pid
	local stripe_count
	local migrate_dir=$DIR/$tdir/migrate_dir
	local other_dir=$DIR/$tdir/other_dir

	test_mkdir $DIR/$tdir
	test_mkdir -i0 -c1 $migrate_dir
	test_mkdir -i0 -c1 $other_dir
	for ((i=0; i<10; i++)); do
		mkdir -p $migrate_dir/dir_${i}
		createmany -o $migrate_dir/dir_${i}/f 10 ||
			error "create files under remote dir failed $i"
	done

	cp /etc/passwd $migrate_dir/$tfile
	cp /etc/passwd $other_dir/$tfile
	chattr +SAD $migrate_dir
	chattr +SAD $migrate_dir/$tfile

	local old_dir_flag=$(lsattr -a $migrate_dir | awk '/\/\.$/ {print $1}')
	local old_file_flag=$(lsattr $migrate_dir/$tfile | awk '{print $1}')
	local old_dir_mode=$(stat -c%f $migrate_dir)
	local old_file_mode=$(stat -c%f $migrate_dir/$tfile)

	mkdir -p $migrate_dir/dir_default_stripe2
	$LFS setstripe -c 2 $migrate_dir/dir_default_stripe2
	$LFS setstripe -c 2 $migrate_dir/${tfile}_stripe2

	mkdir -p $other_dir
	ln $migrate_dir/$tfile $other_dir/luna
	ln $migrate_dir/$tfile $migrate_dir/sofia
	ln $other_dir/$tfile $migrate_dir/david
	ln -s $migrate_dir/$tfile $other_dir/zachary
	ln -s $migrate_dir/$tfile $migrate_dir/${tfile}_ln
	ln -s $other_dir/$tfile $migrate_dir/${tfile}_ln_other

	local len
	local lnktgt

	# inline symlink
	for len in 58 59 60; do
		lnktgt=$(str_repeat 'l' $len)
		touch $migrate_dir/$lnktgt
		ln -s $lnktgt $migrate_dir/${len}char_ln
	done

	# PATH_MAX
	for len in 4094 4095; do
		lnktgt=$(str_repeat 'l' $len)
		ln -s $lnktgt $migrate_dir/${len}char_ln
	done

	# NAME_MAX
	for len in 254 255; do
		touch $migrate_dir/$(str_repeat 'l' $len)
	done

	$LFS migrate -m $MDTIDX $migrate_dir ||
		error "fails on migrating remote dir to MDT1"

	echo "migratate to MDT1, then checking.."
	for ((i = 0; i < 10; i++)); do
		for file in $(find $migrate_dir/dir_${i}); do
			mdt_index=$($LFS getstripe -m $file)
			# broken symlink getstripe will fail
			[ $mdt_index -ne $MDTIDX ] && stat -L $file &&
				error "$file is not on MDT${MDTIDX}"
		done
	done

	# the multiple link file should still in MDT0
	mdt_index=$($LFS getstripe -m $migrate_dir/$tfile)
	[ $mdt_index == 0 ] ||
		error "$file is not on MDT${MDTIDX}"

	local new_dir_flag=$(lsattr -a $migrate_dir | awk '/\/\.$/ {print $1}')
	[ "$old_dir_flag" = "$new_dir_flag" ] ||
		error " expect $old_dir_flag get $new_dir_flag"

	local new_file_flag=$(lsattr $migrate_dir/$tfile | awk '{print $1}')
	[ "$old_file_flag" = "$new_file_flag" ] ||
		error " expect $old_file_flag get $new_file_flag"

	local new_dir_mode=$(stat -c%f $migrate_dir)
	[ "$old_dir_mode" = "$new_dir_mode" ] ||
		error "expect mode $old_dir_mode get $new_dir_mode"

	local new_file_mode=$(stat -c%f $migrate_dir/$tfile)
	[ "$old_file_mode" = "$new_file_mode" ] ||
		error "expect mode $old_file_mode get $new_file_mode"

	diff /etc/passwd $migrate_dir/$tfile ||
		error "$tfile different after migration"

	diff /etc/passwd $other_dir/luna ||
		error "luna different after migration"

	diff /etc/passwd $migrate_dir/sofia ||
		error "sofia different after migration"

	diff /etc/passwd $migrate_dir/david ||
		error "david different after migration"

	diff /etc/passwd $other_dir/zachary ||
		error "zachary different after migration"

	diff /etc/passwd $migrate_dir/${tfile}_ln ||
		error "${tfile}_ln different after migration"

	diff /etc/passwd $migrate_dir/${tfile}_ln_other ||
		error "${tfile}_ln_other different after migration"

	stripe_count=$($LFS getstripe -c $migrate_dir/dir_default_stripe2)
	[ $stripe_count = 2 ] ||
		error "dir strpe_count $d != 2 after migration."

	stripe_count=$($LFS getstripe -c $migrate_dir/${tfile}_stripe2)
	[ $stripe_count = 2 ] ||
		error "file strpe_count $d != 2 after migration."

	#migrate back to MDT0
	MDTIDX=0

	$LFS migrate -m $MDTIDX $migrate_dir ||
		error "fails on migrating remote dir to MDT0"

	echo "migrate back to MDT0, checking.."
	for file in $(find $migrate_dir); do
		mdt_index=$($LFS getstripe -m $file)
		[ $mdt_index -ne $MDTIDX ] && stat -L $file &&
			error "$file is not on MDT${MDTIDX}"
	done

	local new_dir_flag=$(lsattr -a $migrate_dir | awk '/\/\.$/ {print $1}')
	[ "$old_dir_flag" = "$new_dir_flag" ] ||
		error " expect $old_dir_flag get $new_dir_flag"

	local new_file_flag=$(lsattr $migrate_dir/$tfile | awk '{print $1}')
	[ "$old_file_flag" = "$new_file_flag" ] ||
		error " expect $old_file_flag get $new_file_flag"

	local new_dir_mode=$(stat -c%f $migrate_dir)
	[ "$old_dir_mode" = "$new_dir_mode" ] ||
		error "expect mode $old_dir_mode get $new_dir_mode"

	local new_file_mode=$(stat -c%f $migrate_dir/$tfile)
	[ "$old_file_mode" = "$new_file_mode" ] ||
		error "expect mode $old_file_mode get $new_file_mode"

	diff /etc/passwd ${migrate_dir}/$tfile ||
		error "$tfile different after migration"

	diff /etc/passwd ${other_dir}/luna ||
		error "luna different after migration"

	diff /etc/passwd ${migrate_dir}/sofia ||
		error "sofia different after migration"

	diff /etc/passwd ${other_dir}/zachary ||
		error "zachary different after migration"

	diff /etc/passwd $migrate_dir/${tfile}_ln ||
		error "${tfile}_ln different after migration"

	diff /etc/passwd $migrate_dir/${tfile}_ln_other ||
		error "${tfile}_ln_other different after migration"

	stripe_count=$($LFS getstripe -c ${migrate_dir}/dir_default_stripe2)
	[ $stripe_count = 2 ] ||
		error "dir strpe_count $d != 2 after migration."

	stripe_count=$($LFS getstripe -c ${migrate_dir}/${tfile}_stripe2)
	[ $stripe_count = 2 ] ||
		error "file strpe_count $d != 2 after migration."

	rm -rf $DIR/$tdir || error "rm dir failed after migration"
}
run_test 230b "migrate directory"

test_230c() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	[ $MDS1_VERSION -lt $(version_code 2.11.52) ] &&
		skip "Need MDS version at least 2.11.52"

	local MDTIDX=1
	local total=3
	local mdt_index
	local file
	local migrate_dir=$DIR/$tdir/migrate_dir

	#If migrating directory fails in the middle, all entries of
	#the directory is still accessiable.
	test_mkdir $DIR/$tdir
	test_mkdir -i0 -c1 $migrate_dir
	test_mkdir -i1 -c1 $DIR/$tdir/remote_dir
	stat $migrate_dir
	createmany -o $migrate_dir/f $total ||
		error "create files under ${migrate_dir} failed"

	# fail after migrating top dir, and this will fail only once, so the
	# first sub file migration will fail (currently f3), others succeed.
	#OBD_FAIL_MIGRATE_ENTRIES	0x1801
	do_facet mds1 lctl set_param fail_loc=0x1801
	local t=$(ls $migrate_dir | wc -l)

	$LFS migrate --mdt-index $MDTIDX $migrate_dir &&
		error "migrate should fail"
	local u=$(ls $migrate_dir | wc -l)
	[ "$u" == "$t" ] || error "$u != $t during migration"

	# add new dir/file should succeed
	mkdir $migrate_dir/dir ||
		error "mkdir failed under migrating directory"
	touch $migrate_dir/file ||
		error "create file failed under migrating directory"

	# add file with existing name should fail
	for file in $migrate_dir/f*; do
		stat $file > /dev/null || error "stat $file failed"
		$OPENFILE -f O_CREAT:O_EXCL $file &&
			error "open(O_CREAT|O_EXCL) $file should fail"
		$MULTIOP $file m && error "create $file should fail"
		touch $DIR/$tdir/remote_dir/$tfile ||
			error "touch $tfile failed"
		ln $DIR/$tdir/remote_dir/$tfile $file &&
			error "link $file should fail"
		mdt_index=$($LFS getstripe -m $file)
		if [ $mdt_index == 0 ]; then
			# file failed to migrate is not allowed to rename to
			mv $DIR/$tdir/remote_dir/$tfile $file &&
				error "rename to $file should fail"
		else
			mv $DIR/$tdir/remote_dir/$tfile $file ||
				error "rename to $file failed"
		fi
		echo hello >> $file || error "write $file failed"
	done

	# resume migration with different options should fail
	$LFS migrate -m 0 $migrate_dir &&
		error "migrate -m 0 $migrate_dir should fail"

	$LFS migrate -m $MDTIDX -c 2 $migrate_dir &&
		error "migrate -c 2 $migrate_dir should fail"

	# resume migration should succeed
	$LFS migrate -m $MDTIDX $migrate_dir ||
		error "migrate $migrate_dir failed"

	echo "Finish migration, then checking.."
	for file in $(find $migrate_dir); do
		mdt_index=$($LFS getstripe -m $file)
		[ $mdt_index == $MDTIDX ] ||
			error "$file is not on MDT${MDTIDX}"
	done

	if (($MDS1_VERSION >= $(version_code 2.16.50) )); then
		echo "Migrate a dir with an open file"
		touch $migrate_dir/foo || error "failed to create file"
		local foo_fid=$($LFS path2fid $migrate_dir/foo)
		$MULTIOP $migrate_dir/foo o_c &
		local bg_pid=$!
		sleep 1

		$LFS migrate -m 0 $migrate_dir || {
			kill -USR1 $bg_pid
			error "migrate a dir with an open file fails"
		}

		kill -USR1 $bg_pid
		wait $bg_pid || error "multiop fails"

		local foo_fid_new=$($LFS path2fid $migrate_dir/foo)
		[[ "$foo_fid" == "$foo_fid_new" ]] ||
			error "migrate should skip an open file $foo_fid != $foo_fid_new"

		for file in $(find $migrate_dir); do
			[[ $file == "$migrate_dir/foo" ]] && continue
			mdt_index=$($LFS getstripe -m $file)
			[[ "$mdt_index" == "0" ]] ||
				error "$file is not on MDT0"
		done

		# repeating the migrate should leave the dir's FID the same
		# and update only the skipped file's FID
		local old_dir_fid=$($LFS path2fid $migrate_dir)
		local old_file_fid=$($LFS path2fid $migrate_dir/file)

		$LFS migrate -m 0 $migrate_dir || error "Repeating migrate fails"

		local new_dir_fid=$($LFS path2fid $migrate_dir)
		local new_file_fid=$($LFS path2fid $migrate_dir/file)

		foo_fid_new=$($LFS path2fid $migrate_dir/foo)

		[[ "$foo_fid_old" != "$foo_fid_new" ]] ||
			error "Expecting the skipped file to be migrated, but its FID is the same"
		[[ "$old_dir_fid" != "$new_fid_dir" ]] ||
			error "The top-level dir has been migrated after repeating the same migrate cmd"
		[[ "$old_file_fid" == "$new_file_fid" ]] ||
			error "The migrated file has been migrated again"
	fi

	rm -rf $DIR/$tdir || error "rm dir failed after migration"
}
run_test 230c "check directory accessiblity if migration failed"

test_230d() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"
	[ $MDS1_VERSION -lt $(version_code 2.11.52) ] &&
		skip "Need MDS version at least 2.11.52"
	# LU-11235
	[ "$mds1_FSTYPE" == "zfs" ] && skip "skip ZFS backend"

	local migrate_dir=$DIR/$tdir/migrate_dir
	local old_index
	local new_index
	local old_count
	local new_count
	local new_hash
	local mdt_index
	local i
	local j

	old_index=$((RANDOM % MDSCOUNT))
	old_count=$((MDSCOUNT - old_index))
	new_index=$((RANDOM % MDSCOUNT))
	new_count=$((MDSCOUNT - new_index))
	new_hash=1 # for all_char

	[ $old_count -gt 1 ] && old_count=$((old_count - RANDOM % old_count))
	[ $new_count -gt 1 ] && new_count=$((new_count - RANDOM % new_count))

	test_mkdir $DIR/$tdir
	test_mkdir -i $old_index -c $old_count $migrate_dir

	for ((i=0; i<100; i++)); do
		test_mkdir -i0 -c1 $migrate_dir/dir_${i}
		createmany -o $migrate_dir/dir_${i}/f 100 ||
			error "create files under remote dir failed $i"
	done

	echo -n "Migrate from MDT$old_index "
	[ $old_count -gt 1 ] && echo -n "... MDT$((old_index + old_count - 1)) "
	echo -n "to MDT$new_index"
	[ $new_count -gt 1 ] && echo -n " ... MDT$((new_index + new_count - 1))"
	echo

	echo "$LFS migrate -m$new_index -c$new_count -H $new_hash $migrate_dir"
	$LFS migrate -m $new_index -c $new_count -H $new_hash $migrate_dir ||
		error "migrate remote dir error"

	echo "Finish migration, then checking.."
	for file in $(find $migrate_dir -maxdepth 1); do
		mdt_index=$($LFS getstripe -m $file)
		if [ $mdt_index -lt $new_index ] ||
		   [ $mdt_index -gt $((new_index + new_count - 1)) ]; then
			error "$file is on MDT$mdt_index"
		fi
	done

	rm -rf $DIR/$tdir || error "rm dir failed after migration"
}
run_test 230d "check migrate big directory"

test_230e() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"
	[ $MDS1_VERSION -lt $(version_code 2.11.52) ] &&
		skip "Need MDS version at least 2.11.52"

	local i
	local j
	local a_fid
	local b_fid

	mkdir_on_mdt0 $DIR/$tdir
	mkdir $DIR/$tdir/migrate_dir
	mkdir $DIR/$tdir/other_dir
	touch $DIR/$tdir/migrate_dir/a
	ln $DIR/$tdir/migrate_dir/a $DIR/$tdir/other_dir/b
	ls $DIR/$tdir/other_dir

	$LFS migrate -m 1 $DIR/$tdir/migrate_dir ||
		error "migrate dir fails"

	mdt_index=$($LFS getstripe -m $DIR/$tdir/migrate_dir)
	[ $mdt_index == 1 ] || error "migrate_dir is not on MDT1"

	mdt_index=$($LFS getstripe -m $DIR/$tdir/migrate_dir/a)
	[ $mdt_index == 0 ] || error "a is not on MDT0"

	$LFS migrate -m 1 $DIR/$tdir/other_dir ||
		error "migrate dir fails"

	mdt_index=$($LFS getstripe -m $DIR/$tdir/other_dir)
	[ $mdt_index == 1 ] || error "other_dir is not on MDT1"

	mdt_index=$($LFS getstripe -m $DIR/$tdir/migrate_dir/a)
	[ $mdt_index == 1 ] || error "a is not on MDT1"

	mdt_index=$($LFS getstripe -m $DIR/$tdir/other_dir/b)
	[ $mdt_index == 1 ] || error "b is not on MDT1"

	a_fid=$($LFS path2fid $DIR/$tdir/migrate_dir/a)
	b_fid=$($LFS path2fid $DIR/$tdir/other_dir/b)

	[ "$a_fid" = "$b_fid" ] || error "different fid after migration"

	rm -rf $DIR/$tdir || error "rm dir failed after migration"
}
run_test 230e "migrate mulitple local link files"

test_230f() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"
	[ $MDS1_VERSION -lt $(version_code 2.11.52) ] &&
		skip "Need MDS version at least 2.11.52"

	local a_fid
	local ln_fid

	mkdir -p $DIR/$tdir
	mkdir $DIR/$tdir/migrate_dir
	$LFS mkdir -i1 $DIR/$tdir/other_dir
	touch $DIR/$tdir/migrate_dir/a
	ln $DIR/$tdir/migrate_dir/a $DIR/$tdir/other_dir/ln1
	ln $DIR/$tdir/migrate_dir/a $DIR/$tdir/other_dir/ln2
	ls $DIR/$tdir/other_dir

	# a should be migrated to MDT1, since no other links on MDT0
	$LFS migrate -m 1 $DIR/$tdir/migrate_dir ||
		error "#1 migrate dir fails"
	mdt_index=$($LFS getstripe -m $DIR/$tdir/migrate_dir)
	[ $mdt_index == 1 ] || error "migrate_dir is not on MDT1"
	mdt_index=$($LFS getstripe -m $DIR/$tdir/migrate_dir/a)
	[ $mdt_index == 1 ] || error "a is not on MDT1"

	# a should stay on MDT1, because it is a mulitple link file
	$LFS migrate -m 0 $DIR/$tdir/migrate_dir ||
		error "#2 migrate dir fails"
	mdt_index=$($LFS getstripe -m $DIR/$tdir/migrate_dir/a)
	[ $mdt_index == 1 ] || error "a is not on MDT1"

	$LFS migrate -m 1 $DIR/$tdir/migrate_dir ||
		error "#3 migrate dir fails"

	a_fid=$($LFS path2fid $DIR/$tdir/migrate_dir/a)
	ln_fid=$($LFS path2fid $DIR/$tdir/other_dir/ln1)
	[ "$a_fid" = "$ln_fid" ] || error "different fid after migrate to MDT1"

	rm -rf $DIR/$tdir/other_dir/ln1 || error "unlink ln1 fails"
	rm -rf $DIR/$tdir/other_dir/ln2 || error "unlink ln2 fails"

	# a should be migrated to MDT0, since no other links on MDT1
	$LFS migrate -m 0 $DIR/$tdir/migrate_dir ||
		error "#4 migrate dir fails"
	mdt_index=$($LFS getstripe -m $DIR/$tdir/migrate_dir/a)
	[ $mdt_index == 0 ] || error "a is not on MDT0"

	rm -rf $DIR/$tdir || error "rm dir failed after migration"
}
run_test 230f "migrate mulitple remote link files"

test_230g() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"
	[ $MDS1_VERSION -lt $(version_code 2.11.52) ] &&
		skip "Need MDS version at least 2.11.52"

	mkdir -p $DIR/$tdir/migrate_dir

	$LFS migrate -m 1000 $DIR/$tdir/migrate_dir &&
		error "migrating dir to non-exist MDT succeeds"
	true
}
run_test 230g "migrate dir to non-exist MDT"

test_230h() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"
	[ $MDS1_VERSION -lt $(version_code 2.11.52) ] &&
		skip "Need MDS version at least 2.11.52"

	local mdt_index

	mkdir -p $DIR/$tdir/migrate_dir

	$LFS migrate -m1 $DIR &&
		error "migrating mountpoint1 should fail"

	$LFS migrate -m1 $DIR/$tdir/.. &&
		error "migrating mountpoint2 should fail"

	# same as mv
	$LFS migrate -m1 $DIR/$tdir/migrate_dir/.. &&
		error "migrating $tdir/migrate_dir/.. should fail"

	true
}
run_test 230h "migrate .. and root"

test_230i() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"
	[ $MDS1_VERSION -lt $(version_code 2.11.52) ] &&
		skip "Need MDS version at least 2.11.52"

	mkdir -p $DIR/$tdir/migrate_dir

	$LFS migrate -m 1 $DIR/$tdir/migrate_dir/ ||
		error "migration fails with a tailing slash"

	$LFS migrate -m 0 $DIR/$tdir/migrate_dir// ||
		error "migration fails with two tailing slashes"
}
run_test 230i "lfs migrate -m tolerates trailing slashes"

test_230j() {
	[ $MDSCOUNT -lt 2 ] && skip "needs >= 2 MDTs"
	[ $MDS1_VERSION -lt $(version_code 2.13.52) ] &&
		skip "Need MDS version at least 2.11.52"

	$LFS mkdir -i 0 -c 1 $DIR/$tdir || error "mkdir $tdir failed"
	$LFS setstripe -E 1M -L mdt $DIR/$tdir/$tfile ||
		error "create $tfile failed"
	cat /etc/passwd > $DIR/$tdir/$tfile

	$LFS migrate -m 1 $DIR/$tdir || error "migrate failed"

	cmp /etc/passwd $DIR/$tdir/$tfile ||
		error "DoM file mismatch after migration"
}
run_test 230j "DoM file data not changed after dir migration"

test_230k() {
	[ $MDSCOUNT -lt 4 ] && skip "needs >= 4 MDTs"

	(( $MDS1_VERSION > $(version_code v2_12_9-38-g80e9ebc1b1e4) )) ||
		skip "Need MDS > v2_12_9-38-g80e9ebc1b1e4"

	local total=20
	local files_on_starting_mdt=0

	$LFS mkdir -i -1 -c 2 $DIR/$tdir || error "mkdir failed"
	$LFS getdirstripe $DIR/$tdir
	for i in $(seq $total); do
		echo $((i*i - i)) > $DIR/$tdir/$tfile.$i || error "write failed"
		[[ $($LFS getstripe -m $DIR/$tdir/$tfile.$i) -eq 0 ]] &&
			files_on_starting_mdt=$((files_on_starting_mdt + 1))
	done

	echo "$files_on_starting_mdt files on MDT0"

	$LFS migrate -m 1,3 $DIR/$tdir || error "migrate -m 1,3 failed"
	$LFS getdirstripe $DIR/$tdir

	files_on_starting_mdt=0
	for i in $(seq $total); do
		$(echo $((i*i - i)) | cmp $DIR/$tdir/$tfile.$i -) ||
			error "file $tfile.$i mismatch after migration"
		[[ $($LFS getstripe -m $DIR/$tdir/$tfile.$i) -eq 1 ]] &&
			files_on_starting_mdt=$((files_on_starting_mdt + 1))
	done

	echo "$files_on_starting_mdt files on MDT1 after migration"
	[[ $files_on_starting_mdt -eq $total ]] && error "all files on MDT1"

	$LFS migrate -m 0 -c 2 $DIR/$tdir || error "migrate -m 0 -c 2 failed"
	$LFS getdirstripe $DIR/$tdir

	files_on_starting_mdt=0
	for i in $(seq $total); do
		$(echo $((i*i - i)) | cmp $DIR/$tdir/$tfile.$i -) ||
			error "file $tfile.$i mismatch after 2nd migration"
		[[ $($LFS getstripe -m $DIR/$tdir/$tfile.$i) -eq 0 ]] &&
			files_on_starting_mdt=$((files_on_starting_mdt + 1))
	done

	echo "$files_on_starting_mdt files on MDT0 after 2nd migration"
	[[ $files_on_starting_mdt -eq $total ]] && error "all files on MDT0"

	true
}
run_test 230k "file data not changed after dir migration"

test_230l() {
	[ $MDSCOUNT -lt 2 ] && skip "needs >= 2 MDTs"
	[ $MDS1_VERSION -lt $(version_code 2.11.56) ] &&
		skip "Need MDS version at least 2.11.56"

	$LFS mkdir -i 0 -c 1 $DIR/$tdir || error "mkdir failed"
	createmany -o $DIR/$tdir/f___________________________________ 1000 ||
		error "create files under remote dir failed $i"
	$LFS migrate -m 1 $DIR/$tdir || error "migrate failed"
}
run_test 230l "readdir between MDTs won't crash"

test_230m() {
	[ $MDSCOUNT -lt 2 ] && skip "needs >= 2 MDTs"
	[ $MDS1_VERSION -lt $(version_code 2.11.56) ] &&
		skip "Need MDS version at least 2.11.56"

	local MDTIDX=1
	local mig_dir=$DIR/$tdir/migrate_dir
	local longstr="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
	local shortstr="b"
	local val

	echo "Creating files and dirs with xattrs"
	test_mkdir $DIR/$tdir
	test_mkdir -i0 -c1 $mig_dir
	mkdir $mig_dir/dir
	setfattr -n user.attr1 -v $longstr $mig_dir/dir ||
		error "cannot set xattr attr1 on dir"
	setfattr -n user.attr2 -v $shortstr $mig_dir/dir ||
		error "cannot set xattr attr2 on dir"
	touch $mig_dir/dir/f0
	setfattr -n user.attr1 -v $longstr $mig_dir/dir/f0 ||
		error "cannot set xattr attr1 on file"
	setfattr -n user.attr2 -v $shortstr $mig_dir/dir/f0 ||
		error "cannot set xattr attr2 on file"
	sync ; sync ; echo 3 > /proc/sys/vm/drop_caches
	val=$(getfattr --only-values -n user.attr1 $mig_dir/dir 2>/dev/null)
	[ "$val" = $longstr ] || error "xattr attr1 not set properly on dir"
	val=$(getfattr --only-values -n user.attr2 $mig_dir/dir 2>/dev/null)
	[ "$val" = $shortstr ] || error "xattr attr2 not set properly on dir"
	val=$(getfattr --only-values -n user.attr1 $mig_dir/dir/f0 2>/dev/null)
	[ "$val" = $longstr ] || error "xattr attr1 not set properly on file"
	val=$(getfattr --only-values -n user.attr2 $mig_dir/dir/f0 2>/dev/null)
	[ "$val" = $shortstr ] || error "xattr attr2 not set properly on file"

	echo "Migrating to MDT1"
	$LFS migrate -m $MDTIDX $mig_dir ||
		error "fails on migrating dir to MDT1"

	sync ; sync ; echo 3 > /proc/sys/vm/drop_caches
	echo "Checking xattrs"
	val=$(getfattr --only-values -n user.attr1 $mig_dir/dir 2>/dev/null)
	[ "$val" = $longstr ] ||
		error "expecting xattr1 $longstr on dir, found $val"
	val=$(getfattr --only-values -n user.attr2 $mig_dir/dir 2>/dev/null)
	[ "$val" = $shortstr ] ||
		error "expecting xattr2 $shortstr on dir, found $val"
	val=$(getfattr --only-values -n user.attr1 $mig_dir/dir/f0 2>/dev/null)
	[ "$val" = $longstr ] ||
		error "expecting xattr1 $longstr on file, found $val"
	val=$(getfattr --only-values -n user.attr2 $mig_dir/dir/f0 2>/dev/null)
	[ "$val" = $shortstr ] ||
		error "expecting xattr2 $shortstr on file, found $val"
}
run_test 230m "xattrs not changed after dir migration"

test_230n() {
	[ $MDSCOUNT -lt 2 ] && skip "needs >= 2 MDTs"
	[[ $MDS1_VERSION -ge $(version_code 2.13.53) ]] ||
		skip "Need MDS version at least 2.13.53"

	$LFS mkdir -i 0 $DIR/$tdir || error "mkdir $tdir failed"
	cat /etc/hosts > $DIR/$tdir/$tfile
	$LFS mirror extend -N1 $DIR/$tdir/$tfile || error "Mirroring failed"
	$LFS migrate -m 1 $DIR/$tdir || error "Migration failed"

	cmp /etc/hosts $DIR/$tdir/$tfile ||
		error "File data mismatch after migration"
}
run_test 230n "Dir migration with mirrored file"

test_230o() {
	[ $MDSCOUNT -ge 2 ] || skip "needs >= 2 MDTs"
	[ $MDS1_VERSION -ge $(version_code 2.13.52) ] ||
		skip "Need MDS version at least 2.13.52"

	local mdts=$(mdts_nodes)
	local timeout=100
	local restripe_status
	local delta
	local i

	[[ $mds1_FSTYPE == zfs ]] && timeout=300

	# in case "crush" hash type is not set
	do_nodes $mdts "$LCTL set_param lod.*.mdt_hash=crush"

	restripe_status=$(do_facet mds1 $LCTL get_param -n \
			   mdt.*MDT0000.enable_dir_restripe)
	do_nodes $mdts "$LCTL set_param mdt.*.enable_dir_restripe=1"
	stack_trap "do_nodes $mdts $LCTL set_param \
		    mdt.*.enable_dir_restripe=$restripe_status"

	mkdir $DIR/$tdir
	createmany -m $DIR/$tdir/f 100 ||
		error "create files under remote dir failed $i"
	createmany -d $DIR/$tdir/d 100 ||
		error "create dirs under remote dir failed $i"

	for i in $(seq 2 $MDSCOUNT); do
		do_nodes $mdts "$LCTL set_param mdt.*.md_stats=clear >/dev/null"
		$LFS setdirstripe -c $i $DIR/$tdir ||
			error "split -c $i $tdir failed"
		wait_update $HOSTNAME \
			"$LFS getdirstripe -H $DIR/$tdir" "crush" $timeout ||
			error "dir split not finished"
		delta=$(do_nodes $mdts "lctl get_param -n mdt.*MDT*.md_stats" |
			awk '/migrate/ {sum += $2} END { print sum }')
		echo "$delta migrated when dir split $((i - 1)) to $i stripes"
		# delta is around total_files/stripe_count
		(( $delta < 200 / (i - 1) + 4 )) ||
			error "$delta files migrated >= $((200 / (i - 1) + 4))"
	done
}
run_test 230o "dir split"

test_230p() {
	(( MDSCOUNT > 1 )) || skip "needs >= 2 MDTs"
	(( MDS1_VERSION >= $(version_code 2.13.52) )) ||
		skip "Need MDS version at least 2.13.52"

	local mdts=$(mdts_nodes)
	local timeout=100
	local restripe_status
	local delta
	local c

	[[ $mds1_FSTYPE == zfs ]] && timeout=300

	do_nodes $mdts "$LCTL set_param lod.*.mdt_hash=crush"

	restripe_status=$(do_facet mds1 $LCTL get_param -n \
			   mdt.*MDT0000.enable_dir_restripe)
	do_nodes $mdts "$LCTL set_param mdt.*.enable_dir_restripe=1"
	stack_trap "do_nodes $mdts $LCTL set_param \
		    mdt.*.enable_dir_restripe=$restripe_status"

	test_mkdir -c $MDSCOUNT -H crush $DIR/$tdir
	createmany -m $DIR/$tdir/f 100 ||
		error "create files under remote dir failed"
	createmany -d $DIR/$tdir/d 100 ||
		error "create dirs under remote dir failed"

	for ((c = $MDSCOUNT - 1; c >= 1; c--)); do
		local mdt_hash="crush"

		do_nodes $mdts "$LCTL set_param mdt.*.md_stats=clear >/dev/null"
		$LFS setdirstripe -c $c $DIR/$tdir ||
			error "split -c $c $tdir failed"
		if (( MDS1_VERSION > $(version_code 2.14.0-7-10-g3ae36f4c0a) )); then
			mdt_hash="$mdt_hash,fixed"
		elif (( $c == 1 )); then
			mdt_hash="none"
		fi
		wait_update $HOSTNAME \
			"$LFS getdirstripe -H $DIR/$tdir" $mdt_hash $timeout ||
			error "dir merge not finished"
		delta=$(do_nodes $mdts "lctl get_param -n mdt.*MDT*.md_stats" |
			awk '/migrate/ {sum += $2} END { print sum }')
		echo "$delta migrated when dir merge $((c + 1)) to $c stripes"
		# delta is around total_files/stripe_count
		(( delta < 200 / c + 4 )) ||
			error "$delta files migrated >= $((200 / c + 4))"
	done

	(( MDS1_VERSION >= $(version_code v2_16_52-71-g103c1f560c) )) ||
		skip "need MDS >= 2.16.52.71 for resplitting support"

	# and restripe to -c 2
	echo Splitting the dir back to 2 stripes.
	$LFS setdirstripe -c 2 $DIR/$tdir || {
		$LFS getdirstripe $DIR/$tdir
		error "split $tdir to 2 stripes failed"
	}
	wait_update $HOSTNAME \
		"$LFS getdirstripe -H $DIR/$tdir" "crush" $timeout ||
		error "dir split not finished"
}
run_test 230p "dir merge"

test_230q() {
	(( MDSCOUNT > 1)) || skip "needs >= 2 MDTs"
	(( MDS1_VERSION >= $(version_code 2.13.52) )) ||
		skip "Need MDS version at least 2.13.52"

	local mdts=$(mdts_nodes)
	local saved_threshold=$(do_facet mds1 \
			$LCTL get_param -n mdt.*-MDT0000.dir_split_count)
	local saved_delta=$(do_facet mds1 \
			$LCTL get_param -n mdt.*-MDT0000.dir_split_delta)
	local threshold=100
	local delta=2
	local total=0
	local stripe_count=0
	local stripe_index
	local nr_files
	local create

	# test with fewer files on ZFS
	[ "$mds1_FSTYPE" == "zfs" ] && threshold=40

	stack_trap "do_nodes $mdts $LCTL set_param \
		    mdt.*.dir_split_count=$saved_threshold"
	stack_trap "do_nodes $mdts $LCTL set_param \
		    mdt.*.dir_split_delta=$saved_delta"
	stack_trap "do_nodes $mdts $LCTL set_param mdt.*.dir_restripe_nsonly=1"
	do_nodes $mdts "$LCTL set_param mdt.*.enable_dir_auto_split=1"
	do_nodes $mdts "$LCTL set_param mdt.*.dir_split_count=$threshold"
	do_nodes $mdts "$LCTL set_param mdt.*.dir_split_delta=$delta"
	do_nodes $mdts "$LCTL set_param mdt.*.dir_restripe_nsonly=0"
	do_nodes $mdts "$LCTL set_param lod.*.mdt_hash=crush"

	$LFS mkdir -i -1 -c 1 $DIR/$tdir || error "mkdir $tdir failed"
	stripe_index=$($LFS getdirstripe -i $DIR/$tdir)

	create=$((threshold * 3 / 2))
	while [ $stripe_count -lt $MDSCOUNT ]; do
		createmany -m $DIR/$tdir/f $total $create ||
			error "create sub files failed"
		stat $DIR/$tdir > /dev/null
		total=$((total + create))
		stripe_count=$((stripe_count + delta))
		[ $stripe_count -gt $MDSCOUNT ] && stripe_count=$MDSCOUNT

		wait_update $HOSTNAME \
			"$LFS getdirstripe -c $DIR/$tdir" "$stripe_count" 40 ||
			error "stripe count $($LFS getdirstripe -c $DIR/$tdir) != $stripe_count"

		wait_update $HOSTNAME \
			"$LFS getdirstripe -H $DIR/$tdir" "crush" 200 ||
			error "stripe hash $($LFS getdirstripe -H $DIR/$tdir) != crush"

		nr_files=$($LFS find -m 1 $DIR/$tdir | grep -c -w $stripe_index)
		echo "$nr_files/$total files on MDT$stripe_index after split"
		# allow 10% margin of imbalance with crush hash
		(( $nr_files <= $total / $stripe_count + $create / 10)) ||
			error "$nr_files files on MDT$stripe_index after split"

		nr_files=$($LFS find -type f $DIR/$tdir | wc -l)
		[ $nr_files -eq $total ] ||
			error "total sub files $nr_files != $total"
	done

	(( MDS1_VERSION >= $(version_code 2.14.51) )) || return 0

	echo "fixed layout directory won't auto split"
	$LFS migrate -m 0 $DIR/$tdir || error "migrate $tdir failed"
	wait_update $HOSTNAME "$LFS getdirstripe -H $DIR/$tdir" "crush,fixed" \
		10 || error "stripe hash $($LFS getdirstripe -H $DIR/$tdir)"
	wait_update $HOSTNAME "$LFS getdirstripe -c $DIR/$tdir" 1 10 ||
		error "stripe count $($LFS getdirstripe -c $DIR/$tdir)"
}
run_test 230q "dir auto split"

test_230r() {
	[[ $PARALLEL != "yes" ]] || skip "skip parallel run"
	[[ $MDSCOUNT -ge 2 ]] || skip_env "needs >= 2 MDTs"
	[[ $MDS1_VERSION -ge $(version_code 2.13.54) ]] ||
		skip "Need MDS version at least 2.13.54"

	# maximum amount of local locks:
	# parent striped dir - 2 locks
	# new stripe in parent to migrate to - 1 lock
	# source and target - 2 locks
	# Total 5 locks for regular file
	mkdir -p $DIR/$tdir
	$LFS mkdir -i1 -c2 $DIR/$tdir/dir1
	touch $DIR/$tdir/dir1/eee

	# create 4 hardlink for 4 more locks
	# Total: 9 locks > RS_MAX_LOCKS (8)
	$LFS mkdir -i1 -c1 $DIR/$tdir/dir2
	$LFS mkdir -i1 -c1 $DIR/$tdir/dir3
	$LFS mkdir -i1 -c1 $DIR/$tdir/dir4
	$LFS mkdir -i1 -c1 $DIR/$tdir/dir5
	ln $DIR/$tdir/dir1/eee $DIR/$tdir/dir2/eee
	ln $DIR/$tdir/dir1/eee $DIR/$tdir/dir3/eee
	ln $DIR/$tdir/dir1/eee $DIR/$tdir/dir4/eee
	ln $DIR/$tdir/dir1/eee $DIR/$tdir/dir5/eee

	cancel_lru_locks mdc

	$LFS migrate -m1 -c1 $DIR/$tdir/dir1 ||
		error "migrate dir fails"

	rm -rf $DIR/$tdir || error "rm dir failed after migration"
}
run_test 230r "migrate with too many local locks"

test_230s() {
	(( $MDS1_VERSION >= $(version_code 2.14.52) )) ||
		skip "Need MDS version at least 2.14.52"

	local mdts=$(mdts_nodes)
	local restripe_status=$(do_facet mds1 $LCTL get_param -n \
				mdt.*MDT0000.enable_dir_restripe)

	stack_trap "do_nodes $mdts $LCTL set_param \
		    mdt.*.enable_dir_restripe=$restripe_status"

	local st
	for st in 0 1; do
		do_nodes $mdts "$LCTL set_param mdt.*.enable_dir_restripe=$st"
		test_mkdir $DIR/$tdir
		$LFS mkdir $DIR/$tdir |& grep "File exists" ||
			error "$LFS mkdir should return EEXIST if target exists"
		rmdir $DIR/$tdir
	done
}
run_test 230s "lfs mkdir should return -EEXIST if target exists"

test_230t()
{
	(( $MDSCOUNT >= 2 )) || skip_env "needs >= 2 MDTs"
	(( $MDS1_VERSION >= $(version_code 2.14.50) )) ||
		skip "Need MDS version at least 2.14.50"

	test_mkdir $DIR/$tdir || error "mkdir $tdir failed"
	test_mkdir $DIR/$tdir/subdir || error "mkdir subdir failed"
	$LFS project -p 1 -s $DIR/$tdir ||
		error "set $tdir project id failed"
	$LFS project -p 2 -s $DIR/$tdir/subdir ||
		error "set subdir project id failed"
	local pbefore="$($LFS project -d $DIR/$tdir)"
	local sbefore="$($LFS project -d $DIR/$tdir/subdir)"
	$LFS migrate -m 1 -c $MDSCOUNT $DIR/$tdir || error "migrate failed"

	local pafter="$($LFS project -d $DIR/$tdir)"
	local safter="$($LFS project -d $DIR/$tdir/subdir)"
	[[ "$pbefore" == "$pafter" ]] || error "projid '$pbefore' != '$pafter'"
	[[ "$sbefore" == "$safter" ]] || error "projid '$sbefore' != '$safter'"

	(( $MDS1_VERSION >= $(version_code 2.15.59.107) )) ||
		{ echo "Need MDS >= 2.15.59.107 for projid rename"; return 0; }

	# check rename works, even if source parent projid differs (LU-17016)
	test_mkdir $DIR/$tdir.2 || error "mkdir $tdir.2 failed"
	local fid_before=$($LFS path2fid $DIR/$tdir/subdir)

	$LFS project -p 2 -s $DIR/$tdir.2 || error "set $tdir.2 projid failed"
	mrename $DIR/$tdir/subdir $DIR/$tdir.2/subdir ||
		error "subdir failed rename for different source parent projid"
	local fid_after=$($LFS path2fid $DIR/$tdir.2/subdir)

	[[ "$fid_before" == "$fid_after" ]] ||
		error "fid before '$fid_before' != after '$fid_after'"
}
run_test 230t "migrate directory with project ID set"

test_230u()
{
	(( MDSCOUNT > 3 )) || skip_env "needs >= 4 MDTs"
	(( MDS1_VERSION >= $(version_code 2.14.53) )) ||
		skip "Need MDS version at least 2.14.53"

	local count

	mkdir_on_mdt0 $DIR/$tdir || error "mkdir $tdir failed"
	mkdir $DIR/$tdir/sub{0..99} || error "mkdir sub failed"
	$LFS migrate -m -1 $DIR/$tdir/sub{0..99} || error "migrate sub failed"
	for i in $(seq 0 $((MDSCOUNT - 1))); do
		count=$($LFS getstripe -m $DIR/$tdir/sub* | grep -c ^$i)
		echo "$count dirs migrated to MDT$i"
	done
	count=$($LFS getstripe -m $DIR/$tdir/sub* | sort -u | wc -l)
	(( count >= MDSCOUNT - 1 )) || error "dirs migrated to $count MDTs"
}
run_test 230u "migrate directory by QOS"

test_230v()
{
	(( MDSCOUNT > 3 )) || skip_env "needs >= 4 MDTs"
	(( MDS1_VERSION >= $(version_code 2.14.53) )) ||
		skip "Need MDS version at least 2.14.53"

	local count

	mkdir $DIR/$tdir || error "mkdir $tdir failed"
	mkdir $DIR/$tdir/sub{0..99} || error "mkdir sub failed"
	$LFS migrate -m 0,2,1 $DIR/$tdir || error "migrate $tdir failed"
	for i in $(seq 0 $((MDSCOUNT - 1))); do
		count=$($LFS getstripe -m $DIR/$tdir/sub* | grep -c ^$i)
		echo "$count subdirs migrated to MDT$i"
		(( i == 3 )) && (( count > 0 )) &&
			error "subdir shouldn't be migrated to MDT3"
	done
	count=$($LFS getstripe -m $DIR/$tdir/sub* | sort -u | wc -l)
	(( count == 3 )) || error "dirs migrated to $count MDTs"
}
run_test 230v "subdir migrated to the MDT where its parent is located"

test_230w() {
	(( MDSCOUNT > 1 )) || skip "needs >= 2 MDTs"
	(( MDS1_VERSION >= $(version_code 2.15.0) )) ||
		skip "Need MDS version at least 2.15.0"

	mkdir -p $DIR/$tdir || error "mkdir $tdir failed"
	createmany -o $DIR/$tdir/f 10 || error "create files failed"
	createmany -d $DIR/$tdir/d 10 || error "create dirs failed"

	$LFS migrate -m 1 -c $MDSCOUNT -d $DIR/$tdir ||
		error "migrate failed"

	(( $($LFS getdirstripe -c $DIR/$tdir) == MDSCOUNT )) ||
		error "$tdir stripe count mismatch"

	for i in $(seq 0 9); do
		(( $($LFS getdirstripe -c $DIR/$tdir/d$i) == 0 )) ||
			error "d$i is striped"
	done
}
run_test 230w "non-recursive mode dir migration"

test_230x() {
	(( MDSCOUNT > 1 )) || skip "needs >= 2 MDTs"
	(( MDS1_VERSION >= $(version_code v2_15_52-83-g6aee406c84) )) ||
		skip "Need MDS >= 2.15.53 for migrate space check"

	mkdir -p $DIR/$tdir || error "mkdir failed"
	createmany -d $DIR/$tdir/sub 100 || error "createmany failed"

	local mdt_name=$(mdtname_from_index 0)
	local low=$(do_facet mds2 $LCTL get_param -n \
		osp.*$mdt_name-osp-MDT0001.reserved_ino_low)
	local high=$(do_facet mds2 $LCTL get_param -n \
		osp.*$mdt_name-osp-MDT0001.reserved_ino_high)
	local ffree=$($LFS df -i $MOUNT | awk "/$mdt_name/ { print \$4 }")
	local maxage=$(do_facet mds2 $LCTL get_param -n \
		osp.*$mdt_name-osp-MDT0001.maxage)

	stack_trap "do_facet mds2 $LCTL set_param -n \
		osp.*$mdt_name-osp-MDT0001.reserved_ino_low=$low \
		osp.*$mdt_name-osp-MDT0001.reserved_ino_high=$high" EXIT
	stack_trap "do_facet mds2 $LCTL set_param -n \
		osp.*$mdt_name-osp-MDT0001.maxage=$maxage" EXIT

	do_facet mds2 $LCTL set_param -n \
		osp.*$mdt_name-osp-MDT0001.reserved_ino_low=$((ffree + 1))
	do_facet mds2 $LCTL set_param -n osp.*$mdt_name-osp-MDT0001.maxage=1
	sleep 4
	$LFS migrate -m 1 -c $MDSCOUNT $DIR/$tdir &&
		error "migrate $tdir should fail"

	do_facet mds2 $LCTL set_param -n \
		osp.*$mdt_name-osp-MDT0001.reserved_ino_low=$low
	do_facet mds2 $LCTL set_param -n \
		osp.*$mdt_name-osp-MDT0001.reserved_ino_high=$high
	sleep 4
	$LFS migrate -m 1 -c $MDSCOUNT $DIR/$tdir ||
		error "migrate failed"
	(( $($LFS getdirstripe -c $DIR/$tdir) == $MDSCOUNT )) ||
		error "$tdir stripe count mismatch"
}
run_test 230x "dir migration check space"

test_230y() {
	(( MDSCOUNT > 1 )) || skip "needs >= 2 MDTs"
	(( MDS1_VERSION >= $(version_code 2.15.55.45) )) ||
		skip "Need MDS version at least 2.15.55.45"

	local pid

	test_mkdir -c -1 $DIR/$tdir || error "mkdir $tdir failed"
	$LFS getdirstripe $DIR/$tdir
	createmany -d $DIR/$tdir/d 100 || error "createmany failed"
	$LFS migrate -m 1 -c 2 $DIR/$tdir &
	pid=$!
	sleep 1

	#OBD_FAIL_MIGRATE_BAD_HASH	0x1802
	do_facet mds2 lctl set_param fail_loc=0x1802

	wait $pid
	do_facet mds2 lctl set_param fail_loc=0
	$LFS getdirstripe $DIR/$tdir
	unlinkmany -d $DIR/$tdir/d 100 || error "unlinkmany failed"
	rmdir $DIR/$tdir || error "rmdir $tdir failed"
}
run_test 230y "unlink dir with bad hash type"

test_230z() {
	(( MDSCOUNT > 1 )) || skip "needs >= 2 MDTs"
	(( MDS1_VERSION >= $(version_code 2.15.55.45) )) ||
		skip "Need MDS version at least 2.15.55.45"

	local pid

	test_mkdir -c -1 $DIR/$tdir || error "mkdir $tdir failed"
	$LFS getdirstripe $DIR/$tdir
	createmany -d $DIR/$tdir/d 100 || error "createmany failed"
	$LFS migrate -m 1 -c 2 -H fnv_1a_64 $DIR/$tdir &
	pid=$!
	sleep 1

	#OBD_FAIL_MIGRATE_BAD_HASH	0x1802
	do_facet mds2 lctl set_param fail_loc=0x1802

	wait $pid
	do_facet mds2 lctl set_param fail_loc=0
	$LFS getdirstripe $DIR/$tdir

	# resume migration
	$LFS migrate -m 1 -c 2 -H fnv_1a_64 $DIR/$tdir ||
		error "resume migration failed"
	$LFS getdirstripe $DIR/$tdir
	[ $($LFS getdirstripe -H $DIR/$tdir) == "fnv_1a_64,fixed" ] ||
		error "migration is not finished"
}
run_test 230z "resume dir migration with bad hash type"

test_230A_check_lmm_oi() {
	local FID LMM_FID

	FID=$($LFS path2fid "$1")
	while read LMM_FID; do
	[[ "$FID" == "$LMM_FID" ]] || {
		echo "FID=$FID LMM_FID=$LMM_FID"
		return 1
	}
	done < <( $LFS getstripe -v "$1" | awk '/lmm_fid:/ {print $2 }' )
	return 0
}

test_230A()
{
        (( MDSCOUNT > 1 )) || skip "needs >= 2 MDTs"
        (( MDS1_VERSION >= $(version_code 2.16.57) )) ||
                skip "need MDS >= 2.16.57 for lmm_oi migrate update"

	$LFS mkdir -i 0 -c 1 $DIR/$tdir || error "mkdir $tdir failed"
	$LFS setstripe -E 10M -c 1 -E -1 -c 1 $DIR/$tdir/file || error "file creation failed"
	test_230A_check_lmm_oi $DIR/$tdir/file || error "Wrong lmm oi before migrate"
	$LFS migrate -m 1 $DIR/$tdir || error "migrate failed"
	test_230A_check_lmm_oi $DIR/$tdir/file || error "Wrong lmm oi after migrate"
}
run_test 230A "dir migrate should update lmm_oi"

test_230B() {
	(( MDSCOUNT > 1 )) || skip "needs >= 2 MDTs"
	(( MDS1_VERSION >= $(version_code 2.17.51) )) ||
                skip "need MDS >= 2.17.51 for lmm_oi migrate update"

	test_mkdir -i 0 -c 1 $DIR/$tdir
	echo "create files"
	createmany -d $DIR/$tdir/d 10
	(
		cd $DIR/$tdir
		sleep 10
		echo create the second "foo" file
		mkdir foo
	) &

	do_facet mds2 lctl set_param fail_loc=0x1801
	echo "attempt to migrate"
	$LFS migrate -m 1 $DIR/$tdir
	echo create the first "foo" file
	touch $DIR/$tdir/foo
	echo wait ...
	wait
	num=$(ls -l $DIR/$tdir | grep -c foo)
	do_facet mds2 lctl set_param fail_loc=0
	$LFS getdirstripe $DIR/$tdir
	$LFS path2fid $DIR/$tdir
	(( num == 1 )) || error "duplicated files creation during migration"
}
run_test 230B "create duplicated entries in a migrating dir"

test_231a()
{
	# For simplicity this test assumes that max_pages_per_rpc
	# is the same across all OSCs
	local max_pages=$($LCTL get_param -n osc.*.max_pages_per_rpc | head -n1)
	local bulk_size=$((max_pages * PAGE_SIZE))
	local brw_size=$(do_facet ost1 $LCTL get_param -n obdfilter.*.brw_size |
				       head -n 1)

	mkdir -p $DIR/$tdir
	$LFS setstripe -S ${brw_size}M $DIR/$tdir ||
		error "failed to set stripe with -S ${brw_size}M option"
	stack_trap "rm -rf $DIR/$tdir"

	# clear the OSC stats
	$LCTL set_param osc.*.stats=0 &>/dev/null
	stop_writeback

	# Client writes $bulk_size - there must be 1 rpc for $max_pages.
	dd if=/dev/zero of=$DIR/$tdir/$tfile bs=$bulk_size count=1 \
		oflag=direct &>/dev/null || error "dd failed"

	sync; sleep 1; sync # just to be safe
	local nrpcs=$($LCTL get_param osc.*.stats |awk '/ost_write/ {print $2}')
	if [ x$nrpcs != "x1" ]; then
		$LCTL get_param osc.*.stats
		error "found $nrpcs ost_write RPCs, not 1 as expected"
	fi

	start_writeback
	# Drop the OSC cache, otherwise we will read from it
	cancel_lru_locks osc

	# clear the OSC stats
	$LCTL set_param osc.*.stats=0 &>/dev/null

	# Client reads $bulk_size.
	dd if=$DIR/$tdir/$tfile of=/dev/null bs=$bulk_size count=1 \
		iflag=direct &>/dev/null || error "dd failed"

	nrpcs=$($LCTL get_param osc.*.stats | awk '/ost_read/ { print $2 }')
	if [ x$nrpcs != "x1" ]; then
		$LCTL get_param osc.*.stats
		error "found $nrpcs ost_read RPCs, not 1 as expected"
	fi
}
run_test 231a "checking that reading/writing of BRW RPC size results in one RPC"

test_231b() {
	mkdir -p $DIR/$tdir
	stack_trap "rm -rf $DIR/$tdir"
	local i
	for i in {0..1023}; do
		dd if=/dev/zero of=$DIR/$tdir/$tfile conv=notrunc \
			seek=$((2 * i)) bs=4096 count=1 &>/dev/null ||
			error "dd of=$DIR/$tdir/$tfile seek=$((2 * i)) failed"
	done
	sync
}
run_test 231b "must not assert on fully utilized OST request buffer"

test_232a() {
	mkdir -p $DIR/$tdir
	$LFS setstripe -c1 -i0 $DIR/$tdir/$tfile

	#define OBD_FAIL_LDLM_OST_LVB		 0x31c
	do_facet ost1 $LCTL set_param fail_loc=0x31c

	# ignore dd failure
	dd if=/dev/zero of=$DIR/$tdir/$tfile bs=1M count=1 || true
	stack_trap "rm -f $DIR/$tdir/$tfile"

	do_facet ost1 $LCTL set_param fail_loc=0
	umount_client $MOUNT || error "umount failed"
	mount_client $MOUNT || error "mount failed"
	stop ost1 || error "cannot stop ost1"
	start ost1 $(ostdevname 1) $OST_MOUNT_OPTS || error "cannot start ost1"
}
run_test 232a "failed lock should not block umount"

test_232b() {
	[ $MDS1_VERSION -ge $(version_code 2.10.58) ] ||
		skip "Need MDS version at least 2.10.58"

	mkdir -p $DIR/$tdir
	$LFS setstripe -c1 -i0 $DIR/$tdir/$tfile
	dd if=/dev/zero of=$DIR/$tdir/$tfile bs=1M count=1
	stack_trap "rm -f $DIR/$tdir/$tfile"
	sync
	cancel_lru_locks osc

	#define OBD_FAIL_LDLM_OST_LVB		 0x31c
	do_facet ost1 $LCTL set_param fail_loc=0x31c

	# ignore failure
	$LFS data_version $DIR/$tdir/$tfile || true

	do_facet ost1 $LCTL set_param fail_loc=0
	umount_client $MOUNT || error "umount failed"
	mount_client $MOUNT || error "mount failed"
	stop ost1 || error "cannot stop ost1"
	start ost1 $(ostdevname 1) $OST_MOUNT_OPTS || error "cannot start ost1"
}
run_test 232b "failed data version lock should not block umount"

test_233a() {
	[ $MDS1_VERSION -ge $(version_code 2.3.64) ] ||
		skip "Need MDS version at least 2.3.64"
	[ -n "$FILESET" ] && skip_env "SKIP due to FILESET set"

	local fid=$($LFS path2fid $MOUNT)

	stat $MOUNT/.lustre/fid/$fid > /dev/null ||
		error "cannot access $MOUNT using its FID '$fid'"
}
run_test 233a "checking that OBF of the FS root succeeds"

test_233b() {
	[ $MDS1_VERSION -ge $(version_code 2.5.90) ] ||
		skip "Need MDS version at least 2.5.90"
	[ -n "$FILESET" ] && skip_env "SKIP due to FILESET set"

	local fid=$($LFS path2fid $MOUNT/.lustre)

	stat $MOUNT/.lustre/fid/$fid > /dev/null ||
		error "cannot access $MOUNT/.lustre using its FID '$fid'"

	fid=$($LFS path2fid $MOUNT/.lustre/fid)
	stat $MOUNT/.lustre/fid/$fid > /dev/null ||
		error "cannot access $MOUNT/.lustre/fid using its FID '$fid'"
}
run_test 233b "checking that OBF of the FS .lustre succeeds"

test_234() {
	local p="$TMP/sanityN-$TESTNAME.parameters"
	save_lustre_params client "llite.*.xattr_cache" > $p
	lctl set_param llite.*.xattr_cache 1 ||
		skip_env "xattr cache is not supported"

	mkdir -p $DIR/$tdir || error "mkdir failed"
	touch $DIR/$tdir/$tfile || error "touch failed"
	# OBD_FAIL_LLITE_XATTR_ENOMEM
	$LCTL set_param fail_loc=0x1405
	getfattr -n user.attr $DIR/$tdir/$tfile &&
		error "getfattr should have failed with ENOMEM"
	$LCTL set_param fail_loc=0x0
	rm -rf $DIR/$tdir

	restore_lustre_params < $p
	rm -f $p
}
run_test 234 "xattr cache should not crash on ENOMEM"

test_235() {
	[ $MDS1_VERSION -lt $(version_code 2.4.52) ] &&
		skip "Need MDS version at least 2.4.52"

	flock_deadlock $DIR/$tfile
	local RC=$?
	case $RC in
		0)
		;;
		124) error "process hangs on a deadlock"
		;;
		*) error "error executing flock_deadlock $DIR/$tfile"
		;;
	esac
}
run_test 235 "LU-1715: flock deadlock detection does not work properly"

#LU-2935
test_236() {
	check_swap_layouts_support

	local ref1=/etc/passwd
	local ref2=/etc/group
	local file1=$DIR/$tdir/f1
	local file2=$DIR/$tdir/f2

	test_mkdir -c1 $DIR/$tdir
	$LFS setstripe -c 1 $file1 || error "cannot setstripe on '$file1': rc = $?"
	cp $ref1 $file1 || error "cp $ref1 $file1 failed: rc = $?"
	$LFS setstripe -c 2 $file2 || error "cannot setstripe on '$file2': rc = $?"
	cp $ref2 $file2 || error "cp $ref2 $file2 failed: rc = $?"
	local fd=$(free_fd)
	local cmd="exec $fd<>$file2"
	eval $cmd
	rm $file2
	$LFS swap_layouts $file1 /proc/self/fd/${fd} ||
		error "cannot swap layouts of '$file1' and /proc/self/fd/${fd}"
	cmd="exec $fd>&-"
	eval $cmd
	cmp $ref2 $file1 || error "content compare failed ($ref2 != $file1)"

	#cleanup
	rm -rf $DIR/$tdir
}
run_test 236 "Layout swap on open unlinked file"

# LU-4659 linkea consistency
test_238() {
	[[ $MDS1_VERSION -gt $(version_code 2.5.57) ]] ||
		[[ $MDS1_VERSION -gt $(version_code 2.5.1) &&
		   $MDS1_VERSION -lt $(version_code 2.5.50) ]] ||
		skip "Need MDS version at least 2.5.58 or 2.5.2+"

	touch $DIR/$tfile
	ln $DIR/$tfile $DIR/$tfile.lnk
	touch $DIR/$tfile.new
	mv $DIR/$tfile.new $DIR/$tfile
	local fid1=$($LFS path2fid $DIR/$tfile)
	local fid2=$($LFS path2fid $DIR/$tfile.lnk)
	local path1=$($LFS fid2path $FSNAME "$fid1")
	[ $tfile == $path1 ] || error "linkea inconsistent: $tfile $fid1 $path1"
	local path2=$($LFS fid2path $FSNAME "$fid2")
	[ $tfile.lnk == $path2 ] ||
		error "linkea inconsistent: $tfile.lnk $fid2 $path2!"
	rm -f $DIR/$tfile*
}
run_test 238 "Verify linkea consistency"

test_239A() { # was test_239
	[ $MDS1_VERSION -lt $(version_code 2.5.60) ] &&
		skip "Need MDS version at least 2.5.60"

	local mdts=$(mdts_nodes)

	mkdir -p $DIR/$tdir
	createmany -o $DIR/$tdir/f- 5000
	unlinkmany $DIR/$tdir/f- 5000
	[ $MDS1_VERSION -gt $(version_code 2.10.4) ] &&
		do_nodes $mdts "lctl set_param -n osp.*.force_sync=1"
	changes=$(do_nodes $mdts "lctl get_param -n osp.*MDT*.sync_changes \
			osp.*MDT*.sync_in_flight" | calc_sum)
	[ "$changes" -eq 0 ] || error "$changes not synced"
}
run_test 239A "osp_sync test"

test_239a() { #LU-5297
	remote_mds_nodsh && skip "remote MDS with nodsh"

	touch $DIR/$tfile
	#define OBD_FAIL_OSP_CHECK_INVALID_REC     0x2100
	do_facet $SINGLEMDS $LCTL set_param fail_loc=0x2100
	chgrp $RUNAS_GID $DIR/$tfile
	wait_delete_completed
}
run_test 239a "process invalid osp sync record correctly"

test_239b() { #LU-5297
	remote_mds_nodsh && skip "remote MDS with nodsh"

	touch $DIR/$tfile1
	#define OBD_FAIL_OSP_CHECK_ENOMEM     0x2101
	do_facet $SINGLEMDS $LCTL set_param fail_loc=0x2101
	chgrp $RUNAS_GID $DIR/$tfile1
	wait_delete_completed
	do_facet $SINGLEMDS $LCTL set_param fail_loc=0
	touch $DIR/$tfile2
	chgrp $RUNAS_GID $DIR/$tfile2
	wait_delete_completed
}
run_test 239b "process osp sync record with ENOMEM error correctly"

test_240() {
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"
	remote_mds_nodsh && skip "remote MDS with nodsh"

	mkdir -p $DIR/$tdir

	$LFS mkdir -i 0 $DIR/$tdir/d0 ||
		error "failed to mkdir $DIR/$tdir/d0 on MDT0"
	$LFS mkdir -i 1 $DIR/$tdir/d0/d1 ||
		error "failed to mkdir $DIR/$tdir/d0/d1 on MDT1"

	umount_client $MOUNT || error "umount failed"
	#define OBD_FAIL_TGT_DELAY_CONDITIONAL	 0x713
	do_facet mds2 lctl set_param fail_loc=0x713 fail_val=1
	mount_client $MOUNT || error "failed to mount client"

	echo "stat $DIR/$tdir/d0/d1, should not fail/ASSERT"
	stat $DIR/$tdir/d0/d1 || error "fail to stat $DIR/$tdir/d0/d1"
}
run_test 240 "race between ldlm enqueue and the connection RPC (no ASSERT)"

test_241_bio() {
	local count=$1
	local bsize=$2

	for LOOP in $(seq $count); do
		dd if=$DIR/$tfile of=/dev/null bs=$bsize count=1 2>/dev/null
		cancel_lru_locks $OSC || true
	done
}

test_241_dio() {
	local count=$1
	local bsize=$2

	for LOOP in $(seq $1); do
		dd if=$DIR/$tfile of=/dev/null bs=$bsize count=1 iflag=direct \
			2>/dev/null
	done
}

test_241a() { # was test_241
	local bsize=$PAGE_SIZE

	(( bsize < 40960 )) && bsize=40960
	dd if=/dev/zero of=$DIR/$tfile count=1 bs=$bsize
	ls -la $DIR/$tfile
	cancel_lru_locks $OSC
	test_241_bio 1000 $bsize &
	PID=$!
	test_241_dio 1000 $bsize
	wait $PID
}
run_test 241a "bio vs dio"

test_241b() {
	local bsize=$PAGE_SIZE

	(( bsize < 40960 )) && bsize=40960
	dd if=/dev/zero of=$DIR/$tfile count=1 bs=$bsize
	ls -la $DIR/$tfile
	test_241_dio 1000 $bsize &
	PID=$!
	test_241_dio 1000 $bsize
	wait $PID
}
run_test 241b "dio vs dio"

test_242() {
	remote_mds_nodsh && skip "remote MDS with nodsh"

	mkdir_on_mdt0 $DIR/$tdir
	touch $DIR/$tdir/$tfile

	#define OBD_FAIL_MDS_READPAGE_PACK	0x105
	do_facet mds1 lctl set_param fail_loc=0x105
	/bin/ls $DIR/$tdir && error "ls $DIR/$tdir should fail"

	do_facet mds1 lctl set_param fail_loc=0
	/bin/ls $DIR/$tdir || error "ls $DIR/$tdir failed"
}
run_test 242 "mdt_readpage failure should not cause directory unreadable"

test_243()
{
	test_mkdir $DIR/$tdir
	group_lock_test -d $DIR/$tdir || error "A group lock test failed"
}
run_test 243 "various group lock tests"

test_244a()
{
	test_mkdir $DIR/$tdir
	dd if=/dev/zero of=$DIR/$tdir/$tfile bs=1M count=35
	sendfile_grouplock $DIR/$tdir/$tfile || \
		error "sendfile+grouplock failed"
	rm -rf $DIR/$tdir
}
run_test 244a "sendfile with group lock tests"

test_244b()
{
	[ $PARALLEL == "yes" ] && skip "skip parallel run" && return

	local threads=50
	local size=$((1024*1024))

	test_mkdir $DIR/$tdir
	for i in $(seq 1 $threads); do
		local file=$DIR/$tdir/file_$((i / 10))
		$MULTIOP $file OG1234w$size_$((i % 3))w$size_$((i % 4))g1234c &
		local pids[$i]=$!
	done
	for i in $(seq 1 $threads); do
		wait ${pids[$i]}
	done
}
run_test 244b "multi-threaded write with group lock"

test_245a() {
	local flagname="multi_mod_rpcs"
	local connect_data_name="max_mod_rpcs"
	local out

	# check if multiple modify RPCs flag is set
	out=$($LCTL get_param mdc.$FSNAME-MDT0000-*.import |
		grep "connect_flags:")
	echo "$out"

	echo "$out" | grep -qw $flagname
	if [ $? -ne 0 ]; then
		echo "connect flag $flagname is not set"
		return
	fi

	# check if multiple modify RPCs data is set
	out=$($LCTL get_param mdc.$FSNAME-MDT0000-*.import)
	echo "$out"

	echo "$out" | grep -qw $connect_data_name ||
		error "import should have connect data $connect_data_name"
}
run_test 245a "check mdc connection flag/data: multiple modify RPCs"

test_245b() {
	local flagname="multi_mod_rpcs"
	local connect_data_name="max_mod_rpcs"
	local out

	remote_mds_nodsh && skip "remote MDS with nodsh"
	[[ $MDSCOUNT -ge 2 ]] || skip "needs >= 2 MDTs"

	# check if multiple modify RPCs flag is set
	out=$(do_facet mds1 \
	      $LCTL get_param osp.$FSNAME-MDT0001-osp-MDT0000.import |
	      grep "connect_flags:")
	echo "$out"

	[[ "$out" =~ $flagname ]] || skip "connect flag $flagname is not set"

	# check if multiple modify RPCs data is set
	out=$(do_facet mds1 \
	      $LCTL get_param osp.$FSNAME-MDT0001-osp-MDT0000.import)

	[[ "$out" =~ $connect_data_name ]] ||
		{
			echo "$out"
			error "missing connect data $connect_data_name"
		}
}
run_test 245b "check osp connection flag/data: multiple modify RPCs"

cleanup_247() {
	local submount=$1

	trap 0
	umount_client $submount
	rmdir $submount
}

test_247a() {
	lctl get_param -n mdc.$FSNAME-MDT0000*.import |
		grep -q subtree ||
		skip_env "Fileset feature is not supported"

	local submount=${MOUNT}_$tdir

	mkdir $MOUNT/$tdir
	mkdir -p $submount || error "mkdir $submount failed"
	FILESET="$FILESET/$tdir" mount_client $submount ||
		error "mount $submount failed"
	trap "cleanup_247 $submount" EXIT
	echo foo > $submount/$tfile || error "write $submount/$tfile failed"
	[ $(cat $MOUNT/$tdir/$tfile) = "foo" ] ||
		error "read $MOUNT/$tdir/$tfile failed"
	cleanup_247 $submount
}
run_test 247a "mount subdir as fileset"

test_247b() {
	lctl get_param -n mdc.$FSNAME-MDT0000*.import | grep -q subtree ||
		skip_env "Fileset feature is not supported"

	local submount=${MOUNT}_$tdir

	rm -rf $MOUNT/$tdir
	mkdir -p $submount || error "mkdir $submount failed"
	FILESET="$FILESET/$tdir" mount_client $submount &&
		error "mount $submount should fail"
	rmdir $submount
}
run_test 247b "mount subdir that dose not exist"

test_247c() {
	lctl get_param -n mdc.$FSNAME-MDT0000*.import | grep -q subtree ||
		skip_env "Fileset feature is not supported"

	local submount=${MOUNT}_$tdir

	mkdir -p $MOUNT/$tdir/dir1
	mkdir -p $submount || error "mkdir $submount failed"
	trap "cleanup_247 $submount" EXIT
	FILESET="$FILESET/$tdir" mount_client $submount ||
		error "mount $submount failed"
	local fid=$($LFS path2fid $MOUNT/)
	$LFS fid2path $submount $fid && error "fid2path should fail"
	cleanup_247 $submount
}
run_test 247c "running fid2path outside subdirectory root"

test_247d() {
	lctl get_param -n mdc.$FSNAME-MDT0000*.import | grep -q subtree ||
		skip "Fileset feature is not supported"

	local submount=${MOUNT}_$tdir

	mkdir -p $MOUNT/$tdir/dir1
	mkdir -p $submount || error "mkdir $submount failed"
	FILESET="$FILESET/$tdir" mount_client $submount ||
		error "mount $submount failed"
	trap "cleanup_247 $submount" EXIT

	local td=$submount/dir1
	local fid=$($LFS path2fid $td)
	[ -z "$fid" ] && error "path2fid unable to get $td FID"

	# check that we get the same pathname back
	local rootpath
	local found
	for rootpath in "$submount" "$submount///" "$submount/dir1"; do
		echo "$rootpath $fid"
		found=$($LFS fid2path $rootpath "$fid")
		[ -n "$found" ] || error "fid2path should succeed"
		[ "$found" == "$td" ] || error "fid2path $found != $td"
	done
	# check wrong root path format
	rootpath=$submount"_wrong"
	found=$($LFS fid2path $rootpath "$fid")
	[ -z "$found" ] || error "fid2path should fail ($rootpath != $submount)"

	cleanup_247 $submount
}
run_test 247d "running fid2path inside subdirectory root"

# LU-8037
test_247e() {
	lctl get_param -n mdc.$FSNAME-MDT0000*.import |
		grep -q subtree ||
		skip "Fileset feature is not supported"

	local submount=${MOUNT}_$tdir

	mkdir $MOUNT/$tdir
	mkdir -p $submount || error "mkdir $submount failed"
	FILESET="$FILESET/.." mount_client $submount &&
		error "mount $submount should fail"
	rmdir $submount
}
run_test 247e "mount .. as fileset"

test_247f() {
	(( $MDSCOUNT > 1 )) || skip_env "needs >= 2 MDTs"
	(( $MDS1_VERSION >= $(version_code 2.14.50.162) )) ||
		skip "Need at least version 2.14.50.162"
	lctl get_param -n mdc.$FSNAME-MDT0000*.import | grep -q subtree ||
		skip "Fileset feature is not supported"

	mkdir_on_mdt0 $DIR/$tdir || error "mkdir $tdir failed"
	$LFS mkdir -i $((MDSCOUNT - 1)) $DIR/$tdir/remote ||
		error "mkdir remote failed"
	$LFS mkdir -i $((MDSCOUNT - 1)) $DIR/$tdir/remote/subdir ||
		error "mkdir remote/subdir failed"
	$LFS mkdir -i 0 -c $MDSCOUNT $DIR/$tdir/striped ||
		error "mkdir striped failed"
	mkdir $DIR/$tdir/striped/subdir || error "mkdir striped/subdir failed"

	local submount=${MOUNT}_$tdir

	mkdir -p $submount || error "mkdir $submount failed"
	stack_trap "rmdir $submount"

	local dir
	local fileset=$FILESET
	local mdts=$(mdts_nodes)

	do_nodes $mdts "$LCTL set_param mdt.*.enable_remote_subdir_mount=1"
	for dir in $tdir/remote $tdir/remote/subdir $tdir/striped \
		$tdir/striped/subdir $tdir/striped/.; do
		FILESET="$fileset/$dir" mount_client $submount ||
			error "mount $dir failed"
		umount_client $submount
	done
}
run_test 247f "mount striped or remote directory as fileset"

test_subdir_mount_lock()
{
	local testdir=$1
	local submount=${MOUNT}_$(basename $testdir)

	touch $DIR/$testdir/$tfile || error "touch $tfile failed"

	mkdir -p $submount || error "mkdir $submount failed"
	stack_trap "rmdir $submount"

	FILESET="$FILESET/$testdir" mount_client $submount ||
		error "mount $FILESET failed"
	stack_trap "umount $submount"

	local mdts=$(mdts_nodes)

	local nrpcs

	stat $submount > /dev/null || error "stat $submount failed"
	cancel_lru_locks $MDC
	stat $submount > /dev/null || error "stat $submount failed"
	stat $submount/$tfile > /dev/null || error "stat $tfile failed"
	do_nodes $mdts "$LCTL set_param mdt.*.md_stats=clear > /dev/null"
	stat $submount/$tfile > /dev/null || error "stat $tfile failed"
	nrpcs=$(do_nodes $mdts "lctl get_param -n mdt.*.md_stats" |
		awk '/getattr/ {sum += $2} END {print sum}')

	[ -z "$nrpcs" ] || error "$nrpcs extra getattr sent"
}

test_247g() {
	(( $MDSCOUNT > 1 )) || skip_env "needs > 1 MDTs"

	$LFS mkdir -i 0 -c 4 -H fnv_1a_64 $DIR/$tdir ||
		error "mkdir $tdir failed"
	test_subdir_mount_lock $tdir
}
run_test 247g "striped directory submount revalidate ROOT from cache"

test_247h() {
	(( $MDSCOUNT > 1 )) || skip_env "needs > 1 MDTs"
	(( $MDS1_VERSION >= $(version_code 2.15.51) )) ||
		skip "Need MDS version at least 2.15.51"

	$LFS mkdir -i 1 -c $MDSCOUNT $DIR/$tdir || error "mkdir $tdir failed"
	test_subdir_mount_lock $tdir
	mkdir_on_mdt -i 0 $DIR/$tdir/$tdir.0 || error "mkdir $tdir.0 failed"
	mkdir_on_mdt -i 1 $DIR/$tdir/$tdir.0/$tdir.1 ||
		error "mkdir $tdir.1 failed"
	test_subdir_mount_lock $tdir/$tdir.0/$tdir.1
}
run_test 247h "remote directory submount revalidate ROOT from cache"

test_248a() {
	local fast_read_sav=$($LCTL get_param -n llite.*.fast_read 2>/dev/null)
	[ -z "$fast_read_sav" ] && skip "no fast read support"

	# create a large file for fast read verification
	dd if=/dev/zero of=$DIR/$tfile bs=1M count=128 > /dev/null 2>&1

	# make sure the file is created correctly
	$CHECKSTAT -s $((128*1024*1024)) $DIR/$tfile ||
		{ rm -f $DIR/$tfile; skip "file creation error"; }

	echo "Test 1: verify that fast read is 4 times faster on cache read"

	# small read with fast read enabled
	$LCTL set_param -n llite.*.fast_read=1
	local t_fast=$(dd if=$DIR/$tfile of=/dev/null bs=4k 2>&1 |
		grep -E -o '([[:digit:]\.\,e-]+) s' | cut -d's' -f1 |
		sed -e 's/,/./' -e 's/[eE]+*/\*10\^/')
	# small read with fast read disabled
	$LCTL set_param -n llite.*.fast_read=0
	local t_slow=$(dd if=$DIR/$tfile of=/dev/null bs=4k 2>&1 |
		grep -E -o '([[:digit:]\.\,e-]+) s' | cut -d's' -f1 |
		sed -e 's/,/./' -e 's/[eE]+*/\*10\^/')

	# verify that fast read is 4 times faster for cache read
	[ $(bc <<< "4 * $t_fast < $t_slow") -eq 1 ] ||
		error_not_in_vm "fast read was not 4 times faster: " \
			   "$t_fast vs $t_slow"

	echo "Test 2: verify the performance between big and small read"
	$LCTL set_param -n llite.*.fast_read=1

	# 1k non-cache read
	cancel_lru_locks osc
	local t_1k=$(dd if=$DIR/$tfile of=/dev/null bs=1k 2>&1 |
		grep -E -o '([[:digit:]\.\,e-]+) s' | cut -d's' -f1 |
		sed -e 's/,/./' -e 's/[eE]+*/\*10\^/')

	# 1M non-cache read
	cancel_lru_locks osc
	local t_1m=$(dd if=$DIR/$tfile of=/dev/null bs=1k 2>&1 |
		grep -E -o '([[:digit:]\.\,e-]+) s' | cut -d's' -f1 |
		sed -e 's/,/./' -e 's/[eE]+*/\*10\^/')

	# verify that big IO is not 4 times faster than small IO
	[ $(bc <<< "4 * $t_1k >= $t_1m") -eq 1 ] ||
		error_not_in_vm "bigger IO is way too fast: $t_1k vs $t_1m"

	$LCTL set_param -n llite.*.fast_read=$fast_read_sav
	rm -f $DIR/$tfile
}
run_test 248a "fast read verification"

test_248b() {
	# Default short_io_bytes=16384, try both smaller and larger sizes.
	# Lustre O_DIRECT read and write needs to be a multiple of PAGE_SIZE.
	# 6017024 = 2^12*13*113 = 47008*128 = 11752*512 = 4096*1469 = 53248*113
	echo "bs=53248 count=113 normal buffered write"
	dd if=/dev/urandom of=$TMP/$tfile.0 bs=53248 count=113 ||
		error "dd of initial data file failed"
	stack_trap "rm -f $DIR/$tfile.[0-3] $TMP/$tfile.[0-3]" EXIT

	echo "bs=47008 count=128 oflag=dsync normal write $tfile.0"
	dd if=$TMP/$tfile.0 of=$DIR/$tfile.0 bs=47008 count=128 oflag=dsync ||
		error "dd with sync normal writes failed"
	cmp $TMP/$tfile.0 $DIR/$tfile.0 || error "compare $DIR/$tfile.0 failed"

	echo "bs=11752 count=512 oflag=dsync small write $tfile.1"
	dd if=$TMP/$tfile.0 of=$DIR/$tfile.1 bs=11752 count=512 oflag=dsync ||
		error "dd with sync small writes failed"
	cmp $TMP/$tfile.0 $DIR/$tfile.1 || error "compare $DIR/$tfile.1 failed"

	cancel_lru_locks osc

	# calculate the small O_DIRECT size and count for the client PAGE_SIZE
	local num=$((13 * 113 / (PAGE_SIZE / 4096)))
	echo "bs=$PAGE_SIZE count=$num iflag=direct small read $tfile.1"
	dd if=$DIR/$tfile.1 of=$TMP/$tfile.1 bs=$PAGE_SIZE count=$num \
		iflag=direct || error "dd with O_DIRECT small read failed"
	# adjust bytes checked to handle larger PAGE_SIZE for ARM/PPC
	cmp --bytes=$((PAGE_SIZE * num)) $TMP/$tfile.0 $TMP/$tfile.1 ||
		error "compare $TMP/$tfile.1 failed"

	local save=$($LCTL get_param -n osc.*OST000*.short_io_bytes | head -n 1)
	stack_trap "$LCTL set_param osc.$FSNAME-*.short_io_bytes=$save" EXIT

	# just to see what the maximum tunable value is, and test parsing
	echo "test invalid parameter 2MB"
	$LCTL set_param osc.$FSNAME-OST0000*.short_io_bytes=2M &&
		error "too-large short_io_bytes allowed"
	echo "test maximum parameter 512KB"
	# if we can set a larger short_io_bytes, run test regardless of version
	if ! $LCTL set_param osc.$FSNAME-OST0000*.short_io_bytes=512K; then
		# older clients may not allow setting it this large, that's OK
		[ $CLIENT_VERSION -ge $(version_code 2.13.50) ] ||
			skip "Need at least client version 2.13.50"
		error "medium short_io_bytes failed"
	fi
	$LCTL get_param osc.$FSNAME-OST0000*.short_io_bytes
	size=$($LCTL get_param -n osc.$FSNAME-OST0000*.short_io_bytes)

	echo "test large parameter 64KB"
	$LCTL set_param osc.$FSNAME-*.short_io_bytes=65536
	$LCTL get_param osc.$FSNAME-OST0000*.short_io_bytes

	echo "bs=47008 count=128 oflag=dsync large write $tfile.2"
	dd if=$TMP/$tfile.0 of=$DIR/$tfile.2 bs=47008 count=128 oflag=dsync ||
		error "dd with sync large writes failed"
	cmp $TMP/$tfile.0 $DIR/$tfile.2 || error "compare $DIR/$tfile.2 failed"

	# calculate the large O_DIRECT size and count for the client PAGE_SIZE
	local size=$(((4096 * 13 + PAGE_SIZE - 1) / PAGE_SIZE * PAGE_SIZE))
	num=$((113 * 4096 / PAGE_SIZE))
	echo "bs=$size count=$num oflag=direct large write $tfile.3"
	dd if=$TMP/$tfile.0 of=$DIR/$tfile.3 bs=$size count=$num oflag=direct ||
		error "dd with O_DIRECT large writes failed"
	cmp --bytes=$((size * num)) $TMP/$tfile.0 $DIR/$tfile.3 ||
		error "compare $DIR/$tfile.3 failed"

	cancel_lru_locks osc

	echo "bs=$size count=$num iflag=direct large read $tfile.2"
	dd if=$DIR/$tfile.2 of=$TMP/$tfile.2 bs=$size count=$num iflag=direct ||
		error "dd with O_DIRECT large read failed"
	cmp --bytes=$((size * num)) $TMP/$tfile.0 $TMP/$tfile.2 ||
		error "compare $TMP/$tfile.2 failed"

	echo "bs=$size count=$num iflag=direct large read $tfile.3"
	dd if=$DIR/$tfile.3 of=$TMP/$tfile.3 bs=$size count=$num iflag=direct ||
		error "dd with O_DIRECT large read failed"
	cmp --bytes=$((size * num)) $TMP/$tfile.0 $TMP/$tfile.3 ||
		error "compare $TMP/$tfile.3 failed"
}
run_test 248b "test short_io read and write for both small and large sizes"

test_248c() {
	$LCTL set_param llite.*.read_ahead_stats=c
	# This test compares whole file readahead to non-whole file readahead
	# The performance should be consistently slightly faster for whole file,
	# and the bug caused whole file readahead to be 80-100x slower, but to
	# account for possible test system lag, we require whole file to be
	# <= 1.5xnon-whole file, and require 3 failures in a row to fail the
	# test
	local time1
	local time2
	local counter
	local whole_mb=$($LCTL get_param -n llite.*.max_read_ahead_whole_mb)
	stack_trap "$LCTL set_param llite.*.max_read_ahead_whole_mb=$whole_mb"

	# LU-16904 Use stripe counct 1 for root before the readahead issue
	# described in LU-17755 and LU-15155 get fixed
	test_mkdir $DIR/$tdir || error "mkdir $tdir failed"
	$LFS setstripe -c 1 $DIR/$tdir || error "setstripe $tdir failed"

	for (( counter = 0; counter < 3; counter++ )); do
		$LCTL set_param llite.*.max_read_ahead_whole_mb=64
		rm -f $DIR/$tdir/$tfile
		touch $DIR/$tdir/$tfile || error "(0) failed to create file"
		# 64 MiB
		$TRUNCATE $DIR/$tdir/$tfile 67108864 || error "(1) trunc failed"
		time1=$(dd if=$DIR/$tdir/$tfile bs=4K of=/dev/null 2>&1 |
			awk '/bytes/ { print $8 }')
		echo "whole file readahead of 64 MiB took $time1 seconds"
		$LCTL get_param llite.*.read_ahead_stats

		$LCTL set_param llite.*.read_ahead_stats=clear
		$LCTL set_param llite.*.max_read_ahead_whole_mb=8
		rm -f $DIR/$tdir/$tfile
		touch $DIR/$tdir/$tfile || error "(2) failed to create file"
		# 64 MiB
		$TRUNCATE $DIR/$tdir/$tfile 67108864 || error "(3) trunc failed"
		time2=$(dd if=$DIR/$tdir/$tfile bs=4K of=/dev/null 2>&1 |
			awk '/bytes/ { print $8 }')
		echo "non-whole file readahead of 64 MiB took $time2 seconds"
		$LCTL get_param llite.*.read_ahead_stats

		# Check if time1 is not more than 1.5 times2
		timecheck=$(echo "$time1 <= (1.5 * $time2)" | bc -l)

		if (( $timecheck == 1 )); then
			echo "Test passed on attempt $counter"
			break
		fi
		echo "Try $counter failed: whole file readahead took: $time1, greater than non: $time2"
	done
	(( $counter < 3 )) ||
		error "whole file readahead failed 3x, probably not just VM lag"
}
run_test 248c "verify whole file read behavior"

test_248d() {
	local fast_read_sav=$($LCTL get_param -n llite.*.fast_read 2>/dev/null)

	[ -z "$fast_read_sav" ] && skip "no fast read support"
	stack_trap "$LCTL set_param -n llite.*.fast_read=$fast_read_sav"

	# Create a small file and warm the page cache
	dd if=/dev/urandom of=$DIR/$tfile bs=32K count=1 2>/dev/null ||
		error "dd write failed"
	stack_trap "rm -f $DIR/$tfile"

	# Warm page cache with a full read
	$LCTL set_param -n llite.*.fast_read=1
	dd if=$DIR/$tfile of=/dev/null bs=32K 2>/dev/null ||
		error "dd warmup read failed"

	# Clear stats and do a burst of small reads from cache
	$LCTL set_param llite.*.read_ahead_stats=0
	dd if=$DIR/$tfile of=/dev/null bs=8 count=4000 2>/dev/null ||
		error "dd tiny read failed"

	local failed=$($LCTL get_param -n llite.*.read_ahead_stats |
		awk '/failed_to_fast_read/ { print $1 }')

	# All reads from a warm cache should use fast read without
	# any failures.  A non-zero count means pages were not
	# served from cache, indicating the fast read path is
	# broken or being bypassed.
	[[ ${failed:-0} -eq 0 ]] ||
		error "expected 0 failed_to_fast_read, got $failed"
}
run_test 248d "fast read serves tiny reads from cache without failures"

test_249() { # LU-7890
	[ $MDS1_VERSION -lt $(version_code 2.8.53) ] &&
		skip "Need at least version 2.8.54"

	rm -f $DIR/$tfile
	$LFS setstripe -c 1 $DIR/$tfile
	# Offset 2T == 4k * 512M
	dd if=/dev/zero of=$DIR/$tfile bs=4k count=1 seek=512M ||
		error "dd to 2T offset failed"
}
run_test 249 "Write above 2T file size"

test_250() {
	[ "$(facet_fstype ost$(($($LFS getstripe -i $DIR/$tfile) + 1)))" = "zfs" ] \
	 && skip "no 16TB file size limit on ZFS"

	[ "$(facet_fstype ost$(($($LFS getstripe -i $DIR/$tfile) + 1)))" = "wbcfs" ] \
	 && skip "no 16TB file size limit on wbcfs"

	$LFS setstripe -c 1 $DIR/$tfile
	# ldiskfs extent file size limit is (16TB - 4KB - 1) bytes
	local size=$((16 * 1024 * 1024 * 1024 * 1024 - 4096 - 1))
	$TRUNCATE $DIR/$tfile $size || error "truncate $tfile to $size failed"
	dd if=/dev/zero of=$DIR/$tfile bs=10 count=1 oflag=append \
		conv=notrunc,fsync && error "append succeeded"
	return 0
}
run_test 250 "Write above 16T limit"

test_251a() {
	$LFS setstripe -c -1 -S 1048576 $DIR/$tfile

	#define OBD_FAIL_LLITE_LOST_LAYOUT 0x1407
	#Skip once - writing the first stripe will succeed
	$LCTL set_param fail_loc=0xa0001407 fail_val=1
	$MULTIOP $DIR/$tfile o:O_RDWR:w2097152c 2>&1 | grep -q "short write" &&
		error "short write happened"

	$LCTL set_param fail_loc=0xa0001407 fail_val=1
	$MULTIOP $DIR/$tfile or2097152c 2>&1 | grep -q "short read" &&
		error "short read happened"

	rm -f $DIR/$tfile
}
run_test 251a "Handling short read and write correctly"

test_252() {
	remote_mds_nodsh && skip "remote MDS with nodsh"
	remote_ost_nodsh && skip "remote OST with nodsh"
	if [ "$ost1_FSTYPE" != ldiskfs ] || [ "$mds1_FSTYPE" != ldiskfs ]; then
		skip_env "ldiskfs only test"
	fi

	local tgt
	local dev
	local out
	local uuid
	local num
	local gen

	# check lr_reader on OST0000
	tgt=ost1
	dev=$(facet_device $tgt)
	out=$(do_facet $tgt $LR_READER $dev)
	[ $? -eq 0 ] || error "$LR_READER failed on target $tgt device $dev"
	echo "$out"
	uuid=$(echo "$out" | grep -i uuid | awk '{ print $2 }')
	[ "$uuid" == "$(ostuuid_from_index 0)" ] ||
		error "Invalid uuid returned by $LR_READER on target $tgt"
	echo -e "uuid returned by $LR_READER is '$uuid'\n"

	# check lr_reader -c on MDT0000
	tgt=mds1
	dev=$(facet_device $tgt)
	if ! do_facet $tgt $LR_READER -h | grep -q OPTIONS; then
		skip "$LR_READER does not support additional options"
	fi
	out=$(do_facet $tgt $LR_READER -c $dev)
	[ $? -eq 0 ] || error "$LR_READER failed on target $tgt device $dev"
	echo "$out"
	num=$(echo "$out" | grep -c "mdtlov")
	[ "$num" -eq $((MDSCOUNT - 1)) ] ||
		error "Invalid number of mdtlov clients returned by $LR_READER"
	echo -e "Number of mdtlov clients returned by $LR_READER is '$num'\n"

	# check lr_reader -cr on MDT0000
	out=$(do_facet $tgt $LR_READER -cr $dev)
	[ $? -eq 0 ] || error "$LR_READER failed on target $tgt device $dev"
	echo "$out"
	echo "$out" | grep -q "^reply_data:$" ||
		error "$LR_READER should have returned 'reply_data' section"
	num=$(echo "$out" | grep -c "client_generation")
	echo -e "Number of reply data returned by $LR_READER is '$num'\n"
}
run_test 252 "check lr_reader tool"

test_253() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	remote_mgs_nodsh && skip "remote MGS with nodsh"
	check_set_fallocate_or_skip

	local ostidx=0
	local rc=0
	local ost_name=$(ostname_from_index $ostidx)

	# on the mdt's osc
	local mdtosc_proc1=$(get_mdtosc_proc_path $SINGLEMDS $ost_name)
	do_facet $SINGLEMDS $LCTL get_param -n \
		osp.$mdtosc_proc1.reserved_mb_high ||
		skip  "remote MDS does not support reserved_mb_high"

	rm -rf $DIR/$tdir
	wait_mds_ost_sync
	wait_delete_completed
	mkdir $DIR/$tdir
	stack_trap "rm -rf $DIR/$tdir"

	pool_add $TESTNAME || error "Pool creation failed"
	pool_add_targets $TESTNAME 0 || error "Pool add targets failed"

	$LFS setstripe $DIR/$tdir -i $ostidx -c 1 -p $FSNAME.$TESTNAME ||
		error "Setstripe failed"

	dd if=/dev/zero of=$DIR/$tdir/$tfile.0 bs=1M count=10

	local wms=$(ost_watermarks_get $ostidx)

	ost_watermarks_set $ostidx 60 50
	stack_trap "ost_watermarks_set $ostidx $wms"

	local free_kb=$($LFS df $MOUNT | awk "/$ost_name/ { print \$4 }")
	local size=$((free_kb * 1024))

	fallocate -l $size $DIR/$tdir/fill_ost$ostidx ||
		error "fallocate failed"
	sleep_maxage

	local oa_status=$(do_facet $SINGLEMDS $LCTL get_param -n \
			osp.$mdtosc_proc1.prealloc_status)
	echo "prealloc_status $oa_status"

	dd if=/dev/zero of=$DIR/$tdir/$tfile.1 bs=1M count=1 &&
		error "File creation should fail"

	#object allocation was stopped, but we still able to append files
	dd if=/dev/zero of=$DIR/$tdir/$tfile.0 bs=1M seek=6 count=5 \
		oflag=append || error "Append failed"

	rm -f $DIR/$tdir/$tfile.0
	rm -f $DIR/$tdir/fill_ost$ostidx

	wait_delete_completed
	sleep_maxage

	for i in $(seq 10 12); do
		dd if=/dev/zero of=$DIR/$tdir/$tfile.$i bs=1M count=1 \
			2>/dev/null || error "File creation failed after rm"
	done

	oa_status=$(do_facet $SINGLEMDS $LCTL get_param -n \
			osp.$mdtosc_proc1.prealloc_status)
	echo "prealloc_status $oa_status"

	if (( oa_status != 0 )); then
		error "Object allocation still disable after rm"
	fi
}
run_test 253 "Check object allocation limit"

test_254() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"

	local mdt=$(facet_svc $SINGLEMDS)

	do_facet $SINGLEMDS $LCTL get_param -n mdd.$mdt.changelog_size ||
		skip "MDS does not support changelog_size"

	local cl_user

	changelog_register || error "changelog_register failed"

	changelog_clear 0 || error "changelog_clear failed"

	local size1=$(do_facet $SINGLEMDS \
		      $LCTL get_param -n mdd.$mdt.changelog_size)
	echo "Changelog size $size1"

	rm -rf $DIR/$tdir
	$LFS mkdir -i 0 $DIR/$tdir
	# change something
	mkdir -p $DIR/$tdir/pics/2008/zachy
	touch $DIR/$tdir/pics/2008/zachy/timestamp
	cp /etc/hosts $DIR/$tdir/pics/2008/zachy/pic1.jpg
	mv $DIR/$tdir/pics/2008/zachy $DIR/$tdir/pics/zach
	ln $DIR/$tdir/pics/zach/pic1.jpg $DIR/$tdir/pics/2008/portland.jpg
	ln -s $DIR/$tdir/pics/2008/portland.jpg $DIR/$tdir/pics/desktop.jpg
	rm $DIR/$tdir/pics/desktop.jpg

	local size2=$(do_facet $SINGLEMDS \
		      $LCTL get_param -n mdd.$mdt.changelog_size)
	echo "Changelog size after work $size2"

	(( $size2 > $size1 )) ||
		error "new Changelog size=$size2 less than old size=$size1"
}
run_test 254 "Check changelog size"

ladvise_no_type()
{
	local type=$1
	local file=$2

	lfs ladvise -a invalid $file 2>&1 | grep "Valid types" |
		awk -F: '{print $2}' | grep $type > /dev/null
	if [ $? -ne 0 ]; then
		return 0
	fi
	return 1
}

ladvise_no_ioctl()
{
	local file=$1

	lfs ladvise -a willread $file > /dev/null 2>&1
	if [ $? -eq 0 ]; then
		return 1
	fi

	lfs ladvise -a willread $file 2>&1 |
		grep "Inappropriate ioctl for device" > /dev/null
	if [ $? -eq 0 ]; then
		return 0
	fi
	return 1
}

percent() {
	# don't print any decimal places to avoid bash comparison issues
	bc <<< "scale=0; ($1 - $2) * 100 / $2"
}

# run a random read IO workload
# usage: random_read_iops <filename> <filesize> <iosize>
random_read_iops() {
	local file=$1
	local fsize=$2
	local iosize=${3:-4096}

	$READS -f $file -s $fsize -b $iosize -n $((fsize / iosize)) -t 60 |
		sed -e '/^$/d' -e 's#.*s, ##' -e 's#MB/s##'
}

drop_file_oss_cache() {
	local file="$1"
	local nodes="$2"

	$LFS ladvise -a dontneed $file 2>/dev/null ||
		do_nodes $nodes "echo 3 > /proc/sys/vm/drop_caches"
}

ladvise_willread_performance()
{
	local repeat=10
	local average_origin=0
	local average_cache=0
	local average_ladvise=0
	local osts=$(osts_nodes)

	# Hybrid IO switches to DIO, which invalidates much of the caching
	# So disable it for this test
	local hybrid=$($LCTL get_param -n llite.*.hybrid_io)
	$LCTL set_param llite.*.hybrid_io=0
	stack_trap "$LCTL set_param -n llite.*.hybrid_io=$hybrid" EXIT

	for ((i = 1; i <= $repeat; i++)); do
		echo "Iter $i/$repeat: reading without willread hint"
		cancel_lru_locks osc
		drop_file_oss_cache $DIR/$tfile $osts
		local speed_origin=$(random_read_iops $DIR/$tfile $size)
		echo "Iter $i/$repeat: uncached speed: $speed_origin"
		average_origin=$(bc <<<"$average_origin + $speed_origin")

		cancel_lru_locks osc
		local speed_cache=$(random_read_iops $DIR/$tfile $size)
		echo "Iter $i/$repeat: OSS cache speed: $speed_cache"
		average_cache=$(bc <<<"$average_cache + $speed_cache")

		cancel_lru_locks osc
		drop_file_oss_cache $DIR/$tfile $osts
		$LFS ladvise -a willread $DIR/$tfile || error "ladvise failed"
		local speed_ladvise=$(random_read_iops $DIR/$tfile $size)
		echo "Iter $i/$repeat: ladvise speed: $speed_ladvise"
		average_ladvise=$(bc <<<"$average_ladvise + $speed_ladvise")
	done
	average_origin=$(bc <<<"scale=2; $average_origin / $repeat")
	average_cache=$(bc <<<"scale=2; $average_cache / $repeat")
	average_ladvise=$(bc <<<"scale=2; $average_ladvise / $repeat")

	speedup_cache=$(percent $average_cache $average_origin)
	speedup_ladvise=$(percent $average_ladvise $average_origin)

	echo "Average uncached read: $average_origin"
	echo "Average speedup with OSS cached read: " \
		"$average_cache = +$speedup_cache%"
	echo "Average speedup with ladvise willread: " \
		"$average_ladvise = +$speedup_ladvise%"

	local lowest_speedup=20
	if (( $speedup_cache < $lowest_speedup )); then
		echo "Speedup with OSS cached read less than $lowest_speedup%,"\
		     " got $speedup_cache%. Skipping ladvise willread check."
		return 0
	fi

	# the test won't work on ZFS until it supports 'ladvise dontneed', but
	# it is still good to run until then to exercise 'ladvise willread'
	! $LFS ladvise -a dontneed $DIR/$tfile &&
		[ "$ost1_FSTYPE" = "zfs" ] &&
		echo "osd-zfs does not support dontneed or drop_caches" &&
		return 0

	lowest_speedup=$(bc <<< "scale=0; $average_cache / 2")
	(( $speedup_ladvise > $lowest_speedup )) ||
		error_not_in_vm "Speedup with willread is less than " \
			"$lowest_speedup%, got $speedup_ladvise%"
}

test_255a() {
	[ $OST1_VERSION -lt $(version_code 2.8.54) ] &&
		skip "lustre < 2.8.54 does not support ladvise "
	remote_ost_nodsh && skip "remote OST with nodsh"

	stack_trap "rm -f $DIR/$tfile"
	lfs setstripe -c -1 -i 0 $DIR/$tfile || error "$tfile failed"

	ladvise_no_type willread $DIR/$tfile &&
		skip "willread ladvise is not supported"

	ladvise_no_ioctl $DIR/$tfile &&
		skip "ladvise ioctl is not supported"

	local size_mb=100
	local size=$((size_mb * 1048576))
	dd if=/dev/zero of=$DIR/$tfile bs=1048576 count=$size_mb ||
		error "dd to $DIR/$tfile failed"

	lfs ladvise -a willread $DIR/$tfile ||
		error "Ladvise failed with no range argument"

	lfs ladvise -a willread -s 0 $DIR/$tfile ||
		error "Ladvise failed with no -l or -e argument"

	lfs ladvise -a willread -e 1 $DIR/$tfile ||
		error "Ladvise failed with only -e argument"

	lfs ladvise -a willread -l 1 $DIR/$tfile ||
		error "Ladvise failed with only -l argument"

	lfs ladvise -a willread -s 2 -e 1 $DIR/$tfile &&
		error "End offset should not be smaller than start offset"

	lfs ladvise -a willread -s 2 -e 2 $DIR/$tfile &&
		error "End offset should not be equal to start offset"

	lfs ladvise -a willread -s $size -l 1 $DIR/$tfile ||
		error "Ladvise failed with overflowing -s argument"

	lfs ladvise -a willread -s 1 -e $((size + 1)) $DIR/$tfile ||
		error "Ladvise failed with overflowing -e argument"

	lfs ladvise -a willread -s 1 -l $size $DIR/$tfile ||
		error "Ladvise failed with overflowing -l argument"

	lfs ladvise -a willread -l 1 -e 2 $DIR/$tfile &&
		error "Ladvise succeeded with conflicting -l and -e arguments"

	echo "Synchronous ladvise should wait"
	local delay=8
	local osts=$(osts_nodes)

	#define OBD_FAIL_OST_LADVISE_PAUSE	 0x237
	do_nodes $osts $LCTL set_param fail_val=$delay fail_loc=0x237
	stack_trap "do_nodes $osts $LCTL set_param fail_loc=0"

	local start_ts=$SECONDS
	lfs ladvise -a willread $DIR/$tfile ||
		error "Ladvise failed with no range argument"
	local end_ts=$SECONDS
	local inteval_ts=$((end_ts - start_ts))

	if [ $inteval_ts -lt $(($delay - 1)) ]; then
		error "Synchronous advice didn't wait reply"
	fi

	echo "Asynchronous ladvise shouldn't wait"
	local start_ts=$SECONDS
	lfs ladvise -a willread -b $DIR/$tfile ||
		error "Ladvise failed with no range argument"
	local end_ts=$SECONDS
	local inteval_ts=$((end_ts - start_ts))

	if [ $inteval_ts -gt $(($delay / 2)) ]; then
		error "Asynchronous advice blocked"
	fi

	ladvise_willread_performance
}
run_test 255a "check 'lfs ladvise -a willread'"

facet_meminfo() {
	local facet=$1
	local info=$2

	do_facet $facet "cat /proc/meminfo | grep ^${info}:" | awk '{print $2}'
}

test_255b() {
	[ $OST1_VERSION -lt $(version_code 2.8.54) ] &&
		skip "lustre < 2.8.54 does not support ladvise "
	remote_ost_nodsh && skip "remote OST with nodsh"

	stack_trap "rm -f $DIR/$tfile"
	lfs setstripe -c 1 -i 0 $DIR/$tfile

	ladvise_no_type dontneed $DIR/$tfile &&
		skip "dontneed ladvise is not supported"

	ladvise_no_ioctl $DIR/$tfile &&
		skip "ladvise ioctl is not supported"

	! $LFS ladvise -a dontneed $DIR/$tfile &&
		[ "$ost1_FSTYPE" = "zfs" ] &&
		skip "zfs-osd does not support 'ladvise dontneed'"

	local size_mb=100
	local size=$((size_mb * 1048576))
	# In order to prevent disturbance of other processes, only check 3/4
	# of the memory usage
	local kibibytes=$((size_mb * 1024 * 3 / 4))

	dd if=/dev/zero of=$DIR/$tfile bs=1048576 count=$size_mb ||
		error "dd to $DIR/$tfile failed"

	#force write to complete before dropping OST cache & checking memory
	sync

	local total=$(facet_meminfo ost1 MemTotal)
	echo "Total memory: $total KiB"

	do_facet ost1 "sync && echo 3 > /proc/sys/vm/drop_caches"
	local before_read=$(facet_meminfo ost1 Cached)
	echo "Cache used before read: $before_read KiB"

	lfs ladvise -a willread $DIR/$tfile ||
		error "Ladvise willread failed"
	local after_read=$(facet_meminfo ost1 Cached)
	echo "Cache used after read: $after_read KiB"

	lfs ladvise -a dontneed $DIR/$tfile ||
		error "Ladvise dontneed again failed"
	local no_read=$(facet_meminfo ost1 Cached)
	echo "Cache used after dontneed ladvise: $no_read KiB"

	if [ $total -lt $((before_read + kibibytes)) ]; then
		echo "Memory is too small, abort checking"
		return 0
	fi

	if [ $((before_read + kibibytes)) -gt $after_read ]; then
		error "Ladvise willread should use more memory" \
			"than $kibibytes KiB"
	fi

	if [ $((no_read + kibibytes)) -gt $after_read ]; then
		error "Ladvise dontneed should release more memory" \
			"than $kibibytes KiB"
	fi
}
run_test 255b "check 'lfs ladvise -a dontneed'"

test_255c() {
	[ $OST1_VERSION -lt $(version_code 2.10.50) ] &&
		skip "lustre < 2.10.50 does not support lockahead"

	local ost1_imp=$(get_osc_import_name client ost1)
	local imp_name=$($LCTL list_param osc.$ost1_imp | head -n1 |
			 cut -d'.' -f2)
	local count
	local new_count
	local difference
	local i
	local rc

	test_mkdir -p $DIR/$tdir
	$LFS setstripe -i 0 -c 1 $DIR/$tdir

	#test 10 returns only success/failure
	i=10
	lockahead_test -d $DIR/$tdir -t $i -f $tfile
	rc=$?
	if [ $rc -eq 255 ]; then
		error "Ladvise test${i} failed, ${rc}"
	fi

	#test 11 counts lock enqueue requests, all others count new locks
	i=11
	count=$(do_facet ost1 \
		$LCTL get_param -n ost.OSS.ost.stats)
	count=$(echo "$count" | grep ldlm_extent_enqueue | awk '{ print $2 }')

	lockahead_test -d $DIR/$tdir -t $i -f $tfile
	rc=$?
	if [ $rc -eq 255 ]; then
		error "Ladvise test${i} failed, ${rc}"
	fi

	new_count=$(do_facet ost1 \
		$LCTL get_param -n ost.OSS.ost.stats)
	new_count=$(echo "$new_count" | grep ldlm_extent_enqueue | \
		   awk '{ print $2 }')

	difference="$((new_count - count))"
	if [ $difference -ne $rc ]; then
		error "Ladvise test${i}, bad enqueue count, returned " \
		      "${rc}, actual ${difference}"
	fi

	for i in $(seq 12 21); do
		# If we do not do this, we run the risk of having too many
		# locks and starting lock cancellation while we are checking
		# lock counts.
		cancel_lru_locks osc

		count=$($LCTL get_param -n \
		       ldlm.namespaces.$imp_name.lock_unused_count)

		lockahead_test -d $DIR/$tdir -t $i -f $tfile
		rc=$?
		if [ $rc -eq 255 ]; then
			error "Ladvise test ${i} failed, ${rc}"
		fi

		new_count=$($LCTL get_param -n \
		       ldlm.namespaces.$imp_name.lock_unused_count)
		difference="$((new_count - count))"

		# Test 15 output is divided by 100 to map down to valid return
		if [ $i -eq 15 ]; then
			rc="$((rc * 100))"
		fi

		if [ $difference -ne $rc ]; then
			error "Ladvise test ${i}, bad lock count, returned " \
			      "${rc}, actual ${difference}"
		fi
	done

	#test 22 returns only success/failure
	i=22
	lockahead_test -d $DIR/$tdir -t $i -f $tfile
	rc=$?
	if [ $rc -eq 255 ]; then
		error "Ladvise test${i} failed, ${rc}"
	fi
}
run_test 255c "suite of ladvise lockahead tests"

test_256() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"
	[ "$mds1_FSTYPE" != "ldiskfs" ] && skip "ldiskfs only test"
	changelog_users $SINGLEMDS | grep "^cl" &&
		skip "active changelog user"

	local cl_user
	local cat_sl
	local mdt_dev

	mdt_dev=$(facet_device $SINGLEMDS)
	echo $mdt_dev

	changelog_register || error "changelog_register failed"

	rm -rf $DIR/$tdir
	mkdir_on_mdt -i$(($(facet_number $SINGLEMDS) - 1)) $DIR/$tdir

	changelog_clear 0 || error "changelog_clear failed"

	# change something
	touch $DIR/$tdir/{1..10}

	# stop the MDT
	stop $SINGLEMDS || error "Fail to stop MDT"

	# remount the MDT
	start $SINGLEMDS $(facet_device $SINGLEMDS) $MDS_MOUNT_OPTS ||
		error "Fail to start MDT"

	#after mount new plainllog is used
	touch $DIR/$tdir/{11..19}
	local tmpfile="$(mktemp --tmpdir -u $tfile.XXXXXX)"
	stack_trap "rm -f $tmpfile"
	cat_sl=$(do_facet $SINGLEMDS "sync; \
		 $DEBUGFS -c -R 'dump changelog_catalog $tmpfile' $mdt_dev; \
		 llog_reader $tmpfile | grep -c type=1064553b")
	do_facet $SINGLEMDS llog_reader $tmpfile

	[ $cat_sl != 2 ] && error "Changelog catalog has $cat_sl != 2 slots"

	changelog_clear 0 || error "changelog_clear failed"

	cat_sl=$(do_facet $SINGLEMDS "sync; \
		 $DEBUGFS -c -R 'dump changelog_catalog $tmpfile' $mdt_dev; \
		 llog_reader $tmpfile | grep -c type=1064553b")

	if (( cat_sl == 2 )); then
		error "Empty plain llog was not deleted from changelog catalog"
	elif (( cat_sl != 1 )); then
		error "Active plain llog shouldn't be deleted from catalog"
	fi
}
run_test 256 "Check llog delete for empty and not full state"

test_257() {
	remote_mds_nodsh && skip "remote MDS with nodsh"
	[[ $MDS1_VERSION -lt $(version_code 2.8.55) ]] &&
		skip "Need MDS version at least 2.8.55"

	test_mkdir $DIR/$tdir

	setfattr -n trusted.name1 -v value1 $DIR/$tdir ||
		error "setfattr -n trusted.name1=value1 $DIR/$tdir failed"
	stat $DIR/$tdir

#define OBD_FAIL_MDS_XATTR_REP			0x161
	local mdtidx=$($LFS getstripe -m $DIR/$tdir)
	local facet=mds$((mdtidx + 1))
	set_nodes_failloc $(facet_active_host $facet) 0x80000161
	getfattr -n trusted.name1 $DIR/$tdir 2> /dev/null

	stop $facet || error "stop MDS failed"
	start $facet $(mdsdevname $((mdtidx + 1))) $MDS_MOUNT_OPTS ||
		error "start MDS fail"
	wait_recovery_complete $facet
}
run_test 257 "xattr locks are not lost"

# Verify we take the i_mutex when security requires it
test_258a() {
#define OBD_FAIL_IMUTEX_SEC 0x141c
	$LCTL set_param fail_loc=0x141c
	touch $DIR/$tfile
	chmod u+s $DIR/$tfile
	chmod a+rwx $DIR/$tfile
	$RUNAS dd if=/dev/zero of=$DIR/$tfile bs=4k count=1 oflag=append
	RC=$?
	if [ $RC -ne 0 ]; then
		error "error, failed to take i_mutex, rc=$?"
	fi
	rm -f $DIR/$tfile
}
run_test 258a "verify i_mutex security behavior when suid attributes is set"

# Verify we do NOT take the i_mutex in the normal case
test_258b() {
#define OBD_FAIL_IMUTEX_NOSEC 0x141d
	$LCTL set_param fail_loc=0x141d
	touch $DIR/$tfile
	chmod a+rwx $DIR
	chmod a+rw $DIR/$tfile
	$RUNAS dd if=/dev/zero of=$DIR/$tfile bs=4k count=1 oflag=append
	RC=$?
	if [ $RC -ne 0 ]; then
		error "error, took i_mutex unnecessarily, rc=$?"
	fi
	rm -f $DIR/$tfile

}
run_test 258b "verify i_mutex security behavior"

test_259() {
	local file=$DIR/$tfile
	local before
	local after

	[ "$mds1_FSTYPE" != "ldiskfs" ] && skip "ldiskfs only test"

	stack_trap "rm -f $file" EXIT

	wait_delete_completed
	before=$(do_facet ost1 "$LCTL get_param -n osd-*.*OST0000.kbytesfree")
	echo "before: $before"

	$LFS setstripe -i 0 -c 1 $file
	dd if=/dev/zero of=$file bs=1M count=10 || error "couldn't write"
	sync_all_data
	after=$(do_facet ost1 "$LCTL get_param -n osd-*.*OST0000.kbytesfree")
	echo "after write: $after"

#define OBD_FAIL_OSD_FAIL_AT_TRUNCATE          0x2301
	do_facet ost1 $LCTL set_param fail_loc=0x2301
	$TRUNCATE $file 0
	after=$(do_facet ost1 "$LCTL get_param -n osd-*.*OST0000.kbytesfree")
	echo "after truncate: $after"

	stop ost1
	do_facet ost1 $LCTL set_param fail_loc=0
	start ost1 $(ostdevname 1) $OST_MOUNT_OPTS || error "cannot start ost1"
	sleep 2
	after=$(do_facet ost1 "$LCTL get_param -n osd-*.*OST0000.kbytesfree")
	echo "after restart: $after"
	[ $((after - before)) -ge $(fs_log_size ost1) ] &&
		error "missing truncate?"

	return 0
}
run_test 259 "crash at delayed truncate"

test_260() {
#define OBD_FAIL_MDC_CLOSE               0x806
	$LCTL set_param fail_loc=0x80000806
	touch $DIR/$tfile

}
run_test 260 "Check mdc_close fail"

### Data-on-MDT sanity tests ###
test_270a() {
	[ $MDS1_VERSION -lt $(version_code 2.10.55) ] &&
		skip "Need MDS version at least 2.10.55 for DoM"

	# create DoM file
	local dom=$DIR/$tdir/dom_file
	local tmp=$DIR/$tdir/tmp_file

	mkdir_on_mdt0 $DIR/$tdir

	# basic checks for DoM component creation
	$LFS setstripe -E 1024K -E 2048K -L mdt $dom 2>/dev/null &&
		error "Can set MDT layout to non-first entry"

	$LFS setstripe -E 1024K -L mdt -E 2048K -L mdt $dom 2>/dev/null &&
		error "Can define multiple entries as MDT layout"

	$LFS setstripe -E 1M -L mdt $dom || error "Can't create DoM layout"

	[ $($LFS getstripe -L $dom) == "mdt" ] || error "bad pattern"
	[ $($LFS getstripe -c $dom) == 0 ] || error "bad stripe count"
	[ $($LFS getstripe -S $dom) == 1048576 ] || error "bad stripe size"

	local mdtidx=$($LFS getstripe -m $dom)
	local mdtname=MDT$(printf %04x $mdtidx)
	local facet=mds$((mdtidx + 1))
	local space_check=1

# previous files might released in background, but tests wants to have stable
# counters a specially in case running in loop
	do_facet $facet \
		"$LCTL set_param -n mdt.*.force_sync=1"

	# Skip free space checks with ZFS
	[ "$(facet_fstype $facet)" == "zfs" ] && space_check=0

	# write
	sync
	local size_tmp=$((65536 * 3))
	local mdtfree1=$(do_facet $facet \
			 lctl get_param -n osd*.*$mdtname.kbytesfree)

	dd if=/dev/urandom of=$tmp bs=1024 count=$((size_tmp / 1024))
	# check also direct IO along write
	# IO size must be a multiple of PAGE_SIZE on all platforms (ARM=64KB)
	dd if=$tmp of=$dom bs=65536 count=$((size_tmp / 65536)) oflag=direct
	sync
	cmp $tmp $dom || error "file data is different"
	[ $(stat -c%s $dom) == $size_tmp ] ||
		error "bad size after write: $(stat -c%s $dom) != $size_tmp"
	if [ $space_check == 1 ]; then
		local mdtfree2=$(do_facet $facet \
				 lctl get_param -n osd*.*$mdtname.kbytesfree)

		# increase in usage from by $size_tmp
		[ $(($mdtfree1 - $mdtfree2)) -ge $((size_tmp / 1024)) ] ||
			error "MDT free space wrong after write: " \
			      "$mdtfree1 >= $mdtfree2 + $size_tmp/1024"
	fi

	# truncate
	local size_dom=10000

	$TRUNCATE $dom $size_dom
	[ $(stat -c%s $dom) == $size_dom ] ||
		error "bad size after truncate: $(stat -c%s $dom) != $size_dom"
	if [ $space_check == 1 ]; then
		mdtfree1=$(do_facet $facet \
				lctl get_param -n osd*.*$mdtname.kbytesfree)
		# decrease in usage from $size_tmp to new $size_dom
		[ $(($mdtfree1 - $mdtfree2)) -ge \
		  $(((size_tmp - size_dom) / 4096 * 4)) ] ||
			error "MDT free space is wrong after truncate: " \
			      "$mdtfree1 >= $mdtfree2 + ($size_tmp - $size_dom) / 1024"
	fi

	# append
	cat $tmp >> $dom
	sync
	size_dom=$((size_dom + size_tmp))
	[ $(stat -c%s $dom) == $size_dom ] ||
		error "bad size after append: $(stat -c%s $dom) != $size_dom"
	if [ $space_check == 1 ]; then
		mdtfree2=$(do_facet $facet \
				lctl get_param -n osd*.*$mdtname.kbytesfree)
		# increase in usage by $size_tmp from previous
		[ $(($mdtfree1 - $mdtfree2)) -ge $((size_tmp / 1024)) ] ||
			error "MDT free space is wrong after append: " \
			      "$mdtfree1 >= $mdtfree2 + $size_tmp/1024"
	fi

	# delete
	rm $dom
# object might released in background
	do_facet $facet \
		"$LCTL set_param -n mdt.*.force_sync=1"
	if [ $space_check == 1 ]; then
		mdtfree1=$(do_facet $facet \
				lctl get_param -n osd*.*$mdtname.kbytesfree)
		# decrease in usage by $size_dom from previous
		[ $(($mdtfree1 - $mdtfree2)) -ge $((size_dom / 1024)) ] ||
			error "MDT free space is wrong after removal: " \
			      "$mdtfree1 >= $mdtfree2 + $size_dom/1024"
	fi

	# combined striping
	$LFS setstripe -E 1024K -L mdt -E EOF $dom ||
		error "Can't create DoM + OST striping"

	size_tmp=2031616 # must be a multiple of PAGE_SIZE=65536 on ARM
	dd if=/dev/urandom of=$tmp bs=1024 count=$((size_tmp / 1024))
	# check also direct IO along write
	dd if=$tmp of=$dom bs=65536 count=$((size_tmp / 65536)) oflag=direct
	sync
	cmp $tmp $dom || error "file data is different"
	[ $(stat -c%s $dom) == $size_tmp ] ||
		error "bad size after write: $(stat -c%s $dom) != $size_tmp"
	rm $dom $tmp

	return 0
}
run_test 270a "DoM: basic functionality tests"

test_270b() {
	[ $MDS1_VERSION -lt $(version_code 2.10.55) ] &&
		skip "Need MDS version at least 2.10.55"

	local dom=$DIR/$tdir/dom_file
	local max_size=1048576

	mkdir -p $DIR/$tdir
	$LFS setstripe -E $max_size -L mdt $dom

	# truncate over the limit
	$TRUNCATE $dom $(($max_size + 1)) &&
		error "successful truncate over the maximum size"
	# write over the limit
	dd if=/dev/zero of=$dom bs=$max_size seek=1 count=1 &&
		error "successful write over the maximum size"
	# append over the limit
	dd if=/dev/zero of=$dom bs=$(($max_size - 3)) count=1
	echo "12345" >> $dom && error "successful append over the maximum size"
	rm $dom

	return 0
}
run_test 270b "DoM: maximum size overflow checks for DoM-only file"

test_270c() {
	[ $MDS1_VERSION -lt $(version_code 2.10.55) ] &&
		skip "Need MDS version at least 2.10.55"

	mkdir -p $DIR/$tdir
	$LFS setstripe -E 1024K -L mdt $DIR/$tdir

	# check files inherit DoM EA
	touch $DIR/$tdir/first
	[ $($LFS getstripe -L $DIR/$tdir/first) == "mdt" ] ||
		error "bad pattern"
	[ $($LFS getstripe -c $DIR/$tdir/first) == 0 ] ||
		error "bad stripe count"
	[ $($LFS getstripe -S $DIR/$tdir/first) == 1048576 ] ||
		error "bad stripe size"

	# check directory inherits DoM EA and uses it as default
	mkdir $DIR/$tdir/subdir
	touch $DIR/$tdir/subdir/second
	[ $($LFS getstripe -L $DIR/$tdir/subdir/second) == "mdt" ] ||
		error "bad pattern in sub-directory"
	[ $($LFS getstripe -c $DIR/$tdir/subdir/second) == 0 ] ||
		error "bad stripe count in sub-directory"
	[ $($LFS getstripe -S $DIR/$tdir/subdir/second) == 1048576 ] ||
		error "bad stripe size in sub-directory"
	return 0
}
run_test 270c "DoM: DoM EA inheritance tests"

test_270d() {
	[ $MDS1_VERSION -lt $(version_code 2.10.55) ] &&
		skip "Need MDS version at least 2.10.55"

	mkdir -p $DIR/$tdir
	$LFS setstripe -E 1024K -L mdt $DIR/$tdir

	# inherit default DoM striping
	mkdir $DIR/$tdir/subdir
	touch $DIR/$tdir/subdir/f1

	# change default directory striping
	$LFS setstripe -c 1 $DIR/$tdir/subdir
	touch $DIR/$tdir/subdir/f2
	[ $($LFS getstripe -c $DIR/$tdir/subdir/f2) == 1 ] ||
		error "wrong default striping in file 2"
	[ $($LFS getstripe -L $DIR/$tdir/subdir/f2) == "raid0" ] ||
		error "bad pattern in file 2"
	return 0
}
run_test 270d "DoM: change striping from DoM to RAID0"

test_270e() {
	[ $MDS1_VERSION -lt $(version_code 2.10.55) ] &&
		skip "Need MDS version at least 2.10.55"

	mkdir -p $DIR/$tdir/dom
	mkdir -p $DIR/$tdir/norm
	DOMFILES=20
	NORMFILES=10
	$LFS setstripe -E 1M -L mdt $DIR/$tdir/dom
	$LFS setstripe -i 0 -S 2M $DIR/$tdir/norm

	createmany -o $DIR/$tdir/dom/dom- $DOMFILES
	createmany -o $DIR/$tdir/norm/norm- $NORMFILES

	# find DoM files by layout
	NUM=$($LFS find -L mdt -type f $DIR/$tdir 2>/dev/null | wc -l)
	[ $NUM -eq  $DOMFILES ] ||
		error "lfs find -L: found $NUM, expected $DOMFILES"
	echo "Test 1: lfs find 20 DOM files by layout: OK"

	# there should be 1 dir with default DOM striping
	NUM=$($LFS find -L mdt -type d $DIR/$tdir 2>/dev/null | wc -l)
	[ $NUM -eq  1 ] ||
		error "lfs find -L: found $NUM, expected 1 dir"
	echo "Test 2: lfs find 1 DOM dir by layout: OK"

	# find DoM files by stripe size
	NUM=$($LFS find -S -1200K -type f $DIR/$tdir 2>/dev/null | wc -l)
	[ $NUM -eq  $DOMFILES ] ||
		error "lfs find -S: found $NUM, expected $DOMFILES"
	echo "Test 4: lfs find 20 DOM files by stripe size: OK"

	# find files by stripe offset except DoM files
	NUM=$($LFS find -i 0 -type f $DIR/$tdir 2>/dev/null | wc -l)
	[ $NUM -eq  $NORMFILES ] ||
		error "lfs find -i: found $NUM, expected $NORMFILES"
	echo "Test 5: lfs find no DOM files by stripe index: OK"
	return 0
}
run_test 270e "DoM: lfs find with DoM files test"

test_270f() {
	[ $MDS1_VERSION -lt $(version_code 2.10.55) ] &&
		skip "Need MDS version at least 2.10.55"

	local mdtname=${FSNAME}-MDT0000-mdtlov
	local dom=$DIR/$tdir/dom_file
	local dom_limit_saved=$(do_facet mds1 $LCTL get_param -n \
						lod.$mdtname.dom_stripesize)
	local dom_limit=131072

	do_facet mds1 $LCTL set_param -n lod.$mdtname.dom_stripesize=$dom_limit
	local dom_current=$(do_facet mds1 $LCTL get_param -n \
						lod.$mdtname.dom_stripesize)
	[ ${dom_limit} -eq ${dom_current} ] ||
		error "Cannot change per-MDT DoM stripe limit to $dom_limit"

	$LFS mkdir -i 0 -c 1 $DIR/$tdir
	$LFS setstripe -d $DIR/$tdir
	$LFS setstripe -E $dom_limit -L mdt $DIR/$tdir ||
		error "Can't set directory default striping"

	# exceed maximum stripe size
	$LFS setstripe -E $((dom_limit * 2)) -L mdt $dom ||
		error "Can't create file with $((dom_limit * 2)) DoM stripe"
	[ $($LFS getstripe -S $dom) -eq $((dom_limit * 2)) ] &&
		error "Able to create DoM component size more than LOD limit"

	do_facet mds1 $LCTL set_param -n lod.$mdtname.dom_stripesize=0
	dom_current=$(do_facet mds1 $LCTL get_param -n \
						lod.$mdtname.dom_stripesize)
	[ 0 -eq ${dom_current} ] ||
		error "Can't set zero DoM stripe limit"
	rm $dom

	# attempt to create DoM file on server with disabled DoM should
	# remove DoM entry from layout and be succeed
	$LFS setstripe -E $dom_limit -L mdt -E -1 $dom ||
		error "Can't create DoM file (DoM is disabled)"
	[ $($LFS getstripe -L $dom) == "mdt" ] &&
		error "File has DoM component while DoM is disabled"
	rm $dom

	# attempt to create DoM file with only DoM stripe should return error
	$LFS setstripe -E $dom_limit -L mdt $dom &&
		error "Able to create DoM-only file while DoM is disabled"

	# too low values to be aligned with smallest stripe size 64K
	do_facet mds1 $LCTL set_param -n lod.$mdtname.dom_stripesize=30000
	dom_current=$(do_facet mds1 $LCTL get_param -n \
						lod.$mdtname.dom_stripesize)
	[ 30000 -eq ${dom_current} ] &&
		error "Can set too small DoM stripe limit"

	# 64K is a minimal stripe size in Lustre, expect limit of that size
	[ 65536 -eq ${dom_current} ] ||
		error "Limit is not set to 64K but ${dom_current}"

	do_facet mds1 $LCTL set_param -n lod.$mdtname.dom_stripesize=2147483648
	dom_current=$(do_facet mds1 $LCTL get_param -n \
						lod.$mdtname.dom_stripesize)
	echo $dom_current
	[ 2147483648 -eq ${dom_current} ] &&
		error "Can set too large DoM stripe limit"

	do_facet mds1 $LCTL set_param -n \
				lod.$mdtname.dom_stripesize=$((dom_limit * 2))
	$LFS setstripe -E $((dom_limit * 2)) -L mdt $dom ||
		error "Can't create DoM component size after limit change"
	do_facet mds1 $LCTL set_param -n \
				lod.$mdtname.dom_stripesize=$((dom_limit / 2))
	$LFS setstripe -E $dom_limit -L mdt ${dom}_big ||
		error "Can't create DoM file after limit decrease"
	[ $($LFS getstripe -S ${dom}_big) -eq $((dom_limit / 2)) ] ||
		error "Can create big DoM component after limit decrease"
	touch ${dom}_def ||
		error "Can't create file with old default layout"

	do_facet mds1 $LCTL set_param -n lod.*.dom_stripesize=$dom_limit_saved
	return 0
}
run_test 270f "DoM: maximum DoM stripe size checks"

test_270g() {
	[ $MDS1_VERSION -ge $(version_code 2.13.52) ] ||
		skip "Need MDS version at least 2.13.52"
	local dom=$DIR/$tdir/$tfile

	$LFS mkdir -i 0 -c 1 $DIR/$tdir
	local lodname=${FSNAME}-MDT0000-mdtlov

	local save="$TMP/$TESTSUITE-$TESTNAME.parameters"
	save_lustre_params mds1 "lod.${lodname}.dom_stripesize_max_kb" > $save
	save_lustre_params mds1 "lod.${lodname}.dom_threshold_free_mb" >> $save
	stack_trap "restore_lustre_params < $save; rm -f $save" EXIT

	local dom_limit=1024
	local dom_threshold="50%"

	$LFS setstripe -d $DIR/$tdir
	$LFS setstripe -E ${dom_limit}K -L mdt $DIR/$tdir ||
		error "Can't set directory default striping"

	do_facet mds1 $LCTL set_param -n \
				lod.${lodname}.dom_stripesize_max_kb=$dom_limit
	# set 0 threshold and create DOM file to change tunable stripesize
	do_facet mds1 $LCTL set_param -n lod.${lodname}.dom_threshold_free_mb=0
	$LFS setstripe -E ${dom_limit}K -L mdt -E -1 $dom ||
		error "Failed to create $dom file"
	# now tunable dom_cur_stripesize should reach maximum
	local dom_current=$(do_facet mds1 $LCTL get_param -n \
					lod.${lodname}.dom_stripesize_cur_kb)
	[[ $dom_current == $dom_limit ]] ||
		error "Current DOM stripesize is not maximum"
	rm $dom

	# set threshold for further tests
	do_facet mds1 $LCTL set_param -n \
			lod.${lodname}.dom_threshold_free_mb=$dom_threshold
	echo "DOM threshold is $dom_threshold free space"
	local dom_def
	local dom_set
	# Spoof bfree to exceed threshold
	#define OBD_FAIL_MDS_STATFS_SPOOF   0x168
	do_facet mds1 $LCTL set_param -n fail_loc=0x0168
	for spfree in 40 20 0 15 30 55; do
		do_facet mds1 $LCTL set_param -n fail_val=$spfree
		$LFS setstripe -E ${dom_limit}K -L mdt -E -1 $dom ||
			error "Failed to create $dom file"
		dom_def=$(do_facet mds1 $LCTL get_param -n \
					lod.${lodname}.dom_stripesize_cur_kb)
		echo "Free space: ${spfree}%, default DOM stripe: ${dom_def}K"
		[[ $dom_def != $dom_current ]] ||
			error "Default stripe size was not changed"
		if (( spfree > 0 )) ; then
			dom_set=$($LFS getstripe -S $dom)
			(( dom_set == dom_def * 1024 )) ||
				error "DOM component size is still old"
		else
			[[ $($LFS getstripe -L $dom) != "mdt" ]] ||
				error "DoM component is set with no free space"
		fi
		rm $dom
		dom_current=$dom_def
	done
}
run_test 270g "DoM: default DoM stripe size depends on free space"

test_270h() {
	[[ $MDS1_VERSION -ge $(version_code 2.13.53) ]] ||
		skip "Need MDS version at least 2.13.53"

	local mdtname=${FSNAME}-MDT0000-mdtlov
	local dom=$DIR/$tdir/$tfile
	local save="$TMP/$TESTSUITE-$TESTNAME.parameters"

	save_lustre_params mds1 "lod.*.dom_stripesize" > $save
	stack_trap "restore_lustre_params < $save; rm -f $save" EXIT

	$LFS mkdir -i 0 -c 1 $DIR/$tdir
	$LFS setstripe -E 1M -c1  -E -1 -c2 ${dom}_1 ||
		error "can't create OST file"
	# mirrored file with DOM entry in the second mirror
	$LFS mirror extend -N -E 1M -L mdt -E eof -c2 ${dom}_1 ||
		error "can't create mirror with DoM component"

	do_facet mds1 $LCTL set_param -n lod.$mdtname.dom_stripesize=0

	# DOM component in the middle and has other enries in the same mirror,
	# should succeed but lost DoM component
	local fid1=$($LFS path2fid ${dom}_1)

	$LFS setstripe --copy=$fid1 $dom ||
		error "Can't create file from OST|DOM mirror layout"
	# check new file has no DoM layout after all
	[[ $($LFS getstripe -L $dom) != "mdt" ]] ||
		error "File has DoM component while DoM is disabled"
}
run_test 270h "DoM: DoM stripe removal when disabled on server"

test_270i() {
	(( $MDS1_VERSION >= $(version_code 2.14.54) )) ||
		skip "Need MDS version at least 2.14.54"

	mkdir $DIR/$tdir
	# DoM with plain layout
	$LFS setstripe -L mdt -S 128k -c -1 $DIR/$tdir &&
		error "default plain layout with DoM must fail"
	$LFS setstripe -L mdt -S 128k -c -1 $DIR/$tdir/$tfile &&
		error "setstripe plain file layout with DoM must fail"
	$LFS setstripe -E 1M -L mdt -S 128k -c -1 -E eof $DIR/$tdir &&
		error "default DoM layout with bad striping must fail"
	$LFS setstripe -E 1M -L mdt -S 128k -c -1 -E eof $DIR/$tdir/$tfile &&
		error "setstripe to DoM layout with bad striping must fail"
	return 0
}
run_test 270i "DoM: setting invalid DoM striping should fail"

test_270j() {
	(( $MDS1_VERSION >= $(version_code 2.15.55.203) )) ||
		skip "Need MDS version at least 2.15.55.203"

	local dom=$DIR/$tdir/$tfile
	local odv
	local ndv

	mkdir -p $DIR/$tdir

	$LFS setstripe -E 1M -L mdt -E -1 -c1 $dom
	stack_trap "rm -f $dom"

	odv=$($LFS data_version $dom)
	chmod 666 $dom
	mv $dom ${dom}_moved
	link ${dom}_moved $dom
	setfattr -n user.attrx -v "some_attr" $dom
	ndv=$($LFS data_version $dom)
	(( $ndv == $odv )) ||
		error "data version was changed by metadata operations"

	dd if=/dev/urandom of=$dom bs=1M count=1 ||
		error "failed to write data into $dom"
	cancel_lru_locks mdc
	ndv=$($LFS data_version $dom)
	(( $ndv != $odv )) ||
		error "data version wasn't changed on write"

	odv=$ndv
	$TRUNCATE $dom 1000 || error "failed to truncate $dom"
	ndv=$($LFS data_version $dom)
	(( $ndv != $odv )) ||
		error "data version wasn't changed on truncate down"

	odv=$ndv
	$TRUNCATE $dom 25000
	ndv=$($LFS data_version $dom)
	(( $ndv != $odv )) ||
		error "data version wasn't changed on truncate up"

	# check also fallocate for ldiskfs
	if [[ "$mds1_FSTYPE" == ldiskfs ]]; then
		odv=$ndv
		fallocate -l 1048576 $dom
		ndv=$($LFS data_version $dom)
		(( $ndv != $odv )) ||
			error "data version wasn't changed on fallocate"

		odv=$ndv
		fallocate -p --offset 4096 -l 4096 $dom
		ndv=$($LFS data_version $dom)
		(( $ndv != $odv )) ||
			error "data version wasn't changed on fallocate punch"
	fi
}
run_test 270j "DoM migration: DOM file to the OST-striped file (plain)"

test_271a() {
	[ $MDS1_VERSION -lt $(version_code 2.10.55) ] &&
		skip "Need MDS version at least 2.10.55"

	local dom=$DIR/$tdir/dom

	mkdir -p $DIR/$tdir

	$LFS setstripe -E 1024K -L mdt $dom

	lctl set_param -n mdc.*.stats=clear
	dd if=/dev/zero of=$dom bs=4096 count=1 || return 1
	cat $dom > /dev/null
	local reads=$(lctl get_param -n mdc.*.stats | grep -c ost_read)
	[ $reads -eq 0 ] || error "Unexpected $reads READ RPCs"
	ls $dom
	rm -f $dom
}
run_test 271a "DoM: data is cached for read after write"

test_271b() {
	[ $MDS1_VERSION -lt $(version_code 2.10.55) ] &&
		skip "Need MDS version at least 2.10.55"

	local dom=$DIR/$tdir/dom

	mkdir -p $DIR/$tdir

	$LFS setstripe -E 1024K -L mdt -E EOF $dom

	lctl set_param -n mdc.*.stats=clear
	dd if=/dev/zero of=$dom bs=4096 count=1 || return 1
	cancel_lru_locks mdc
	$CHECKSTAT -t file -s 4096 $dom || error "stat #1 fails"
	# second stat to check size is cached on client
	$CHECKSTAT -t file -s 4096 $dom || error "stat #2 fails"
	local gls=$(lctl get_param -n mdc.*.stats | grep -c ldlm_glimpse)
	[ $gls -eq 0 ] || error "Unexpected $gls glimpse RPCs"
	rm -f $dom
}
run_test 271b "DoM: no glimpse RPC for stat (DoM only file)"

test_271ba() {
	[ $MDS1_VERSION -lt $(version_code 2.10.55) ] &&
		skip "Need MDS version at least 2.10.55"

	local dom=$DIR/$tdir/dom

	mkdir -p $DIR/$tdir

	$LFS setstripe -E 1024K -L mdt -E EOF $dom

	lctl set_param -n mdc.*.stats=clear
	lctl set_param -n osc.*.stats=clear
	# Hybrid switches to DIO, so does not hold the required lock to skip
	# the glimpse, so we disable it here...
	local hybrid=$($LCTL get_param -n llite.*.hybrid_io)
	$LCTL set_param llite.*.hybrid_io=0
	stack_trap "$LCTL set_param -n llite.*.hybrid_io=$hybrid" EXIT
	dd if=/dev/zero of=$dom bs=2048K count=1 || return 1
	cancel_lru_locks mdc
	$CHECKSTAT -t file -s 2097152 $dom || error "stat"
	# second stat to check size is cached on client
	$CHECKSTAT -t file -s 2097152 $dom || error "stat"
	local gls=$(lctl get_param -n mdc.*.stats | grep -c ldlm_glimpse)
	[ $gls == 0 ] || error "Unexpected $gls glimpse RPCs"
	local gls=$(lctl get_param -n osc.*.stats | grep -c ldlm_glimpse)
	[ $gls == 0 ] || error "Unexpected $gls OSC glimpse RPCs"
	rm -f $dom
}
run_test 271ba "DoM: no glimpse RPC for stat (combined file)"


get_mdc_stats() {
	local mdtidx=$1
	local param=$2
	local mdt=$(mdtname_from_index $mdtidx)

	if [ -z $param ]; then
		$LCTL get_param -n mdc.$mdt*.stats
	else
		$LCTL get_param -n mdc.$mdt*.stats | awk "/$param/"'{print $2}'
	fi
}

test_271c() {
	(( $MDS1_VERSION >= $(version_code v2_10_55_0-74-g2f09984f3f) )) ||
		skip "Need MDS >= 2.10.55.74 for combined DoM lock bits"

	local dom=$DIR/$tdir/dom

	mkdir -p $DIR/$tdir

	$LFS setstripe -E 1024K -L mdt $DIR/$tdir ||
		error "unable to set DoM layout on $DIR/$tdir"

	local mdtidx=$($LFS getstripe -m $DIR/$tdir)
	local facet=mds$((mdtidx + 1))

	cancel_lru_locks mdc
	do_facet $facet lctl set_param -n mdt.*.dom_lock=0
	createmany -o $dom 1000
	lctl set_param -n mdc.*.stats=clear
	smalliomany -w $dom 1000 200
	get_mdc_stats $mdtidx
	local enq=$(get_mdc_stats $mdtidx ldlm_ibits_enqueue)
	# Each file has 1 open, 1 IO enqueues, total 2000
	# but now we have also +1 getxattr for security.capability, total 3000
	[ $enq -ge 2000 ] || error "Too few enqueues $enq, expected > 2000"
	unlinkmany $dom 1000

	cancel_lru_locks mdc
	do_facet $facet lctl set_param -n mdt.*.dom_lock=1
	createmany -o $dom 1000
	lctl set_param -n mdc.*.stats=clear
	smalliomany -w $dom 1000 200
	local enq_2=$(get_mdc_stats $mdtidx ldlm_ibits_enqueue)
	# Expect to see reduced amount of RPCs by 1000 due to single enqueue
	# for OPEN and IO lock.
	[ $((enq - enq_2)) -ge 1000 ] ||
		error "Too many enqueues $enq_2, expected about $((enq - 1000))"
	unlinkmany $dom 1000
	return 0
}
run_test 271c "DoM: IO lock at open saves enqueue RPCs"

test_271d() {
	(( $MDS1_VERSION >= $(version_code v2_11_53_0-56-g13372d6c24) )) ||
		skip "Need MDS version at least 2.11.53"

	local dom=$DIR/$tdir/dom
	local tmp=$TMP/$tfile
	stack_trap "rm -f $tmp"

	mkdir -p $DIR/$tdir

	$LFS setstripe -E 1024K -L mdt $DIR/$tdir

	local mdtidx=$($LFS getstripe --mdt-index $DIR/$tdir)

	cancel_lru_locks mdc
	dd if=/dev/urandom of=$tmp bs=1000 count=1
	dd if=$tmp of=$dom bs=1000 count=1
	cancel_lru_locks mdc

	cat /etc/hosts >> $tmp
	lctl set_param -n mdc.*.stats=clear

	# append data to the same file it should update local page
	echo "Append to the same page"
	cat /etc/hosts >> $dom
	local stats=($(get_mdc_stats $mdtidx 'req_wait|req_active|ost_read'))
	local rw=${stats[0]}
	local ra=${stats[1]}
	local num=${stats[2]}

	[[ -z "$num" ]] || error "$num READ RPC occured"
	(( $ra == $rw )) || {
		get_mdc_stats $mdtidx
		echo "req_active: $ra"
		echo "req_waittime: $rw"
		error "$((ra - rw)) resend occured on append"
	}
	echo "... DONE"

	# compare content
	cmp $tmp $dom || error "file miscompare"

	cancel_lru_locks mdc
	lctl set_param -n mdc.*.stats=clear

	echo "Open and read file"
	cat $dom > /dev/null
	stats=($(get_mdc_stats $mdtidx 'req_wait|req_active|ost_read'))
	rw=${stats[0]}
	ra=${stats[1]}
	num=${stats[2]}

	[[ -z "$num" ]] || error "$num READ RPC occured"
	(( $ra == $rw )) || {
		get_mdc_stats $mdtidx
		echo "req_active: $ra"
		echo "req_waittime: $rw"
		error "$((ra - rw)) resend occured on open+read"
	}
	echo "... DONE"

	# compare content
	cmp -bl $tmp $dom || error "file miscompare"
}
run_test 271d "DoM: read on open (1K file in reply buffer)"

test_271f() {
	(( $MDS1_VERSION >= $(version_code v2_11_53_0-56-g13372d6c24) )) ||
		skip "Need MDS version at least 2.11.53"

	local dom=$DIR/$tdir/dom
	local tmp=$TMP/$tfile
	stack_trap "rm -f $tmp"

	mkdir -p $DIR/$tdir

	$LFS setstripe -E 1024K -L mdt $DIR/$tdir

	local mdtidx=$($LFS getstripe --mdt-index $DIR/$tdir)

	cancel_lru_locks mdc
	dd if=/dev/urandom of=$tmp bs=265000 count=1
	dd if=$tmp of=$dom bs=265000 count=1
	cancel_lru_locks mdc
	cat /etc/hosts >> $tmp
	lctl set_param -n mdc.*.stats=clear

	echo "Append to the same page"
	cat /etc/hosts >> $dom
	local stats=($(get_mdc_stats $mdtidx 'req_wait|req_active|ost_read'))
	local rw=${stats[0]}
	local ra=${stats[1]}
	local num=${stats[2]}

	[[ -z "$num" ]] || error "$num READ RPC occured"
	(( $ra == $rw )) || {
		get_mdc_stats $mdtidx
		echo "req_active: $ra"
		echo "req_waittime: $rw"
		error "$((ra - rw)) resend occured on append"
	}
	echo "... DONE"

	# compare content
	cmp $tmp $dom || error "file miscompare"

	cancel_lru_locks mdc
	lctl set_param -n mdc.*.stats=clear

	echo "Open and read file"
	cat $dom > /dev/null
	stats=($(get_mdc_stats $mdtidx 'req_wait|req_active|ost_read'))
	rw=${stats[0]}
	ra=${stats[1]}
	num=${stats[2]}

	[[ -n "$num" ]] || num=0
	(( $num == 1 )) || error "expect 1 READ RPC, $num occured"
	(( $ra == $rw )) || {
		get_mdc_stats $mdtidx
		echo "req_active: $ra"
		echo "req_waittime: $rw"
		error "$((ra - rw)) resend occured on open+read"
	}
	echo "... DONE"

	# compare content
	cmp -bl $tmp $dom || error "file miscompare"
}
run_test 271f "DoM: read on open (200K file and read tail)"

test_271g() {
	[[ $($LCTL get_param mdc.*.import) =~ async_discard ]] ||
		skip "Skipping due to old client or server version"

	$LFS setstripe -E 1024K -L mdt -E EOF $DIR1/$tfile
	# to get layout
	$CHECKSTAT -t file $DIR1/$tfile

	$MULTIOP $DIR1/$tfile Ow40960_w4096c &
	MULTIOP_PID=$!
	sleep 1
	#define OBD_FAIL_LDLM_CANCEL_BL_CB_RACE
	$LCTL set_param fail_loc=0x80000314
	rm $DIR1/$tfile || error "Unlink fails"
	RC=$?
	kill -USR1 $MULTIOP_PID && wait $MULTIOP_PID || error "multiop failure"
	[ $RC -eq 0 ] || error "Failed write to stale object"
}
run_test 271g "Discard DoM data vs client flush race"

test_272a() {
	[ $MDS1_VERSION -lt $(version_code 2.11.50) ] &&
		skip "Need MDS version at least 2.11.50"

	local dom=$DIR/$tdir/dom
	mkdir -p $DIR/$tdir

	$LFS setstripe -E 256K -L mdt -E -1 -c1 $dom
	dd if=/dev/urandom of=$dom bs=512K count=1 ||
		error "failed to write data into $dom"
	local old_md5=$(md5sum $dom)

	$LFS migrate -E 256K -L mdt -E -1 -c2 $dom ||
		error "failed to migrate to the same DoM component"

	local new_md5=$(md5sum $dom)

	[ "$old_md5" == "$new_md5" ] ||
		error "md5sum differ: $old_md5, $new_md5"

	[ $($LFS getstripe -c $dom) -eq 2 ] ||
		error "bad final stripe count: $($LFS getstripe -c $dom) != 2"
}
run_test 272a "DoM migration: new layout with the same DOM component"

test_272b() {
	[ $MDS1_VERSION -lt $(version_code 2.11.50) ] &&
		skip "Need MDS version at least 2.11.50"

	local dom=$DIR/$tdir/dom
	mkdir -p $DIR/$tdir
	$LFS setstripe -E 1M -L mdt -E -1 -c1 $dom
	stack_trap "rm -rf $DIR/$tdir"

	local mdtidx=$($LFS getstripe -m $dom)
	local mdtname=MDT$(printf %04x $mdtidx)
	local facet=mds$((mdtidx + 1))

	local mdtfree1=$(do_facet $facet \
		lctl get_param -n osd*.*$mdtname.kbytesfree)
	dd if=/dev/urandom of=$dom bs=2M count=1 ||
		error "failed to write data into $dom"
	local old_md5=$(md5sum $dom)
	cancel_lru_locks mdc
	local mdtfree1=$(do_facet $facet \
		lctl get_param -n osd*.*$mdtname.kbytesfree)

	$LFS migrate -c2 $dom ||
		error "failed to migrate to the new composite layout"
	[[ $($LFS getstripe --component-start=0 -L $dom) != 'mdt' ]] ||
		error "MDT stripe was not removed"
	! getfattr -n trusted.dataver $dom &> /dev/null ||
		error "$dir1 shouldn't have DATAVER EA"

	cancel_lru_locks mdc
	local new_md5=$(md5sum $dom)
	[ "$old_md5" == "$new_md5" ] ||
		error "$old_md5 != $new_md5"

	# Skip free space checks with ZFS
	if [ "$(facet_fstype $facet)" != "zfs" ]; then
		local mdtfree2=$(do_facet $facet \
				lctl get_param -n osd*.*$mdtname.kbytesfree)
		[ $mdtfree2 -gt $mdtfree1 ] ||
			error "MDT space is not freed after migration"
	fi
	return 0
}
run_test 272b "DoM migration: DOM file to the OST-striped file (plain)"

test_272c() {
	[ $MDS1_VERSION -lt $(version_code 2.11.50) ] &&
		skip "Need MDS version at least 2.11.50"

	local dom=$DIR/$tdir/$tfile
	mkdir -p $DIR/$tdir
	$LFS setstripe -E 1M -L mdt -E -1 -c1 $dom
	stack_trap "rm -rf $DIR/$tdir"

	local mdtidx=$($LFS getstripe -m $dom)
	local mdtname=MDT$(printf %04x $mdtidx)
	local facet=mds$((mdtidx + 1))

	dd if=/dev/urandom of=$dom bs=2M count=1 oflag=direct ||
		error "failed to write data into $dom"
	local old_md5=$(md5sum $dom)
	cancel_lru_locks mdc
	local mdtfree1=$(do_facet $facet \
		lctl get_param -n osd*.*$mdtname.kbytesfree)

	$LFS migrate -E 2M -c1 -E -1 -c2 $dom ||
		error "failed to migrate to the new composite layout"
	[[ $($LFS getstripe --component-start=0 -L $dom) != 'mdt' ]] ||
		error "MDT stripe was not removed"

	cancel_lru_locks mdc
	local new_md5=$(md5sum $dom)
	[ "$old_md5" == "$new_md5" ] ||
		error "$old_md5 != $new_md5"

	# Skip free space checks with ZFS
	if [ "$(facet_fstype $facet)" != "zfs" ]; then
		local mdtfree2=$(do_facet $facet \
				lctl get_param -n osd*.*$mdtname.kbytesfree)
		[ $mdtfree2 -gt $mdtfree1 ] ||
			error "MDS space is not freed after migration"
	fi
	return 0
}
run_test 272c "DoM migration: DOM file to the OST-striped file (composite)"

test_272d() {
	[ $MDS1_VERSION -lt $(version_code 2.12.55) ] &&
		skip "Need MDS version at least 2.12.55"

	local dom=$DIR/$tdir/$tfile
	mkdir -p $DIR/$tdir
	$LFS setstripe -E 1M -L mdt -E -1 -c1 $dom
	stack_trap "rm -f $dom"

	local mdtidx=$($LFS getstripe -m $dom)
	local mdtname=MDT$(printf %04x $mdtidx)
	local facet=mds$((mdtidx + 1))

	dd if=/dev/urandom of=$dom bs=2M count=1 oflag=direct ||
		error "failed to write data into $dom"
	local old_md5=$(md5sum $dom)
	cancel_lru_locks mdc
	local mdtfree1=$(do_facet $facet \
		lctl get_param -n osd*.*$mdtname.kbytesfree)

	$LFS mirror extend -N -E 2M -c1 -E -1 -c2 $dom ||
		error "failed mirroring to the new composite layout"
	$LFS mirror resync $dom ||
		error "failed mirror resync"
	$LFS mirror split --mirror-id 1 -d $dom ||
		error "failed mirror split"

	[ $($LFS getstripe -L $dom) != 'mdt' ] ||
		error "MDT stripe was not removed"

	cancel_lru_locks mdc
	local new_md5=$(md5sum $dom)
	[ "$old_md5" == "$new_md5" ] ||
		error "$old_md5 != $new_md5"

	# Skip free space checks with ZFS
	if [ "$(facet_fstype $facet)" != "zfs" ]; then
		local mdtfree2=$(do_facet $facet \
				lctl get_param -n osd*.*$mdtname.kbytesfree)
		[ $mdtfree2 -gt $mdtfree1 ] ||
			error "MDS space is not freed after DOM mirror deletion"
	fi
	return 0
}
run_test 272d "DoM mirroring: OST-striped mirror to DOM file"

test_272e() {
	[ $MDS1_VERSION -lt $(version_code 2.12.55) ] &&
		skip "Need MDS version at least 2.12.55"

	local dom=$DIR/$tdir/$tfile
	mkdir -p $DIR/$tdir
	$LFS setstripe -c 2 $dom
	stack_trap "rm -f $dom"

	dd if=/dev/urandom of=$dom bs=2M count=1 oflag=direct ||
		error "failed to write data into $dom"
	local old_md5=$(md5sum $dom)
	cancel_lru_locks

	$LFS mirror extend -N -E 1M -L mdt -E eof -c2 $dom ||
		error "failed mirroring to the DOM layout"
	$LFS mirror resync $dom ||
		error "failed mirror resync"
	$LFS mirror split --mirror-id 1 -d $dom ||
		error "failed mirror split"

	[[ $($LFS getstripe -L --component-start=0 $dom) == 'mdt' ]] ||
		error "MDT stripe wasn't set"

	cancel_lru_locks
	local new_md5=$(md5sum $dom)
	[ "$old_md5" == "$new_md5" ] ||
		error "$old_md5 != $new_md5"

	return 0
}
run_test 272e "DoM mirroring: DOM mirror to the OST-striped file"

test_272f() {
	[ $MDS1_VERSION -lt $(version_code 2.12.55) ] &&
		skip "Need MDS version at least 2.12.55"

	local dom=$DIR/$tdir/$tfile
	mkdir -p $DIR/$tdir
	$LFS setstripe -c 2 $dom
	stack_trap "rm -f $dom"

	dd if=/dev/urandom of=$dom bs=2M count=1 oflag=direct ||
		error "failed to write data into $dom"
	local old_md5=$(md5sum $dom)
	cancel_lru_locks

	$LFS migrate -E 1M -L mdt -E eof -c2 -v $dom ||
		error "failed migrating to the DOM file"

	[[ $($LFS getstripe -L --component-start=0 $dom) == 'mdt' ]] ||
		error "MDT stripe wasn't set"

	cancel_lru_locks
	local new_md5=$(md5sum $dom)
	[ "$old_md5" != "$new_md5" ] &&
		error "$old_md5 != $new_md5"

	return 0
}
run_test 272f "DoM migration: OST-striped file to DOM file"

test_273a() {
	[ $MDS1_VERSION -lt $(version_code 2.11.50) ] &&
		skip "Need MDS version at least 2.11.50"

	# Layout swap cannot be done if either file has DOM component,
	# this will never be supported, migration should be used instead

	local dom=$DIR/$tdir/$tfile
	mkdir -p $DIR/$tdir

	$LFS setstripe -c2 ${dom}_plain
	$LFS setstripe -E 1M -L mdt -E -1 -c2 ${dom}_dom
	$LFS swap_layouts ${dom}_plain ${dom}_dom &&
		error "can swap layout with DoM component"
	$LFS swap_layouts ${dom}_dom ${dom}_plain &&
		error "can swap layout with DoM component"

	$LFS setstripe -E 1M -c1 -E -1 -c2 ${dom}_comp
	$LFS swap_layouts ${dom}_comp ${dom}_dom &&
		error "can swap layout with DoM component"
	$LFS swap_layouts ${dom}_dom ${dom}_comp &&
		error "can swap layout with DoM component"
	return 0
}
run_test 273a "DoM: layout swapping should fail with DOM"

test_273b() {
	mkdir -p $DIR/$tdir
	$LFS setstripe -E 1M -L mdt -E -1 -c -1 $DIR/$tdir

#define OBD_FAIL_MDS_COMMITRW_DELAY      0x16b
	do_facet mds1 $LCTL set_param fail_loc=0x8000016b fail_val=2

	$MULTIOP $DIR/$tdir/$tfile Ouw2097152c
}
run_test 273b "DoM: race writeback and object destroy"

test_273c() {
	mkdir -p $DIR/$tdir
	$LFS setstripe -E 1M -E-1 -c-1 $DIR/$tdir

	#define OBD_FAIL_OFD_COMMITRW_DELAY      0x1e1
	do_facet ost1 $LCTL set_param fail_loc=0x800001e1 fail_val=2

	$MULTIOP $DIR/$tdir/$tfile Ouw2097152c
}
run_test 273c "race writeback and object destroy"

test_275() {
	remote_ost_nodsh && skip "remote OST with nodsh"
	[ $OST1_VERSION -lt $(version_code 2.10.57) ] &&
		skip "Need OST version >= 2.10.57"

	local file=$DIR/$tfile
	local osts=$(osts_nodes)

	dd if=/dev/urandom of=$file bs=1M count=2 ||
		error "failed to create a file"
	stack_trap "rm -f $file"
	cancel_lru_locks osc

	#lock 1
	dd if=$file of=/dev/null bs=1M count=1 iflag=direct ||
		error "failed to read a file"

#define OBD_FAIL_LDLM_PAUSE_CANCEL2      0x31f
	$LCTL set_param fail_loc=0x8000031f

	cancel_lru_locks osc &
	sleep 1

#define OBD_FAIL_LDLM_PROLONG_PAUSE      0x32b
	do_nodes $osts $LCTL set_param fail_loc=0x8000032b
	#IO takes another lock, but matches the PENDING one
	#and places it to the IO RPC
	dd if=$file of=/dev/null bs=1M count=1 iflag=direct ||
		error "failed to read a file with PENDING lock"
}
run_test 275 "Read on a canceled duplicate lock"

test_276() {
	(( $OST1_VERSION > $(version_code v2_10_58_0-52-g4f40429775) )) ||
		skip "need OSS > 2.10.58.52 to avoid statfs race"
	remote_ost_nodsh && skip "remote OST with nodsh"
	local pid

	do_facet ost1 "(while true; do \
		$LCTL get_param obdfilter.*.filesfree > /dev/null 2>&1; \
		done) & pid=\\\$!; echo \\\$pid > $TMP/sanity_276_pid" &
	pid=$!

	local end=$(($SECONDS + 120))
	[[ "$SLOW" == "yes" ]] && $((end += 600))

	while (($SECONDS < end)); do
		stop ost1
		start ost1 $(ostdevname 1) $OST_MOUNT_OPTS
	done
	kill -9 $pid
	do_facet ost1 "pid=\\\$(cat $TMP/sanity_276_pid); kill -9 \\\$pid; \
		rm $TMP/sanity_276_pid"
}
run_test 276 "Race between mount and obd_statfs"

test_277() {
	$LCTL set_param ldlm.namespaces.*.lru_size=0
	dd if=/dev/zero of=$DIR/$tfile bs=1M count=1
	local cached_mb=$($LCTL get_param llite.*.max_cached_mb |
			  awk '/^used_mb/ { print $2 }')
	[ $cached_mb -eq 1 ] || error "expected mb 1 got $cached_mb"
	dd if=/dev/zero of=$DIR/$tfile bs=1M count=1 \
		oflag=direct conv=notrunc
	stack_trap "rm -f $DIR/$tfile"
	cached_mb=$($LCTL get_param llite.*.max_cached_mb |
		    awk '/^used_mb/ { print $2 }')
	[ $cached_mb -eq 0 ] || error "expected mb 0 got $cached_mb"
}
run_test 277 "Direct IO shall drop page cache"

test_278() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run" && return
	[ $MDSCOUNT -lt 2 ] && skip "needs >= 2 MDTs" && return
	[[ "$(facet_host mds1)" != "$(facet_host mds2)" ]] &&
		skip "needs the same host for mdt1 mdt2" && return

	local pid1
	local pid2

#define OBD_FAIL_OBD_STOP_MDS_RACE     0x60b
	do_facet mds2 $LCTL set_param fail_loc=0x8000060c
	stop mds2 &
	pid2=$!

	stop mds1

	echo "Starting MDTs"
	start mds1 $(mdsdevname 1) $MDS_MOUNT_OPTS
	wait $pid2
#For the error assertion will happen. lu_env_get_key(..., &mdt_thread_key)
#will return NULL
	do_facet mds2 $LCTL set_param fail_loc=0

	start mds2 $(mdsdevname 2) $MDS_MOUNT_OPTS
	wait_recovery_complete mds2
}
run_test 278 "Race starting MDS between MDTs stop/start"

test_280() {
	[ $MGS_VERSION -lt $(version_code 2.13.52) ] &&
		skip "Need MGS version at least 2.13.52"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	combined_mgs_mds || skip "needs combined MGS/MDT"

	umount_client $MOUNT
#define OBD_FAIL_MDS_LLOG_UMOUNT_RACE   0x15e
	do_facet mgs $LCTL set_param fail_loc=0x8000015e fail_val=0

	mount_client $MOUNT &
	sleep 1
	stop mgs || error "stop mgs failed"
	#for a race mgs would crash
	start mgs $(mgsdevname) $MGS_MOUNT_OPTS || error "start mgs failed"
	# make sure we unmount client before remounting
	wait
	umount_client $MOUNT
	mount_client $MOUNT || error "mount client failed"
}
run_test 280 "Race between MGS umount and client llog processing"

cleanup_test_300() {
	trap 0
	umask $SAVE_UMASK
}

test_striped_dir() {
	local mdt_index=$1
	local stripe_count=$2
	local overstriping=$3
	local stripe_index
	local getstripe_count

	mkdir -p $DIR/$tdir

	SAVE_UMASK=$(umask)
	trap cleanup_test_300 RETURN EXIT

	if [ -z $overstriping ]; then
		$LFS setdirstripe -i $mdt_index -c $stripe_count -H all_char \
					-o 755 $DIR/$tdir/striped_dir ||
			error "set striped dir error"
	else
		$LFS setdirstripe -i $mdt_index -C $stripe_count -H all_char \
					-o 755 $DIR/$tdir/striped_dir ||
			error "set striped dir error"
	fi

	local mode=$(stat -c%a $DIR/$tdir/striped_dir)
	[ "$mode" = "755" ] || error "expect 755 got $mode"

	$LFS getdirstripe $DIR/$tdir/striped_dir > /dev/null 2>&1 ||
		error "getdirstripe failed"
	getstripe_count=$($LFS getdirstripe -c $DIR/$tdir/striped_dir)
	if [ "$getstripe_count" != "$stripe_count" ]; then
		error "1:stripe_count is $getstripe_count, expect $stripe_count"
	fi
	getstripe_count=$($LFS getdirstripe -T $DIR/$tdir/striped_dir)
	if [ "$getstripe_count" != "$stripe_count" ]; then
		error "2:stripe_count is $getstripe_count, expect $stripe_count"
	fi

	stripe_index=$($LFS getdirstripe -i $DIR/$tdir/striped_dir)
	if [ "$stripe_index" != "$mdt_index" ]; then
		error "stripe_index is $stripe_index, expect $mdt_index"
	fi

	[ $(stat -c%h $DIR/$tdir/striped_dir) == '2' ] ||
		error "nlink error after create striped dir"

	mkdir $DIR/$tdir/striped_dir/a
	mkdir $DIR/$tdir/striped_dir/b

	stat $DIR/$tdir/striped_dir/a ||
		error "create dir under striped dir failed"
	stat $DIR/$tdir/striped_dir/b ||
		error "create dir under striped dir failed"

	[ $(stat -c%h $DIR/$tdir/striped_dir) == '4' ] ||
		error "nlink error after mkdir"

	rmdir $DIR/$tdir/striped_dir/a
	[ $(stat -c%h $DIR/$tdir/striped_dir) == '3' ] ||
		error "nlink error after rmdir"

	rmdir $DIR/$tdir/striped_dir/b
	[ $(stat -c%h $DIR/$tdir/striped_dir) == '2' ] ||
		error "nlink error after rmdir"

	chattr +i $DIR/$tdir/striped_dir
	createmany -o $DIR/$tdir/striped_dir/f 10 &&
		error "immutable flags not working under striped dir!"
	chattr -i $DIR/$tdir/striped_dir

	rmdir $DIR/$tdir/striped_dir ||
		error "rmdir striped dir error"

	cleanup_test_300

	true
}

test_300a() {
	[ $MDS1_VERSION -lt $(version_code 2.7.0) ] &&
		skip "skipped for lustre < 2.7.0"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"

	test_striped_dir 0 2 || error "failed on striped dir on MDT0"
	test_striped_dir 1 2 || error "failed on striped dir on MDT0"
}
run_test 300a "basic striped dir sanity test"

test_300b() {
	[ $MDS1_VERSION -lt $(version_code 2.7.0) ] &&
		skip "skipped for lustre < 2.7.0"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"

	local i
	local mtime1
	local mtime2
	local mtime3

	test_mkdir $DIR/$tdir || error "mkdir fail"
	$LFS setdirstripe -i 0 -c 2 -H all_char $DIR/$tdir/striped_dir ||
		error "set striped dir error"
	for i in {0..9}; do
		mtime1=$(stat -c %Y $DIR/$tdir/striped_dir)
		sleep 1
		touch $DIR/$tdir/striped_dir/file_$i || error "touch error $i"
		mtime2=$(stat -c %Y $DIR/$tdir/striped_dir)
		[ $mtime1 -eq $mtime2 ] && error "mtime unchanged after create"
		sleep 1
		rm -f $DIR/$tdir/striped_dir/file_$i || error "unlink error $i"
		mtime3=$(stat -c %Y $DIR/$tdir/striped_dir)
		[ $mtime2 -eq $mtime3 ] && error "mtime unchanged after unlink"
	done
	true
}
run_test 300b "check ctime/mtime for striped dir"

test_300c() {
	[ $MDS1_VERSION -lt $(version_code 2.7.0) ] &&
		skip "skipped for lustre < 2.7.0"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"

	local file_count

	mkdir_on_mdt0 $DIR/$tdir
	$LFS setdirstripe -i 0 -c 2 $DIR/$tdir/striped_dir ||
		error "set striped dir error"

	chown $RUNAS_ID:$RUNAS_GID $DIR/$tdir/striped_dir ||
		error "chown striped dir failed"

	$RUNAS createmany -o $DIR/$tdir/striped_dir/f 5000 ||
		error "create 5k files failed"

	file_count=$(ls $DIR/$tdir/striped_dir | wc -l)

	[ "$file_count" = 5000 ] || error "file count $file_count != 5000"

	rm -rf $DIR/$tdir
}
run_test 300c "chown && check ls under striped directory"

test_300d() {
	[ $MDS1_VERSION -lt $(version_code 2.7.0) ] &&
		skip "skipped for lustre < 2.7.0"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"

	local stripe_count
	local file

	mkdir -p $DIR/$tdir
	$LFS setstripe -c 2 $DIR/$tdir

	#local striped directory
	$LFS setdirstripe -i 0 -c 2 -H all_char $DIR/$tdir/striped_dir ||
		error "set striped dir error"
	#look at the directories for debug purposes
	ls -l $DIR/$tdir
	$LFS getdirstripe $DIR/$tdir
	ls -l $DIR/$tdir/striped_dir
	$LFS getdirstripe $DIR/$tdir/striped_dir
	createmany -o $DIR/$tdir/striped_dir/f 10 ||
		error "create 10 files failed"

	#remote striped directory
	$LFS setdirstripe -i 1 -c 2 $DIR/$tdir/remote_striped_dir ||
		error "set striped dir error"
	#look at the directories for debug purposes
	ls -l $DIR/$tdir
	$LFS getdirstripe $DIR/$tdir
	ls -l $DIR/$tdir/remote_striped_dir
	$LFS getdirstripe $DIR/$tdir/remote_striped_dir
	createmany -o $DIR/$tdir/remote_striped_dir/f 10 ||
		error "create 10 files failed"

	for file in $(find $DIR/$tdir); do
		stripe_count=$($LFS getstripe -c $file)
		[ $stripe_count -eq 2 ] ||
			error "wrong stripe $stripe_count for $file"
	done

	rm -rf $DIR/$tdir
}
run_test 300d "check default stripe under striped directory"

test_300e() {
	[ $MDS1_VERSION -lt $(version_code 2.7.55) ] &&
		skip "Need MDS version at least 2.7.55"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"

	local stripe_count
	local file

	mkdir -p $DIR/$tdir

	$LFS setdirstripe -i 0 -c 2 -H all_char $DIR/$tdir/striped_dir ||
		error "set striped dir error"

	touch $DIR/$tdir/striped_dir/a
	touch $DIR/$tdir/striped_dir/b
	touch $DIR/$tdir/striped_dir/c

	mkdir $DIR/$tdir/striped_dir/dir_a
	mkdir $DIR/$tdir/striped_dir/dir_b
	mkdir $DIR/$tdir/striped_dir/dir_c

	$LFS setdirstripe -i 0 -c 2 -H all_char $DIR/$tdir/striped_dir/stp_a ||
		error "set striped adir under striped dir error"

	$LFS setdirstripe -i 0 -c 2 -H all_char $DIR/$tdir/striped_dir/stp_b ||
		error "set striped bdir under striped dir error"

	$LFS setdirstripe -i 0 -c 2 -H all_char $DIR/$tdir/striped_dir/stp_c ||
		error "set striped cdir under striped dir error"

	mrename $DIR/$tdir/striped_dir/dir_a $DIR/$tdir/striped_dir/dir_b ||
		error "rename dir under striped dir fails"

	mrename $DIR/$tdir/striped_dir/stp_a $DIR/$tdir/striped_dir/stp_b ||
		error "rename dir under different stripes fails"

	mrename $DIR/$tdir/striped_dir/a $DIR/$tdir/striped_dir/c ||
		error "rename file under striped dir should succeed"

	mrename $DIR/$tdir/striped_dir/dir_b $DIR/$tdir/striped_dir/dir_c ||
		error "rename dir under striped dir should succeed"

	rm -rf $DIR/$tdir
}
run_test 300e "check rename under striped directory"

test_300f() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"
	[ $MDS1_VERSION -lt $(version_code 2.7.55) ] &&
		skip "Need MDS version at least 2.7.55"

	local stripe_count
	local file

	rm -rf $DIR/$tdir
	mkdir -p $DIR/$tdir

	$LFS setdirstripe -i 0 -c 2 -H all_char $DIR/$tdir/striped_dir ||
		error "set striped dir error"

	$LFS setdirstripe -i 0 -c 2 -H all_char $DIR/$tdir/striped_dir1 ||
		error "set striped dir error"

	touch $DIR/$tdir/striped_dir/a
	mkdir $DIR/$tdir/striped_dir/dir_a
	$LFS setdirstripe -i 0 -c 2 $DIR/$tdir/striped_dir/stp_a ||
		error "create striped dir under striped dir fails"

	touch $DIR/$tdir/striped_dir1/b
	mkdir $DIR/$tdir/striped_dir1/dir_b
	$LFS setdirstripe -i 0 -c 2 $DIR/$tdir/striped_dir/stp_b ||
		error "create striped dir under striped dir fails"

	mrename $DIR/$tdir/striped_dir/dir_a $DIR/$tdir/striped_dir1/dir_b ||
		error "rename dir under different striped dir should fail"

	mrename $DIR/$tdir/striped_dir/stp_a $DIR/$tdir/striped_dir1/stp_b ||
		error "rename striped dir under diff striped dir should fail"

	mrename $DIR/$tdir/striped_dir/a $DIR/$tdir/striped_dir1/a ||
		error "rename file under diff striped dirs fails"

	rm -rf $DIR/$tdir
}
run_test 300f "check rename cross striped directory"

test_300_check_default_striped_dir()
{
	local dirname=$1
	local default_count=$2
	local default_index=$3
	local stripe_count
	local stripe_index
	local dir_stripe_index
	local dir

	echo "checking $dirname $default_count $default_index"
	$LFS setdirstripe -D -c $default_count -i $default_index \
				-H all_char $DIR/$tdir/$dirname ||
		error "set default stripe on striped dir error"
	stripe_count=$($LFS getdirstripe -D -c $DIR/$tdir/$dirname)
	[ $stripe_count -eq $default_count ] ||
		error "expect $default_count get $stripe_count for $dirname"

	stripe_index=$($LFS getdirstripe -D -i $DIR/$tdir/$dirname)
	[ $stripe_index -eq $default_index ] ||
		error "expect $default_index get $stripe_index for $dirname"

	mkdir $DIR/$tdir/$dirname/{test1,test2,test3,test4} ||
						error "create dirs failed"

	createmany -o $DIR/$tdir/$dirname/f- 10 || error "create files failed"
	unlinkmany $DIR/$tdir/$dirname/f- 10	|| error "unlink files failed"
	for dir in $(find $DIR/$tdir/$dirname/*); do
		stripe_count=$($LFS getdirstripe -c $dir)
		(( $stripe_count == $default_count )) ||
		(( $stripe_count == $MDSCOUNT && $default_count == -1 )) ||
		(( $stripe_count == 0 )) || (( $default_count == 1 )) ||
		error "stripe count $default_count != $stripe_count for $dir"

		stripe_index=$($LFS getdirstripe -i $dir)
		[ $default_index -eq -1 ] ||
			[ $stripe_index -eq $default_index ] ||
			error "$stripe_index != $default_index for $dir"

		#check default stripe
		stripe_count=$($LFS getdirstripe -D -c $dir)
		[ $stripe_count -eq $default_count ] ||
		error "default count $default_count != $stripe_count for $dir"

		stripe_index=$($LFS getdirstripe -D -i $dir)
		[ $stripe_index -eq $default_index ] ||
		error "default index $default_index != $stripe_index for $dir"
	done
	rmdir $DIR/$tdir/$dirname/* || error "rmdir failed"
}

test_300g() {
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"
	[ $MDS1_VERSION -lt $(version_code 2.7.55) ] &&
		skip "Need MDS version at least 2.7.55"

	local dir
	local stripe_count
	local stripe_index

	mkdir_on_mdt0 $DIR/$tdir
	mkdir $DIR/$tdir/normal_dir

	#Checking when client cache stripe index
	$LFS setdirstripe -c$MDSCOUNT $DIR/$tdir/striped_dir
	$LFS setdirstripe -D -i1 $DIR/$tdir/striped_dir ||
		error "create striped_dir failed"

	$LFS setdirstripe -i0 $DIR/$tdir/striped_dir/dir0 ||
		error "create dir0 fails"
	stripe_index=$($LFS getdirstripe -i $DIR/$tdir/striped_dir/dir0)
	[ $stripe_index -eq 0 ] ||
		error "dir0 expect index 0 got $stripe_index"

	mkdir $DIR/$tdir/striped_dir/dir1 ||
		error "create dir1 fails"
	stripe_index=$($LFS getdirstripe -i $DIR/$tdir/striped_dir/dir1)
	[ $stripe_index -eq 1 ] ||
		error "dir1 expect index 1 got $stripe_index"

	#check default stripe count/stripe index
	test_300_check_default_striped_dir normal_dir $MDSCOUNT 1
	test_300_check_default_striped_dir normal_dir 1 0
	test_300_check_default_striped_dir normal_dir -1 1
	test_300_check_default_striped_dir normal_dir 2 -1

	#delete default stripe information
	echo "delete default stripeEA"
	$LFS setdirstripe -d $DIR/$tdir/normal_dir ||
		error "set default stripe on striped dir error"

	mkdir -p $DIR/$tdir/normal_dir/{test1,test2,test3,test4}
	for dir in $(find $DIR/$tdir/normal_dir/*); do
		stripe_count=$($LFS getdirstripe -c $dir)
		[ $stripe_count -eq 0 ] ||
			error "expect 1 get $stripe_count for $dir"
	done
}
run_test 300g "check default striped directory for normal directory"

test_300h() {
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"
	[ $MDS1_VERSION -lt $(version_code 2.7.55) ] &&
		skip "Need MDS version at least 2.7.55"

	local dir
	local stripe_count

	mkdir $DIR/$tdir
	$LFS setdirstripe -i0 -c$MDSCOUNT -H all_char $DIR/$tdir/striped_dir ||
		error "set striped dir error"

	test_300_check_default_striped_dir striped_dir $MDSCOUNT 1
	test_300_check_default_striped_dir striped_dir 1 0
	test_300_check_default_striped_dir striped_dir -1 1
	test_300_check_default_striped_dir striped_dir 2 -1

	#delete default stripe information
	$LFS setdirstripe -d $DIR/$tdir/striped_dir ||
		error "set default stripe on striped dir error"

	mkdir -p $DIR/$tdir/striped_dir/{test1,test2,test3,test4}
	for dir in $(find $DIR/$tdir/striped_dir/*); do
		stripe_count=$($LFS getdirstripe -c $dir)
		[ $stripe_count -eq 0 ] ||
			error "expect 1 get $stripe_count for $dir"
	done
}
run_test 300h "check default striped directory for striped directory"

test_300i() {
	[[ $PARALLEL == "yes" ]] && skip "skip parallel run"
	(( $MDSCOUNT >= 2 )) || skip_env "needs >= 2 MDTs"
	(( $MDS1_VERSION >= $(version_code 2.7.55) )) ||
		skip "Need MDS version at least 2.7.55"

	local stripe_count
	local file

	mkdir $DIR/$tdir

	$LFS setdirstripe -i 0 -c$MDSCOUNT -H all_char $DIR/$tdir/striped_dir ||
		error "set striped dir error"

	createmany -o $DIR/$tdir/striped_dir/f- 10 ||
		error "create files under striped dir failed"

	$LFS setdirstripe -i0 -c$MDSCOUNT -H all_char $DIR/$tdir/hashdir ||
		error "set striped hashdir error"

	$LFS setdirstripe -i0 -c$MDSCOUNT -H all_char $DIR/$tdir/hashdir/d0 ||
		error "create dir0 under hash dir failed"
	$LFS setdirstripe -i0 -c$MDSCOUNT -H fnv_1a_64 $DIR/$tdir/hashdir/d1 ||
		error "create dir1 under hash dir failed"
	$LFS setdirstripe -i0 -c$MDSCOUNT -H crush $DIR/$tdir/hashdir/d2 ||
		error "create dir2 under hash dir failed"

	# unfortunately, we need to umount to clear dir layout cache for now
	# once we fully implement dir layout, we can drop this
	umount_client $MOUNT || error "umount failed"
	mount_client $MOUNT || error "mount failed"

	$LFS find -H fnv_1a_64,crush $DIR/$tdir/hashdir
	local dircnt=$($LFS find -H fnv_1a_64,crush $DIR/$tdir/hashdir | wc -l)
	(( $dircnt == 2 )) || error "lfs find striped dir got $dircnt != 2"

	if (( $MDS1_VERSION > $(version_code v2_15_50-185-g1ac4b9598a) )); then
		$LFS mkdir -i0 -c$MDSCOUNT -H crush2 $DIR/$tdir/hashdir/d3 ||
			error "create crush2 dir $tdir/hashdir/d3 failed"
		$LFS find -H crush2 $DIR/$tdir/hashdir
		dircnt=$($LFS find -H crush2 $DIR/$tdir/hashdir | wc -l)
		(( $dircnt == 1 )) || error "find crush2 dir got $dircnt != 1"

		# mkdir with an invalid hash type (hash=fail_val) from client
		# should be replaced on MDS with a valid (default) hash type
		#define OBD_FAIL_LMV_UNKNOWN_STRIPE	0x1901
		$LCTL set_param fail_loc=0x1901 fail_val=99
		$LFS mkdir -c2 $DIR/$tdir/hashdir/d99

		local hash=$($LFS getdirstripe -H $DIR/$tdir/hashdir/d99)
		local expect=$(do_facet mds1 \
			$LCTL get_param -n lod.$FSNAME-MDT0000-mdtlov.mdt_hash)
		[[ $hash == $expect ]] ||
			error "d99 hash '$hash' != expected hash '$expect'"
	fi

	#set the stripe to be unknown hash type on read
	#define OBD_FAIL_LMV_UNKNOWN_STRIPE	0x1901
	$LCTL set_param fail_loc=0x1901 fail_val=99
	for ((i = 0; i < 10; i++)); do
		$CHECKSTAT -t file $DIR/$tdir/striped_dir/f-$i ||
			error "stat f-$i failed"
		rm $DIR/$tdir/striped_dir/f-$i || error "unlink f-$i failed"
	done

	touch $DIR/$tdir/striped_dir/f0 &&
		error "create under striped dir with unknown hash should fail"

	$LCTL set_param fail_loc=0

	umount_client $MOUNT || error "umount failed"
	mount_client $MOUNT || error "mount failed"

	return 0
}
run_test 300i "client handle unknown hash type striped directory"

test_300j() {
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ $MDS1_VERSION -lt $(version_code 2.7.55) ] &&
		skip "Need MDS version at least 2.7.55"

	local stripe_count
	local file

	mkdir $DIR/$tdir

	#define OBD_FAIL_SPLIT_UPDATE_REC	0x1702
	$LCTL set_param fail_loc=0x1702
	$LFS setdirstripe -i 0 -c$MDSCOUNT -H all_char $DIR/$tdir/striped_dir ||
		error "set striped dir error"

	createmany -o $DIR/$tdir/striped_dir/f- 10 ||
		error "create files under striped dir failed"

	$LCTL set_param fail_loc=0

	rm -rf $DIR/$tdir || error "unlink striped dir fails"

	return 0
}
run_test 300j "test large update record"

test_300k() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"
	[ $MDS1_VERSION -lt $(version_code 2.7.55) ] &&
		skip "Need MDS version at least 2.7.55"

	# this test needs a huge transaction
	local kb
	kb=$(do_facet $SINGLEMDS "$LCTL get_param -n \
	     osd*.$FSNAME-MDT0000.kbytestotal")
	[ $kb -lt $((1024*1024)) ] && skip "MDT0 too small: $kb"

	local stripe_count
	local file

	mkdir $DIR/$tdir

	#define OBD_FAIL_LARGE_STRIPE	0x1703
	$LCTL set_param fail_loc=0x1703
	$LFS setdirstripe -i 0 -c192 $DIR/$tdir/striped_dir ||
		error "set striped dir error"
	$LCTL set_param fail_loc=0

	$LFS getdirstripe $DIR/$tdir/striped_dir ||
		error "getstripeddir fails"
	rm -rf $DIR/$tdir/striped_dir ||
		error "unlink striped dir fails"

	return 0
}
run_test 300k "test large striped directory"

test_300l() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"
	[ $MDS1_VERSION -lt $(version_code 2.7.55) ] &&
		skip "Need MDS version at least 2.7.55"

	local stripe_index

	test_mkdir -p $DIR/$tdir/striped_dir
	chown $RUNAS_ID $DIR/$tdir/striped_dir ||
			error "chown $RUNAS_ID failed"
	$LFS setdirstripe -i 1 -D $DIR/$tdir/striped_dir ||
		error "set default striped dir failed"

	do_facet mds2 $LCTL set_param mdt.*MDT0001.enable_remote_dir_gid=-1
	stack_trap "do_facet mds2 $LCTL set_param mdt.*MDT0001.enable_remote_dir_gid=0"
	#define OBD_FAIL_MDS_STALE_DIR_LAYOUT	 0x158
	$LCTL set_param fail_loc=0x80000158
	$RUNAS mkdir $DIR/$tdir/striped_dir/test_dir || error "create dir fails"

	stripe_index=$($LFS getdirstripe -i $DIR/$tdir/striped_dir/test_dir)
	[ $stripe_index -eq 1 ] ||
		error "expect 1 get $stripe_index for $dir"
}
run_test 300l "non-root user to create dir under striped dir with stale layout"

test_300m() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ $MDSCOUNT -ge 2 ] && skip_env "Only for single MDT"
	[ $MDS1_VERSION -lt $(version_code 2.7.55) ] &&
		skip "Need MDS version at least 2.7.55"

	mkdir -p $DIR/$tdir/striped_dir
	$LFS setdirstripe -D -c 1 $DIR/$tdir/striped_dir ||
		error "set default stripes dir error"

	mkdir $DIR/$tdir/striped_dir/a || error "mkdir a fails"

	stripe_count=$($LFS getdirstripe -c $DIR/$tdir/striped_dir/a)
	[ $stripe_count -eq 0 ] ||
			error "expect 0 get $stripe_count for a"

	$LFS setdirstripe -D -c 2 $DIR/$tdir/striped_dir ||
		error "set default stripes dir error"

	mkdir $DIR/$tdir/striped_dir/b || error "mkdir b fails"

	stripe_count=$($LFS getdirstripe -c $DIR/$tdir/striped_dir/b)
	[ $stripe_count -eq 0 ] ||
			error "expect 0 get $stripe_count for b"

	$LFS setdirstripe -D -c1 -i2 $DIR/$tdir/striped_dir ||
		error "set default stripes dir error"

	mkdir $DIR/$tdir/striped_dir/c &&
		error "default stripe_index is invalid, mkdir c should fails"

	rm -rf $DIR/$tdir || error "rmdir fails"
}
run_test 300m "setstriped directory on single MDT FS"

test_300n() {
	[[ $PARALLEL != "yes" ]] || skip "skip parallel run"
	(( $MDSCOUNT >= 2 )) || skip_env "needs >= 2 MDTs"
	(( $MDS1_VERSION >= $(version_code 2.7.55) )) ||
		skip "Need MDS >= 2.7.55 for enable_remote_dir_gid"
	remote_mds_nodsh && skip "remote MDS with nodsh"

	local stripe_index
	local mdts=$(mdts_nodes)
	local param_gid="mdt.*.enable_remote_dir_gid"
	local old_gid=($(do_facet mds1 $LCTL get_param -n $param_gid))

	mkdir --mode=0777 $DIR/$tdir

	stack_trap "do_nodes $mdts '$LCTL set_param $param_gid=$old_gid'"
	# mkdir _gid=0 with explicit setstripe, should not work for regular user
	do_nodes $mdts $LCTL set_param $param_gid=0 ||
		error "set $param_gid=0 failed"
	$RUNAS $LFS setdirstripe -i0 -c$MDSCOUNT \
				$DIR/$tdir/striped_dir > /dev/null 2>&1 &&
		error "create striped dir succeeds with remote_gid=0"
	$RUNAS $LFS setdirstripe -D -i 1 -c$MDSCOUNT $DIR/$tdir/striped_dir &&
		error "set default dir layout succeeds with remote_gid=0"
	[[ ! -e $DIR/$tdir/striped_dir ]] || error "striped_dir was created"

	# mkdir _gid=-1 with explicit setstripe, should work for any user
	do_nodes $mdts $LCTL set_param $param_gid=-1
	$RUNAS $LFS setdirstripe -i0 -c$MDSCOUNT $DIR/$tdir/striped_dir ||
		error "create striped dir fails with remote_gid=-1"
	$RUNAS $LFS setdirstripe -D -i 1 -c$MDSCOUNT $DIR/$tdir/striped_dir ||
		error "set default dir layout fails with remote_gid=-1"

	# mkdir _gid=0 with default setstripe, should work for any user
	do_nodes $mdts $LCTL set_param $param_gid=0
	$RUNAS mkdir $DIR/$tdir/striped_dir/test_dir.{1,2,3} ||
		error "mkdir in default test_dir with remote_gid=0 fails"
	[[ -d $DIR/$tdir/striped_dir/test_dir.1 ]] ||
		error "striped_dir/test_dir.1 not created"
}
run_test 300n "non-root user to create dir under striped dir with default EA"

test_300ne()
{
	[[ $PARALLEL != "yes" ]] || skip "skip parallel run"
	(( $MDSCOUNT >= 2 )) || skip_env "needs >= 2 MDTs"
	(( $MDS1_VERSION >= $(version_code 2.17.51) )) ||
		skip "Need MDS >= 2.17.51 for supp remote_dir_gid"
	remote_mds_nodsh && skip "remote MDS with nodsh"

	local param_gid="mdt.*.enable_remote_dir_gid"
	local old_gid=($(do_facet mds1 $LCTL get_param -n $param_gid))
	local mdts=$(mdts_nodes)

	echo "using primary group $RUNAS_GID"
	do_nodes $mdts "grep '$RUNAS_GID:' /etc/group"
	do_nodes $mdts "id $RUNAS_ID"
	do_nodes $mdts "$LCTL get_param mdt.*.identity_upcall"
	do_nodes $mdts "$L_GETIDENTITY -d $RUNAS_ID"
	start_full_debug_logging
	stack_trap stop_full_debug_logging

	mkdir_on_mdt0 -o 0777 $DIR/$tdir

	stack_trap "do_nodes $mdts '$LCTL set_param $param_gid=$old_gid'"
	# mkdir _gid=N with explicit setstripe, should work for primary group
	do_nodes $mdts $LCTL set_param $param_gid=$RUNAS_GID
	$RUNAS $LFS mkdir -i 1 $DIR/$tdir/group_dir ||
		error "create remote dir fails with remote_gid=$RUNAS_ID"
	[[ -d $DIR/$tdir/group_dir ]] || error "$tdir/group_dir not created"

	echo "using $TSTUSR with secondary groups $new_gids"
	local tst_gids=$(do_facet mds1 id -G $TSTUSR | tr ' ' ',')
	local new_gids="$tst_gids,$RUNAS_ID"
	local runas="$RUNAS -u $TSTUSR -g $TSTUSR -G$new_gids"

	# add $RUNAS_ID as a secondary group to $TSTUSR
	stack_trap "do_nodes $mdts usermod -G $tst_gids $TSTUSR"
	do_nodes $mdts usermod -a -G $RUNAS_ID $TSTUSR ||
		error "can't add $TSTUSR to group $RUNAS_ID"

	do_nodes $mdts "grep ':$RUNAS_ID:' /etc/group"
	do_nodes $mdts "id $TSTUSR"
	do_nodes $mdts "$L_GETIDENTITY -d $(id -u $TSTUSR)"

	# mkdir _gid=N with explicit setstripe, should work for secondary group
	$runas $LFS mkdir -i 1 $DIR/$tdir/secondary_dir ||
		error "create remote dir fails with secondary gids=$new_gids"
	[[ -d $DIR/$tdir/secondary_dir ]] || error "secondary_dir not created"
}
run_test 300ne "create remote dir with various mdt.enable_remote_gid"

test_300o() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"
	[ $MDS1_VERSION -lt $(version_code 2.7.55) ] &&
		skip "Need MDS version at least 2.7.55"

	local numfree1
	local numfree2

	mkdir -p $DIR/$tdir

	numfree1=$(lctl get_param -n mdc.*MDT0000*.filesfree)
	numfree2=$(lctl get_param -n mdc.*MDT0001*.filesfree)
	if [ $numfree1 -lt 66000 ] || [ $numfree2 -lt 66000 ]; then
		skip "not enough free inodes $numfree1 $numfree2"
	fi

	numfree1=$(lctl get_param -n mdc.*MDT0000-mdc-*.kbytesfree)
	numfree2=$(lctl get_param -n mdc.*MDT0001-mdc-*.kbytesfree)
	if [ $numfree1 -lt 300000 ] || [ $numfree2 -lt 300000 ]; then
		skip "not enough free space $numfree1 $numfree2"
	fi

	$LFS setdirstripe -c2 $DIR/$tdir/striped_dir ||
		error "setdirstripe fails"

	createmany -d $DIR/$tdir/striped_dir/d 131000 ||
		error "create dirs fails"

	$LCTL set_param ldlm.namespaces.*mdc-*.lru_size=0
	ls $DIR/$tdir/striped_dir > /dev/null ||
		error "ls striped dir fails"
	unlinkmany -d $DIR/$tdir/striped_dir/d 131000 ||
		error "unlink big striped dir fails"
}
run_test 300o "unlink big sub stripe(> 65000 subdirs)"

test_300p() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"
	remote_mds_nodsh && skip "remote MDS with nodsh"

	mkdir_on_mdt0 $DIR/$tdir

	#define OBD_FAIL_OUT_ENOSPC	0x1704
	do_facet mds2 lctl set_param fail_loc=0x1704
	$LFS setdirstripe -i 0,1 $DIR/$tdir/bad_striped_dir &&
		error "create striped directory should fail"

	! [ -e $DIR/$tdir/bad_striped_dir ] || error "striped dir exists"
}
run_test 300p "create striped directory without space"

test_300q() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"

	local fd=$(free_fd)
	local cmd="exec $fd<$tdir"
	cd $DIR
	$LFS mkdir -c $MDSCOUNT $tdir || error "create $tdir fails"
	eval $cmd
	cmd="exec $fd<&-"
	trap "eval $cmd" EXIT
	cd $tdir || error "cd $tdir fails"
	rmdir  ../$tdir || error "rmdir $tdir fails"
	mkdir local_dir && error "create dir succeeds"
	$LFS setdirstripe -i1 remote_dir && error "create remote dir succeeds"
	eval $cmd
	return 0
}
run_test 300q "create remote directory under orphan directory"

test_300r() {
	[ $MDS1_VERSION -lt $(version_code 2.7.55) ] &&
		skip "Need MDS version at least 2.7.55" && return
	[ $MDSCOUNT -lt 2 ] && skip "needs >= 2 MDTs" && return

	mkdir $DIR/$tdir

	$LFS setdirstripe -i 0 -c -1 $DIR/$tdir/striped_dir ||
		error "set striped dir error"

	$LFS getdirstripe $DIR/$tdir/striped_dir ||
		error "getstripeddir fails"

	local stripe_count
	stripe_count=$($LFS getdirstripe $DIR/$tdir/striped_dir |
		      awk '/lmv_stripe_count:/ { print $2 }')

	[ $MDSCOUNT -ne $stripe_count ] &&
		error "wrong stripe count $stripe_count expected $MDSCOUNT"

	rm -rf $DIR/$tdir/striped_dir ||
		error "unlink striped dir fails"
}
run_test 300r "test -1 striped directory"

test_300s_helper() {
	local count=$1

	local stripe_dir=$DIR/$tdir/striped_dir.$count

	$LFS mkdir -c $count $stripe_dir ||
		error "lfs mkdir -c error"

	$LFS getdirstripe $stripe_dir ||
		error "lfs getdirstripe fails"

	local stripe_count
	stripe_count=$($LFS getdirstripe $stripe_dir |
		      awk '/lmv_stripe_count:/ { print $2 }')

	[ $count -ne $stripe_count ] &&
		error_noexit "bad stripe count $stripe_count expected $count"

	local dupe_stripes
	dupe_stripes=$($LFS getdirstripe $stripe_dir |
		awk '/0x/ {count[$1] += 1}; END {
			for (idx in count) {
				if (count[idx]>1) {
					print "index " idx " count " count[idx]
				}
			}
		}')

	if [[ -n "$dupe_stripes" ]] ; then
		lfs getdirstripe $stripe_dir
		error_noexit "Dupe MDT above: $dupe_stripes "
	fi

	rm -rf $stripe_dir ||
		error_noexit "unlink $stripe_dir fails"
}

test_300s() {
	[ $MDS1_VERSION -lt $(version_code 2.7.55) ] &&
		skip "Need MDS version at least 2.7.55" && return
	[ $MDSCOUNT -lt 2 ] && skip "needs >= 2 MDTs" && return

	mkdir $DIR/$tdir
	for count in $(seq 2 $MDSCOUNT); do
		test_300s_helper $count
	done
}
run_test 300s "test lfs mkdir -c without -i"

test_300t() {
	(( $MDS1_VERSION >= $(version_code 2.14.55) )) ||
		skip "need MDS 2.14.55 or later"
	(( $MDSCOUNT >= 2 )) || skip "needs at least 2 MDTs"

	local testdir="$DIR/$tdir/striped_dir"
	local dir1=$testdir/dir1
	local dir2=$testdir/dir2

	mkdir -p $testdir

	$LFS setdirstripe -D -c -1 --max-inherit=3 $testdir ||
		error "failed to set default stripe count for $testdir"

	mkdir $dir1
	local stripe_count=$($LFS getdirstripe -c $dir1)

	(( $stripe_count == $MDSCOUNT )) || error "wrong stripe count"

	local max_count=$((MDSCOUNT - 1))
	local mdts=$(mdts_nodes)

	do_nodes $mdts $LCTL set_param lod.*.max_mdt_stripecount=$max_count
	stack_trap "do_nodes $mdts $LCTL set_param lod.*.max_mdt_stripecount=0"

	mkdir $dir2
	stripe_count=$($LFS getdirstripe -c $dir2)

	if (( $MDSCOUNT == 2 &&
	      $MDS1_VERSION >= $(version_code 2.16.0) )); then
		(( $stripe_count == 0 )) || error "(0) wrong stripe count"
	else
		(( $stripe_count == $max_count )) ||
			error "(1) wrong stripe count"
	fi
}
run_test 300t "test max_mdt_stripecount"

max_stripes_per_mdt=$(do_facet mds1 $LCTL get_param -n \
		      lod.$FSNAME-MDT0000-mdtlov.max_stripes_per_mdt || echo 0)
((max_stripes_per_mdt == 0)) ||
	do_nodes $(mdts_nodes) $LCTL set_param -n \
	lod.$FSNAME-MDT*.max_stripes_per_mdt=$LMV_MAX_STRIPES_PER_MDT
# 300u family tests MDT overstriping
test_300ua() {
	(( MDSCOUNT > 1 )) || skip "needs >= 2 MDTs"

	local setcount=$((MDSCOUNT * 2))

	local expected_count

	mkdir $DIR/$tdir
	$LFS setdirstripe -C $setcount $DIR/$tdir/${tdir}.0 ||
		error "(0) failed basic overstriped dir creation test"
	local getstripe_count=$($LFS getdirstripe -c $DIR/$tdir/${tdir}.0)

	# This does a basic interop test - if the MDS does not support mdt
	# overstriping, we should get stripes == number of MDTs
	if (( max_stripes_per_mdt == 0 )); then
		expected_count=$MDSCOUNT
	else
		expected_count=$setcount
	fi
	(( getstripe_count == expected_count )) ||
		error "(1) incorrect stripe count for simple overstriped dir"

	rm -rf $DIR/$tdir/${tdir}.0 ||
		error "(2) unable to rm overstriped dir"

	# Tests after this require overstriping support
	(( max_stripes_per_mdt > 0 )) || return 0

	test_striped_dir 0 $setcount true ||
		error "(3)failed on overstriped dir"
	test_striped_dir 1 $setcount true ||
		error "(4)failed on overstriped dir"

	local setcount=$((MDSCOUNT * $LMV_MAX_STRIPES_PER_MDT))

	test_striped_dir 0 $setcount true ||
		error "(5)failed on overstriped dir"
}
run_test 300ua "basic overstriped dir sanity test"

test_300ub() {
	(( max_stripes_per_mdt > 0 )) ||
		skip "skipped for MDS that doesn't support metadata overstripe"
	(( MDSCOUNT > 1 )) || skip "needs >= 2 MDTs"

	mkdir $DIR/$tdir

	echo "Testing invalid stripe count, failure expected"
	local setcount=$((MDSCOUNT * 2))

	$LFS setdirstripe -c $setcount $DIR/$tdir/${tdir}.0
	local getstripe_count=$($LFS getdirstripe -c $DIR/$tdir/${tdir}.0)

	(( getstripe_count <= MDSCOUNT )) ||
		error "(0)stripe count ($setcount) > MDT count ($MDSCOUNT) succeeded with -c"

	# When a user requests > LMV_MAX_STRIPES_PER_MDT, we reduce to that
	setcount=$((MDSCOUNT * 2 * LMV_MAX_STRIPES_PER_MDT))
	$LFS setdirstripe -C $setcount $DIR/$tdir/${tdir}.1

	local maxcount=$((MDSCOUNT * LMV_MAX_STRIPES_PER_MDT))

	getstripe_count=$($LFS getdirstripe -c $DIR/$tdir/${tdir}.1)
	(( getstripe_count == maxcount )) ||
		error "(1)stripe_count is $getstripe_count, expect $maxcount"

	# Test specific striping with -i
	$LFS setdirstripe -i 0,0,0,0 $DIR/$tdir/${tdir}.2

	getstripe_count=$($LFS getdirstripe -c $DIR/$tdir/${tdir}.2)
	(( getstripe_count == 4 )) ||
		error "(2)stripe_count is $getstripe_count, expect 4"

	local nonzeroindices=$($LFS getdirstripe $DIR/$tdir/${tdir}.2 | grep "\[" | \
			       grep -v mdtidx | awk '{print $1}' | grep -c -v 0)

	[[ -n "$nonzeroindices" ]] ||
		error "(3) stripes indices not all 0: $nonzeroindices"

	# Test specific striping with too many stripes on one MDT
	echo "Testing invalid striping, failure expected"
	$LFS setdirstripe -i 0,1,0,1,0,1,0,1,0,1,0 $DIR/$tdir/${tdir}.3
	$LFS getdirstripe $DIR/$tdir/${tdir}.3
	getstripe_count=$($LFS getdirstripe $DIR/$tdir/${tdir}.3 | grep "\[" | \
			  grep -v mdtidx | awk '{print $1}' | grep -c '0')
	echo "stripes on MDT0: $getstripe_count"
	(( getstripe_count <= LMV_MAX_STRIPES_PER_MDT )) ||
		error "(4) setstripe with too many stripes on MDT0 succeeded"

	setcount=$((MDSCOUNT * 2))
	$LFS setdirstripe -C $setcount -H all_char $DIR/${tdir}.4 ||
		error "(5) can't setdirstripe with manually set hash function"

	getstripe_count=$($LFS getdirstripe -c $DIR/${tdir}.4)
	(( getstripe_count == setcount )) ||
		error "(6)stripe_count is $getstripe_count, expect $setcount"

	setcount=$((MDSCOUNT * 2))
	mkdir $DIR/${tdir}.5
	$LFS setdirstripe -C $setcount -D -H crush $DIR/${tdir}.5 ||
		error "(7) can't setdirstripe with manually set hash function"
	mkdir $DIR/${tdir}.5/${tdir}.6

	getstripe_count=$($LFS getdirstripe -c $DIR/${tdir}.5/${tdir}.6)
	(( getstripe_count == setcount )) ||
		error "(8)stripe_count is $getstripe_count, expect $setcount"
}
run_test 300ub "test MDT overstriping interface & limits"

test_300uc() {
	(( max_stripes_per_mdt > 0 )) ||
		skip "skipped for MDS that doesn't support metadata overstripe"
	(( MDSCOUNT > 1 )) || skip "needs >= 2 MDTs"

	mkdir $DIR/$tdir

	local setcount=$((MDSCOUNT * 2))

	$LFS setdirstripe -D -C $setcount $DIR/$tdir

	mkdir $DIR/$tdir/${tdir}.1

	local getstripe_count=$($LFS getdirstripe -c $DIR/$tdir/${tdir}.1)

	(( getstripe_count == setcount )) ||
		error "(0)stripe_count is $getstripe_count, expect $setcount"

	mkdir $DIR/$tdir/${tdir}.1/${tdir}.2

	local getstripe_count=$($LFS getdirstripe -c \
				$DIR/$tdir/${tdir}.1/${tdir}.2)

	(( getstripe_count == setcount )) ||
		error "(1)stripe_count is $getstripe_count, expect $setcount"
}
run_test 300uc "test MDT overstriping as default & inheritance"

test_300ud() {
	(( max_stripes_per_mdt > 0 )) ||
		skip "skipped for MDS that doesn't support metadata overstripe"
	(( MDSCOUNT > 1 )) || skip "needs >= 2 MDTs"

	local mdts=$(mdts_nodes)
	local timeout=100

	local restripe_status
	local delta
	local i

	[[ $mds1_FSTYPE == zfs ]] && timeout=300

	# in case "crush" hash type is not set
	do_nodes $mdts "$LCTL set_param lod.*.mdt_hash=crush"

	restripe_status=$(do_facet mds1 $LCTL get_param -n \
			   mdt.*MDT0000.enable_dir_restripe)
	do_nodes $mdts "$LCTL set_param mdt.*.enable_dir_restripe=1"
	stack_trap "do_nodes $mdts $LCTL set_param \
		    mdt.*.enable_dir_restripe=$restripe_status"

	mkdir $DIR/$tdir
	createmany -m $DIR/$tdir/f $((50 * MDSCOUNT)) ||
		error "create files under remote dir failed $i"
	createmany -d $DIR/$tdir/d $((50 * MDSCOUNT)) ||
		error "create dirs under remote dir failed $i"

	local setcount=$((MDSCOUNT * $LMV_MAX_STRIPES_PER_MDT))

	(( setcount < 13 )) || setcount=12
	for i in $(seq 2 $setcount); do
		do_nodes $mdts "$LCTL set_param mdt.*.md_stats=clear >/dev/null"
		$LFS setdirstripe -C $i $DIR/$tdir ||
			error "split -C $i $tdir failed"
		wait_update $HOSTNAME \
			"$LFS getdirstripe -H $DIR/$tdir" "crush" $timeout ||
			error "dir split not finished"
		delta=$(do_nodes $mdts "lctl get_param -n mdt.*MDT*.md_stats" |
			awk '/migrate/ {sum += $2} END { print sum }')
		echo "$delta migrated when dir split $((i - 1)) to $i stripes"
		# delta is around total_files/stripe_count, deviation 3%
		(( delta < 100 * MDSCOUNT / i + 3 * MDSCOUNT )) ||
			error "$delta files migrated >= $((100 * MDSCOUNT / i + 3 * MDSCOUNT))"
	done
}
run_test 300ud "dir split"

test_300ue() {
	(( max_stripes_per_mdt > 0 )) ||
		skip "skipped for MDS that doesn't support metadata overstripe"
	(( MDSCOUNT > 1 )) || skip "needs >= 2 MDTs"

	local mdts=$(mdts_nodes)
	local timeout=100

	local restripe_status
	local delta
	local c

	[[ $mds1_FSTYPE == zfs ]] && timeout=300

	do_nodes $mdts "$LCTL set_param lod.*.mdt_hash=crush"

	restripe_status=$(do_facet mds1 $LCTL get_param -n \
			   mdt.*MDT0000.enable_dir_restripe)
	do_nodes $mdts "$LCTL set_param mdt.*.enable_dir_restripe=1"
	stack_trap "do_nodes $mdts $LCTL set_param \
		    mdt.*.enable_dir_restripe=$restripe_status"

	local setcount=$((MDSCOUNT * $LMV_MAX_STRIPES_PER_MDT))

	(( setcount < 13 )) || setcount=12
	test_mkdir -C $setcount -H crush $DIR/$tdir
	createmany -m $DIR/$tdir/f $((50 * MDSCOUNT)) ||
		error "create files under remote dir failed"
	createmany -d $DIR/$tdir/d $((50 * MDSCOUNT)) ||
		error "create dirs under remote dir failed"

	for c in $(seq $((setcount - 1)) -1 1); do
		do_nodes $mdts "$LCTL set_param mdt.*.md_stats=clear >/dev/null"
		$LFS setdirstripe -C $c $DIR/$tdir ||
			error "split -C $c $tdir failed"
		wait_update $HOSTNAME \
			"$LFS getdirstripe -H $DIR/$tdir" "crush,fixed" $timeout ||
			error "dir merge not finished"
		delta=$(do_nodes $mdts "lctl get_param -n mdt.*MDT*.md_stats" |
			awk '/migrate/ {sum += $2} END { print sum }')
		echo "$delta migrated when dir merge $((c + 1)) to $c stripes"
		# delta is around total_files/stripe_count, deviation 3%
		(( delta < 100 * MDSCOUNT / c + 3 * MDSCOUNT )) ||
			error "$delta files migrated >= $((100 * MDSCOUNT / c + 3 * MDSCOUNT))"
	done
}
run_test 300ue "dir merge"

test_300uf() {
	(( max_stripes_per_mdt > 0 )) ||
		skip "skipped for MDS that doesn't support metadata overstripe"
	(( MDSCOUNT > 1 )) || skip "needs >= 2 MDTs"

	# maximum amount of local locks:
	# parent striped dir - 2 locks
	# new stripe in parent to migrate to - 1 lock
	# source and target - 2 locks
	# Total 5 locks for regular file
	#
	# NB: Overstriping should add several extra local locks
	# FIXME: Remove this once understood
	#lctl set_param *debug=-1 debug_mb=10000
	lctl clear
	lctl mark "touch/create"
	mkdir -p $DIR/$tdir
	local setcount=$((MDSCOUNT * $LMV_MAX_STRIPES_PER_MDT))
	local setcount=$((MDSCOUNT * 5))

	$LFS mkdir -i1 -C $setcount $DIR/$tdir/dir1
	touch $DIR/$tdir/dir1/eee

	lctl mark "hardlinks"
	# create 4 hardlink for 4 more locks
	# Total: 9 locks > RS_MAX_LOCKS (8)
	$LFS mkdir -i1 -c1 $DIR/$tdir/dir2
	$LFS mkdir -i1 -c1 $DIR/$tdir/dir3
	$LFS mkdir -i1 -c1 $DIR/$tdir/dir4
	$LFS mkdir -i1 -c1 $DIR/$tdir/dir5
	ln $DIR/$tdir/dir1/eee $DIR/$tdir/dir2/eee
	ln $DIR/$tdir/dir1/eee $DIR/$tdir/dir3/eee
	ln $DIR/$tdir/dir1/eee $DIR/$tdir/dir4/eee
	ln $DIR/$tdir/dir1/eee $DIR/$tdir/dir5/eee

	lctl mark "cancel lru"
	cancel_lru_locks mdc

	lctl mark "migrate"
	$LFS migrate -m1 -c1 $DIR/$tdir/dir1 ||
		error "migrate dir fails"

	rm -rf $DIR/$tdir || error "rm dir failed after migration"
}
run_test 300uf "migrate with too many local locks"

test_300ug() {
	(( max_stripes_per_mdt > 0 )) ||
		skip "skipped for MDS that doesn't support metadata overstripe"
	(( MDSCOUNT > 1 )) || skip "needs >= 2 MDTs"

	mkdir -p $DIR/$tdir
	local migrate_dir=$DIR/$tdir/migrate_dir
	local setcount=$((MDSCOUNT * $LMV_MAX_STRIPES_PER_MDT))
	local setcount2=$((setcount - 2))

	$LFS setdirstripe -c 2 $migrate_dir ||
		error "(0) failed to create striped directory"

	$LFS migrate -m 0 -C $setcount $migrate_dir ||
		error "(1)failed to migrate to overstriped directory"
	local getstripe_count=$($LFS getdirstripe -c $migrate_dir)

	(( getstripe_count == setcount )) ||
		error "(2)stripe_count is $getstripe_count, expect $setcount"
	touch $DIR/$tdir/migrate_dir/$tfile ||
		error "(3)failed to create file in overstriped directory"
	$LFS migrate -m 0 -C $setcount2 $migrate_dir ||
		error "(4)failed to migrate overstriped directory"
	# Check stripe count after migration
	$LFS getdirstripe $migrate_dir
	getstripe_count=$($LFS getdirstripe -c $migrate_dir)
	(( getstripe_count == setcount2 )) ||
		error "(5)stripe_count is $getstripe_count, expect $setcount2"

	rm -rf $migrate_dir || error "(6) unable to rm overstriped dir"
}
run_test 300ug "migrate overstriped dirs"

test_300uh() {
	(( max_stripes_per_mdt > 0 )) ||
		skip "skipped for MDS that doesn't support metadata overstripe"
	(( MDSCOUNT > 1 )) || skip "needs >= 2 MDTs"

	local mdts=$(mdts_nodes)
	local val=$(do_facet mds1 $LCTL get_param -n \
		    lod.$FSNAME-MDT0000-mdtlov.max_stripes_per_mdt)

	stack_trap "do_nodes $mdts $LCTL set_param -n \
		    lod.$FSNAME-MDT*.max_stripes_per_mdt=$val"

	# create 5 stripes will be silently clamped down
	do_nodes $mdts $LCTL set_param -n \
		lod.$FSNAME-MDT*.max_stripes_per_mdt=2
	$LFS setdirstripe -C $((MDSCOUNT * 5)) $DIR/$tdir ||
		error "mkdir $tdir failed"
	$LFS getdirstripe -H $DIR/$tdir | grep overstriped ||
		error "overstriped flag not found"

	local count=$($LFS getdirstripe -c $DIR/$tdir)

	((count == 2 * MDSCOUNT)) || error "count $count != $((2 * MDSCOUNT))"

	# create 3 stripes on MDT0 should fail
	$LFS setdirstripe -i 0,0,0 $DIR/$tdir/sub && error "mkdir sub succeeded"

	# OVERSTRIPED flag will be cleared if not really overstriped
	$LFS setdirstripe -C $MDSCOUNT $DIR/$tdir/sub ||
		error "mkdir sub failed"
	$LFS getdirstripe -H $DIR/$tdir/sub | grep -v overstriped ||
		error "overstriped flag found"
}
run_test 300uh "overstripe tunable max_stripes_per_mdt"

test_300ui() {
	(( max_stripes_per_mdt > 0 )) ||
		skip "skipped for MDS that doesn't support metadata overstripe"
	(( MDSCOUNT == 1 )) || skip "1 MDT only"

	$LFS setdirstripe -C 2 $DIR/$tdir && error "mkdir $tdir succeeded" ||
		true
}
run_test 300ui "overstripe is not supported on one MDT system"

test_300uj() {
	(( MDSCOUNT > 1 )) || skip "needs >= 2 MDTs"
	(( MDS1_VERSION >= $(version_code 2.16.0) )) ||
		skip "need MDS >= 2.16.0 for llog timestamps"

	local setcount=-2
	local expected_count=$((MDSCOUNT * 2))

	mkdir $DIR/$tdir
	$LFS mkdir -C $setcount $DIR/$tdir/${tdir}.0 ||
		error "(0) failed overstriped dir creation with -C -N test"
	local getstripe_count=$($LFS getdirstripe -c $DIR/$tdir/${tdir}.0)
	(( getstripe_count == expected_count )) ||
		error "(1) incorrect stripe count for -C -N overstriped dir"
	rm -f $DIR/$tdir/${tdir}.0

	# limit testing
	setcount=-6
	$LFS setdirstripe -C $setcount $DIR/$tdir/${tdir}.1 2>&1 |
		grep "invalid stripe count" ||
		error "(0) failed overstriped dir creation limit test"
}
run_test 300uj "overstriped dir with -C -N sanity test"

(( max_stripes_per_mdt == 0 )) ||
	do_nodes $(mdts_nodes) $LCTL set_param -n \
		lod.$FSNAME-MDT*.max_stripes_per_mdt=$max_stripes_per_mdt

prepare_remote_file() {
	mkdir $DIR/$tdir/src_dir ||
		error "create remote source failed"

	cp /etc/hosts $DIR/$tdir/src_dir/a ||
		 error "cp to remote source failed"
	touch $DIR/$tdir/src_dir/a

	$LFS mkdir -i 1 $DIR/$tdir/tgt_dir ||
		error "create remote target dir failed"

	touch $DIR/$tdir/tgt_dir/b

	mrename $DIR/$tdir/src_dir/a $DIR/$tdir/tgt_dir/b ||
		error "rename dir cross MDT failed!"

	$CHECKSTAT -t file $DIR/$tdir/src_dir/a &&
		error "src_child still exists after rename"

	$CHECKSTAT -t file $DIR/$tdir/tgt_dir/b ||
		error "missing file(a) after rename"

	diff /etc/hosts $DIR/$tdir/tgt_dir/b ||
		error "diff after rename"
}

test_310a() {
	[[ $MDSCOUNT -lt 2 ]] && skip_env "needs >= 4 MDTs"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	local remote_file=$DIR/$tdir/tgt_dir/b

	mkdir -p $DIR/$tdir

	prepare_remote_file || error "prepare remote file failed"

	#open-unlink file
	$OPENUNLINK $remote_file $remote_file ||
		error "openunlink $remote_file failed"
	$CHECKSTAT -a $remote_file || error "$remote_file exists"
}
run_test 310a "open unlink remote file"

test_310b() {
	[[ $MDSCOUNT -lt 2 ]] && skip_env "needs >= 4 MDTs"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	local remote_file=$DIR/$tdir/tgt_dir/b

	mkdir -p $DIR/$tdir

	prepare_remote_file || error "prepare remote file failed"

	ln $remote_file $DIR/$tfile || error "link failed for remote file"
	$MULTIOP $DIR/$tfile Ouc || error "mulitop failed"
	$CHECKSTAT -t file $remote_file || error "check file failed"
}
run_test 310b "unlink remote file with multiple links while open"

test_310c() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[[ $MDSCOUNT -lt 4 ]] && skip_env "needs >= 4 MDTs"

	local remote_file=$DIR/$tdir/tgt_dir/b

	mkdir -p $DIR/$tdir

	prepare_remote_file || error "prepare remote file failed"

	ln $remote_file $DIR/$tfile || error "link failed for remote file"
	multiop_bg_pause $remote_file O_uc ||
			error "mulitop failed for remote file"
	MULTIPID=$!
	$MULTIOP $DIR/$tfile Ouc
	kill -USR1 $MULTIPID
	wait $MULTIPID
}
run_test 310c "open-unlink remote file with multiple links"

#LU-4825
test_311() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ $OSTCOUNT -lt 2 ] && skip "needs >= 2 OSTs"
	[ $MDS1_VERSION -lt $(version_code 2.8.54) ] &&
		skip "lustre < 2.8.54 does not contain LU-4825 fix"
	remote_mds_nodsh && skip "remote MDS with nodsh"

	local old_iused=$($LFS df -i --output=iused --ost=0)
	echo "old_iused=$old_iused"
	local mdts=$(mdts_nodes)

	mkdir -p $DIR/$tdir
	$LFS setstripe -i 0 -c 1 $DIR/$tdir
	createmany -o $DIR/$tdir/$tfile. 1000

	# statfs data is not real time, let's just calculate it
	old_iused=$((old_iused + 1000))
	echo "suppose current old_iused=$old_iused"

	local count=$(do_facet $SINGLEMDS "$LCTL get_param -n \
			osp.*OST0000*MDT0000.create_count")
	local max_count=$(do_facet $SINGLEMDS "$LCTL get_param -n \
				osp.*OST0000*MDT0000.max_create_count")
	echo "create_count=$count, max_create_count=$max_count"
	do_nodes $mdts "$LCTL set_param -n osp.*OST0000*.max_create_count=0"

	$LFS setstripe -i 0 $DIR/$tdir/$tfile || error "setstripe failed"
	local index=$($LFS getstripe -i $DIR/$tdir/$tfile)
	[ $index -ne 0 ] || error "$tfile stripe index is 0"

	unlinkmany $DIR/$tdir/$tfile. 1000
	wait_delete_completed
	wait_zfs_commit $SINGLEMDS 20

	do_nodes $mdts "$LCTL set_param -n \
			osp.*OST0000*.max_create_count=$max_count"
	[ $MDS1_VERSION -lt $(version_code 2.12.51) ] &&
		do_nodes $mdts "$LCTL set_param -n \
				osp.*OST0000*.create_count=$count"
	do_nodes $mdts "$LCTL get_param osp.*OST0000*.create_count" |
			grep "=0" && error "create_count is zero"

	local new_iused
	for i in $(seq 120); do
		new_iused=$($LFS df --output=iused --ost=0)
		echo -n "$new_iused "
		# system may be too busy to destroy all objs in time, use
		# a somewhat small value to not fail autotest
		((old_iused - new_iused > 400)) && break
		sleep 1
	done

	echo -e "\nwaited $i sec, old Iused $old_iused, new Iused $new_iused"
	((old_iused - new_iused > 400)) ||
		error "objs not destroyed after unlink"
}
run_test 311 "disable OSP precreate, and unlink should destroy objs"

zfs_get_objid()
{
	local ost=$1
	local tf=$2
	local fid=($($LFS getstripe $tf | grep 0x))
	local seq=${fid[3]#0x}
	local objid=${fid[1]}

	local vdevdir=$(dirname $(facet_vdevice $ost))
	local cmd="$ZDB -e -p $vdevdir -ddddd $(facet_device $ost)"
	local zfs_zapid=$(do_facet $ost $cmd |
			  grep -w "/O/$seq/d$((objid%32))" -C 5 |
			  awk '/Object/{getline; print $1}')
	local zfs_objid=$(do_facet $ost $cmd $zfs_zapid |
			  awk "/$objid = /"'{printf $3}')

	echo $zfs_objid
}

zfs_object_blksz() {
	local ost=$1
	local objid=$2

	local vdevdir=$(dirname $(facet_vdevice $ost))
	local cmd="$ZDB -e -p $vdevdir -dddd $(facet_device $ost)"
	local blksz=$(do_facet $ost $cmd $objid |
		      awk '/dblk/{getline; printf $4}')

	case "${blksz: -1}" in
		k|K) blksz=$((${blksz:0:$((${#blksz} - 1))}*1024)) ;;
		m|M) blksz=$((${blksz:0:$((${#blksz} - 1))}*1024*1024)) ;;
		*) ;;
	esac

	echo $blksz
}

test_312() { # LU-4856
	remote_ost_nodsh && skip "remote OST with nodsh"
	[[ "$ost1_FSTYPE" == "zfs" ]] || skip "the test only applies to zfs"

	local max_blksz=$(do_facet ost1 \
			  $ZFS get -p recordsize $(facet_device ost1) |
			  awk '!/VALUE/{print $3}')
	local tf=$DIR/$tfile

	$LFS setstripe -c1 $tf
	local facet="ost$(($($LFS getstripe -i $tf) + 1))"

	# Get ZFS object id
	local zfs_objid=$(zfs_get_objid $facet $tf)
	# block size change by sequential overwrite
	local bs

	for ((bs=$PAGE_SIZE; bs <= max_blksz; bs *= 4)) ; do
		dd if=/dev/zero of=$tf bs=$bs count=1 oflag=sync conv=notrunc

		local blksz=$(zfs_object_blksz $facet $zfs_objid)
		[[ $blksz -eq $bs ]] || error "blksz error: $blksz, expected: $bs"
	done
	rm -f $tf

	$LFS setstripe -c1 $tf
	facet="ost$(($($LFS getstripe -i $tf) + 1))"

	# block size change by sequential append write
	dd if=/dev/zero of=$tf bs=$PAGE_SIZE count=1 oflag=sync conv=notrunc
	zfs_objid=$(zfs_get_objid $facet $tf)
	local count

	for ((count = 1; count < $((max_blksz / PAGE_SIZE)); count *= 2)); do
		dd if=/dev/zero of=$tf bs=$PAGE_SIZE count=$count seek=$count \
			oflag=sync conv=notrunc

		blksz=$(zfs_object_blksz $facet $zfs_objid)
		(( $blksz == 2 * count * PAGE_SIZE )) ||
			error "blksz error, actual $blksz, " \
				"expected: 2 * $count * $PAGE_SIZE"
	done
	rm -f $tf

	# random write
	$LFS setstripe -c1 $tf
	facet="ost$(($($LFS getstripe -i $tf) + 1))"
	zfs_objid=$(zfs_get_objid $facet $tf)

	dd if=/dev/zero of=$tf bs=1K count=1 oflag=sync conv=notrunc
	blksz=$(zfs_object_blksz $facet $zfs_objid)
	(( blksz == PAGE_SIZE )) ||
		error "blksz error: $blksz, expected: $PAGE_SIZE"

	dd if=/dev/zero of=$tf bs=64K count=1 oflag=sync conv=notrunc seek=128
	blksz=$(zfs_object_blksz $facet $zfs_objid)
	(( blksz == 65536 )) || error "blksz error: $blksz, expected: 64k"

	dd if=/dev/zero of=$tf bs=1M count=1 oflag=sync conv=notrunc
	blksz=$(zfs_object_blksz $facet $zfs_objid)
	(( blksz == 65536 )) || error "rewrite error: $blksz, expected: 64k"
}
run_test 312 "make sure ZFS adjusts its block size by write pattern"

test_313() {
	remote_ost_nodsh && skip "remote OST with nodsh"

	local file=$DIR/$tfile

	rm -f $file
	$LFS setstripe -c 1 -i 0 $file || error "setstripe failed"

	# define OBD_FAIL_TGT_RCVD_EIO		 0x720
	do_facet ost1 "$LCTL set_param fail_loc=0x720"
	dd if=/dev/zero of=$file bs=$PAGE_SIZE oflag=direct count=1 &&
		error "write should failed"
	do_facet ost1 "$LCTL set_param fail_loc=0"
	rm -f $file
}
run_test 313 "io should fail after last_rcvd update fail"

test_314() {
	[ $OSTCOUNT -lt 2 ] && skip "needs >= 2 OSTs"

	$LFS setstripe -c 2 -i 0 $DIR/$tfile || error "setstripe failed"
	do_facet ost1 "$LCTL set_param fail_loc=0x720"
	rm -f $DIR/$tfile
	wait_delete_completed
	do_facet ost1 "$LCTL set_param fail_loc=0"
}
run_test 314 "OSP shouldn't fail after last_rcvd update failure"

test_315() { # LU-618
	[ -f /proc/$$/io ] || skip_env "no IO accounting in kernel"

	local file=$DIR/$tfile
	rm -f $file

	$MULTIOP $file oO_CREAT:O_DIRECT:O_RDWR:w4063232c ||
		error "multiop file write failed"
	$MULTIOP $file oO_RDONLY:r4063232_c &
	PID=$!

	sleep 2

	local rbytes=$(awk '/read_bytes/ { print $2 }' /proc/$PID/io)
	kill -USR1 $PID

	[ $rbytes -gt 4000000 ] || error "read is not accounted ($rbytes)"
	rm -f $file
}
run_test 315 "read should be accounted"

test_316() {
	(( $MDSCOUNT >= 2 )) || skip "needs >= 2 MDTs"
	large_xattr_enabled || skip "ea_inode feature disabled"

	mkdir_on_mdt0 $DIR/$tdir || error "mkdir $tdir failed"
	mkdir $DIR/$tdir/d || error "mkdir $tdir/d failed"
	chown nobody $DIR/$tdir/d || error "chown $tdir/d failed"
	touch $DIR/$tdir/d/$tfile || error "touch $tdir/d/$tfile failed"

	$LFS migrate -m1 $DIR/$tdir/d || error "lfs migrate -m1 failed"
}
run_test 316 "lfs migrate of file with large_xattr enabled"

test_317() {
	[ $MDS1_VERSION -lt $(version_code 2.11.53) ] &&
		skip "Need MDS version at least 2.11.53"
	if [ "$ost1_FSTYPE" == "zfs" ]; then
		skip "LU-10370: no implementation for ZFS"
	fi

	local trunc_sz
	local grant_blk_size

	grant_blk_size=$($LCTL get_param osc.$FSNAME*.import |
			awk '/grant_block_size:/ { print $2; exit; }')
	#
	# Create File of size 5M. Truncate it to below size's and verify
	# blocks count.
	#
	dd if=/dev/zero of=$DIR/$tfile bs=5M count=1 conv=fsync ||
		error "Create file $DIR/$tfile failed"
	stack_trap "rm -f $DIR/$tfile" EXIT

	for trunc_sz in 2097152 4097 4000 509 0; do
		$TRUNCATE $DIR/$tfile $trunc_sz ||
			error "truncate $tfile to $trunc_sz failed"
		local sz=$(stat --format=%s $DIR/$tfile)
		local blk=$(stat --format=%b $DIR/$tfile)
		local trunc_blk=$((((trunc_sz + (grant_blk_size - 1) ) /
				     grant_blk_size) * 8))

		if [[ $blk -ne $trunc_blk ]]; then
			$(which stat) $DIR/$tfile
			error "Expected Block $trunc_blk got $blk for $tfile"
		fi

		$CHECKSTAT -s $trunc_sz $DIR/$tfile ||
			error "Expected Size $trunc_sz got $sz for $tfile"
	done

	#
	# sparse file test
	# Create file with a hole and write actual 65536 bytes which aligned
	# with 4K and 64K PAGE_SIZE. Block count must be 128.
	#
	local bs=65536
	dd if=/dev/zero of=$DIR/$tfile bs=$bs count=1 seek=5 conv=fsync ||
		error "Create file : $DIR/$tfile"

	#
	# Truncate to size $trunc_sz bytes. Strip tail blocks and leave only 8
	# blocks. The block count must drop to 8.
	#
	trunc_sz=$(($(stat --format=%s $DIR/$tfile) -
		((bs - grant_blk_size) + 1)))
	$TRUNCATE $DIR/$tfile $trunc_sz ||
		error "truncate $tfile to $trunc_sz failed"

	local trunc_bsz=$((grant_blk_size / $(stat --format=%B $DIR/$tfile)))
	sz=$(stat --format=%s $DIR/$tfile)
	blk=$(stat --format=%b $DIR/$tfile)

	if [[ $blk -ne $trunc_bsz ]]; then
		$(which stat) $DIR/$tfile
		error "Expected Block $trunc_bsz got $blk for $tfile"
	fi

	$CHECKSTAT -s $trunc_sz $DIR/$tfile ||
		error "Expected Size $trunc_sz got $sz for $tfile"
}
run_test 317 "Verify blocks get correctly update after truncate"

test_318() {
	local llite_name="llite.$($LFS getname $MOUNT | awk '{print $1}')"
	local old_max_active=$($LCTL get_param -n \
			    ${llite_name}.max_read_ahead_async_active \
			    2>/dev/null)

	$LCTL set_param llite.*.max_read_ahead_async_active=256
	local max_active=$($LCTL get_param -n \
			   ${llite_name}.max_read_ahead_async_active \
			   2>/dev/null)
	[ $max_active -ne 256 ] && error "expected 256 but got $max_active"

	$LCTL set_param llite.*.max_read_ahead_async_active=0 ||
		error "set max_read_ahead_async_active should succeed"

	$LCTL set_param llite.*.max_read_ahead_async_active=512
	max_active=$($LCTL get_param -n \
		     ${llite_name}.max_read_ahead_async_active 2>/dev/null)
	[ $max_active -eq 512 ] || error "expected 512 but got $max_active"

	# restore @max_active
	[ $old_max_active -ne 0 ] && $LCTL set_param \
		llite.*.max_read_ahead_async_active=$old_max_active

	local old_threshold=$($LCTL get_param -n \
		${llite_name}.read_ahead_async_file_threshold_mb 2>/dev/null)
	local max_per_file_mb=$($LCTL get_param -n \
		${llite_name}.max_read_ahead_per_file_mb 2>/dev/null)

	local invalid=$(($max_per_file_mb + 1))
	$LCTL set_param \
		llite.*.read_ahead_async_file_threshold_mb=$invalid\
			&& error "set $invalid should fail"

	local valid=$(($invalid - 1))
	$LCTL set_param \
		llite.*.read_ahead_async_file_threshold_mb=$valid ||
			error "set $valid should succeed"
	local threshold=$($LCTL get_param -n \
		${llite_name}.read_ahead_async_file_threshold_mb 2>/dev/null)
	[ $threshold -eq $valid ] || error \
		"expect threshold $valid got $threshold"
	$LCTL set_param \
		llite.*.read_ahead_async_file_threshold_mb=$old_threshold
}
run_test 318 "Verify async readahead tunables"

test_319() {
	(( $MDSCOUNT >= 2 )) || skip "needs >= 2 MDTs"

	local before=$(date +%s)
	local evict
	local mdir=$DIR/$tdir
	local file=$mdir/xxx

	$LFS mkdir -i0 $mdir || error "mkdir $mdir fails"
	touch $file

#define OBD_FAIL_LDLM_LOCAL_CANCEL_PAUSE 0x32c
	$LCTL set_param fail_val=5 fail_loc=0x8000032c
	$LFS migrate -m1 $mdir &

	sleep 1
	dd if=$file of=/dev/null
	wait
	evict=$($LCTL get_param mdc.$FSNAME-MDT*.state |
	  awk -F"[ [,]" '/EVICTED ]$/ { if (mx<$5) {mx=$5;} } END { print mx }')

	[ -z "$evict" ] || [[ $evict -le $before ]] || error "eviction happened"
}
run_test 319 "lost lease lock on migrate error"

test_350() {
	local mdts=$(mdts_nodes)

	mkdir $DIR/$tdir || error "mkdir $DIR/$tdir failed"
	stack_trap "rm -r $DIR/$tdir"

	#force 1/100 of replies to take "NID mismatch" codepath
	#define CFS_FAIL_MATCH_MD_NID 0xe001  CFS_FAIL_SOME 0x10000000
	do_nodes $mdts $LCTL set_param fail_loc=0x1000e001 fail_val=100

	while ls -lR $DIR/$tdir > /dev/null; do :; done &
	stack_trap "killall -9 ls || killall -9 ls"

	cp -a /etc $DIR/$tdir || error "cp failed"
}
run_test 350 "force NID mismatch path to be exercised"

test_398a() { # LU-4198
	local ost1_imp=$(get_osc_import_name client ost1)
	local imp_name=$($LCTL list_param osc.$ost1_imp | head -n1 |
			 cut -d'.' -f2)

	$LFS setstripe -c 1 -i 0 $DIR/$tfile
	stack_trap "rm -f $DIR/$tfile"
	$LCTL set_param ldlm.namespaces.*.lru_size=clear

	# request a new lock on client
	dd if=/dev/zero of=$DIR/$tfile bs=1M count=1

	dd if=/dev/zero of=$DIR/$tfile bs=1M count=1 oflag=direct conv=notrunc
	local lock_count=$($LCTL get_param -n \
			   ldlm.namespaces.$imp_name.lru_size)
	[[ $lock_count -eq 0 ]] || error "lock should be cancelled by direct IO"

	$LCTL set_param ldlm.namespaces.$imp_name.lru_size=clear

	# no lock cached, should use lockless DIO and not enqueue new lock
	dd if=/dev/zero of=$DIR/$tfile bs=1M count=1 oflag=direct conv=notrunc
	lock_count=$($LCTL get_param -n \
		     ldlm.namespaces.$imp_name.lru_size)
	[[ $lock_count -eq 0 ]] || error "no lock should be held by direct IO"

	$LCTL set_param ldlm.namespaces.$imp_name.lru_size=clear

	# no lock cached, should use locked DIO append
	dd if=/dev/zero of=$DIR/$tfile bs=1M count=1 oflag=direct oflag=append \
		conv=notrunc || error "DIO append failed"
	lock_count=$($LCTL get_param -n \
		     ldlm.namespaces.$imp_name.lru_size)
	[[ $lock_count -ne 0 ]] || error "lock still must be held by DIO append"
}
run_test 398a "direct IO should cancel lock otherwise lockless"

test_398b() { # LU-4198
	local before=$(date +%s)
	local njobs=4
	local size=48

	which fio || skip_env "no fio installed"
	$LFS setstripe -c -1 -S 1M $DIR/$tfile
	dd if=/dev/zero of=$DIR/$tfile bs=1M count=$size

	# Single page, multiple pages, stripe size, 4*stripe size
	for bsize in $(( $PAGE_SIZE )) $(( 4*$PAGE_SIZE )) 1048576 4194304; do
		echo "mix direct rw ${bsize} by fio with $njobs jobs..."
		fio --name=rand-rw --rw=randrw --bs=$bsize --direct=1 \
			--numjobs=$njobs --fallocate=none \
			--iodepth=16 --allow_file_create=0 \
			--size=$((size/njobs))M \
			--filename=$DIR/$tfile &
		bg_pid=$!

		echo "mix buffer rw ${bsize} by fio with $njobs jobs..."
		fio --name=rand-rw --rw=randrw --bs=$bsize \
			--numjobs=$njobs --fallocate=none \
			--iodepth=16 --allow_file_create=0 \
			--size=$((size/njobs))M \
			--filename=$DIR/$tfile || true
		wait $bg_pid
	done

	evict=$(do_facet client $LCTL get_param \
		osc.$FSNAME-OST*-osc-*/state |
	    awk -F"[ [,]" '/EVICTED ]$/ { if (t<$5) {t=$5;} } END { print t }')

	[ -z "$evict" ] || [[ $evict -le $before ]] ||
		(do_facet client $LCTL get_param \
			osc.$FSNAME-OST*-osc-*/state;
		    error "eviction happened: $evict before:$before")

	rm -f $DIR/$tfile
}
run_test 398b "DIO and buffer IO race"

test_398c() { # LU-4198
	local ost1_imp="osc.$(get_osc_import_name client ost1)"
	local imp_name=($($LCTL list_param $ost1_imp | cut -d'.' -f2))

	which fio || skip_env "no fio installed"

	saved_debug=$($LCTL get_param -n debug)
	$LCTL set_param debug=0

	local size=($($LCTL get_param -n $ost1_imp.kbytesavail))
	(( size /= 1024 )) # by megabytes
	(( size /= 2 )) # write half of the OST at most
	(( size <= 40 )) || size=40 #reduce test time anyway

	$LFS setstripe -c 1 $DIR/$tfile

	# it seems like ldiskfs reserves more space than necessary if the
	# writing blocks are not mapped, so it extends the file firstly
	dd if=/dev/zero of=$DIR/$tfile bs=1M count=$size && sync
	cancel_lru_locks osc

	# clear and verify rpc_stats later
	$LCTL set_param $ost1_imp.rpc_stats=clear

	local njobs=4
	echo "writing ${size}M to OST0 by fio with $njobs jobs..."
	fio --name=rand-write --rw=randwrite --bs=$PAGE_SIZE --direct=1 \
		--numjobs=$njobs --fallocate=none --ioengine=libaio \
		--iodepth=16 --allow_file_create=0 --size=$((size/njobs))M \
		--filename=$DIR/$tfile
	[ $? -eq 0 ] || error "fio write error"

	(( $($LCTL get_param -n ldlm.namespaces.$imp_name.lock_count) == 0 )) ||
		error "Locks were requested while doing AIO"

	# get the percentage of 1-page I/O
	pct=$($LCTL get_param osc.${imp_name}.rpc_stats |
		grep -A 1 'pages per rpc' | grep -v 'pages per rpc' |
		awk '{print $7}')
	(( $pct <= 50 )) || {
		$LCTL get_param osc.${imp_name}.rpc_stats
		error "$pct% of I/O are 1-page"
	}

	echo "mix rw ${size}M to OST0 by fio with $njobs jobs..."
	fio --name=rand-rw --rw=randrw --bs=$PAGE_SIZE --direct=1 \
		--numjobs=$njobs --fallocate=none --ioengine=libaio \
		--iodepth=16 --allow_file_create=0 --size=$((size/njobs))M \
		--filename=$DIR/$tfile
	[ $? -eq 0 ] || error "fio mixed read write error"

	echo "AIO with large block size ${size}M"
	fio --name=rand-rw --rw=randrw --bs=${size}M --direct=1 \
		--numjobs=1 --fallocate=none --ioengine=libaio \
		--iodepth=16 --allow_file_create=0 --size=${size}M \
		--filename=$DIR/$tfile
	[ $? -eq 0 ] || error "fio large block size failed"

	rm -f $DIR/$tfile
	$LCTL set_param debug="$saved_debug"
}
run_test 398c "run fio to test AIO"

test_398d() { #  LU-13846
	which aiocp || skip_env "no aiocp installed"
	local aio_file=$DIR/$tfile.aio

	$LFS setstripe -c -1 -S 1M $DIR/$tfile $aio_file

	dd if=/dev/urandom of=$DIR/$tfile bs=1M count=64
	aiocp -a $PAGE_SIZE -b 64M -s 64M -f O_DIRECT $DIR/$tfile $aio_file
	stack_trap "rm -f $DIR/$tfile $aio_file"

	diff $DIR/$tfile $aio_file || error "file diff after aiocp"

	# test memory unaligned aio
	# LU-18032 - unaligned AIO is disabled
	#aiocp -a 512 -b 64M -s 64M -f O_DIRECT $DIR/$tfile $aio_file ||
	#	error "unaligned aio failed"
	#diff $DIR/$tfile $aio_file || error "file diff after aiocp"

	rm -f $DIR/$tfile $aio_file
}
run_test 398d "run aiocp to verify block size > stripe size"

test_398e() {
	dd if=/dev/zero of=$DIR/$tfile bs=1234 count=1
	touch $DIR/$tfile.new
	dd if=$DIR/$tfile of=$DIR/$tfile.new bs=1M count=1 oflag=direct
}
run_test 398e "O_Direct open cleared by fcntl doesn't cause hang"

test_398f() { #  LU-14687
	which aiocp || skip_env "no aiocp installed"
	local aio_file=$DIR/$tfile.aio

	$LFS setstripe -c -1 -S 1M $DIR/$tfile $aio_file

	dd if=/dev/zero of=$DIR/$tfile bs=1M count=64
	stack_trap "rm -f $DIR/$tfile $aio_file"

	#define OBD_FAIL_LLITE_PAGE_ALLOC 0x1418
	$LCTL set_param fail_loc=0x1418
	# make sure we don't crash and fail properly
	aiocp -b 64M -s 64M -f O_DIRECT $DIR/$tfile $aio_file &&
		error "aio with page allocation failure succeeded"
	$LCTL set_param fail_loc=0
	diff $DIR/$tfile $aio_file
	[[ $? != 0 ]] || error "no diff after failed aiocp"
}
run_test 398f "verify aio handles ll_direct_rw_pages errors correctly"

# NB: To get the parallel DIO behavior in LU-13798, there must be > 1
# stripe and i/o size must be > stripe size
# Old style synchronous DIO waits after submitting each chunk, resulting in a
# single RPC in flight.  This test shows async DIO submission is working by
# showing multiple RPCs in flight.
test_398g() { #  LU-13798
	$LFS setstripe -o 0,0 -S 1M $DIR/$tfile

	# We need to do some i/o first to acquire enough grant to put our RPCs
	# in flight; otherwise a new connection may not have enough grant
	# available
	dd if=/dev/urandom of=$DIR/$tfile bs=8M count=1 oflag=direct ||
		error "parallel dio failed"
	stack_trap "rm -f $DIR/$tfile"

	# Reduce RPC size to 1M to avoid combination in to larger RPCs
	local pages_per_rpc=$($LCTL get_param osc.*-OST0000-*.max_pages_per_rpc)
	$LCTL set_param osc.*-OST0000-*.max_pages_per_rpc=1M
	stack_trap "$LCTL set_param -n $pages_per_rpc"

	# Recreate file so it's empty
	rm -f $DIR/$tfile
	$LFS setstripe -o 0,0 -S 1M $DIR/$tfile
	#Pause rpc completion to guarantee we see multiple rpcs in flight
	#define OBD_FAIL_OST_BRW_PAUSE_BULK
	do_facet ost1 $LCTL set_param fail_loc=0x214 fail_val=2
	stack_trap "do_facet ost1 $LCTL set_param fail_loc=0"

	# Clear rpc stats
	$LCTL set_param osc.*.rpc_stats=c

	dd if=/dev/urandom of=$DIR/$tfile bs=8M count=1 oflag=direct ||
		error "parallel dio failed"
	stack_trap "rm -f $DIR/$tfile"

	$LCTL get_param osc.*-OST0000-*.rpc_stats
	pct=$($LCTL get_param osc.*-OST0000-*.rpc_stats |
		grep -A 8 'rpcs in flight' | grep -v 'rpcs in flight' |
		grep "8:" | awk '{print $8}')
	# We look at the "8 rpcs in flight" field, and verify A) it is present
	# and B) it includes all RPCs.  This proves we had 8 RPCs in flight,
	# as expected for an 8M DIO to a file with 1M stripes.
	# NB: There is occasionally a mystery extra write RPC to a different
	# file.  I can't identify why that's happening, so we set up a margin
	# of 1 RPC here, ie, 8/9 RPCs at this size, or ~88%
	[ $pct -gt 87 ] || error "we should see 8 RPCs in flight"

	# Verify turning off parallel dio works as expected
	# Clear rpc stats
	$LCTL set_param osc.*.rpc_stats=c
	$LCTL set_param llite.*.parallel_dio=0
	stack_trap '$LCTL set_param llite.*.parallel_dio=1'

	dd if=/dev/urandom of=$DIR/$tfile bs=8M count=1 oflag=direct ||
		error "dio with parallel dio disabled failed"

	# Ideally, we would see only one RPC in flight here, but there is an
	# unavoidable race between i/o completion and RPC in flight counting,
	# so while only 1 i/o is in flight at a time, the RPC in flight counter
	# will sometimes exceed 1 (3 or 4 is not rare on VM testing).
	# So instead we just verify it's always < 8.
	$LCTL get_param osc.*-OST0000-*.rpc_stats
	ret=$($LCTL get_param osc.*-OST0000-*.rpc_stats |
		grep -A 8 'rpcs in flight' | grep -v 'rpcs in flight' |
		grep '^$' -B1 | grep . | awk '{print $1}')
	[ $ret != "8:" ] ||
		error "we should see fewer than 8 RPCs in flight (saw $ret)"
}
run_test 398g "verify parallel dio async RPC submission"

test_398h() { #  LU-13798
	local dio_file=$DIR/$tfile.dio

	$LFS setstripe -C 2 -S 1M $DIR/$tfile $dio_file

	dd if=/dev/urandom of=$DIR/$tfile bs=8M count=8 oflag=direct
	stack_trap "rm -f $DIR/$tfile $dio_file"

	dd if=$DIR/$tfile of=$dio_file bs=8M count=8 iflag=direct oflag=direct ||
		error "parallel dio failed"
	diff $DIR/$tfile $dio_file
	[[ $? == 0 ]] || error "file diff after aiocp"
}
run_test 398h "verify correctness of read & write with i/o size >> stripe size"

test_398i() { #  LU-13798
	local dio_file=$DIR/$tfile.dio

	$LFS setstripe -C 2 -S 1M $DIR/$tfile $dio_file

	dd if=/dev/urandom of=$DIR/$tfile bs=8M count=8 oflag=direct
	stack_trap "rm -f $DIR/$tfile $dio_file"

	#define OBD_FAIL_LLITE_PAGE_ALLOC 0x1418
	$LCTL set_param fail_loc=0x1418
	# make sure we don't crash and fail properly
	dd if=$DIR/$tfile of=$dio_file bs=8M count=8 iflag=direct oflag=direct &&
		error "parallel dio page allocation failure succeeded"
	diff $DIR/$tfile $dio_file
	[[ $? != 0 ]] || error "no diff after failed aiocp"
}
run_test 398i "verify parallel dio handles ll_direct_rw_pages errors correctly"

test_398j() { #  LU-13798
	# Stripe size > RPC size but less than i/o size tests split across
	# stripes and RPCs for individual i/o op
	$LFS setstripe -o 0,0 -S 4M $DIR/$tfile $DIR/$tfile.2

	# Reduce RPC size to 1M to guarantee split to multiple RPCs per stripe
	local pages_per_rpc=$($LCTL get_param osc.*-OST0000-*.max_pages_per_rpc)
	$LCTL set_param osc.*-OST0000-*.max_pages_per_rpc=1M
	stack_trap "$LCTL set_param -n $pages_per_rpc"

	dd if=/dev/urandom of=$DIR/$tfile bs=8M count=8 oflag=direct ||
		error "parallel dio write failed"
	stack_trap "rm -f $DIR/$tfile $DIR/$tfile.2"

	dd if=$DIR/$tfile of=$DIR/$tfile.2 bs=8M count=8 iflag=direct ||
		error "parallel dio read failed"
	diff $DIR/$tfile $DIR/$tfile.2
	[[ $? == 0 ]] || error "file diff after parallel dio read"
}
run_test 398j "test parallel dio where stripe size > rpc_size"

test_398k() { #  LU-13798
	wait_delete_completed
	wait_mds_ost_sync

	# 4 stripe file; we will cause out of space on OST0
	$LFS setstripe -o 0,1,0,1 -S 1M $DIR/$tfile

	# Fill OST0 (if it's not too large)
	ORIGFREE=$($LCTL get_param -n lov.$FSNAME-clilov-*.kbytesavail |
		   head -n1)
	if [[ $ORIGFREE -gt $MAXFREE ]]; then
		skip "$ORIGFREE > $MAXFREE skipping out-of-space test on OST0"
	fi
	$LFS setstripe -i 0 -c 1 $DIR/$tfile.1
	dd if=/dev/zero of=$DIR/$tfile.1 bs=1024 count=$MAXFREE &&
		error "dd should fill OST0"
	stack_trap "rm -f $DIR/$tfile.1"

	dd if=/dev/urandom of=$DIR/$tfile bs=8M count=8 oflag=direct
	err=$?

	ls -la $DIR/$tfile
	$CHECKSTAT -t file -s 0 $DIR/$tfile ||
		error "file is not 0 bytes in size"

	# dd above should not succeed, but don't error until here so we can
	# get debug info above
	[[ $err != 0 ]] ||
		error "parallel dio write with enospc succeeded"
	stack_trap "rm -f $DIR/$tfile"
}
run_test 398k "test enospc on first stripe"

test_398l() { #  LU-13798
	wait_delete_completed
	wait_mds_ost_sync
	# Clean up after the test
	stack_trap wait_delete_completed
	stack_trap wait_mds_ost_sync

	# 4 stripe file; we will cause out of space on OST0
	# Note the 1M stripe size and the > 1M i/o size mean this ENOSPC
	# happens on the second i/o chunk we issue
	$LFS setstripe -o 1,0,1,0 -S 1M $DIR/$tfile $DIR/$tfile.2

	dd if=/dev/urandom of=$DIR/$tfile bs=8M count=2 oflag=direct
	stack_trap "rm -f $DIR/$tfile"

	# Fill OST0 (if it's not too large)
	ORIGFREE=$($LCTL get_param -n lov.$FSNAME-clilov-*.kbytesavail |
		   head -n1)
	if [[ $ORIGFREE -gt $MAXFREE ]]; then
		skip "$ORIGFREE > $MAXFREE skipping out-of-space test on OST0"
	fi
	$LFS setstripe -i 0 -c 1 $DIR/$tfile.1
	dd if=/dev/zero of=$DIR/$tfile.1 bs=1024 count=$MAXFREE &&
		error "dd should fill OST0"
	stack_trap "rm -f $DIR/$tfile.1"

	dd if=$DIR/$tfile of=$DIR/$tfile.2 bs=8M count=8 oflag=direct
	err=$?
	stack_trap "rm -f $DIR/$tfile.2"

	# Check that short write completed as expected
	ls -la $DIR/$tfile.2
	$CHECKSTAT -t file -s 1048576 $DIR/$tfile.2 ||
		error "file is not 1M in size"

	# dd above should not succeed, but don't error until here so we can
	# get debug info above
	[[ $err != 0 ]] ||
		error "parallel dio write with enospc succeeded"

	# Truncate source file to same length as output file and diff them
	$TRUNCATE $DIR/$tfile 1048576
	diff $DIR/$tfile $DIR/$tfile.2
	[[ $? == 0 ]] || error "data incorrect after short write"
}
run_test 398l "test enospc on intermediate stripe/RPC"

test_398m() { #  LU-13798
	$LFS setstripe -o 0,1,0,1 -S 1M $DIR/$tfile

	# Set up failure on OST0, the first stripe:
	#define OBD_FAIL_OST_BRW_WRITE_BULK     0x20e
	#NB: Fail val is ost # + 1, because we cannot use cfs_fail_val = 0
	# OST0 is on ost1, OST1 is on ost2.
	# So this fail_val specifies OST0
	do_facet ost1 $LCTL set_param fail_loc=0x20e fail_val=1
	stack_trap "do_facet ost1 $LCTL set_param fail_loc=0"

	dd if=/dev/urandom of=$DIR/$tfile bs=8M count=8 oflag=direct &&
		error "parallel dio write with failure on first stripe succeeded"
	stack_trap "rm -f $DIR/$tfile"
	do_facet ost1 $LCTL set_param fail_loc=0 fail_val=0

	# Place data in file for read
	dd if=/dev/urandom of=$DIR/$tfile bs=8M count=8 oflag=direct ||
		error "parallel dio write failed"

	# Fail read on OST0, first stripe
	#define OBD_FAIL_OST_BRW_READ_BULK       0x20f
	do_facet ost1 $LCTL set_param fail_loc=0x20f fail_val=1
	dd if=$DIR/$tfile of=$DIR/$tfile.2 bs=8M count=8 iflag=direct &&
		error "parallel dio read with error on first stripe succeeded"
	rm -f $DIR/$tfile.2
	do_facet ost1 $LCTL set_param fail_loc=0 fail_val=0

	# Switch to testing on OST1, second stripe
	# Clear file contents, maintain striping
	echo > $DIR/$tfile
	# Set up failure on OST1, second stripe:
	do_facet ost2 $LCTL set_param fail_loc=0x20e fail_val=2
	stack_trap "do_facet ost2 $LCTL set_param fail_loc=0"

	dd if=/dev/urandom of=$DIR/$tfile bs=8M count=8 oflag=direct &&
		error "parallel dio write with failure on second stripe succeeded"
	stack_trap "rm -f $DIR/$tfile"
	do_facet ost2 $LCTL set_param fail_loc=0 fail_val=0

	# Place data in file for read
	dd if=/dev/urandom of=$DIR/$tfile bs=8M count=8 oflag=direct ||
		error "parallel dio write failed"

	# Fail read on OST1, second stripe
	#define OBD_FAIL_OST_BRW_READ_BULK       0x20f
	do_facet ost2 $LCTL set_param fail_loc=0x20f fail_val=2
	dd if=$DIR/$tfile of=$DIR/$tfile.2 bs=8M count=8 iflag=direct &&
		error "parallel dio read with error on second stripe succeeded"
	rm -f $DIR/$tfile.2
	do_facet ost2 $LCTL set_param fail_loc=0 fail_val=0
}
run_test 398m "test RPC failures with parallel dio"

# Parallel submission of DIO should not cause problems for append, but it's
# important to verify.
test_398n() { #  LU-13798
	$LFS setstripe -C 2 -S 1M $DIR/$tfile

	dd if=/dev/urandom of=$DIR/$tfile bs=8M count=8 ||
		error "dd to create source file failed"
	stack_trap "rm -f $DIR/$tfile"

	dd if=$DIR/$tfile of=$DIR/$tfile.1 bs=8M count=8 oflag=direct oflag=append ||
		error "parallel dio write with failure on second stripe succeeded"
	stack_trap "rm -f $DIR/$tfile $DIR/$tfile.1"
	diff $DIR/$tfile $DIR/$tfile.1
	[[ $? == 0 ]] || error "data incorrect after append"

}
run_test 398n "test append with parallel DIO"

test_398o() {
	directio rdwr $DIR/$tfile 0 1 1 || error "bad KMS"
}
run_test 398o "right kms with DIO"

test_398p()
{
	(( $OSTCOUNT >= 2 )) || skip "needs >= 2 OSTs"
	which aiocp || skip_env "no aiocp installed"

	local stripe_size=$((1024 * 1024)) #1 MiB
	# Max i/o below is ~ 4 * stripe_size, so this gives ~5 i/os
	local file_size=$((25 * stripe_size))

	$LFS setstripe -c 2 -S $stripe_size $DIR/$tfile.1
	stack_trap "rm -f $DIR/$tfile*"
	# Just a bit bigger than the largest size in the test set below
	dd if=/dev/urandom bs=$file_size count=1 of=$DIR/$tfile.1 ||
		error "buffered i/o to create file failed"

	for bs in $PAGE_SIZE $((PAGE_SIZE * 4)) $stripe_size \
		$((stripe_size * 4)); do

		$LFS setstripe -c 2 -S $stripe_size $DIR/$tfile.2

		echo "bs: $bs, file_size $file_size"
		aiocp -a $PAGE_SIZE -b $bs -s $file_size -f O_DIRECT \
			$DIR/$tfile.1 $DIR/$tfile.2 &
		pid_dio1=$!
		# Buffered I/O with similar but not the same block size
		dd if=$DIR/$tfile.1 bs=$((bs * 2)) of=$DIR/$tfile.2 \
			conv=notrunc &
		pid_bio2=$!
		wait $pid_dio1
		rc1=$?
		wait $pid_bio2
		rc2=$?
		if (( rc1 != 0 )); then
			error "aio copy 1 w/bsize $bs failed: $rc1"
		fi
		if (( rc2 != 0 )); then
			error "buffered copy 2 w/bsize $bs failed: $rc2"
		fi

		$CHECKSTAT -t file -s $file_size $DIR/$tfile.2 ||
			error "size incorrect"
		cmp --verbose $DIR/$tfile.1 $DIR/$tfile.2 ||
			error "files differ, bsize $bs"
		rm -f $DIR/$tfile.2
	done
}
run_test 398p "race aio with buffered i/o"

test_398q()
{
	(( $OSTCOUNT >= 2 )) || skip "needs >= 2 OSTs"

	local stripe_size=$((1024 * 1024)) #1 MiB
	# Max i/o below is ~ 4 * stripe_size, so this gives ~5 i/os
	local file_size=$((25 * stripe_size))

	$LFS setstripe -c 2 -S $stripe_size $DIR/$tfile.1
	$LFS setstripe -c 2 -S $stripe_size $DIR/$tfile.2

	# Just a bit bigger than the largest size in the test set below
	dd if=/dev/urandom bs=$file_size count=1 of=$DIR/$tfile.1 ||
		error "buffered i/o to create file failed"

	for bs in $PAGE_SIZE $((PAGE_SIZE * 4)) $stripe_size \
		$((stripe_size * 4)); do

		echo "bs: $bs, file_size $file_size"
		dd if=$DIR/$tfile.1 bs=$((bs *2 )) of=$DIR/$tfile.2 \
			conv=notrunc oflag=direct iflag=direct &
		pid_dio1=$!
		# Buffered I/O with similar but not the same block size
		dd if=$DIR/$tfile.1 bs=$((bs * 2)) of=$DIR/$tfile.2 \
			conv=notrunc &
		pid_bio2=$!
		wait $pid_dio1
		rc1=$?
		wait $pid_bio2
		rc2=$?
		if (( rc1 != 0 )); then
			error "dio copy 1 w/bsize $bs failed: $rc1"
		fi
		if (( rc2 != 0 )); then
			error "buffered copy 2 w/bsize $bs failed: $rc2"
		fi

		$CHECKSTAT -t file -s $file_size $DIR/$tfile.2 ||
			error "size incorrect"
		diff $DIR/$tfile.1 $DIR/$tfile.2 ||
			error "files differ, bsize $bs"
	done

	rm -f $DIR/$tfile*
}
run_test 398q "race dio with buffered i/o"

test_398r() {
	$LFS setstripe -i 0 -c 1 $DIR/$tfile || error "setstripe failed"
	echo "hello, world" > $DIR/$tfile

	cancel_lru_locks osc

#define OBD_FAIL_OST_BRW_READ_BULK       0x20f
	do_facet ost1 $LCTL set_param fail_loc=0x20f
	cat $DIR/$tfile > /dev/null && error "cat should fail"
	return 0
}
run_test 398r "i/o error on file read"

test_398s() {
	[[ $OSTCOUNT -ge 2 && "$ost1_HOST" = "$ost2_HOST" ]] ||
		skip "remote OST"

	$LFS mirror create -N -i 0 -c 1 -N -i 1 -c 1 $DIR/$tfile ||
		error "mirror create failed"

	echo "hello, world" > $DIR/$tfile
	$LFS mirror resync $DIR/$tfile || error "mirror resync failed"

	cancel_lru_locks osc

#define OBD_FAIL_OST_BRW_READ_BULK       0x20f
	do_facet ost1 $LCTL set_param fail_loc=0x20f
	cat $DIR/$tfile > /dev/null && error "cat should fail"
	return 0
}
run_test 398s "i/o error on mirror file read"

test_398t() { # LU-19536
	unaligned_dio_or_skip

	$LFS setstripe -c 1 $DIR/$tfile || error "setstripe failed"

	# Use a non-page-aligned block size to trigger unaligned
	# DIO path. The fail_loc makes ll_allocate_dio_buffer
	# fail after allocating the pages array, exercising the
	# cleanup path which had a double-free bug.
#define OBD_FAIL_LLITE_DIO_BUFFER_ALLOC       0x1438
	$LCTL set_param fail_loc=0x80001438

	dd if=/dev/zero of=$DIR/$tfile bs=1024 count=64 oflag=direct 2>/dev/null

	$LCTL set_param fail_loc=0
	# write may fail or succeed (if retried), but must not crash

	# verify the system is still functional
	echo "sanity check" > $DIR/$tfile || error "write after fail_loc failed"
}
run_test 398t "DIO buffer alloc failure must not crash (double-free)"

test_398u() { # LU-19536
	unaligned_dio_or_skip

	# Force ENOMEM mid-IO to exercise the drain+retry path.
	#
	# OBD_FAIL_LLITE_DIO_DRAIN_RETRY (0x1439) does two things:
	# 1) PRECHECK caps each sub_dio to PAGE_SIZE, so a single
	#    write() generates many loop iterations with in-flight
	#    sub_dios.
	# 2) CFS_FAIL_CHECK with SKIP|ONCE triggers ENOMEM in
	#    ll_allocate_dio_buffer after fail_val successes.
	#
	# With fail_val=5, iterations 1-5 succeed (tot_bytes > 0),
	# iteration 6 gets ENOMEM, and the drain+retry path fires.
	$LFS setstripe -c -1 $DIR/$tfile || error "setstripe"
#define OBD_FAIL_LLITE_DIO_DRAIN_RETRY        0x1439
	$LCTL set_param fail_loc=0xa0001439 fail_val=5

	# bs=4608 (4096+512): not page-aligned but 512-aligned for
	# O_DIRECT.  write 1 at offset 0 is page-aligned (regular
	# DIO), write 2 at offset 4608 is unaligned.  With sub_dios
	# capped to PAGE_SIZE, each unaligned write generates 2 loop
	# iterations (4096+512), so 3 unaligned writes = 6 alloc
	# calls.  fail_val=5 skips 5, fails the 6th — at which
	# point tot_bytes > 0 (one iteration succeeded in this
	# call), so drain+retry fires.
	dd if=/dev/zero of=$DIR/$tfile bs=$((PAGE_SIZE+512)) count=10 \
		oflag=direct || error "dd with drain retry failed"
	$LCTL set_param fail_loc=0

	local sz=$(stat -c %s $DIR/$tfile)
	(( sz == $((10 * (PAGE_SIZE+512))) )) ||
		error "file size $sz != expected $((10 * 4608))"
}
run_test 398u "DIO pool ENOMEM triggers drain and retry"

test_fake_rw() {
	local read_write=$1
	if [ "$read_write" = "write" ]; then
		local dd_cmd="dd if=/dev/zero of=$DIR/$tfile"
	elif [ "$read_write" = "read" ]; then
		local dd_cmd="dd of=/dev/null if=$DIR/$tfile"
	else
		error "argument error"
	fi

	# turn off debug for performance testing
	local saved_debug=$($LCTL get_param -n debug)
	$LCTL set_param debug=0

	$LFS setstripe -c 1 -i 0 $DIR/$tfile

	# get ost1 size - $FSNAME-OST0000
	local ost1_avail_size=$($LFS df $DIR | awk /${ost1_svc}/'{ print $4 }')
	local blocks=$((ost1_avail_size/2/1024)) # half avail space by megabytes
	[ $blocks -gt 1000 ] && blocks=1000 # 1G in maximum

	if [ "$read_write" = "read" ]; then
		$TRUNCATE $DIR/$tfile $(expr 1048576 \* $blocks)
	fi

	local start_time=$(date +%s.%N)
	$dd_cmd bs=1M count=$blocks oflag=sync ||
		error "real dd $read_write error"
	local duration=$(bc <<< "$(date +%s.%N) - $start_time")

	if [ "$read_write" = "write" ]; then
		rm -f $DIR/$tfile
	fi

	# define OBD_FAIL_OST_FAKE_RW		0x238
	do_facet ost1 $LCTL set_param fail_loc=0x238

	local start_time=$(date +%s.%N)
	$dd_cmd bs=1M count=$blocks oflag=sync ||
		error "fake dd $read_write error"
	local duration_fake=$(bc <<< "$(date +%s.%N) - $start_time")

	if [ "$read_write" = "write" ]; then
		# verify file size
		cancel_lru_locks osc
		$CHECKSTAT -t file -s $((blocks * 1024 * 1024)) $DIR/$tfile ||
			error "$tfile size not $blocks MB"
	fi
	do_facet ost1 $LCTL set_param fail_loc=0

	echo "fake $read_write $duration_fake vs. normal $read_write" \
		"$duration in seconds"
	[ $(bc <<< "$duration_fake < $duration") -eq 1 ] ||
		error_not_in_vm "fake write is slower"

	$LCTL set_param -n debug="$saved_debug"
	rm -f $DIR/$tfile
}
test_399a() { # LU-7655 for OST fake write
	remote_ost_nodsh && skip "remote OST with nodsh"

	test_fake_rw write
}
run_test 399a "fake write should not be slower than normal write"

test_399b() { # LU-8726 for OST fake read
	remote_ost_nodsh && skip "remote OST with nodsh"

	test_fake_rw read
}
run_test 399b "fake read should not be slower than normal read"

test_400a() { # LU-1606, was conf-sanity test_74
	if ! which $CC > /dev/null 2>&1; then
		skip_env "$CC is not installed"
	fi

	local extra_flags=''
	local out=$TMP/$tfile
	local prefix=/usr/include/lustre
	local prog

	# Oleg removes .c files in his test rig so test if any c files exist
	[[ -n "$(ls -A $LUSTRE_TESTS_API_DIR)" ]] ||
		skip_env "Needed .c test files are missing"

	if ! [[ -d $prefix ]]; then
		# Assume we're running in tree and fixup the include path.
		extra_flags+=" -I$LUSTRE/../lnet/include/uapi"
		extra_flags+=" -I$LUSTRE/include/uapi -I$LUSTRE/include"
		extra_flags+=" -L$LUSTRE/utils/.libs"
	fi

	for prog in $LUSTRE_TESTS_API_DIR/*.c; do
		$CC -Wall -Werror $extra_flags -o $out $prog -llustreapi ||
			error "client api broken"
	done
	rm -f $out
}
run_test 400a "Lustre client api program can compile and link"

test_400b() { # LU-1606, LU-5011
	local header
	local out=$TMP/$tfile
	local prefix=/usr/include/linux/lustre

	# We use a hard coded prefix so that this test will not fail
	# when run in tree. There are headers in lustre/include/lustre/
	# that are not packaged (like lustre_idl.h) and have more
	# complicated include dependencies (like config.h and lnet/types.h).
	# Since this test about correct packaging we just skip them when
	# they don't exist (see below) rather than try to fixup cppflags.

	if ! which $CC > /dev/null 2>&1; then
		skip_env "$CC is not installed"
	fi

	for header in $prefix/*.h; do
		if ! [[ -f "$header" ]]; then
			continue
		fi

		if [[ "$(basename $header)" == lustre_ioctl.h ]]; then
			continue # lustre_ioctl.h is internal header
		fi

		$CC -Wall -Werror -include $header -c -x c /dev/null -o $out ||
			error "cannot compile '$header'"
	done
	rm -f $out
}
run_test 400b "packaged headers can be compiled"

test_401a() { #LU-7437
	local printf_arg=$(find -printf 2>&1 | grep "unrecognized:")
	[ -n "$printf_arg" ] && skip_env "find does not support -printf"

	#count the number of parameters by "list_param -R"
	local params=$($LCTL list_param -R '*' 2>/dev/null | wc -l)
	#count the number of parameters by listing proc files
	local proc_dirs=$(eval \ls -d $proc_regexp 2>/dev/null)
	echo "proc_dirs='$proc_dirs'"
	[ -n "$proc_dirs" ] || error "no proc_dirs on $HOSTNAME"
	local procs=$(find -L $proc_dirs -mindepth 1 -printf '%P\n' 2>/dev/null|
		      sort -u | wc -l)

	[ $params -eq $procs ] ||
		error "found $params parameters vs. $procs proc files"

	# test the list_param -D option only returns directories
	params=$($LCTL list_param -R -D '*' 2>/dev/null | wc -l)
	#count the number of parameters by listing proc directories
	procs=$(find -L $proc_dirs -mindepth 1 -type d -printf '%P\n' 2>/dev/null |
		sort -u | wc -l)

	[ $params -eq $procs ] ||
		error "found $params parameters vs. $procs proc files '-D'"
}
run_test 401a "Verify if 'lctl list_param -R' can list parameters recursively"

test_401aa() {
	$LCTL list_param -p osc.* | while read path; do
		[[ -r $path ]] && echo "$path" || error "'$path' does not exist"
	done
}
run_test 401aa "Verify that 'lctl list_param -p' lists the correct path names"

test_401ab() {
	$LCTL list_param -pr "*" | while read path; do
		[[ -r $path ]] || error "'$path' not readable"
	done

	$LCTL list_param -pLr "*" | while read path; do
		[[ -r $path ]] || error "'$path' not readable (--no-links)"
	done
}
run_test 401ab "Check that 'lctl list_param -r' lists only readable params"

test_401ac() {
	$LCTL list_param -pw "*" | while read path; do
		[[ -w $path ]] || error "'$path' not writable"
	done

	$LCTL list_param -pLw "*" | while read path; do
		[[ -w $path ]] || error "'$path' not writable (--no-links)"
	done
}
run_test 401ac "Check that 'lctl list_param -w' lists only writable params"

test_401ad() {
	$LCTL list_param -prw "*" | while read path; do
		[[ -r $path && -w $path ]] ||
			error "'$path' not readable and writable"
	done

	$LCTL list_param -pLrw "*" | while read path; do
		[[ -r $path && -w $path ]] ||
			error "'$path' not readable and writable (--no-links)"
	done
}
run_test 401ad "Check that 'lctl list_param -wr' is conjunctive"

test_401b() {
	# jobid_var may not allow arbitrary values, so use jobid_name
	# if available
	if $LCTL list_param jobid_name > /dev/null 2>&1; then
		local jobvarname=jobid_name tmp='testing%p'
	else
		local jobvarname=jobid_var tmp=testing
	fi

	local save=$($LCTL get_param -n $jobvarname)

	$LCTL set_param foo=bar $jobvarname=$tmp bar=baz &&
		error "no error returned when setting bad parameters"

	local jobid_new=$($LCTL get_param -n foe $jobvarname baz)
	[[ "$jobid_new" == "$tmp" ]] || error "jobid tmp $jobid_new != $tmp"

	$LCTL set_param -n fog=bam $jobvarname=$save bat=fog
	local jobid_old=$($LCTL get_param -n foe $jobvarname bag)
	[[ "$jobid_old" == "$save" ]] || error "jobid new $jobid_old != $save"
}
run_test 401b "Verify 'lctl {get,set}_param' continue after error"

test_401c() {
	# jobid_var may not allow arbitrary values, so use jobid_name
	# if available
	if $LCTL list_param jobid_name > /dev/null 2>&1; then
		local jobvarname=jobid_name
	else
		local jobvarname=jobid_var
	fi

	local jobid_var_old=$($LCTL get_param -n $jobvarname)
	local jobid_var_new

	$LCTL set_param $jobvarname= &&
		error "no error returned for 'set_param a='"

	jobid_var_new=$($LCTL get_param -n $jobvarname)
	[[ "$jobid_var_old" == "$jobid_var_new" ]] ||
		error "$jobvarname was changed by setting without value"

	$LCTL set_param $jobvarname &&
		error "no error returned for 'set_param a'"

	jobid_var_new=$($LCTL get_param -n $jobvarname)
	[[ "$jobid_var_old" == "$jobid_var_new" ]] ||
		error "$jobvarname was changed by setting without value"
}
run_test 401c "Verify 'lctl set_param' without value fails in either format."

test_401d() {
	# jobid_var may not allow arbitrary values, so use jobid_name
	# if available
	if $LCTL list_param jobid_name > /dev/null 2>&1; then
		local jobvarname=jobid_name new_value='foo=bar%p'
	else
		local jobvarname=jobid_var new_value=foo=bar
	fi

	local jobid_var_old=$($LCTL get_param -n $jobvarname)
	local jobid_var_new

	$LCTL set_param $jobvarname=$new_value ||
		error "'set_param a=b' did not accept a value containing '='"

	jobid_var_new=$($LCTL get_param -n $jobvarname)
	[[ "$jobid_var_new" == "$new_value" ]] ||
		error "'set_param a=b' failed on a value containing '='"

	# Reset the $jobvarname to test the other format
	$LCTL set_param $jobvarname=$jobid_var_old
	jobid_var_new=$($LCTL get_param -n $jobvarname)
	[[ "$jobid_var_new" == "$jobid_var_old" ]] ||
		error "failed to reset $jobvarname"

	$LCTL set_param $jobvarname $new_value ||
		error "'set_param a b' did not accept a value containing '='"

	jobid_var_new=$($LCTL get_param -n $jobvarname)
	[[ "$jobid_var_new" == "$new_value" ]] ||
		error "'set_param a b' failed on a value containing '='"

	$LCTL set_param $jobvarname $jobid_var_old
	jobid_var_new=$($LCTL get_param -n $jobvarname)
	[[ "$jobid_var_new" == "$jobid_var_old" ]] ||
		error "failed to reset $jobvarname"
}
run_test 401d "Verify 'lctl set_param' accepts values containing '='"

cleanup_401db() {
	local saved_val=$1

	echo "start cleanup... "
	do_facet mgs $LCTL set_param -P at_min="$saved_val"
	wait_update $HOSTNAME "$LCTL get_param -n at_min" "$saved_val"
	echo "done"
}

test_401db() { #LU-9544
	local param="at_min"
	local saved_val=$($LCTL get_param -n $param)
	local new_val=$((saved_val + 6))

	stack_trap "cleanup_401db $saved_val"

	do_facet mgs $LCTL set_param -P $param=$new_val ||
		error "failed to set $param=$new_val"

	wait_update $HOSTNAME "$LCTL get_param -n $param" $new_val
	local expected=$($LCTL get_param -n $param)

	do_facet mgs $LCTL set_param -P -d $param=$new_val ||
		error "failed to delete $param"

	echo "Wait for erroneous changes"
	wait_update_cond $HOSTNAME "$LCTL get_param -n $param" != $new_val
	local result=$($LCTL get_param -n $param)

	! [[ "$result" =~ "=" ]] || {
		echo "result:$result"
		error "'lctl set_param -P -d a=b' added trailing '='"
	}

	[[ $result == $expected ]] || {
		echo -e "result:$result\nexpected:$expected"
		error "'lctl set_param -P -d a=b' changed value of a"
	}
}
run_test 401db "Verify 'lctl set_param' does not add trailing '='"

test_401e() { # LU-14779
	$LCTL list_param -R "ldlm.namespaces.MGC*" ||
		error "lctl list_param MGC* failed"
	$LCTL get_param "ldlm.namespaces.MGC*" || error "lctl get_param failed"
	$LCTL get_param "ldlm.namespaces.MGC*.lru_size" ||
		error "lctl get_param lru_size failed"
}
run_test 401e "verify 'lctl get_param' works with NID in parameter"

test_401fa() {
	$LCTL list_param -RpL "*" | while read path; do
		[[ ! -L $path ]] ||
			error "list_param -RpL returned the symlink: '$path'"
	done
}
run_test 401fa "check 'lctl list_param' doesn't follow symlinks with --no-links"

test_401fb() {
	local modules=$(ls /sys/module/{lnet,osc,mdd,obdclass,ofd,ptlrpc,mgc,ksocklnd,mdt,osd_ldiskfs,lquota}/parameters/* | wc -l)
	local params=$($LCTL list_param -M "*" | wc -l)
	local module_params=$($LCTL list_param -M --module "*" | wc -l)

	(( modules + params == module_params )) ||
		error "expected $((modules+params)) params, got $module_params"
}
run_test 401fb "check 'lctl {get,list,set}_param' only sees modules params with --module"

test_401ga() {
	local paramdir=/etc/lustre
	local fsnamefile=$paramdir/mount.$FSNAME.params
	local clientfile=$paramdir/mount.client.params

	local param1="osc.$FSNAME-OST0000-*.max_dirty_mb"
	local param2="at_max"

	local value1_new value2_new
	local value1_old=$($LCTL get_param -n $param1)
	local value2_old=$($LCTL get_param -n $param2)

	local value1_client=$(( value1_old - 1 ))
	local value1_fsname=$(( value1_old - 3 ))
	local value2_client=$(( value2_old - 10 ))
	local value2_fsname=$(( value2_old - 13 ))

	stack_trap "$LCTL set_param $param1=$value1_old"
	stack_trap "$LCTL set_param $param2=$value2_old"

	if [[ -e $fsnamefile ]]; then
		mv $fsnamefile $fsnamefile.$TESTNAME
		stack_trap "mv $fsnamefile.$TESTNAME $fsnamefile"
	else
		stack_trap "rm -f $fsnamefile"
	fi

	if [[ -e $clientfile ]]; then
		mv $clientfile $clientfile.$TESTNAME
		stack_trap "mv $clientfile.$TESTNAME $clientfile"
	else
		stack_trap "rm -f $clientfile"
	fi

	# do not allow bad params to be set
	$LCTL set_param --client $TESTNAME=$TESTNAME &&
		error "set $TESTNAME as param in $clientfile" || true

	# set garbage val to be overwritten
	$LCTL set_param --client $param1=$TESTNAME ||
		error "failed to set $param1 in $clientfile"

	$LCTL set_param --client $param1=$value1_client ||
		error "failed to overwrite $param1 in $clientfile"

	# nothing should be changed
	$LCTL set_param --client $param1=$value1_client ||
		error "error setting duplicate param $param1 in $clientfile"

	$LCTL set_param --client=$FSNAME $param1=$value1_fsname ||
		error "failed to set $param1 in $fsnamefile"

	$LCTL set_param --client=$FSNAME $param2=$value2_fsname &&
		error "set $param2 in $fsnamefile without containing $FSNAME" ||
		true

	$LCTL set_param --client $TESTNAME= $param2=$value2_client || true
	grep -q "$param2=$value2_client" $clientfile ||
		error "set_param -C did not continue after error"

	remount_client $MOUNT

	value1_new=$($LCTL get_param -n $param1)
	value2_new=$($LCTL get_param -n $param2)

	[[ "$value1_new" == "$value1_client" ]] &&
		error "$param1 not $value1_fsname, got client param $value1_new"
	[[ "$value1_new" == "$value1_fsname" ]] ||
		error "$param1 not $FSNAME param $value1_fsname, got $value1_new"
	[[ "$value2_new" == "$value2_client" ]] ||
		error "$param2 not client param $value2_client, got $value2_new"
}
run_test 401ga "check 'set_param -C' sets params upon mount"

test_401gb() {
	local paramdir=/etc/lustre
	local fsnamefile=$paramdir/mount.$FSNAME.params
	local clientfile=$paramdir/mount.client.params

	local param1="osc.$FSNAME-OST0000-*.max_dirty_mb"
	local param2="at_max"

	local value1_new value2_new
	local value1_old=$($LCTL get_param -n $param1)
	local value2_old=$($LCTL get_param -n $param2)

	local value1_client=$(( value1_old - 1 ))
	local value1_fsname=$(( value1_old - 3 ))
	local value2_client=$(( value2_old - 10 ))

	stack_trap "$LCTL set_param $param1=$value1_old"
	stack_trap "$LCTL set_param $param2=$value2_old"

	if [[ -e $fsnamefile ]]; then
		mv $fsnamefile $fsnamefile.$TESTNAME
		stack_trap "mv $fsnamefile.$TESTNAME $fsnamefile"
	else
		stack_trap "rm $fsnamefile"
	fi

	if [[ -e $clientfile ]]; then
		mv $clientfile $clientfile.$TESTNAME
		stack_trap "mv $clientfile.$TESTNAME $clientfile"
	else
		stack_trap "rm $clientfile"
	fi

	$LCTL set_param --client $param1=$value1_client $param2=$value2_client
	$LCTL set_param --client=$FSNAME $param1=$value1_fsname

	$LCTL set_param -d --client $TESTNAME=$TESTNAME ||
		error "error deleting bad param $TESTNAME from $clientfile"

	$LCTL set_param -d --client $param2 ||
		error "error deleting $param2 from $clientfile"

	$LCTL set_param -d --client=$FSNAME $param1 $param2 ||
		error "error deleting $param1 and $param2 from $fsnamefile"

	remount_client $MOUNT

	value1_new=$($LCTL get_param -n $param1)
	value2_new=$($LCTL get_param -n $param2)

	[[ "$value1_new" == "$value1_fsname" ]] &&
		error "$param1 not $value1_client, got $FSNAME param $value1_new"
	[[ "$value1_new" == "$value1_client" ]] ||
		error "$param1 not client param $value1_client, got $value1_new"
	[[ "$value2_new" == "$value2_old" ]] ||
		error "$param2 not $value2_old, got $value2_new"
}
run_test 401gb "check 'set_param -d -C' removes client params"

test_401gc() {
	local expected=$($LCTL list_param -R "*" | grep -c brw_stats)
	local actual=$($LCTL find_param -N brw_stats | wc -l)
	(( expected == actual )) ||
		error "expected $expected, but found $actual"

	expected="$($LCTL get_param checksum_speed)"
	actual="$($LCTL find_param check.*speed)"
	[[ "$expected" =~ "$actual" ]] ||
		error "expected '$expected', but found '$actual'"
}
run_test 401gc "check 'lctl find_param' can find params using regex"

test_401gd() {
	# Verify find_param only reads matching params (LU-20038)
	local strace_log=$TMP/$tfile.strace

	# find_param for 'memused' should not open brw_stats
	strace -e trace=openat -o $strace_log \
		$LCTL find_param memused > /dev/null

	# Should have found at least one match
	local count=$($LCTL find_param -N memused | wc -l)
	(( count >= 1 )) ||
		error "(0) find_param memused found no results"

	# brw_stats should NOT have been opened for reading
	grep -q "brw_stats.*O_RDONLY" $strace_log &&
		error "(1) brw_stats was opened, but should not be"

	# job_stats should NOT have been opened for reading
	grep -q "job_stats.*O_RDONLY" $strace_log &&
		error "(2) job_stats was opened, but should not be"

	# memused SHOULD have been opened
	grep -q "memused.*O_RDONLY" $strace_log ||
		error "(3) memused was not opened, but should be"

	rm -f $strace_log
}
run_test 401gd "check 'lctl find_param' does not read non-matching params"

test_402() {
	[[ $MDS1_VERSION -ge $(version_code 2.7.66) ]] ||
	[[ $MDS1_VERSION -ge $(version_code 2.7.18.4) &&
		$MDS1_VERSION -lt $(version_code 2.7.50) ]] ||
	[[ $MDS1_VERSION -ge $(version_code 2.7.2) &&
		$MDS1_VERSION -lt $(version_code 2.7.11) ]] ||
		skip "Need MDS version 2.7.2+ or 2.7.18.4+ or 2.7.66+"
	remote_mds_nodsh && skip "remote MDS with nodsh"

	$LFS setdirstripe -i 0 $DIR/$tdir || error "setdirstripe -i 0 failed"
#define OBD_FAIL_MDS_FLD_LOOKUP 0x15c
	do_facet mds1 "lctl set_param fail_loc=0x8000015c"
	touch $DIR/$tdir/$tfile && error "touch should fail with ENOENT" ||
		echo "Touch failed - OK"
}
run_test 402 "Return ENOENT to lod_generate_and_set_lovea"

test_403() {
	local file1=$DIR/$tfile.1
	local file2=$DIR/$tfile.2
	local tfile=$TMP/$tfile

	rm -f $file1 $file2 $tfile

	touch $file1
	ln $file1 $file2

	# 30 sec OBD_TIMEOUT in ll_getattr()
	# right before populating st_nlink
	$LCTL set_param fail_loc=0x80001409
	stat -c %h $file1 > $tfile &

	# create an alias, drop all locks and reclaim the dentry
	< $file2
	cancel_lru_locks mdc
	cancel_lru_locks osc
	sysctl -w vm.drop_caches=2

	wait

	[ $(cat $tfile) -gt 0 ] || error "wrong nlink count: $(cat $tfile)"

	rm -f $tfile $file1 $file2
}
run_test 403 "i_nlink should not drop to zero due to aliasing"

test_404() { # LU-6601
	[[ $MDS1_VERSION -ge $(version_code 2.8.53) ]] ||
		skip "Need server version newer than 2.8.52"
	remote_mds_nodsh && skip "remote MDS with nodsh"

	local mosps=$(do_facet $SINGLEMDS $LCTL dl |
		awk '/osp .*-osc-MDT/ { print $4}')

	local osp
	for osp in $mosps; do
		echo "Deactivate: " $osp
		do_facet $SINGLEMDS $LCTL --device %$osp deactivate
		wait_update_facet $SINGLEMDS \
			"$LCTL dl | awk -vp=$osp '\\\$4 == p { print \\\$2 }'" \
			"IN" 10 || error "deactivate error"
		echo "Activate: " $osp
		do_facet $SINGLEMDS $LCTL --device %$osp activate
		wait_update_facet $SINGLEMDS \
			"$LCTL dl | awk -vp=$osp '\\\$4 == p { print \\\$2 }'" \
			"UP" 10 || error "activate error"
	done
}
run_test 404 "validate manual {de}activated works properly for OSPs"

test_405() {
	[ -n "$FILESET" ] && skip "Not functional for FILESET set"
	[ $MDS1_VERSION -lt $(version_code 2.6.92) ] ||
		[ $CLIENT_VERSION -lt $(version_code 2.6.99) ] &&
			skip "Layout swap lock is not supported"

	check_swap_layouts_support
	check_swap_layout_no_dom $DIR

	test_mkdir $DIR/$tdir
	swap_lock_test -d $DIR/$tdir ||
		error "One layout swap locked test failed"
}
run_test 405 "Various layout swap lock tests"

test_406() {
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"
	[ $OSTCOUNT -lt 2 ] && skip_env "needs >= 2 OSTs"
	[ -n "$FILESET" ] && skip "SKIP due to FILESET set"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	[ $MDS1_VERSION -lt $(version_code 2.8.50) ] &&
		skip "Need MDS version at least 2.8.50"

	local def_stripe_size=$($LFS getstripe -S $MOUNT)
	local test_pool=$TESTNAME

	pool_add $test_pool || error "pool_add failed"
	pool_add_targets $test_pool 0 $(($OSTCOUNT - 1)) 1 ||
		error "pool_add_targets failed"

	save_layout_restore_at_exit $MOUNT

	# parent set default stripe count only, child will stripe from both
	# parent and fs default
	$LFS setstripe -c 1 -i 1 -S $((def_stripe_size * 2)) -p $test_pool $MOUNT ||
		error "setstripe $MOUNT failed"
	$LFS mkdir -c $MDSCOUNT $DIR/$tdir || error "mkdir $tdir failed"
	$LFS setstripe -c $OSTCOUNT $DIR/$tdir || error "setstripe $tdir failed"
	for i in $(seq 10); do
		local f=$DIR/$tdir/$tfile.$i
		touch $f || error "touch failed"
		local count=$($LFS getstripe -c $f)
		[ $count -eq $OSTCOUNT ] ||
			error "$f stripe count $count != $OSTCOUNT"
		local offset=$($LFS getstripe -i $f)
		[ $offset -eq 1 ] || error "$f stripe offset $offset != 1"
		local size=$($LFS getstripe -S $f)
		[ $size -eq $((def_stripe_size * 2)) ] ||
			error "$f stripe size $size != $((def_stripe_size * 2))"
		local pool=$($LFS getstripe -p $f)
		[ $pool == $test_pool ] || error "$f pool $pool != $test_pool"
	done

	# change fs default striping, delete parent default striping, now child
	# will stripe from new fs default striping only
	$LFS setstripe -c 1 -S $def_stripe_size -i 0 $MOUNT ||
		error "change $MOUNT default stripe failed"
	$LFS setstripe -c 0 $DIR/$tdir ||
		error "delete $tdir default stripe failed"
	for i in $(seq 11 20); do
		local f=$DIR/$tdir/$tfile.$i
		touch $f || error "touch $f failed"
		local count=$($LFS getstripe -c $f)
		[ $count -eq 1 ] || error "$f stripe count $count != 1"
		local offset=$($LFS getstripe -i $f)
		[ $offset -eq 0 ] || error "$f stripe offset $offset != 0"
		local size=$($LFS getstripe -S $f)
		[ $size -eq $def_stripe_size ] ||
			error "$f stripe size $size != $def_stripe_size"
		local pool=$($LFS getstripe -p $f)
		[ $pool == $test_pool ] || error "$f pool $pool isn't set"
	done

	unlinkmany $DIR/$tdir/$tfile. 1 20

	local f=$DIR/$tdir/$tfile
	pool_remove_all_targets $test_pool $f
	pool_remove $test_pool $f
}
run_test 406 "DNE support fs default striping"

test_407() {
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"
	[[ $MDS1_VERSION -lt $(version_code 2.8.55) ]] &&
		skip "Need MDS version at least 2.8.55"
	remote_mds_nodsh && skip "remote MDS with nodsh"

	$LFS mkdir -i 0 -c 1 $DIR/$tdir.0 ||
		error "$LFS mkdir -i 0 -c 1 $tdir.0 failed"
	$LFS mkdir -i 1 -c 1 $DIR/$tdir.1 ||
		error "$LFS mkdir -i 1 -c 1 $tdir.1 failed"
	touch $DIR/$tdir.0/$tfile.0 || error "touch $tdir.0/$tfile.0 failed"

	#define OBD_FAIL_DT_TXN_STOP	0x2019
	for idx in $(seq $MDSCOUNT); do
		do_facet mds$idx "lctl set_param fail_loc=0x2019"
	done
	$LFS mkdir -c 2 $DIR/$tdir && error "$LFS mkdir -c 2 $tdir should fail"
	mv $DIR/$tdir.0/$tfile.0 $DIR/$tdir.1/$tfile.1 &&
		error "mv $tdir.0/$tfile.0 $tdir.1/$tfile.1 should fail"
	true
}
run_test 407 "transaction fail should cause operation fail"

test_408() {
	dd if=/dev/zero of=$DIR/$tfile bs=$PAGE_SIZE count=1 oflag=direct

	#define OBD_FAIL_OSC_BRW_PREP_REQ2        0x40a
	lctl set_param fail_loc=0x8000040a
	# let ll_prepare_partial_page() fail
	dd if=/dev/zero of=$DIR/$tfile bs=2048 count=1 conv=notrunc || true

	rm -f $DIR/$tfile

	# create at least 100 unused inodes so that
	# shrink_icache_memory(0) should not return 0
	touch $DIR/$tfile-{0..100}
	rm -f $DIR/$tfile-{0..100}
	sync

	echo 2 > /proc/sys/vm/drop_caches
}
run_test 408 "drop_caches should not hang due to page leaks"

test_409()
{
	[ $MDSCOUNT -lt 2 ] && skip "needs >= 2 MDTs"

	mkdir -p $DIR/$tdir || error "(0) Fail to mkdir"
	$LFS mkdir -i 1 -c 2 $DIR/$tdir/foo || error "(1) Fail to mkdir"
	touch $DIR/$tdir/guard || error "(2) Fail to create"

	local PREFIX=$(str_repeat 'A' 128)
	echo "Create 1K hard links start at $(date)"
	createmany -l $DIR/$tdir/guard $DIR/$tdir/foo/${PREFIX}_ 1000 ||
		error "(3) Fail to hard link"

	echo "Links count should be right although linkEA overflow"
	stat $DIR/$tdir/guard || error "(4) Fail to stat"
	local linkcount=$(stat --format=%h $DIR/$tdir/guard)
	[ $linkcount -eq 1001 ] ||
		error "(5) Unexpected hard links count: $linkcount"

	echo "List all links start at $(date)"
	ls -l $DIR/$tdir/foo > /dev/null ||
		error "(6) Fail to list $DIR/$tdir/foo"

	echo "Unlink hard links start at $(date)"
	unlinkmany $DIR/$tdir/foo/${PREFIX}_ 1000 ||
		error "(7) Fail to unlink"
	echo "Unlink hard links finished at $(date)"
}
run_test 409 "Large amount of cross-MDTs hard links on the same file"

test_410()
{
	[[ $CLIENT_VERSION -lt $(version_code 2.9.59) ]] &&
		skip "Need client version at least 2.9.59"

	# Create a file, and stat it from the kernel
	local testfile=$DIR/$tfile
	touch $testfile

	local run_id=$RANDOM
	local my_ino=$(stat --format "%i" $testfile)

	# Try to insert the module.
	load_module kunit/kinode run_id=$run_id fname=$testfile ||
		error "load_module failed"

	# Anything but success is a test failure
	dmesg | grep -q \
	    "lustre_kinode_$run_id: inode numbers are identical: $my_ino" ||
	    error "no inode match"

	# Remove the test module
	rmmod -v kinode ||
		error "rmmod failed (may trigger a failure in a later test)"
}
run_test 410 "Test inode number returned from kernel thread"

cleanup_test411_cgroup() {
	trap 0
	cat $1/memory.stat
	rmdir "$1"
}

test_411a() {
	local cg_basedir=/sys/fs/cgroup/memory
	# LU-9966
	test -f "$cg_basedir/memory.kmem.limit_in_bytes" ||
		skip "no setup for cgroup"

	dd if=/dev/zero of=$DIR/$tfile bs=1M count=100 conv=fsync ||
		error "test file creation failed"
	cancel_lru_locks osc

	# Create a very small memory cgroup to force a slab allocation error
	local cgdir=$cg_basedir/osc_slab_alloc
	mkdir $cgdir || error "cgroup mkdir '$cgdir' failed"
	trap "cleanup_test411_cgroup $cgdir" EXIT
	echo 2M > $cgdir/memory.kmem.limit_in_bytes
	echo 1M > $cgdir/memory.limit_in_bytes

	# Should not LBUG, just be killed by oom-killer
	# dd will return 0 even allocation failure in some environment.
	# So don't check return value
	bash -c "echo \$$ > $cgdir/tasks && dd if=$DIR/$tfile of=/dev/null"
	cleanup_test411_cgroup $cgdir

	return 0
}
run_test 411a "Slab allocation error with cgroup does not LBUG"

test_411b() {
	local cg_basedir=/sys/fs/cgroup/memory
	# LU-9966
	[ -e "$cg_basedir/memory.kmem.limit_in_bytes" ] ||
		skip "no setup for cgroup"

	local count=2

	(( OSTCOUNT < 2 )) && count=$OSTCOUNT
	$LFS setstripe -c $count $DIR/$tfile || error "unable to setstripe"

	# To avoid testing failures on x86 and arm, we set the memcg limit
	# with 1024M on both systems.
	local memlimit_mb=1024
	local min_size_ost=$($LFS df | awk "/$FSNAME-OST/ { print \$4 }" |
			     sort -un | head -1)

	(( memlimit_mb * 4 * 1024 < min_size_ost * count - 100 )) ||
		skip "OST space are too small: ${min_size_ost}K"

	echo "count=$count/$OSTCOUNT min_size_ost=${min_size_ost}K"
	$LFS df

	# Create a cgroup and set memory limit
	# (tfile is used as an easy way to get a recognizable cgroup name)
	local cgdir=$cg_basedir/$tfile
	mkdir $cgdir || error "cgroup mkdir '$cgdir' failed"
	stack_trap "cleanup_test411_cgroup $cgdir" EXIT
	echo $((memlimit_mb * 1024 * 1024)) > $cgdir/memory.limit_in_bytes

	echo "writing first file"
	# Write a file 4x the memory limit in size
	bash -c "echo \$$ > $cgdir/tasks && dd if=/dev/zero of=$DIR/$tfile bs=1M count=$((memlimit_mb * 4))" ||
		error "(1) failed to write successfully"

	sync
	cancel_lru_locks osc

	rm -f $DIR/$tfile
	$LFS setstripe -c $count $DIR/$tfile || error "unable to setstripe"

	# Try writing at a larger block size
	# NB: if block size is >= 1/2 cgroup size, we sometimes get OOM killed
	# so test with 1/4 cgroup size (this seems reasonable to me - we do
	# need *some* memory to do IO in)
	echo "writing at larger block size"
	bash -c "echo \$$ > $cgdir/tasks && dd if=/dev/zero of=$DIR/$tfile bs=64M count=$((memlimit_mb * 4 / 128))" ||
		error "(3) failed to write successfully"

	sync
	cancel_lru_locks osc
	rm -f $DIR/$tfile

	$LFS setstripe -c $count $DIR/$tfile.{1..4} || error "unable to setstripe"

	# Try writing multiple files at once
	(( memlimit_mb * 4 * 1024 * 2 < min_size_ost * count - 100 )) ||
		skip "OST space are too small: ${min_size_ost}K"

	echo "writing multiple files"
	bash -c "echo \$$ > $cgdir/tasks && dd if=/dev/zero of=$DIR/$tfile.1 bs=32M count=$((memlimit_mb * 4 / 64))" &
	local pid1=$!
	bash -c "echo \$$ > $cgdir/tasks && dd if=/dev/zero of=$DIR/$tfile.2 bs=32M count=$((memlimit_mb * 4 / 64))" &
	local pid2=$!
	bash -c "echo \$$ > $cgdir/tasks && dd if=/dev/zero of=$DIR/$tfile.3 bs=32M count=$((memlimit_mb * 4 / 64))" &
	local pid3=$!
	bash -c "echo \$$ > $cgdir/tasks && dd if=/dev/zero of=$DIR/$tfile.4 bs=32M count=$((memlimit_mb * 4 / 64))" &
	local pid4=$!

	wait $pid1
	local rc1=$?
	wait $pid2
	local rc2=$?
	wait $pid3
	local rc3=$?
	wait $pid4
	local rc4=$?
	if (( rc1 != 0)); then
		error "error $rc1 writing to file from $pid1"
	fi
	if (( rc2 != 0)); then
		error "error $rc2 writing to file from $pid2"
	fi
	if (( rc3 != 0)); then
		error "error $rc3 writing to file from $pid3"
	fi
	if (( rc4 != 0)); then
		error "error $rc4 writing to file from $pid4"
	fi

	sync
	cancel_lru_locks osc

	# These files can be large-ish (~1 GiB total), so delete them rather
	# than leave for later cleanup
	rm -f $DIR/$tfile.*
	return 0
}
run_test 411b "confirm Lustre can avoid OOM with reasonable cgroups limits"

test_412() {
	(( $MDSCOUNT > 1 )) || skip_env "needs >= 2 MDTs"
	(( $MDS1_VERSION >= $(version_code 2.10.55) )) ||
		skip "Need server version at least 2.10.55"

	$LFS mkdir -i $((MDSCOUNT - 1)),$((MDSCOUNT - 2)) $DIR/$tdir ||
		error "mkdir failed"
	$LFS getdirstripe $DIR/$tdir
	local stripe_index=$($LFS getdirstripe -i $DIR/$tdir)
	[ $stripe_index -eq $((MDSCOUNT - 1)) ] ||
		error "expect $((MDSCOUT - 1)) get $stripe_index"
	local stripe_count=$($LFS getdirstripe -T $DIR/$tdir)
	[ $stripe_count -eq 2 ] ||
		error "expect 2 get $stripe_count"

	(( $MDS1_VERSION >= $(version_code 2.14.55) )) || return 0

	local index
	local index2

	# subdirs should be on the same MDT as parent
	for i in $(seq 0 $((MDSCOUNT - 1))); do
		$LFS mkdir -i $i $DIR/$tdir/mdt$i || error "mkdir mdt$i failed"
		mkdir $DIR/$tdir/mdt$i/sub || error "mkdir sub failed"
		index=$($LFS getstripe -m $DIR/$tdir/mdt$i/sub)
		(( index == i )) || error "mdt$i/sub on MDT$index"
	done

	# stripe offset -1, ditto
	for i in {1..10}; do
		$LFS mkdir -i -1 $DIR/$tdir/qos$i || error "mkdir qos$i failed"
		index=$($LFS getstripe -m $DIR/$tdir/qos$i)
		mkdir $DIR/$tdir/qos$i/sub || error "mkdir sub failed"
		index2=$($LFS getstripe -m $DIR/$tdir/qos$i/sub)
		(( index == index2 )) ||
			error "qos$i on MDT$index, sub on MDT$index2"
	done

	local testdir=$DIR/$tdir/inherit

	$LFS mkdir -i 1 --max-inherit=3 $testdir || error "mkdir inherit failed"
	# inherit 2 levels
	for i in 1 2; do
		testdir=$testdir/s$i
		mkdir $testdir || error "mkdir $testdir failed"
		index=$($LFS getstripe -m $testdir)
		(( index == 1 )) ||
			error "$testdir on MDT$index"
	done

	# not inherit any more
	testdir=$testdir/s3
	mkdir $testdir || error "mkdir $testdir failed"
	getfattr -d -m dmv $testdir | grep dmv &&
		error "default LMV set on $testdir" || true
}
run_test 412 "mkdir on specific MDTs"

TEST413_COUNT=${TEST413_COUNT:-200}

#
# set_maxage() is used by test_413 only.
# This is a helper function to set maxage. Does not return any value.
# Input: maxage to set
#
set_maxage() {
	local lmv_qos_maxage
	local lod_qos_maxage
	local new_maxage=$1
	local mdts=$(mdts_nodes)

	lmv_qos_maxage=$($LCTL get_param -n lmv.*.qos_maxage)
	$LCTL set_param lmv.*.qos_maxage=$new_maxage
	stack_trap "$LCTL set_param \
		lmv.*.qos_maxage=$lmv_qos_maxage > /dev/null"
	lod_qos_maxage=$(do_facet mds1 $LCTL get_param -n \
		lod.$FSNAME-MDT0000-mdtlov.qos_maxage | awk '{ print $1 }')
	do_nodes $mdts $LCTL set_param lod.*.mdt_qos_maxage=$new_maxage
	stack_trap "do_nodes $mdts $LCTL set_param lod.*.mdt_qos_maxage=$lod_qos_maxage > /dev/null"
}

generate_uneven_mdts() {
	local threshold=$1
	local ffree
	local bavail
	local max
	local min
	local max_index
	local min_index
	local tmp
	local i

	echo
	echo "Check for uneven MDTs: "

	ffree=($(lctl get_param -n mdc.*[mM][dD][cC]-[^M]*.filesfree))
	bavail=($(lctl get_param -n mdc.*[mM][dD][cC]-[^M]*.kbytesavail))
	bsize=$(lctl get_param -n mdc.*MDT0000*.blocksize)

	max=$(((${ffree[0]} >> 8) * (${bavail[0]} * bsize >> 16)))
	min=$(((${ffree[0]} >> 8) * (${bavail[0]} * bsize >> 16)))
	max_index=0
	min_index=0
	for ((i = 1; i < ${#ffree[@]}; i++)); do
		tmp=$(((${ffree[i]} >> 8) * (${bavail[i]} * bsize >> 16)))
		if [ $tmp -gt $max ]; then
			max=$tmp
			max_index=$i
		fi
		if [ $tmp -lt $min ]; then
			min=$tmp
			min_index=$i
		fi
	done

	(( min > 0 )) || skip "low space on MDT$min_index"
	(( ${ffree[min_index]} > 0 )) ||
		skip "no free files on MDT$min_index"
	(( ${ffree[min_index]} < 10000000 )) ||
		skip "too many free files on MDT$min_index"

	# Check if we need to generate uneven MDTs
	local diff=$(((max - min) * 100 / min))
	local testdirp=$DIR/$tdir-fillmdt # parent fill folder
	local testdir # individual folder within $testdirp
	local start
	local cmd

	echo "using cmd $cmd"
	for (( i = 0; diff < threshold; i++ )); do
		testdir=${testdirp}/$i
		[ -d $testdir ] && continue

		(( i % 10 > 0 )) || { $LFS df; $LFS df -i; }

		mkdir -p $testdirp
		# generate uneven MDTs, create till $threshold% diff
		echo -n "weight diff=$diff% must be > $threshold% ..."
		echo "Fill MDT$min_index with $TEST413_COUNT files: loop $i"
		$LFS mkdir -i $min_index $testdir ||
			error "mkdir $testdir failed"
		$LFS setstripe -E 1M -L mdt $testdir ||
			error "setstripe $testdir failed"
		start=$SECONDS
		fast_file_write $testdir/f 128K $TEST413_COUNT ||
			error "fast write failed"
		sync; sleep 1; sync

		# wait for QOS to update
		(( SECONDS < start + 2 )) && sleep $((start + 2 - SECONDS))

		ffree=($(lctl get_param -n mdc.*[mM][dD][cC]-*.filesfree))
		bavail=($(lctl get_param -n mdc.*[mM][dD][cC]-*.kbytesavail))
		max=$(((${ffree[max_index]} >> 8) *
			(${bavail[max_index]} * bsize >> 16)))
		min=$(((${ffree[min_index]} >> 8) *
			(${bavail[min_index]} * bsize >> 16)))
		(( min > 0 )) || skip "low space on MDT$min_index"
		diff=$(((max - min) * 100 / min))
	done

	echo "MDT filesfree available: ${ffree[*]}"
	echo "MDT blocks available: ${bavail[*]}"
	echo "weight diff=$diff%"
}

test_qos_mkdir() {
	local mkdir_cmd=$1
	local stripe_count=$2
	local mdts=$(mdts_nodes)

	local testdir
	local lmv_qos_prio_free
	local lmv_qos_threshold_rr
	local lod_qos_prio_free
	local lod_qos_threshold_rr
	local total
	local count
	local i

	# @total is total directories created if it's testing plain
	# directories, otherwise it's total stripe object count for
	# striped directories test.
	# remote/striped directory unlinking is slow on zfs and may
	# timeout, test with fewer directories
	[ "$mds1_FSTYPE" = "zfs" ] && total=120 || total=240

	lmv_qos_prio_free=$($LCTL get_param -n lmv.*.qos_prio_free | head -n1)
	lmv_qos_prio_free=${lmv_qos_prio_free%%%}
	lmv_qos_threshold_rr=$($LCTL get_param -n lmv.*.qos_threshold_rr |
		head -n1)
	lmv_qos_threshold_rr=${lmv_qos_threshold_rr%%%}
	stack_trap "$LCTL set_param \
		lmv.*.qos_prio_free=$lmv_qos_prio_free > /dev/null"
	stack_trap "$LCTL set_param \
		lmv.*.qos_threshold_rr=$lmv_qos_threshold_rr > /dev/null"

	lod_qos_prio_free=$(do_facet mds1 $LCTL get_param -n \
		lod.$FSNAME-MDT0000-mdtlov.mdt_qos_prio_free | head -n1)
	lod_qos_prio_free=${lod_qos_prio_free%%%}
	lod_qos_threshold_rr=$(do_facet mds1 $LCTL get_param -n \
		lod.$FSNAME-MDT0000-mdtlov.mdt_qos_threshold_rr | head -n1)
	lod_qos_threshold_rr=${lod_qos_threshold_rr%%%}
	stack_trap "do_nodes $mdts $LCTL set_param \
		lod.*.mdt_qos_prio_free=$lod_qos_prio_free > /dev/null"
	stack_trap "do_nodes $mdts $LCTL set_param \
		lod.*.mdt_qos_threshold_rr=$lod_qos_threshold_rr > /dev/null"

	# decrease statfs age, so that it can be updated in time
	$LCTL set_param lmv.*.qos_maxage=1 > /dev/null
	do_nodes $mdts $LCTL set_param lod.*.mdt_qos_maxage=1 > /dev/null

	$LCTL set_param lmv.*.qos_threshold_rr=100 > /dev/null
	do_nodes $mdts $LCTL set_param lod.*.mdt_qos_threshold_rr=100 > /dev/null

	testdir=$DIR/$tdir-s$stripe_count/rr

	local stripe_index=$($LFS getstripe -m $testdir)
	local test_mkdir_rr=true

	getfattr -d -m dmv -e hex $testdir | grep dmv
	if (( $? == 0 && $MDS1_VERSION >= $(version_code 2.14.51) )); then
		echo "defstripe: '$($LFS getdirstripe -D $testdir)'"
		(( $($LFS getdirstripe -D --max-inherit-rr $testdir) == 0 )) &&
			test_mkdir_rr=false
	fi

	echo
	$test_mkdir_rr &&
		echo "Mkdir (stripe_count $stripe_count) roundrobin:" ||
		echo "Mkdir (stripe_count $stripe_count) on stripe $stripe_index"

	stack_trap "unlinkmany -d $testdir/subdir $((total / stripe_count))"
	for (( i = 0; i < total / stripe_count; i++ )); do
		eval $mkdir_cmd $testdir/subdir$i ||
			error "$mkdir_cmd subdir$i failed"
	done

	for (( i = 0; i < $MDSCOUNT; i++ )); do
		count=$($LFS getdirstripe -i $testdir/* | grep -c "^$i$")
		echo "$count directories created on MDT$i"
		if $test_mkdir_rr; then
			(( count == total / stripe_count / MDSCOUNT )) ||
				error "subdirs are not evenly distributed"
		elif (( i == stripe_index )); then
			(( count == total / stripe_count )) ||
				error "$count subdirs created on MDT$i"
		else
			(( count == 0 )) ||
				error "$count subdirs created on MDT$i"
		fi

		if $test_mkdir_rr && [ $stripe_count -gt 1 ]; then
			count=$($LFS getdirstripe $testdir/* |
				grep -c -P "^\s+$i\t")
			echo "$count stripes created on MDT$i"
			# deviation should < 5% of average
			delta=$((count - total / MDSCOUNT))
			(( ${delta#-} <= total / MDSCOUNT / 20 )) ||
				error "stripes are not evenly distributed"
		fi
	done

	echo
	echo "Check for uneven MDTs: "

	local ffree
	local bavail
	local max
	local min
	local max_index
	local min_index
	local tmp

	ffree=($(lctl get_param -n mdc.*[mM][dD][cC]-[^M]*.filesfree))
	bavail=($(lctl get_param -n mdc.*[mM][dD][cC]-[^M]*.kbytesavail))
	bsize=$(lctl get_param -n mdc.*MDT0000*.blocksize)

	max=$(((${ffree[0]} >> 8) * (${bavail[0]} * bsize >> 16)))
	min=$(((${ffree[0]} >> 8) * (${bavail[0]} * bsize >> 16)))
	max_index=0
	min_index=0
	for ((i = 1; i < ${#ffree[@]}; i++)); do
		tmp=$(((${ffree[i]} >> 8) * (${bavail[i]} * bsize >> 16)))
		if [ $tmp -gt $max ]; then
			max=$tmp
			max_index=$i
		fi
		if [ $tmp -lt $min ]; then
			min=$tmp
			min_index=$i
		fi
	done
	echo "stripe_count=$stripe_count min_idx=$min_index max_idx=$max_index"

	(( min > 0 )) || skip "low space on MDT$min_index"
	(( ${ffree[min_index]} < 10000000 )) ||
		skip "too many free files on MDT$min_index"

	generate_uneven_mdts 120

	echo "MDT filesfree available: ${ffree[*]}"
	echo "MDT blocks available: ${bavail[*]}"
	echo "weight diff=$(((max - min) * 100 / min))%"
	echo
	echo "Mkdir (stripe_count $stripe_count) with balanced space usage:"

	$LCTL set_param lmv.*.qos_threshold_rr=0 > /dev/null
	$LCTL set_param lmv.*.qos_prio_free=100 > /dev/null
	do_nodes $mdts $LCTL set_param lod.*.mdt_qos_threshold_rr=0 > /dev/null
	do_nodes $mdts $LCTL set_param lod.*.mdt_qos_prio_free=100 > /dev/null

	sleep 1

	testdir=$DIR/$tdir-s$stripe_count/qos

	stack_trap "unlinkmany -d $testdir/subdir $((total / stripe_count))"
	for (( i = 0; i < total / stripe_count; i++ )); do
		eval $mkdir_cmd $testdir/subdir$i ||
			error "$mkdir_cmd subdir$i failed"
	done

	max=0
	for (( i = 0; i < $MDSCOUNT; i++ )); do
		count=$($LFS getdirstripe -i $testdir/* | grep -c "^$i$")
		(( count > max )) && max=$count
		echo "$count directories created on MDT$i : curmax=$max"
	done

	min=$($LFS getdirstripe -i $testdir/* | grep -c "^$min_index$")

	# D-value should > 10% of average
	(( max - min > total / stripe_count / MDSCOUNT / 10 )) ||
		error "subdirs shouldn't be evenly distributed: $max - $min <= $((total / stripe_count / MDSCOUNT / 10))"

	# ditto for stripes
	if (( stripe_count > 1 )); then
		max=0
		for (( i = 0; i < $MDSCOUNT; i++ )); do
			count=$($LFS getdirstripe $testdir/* |
				grep -c -P "^\s+$i\t")
			(( count > max )) && max=$count
			echo "$count stripes created on MDT$i"
		done

		min=$($LFS getdirstripe $testdir/* |
			grep -c -P "^\s+$min_index\t")
		(( max - min > total / MDSCOUNT / 10 )) ||
			error "stripes shouldn't be evenly distributed: $max - $min <= $((total / MDSCOUNT / 10))"
	fi
}

most_full_mdt() {
	local ffree
	local bavail
	local bsize
	local min
	local min_index
	local tmp

	ffree=($(lctl get_param -n mdc.*[mM][dD][cC]-[^M]*.filesfree))
	bavail=($(lctl get_param -n mdc.*[mM][dD][cC]-[^M]*.kbytesavail))
	bsize=$(lctl get_param -n mdc.*MDT0000*.blocksize)

	min=$(((${ffree[0]} >> 8) * (${bavail[0]} * bsize >> 16)))
	min_index=0
	for ((i = 1; i < ${#ffree[@]}; i++)); do
		tmp=$(((${ffree[i]} >> 8) * (${bavail[i]} * bsize >> 16)))
		(( tmp < min )) && min=$tmp && min_index=$i
	done

	echo -n $min_index
}

test_413A() {
	local index=0

	echo "before"
	do_nodes $CLIENTS $LCTL get_param lmv.*.qos_rr_index
	for client in ${CLIENTS//,/ }; do
		local cli_ver=$(lustre_build_version_node $client)

		(( $(version_code $cli_ver) >= $(version_code 2.16.59.8) )) ||
			skip "need $client $cli_ver > 2.16.59.8 for qos_rr_index"
		do_node $client $LCTL set_param -n lmv.*.qos_rr_index=$index
		((index++))
	done
	echo "after"
	do_nodes $CLIENTS $LCTL get_param lmv.*.qos_rr_index
	index=0
	for client in ${CLIENTS//,/ }; do
		got=$(do_node $client $LCTL get_param -n lmv.*.qos_rr_index)
		((got == index)) ||
			error "lmv.*.qos_rr_index was $got != $index"
		((index++))
	done
	echo "all OSCs set correctly"
}
run_test 413A "get and set qos_rr_index on all clients"

test_413a() {
	[ $MDSCOUNT -lt 2 ] &&
		skip "We need at least 2 MDTs for this test"

	[ $MDS1_VERSION -lt $(version_code 2.12.52) ] &&
		skip "Need server version at least 2.12.52"

	local stripe_max=$((MDSCOUNT - 1))
	local stripe_count

	# let caller set maxage for latest result
	set_maxage 1

	# fill MDT unevenly
	generate_uneven_mdts 120

	# test 4-stripe directory at most, otherwise it's too slow
	# We are being very defensive. Although Autotest uses 4 MDTs.
	# We make sure stripe_max does not go over 4.
	(( stripe_max > 4 )) && stripe_max=4
	# unlinking striped directory is slow on zfs, and may timeout, only test
	# plain directory
	[ "$mds1_FSTYPE" == "zfs" ] && stripe_max=1
	for stripe_count in $(seq 1 $stripe_max); do
		mkdir $DIR/$tdir-s$stripe_count || error "mkdir failed"
		mkdir $DIR/$tdir-s$stripe_count/rr || error "mkdir failed"
		$LFS mkdir -i $(most_full_mdt) $DIR/$tdir-s$stripe_count/qos ||
			error "mkdir failed"
		test_qos_mkdir "$LFS mkdir -i -1 -c $stripe_count" $stripe_count
	done
}
run_test 413a "QoS mkdir with 'lfs mkdir -i -1'"

test_413b() {
	[ $MDSCOUNT -lt 2 ] &&
		skip "We need at least 2 MDTs for this test"

	[ $MDS1_VERSION -lt $(version_code 2.12.52) ] &&
		skip "Need server version at least 2.12.52"

	local stripe_max=$((MDSCOUNT - 1))
	local testdir
	local stripe_count

	# let caller set maxage for latest result
	set_maxage 1

	# fill MDT unevenly
	generate_uneven_mdts 120

	# test 4-stripe directory at most, otherwise it's too slow
	# We are being very defensive. Although Autotest uses 4 MDTs.
	# We make sure stripe_max does not go over 4.
	(( stripe_max > 4 )) && stripe_max=4
	[ "$mds1_FSTYPE" == "zfs" ] && stripe_max=1
	for stripe_count in $(seq 1 $stripe_max); do
		testdir=$DIR/$tdir-s$stripe_count
		mkdir $testdir || error "mkdir $testdir failed"
		mkdir $testdir/rr || error "mkdir rr failed"
		$LFS mkdir -i $(most_full_mdt) $testdir/qos ||
			error "mkdir qos failed"
		$LFS setdirstripe -D -c $stripe_count --max-inherit-rr 2 \
			$testdir/rr || error "setdirstripe rr failed"
		$LFS setdirstripe -D -c $stripe_count $testdir/qos ||
			error "setdirstripe failed"
		test_qos_mkdir "mkdir" $stripe_count
	done
}
run_test 413b "QoS mkdir under dir whose default LMV starting MDT offset is -1"

test_413c() {
	(( $MDSCOUNT >= 2 )) ||
		skip "We need at least 2 MDTs for this test"

	(( $MDS1_VERSION >= $(version_code 2.14.51) )) ||
		skip "Need server version at least 2.14.51"

	local testdir
	local inherit
	local inherit_rr
	local lmv_qos_maxage
	local lod_qos_maxage

	# let caller set maxage for latest result
	lmv_qos_maxage=$($LCTL get_param -n lmv.*.qos_maxage)
	$LCTL set_param lmv.*.qos_maxage=1
	stack_trap "$LCTL set_param \
		lmv.*.qos_maxage=$lmv_qos_maxage > /dev/null" RETURN
	lod_qos_maxage=$(do_facet mds1 $LCTL get_param -n \
		lod.$FSNAME-MDT0000-mdtlov.qos_maxage | awk '{ print $1 }')
	do_nodes $(comma_list $(mdts_nodes)) $LCTL set_param \
		lod.*.mdt_qos_maxage=1
	stack_trap "do_nodes $(comma_list $(mdts_nodes)) $LCTL set_param \
		lod.*.mdt_qos_maxage=$lod_qos_maxage > /dev/null" RETURN

	# fill MDT unevenly
	generate_uneven_mdts 120

	testdir=$DIR/${tdir}-s1
	mkdir $testdir || error "mkdir $testdir failed"
	mkdir $testdir/rr || error "mkdir rr failed"
	$LFS mkdir -i $(most_full_mdt) $testdir/qos || error "mkdir qos failed"
	# default max_inherit is -1, default max_inherit_rr is 0
	$LFS setdirstripe -D -c 1 $testdir/rr ||
		error "setdirstripe rr failed"
	$LFS setdirstripe -D -c 1 -i -1 -X 2 --max-inherit-rr 1 $testdir/qos ||
		error "setdirstripe qos failed"
	test_qos_mkdir "mkdir" 1

	mkdir $testdir/rr/level1 || error "mkdir rr/level1 failed"
	inherit=$($LFS getdirstripe -D -X $testdir/rr/level1)
	(( $inherit == -1 )) || error "rr/level1 inherit $inherit != -1"
	inherit_rr=$($LFS getdirstripe -D --max-inherit-rr $testdir/rr/level1)
	(( $inherit_rr == 0 )) || error "rr/level1 inherit-rr $inherit_rr != 0"

	mkdir $testdir/qos/level1 || error "mkdir qos/level1 failed"
	inherit=$($LFS getdirstripe -D -X $testdir/qos/level1)
	(( $inherit == 1 )) || error "qos/level1 inherit $inherit != 1"
	inherit_rr=$($LFS getdirstripe -D --max-inherit-rr $testdir/qos/level1)
	(( $inherit_rr == 0 )) || error "qos/level1 inherit-rr $inherit_rr != 0"
	mkdir $testdir/qos/level1/level2 || error "mkdir level2 failed"
	getfattr -d -m dmv -e hex $testdir/qos/level1/level2 | grep dmv &&
		error "level2 shouldn't have default LMV" || true
}
run_test 413c "mkdir with default LMV max inherit rr"

test_413d() {
	(( MDSCOUNT >= 2 )) ||
		skip "We need at least 2 MDTs for this test"

	(( MDS1_VERSION >= $(version_code 2.14.51) )) ||
		skip "Need server version at least 2.14.51"

	[ -n "$FILESET" ] && skip "Not functional for FILESET set"

	local lmv_qos_threshold_rr

	lmv_qos_threshold_rr=$($LCTL get_param -n lmv.*.qos_threshold_rr |
		head -n1)
	stack_trap "$LCTL set_param \
		lmv.*.qos_threshold_rr=$lmv_qos_threshold_rr > /dev/null" EXIT

	$LCTL set_param lmv.*.qos_threshold_rr=100 > /dev/null
	mkdir -p $DIR/$tdir || error "mkdir $tdir failed"
	getfattr -d -m dmv -e hex $DIR/$tdir | grep dmv &&
		error "$tdir shouldn't have default LMV"
	createmany -d $DIR/$tdir/sub $((100 * MDSCOUNT)) ||
		error "mkdir sub failed"

	local count=$($LFS getstripe -m $DIR/$tdir/* | grep -c ^0)

	(( count == 100 )) || error "$count subdirs on MDT0"
}
run_test 413d "inherit ROOT default LMV"

test_413e() {
	(( MDSCOUNT >= 2 )) ||
		skip "We need at least 2 MDTs for this test"
	(( MDS1_VERSION >= $(version_code 2.14.55) )) ||
		skip "Need server version at least 2.14.55"

	local testdir=$DIR/$tdir
	local tmpfile=$TMP/temp.setdirstripe.stderr.$$
	local max_inherit
	local sub_max_inherit

	mkdir -p $testdir || error "failed to create $testdir"

	# set default max-inherit to -1 if stripe count is 0 or 1
	$LFS setdirstripe -D -c 1 $testdir ||
		error "failed to set default LMV"
	max_inherit=$($LFS getdirstripe -D --max-inherit $testdir)
	(( max_inherit == -1 )) ||
		error "wrong max_inherit value $max_inherit"

	# set default max_inherit to a fixed value if stripe count is not 0 or 1
	$LFS setdirstripe -D -c -1 $testdir ||
		error "failed to set default LMV"
	max_inherit=$($LFS getdirstripe -D --max-inherit $testdir)
	(( max_inherit > 0 )) ||
		error "wrong max_inherit value $max_inherit"

	# and the subdir will decrease the max_inherit by 1
	mkdir -p $testdir/subdir-1 || error "failed to make subdir"
	sub_max_inherit=$($LFS getdirstripe -D --max-inherit $testdir/subdir-1)
	(( sub_max_inherit == max_inherit - 1)) ||
		error "wrong max-inherit of subdir $sub_max_inherit"

	# check specified --max-inherit and warning message
	stack_trap "rm -f $tmpfile"
	$LFS setdirstripe -D -c 2 --max-inherit=-1 $testdir 2> $tmpfile ||
		error "failed to set default LMV"
	max_inherit=$($LFS getdirstripe -D --max-inherit $testdir)
	(( max_inherit == -1 )) ||
		error "wrong max_inherit value $max_inherit"

	# check the warning messages
	if ! [[ $(cat $tmpfile) =~ "max-inherit=" ]]; then
		error "failed to detect warning string"
	fi
}
run_test 413e "check default max-inherit value"

test_fs_dmv_inherit()
{
	local testdir=$DIR/$tdir

	local count
	local inherit
	local inherit_rr

	for i in 1 2; do
		mkdir $testdir || error "mkdir $testdir failed"
		count=$($LFS getdirstripe -D -c $testdir)
		(( count == 1 )) ||
			error "$testdir default LMV count mismatch $count != 1"
		inherit=$($LFS getdirstripe -D -X $testdir)
		(( inherit == 3 - i )) ||
			error "$testdir default LMV max-inherit $inherit != $((3 - i))"
		inherit_rr=$($LFS getdirstripe -D --max-inherit-rr $testdir)
		(( inherit_rr == 3 - i )) ||
			error "$testdir default LMV max-inherit-rr $inherit_rr != $((3 - i))"
		testdir=$testdir/sub
	done

	mkdir $testdir || error "mkdir $testdir failed"
	count=$($LFS getdirstripe -D -c $testdir)
	(( count == 0 )) ||
		error "$testdir default LMV count not zero: $count"
}

test_413f() {
	(( MDSCOUNT >= 2 )) || skip "We need at least 2 MDTs for this test"

	(( MDS1_VERSION >= $(version_code 2.14.55) )) ||
		skip "Need server version at least 2.14.55"

	getfattr -d -m trusted.dmv --absolute-names $DIR > $TMP/dmv.ea ||
		error "dump $DIR default LMV failed"
	stack_trap "setfattr --restore=$TMP/dmv.ea"

	$LFS setdirstripe -D -i -1 -c 1 -X 3 --max-inherit-rr 3 $DIR ||
		error "set $DIR default LMV failed"

	test_fs_dmv_inherit
}
run_test 413f "lfs getdirstripe -D list ROOT default LMV if it's not set on dir"

test_413g() {
	(( MDSCOUNT >= 2 )) || skip "We need at least 2 MDTs for this test"

	local FILESET_orig=$FILESET
	if [ -n "$FILESET" ];then
		cleanup_mount $MOUNT
		FILESET="" mount_client $MOUNT
	fi

	mkdir -p $DIR/$tdir/l2/l3/l4 || error "mkdir $tdir/l1/l2/l3 failed"
	getfattr -d -m trusted.dmv --absolute-names $DIR > $TMP/dmv.ea ||
		error "dump $DIR default LMV failed"
	stack_trap "setfattr --restore=$TMP/dmv.ea"

	$LFS setdirstripe -D -i -1 -c 1 -X 3 --max-inherit-rr 3 $DIR ||
		error "set $DIR default LMV failed"

	local saved_DIR=$DIR
	export DIR=$MOUNT2
	FILESET="/$tdir/l2/l3/l4" mount_client $MOUNT2 ||
		error "mount $MOUNT2 failed"
	if [ -n "$FILESET_orig" ]; then
		stack_trap "umount_client $MOUNT2; export DIR=$saved_DIR;export FILESET=$FILESET_orig; mount_client $MOUNT"
	else
		stack_trap "umount_client $MOUNT2; export DIR=$saved_DIR"
	fi

	# first check filesystem-wide default LMV inheritance
	test_fs_dmv_inherit || error "incorrect fs default LMV inheritance"

	# then check subdirs are spread to all MDTs
	createmany -d $DIR/s $((MDSCOUNT * 100)) || error "createmany failed"

	local count=$($LFS getstripe -m $DIR/s* | sort -u | wc -l)

	(( $count == $MDSCOUNT )) || error "dirs are spread to $count MDTs"

	if [ -n "$FILESET_orig" ];then
		cleanup_mount $MOUNT
		FILESET=$FILESET_orig
		mount_client $MOUNT
	fi
}
run_test 413g "enforce ROOT default LMV on subdir mount"

test_413h() {
	(( MDSCOUNT >= 2 )) ||
		skip "We need at least 2 MDTs for this test"

	(( MDS1_VERSION >= $(version_code 2.15.50.6) )) ||
		skip "Need server version at least 2.15.50.6"

	local lmv_qos_maxage=$($LCTL get_param -n lmv.*.qos_maxage)

	stack_trap "$LCTL set_param \
		lmv.*.qos_maxage=$lmv_qos_maxage > /dev/null"
	$LCTL set_param lmv.*.qos_maxage=1

	local depth=5
	local rr_depth=4
	local dir=$DIR/$tdir/l1/l2/l3/l4/l5
	local count=$((MDSCOUNT * 20))

	generate_uneven_mdts 50

	mkdir -p $dir || error "mkdir $dir failed"
	stack_trap "rm -rf $dir"
	$LFS setdirstripe -D -c 1 -i -1 --max-inherit=$depth \
		--max-inherit-rr=$rr_depth $dir

	for ((d=0; d < depth + 2; d++)); do
		log "dir=$dir:"
		for ((sub=0; sub < count; sub++)); do
			mkdir $dir/d$sub
		done
		$LFS getdirstripe -i $dir/d* | sort | uniq -c | sort -nr
		local num=($($LFS getdirstripe -i $dir/d* | sort | uniq -c))
		# subdirs within $rr_depth should be created round-robin
		if (( d < rr_depth )); then
			(( ${num[0]} != count )) ||
				error "all objects created on MDT ${num[1]}"
		fi

		dir=$dir/d0
	done
}
run_test 413h "don't stick to parent for round-robin dirs"

test_413i() {
	[ $MDSCOUNT -lt 2 ] && skip_env "needs >= 2 MDTs"

	(( MDS1_VERSION >= $(version_code 2.14.55) )) ||
		skip "Need server version at least 2.14.55"

	getfattr -d -m trusted.dmv --absolute-names $DIR > $TMP/dmv.ea ||
		error "dump $DIR default LMV failed"
	stack_trap "setfattr --restore=$TMP/dmv.ea"

	local testdir=$DIR/$tdir
	local def_max_rr=1
	local def_max=3
	local count

	$LFS setdirstripe -D -i-1 -c1 --max-inherit=$def_max \
		--max-inherit-rr=$def_max_rr $DIR ||
		error "set $DIR default LMV failed"

	for i in $(seq 2 3); do
		def_max=$((def_max - 1))
		(( def_max_rr == 0 )) || def_max_rr=$((def_max_rr - 1))

		mkdir $testdir
		# RR is decremented and keeps zeroed once exhausted
		count=$($LFS getdirstripe -D --max-inherit-rr $testdir)
		(( count == def_max_rr )) ||
			error_noexit "$testdir: max-inherit-rr $count != $def_max_rr"

		# max-inherit is decremented
		count=$($LFS getdirstripe -D --max-inherit $testdir)
		(( count == def_max )) ||
			error_noexit "$testdir: max-inherit $count != $def_max"

		testdir=$testdir/d$i
	done

	# d3 is the last inherited from ROOT, no inheritance anymore
	# i.e. no the default layout anymore
	mkdir -p $testdir/d4/d5
	count=$($LFS getdirstripe -D --max-inherit $testdir)
	(( count == -1 )) ||
		error_noexit "$testdir: max-inherit $count != -1"

	local p_count=$($LFS getdirstripe -i $testdir)

	for i in $(seq 4 5); do
		testdir=$testdir/d$i

		# the root default layout is not applied once exhausted
		count=$($LFS getdirstripe -i $testdir)
		(( count == p_count )) ||
			error_noexit "$testdir: stripe-offset $count != parent offset $p_count"
	done

	$LFS setdirstripe -i 0 $DIR/d2
	count=$($LFS getdirstripe -D --max-inherit $DIR/d2)
	(( count == -1 )) ||
		error_noexit "$DIR/d2: max-inherit non-striped default $count != -1"
}
run_test 413i "check default layout inheritance"

test_413j()
{
	(( $MDSCOUNT > 1 )) || skip_env "needs >= 2 MDTs"
	local mdts=$(mdts_nodes)

	mkdir -p $DIR/$tdir || error "mkdir $tdir failed"
	$LFS setdirstripe -D -c2 --max-inherit=2 $DIR/$tdir ||
		error "setdirstripe $tdir failed"

	local value=$(getfattr -n trusted.dmv $DIR/$tdir | \
		      grep "trusted.dmv" |sed -e 's/[^=]\+=//')

	mkdir -p $DIR/$tdir/sub || error "mkdir sub failed"
	# setfattr dmv calls setdirstripe -D
	setfattr -n trusted.dmv -v $value $DIR/$tdir/sub ||
		error "setfattr sub failed"
	local value2=$(getfattr -n trusted.dmv $DIR/$tdir/sub | \
		       grep "trusted.dmv" |sed -e 's/[^=]\+=//')

	[ $value == $value2 ] || error "dmv mismatch"

	(( MDS1_VERSION >= $(version_code 2.15.58) )) || return 0

	# do not allow remove dmv by setfattr -x
	do_nodes $mdts "$LCTL set_param -n mdt.*MDT*.enable_dmv_xattr=0"
	setfattr -x trusted.dmv $DIR/$tdir/sub || error "setfattr sub failed"
	getfattr -n trusted.dmv $DIR/$tdir/sub || error "default LMV deleted"

	# allow remove dmv by setfattr -x
	do_nodes $mdts "$LCTL set_param -n mdt.*MDT*.enable_dmv_xattr=1"
	setfattr -x trusted.dmv $DIR/$tdir/sub || error "setfattr sub failed"
	getfattr -n trusted.dmv $DIR/$tdir/sub && error "default LMV exists"
	do_nodes $mdts "$LCTL set_param -n mdt.*MDT*.enable_dmv_xattr=0"
}
run_test 413j "set default LMV by setxattr"

test_413k() {
	local index1
	local index2
	local old=$($LCTL get_param -n lmv.*.qos_exclude_prefixes)
	local count=$($LCTL get_param -n lmv.*.qos_exclude_prefixes | wc -l)
	local prefixes="abc:123:foo bar"

	# add prefixes
	stack_trap "$LCTL set_param lmv.*.qos_exclude_prefixes=\"$old\""
	$LCTL set_param lmv.*.qos_exclude_prefixes="+$prefixes"

	mkdir $DIR/$tdir || error "mkdir $tdir failed"
	index1=$($LFS getstripe -m $DIR/$tdir)
	for dname in _temporary _temporary.XXXXXX abc 123 "foo bar"; do
		mkdir "$DIR/$tdir/$dname" || error "mkdir $dname failed"
		index2=$($LFS getstripe -m "$DIR/$tdir/$dname")
		((index1 == index2)) ||
			error "$tdir on MDT$index1, $dname on MDT$index2"
	done

	# remove prefixes
	$LCTL set_param lmv.*.qos_exclude_prefixes="-$prefixes"

	# total prefixes length > PAGE_SIZE can be printed correctly
	for c in {a..z}; do
		prefixes=$(str_repeat $c 255)
		$LCTL set_param lmv.*.qos_exclude_prefixes="+$prefixes" >/dev/null
	done
	local count2=$($LCTL get_param -n lmv.*.qos_exclude_prefixes | wc -l)
	((count2 == count + 26)) ||
		error "prefixes count $count2 != $((count + 26))"
}
run_test 413k "QoS mkdir exclude prefixes"

test_413l() {
	local index1
	local index2
	local old=$($LCTL get_param -n lmv.*.qos_exclude_patterns)
	local count=$($LCTL get_param -n lmv.*.qos_exclude_patterns | wc -l)
	local patterns="????-????:[a-z][0-9]"

	# add patterns
	stack_trap "$LCTL set_param lmv.*.qos_exclude_patterns=\"$old\""
	$LCTL set_param lmv.*.qos_exclude_patterns="+$patterns"

	mkdir $DIR/$tdir || error "mkdir $tdir failed"
	index1=$($LFS getstripe -m $DIR/$tdir)
	for dname in abcd-1234 b9; do
		mkdir "$DIR/$tdir/$dname" || error "mkdir $dname failed"
		index2=$($LFS getstripe -m "$DIR/$tdir/$dname")
		((index1 == index2)) ||
			error "$tdir on MDT$index1, $dname on MDT$index2"
	done

	# remove patterns
	$LCTL set_param lmv.*.qos_exclude_patterns="-$patterns"
}
run_test 413l "QoS mkdir exclude patterns"

test_413z() {
	local pids=""
	local subdir
	local pid

	for subdir in $(\ls -1 -d $DIR/d413*-fillmdt/*); do
		unlinkmany $subdir/f. $TEST413_COUNT &
		pids="$pids $!"
	done

	for pid in $pids; do
		wait $pid
	done

	true
}
run_test 413z "413 test cleanup"

test_414() {
#define OBD_FAIL_PTLRPC_BULK_ATTACH      0x521
	$LCTL set_param fail_loc=0x80000521
	dd if=/dev/zero of=$DIR/$tfile bs=2M count=1 oflag=sync
	rm -f $DIR/$tfile
	# This error path has sometimes left inflight requests dangling, so
	# test for this by remounting the client (umount will hang if there's
	# a dangling request)
	umount_client $MOUNT
	mount_client $MOUNT
}
run_test 414 "simulate ENOMEM in ptlrpc_register_bulk()"

test_415() {
	[[ $PARALLEL == "yes" ]] && skip "skip parallel run"
	(( $MDS1_VERSION >= $(version_code 2.11.52) )) ||
		skip "Need server version at least 2.11.52"

	# LU-11102
	local total=500
	local max=120

	# this test may be slow on ZFS
	[[ "$mds1_FSTYPE" == "zfs" ]] && total=50

	# though this test is designed for striped directory, let's test normal
	# directory too since lock is always saved as CoS lock.
	test_mkdir $DIR/$tdir || error "mkdir $tdir"
	createmany -o $DIR/$tdir/$tfile. $total || error "createmany"
	stack_trap "unlinkmany $DIR/$tdir/$tfile. $total || true"
	# if looping with ONLY_REPEAT, wait for previous deletions to finish
	wait_delete_completed_mds

	# run a loop without concurrent touch to measure rename duration.
	# only for test debug/robustness, NOT part of COS functional test.
	local start_time=$SECONDS
	for ((i = 0; i < total; i++)); do
		mrename $DIR/$tdir/$tfile.$i $DIR/$tdir/$tfile-new.$i \
			> /dev/null
	done
	local baseline=$((SECONDS - start_time))
	echo "rename $total files without 'touch' took $baseline sec"

	(
		while true; do
			touch $DIR/$tdir
		done
	) &
	local setattr_pid=$!

	# rename files back to original name so unlinkmany works
	start_time=$SECONDS
	for ((i = 0; i < total; i++)); do
		mrename $DIR/$tdir/$tfile-new.$i $DIR/$tdir/$tfile.$i\
			> /dev/null
	done
	local duration=$((SECONDS - start_time))

	kill -9 $setattr_pid

	echo "rename $total files with 'touch' took $duration sec"
	(( max > 2 * baseline )) || max=$((2 * baseline + 5))
	(( duration <= max )) ||
		error_not_in_vm "rename took $duration > $max sec"
}
run_test 415 "lock revoke is not missing"

test_416() {
	[ $MDS1_VERSION -lt $(version_code 2.11.55) ] &&
		skip "Need server version at least 2.11.55"

	# define OBD_FAIL_OSD_TXN_START    0x19a
	do_facet mds1 lctl set_param fail_loc=0x19a

	lfs mkdir -c $MDSCOUNT $DIR/$tdir

	true
}
run_test 416 "transaction start failure won't cause system hung"

cleanup_417() {
	local mdts=$(mdts_nodes)

	trap 0
	do_nodes $mdts "$LCTL set_param -n mdt.*MDT*.enable_dir_migration=1"
	do_nodes $mdts "$LCTL set_param -n mdt.*MDT*.enable_remote_dir=1"
	do_nodes $mdts "$LCTL set_param -n mdt.*MDT*.enable_striped_dir=1"
}

test_417() {
	[ $MDSCOUNT -lt 2 ] && skip "needs >= 2 MDTs"
	[[ $MDS1_VERSION -lt $(version_code 2.11.56) ]] &&
		skip "Need MDS version at least 2.11.56"

	trap cleanup_417 RETURN EXIT
	local mdts=$(mdts_nodes)

	$LFS mkdir -i 1 $DIR/$tdir.1 || error "create remote dir $tdir.1 failed"
	do_nodes $mdts "$LCTL set_param -n mdt.*MDT*.enable_dir_migration=0"
	$LFS migrate -m 0 $DIR/$tdir.1 &&
		error "migrate dir $tdir.1 should fail"

	do_nodes $mdts "$LCTL set_param -n mdt.*MDT*.enable_remote_dir=0"
	$LFS mkdir -i 1 $DIR/$tdir.2 &&
		error "create remote dir $tdir.2 should fail"

	do_nodes $mdts "$LCTL set_param -n mdt.*MDT*.enable_striped_dir=0"
	$LFS mkdir -c 2 $DIR/$tdir.3 &&
		error "create striped dir $tdir.3 should fail"
	true
}
run_test 417 "disable remote dir, striped dir and dir migration"

# Checks that the outputs of df [-i] and lfs df [-i] match
#
# usage: check_lfs_df <blocks | inodes> <mountpoint>
check_lfs_df() {
	local dir=$2
	local inodes
	local df_out
	local lfs_df_out
	local count
	local passed=false

	# blocks or inodes
	[ "$1" == "blocks" ] && inodes= || inodes="-i"

	for count in {1..100}; do
		do_nodes "$CLIENTS" \
			$LCTL set_param ldlm.namespaces.*.lru_size=clear
		sync; sleep 0.2

		# read the lines of interest
		df_out=($(df -P $inodes $dir | tail -n +2)) ||
			error "df $inodes $dir | tail -n +2 failed"
		lfs_df_out=($($LFS df $inodes $dir | grep summary:)) ||
			error "lfs df $inodes $dir | grep summary: failed"

		# skip first substrings of each output as they are different
		# "<NID>:/<fsname>" for df, "filesystem_summary:" for lfs df
		# compare the two outputs
		passed=true
		#  skip "available" on MDT until LU-13997 is fixed.
		#for i in {1..5}; do
		for i in 1 2 4 5; do
			[ "${df_out[i]}" != "${lfs_df_out[i]}" ] && passed=false
		done
		$passed && break
	done

	if ! $passed; then
		df -P $inodes $dir
		echo
		lfs df $inodes $dir
		error "df and lfs df $1 output mismatch: "	\
		      "df ${inodes}: ${df_out[*]}, "		\
		      "lfs df ${inodes}: ${lfs_df_out[*]}"
	fi
}

test_418() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	local dir=$DIR/$tdir
	local numfiles=$((RANDOM % 4096 + 2))
	local numblocks=$((RANDOM % 256 + 1))

	wait_delete_completed
	test_mkdir $dir

	# check block output
	check_lfs_df blocks $dir
	# check inode output
	check_lfs_df inodes $dir

	# create a single file and retest
	echo "Creating a single file and testing"
	createmany -o $dir/$tfile- 1 &>/dev/null ||
		error "creating 1 file in $dir failed"
	check_lfs_df blocks $dir
	check_lfs_df inodes $dir

	# create a random number of files
	echo "Creating $((numfiles - 1)) files and testing"
	createmany -o $dir/$tfile- 1 $((numfiles - 1)) &>/dev/null ||
		error "creating $((numfiles - 1)) files in $dir failed"

	# write a random number of blocks to the first test file
	echo "Writing $numblocks 4K blocks and testing"
	dd if=/dev/urandom of=$dir/${tfile}-0 bs=4K conv=fsync \
		count=$numblocks &>/dev/null ||
		error "dd to $dir/${tfile}-0 failed"

	# retest
	check_lfs_df blocks $dir
	check_lfs_df inodes $dir

	unlinkmany $dir/$tfile- $numfiles &>/dev/null ||
		error "unlinking $numfiles files in $dir failed"
}
run_test 418 "df and lfs df outputs match"

test_419()
{
	local dir=$DIR/$tdir

	mkdir -p $dir
	touch $dir/file

	cancel_lru_locks mdc

	#OBD_FAIL_LLITE_OPEN_BY_NAME	0x1410
	$LCTL set_param fail_loc=0x1410
	cat $dir/file
	$LCTL set_param fail_loc=0
	rm -rf $dir
}
run_test 419 "Verify open file by name doesn't crash kernel"

test_420()
{
	[[ $MDS1_VERSION -ge $(version_code 2.12.53) ]] ||
		skip "Need MDS version at least 2.12.53"

	local SAVE_UMASK=$(umask)
	local dir=$DIR/$tdir
	local uname=$(getent passwd $RUNAS_ID | cut -d: -f1)

	mkdir -p $dir
	umask 0000
	mkdir -m03777 $dir/testdir
	ls -dn $dir/testdir
	# Need to remove trailing '.' when SELinux is enabled
	local dirperms=$(ls -dn $dir/testdir |
			 awk '{ sub(/\.$/, "", $1); print $1}')
	[ $dirperms == "drwxrwsrwt" ] ||
		error "incorrect perms on $dir/testdir"

	su - $uname -c "PATH=$LUSTRE/tests:\$PATH; \
		openfile -f O_RDONLY:O_CREAT -m 02755 $dir/testdir/testfile"
	ls -n $dir/testdir/testfile
	local fileperms=$(ls -n $dir/testdir/testfile |
			  awk '{ sub(/\.$/, "", $1); print $1}')
	[ $fileperms == "-rwxr-xr-x" ] ||
		error "incorrect perms on $dir/testdir/testfile"

	umask $SAVE_UMASK
}
run_test 420 "clear SGID bit on non-directories for non-members"

test_421a() {
	local cnt
	local fid1
	local fid2

	[ $MDS1_VERSION -lt $(version_code 2.12.54) ] &&
		skip "Need MDS version at least 2.12.54"

	test_mkdir $DIR/$tdir
	createmany -o $DIR/$tdir/f 3
	cnt=$(ls -1 $DIR/$tdir | wc -l)
	[ $cnt != 3 ] && error "unexpected #files: $cnt"

	fid1=$(lfs path2fid $DIR/$tdir/f1)
	fid2=$(lfs path2fid $DIR/$tdir/f2)
	$LFS rmfid $DIR $fid1 $fid2 || error "rmfid failed"

	stat $DIR/$tdir/f1 && error "f1 still visible on the client"
	stat $DIR/$tdir/f2 && error "f2 still visible on the client"

	cnt=$(ls -1 $DIR/$tdir | wc -l)
	[ $cnt == 1 ] || error "unexpected #files after: $cnt"

	rm -f $DIR/$tdir/f3 || error "can't remove f3"
	createmany -o $DIR/$tdir/f 3
	cnt=$(ls -1 $DIR/$tdir | wc -l)
	[ $cnt != 3 ] && error "unexpected #files: $cnt"

	fid1=$(lfs path2fid $DIR/$tdir/f1)
	fid2=$(lfs path2fid $DIR/$tdir/f2)
	echo "remove using fsname $FSNAME"
	$LFS rmfid $FSNAME $fid1 $fid2 || error "rmfid with fsname failed"

	cnt=$(ls -1 $DIR/$tdir | wc -l)
	[ $cnt == 1 ] || error "unexpected #files after: $cnt"
}
run_test 421a "simple rm by fid"

test_421b() {
	local cnt
	local FID1
	local FID2

	[ $MDS1_VERSION -lt $(version_code 2.12.54) ] &&
		skip "Need MDS version at least 2.12.54"

	test_mkdir $DIR/$tdir
	createmany -o $DIR/$tdir/f 3
	multiop_bg_pause $DIR/$tdir/f1 o_c || error "multiop failed to start"
	MULTIPID=$!

	FID1=$(lfs path2fid $DIR/$tdir/f1)
	FID2=$(lfs path2fid $DIR/$tdir/f2)
	$LFS rmfid $DIR $FID1 $FID2 && error "rmfid didn't fail"

	kill -USR1 $MULTIPID
	wait

	cnt=$(ls $DIR/$tdir | wc -l)
	[ $cnt == 2 ] || error "unexpected #files after: $cnt"
}
run_test 421b "rm by fid on open file"

test_421c() {
	local cnt
	local FIDS

	[ $MDS1_VERSION -lt $(version_code 2.12.54) ] &&
		skip "Need MDS version at least 2.12.54"

	test_mkdir $DIR/$tdir
	createmany -o $DIR/$tdir/f 3
	touch $DIR/$tdir/$tfile
	createmany -l$DIR/$tdir/$tfile $DIR/$tdir/h 180
	cnt=$(ls -1 $DIR/$tdir | wc -l)
	[ $cnt != 184 ] && error "unexpected #files: $cnt"

	FID1=$(lfs path2fid $DIR/$tdir/$tfile)
	$LFS rmfid $DIR $FID1 || error "rmfid failed"

	cnt=$(ls $DIR/$tdir | wc -l)
	[ $cnt == 3 ] || error "unexpected #files after: $cnt"
}
run_test 421c "rm by fid against hardlinked files"

test_421d() {
	local cnt
	local FIDS

	[ $MDS1_VERSION -lt $(version_code 2.12.54) ] &&
		skip "Need MDS version at least 2.12.54"

	test_mkdir $DIR/$tdir
	createmany -o $DIR/$tdir/f 4097
	cnt=$(ls -1 $DIR/$tdir | wc -l)
	[ $cnt != 4097 ] && error "unexpected #files: $cnt"

	FIDS=$(lfs path2fid $DIR/$tdir/f* | sed "s/[/][^:]*://g")
	$LFS rmfid $DIR $FIDS || error "rmfid failed"

	cnt=$(ls $DIR/$tdir | wc -l)
	rm -rf $DIR/$tdir
	[ $cnt == 0 ] || error "unexpected #files after: $cnt"
}
run_test 421d "rmfid en masse"

test_421e() {
	local cnt
	local FID

	[ $MDSCOUNT -lt 2 ] && skip "needs >= 2 MDTs"
	[ $MDS1_VERSION -lt $(version_code 2.12.54) ] &&
		skip "Need MDS version at least 2.12.54"

	mkdir -p $DIR/$tdir
	$LFS setdirstripe -c$MDSCOUNT $DIR/$tdir/striped_dir
	createmany -o $DIR/$tdir/striped_dir/f 512
	cnt=$(ls -1 $DIR/$tdir/striped_dir | wc -l)
	[ $cnt != 512 ] && error "unexpected #files: $cnt"

	FIDS=$(lfs path2fid $DIR/$tdir/striped_dir/f* |
		sed "s/[/][^:]*://g")
	$LFS rmfid $DIR $FIDS || error "rmfid failed"

	cnt=$(ls $DIR/$tdir/striped_dir | wc -l)
	rm -rf $DIR/$tdir
	[ $cnt == 0 ] || error "unexpected #files after: $cnt"
}
run_test 421e "rmfid in DNE"

test_421f() {
	local cnt
	local FID

	[ $MDS1_VERSION -lt $(version_code 2.12.54) ] &&
		skip "Need MDS version at least 2.12.54"

	test_mkdir $DIR/$tdir
	touch $DIR/$tdir/f
	cnt=$(ls -1 $DIR/$tdir | wc -l)
	[ $cnt != 1 ] && error "unexpected #files: $cnt"

	FID=$(lfs path2fid $DIR/$tdir/f)
	$RUNAS $LFS rmfid $DIR $FID && error "rmfid didn't fail (1)"
	# rmfid should fail
	cnt=$(ls -1 $DIR/$tdir | wc -l)
	[ $cnt != 1 ] && error "unexpected #files after (2): $cnt"

	chmod a+rw $DIR/$tdir
	ls -la $DIR/$tdir
	$RUNAS $LFS rmfid $DIR $FID && error "rmfid didn't fail (2)"
	# rmfid should fail
	cnt=$(ls -1 $DIR/$tdir | wc -l)
	[ $cnt != 1 ] && error "unexpected #files after (3): $cnt"

	rm -f $DIR/$tdir/f
	$RUNAS touch $DIR/$tdir/f
	FID=$(lfs path2fid $DIR/$tdir/f)
	echo "rmfid as root"
	$LFS rmfid $DIR $FID || error "rmfid as root failed"
	cnt=$(ls -1 $DIR/$tdir | wc -l)
	[ $cnt == 0 ] || error "unexpected #files after (4): $cnt"

	rm -f $DIR/$tdir/f
	$RUNAS touch $DIR/$tdir/f
	cnt=$(ls -1 $DIR/$tdir | wc -l)
	[ $cnt != 1 ] && error "unexpected #files (4): $cnt"
	FID=$(lfs path2fid $DIR/$tdir/f)
	# rmfid w/o user_fid2path mount option should fail
	$RUNAS $LFS rmfid $DIR $FID && error "rmfid didn't fail(3)"
	cnt=$(ls -1 $DIR/$tdir | wc -l)
	[ $cnt == 1 ] || error "unexpected #files after (5): $cnt"

	tmpdir=$(mktemp -d /tmp/lustre-XXXXXX)
	stack_trap "rmdir $tmpdir"
	mount_client $tmpdir "$MOUNT_OPTS,user_fid2path" ||
		error "failed to mount client'"
	stack_trap "umount_client $tmpdir"

	$RUNAS $LFS rmfid $tmpdir $FID || error "rmfid failed"
	# rmfid should succeed
	cnt=$(ls -1 $tmpdir/$tdir | wc -l)
	[ $cnt == 0 ] || error "unexpected #files after (6): $cnt"

	# rmfid shouldn't allow to remove files due to dir's permission
	chmod a+rwx $tmpdir/$tdir
	touch $tmpdir/$tdir/f
	ls -la $tmpdir/$tdir
	FID=$(lfs path2fid $tmpdir/$tdir/f)
	$RUNAS $LFS rmfid $tmpdir $FID && error "rmfid didn't fail"
	return 0
}
run_test 421f "rmfid checks permissions"

test_421g() {
	local cnt
	local FIDS

	[ $MDSCOUNT -lt 2 ] && skip "needs >= 2 MDTs"
	[ $MDS1_VERSION -lt $(version_code 2.12.54) ] &&
		skip "Need MDS version at least 2.12.54"

	mkdir -p $DIR/$tdir
	$LFS setdirstripe -c$MDSCOUNT $DIR/$tdir/striped_dir
	createmany -o $DIR/$tdir/striped_dir/f 512
	cnt=$(ls -1 $DIR/$tdir/striped_dir | wc -l)
	[ $cnt != 512 ] && error "unexpected #files: $cnt"

	FIDS=$(lfs path2fid $DIR/$tdir/striped_dir/f* |
		sed "s/[/][^:]*://g")

	rm -f $DIR/$tdir/striped_dir/f1*
	cnt=$(ls -1 $DIR/$tdir/striped_dir | wc -l)
	removed=$((512 - cnt))

	# few files have been just removed, so we expect
	# rmfid to fail on their fids
	errors=$($LFS rmfid $DIR $FIDS 2>&1 | wc -l)
	[ $removed != $errors ] && error "$errors != $removed"

	cnt=$(ls $DIR/$tdir/striped_dir | wc -l)
	rm -rf $DIR/$tdir
	[ $cnt == 0 ] || error "unexpected #files after: $cnt"
}
run_test 421g "rmfid to return errors properly"

test_421h() {
	local mount_other
	local mount_ret
	local rmfid_ret
	local old_fid
	local fidA
	local fidB
	local fidC
	local fidD

	(( MDS1_VERSION >= $(version_code 2.15.53) )) ||
		skip "Need MDS version at least 2.15.53"

	test_mkdir $DIR/$tdir
	test_mkdir $DIR/$tdir/subdir
	touch $DIR/$tdir/subdir/file0
	old_fid=$(lfs path2fid $DIR/$tdir/subdir/file0 | sed "s/[/][^:]*://g")
	echo File $DIR/$tdir/subdir/file0 FID $old_fid
	rm -f $DIR/$tdir/subdir/file0
	touch $DIR/$tdir/subdir/fileA
	fidA=$(lfs path2fid $DIR/$tdir/subdir/fileA | sed "s/[/][^:]*://g")
	echo File $DIR/$tdir/subdir/fileA FID $fidA
	touch $DIR/$tdir/subdir/fileB
	fidB=$(lfs path2fid $DIR/$tdir/subdir/fileB | sed "s/[/][^:]*://g")
	echo File $DIR/$tdir/subdir/fileB FID $fidB
	ln $DIR/$tdir/subdir/fileB $DIR/$tdir/subdir/fileB_hl
	touch $DIR/$tdir/subdir/fileC
	fidC=$(lfs path2fid $DIR/$tdir/subdir/fileC | sed "s/[/][^:]*://g")
	echo File $DIR/$tdir/subdir/fileC FID $fidC
	ln $DIR/$tdir/subdir/fileC $DIR/$tdir/fileC
	touch $DIR/$tdir/fileD
	fidD=$(lfs path2fid $DIR/$tdir/fileD | sed "s/[/][^:]*://g")
	echo File $DIR/$tdir/fileD FID $fidD

	# mount another client mount point with subdirectory mount
	mount_other=${MOUNT}_other
	FILESET="$FILESET/$tdir/subdir" mount_client $mount_other ${MOUNT_OPTS}
	mount_ret=$?
	FILESET=""
	(( mount_ret == 0 )) || error "mount $mount_other failed"

	echo Removing FIDs:
	echo $LFS rmfid $mount_other $old_fid $fidA $fidD $fidB $fidC
	$LFS rmfid $mount_other $old_fid $fidA $fidD $fidB $fidC
	rmfid_ret=$?

	umount_client $mount_other || error "umount $mount_other failed"
	rm -rf $mount_other

	(( rmfid_ret != 0 )) || error "rmfid should have failed"

	# fileA should have been deleted
	stat $DIR/$tdir/subdir/fileA && error "fileA not deleted"

	# fileB should have been deleted
	stat $DIR/$tdir/subdir/fileB && error "fileB not deleted"

	# fileC should not have been deleted, fid also exists outside of fileset
	stat $DIR/$tdir/subdir/fileC || error "fileC deleted"

	# fileD should not have been deleted, it exists outside of fileset
	stat $DIR/$tdir/fileD || error "fileD deleted"
}
run_test 421h "rmfid with fileset mount"

test_422() {
	test_mkdir -i 0 -c 1 -p $DIR/$tdir/d1
	test_mkdir -i 0 -c 1 -p $DIR/$tdir/d2
	test_mkdir -i 0 -c 1 -p $DIR/$tdir/d3
	dd if=/dev/zero of=$DIR/$tdir/d1/file1 bs=1k count=1
	dd if=/dev/zero of=$DIR/$tdir/d2/file1 bs=1k count=1

	local amc=$(at_max_get client)
	local amo=$(at_max_get mds1)
	local timeout=`lctl get_param -n timeout`

	at_max_set 0 client
	at_max_set 0 mds1

#define OBD_FAIL_PTLRPC_PAUSE_REQ        0x50a
	do_facet mds1 $LCTL set_param fail_loc=0x8000050a \
			fail_val=$(((2*timeout + 10)*1000))
	touch $DIR/$tdir/d3/file &
	sleep 2
#define OBD_FAIL_TGT_REPLY_DATA_RACE	 0x722
	do_facet mds1 $LCTL set_param fail_loc=0x80000722 \
			fail_val=$((2*timeout + 5))
	mv $DIR/$tdir/d1/file1 $DIR/$tdir/d1/file2 &
	local pid=$!
	sleep 1
	kill -9 $pid
	sleep $((2 * timeout))
	echo kill $pid
	kill -9 $pid
	lctl mark touch
	touch $DIR/$tdir/d2/file3
	touch $DIR/$tdir/d2/file4
	touch $DIR/$tdir/d2/file5

	wait
	at_max_set $amc client
	at_max_set $amo mds1

	# LU-12838 - verify the ptlrpc thread watchdog is not always throttled
	do_facet mds1 "dmesg | grep 'Dumping the stack trace for debugging'" ||
		error "Watchdog is always throttled"
}
run_test 422 "kill a process with RPC in progress"

stat_test() {
    df -h $MOUNT &
    df -h $MOUNT &
    df -h $MOUNT &
    df -h $MOUNT &
    df -h $MOUNT &
    df -h $MOUNT &
}

test_423() {
    local _stats
    # ensure statfs cache is expired
    sleep 2;

    _stats=$(stat_test | grep $MOUNT | sort -u | wc -l)
    [[ ${_stats} -ne 1 ]] && error "statfs wrong"

    return 0
}
run_test 423 "statfs should return a right data"

test_424() {
#define OBD_FAIL_PTLRPC_BULK_REPLY_ATTACH      0x522 | CFS_FAIL_ONCE
	$LCTL set_param fail_loc=0x80000522
	dd if=/dev/zero of=$DIR/$tfile bs=2M count=1 oflag=sync
	rm -f $DIR/$tfile
}
run_test 424 "simulate ENOMEM in ptl_send_rpc bulk reply ME attach"

test_425() {
	test_mkdir -c -1 $DIR/$tdir
	$LFS setstripe -c -1 $DIR/$tdir

	lru_resize_disable "" 100

	sleep 5

	stack_trap "unlinkmany $DIR/$tdir/$tfile $((MDSCOUNT * 125)) || true"
	createmany -o -W 4096 $DIR/$tdir/$tfile $((MDSCOUNT * 125)) ||
		error_noexit "Create files in $DIR/$tdir"

	for oscparam in $($LCTL list_param ldlm.namespaces.*osc-[-0-9a-f]*); do
		local lru_size=$($LCTL get_param -n $oscparam.lru_size)
		local lock_count=$($LCTL get_param -n $oscparam.lock_count)

		# allow some margin for batched lock cancellation
		(( $lock_count <= $lru_size * 11 / 10)) || {
			$LCTL get_param $oscparam.lru_size $oscparam.lock_count
			error "osc lock count $lock_count > lru size $lru_size"
		}
	done

	for mdcparam in $($LCTL list_param ldlm.namespaces.*mdc-*); do
		local lru_size=$($LCTL get_param -n $mdcparam.lru_size)
		local lock_count=$($LCTL get_param -n $mdcparam.lock_count)

		# allow some margin for batched lock cancellation
		(( $lock_count <= $lru_size * 11 / 10)) || {
			$LCTL get_param $mdcparam.lru_size $mdcparam.lock_count
			error "mdc lock count $lock_count > lru size $lru_size"
		}
	done
}
run_test 425 "lock count should not exceed lru size"

test_426() {
	splice-test -r $DIR/$tfile
	splice-test -rd $DIR/$tfile
	splice-test $DIR/$tfile
	splice-test -d $DIR/$tfile
}
run_test 426 "splice test on Lustre"

test_427() {
	[ $MDSCOUNT -ge 2 ] || skip "needs >= 2 MDTs"
	(( $MDS1_VERSION >= $(version_code 2.12.4) )) ||
		skip "Need MDS version at least 2.12.4"
	local log

	mkdir $DIR/$tdir
	mkdir $DIR/$tdir/1
	mkdir $DIR/$tdir/2
	test_mkdir -c $MDSCOUNT -i 1 $DIR/$tdir/1/dir
	test_mkdir -c $MDSCOUNT -i 1 $DIR/$tdir/2/dir2

	$LFS getdirstripe $DIR/$tdir/1/dir

	#first setfattr for creating updatelog
	setfattr -n user.attr0 -v "some text" $DIR/$tdir/1/dir

#define OBD_FAIL_OUT_OBJECT_MISS        0x1708
	do_nodes $(mdts_nodes) "$LCTL set_param fail_loc=0x80001708"
	setfattr -n user.attr1 -v "some text" $DIR/$tdir/1/dir &
	setfattr -n user.attr2 -v "another attr"  $DIR/$tdir/2/dir2 &

	sleep 2
	fail mds2
	wait_recovery_complete mds2 $((2*TIMEOUT))

	log=$(do_facet mds1 dmesg | tac | sed "/${TESTNAME//_/ }/,$ d")
	echo $log | grep "get update log failed" &&
		error "update log corruption is detected" || true
}
run_test 427 "Failed DNE2 update request shouldn't corrupt updatelog"

test_428() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	local max_cached_mb=$($LCTL get_param llite.*.max_cached_mb |
			      awk '/^max_cached_mb/ { print $2 }')
	stack_trap "$LCTL set_param -n llite.*.max_cached_mb=$max_cached_mb"

	$LCTL set_param -n llite.*.max_cached_mb=64

	mkdir $DIR/$tdir
	$LFS setstripe -c 1 $DIR/$tdir
	eval touch $DIR/$tdir/$tfile.{1..$OSTCOUNT}
	stack_trap "rm -f $DIR/$tdir/$tfile.*"
	#test write
	for f in $(seq 4); do
		dd if=/dev/zero of=$DIR/$tdir/$tfile.$f bs=128M count=1 &
	done
	wait

	cancel_lru_locks osc
	# Test read
	for f in $(seq 4); do
		dd if=$DIR/$tdir/$tfile.$f of=/dev/null bs=128M count=1 &
	done
	wait
}
run_test 428 "large block size IO should not hang"

test_429() { # LU-7915 / LU-10948
	local ll_opencache_threshold_count="llite.*.opencache_threshold_count"
	local testfile=$DIR/$tfile
	local mdc_rpcstats="mdc.$FSNAME-MDT0000-*.stats"
	local new_flag=1
	local first_rpc
	local second_rpc
	local third_rpc

	$LCTL get_param $ll_opencache_threshold_count ||
		skip "client does not have opencache parameter"

	set_opencache $new_flag
	stack_trap "restore_opencache"
	[ $($LCTL get_param -n $ll_opencache_threshold_count) == $new_flag ] ||
		error "enable opencache failed"
	touch $testfile
	# drop MDC DLM locks
	cancel_lru_locks mdc
	# clear MDC RPC stats counters
	$LCTL set_param $mdc_rpcstats=clear

	# According to the current implementation, we need to run 3 times
	# open & close file to verify if opencache is enabled correctly.
	# 1st, RPCs are sent for lookup/open and open handle is released on
	#      close finally.
	# 2nd, RPC is sent for open, MDS_OPEN_LOCK is fetched automatically,
	#      so open handle won't be released thereafter.
	# 3rd, No RPC is sent out.
	$MULTIOP $testfile oc || error "multiop failed"
	first_rpc=$(calc_stats $mdc_rpcstats ldlm_ibits_enqueue)
	echo "1st: $first_rpc RPCs in flight"

	$MULTIOP $testfile oc || error "multiop failed"
	second_rpc=$(calc_stats $mdc_rpcstats ldlm_ibits_enqueue)
	echo "2nd: $second_rpc RPCs in flight"

	$MULTIOP $testfile oc || error "multiop failed"
	third_rpc=$(calc_stats $mdc_rpcstats ldlm_ibits_enqueue)
	echo "3rd: $third_rpc RPCs in flight"

	#verify no MDC RPC is sent
	[[ $second_rpc == $third_rpc ]] || error "MDC RPC is still sent"
}
run_test 429 "verify if opencache flag on client side does work"

# write data chunks in reverse order to defeat ZFS automatic blocksize
# growth during appends causing SEEK_HOLE to return unexpected offsets
dd_reverse() {
	local of=$1
	local bs=$2
	local count=${3##count=}
	local start=${4##seek=}
	local end=$((start + count - 1))
	local dd_opts="if=/dev/urandom $of $bs count=1"
	local i

	for ((i = end; i >= start; i--)); do
		dd $dd_opts seek=$i oflag=direct conv=notrunc 2>&1 |
			grep -v -E "copied|bytes"
		if (( ${PIPESTATUS[0]} != 0 )); then
			error "${of##of=}: write $start->$end @$bs failed"
			return 1
		fi
	done
}

lseek_test_430() {
	local offset
	local file=$1
	local i

	# data at [256K, 512K)
	dd_reverse of=$file bs=64K count=4 seek=4 || error "256K->512K dd fails"
	# data at [2M, 3M)
	dd_reverse of=$file bs=64K count=16 seek=32 || error "2M->3M dd fails"
	# data at [4M, 5M)
	dd_reverse of=$file bs=64K count=16 seek=64 || error "4M->5M dd fails"
	echo "Data at 256K...512K, 2M...3M and 4M...5M"
	# start at first component hole #1
	printf "Seeking hole from 1000 ... "
	offset=$(lseek_test -l 1000 $file)
	echo $offset
	[[ $offset == 1000 ]] || error "offset $offset != 1000"
	printf "Seeking data from 1000 ... "
	offset=$(lseek_test -d 1000 $file)
	echo $offset
	[[ $offset == 262144 ]] || error "offset $offset != 262144"

	# start at first component data block
	printf "Seeking hole from 300000 ... "
	offset=$(lseek_test -l 300000 $file)
	echo $offset
	[[ $offset == 524288 ]] || error "offset $offset != 524288"
	printf "Seeking data from 300000 ... "
	offset=$(lseek_test -d 300000 $file)
	echo $offset
	[[ $offset == 300000 ]] || error "offset $offset != 300000"

	# start at the first component but beyond end of object size
	printf "Seeking hole from 1000000 ... "
	offset=$(lseek_test -l 1000000 $file)
	echo $offset
	[[ $offset == 1000000 ]] || error "offset $offset != 1000000"
	printf "Seeking data from 1000000 ... "
	offset=$(lseek_test -d 1000000 $file)
	echo $offset
	[[ $offset == 2097152 ]] || error "offset $offset != 2097152"

	# start at second component stripe 2 (empty file)
	printf "Seeking hole from 1500000 ... "
	offset=$(lseek_test -l 1500000 $file)
	echo $offset
	[[ $offset == 1500000 ]] || error "offset $offset != 1500000"
	printf "Seeking data from 1500000 ... "
	offset=$(lseek_test -d 1500000 $file)
	echo $offset
	[[ $offset == 2097152 ]] || error "offset $offset != 2097152"

	# start at second component stripe 1 (all data)
	printf "Seeking hole from 3000000 ... "
	offset=$(lseek_test -l 3000000 $file)
	echo $offset
	[[ $offset == 3145728 ]] || error "offset $offset != 3145728"
	printf "Seeking data from 3000000 ... "
	offset=$(lseek_test -d 3000000 $file)
	echo $offset
	[[ $offset == 3000000 ]] || error "offset $offset != 3000000"

	dd_reverse of=$file bs=64K count=10 seek=10 || error "2nd dd fails"
	echo "Add data block at 640K...1280K"

	# start at before new data block, in hole
	printf "Seeking hole from 600000 ... "
	offset=$(lseek_test -l 600000 $file)
	echo $offset
	[[ $offset == 600000 ]] || error "offset $offset != 600000"
	printf "Seeking data from 600000 ... "
	offset=$(lseek_test -d 600000 $file)
	echo $offset
	[[ $offset == 655360 ]] || error "offset $offset != 655360"

	# start at the first component new data block
	printf "Seeking hole from 1000000 ... "
	offset=$(lseek_test -l 1000000 $file)
	echo $offset
	[[ $offset == 1310720 ]] || error "offset $offset != 1310720"
	printf "Seeking data from 1000000 ... "
	offset=$(lseek_test -d 1000000 $file)
	echo $offset
	[[ $offset == 1000000 ]] || error "offset $offset != 1000000"

	# start at second component stripe 2, new data
	printf "Seeking hole from 1200000 ... "
	offset=$(lseek_test -l 1200000 $file)
	echo $offset
	[[ $offset == 1310720 ]] || error "offset $offset != 1310720"
	printf "Seeking data from 1200000 ... "
	offset=$(lseek_test -d 1200000 $file)
	echo $offset
	[[ $offset == 1200000 ]] || error "offset $offset != 1200000"

	# start beyond file end
	printf "Using offset > filesize ... "
	lseek_test -l 6000000 $file && error "lseek should fail"
	printf "Using offset > filesize ... "
	lseek_test -d 6000000 $file && error "lseek should fail"

	printf "Done\n\n"
}

test_430a() {
	$LCTL get_param osc.*.import | grep -q 'connect_flags:.*seek' ||
		skip "OST does not support SEEK_HOLE"

	local file=$DIR/$tdir/$tfile

	mkdir -p $DIR/$tdir

	$LFS setstripe -E 1M -c2 -S 64K -E 10M -c2 -S 1M $file
	echo "Component #1: 1M, 2 stripes 64K, component #2: EOF, 2 stripes 1M"
	lseek_test_430 $file
	rm $file
	$LFS setstripe -c2 -S 512K $file
	echo "Two stripes, stripe size 512K"
	lseek_test_430 $file
	rm $file
	# FLR with stale mirror
	$LFS setstripe -N -E 512K -c1 -S 64K -E eof -c2 -S 512K \
		       -N -c2 -S 1M $file
	echo "Mirrored file:"
	echo "Component #1: 512K, stripe 64K, component #2: EOF, 2 stripes 512K"
	echo "Plain 2 stripes 1M"
	lseek_test_430 $file
	rm $file

	$LCTL get_param mdc.*.import | grep -q 'connect_flags:.*seek' ||
		skip "MDT does not support SEEK_HOLE"

	$LFS setstripe -E 1M -L mdt -E eof -c2 $file
	# OST stripe #1 will have continuous data at [1M, 3M)
	# OST stripe #2 is empty
	echo "Component #1: 1M DoM, component #2: EOF, 2 stripes 1M"
	lseek_test_430 $file
	rm $file
}
run_test 430a "lseek: SEEK_DATA/SEEK_HOLE basic functionality"

test_430b() {
	$LCTL get_param osc.*.import | grep -q 'connect_flags:.*seek' ||
		skip "OST does not support SEEK_HOLE"

	local offset
	local file=$DIR/$tdir/$tfile

	mkdir -p $DIR/$tdir
	# Empty layout lseek should fail
	$MCREATE $file
	# seek from 0
	printf "Seeking hole from 0 ... "
	lseek_test -l 0 $file && error "lseek should fail"
	printf "Seeking data from 0 ... "
	lseek_test -d 0 $file && error "lseek should fail"
	rm $file

	# 1M-hole file
	$LFS setstripe -E 1M -c2 -E eof $file
	$TRUNCATE $file 1048576
	printf "Seeking hole from 1000000 ... "
	offset=$(lseek_test -l 1000000 $file)
	echo $offset
	[[ $offset == 1000000 ]] || error "offset $offset != 1000000"
	printf "Seeking data from 1000000 ... "
	lseek_test -d 1000000 $file && error "lseek should fail"
	rm $file

	# full component followed by non-inited one
	$LFS setstripe -E 1M -c2 -E eof $file
	dd if=/dev/urandom of=$file bs=1M count=1
	printf "Seeking hole from 1000000 ... "
	offset=$(lseek_test -l 1000000 $file)
	echo $offset
	[[ $offset == 1048576 ]] || error "offset $offset != 1048576"
	printf "Seeking hole from 1048576 ... "
	lseek_test -l 1048576 $file && error "lseek should fail"
	# init second component and truncate back
	echo "123" >> $file
	$TRUNCATE $file 1048576
	printf "Seeking hole from 1000000 ... "
	offset=$(lseek_test -l 1000000 $file)
	echo $offset
	[[ $offset == 1048576 ]] || error "offset $offset != 1048576"
	printf "Seeking hole from 1048576 ... "
	lseek_test -l 1048576 $file && error "lseek should fail"
	# boundary checks for big values
	dd if=/dev/urandom of=$file.10g bs=1 count=1 seek=10G
	offset=$(lseek_test -d 0 $file.10g)
	[[ $offset == 10737418240 ]] || error "offset $offset != 10737418240"
	dd if=/dev/urandom of=$file.100g bs=1 count=1 seek=100G
	offset=$(lseek_test -d 0 $file.100g)
	[[ $offset == 107374182400 ]] || error "offset $offset != 107374182400"
	return 0
}
run_test 430b "lseek: SEEK_DATA/SEEK_HOLE special cases"

test_430c() {
	$LCTL get_param osc.*.import | grep -q 'connect_flags:.*seek' ||
		skip "OST does not support SEEK_HOLE"

	local file=$DIR/$tdir/$tfile
	local start

	mkdir -p $DIR/$tdir
	stack_trap "rm -f $file $file.tmp"
	dd if=/dev/urandom of=$file bs=1k count=1 seek=5M || error "dd failed"

	# cp version 8.33+ prefers lseek over fiemap
	local ver=$(cp --version | awk '{ print $4; exit; }')

	echo "cp $ver installed"
	if (( $(version_code $ver) >= $(version_code 8.33) )); then
		start=$SECONDS
		time cp -v $file $file.tmp || error "cp $file failed"
		(( SECONDS - start < 5 )) || {
			strace cp $file $file.tmp |&
				grep -E "open|read|seek|FIEMAP" |
				grep -A 100 $file
			error "cp: too long runtime $((SECONDS - start))"
		}
	else
		echo "cp test skipped due to $ver < 8.33"
	fi

	# tar version 1.29+ supports SEEK_HOLE/DATA
	ver=$(tar --version | awk '{ print $4; exit; }')
	echo "tar $ver installed"
	if (( $(version_code $ver) >= $(version_code 1.29) )); then
		start=$SECONDS
		time tar cvf $file.tmp --sparse $file || error "tar $file error"
		(( SECONDS - start < 5 )) || {
			strace tar cf $file.tmp --sparse $file |&
				grep -E "open|read|seek|FIEMAP" |
				grep -A 100 $file
			error "tar: too long runtime $((SECONDS - start))"
		}
	else
		echo "tar test skipped due to $ver < 1.29"
	fi
}
run_test 430c "lseek: external tools check"

test_431() { # LU-14187
	local file=$DIR/$tdir/$tfile

	mkdir -p $DIR/$tdir
	$LFS setstripe -c 1 -i 0 $file || error "lfs setstripe failed"
	dd if=/dev/urandom of=$file bs=4k count=1
	dd if=/dev/urandom of=$file bs=4k count=1 seek=10 conv=notrunc
	dd if=/dev/urandom of=$file bs=4k count=1 seek=12 conv=notrunc
	#define OBD_FAIL_OST_RESTART_IO	0x251
	do_facet ost1 "$LCTL set_param fail_loc=0x251"
	$LFS setstripe -c 1 -i 0 $file.0 || error "lfs setstripe failed"
	cp $file $file.0
	cancel_lru_locks
	sync_all_data
	echo 3 > /proc/sys/vm/drop_caches
	diff  $file $file.0 || error "data diff"
}
run_test 431 "Restart transaction for IO"

cleanup_test_432() {
	do_facet mgs $LCTL nodemap_activate 0
	wait_nm_sync active
}

test_432() {
	local tmpdir=$TMP/dir432

	(( $MDS1_VERSION >= $(version_code 2.14.52) )) ||
		skip "Need MDS version at least 2.14.52"

	stack_trap cleanup_test_432 EXIT
	mkdir $DIR/$tdir
	mkdir $tmpdir

	do_facet mgs $LCTL nodemap_activate 1
	wait_nm_sync active
	do_facet mgs $LCTL nodemap_modify --name default \
		--property admin --value 1
	do_facet mgs $LCTL nodemap_modify --name default \
		--property trusted --value 1
	cancel_lru_locks mdc
	wait_nm_sync default admin_nodemap
	wait_nm_sync default trusted_nodemap

	if [ $(mv $tmpdir $DIR/$tdir/ 2>&1 |
	       grep -ci "Operation not permitted") -ne 0 ]; then
		error "mv $tmpdir $DIR/$tdir/ hits 'Operation not permitted'"
	fi
}
run_test 432 "mv dir from outside Lustre"

test_433() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	[[ -n "$($LCTL list_param llite.*.inode_cache 2>/dev/null)" ]] ||
		skip "inode cache not supported"

	$LCTL set_param llite.*.inode_cache=0
	stack_trap "$LCTL set_param llite.*.inode_cache=1"

	local count=256
	local first
	local before
	local after

	cancel_lru_locks mdc
	first=$(num_objects)
	test_mkdir $DIR/$tdir || error "mkdir $tdir"
	createmany -m $DIR/$tdir/f $count
	createmany -d $DIR/$tdir/d $count
	ls -l $DIR/$tdir > /dev/null
	stack_trap "rm -rf $DIR/$tdir"

	before=$(num_objects)
	cancel_lru_locks mdc
	after=$(num_objects)

	# sometimes even $before is less than 2 * count
	while (( before > first + count && before - after < count )); do
		sleep 1
		after=$(num_objects)
		wait=$((wait + 1))
		(( wait % 5 == 0 )) && echo "wait $wait seconds objects: $after"
		if (( wait > 60 )); then
			error "inode slab grew from $first ^ $before v $after"
		fi
	done

	echo "lustre_inode_cache grew from $first to $before, then $after after"
}
run_test 433 "ldlm lock cancel releases dentries and inodes"

test_434() {
	local file
	local getxattr_count
	local mdc_stat_param="mdc.$FSNAME-MDT0000*.md_stats"
	local p="$TMP/$TESTSUITE-$TESTNAME.parameters"

	[[ $(getenforce) == "Disabled" ]] ||
		skip "lsm selinux module have to be disabled for this test"

	test_mkdir -i 0 -c1 $DIR/$tdir/ ||
		error "fail to create $DIR/$tdir/ on MDT0000"

	touch $DIR/$tdir/$tfile-{001..100}

	# disable the xattr cache
	save_lustre_params client "llite.*.xattr_cache" > $p
	lctl set_param llite.*.xattr_cache=0
	stack_trap "restore_lustre_params < $p; rm -f $p" EXIT

	# clear clients mdc stats
	clear_stats $mdc_stat_param ||
		error "fail to clear stats on mdc MDT0000"

	for file in $DIR/$tdir/$tfile-{001..100}; do
		getfattr -n security.selinux $file |&
			grep -q "Operation not supported" ||
			error "getxattr on security.selinux should return EOPNOTSUPP"
	done

	getxattr_count=$(calc_stats $mdc_stat_param "getxattr")
	(( getxattr_count < 100 )) ||
		error "client sent $getxattr_count getxattr RPCs to the MDS"
}
run_test 434 "Client should not send RPCs for security.selinux with SElinux disabled"

test_440() {
	if [[ -f $LUSTRE/scripts/bash-completion/lustre ]]; then
		source $LUSTRE/scripts/bash-completion/lustre
	elif [[ -f /usr/share/bash-completion/completions/lustre ]]; then
		source /usr/share/bash-completion/completions/lustre
	else
		skip "bash completion scripts not found"
	fi

	local lctl_completions
	local lfs_completions

	lctl_completions=$(_lustre_cmds lctl)
	if [[ ! $lctl_completions =~ "get_param" ]]; then
		error "lctl bash completion failed"
	fi

	lfs_completions=$(_lustre_cmds lfs)
	if [[ ! $lfs_completions =~ "setstripe" ]]; then
		error "lfs bash completion failed"
	fi
}
run_test 440 "bash completion for lfs, lctl"

test_442() {
	local pid1
	local pid2
	mkdir -p $DIR/$tdir
	multiop $DIR/$tdir/$tfile.1 O_w1 & pid1=$!
	multiop $DIR/$tdir/$tfile.1 O_w1 & pid2=$!
	sleep 1
	touch $DIR/$tdir/$tfile.2
	$LFS swap_layouts -n $DIR/$tdir/$tfile.1 $DIR/$tdir/$tfile.2
	$LCTL set_param fail_loc=0x1430
	kill -USR1 $pid1
	sleep 1
	kill -USR1 $pid2
	wait
}
run_test 442 "truncate vs read/write should not panic"

test_460d() {
	verify_yaml_available || skip_env "YAML verification not installed"
	$LCTL get_param -n sptlrpc.page_pools
	$LCTL get_param -n sptlrpc.page_pools | verify_yaml ||
		error "The output of encrypt_page_pools is not an valid YAML"
}
run_test 460d "Check encrypt pools output"

resident_pages() {
	local file=$1

	vmtouch $file | awk '/Resident Pages:/ {print $3}' |
		awk -F/ '{ print $1 }'
}

# The command "echo 2 > /proc/sys/vm/drop_caches" may revoke the DLM locks
# due to slab cache reclaim. Thus we should avoid to reclaim slab cache for
# DLM locks during testing since it may evict mlock()ed pages due to the
# release of the DLM extent lock.
# After the page cache shrinker is disabled, "echo 3 > /proc/sys/vm/drop_caches"
# and "echo 2 > /proc/sys/vm/drop_caches" will not scan and clear unused pages
# from the LRU list.
disable_page_cache_shrink() {
	local enabled=$($LCTL get_param -n osc.*.enable_page_cache_shrink |
			head -n 1)

	stack_trap "$LCTL set_param osc.*.enable_page_cache_shrink=$enabled"
	$LCTL set_param osc.*.enable_page_cache_shrink=0
}

enable_mlock_pages_check() {
	local enabled=$($LCTL get_param -n llite.*.enable_mlock_pages)

	stack_trap "$LCTL set_param llite.*.enable_mlock_pages=$enabled"
	$LCTL set_param llite.*.enable_mlock_pages=1
}

test_600a() {
	local file=$DIR/$tfile
	local size_mb=100
	local pcnt=$((size_mb * 1024 * 1024 / PAGE_SIZE))

	which vmtouch || skip_env "This test needs vmtouch utility"
	check_set_fallocate_or_skip
	disable_page_cache_shrink
	enable_mlock_pages_check

	fallocate -l ${size_mb}M $file || error "failed to fallocate $file"
	stack_trap "pkill -9 vmtouch || true"
	vmtouch -vltdw -m 1g $file || error "failed to vmtouch $file"

	local rcnt=$(resident_pages $file)

	echo "before drop_caches (0):"
	grep Mlocked: /proc/meminfo
	$LCTL get_param llite.*.max_cached_mb
	echo "drop page caches (1):"
	echo 1 > /proc/sys/vm/drop_caches
	grep Mlocked: /proc/meminfo
	$LCTL get_param llite.*.max_cached_mb
	vmtouch $file
	(( $pcnt == $rcnt )) || error "resident pages are $rcnt, expected $pcnt"

	local unevict_mb

	$LCTL set_param llite.*.unevict_cached_mb=clear
	$LCTL get_param llite.*.unevict_cached_mb
	unevict_mb=$($LCTL get_param -n llite.*.unevict_cached_mb)
	(( $unevict_mb == $size_mb )) ||
		error "unevict_cached_mb is $unevict_mb, expected $size_mb"

	$LCTL set_param $OSC.*$OSC*.osc_unevict_cached_mb=clear
	$LCTL get_param $OSC.*$OSC*.osc_unevict_cached_mb
	unevict_mb=$($LCTL get_param -n $OSC.*$OSC*.osc_unevict_cached_mb |
		     awk '{sum += $1 } END { print sum }')
	(( $unevict_mb == $size_mb )) ||
		error "osc_unevict_cached_mb is $unevict_mb, expected $size_mb"

	# The lock revocation will evict the cached pages protected by it.
	# This is desired behavior for conflict access from the remote client.
	# But how to deal with the lock revocation triggered by LRU lock
	# shrinking on client side, should this kind of locks that protected
	# the mlocked pages be canceled in this case? Or the lock protecting
	# mlock()ed pages should not put into lock LRU list?
	cancel_lru_locks $OSC
	echo "drop lru DLM lock:"
	grep Mlocked: /proc/meminfo
	$LCTL get_param llite.*.max_cached_mb
	$LCTL get_param osc.*.osc_cached_mb
	rcnt=$(resident_pages $file)
	(( $rcnt == 0 )) || error "resident pages are $rcnt, expected zero"
	unevict_mb=$($LCTL get_param -n llite.*.unevict_cached_mb)
	(( $unevict_mb == 0 )) ||
		error "unevict_cached_mb is $unevict_mb, expected 0"
	unevict_mb=$($LCTL get_param -n $OSC.*$OSC*.osc_unevict_cached_mb |
		     awk '{sum += $1 } END { print sum }')
	(( $unevict_mb == 0 )) ||
		error "osc_unevict_cached_mb is $unevict_mb, expected $size_mb"

}
run_test 600a "basic test for mlock()ed file"

test_600b() {
	local file=$DIR/$tfile
	local size_mb=100
	local cache_limit=64
	local max_cached_mb=$($LCTL get_param llite.*.max_cached_mb |
			      awk '/^max_cached_mb/ { print $2 }')

	which vmtouch || skip_env "This test needs vmtouch utility"
	check_set_fallocate_or_skip
	disable_page_cache_shrink
	enable_mlock_pages_check

	fallocate -l ${size_mb}M $file || error "failed to fallocate $file"
	stack_trap "pkill -9 vmtouch || true"

	cancel_lru_locks $OSC
	$LCTL get_param llite.*.max_cached_mb
	stack_trap "$LCTL set_param llite.*.max_cached_mb=$max_cached_mb"
	$LCTL set_param llite.*.max_cached_mb=$cache_limit

	# The required mlock()ed pages (100M) are larger than @max_cached_mb.
	vmtouch -vltdw -m 1g $file || error "failed to mlock $file"
	vmtouch $file
	grep Mlocked: /proc/meminfo

	local used_mb
	local unevict_mb

	echo 1 > /proc/sys/vm/drop_caches
	$LCTL get_param llite.*.max_cached_mb
	$LCTL set_param llite.*.unevict_cached_mb=clear
	used_mb=$($LCTL get_param llite.*.max_cached_mb |
		  awk '/^used_mb/ { print $2 }')
	unevict_mb=$($LCTL get_param -n llite.*.unevict_cached_mb)
	(( $used_mb == 0 )) || error "used_mb is $used_mb, expected 0"
	(( $unevict_mb >= $size_mb - 1)) || # allow a margin of 1 page
		error "unevict_mb is $unevict_mb, expected $size_mb"
}
run_test 600b "mlock a file (via vmtouch) larger than max_cached_mb"

test_600c() {
	local dir=$DIR/$tdir
	local cache_limit=64
	local max_cached_mb=$($LCTL get_param llite.*.max_cached_mb |
			      awk '/^max_cached_mb/ { print $2 }')

	which vmtouch || skip_env "This test needs vmtouch utility"
	check_set_fallocate_or_skip
	disable_page_cache_shrink
	enable_mlock_pages_check

	stack_trap "rm -rf $dir"
	stack_trap "$LCTL set_param llite.*.max_cached_mb=$max_cached_mb"
	$LCTL set_param llite.*.max_cached_mb=$cache_limit
	stack_trap "pkill -9 vmtouch || true"

	local size=$((64 * 1048576))
	local file1=$dir/$tfile.1
	local file2=$dir/$tfile.2

	mkdir $dir || error "failed to mkdir $dir"
	fallocate -l $size $file1 || error "failed to fallocate $file1"
	fallocate -l $size $file2 || error "failed to fallocate $file2"
	cancel_lru_locks $OSC

	vmtouch -vltdw -m 1g $file1 || error "failed to vmtouch $file1"
	$LCTL get_param llite.*.max_cached_mb
	$LCTL set_param llite.*.unevict_cached_mb=clear
	$LCTL get_param llite.*.max_cached_mb

	local cached_mb=$($LCTL get_param llite.*.max_cached_mb |
			  awk '/^used_mb/ { print $2 }')

	(( $cached_mb == 0 )) || error "expected used_mb 0 got $cached_mb"
	cached_mb=$($LCTL get_param llite.*.max_cached_mb |
		    awk '/^unevict_mb/ { print $2 }')
	(( $cached_mb == 64 )) || error "expected unevict_mb 64 got $cached_mb"

	vmtouch -vt $file2 || error "failed to vmtouch $file2"
	echo 3 > /proc/sys/vm/drop_caches
	dd if=$file2 of=/dev/null bs=1M count=64 ||
		error "failed to reading $file2 into cache"

	pkill -9 vmtouch || error "failed to kill vmtouch"
	vmtouch -vt $file2 || error "failed to load $files into cache"
	$LCTL get_param llite.*.max_cached_mb
	echo 1 > /proc/sys/vm/drop_caches
	$LCTL set_param llite.*.unevict_cached_mb=clear
	cached_mb=$($LCTL get_param llite.*.max_cached_mb |
		    awk '/^used_mb/ { print $2 }')
	(( $cached_mb == 0 )) || error "expected used_mb 0 got $cached_mb"
	cached_mb=$($LCTL get_param llite.*.max_cached_mb |
		    awk '/^unevict_mb/ { print $2 }')
	(( $cached_mb == 0 )) || error "expected unevict_mb 0 got $cached_mb"
}
run_test 600c "Test I/O when mlocked page count > @max_cached_mb"

test_600d_base() {
	local mlcksz=$1
	local fsz=$2
	local n=$3
	local dir=$DIR/$tdir
	local mlckf=$dir/mlockfile

	echo "mlock size: $mlcksz file size: $fsz, n: $n"
	mkdir -p $dir || error "mkdir $dir failed"

	fallocate -l $mlcksz $mlckf || error "failed to fallocate $mlckf"
	for ((i = 0; i < $n; i++)); do
		fallocate -l $fsz $dir/$tfile.$i ||
			error "failed to fallocate $dir/$tfile.$i"
	done

	cancel_lru_locks $OSC

	declare -a pids

	vmtouch -vltdw -m 1G $mlckf || error "failed to mlock $mlckf"
	for ((i = 0; i < $n; i++)); do
		vmtouch -t -m 1g $dir/$tfile.$i &
		pids[i]=$!
	done

	cat /proc/meminfo | grep 'Mlocked'
	$LCTL get_param llite.*.max_cached_mb
	echo "drop caches:"
	echo 1 > /proc/sys/vm/drop_caches
	$LCTL set_param llite.*.unevict_cached_mb=clear
	$LCTL get_param llite.*.max_cached_mb

	for ((i = 0; i < $n; i++)); do
		wait ${pids[i]} || error "touch $dir/$tfile.$i failed: rc = $?"
	done

	cat /proc/meminfo | grep 'Mlocked:'
	pkill -9 vmtouch || true
	rm -rvf $dir || error "failed to rm $dir"
}

test_600d() {
	local dir=$DIR/$tdir
	local cache_limit=64
	local max_cached_mb=$($LCTL get_param llite.*.max_cached_mb |
			      awk '/^max_cached_mb/ { print $2 }')

	which vmtouch || skip_env "This test needs vmtouch utility"
	check_set_fallocate_or_skip
	disable_page_cache_shrink
	enable_mlock_pages_check

	stack_trap "rm -rf $dir"
	stack_trap "$LCTL set_param llite.*.max_cached_mb=$max_cached_mb"
	$LCTL set_param llite.*.max_cached_mb=$cache_limit
	stack_trap "pkill -9 vmtouch || true"

	local size=$((cache_limit * 1048576))

	test_600d_base $((size - PAGE_SIZE)) 4096 16
	test_600d_base $((size - 2 * PAGE_SIZE)) 16384 16
}
run_test 600d "Test I/O with limited LRU page slots (some was mlocked)"

prep_801() {
	[[ $MDS1_VERSION -lt $(version_code 2.9.55) ]] ||
	[[ $OST1_VERSION -lt $(version_code 2.9.55) ]] &&
		skip "Need server version at least 2.9.55"

	start_full_debug_logging
}

post_801() {
	stop_full_debug_logging
}

barrier_stat() {
	if (( $MDS1_VERSION >= $(version_code 2.16.50) )); then
		barrier_stat="barrier stat"
	else
		barrier_stat="barrier_stat"
	fi
	if [ $MGS_VERSION -le $(version_code 2.10.0) ]; then
		local st=$(do_facet mgs $LCTL $barrier_stat $FSNAME |
			   awk '/The barrier for/ { print $7 }')
		echo $st
	else
		local st=$(do_facet mgs $LCTL $barrier_stat -s $FSNAME)
		echo \'$st\'
	fi
}

barrier_expired() {
	local expired

	if [ $MGS_VERSION -le $(version_code 2.10.0) ]; then
		expired=$(do_facet mgs $LCTL barrier_stat $FSNAME |
			  awk '/will be expired/ { print $7 }')
	else
		expired=$(do_facet mgs $LCTL barrier_stat -t $FSNAME)
	fi

	echo $expired
}

test_801a() {
	prep_801

	echo "Start barrier_freeze at: $(date)"
	#define OBD_FAIL_BARRIER_DELAY		0x2202
	do_facet mgs $LCTL set_param fail_val=5 fail_loc=0x2202
	# Do not reduce barrier time - See LU-11873
	do_facet mgs $LCTL barrier_freeze $FSNAME 20 &

	sleep 2
	local b_status=$(barrier_stat)
	echo "Got barrier status at: $(date)"
	[ "$b_status" = "'freezing_p1'" ] ||
		error "(1) unexpected barrier status $b_status"

	do_facet mgs $LCTL set_param fail_val=0 fail_loc=0
	wait
	b_status=$(barrier_stat)
	[ "$b_status" = "'frozen'" ] ||
		error "(2) unexpected barrier status $b_status"

	local expired=$(barrier_expired)
	echo "sleep $((expired + 3)) seconds, then the barrier will be expired"
	sleep $((expired + 3))

	b_status=$(barrier_stat)
	[ "$b_status" = "'expired'" ] ||
		error "(3) unexpected barrier status $b_status"

	# Do not reduce barrier time - See LU-11873
	do_facet mgs $LCTL barrier_freeze $FSNAME 20 ||
		error "(4) fail to freeze barrier"

	b_status=$(barrier_stat)
	[ "$b_status" = "'frozen'" ] ||
		error "(5) unexpected barrier status $b_status"

	echo "Start barrier_thaw at: $(date)"
	#define OBD_FAIL_BARRIER_DELAY		0x2202
	do_facet mgs $LCTL set_param fail_val=5 fail_loc=0x2202
	do_facet mgs $LCTL barrier_thaw $FSNAME &

	sleep 2
	b_status=$(barrier_stat)
	echo "Got barrier status at: $(date)"
	[ "$b_status" = "'thawing'" ] ||
		error "(6) unexpected barrier status $b_status"

	do_facet mgs $LCTL set_param fail_val=0 fail_loc=0
	wait
	b_status=$(barrier_stat)
	[ "$b_status" = "'thawed'" ] ||
		error "(7) unexpected barrier status $b_status"

	#define OBD_FAIL_BARRIER_FAILURE	0x2203
	do_facet $SINGLEMDS $LCTL set_param fail_loc=0x2203
	do_facet mgs $LCTL barrier_freeze $FSNAME

	b_status=$(barrier_stat)
	[ "$b_status" = "'failed'" ] ||
		error "(8) unexpected barrier status $b_status"

	do_facet $SINGLEMDS $LCTL set_param fail_loc=0
	do_facet mgs $LCTL barrier_thaw $FSNAME

	post_801
}
run_test 801a "write barrier user interfaces and stat machine"

test_801b() {
	prep_801

	mkdir $DIR/$tdir || error "(1) fail to mkdir"
	createmany -d $DIR/$tdir/d 6 || error "(2) fail to mkdir"
	touch $DIR/$tdir/d2/f10 || error "(3) fail to touch"
	touch $DIR/$tdir/d3/f11 || error "(4) fail to touch"
	touch $DIR/$tdir/d4/f12 || error "(5) fail to touch"

	cancel_lru_locks mdc

	# 180 seconds should be long enough
	do_facet mgs $LCTL barrier_freeze $FSNAME 180

	local b_status=$(barrier_stat)
	[ "$b_status" = "'frozen'" ] ||
		error "(6) unexpected barrier status $b_status"

	mkdir $DIR/$tdir/d0/d10 &
	mkdir_pid=$!

	touch $DIR/$tdir/d1/f13 &
	touch_pid=$!

	ln $DIR/$tdir/d2/f10 $DIR/$tdir/d2/f14 &
	ln_pid=$!

	mv $DIR/$tdir/d3/f11 $DIR/$tdir/d3/f15 &
	mv_pid=$!

	rm -f $DIR/$tdir/d4/f12 &
	rm_pid=$!

	stat $DIR/$tdir/d5 || error "(7) stat should succeed"

	# To guarantee taht the 'stat' is not blocked
	b_status=$(barrier_stat)
	[ "$b_status" = "'frozen'" ] ||
		error "(8) unexpected barrier status $b_status"

	# let above commands to run at background
	sleep 5

	ps -p $mkdir_pid || error "(9) mkdir should be blocked"
	ps -p $touch_pid || error "(10) touch should be blocked"
	ps -p $ln_pid || error "(11) link should be blocked"
	ps -p $mv_pid || error "(12) rename should be blocked"
	ps -p $rm_pid || error "(13) unlink should be blocked"

	b_status=$(barrier_stat)
	[ "$b_status" = "'frozen'" ] ||
		error "(14) unexpected barrier status $b_status"

	do_facet mgs $LCTL barrier_thaw $FSNAME
	b_status=$(barrier_stat)
	[ "$b_status" = "'thawed'" ] ||
		error "(15) unexpected barrier status $b_status"

	wait $mkdir_pid || error "(16) mkdir should succeed"
	wait $touch_pid || error "(17) touch should succeed"
	wait $ln_pid || error "(18) link should succeed"
	wait $mv_pid || error "(19) rename should succeed"
	wait $rm_pid || error "(20) unlink should succeed"

	post_801
}
run_test 801b "modification will be blocked by write barrier"

test_801c() {
	[[ $MDSCOUNT -lt 2 ]] && skip_env "needs >= 2 MDTs"
	if (( $MDS1_VERSION >= $(version_code 2.16.50) )); then
		barrier_freeze="barrier freeze"
		barrier_thaw="barrier thaw"
		barrier_rescan="barrier rescan"
	else
		barrier_freeze="barrier_freeze"
		barrier_thaw="barrier_thaw"
		barrier_rescan="barrier_rescan"
	fi

	prep_801

	stop mds2 || error "(1) Fail to stop mds2"

	do_facet mgs $LCTL $barrier_freeze $FSNAME 30

	local b_status=$(barrier_stat)
	[ "$b_status" = "'expired'" ] || [ "$b_status" = "'failed'" ] || {
		do_facet mgs $LCTL $barrier_thaw $FSNAME
		error "(2) unexpected barrier status $b_status"
	}

	do_facet mgs $LCTL $barrier_rescan $FSNAME ||
		error "(3) Fail to rescan barrier bitmap"

	# Do not reduce barrier time - See LU-11873
	do_facet mgs $LCTL $barrier_freeze $FSNAME 20

	b_status=$(barrier_stat)
	[ "$b_status" = "'frozen'" ] ||
		error "(4) unexpected barrier status $b_status"

	do_facet mgs $LCTL $barrier_thaw $FSNAME
	b_status=$(barrier_stat)
	[ "$b_status" = "'thawed'" ] ||
		error "(5) unexpected barrier status $b_status"

	local devname=$(mdsdevname 2)

	start mds2 $devname $MDS_MOUNT_OPTS || error "(6) Fail to start mds2"

	do_facet mgs $LCTL $barrier_rescan $FSNAME ||
		error "(7) Fail to rescan barrier bitmap"

	post_801
}
run_test 801c "rescan barrier bitmap"

test_802b() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	remote_mds_nodsh && skip "remote MDS with nodsh"

	do_facet $SINGLEMDS $LCTL get_param mdt.*.readonly ||
		skip "readonly option not available"

	$LFS mkdir -i 0 -c 1 $DIR/$tdir || error "(1) fail to mkdir"

	cp $LUSTRE/tests/test-framework.sh $DIR/$tdir/ ||
		error "(2) Fail to copy"

	# write back all cached data before setting MDT to readonly
	cancel_lru_locks
	sync_all_data

	do_facet $SINGLEMDS $LCTL set_param mdt.*.readonly=1
	stack_trap "do_facet $SINGLEMDS $LCTL set_param mdt.*.readonly=0" EXIT

	echo "Modify should be refused"
	touch $DIR/$tdir/guard && error "(6) Touch should fail under ro mode"

	echo "Read should be allowed"
	diff $LUSTRE/tests/test-framework.sh $DIR/$tdir/test-framework.sh ||
		error "(7) Read should succeed under ro mode"

	# disable readonly
	do_facet $SINGLEMDS $LCTL set_param mdt.*.readonly=0
}
run_test 802b "be able to set MDTs to readonly"

test_802c() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	do_facet ost1 $LCTL get_param obdfilter.*.readonly ||
		skip "readonly option not available"

	$LFS mkdir -i 0 -c 1 $DIR/$tdir || error "(1) fail to mkdir"

	cp $LUSTRE/tests/test-framework.sh $DIR/$tdir/ ||
		error "(2) Fail to copy"

	# write back all cached data before setting OFD to readonly
	cancel_lru_locks
	sync_all_data

	do_facet ost1 $LCTL set_param obdfilter.*.readonly=1
	stack_trap "do_facet ost1 $LCTL set_param obdfilter.*.readonly=0" EXIT

	echo "Modify should be refused"
	touch $DIR/$tdir/guard && error "(6) Touch should fail under ro mode"

	echo "Read should be allowed"
	diff $LUSTRE/tests/test-framework.sh $DIR/$tdir/test-framework.sh ||
		error "(7) Read should succeed under ro mode"
}
run_test 802c "be able to set OFDs to readonly"

test_803a() {
	[[ $MDSCOUNT -lt 2 ]] && skip_env "needs >= 2 MDTs"
	[ $MDS1_VERSION -lt $(version_code 2.10.54) ] &&
		skip "MDS needs to be newer than 2.10.54"

	mkdir_on_mdt0 $DIR/$tdir
	# Create some objects on all MDTs to trigger related logs objects
	for idx in $(seq $MDSCOUNT); do
		$LFS mkdir -c $MDSCOUNT -i $((idx % $MDSCOUNT)) \
			$DIR/$tdir/dir${idx} ||
			error "Fail to create $DIR/$tdir/dir${idx}"
	done

	wait_delete_completed # ensure old test cleanups are finished
	sleep 3
	echo "before create:"
	$LFS df -i $MOUNT
	local before_used=$($LFS df --output=iused --mdt=0)

	for i in {1..10}; do
		$LFS mkdir -c 1 -i 1 $DIR/$tdir/foo$i ||
			error "Fail to create $DIR/$tdir/foo$i"
	done

	# sync ZFS-on-MDS to refresh statfs data
	wait_zfs_commit mds1
	sleep 3
	echo "after create:"
	$LFS df -i $MOUNT
	local after_used=$($LFS df --output=iused --mdt=0)

	# allow for an llog to be cleaned up during the test
	[ $after_used -ge $((before_used + 10 - 1)) ] ||
		error "before ($before_used) + 10 > after ($after_used)"

	for i in {1..10}; do
		rm -rf $DIR/$tdir/foo$i ||
			error "Fail to remove $DIR/$tdir/foo$i"
	done

	# sync ZFS-on-MDS to refresh statfs data
	wait_zfs_commit mds1
	wait_delete_completed
	sleep 3 # avoid MDT return cached statfs
	echo "after unlink:"
	$LFS df -i $MOUNT
	after_used=$($LFS df --output=iused --mdt=0)

	# allow for an llog to be created during the test
	[ $after_used -le $((before_used + 1)) ] ||
		error "after ($after_used) > before ($before_used) + 1"
}
run_test 803a "verify agent object for remote object"

test_803b() {
	[[ $MDSCOUNT -lt 2 ]] && skip_env "needs >= 2 MDTs"
	[ $MDS1_VERSION -lt $(version_code 2.13.56) ] &&
		skip "MDS needs to be newer than 2.13.56"
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	for i in $(seq 0 $((MDSCOUNT - 1))); do
		$LFS mkdir -i $i $DIR/$tdir.$i || error "mkdir $tdir.$i"
	done

	local before=0
	local after=0

	local tmp

	stat $DIR/$tdir.* >/dev/null || error "stat $tdir.*"
	for i in $(seq 0 $((MDSCOUNT - 1))); do
		tmp=$(do_facet mds$i $LCTL get_param mdt.*-MDT000$i.md_stats |
			awk '/getattr/ { print $2 }')
		before=$((before + tmp))
	done
	stat $DIR/$tdir.* >/dev/null || error "stat $tdir.*"
	for i in $(seq 0 $((MDSCOUNT - 1))); do
		tmp=$(do_facet mds$i $LCTL get_param mdt.*-MDT000$i.md_stats |
			awk '/getattr/ { print $2 }')
		after=$((after + tmp))
	done

	[ $before -eq $after ] || error "getattr count $before != $after"
}
run_test 803b "remote object can getattr from cache"

test_804() {
	[[ $MDSCOUNT -lt 2 ]] && skip_env "needs >= 2 MDTs"
	[ $MDS1_VERSION -lt $(version_code 2.10.54) ] &&
		skip "MDS needs to be newer than 2.10.54"
	[ "$mds1_FSTYPE" != "ldiskfs" ] && skip_env "ldiskfs only test"

	mkdir -p $DIR/$tdir
	$LFS mkdir -c 1 -i 1 $DIR/$tdir/dir0 ||
		error "Fail to create $DIR/$tdir/dir0"

	local fid=$($LFS path2fid $DIR/$tdir/dir0)
	local dev=$(mdsdevname 2)

	do_facet mds2 "$DEBUGFS -c -R 'ls /REMOTE_PARENT_DIR' $dev" |
		grep ${fid} || error "NOT found agent entry for dir0"

	$LFS mkdir -c $MDSCOUNT -i 0 $DIR/$tdir/dir1 ||
		error "Fail to create $DIR/$tdir/dir1"

	touch $DIR/$tdir/dir1/foo0 ||
		error "Fail to create $DIR/$tdir/dir1/foo0"
	fid=$($LFS path2fid $DIR/$tdir/dir1/foo0)
	local rc=0

	for idx in $(seq $MDSCOUNT); do
		dev=$(mdsdevname $idx)
		do_facet mds${idx} \
			"$DEBUGFS -c -R 'ls /REMOTE_PARENT_DIR' $dev" |
			grep ${fid} && rc=$idx
	done

	mv $DIR/$tdir/dir1/foo0 $DIR/$tdir/dir1/foo1 ||
		error "Fail to rename foo0 to foo1"
	if [ $rc -eq 0 ]; then
		for idx in $(seq $MDSCOUNT); do
			dev=$(mdsdevname $idx)
			do_facet mds${idx} \
			"$DEBUGFS -c -R 'ls /REMOTE_PARENT_DIR' $dev" |
			grep ${fid} && rc=$idx
		done
	fi

	mv $DIR/$tdir/dir1/foo1 $DIR/$tdir/dir1/foo2 ||
		error "Fail to rename foo1 to foo2"
	if [ $rc -eq 0 ]; then
		for idx in $(seq $MDSCOUNT); do
			dev=$(mdsdevname $idx)
			do_facet mds${idx} \
			"$DEBUGFS -c -R 'ls /REMOTE_PARENT_DIR' $dev" |
			grep ${fid} && rc=$idx
		done
	fi

	[ $rc -ne 0 ] || error "NOT found agent entry for foo"

	ln $DIR/$tdir/dir1/foo2 $DIR/$tdir/dir0/guard ||
		error "Fail to link to $DIR/$tdir/dir1/foo2"
	mv $DIR/$tdir/dir1/foo2 $DIR/$tdir/dir1/foo0 ||
		error "Fail to rename foo2 to foo0"
	unlink $DIR/$tdir/dir1/foo0 ||
		error "Fail to unlink $DIR/$tdir/dir1/foo0"
	rm -rf $DIR/$tdir/dir0 ||
		error "Fail to rm $DIR/$tdir/dir0"

	for idx in $(seq $MDSCOUNT); do
		rc=0

		stop mds${idx}
		dev=$(mdsdevname $idx)
		run_e2fsck $(facet_active_host mds$idx) $dev -n ||
			rc=$?
		start mds${idx} $dev $MDS_MOUNT_OPTS ||
			error "mount mds$idx failed"
		df $MOUNT > /dev/null 2>&1

		# e2fsck should not return error
		[ $rc -eq 0 ] ||
			error "e2fsck detected error on MDT${idx}: rc=$rc"
	done
}
run_test 804 "verify agent entry for remote entry"

cleanup_805() {
	do_facet $SINGLEMDS zfs set quota=$old $fsset
	unlinkmany $DIR/$tdir/f- 1000000
	trap 0
}

test_805() {
	local zfs_version=$(do_facet mds1 cat /sys/module/zfs/version)
	[ "$mds1_FSTYPE" != "zfs" ] && skip "ZFS specific test"
	[ $(version_code $zfs_version) -lt $(version_code 0.7.2) ] &&
		skip "netfree not implemented before 0.7"
	[[ $MDS1_VERSION -ge $(version_code 2.10.57) ]] ||
		skip "Need MDS version at least 2.10.57"

	local fsset
	local freekb
	local usedkb
	local old
	local quota
	local pref="osd-zfs.$FSNAME-MDT0000."

	# limit available space on MDS dataset to meet nospace issue
	# quickly. then ZFS 0.7.2 can use reserved space if asked
	# properly (using netfree flag in osd_declare_destroy()
	fsset=$(do_facet $SINGLEMDS lctl get_param -n $pref.mntdev)
	old=$(do_facet $SINGLEMDS zfs get -H quota $fsset | \
		gawk '{print $3}')
	freekb=$(do_facet $SINGLEMDS lctl get_param -n $pref.kbytesfree)
	usedkb=$(do_facet $SINGLEMDS lctl get_param -n $pref.kbytestotal)
	let "usedkb=usedkb-freekb"
	let "freekb=freekb/2"
	if let "freekb > 5000"; then
		let "freekb=5000"
	fi
	do_facet $SINGLEMDS zfs set quota=$(((usedkb+freekb)*1024)) $fsset
	trap cleanup_805 EXIT
	mkdir_on_mdt0 $DIR/$tdir
	$LFS setstripe -E 1M -c2 -E 4M -c2 -E -1 -c2 $DIR/$tdir ||
		error "Can't set PFL layout"
	createmany -m $DIR/$tdir/f- 1000000 && error "ENOSPC wasn't met"
	rm -rf $DIR/$tdir || error "not able to remove"
	do_facet $SINGLEMDS zfs set quota=$old $fsset
	trap 0
}
run_test 805 "ZFS can remove from full fs"

# Size-on-MDS test
check_lsom_data()
{
	local file=$1
	local expect=$(stat -c %s $file)
	local msg=$2
	local hybrid=$($LCTL get_param -n llite.*.hybrid_io)

	check_lsom_size $1 $expect $msg

	local blocks=$($LFS getsom -b $file)
	expect=$(stat -c %b $file)

	# ZFS does not allocate blocks immediately after writes, so the block
	# size may be incorrect on ZFS with hybrid or direct IO
	if [[ $hybrid != "1" && "$ost1_FSTYPE" != "zfs" ]]; then
                local blocks=$($LFS getsom -b $file)
                expect=$(stat -c %b $file)
		[[ $blocks == $expect ]] ||
			error "$msg $file expected blocks: $expect, got: $blocks"
	elif [[ $hybrid == "1" && "$ost1_FSTYPE" == "zfs" ]]; then
		if [[ $blocks != $expect ]]; then
			echo "HIO + ZFS, block mismatch is expected"
			echo "$msg $file expected blocks: $expect, got: $blocks"
		fi
        fi
}

check_lsom_size()
{
	local size
	local expect=$2
	local msg=$3

	cancel_lru_locks mdc

	size=$($LFS getsom -s $1)
	[[ $size == $expect ]] ||
		error "$msg $file expected size: $expect, got: $size"
}

test_806() {
	[ $MDS1_VERSION -lt $(version_code 2.11.52) ] &&
		skip "Need MDS version at least 2.11.52"

	local bs=1048576

	$LFS setstripe -c-1 $DIR/$tfile || error "setstripe $tfile failed"

	disable_opencache
	stack_trap "restore_opencache"

	# single-threaded write
	echo "Test SOM for single-threaded write"
	dd if=/dev/zero of=$DIR/$tfile bs=$bs count=1 ||
		error "write $tfile failed"
	check_lsom_size $DIR/$tfile $bs "(0)"
	# Test SOM with DIO write (dd truncates to 0)
	dd if=/dev/zero of=$DIR/$tfile bs=$bs count=1 oflag=direct ||
		error "write $tfile failed"
	check_lsom_size $DIR/$tfile $bs "(1)"

	local num=32
	local size=$(($num * $bs))
	local offset=0
	local i

	echo "Test SOM for single client multi-threaded($num) write"
	$TRUNCATE $DIR/$tfile 0
	for ((i = 0; i < $num; i++)); do
		$MULTIOP $DIR/$tfile Oz${offset}w${bs}c &
		local pids[$i]=$!
		offset=$((offset + $bs))
	done
	for (( i=0; i < $num; i++ )); do
		wait ${pids[$i]}
	done
	check_lsom_size $DIR/$tfile $size "(2)"

	$TRUNCATE $DIR/$tfile 0
	for ((i = 0; i < $num; i++)); do
		offset=$((offset - $bs))
		$MULTIOP $DIR/$tfile Oz${offset}w${bs}c &
		local pids[$i]=$!
	done
	for (( i=0; i < $num; i++ )); do
		wait ${pids[$i]}
	done
	check_lsom_size $DIR/$tfile $size "(3)"

	# multi-client writes
	num=$(get_node_count ${CLIENTS//,/ })
	size=$(($num * $bs))
	offset=0
	i=0

	echo "Test SOM for multi-client ($num) writes"
	$TRUNCATE $DIR/$tfile 0
	for client in ${CLIENTS//,/ }; do
		do_node $client $MULTIOP $DIR/$tfile Oz${offset}w${bs}c &
		local pids[$i]=$!
		i=$((i + 1))
		offset=$((offset + $bs))
	done
	for (( i=0; i < $num; i++ )); do
		wait ${pids[$i]}
	done
	check_lsom_size $DIR/$tfile $offset "(4)"

	i=0
	$TRUNCATE $DIR/$tfile 0
	for client in ${CLIENTS//,/ }; do
		offset=$((offset - $bs))
		do_node $client $MULTIOP $DIR/$tfile Oz${offset}w${bs}c &
		local pids[$i]=$!
		i=$((i + 1))
	done
	for (( i=0; i < $num; i++ )); do
		wait ${pids[$i]}
	done
	check_lsom_size $DIR/$tfile $size "(5)"

	# verify SOM blocks count
	echo "Verify SOM block count"
	$TRUNCATE $DIR/$tfile 0
	$MULTIOP $DIR/$tfile oO_TRUNC:O_RDWR:w$((bs))YSc ||
		error "failed to write file $tfile with fdatasync and fstat"
	check_lsom_data $DIR/$tfile "(6)"

	$TRUNCATE $DIR/$tfile 0
	$MULTIOP $DIR/$tfile oO_TRUNC:O_RDWR:w$((bs * 2))Yc ||
		error "failed to write file $tfile with fdatasync"
	check_lsom_data $DIR/$tfile "(7)"

	$TRUNCATE $DIR/$tfile 0
	$MULTIOP $DIR/$tfile oO_TRUNC:O_RDWR:O_SYNC:w$((bs * 3))c ||
		error "failed to write file $tfile with sync IO"
	check_lsom_data $DIR/$tfile "(8)"

	# verify truncate
	echo "Test SOM for truncate"
	# use ftruncate to sync blocks on close request
	$MULTIOP $DIR/$tfile oO_WRONLY:T16384c
	check_lsom_size $DIR/$tfile 16384 "(9)"
	check_lsom_data $DIR/$tfile "(10)"

	$TRUNCATE $DIR/$tfile 1234
	check_lsom_size $DIR/$tfile 1234 "(11)"
	# sync blocks on the MDT
	$MULTIOP $DIR/$tfile oc
	check_lsom_data $DIR/$tfile "(12)"
}
run_test 806 "Verify Lazy Size on MDS"

verify_som_sync_utility() {
	local utility=$1
	local use_llsom_sync=false

	[[ -z "$FILESET" ]] || skip "Not functional for FILESET set"
	[[ $MDS1_VERSION -ge $(version_code 2.11.52) ]] ||
		skip "Need MDS version at least 2.11.52"

	case $utility in
		llsom_sync ) use_llsom_sync=true ;;
		somsync ) use_llsom_sync=false ;;
		*) error "invalid utility $utility" ;;
	esac

	if $use_llsom_sync; then
		# Registration step
		changelog_register || error "changelog_register failed"
		local cl_user="${CL_USERS[$SINGLEMDS]%% *}"
		changelog_users $SINGLEMDS | grep -q $cl_user ||
			error "User $cl_user not found in changelog_users"
	fi

	rm -rf $DIR/$tdir || error "rm $tdir failed"
	mkdir_on_mdt0 $DIR/$tdir || error "mkdir $tdir failed"
	touch $DIR/$tdir/trunc || error "touch $tdir/trunc failed"
	$TRUNCATE $DIR/$tdir/trunc 1024 || error "truncate $tdir/trunc failed"
	$TRUNCATE $DIR/$tdir/trunc 1048576 ||
		error "truncate $tdir/trunc failed"

	local bs=1048576
	echo "Test SOM for single-threaded write with fsync"
	dd if=/dev/zero of=$DIR/$tdir/single_dd bs=$bs count=1 ||
		error "write $tfile failed"
	sync;sync;sync

	# multi-client wirtes
	local num=$(get_node_count ${CLIENTS//,/ })
	local offset=0
	local -a pids

	echo "Test SOM for multi-client ($num) writes"
	touch $DIR/$tfile || error "touch $tfile failed"
	$TRUNCATE $DIR/$tfile 0
	for client in ${CLIENTS//,/ }; do
		do_node $client $MULTIOP $DIR/$tfile Oz${offset}w${bs}c &
		pids+=( $! )
		offset=$((offset + bs))
	done
	wait ${pids[@]}

	do_rpc_nodes "$CLIENTS" cancel_lru_locks osc
	do_nodes "$CLIENTS" "sync ; sleep 5 ; sync"

	if $use_llsom_sync; then
		$LSOM_SYNC -u $cl_user -m $FSNAME-MDT0000 $MOUNT ||
			error "$LSOM_SYNC failed"
	else
		$LFS somsync $DIR/$tfile ||
			error "$LFS somsync $DIR/$tfile failed"
		find $DIR/$tdir -type f | xargs $LFS path2fid |
			awk '{print $2}' | xargs $LFS somsync --by-fid $DIR ||
				error "$LFS somsync --by-fid $DIR failed"
	fi

	check_lsom_data $DIR/$tdir/trunc "(0)"
	check_lsom_data $DIR/$tdir/single_dd "(1)"
	check_lsom_data $DIR/$tfile "(2)"

	rm -rf $DIR/$tdir
	# Deregistration step
	! $use_llsom_sync || changelog_deregister ||
		error "changelog_deregister failed"
}

test_807a() {
	verify_som_sync_utility llsom_sync
}
run_test 807a "verify LSOM syncing tool"

test_807b() {
	verify_som_sync_utility somsync
}
run_test 807b "verify lfs somsync utility"

check_som_nologged()
{
	local lines=$($LFS changelog $FSNAME-MDT0000 |
		grep 'x=trusted.som' | wc -l)
	[ $lines -ne 0 ] && error "trusted.som xattr is logged in Changelogs"
}

test_808() {
	[ $MDS1_VERSION -lt $(version_code 2.11.55) ] &&
		skip "Need MDS version at least 2.11.55"

	# Registration step
	changelog_register || error "changelog_register failed"

	touch $DIR/$tfile || error "touch $tfile failed"
	check_som_nologged

	dd if=/dev/zero of=$DIR/$tfile bs=1048576 count=1 ||
		error "write $tfile failed"
	check_som_nologged

	$TRUNCATE $DIR/$tfile 1234
	check_som_nologged

	$TRUNCATE $DIR/$tfile 1048576
	check_som_nologged

	# Deregistration step
	changelog_deregister || error "changelog_deregister failed"
}
run_test 808 "Check trusted.som xattr not logged in Changelogs"

check_som_nodata()
{
	$LFS getsom $1
	[[ $? -eq 61 ]] || error "DoM-only file $1 has SOM xattr"
}

test_809() {
	[ $MDS1_VERSION -lt $(version_code 2.11.56) ] &&
		skip "Need MDS version at least 2.11.56"

	$LFS setstripe -E 1M -L mdt $DIR/$tfile ||
		error "failed to create DoM-only file $DIR/$tfile"
	touch $DIR/$tfile || error "touch $tfile failed"
	check_som_nodata $DIR/$tfile

	dd if=/dev/zero of=$DIR/$tfile bs=2048 count=1 ||
		error "write $tfile failed"
	check_som_nodata $DIR/$tfile

	$TRUNCATE $DIR/$tfile 1234
	check_som_nodata $DIR/$tfile

	$TRUNCATE $DIR/$tfile 4097
	check_som_nodata $DIR/$file
}
run_test 809 "Verify no SOM xattr store for DoM-only files"

test_810() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	$GSS && skip_env "could not run with gss"
	[[ $OST1_VERSION -gt $(version_code 2.12.58) ]] ||
		skip "OST < 2.12.58 doesn't align checksum"

	set_checksums 1
	stack_trap "set_checksums $ORIG_CSUM" EXIT
	stack_trap "set_checksum_type $ORIG_CSUM_TYPE" EXIT

	local csum
	local before
	local after
	for csum in $CKSUM_TYPES; do
		#define OBD_FAIL_OSC_NO_GRANT	0x411
		$LCTL set_param osc.*.checksum_type=$csum fail_loc=0x411
		for i in "10240 0" "10000 0" "4000 1" "500 1"; do
			eval set -- $i
			dd if=/dev/urandom of=$DIR/$tfile bs=$1 count=2 seek=$2
			before=$(md5sum $DIR/$tfile)
			$LCTL set_param ldlm.namespaces.*osc*.lru_size=clear
			after=$(md5sum $DIR/$tfile)
			[ "$before" == "$after" ] ||
				error "$csum: $before != $after bs=$1 seek=$2"
		done
	done
}
run_test 810 "partial page writes on ZFS (LU-11663)"

test_812a() {
	[ $OST1_VERSION -lt $(version_code 2.12.51) ] &&
		skip "OST < 2.12.51 doesn't support this fail_loc"
	local old

	old=$($LCTL get_param -n osc.*.idle_timeout | head -n 1)
	$LCTL set_param osc.*.idle_timeout=10
	stack_trap "$LCTL set_param osc.*.idle_timeout=$old" EXIT

	$LFS setstripe -c 1 -i 0 $DIR/$tfile
	# ensure ost1 is connected
	stat $DIR/$tfile >/dev/null || error "can't stat"
	wait_osc_import_state client ost1 FULL
	# no locks, no reqs to let the connection idle
	cancel_lru_locks osc

	# delay OST_DISCONNECT on OST1 to put OSC into intermediate state
#define OBD_FAIL_OST_DISCONNECT_DELAY	 0x245
	do_facet ost1 "$LCTL set_param fail_loc=0x245 fail_val=8"
	wait_osc_import_state client ost1 CONNECTING
	do_facet ost1 "$LCTL set_param fail_loc=0 fail_val=0"

	stat $DIR/$tfile >/dev/null || error "can't stat file"
}
run_test 812a "do not drop reqs generated when imp is going to idle (LU-11951)"

test_812b() { # LU-12378
	[ $OST1_VERSION -lt $(version_code 2.12.51) ] &&
		skip "OST < 2.12.51 doesn't support this fail_loc"
	local old

	old=$($LCTL get_param -n osc.*.idle_timeout | head -n 1)
	$LCTL set_param osc.*.idle_timeout=10
	stack_trap "$LCTL set_param osc.*.idle_timeout=$old" EXIT

	$LFS setstripe -c 1 -i 0 $DIR/$tfile || error "setstripe failed"
	# ensure ost1 is connected
	stat $DIR/$tfile >/dev/null || error "can't stat"
	wait_osc_import_state client ost1 FULL
	# no locks, no reqs to let the connection idle
	cancel_lru_locks osc

	# delay OST_DISCONNECT on OST1 to put OSC into intermediate state
#define OBD_FAIL_OST_DISCONNECT_DELAY	 0x245
	do_facet ost1 "$LCTL set_param fail_loc=0x245 fail_val=8"
	wait_osc_import_state client ost1 CONNECTING
	do_facet ost1 "$LCTL set_param fail_loc=0 fail_val=0"

	$LFS quota -u 0 $DIR/ || error "lfs quota should succeed"
	wait_osc_import_state client ost1 IDLE
}
run_test 812b "do not drop no resend request for idle connect"

test_812c() {
	local old

	old=$($LCTL get_param -n osc.*.idle_timeout | head -n 1)

	$LFS setstripe -c 1 -o 0 $DIR/$tfile
	$LFS getstripe $DIR/$tfile
	$LCTL set_param osc.*.idle_timeout=10
	stack_trap "$LCTL set_param osc.*.idle_timeout=$old" EXIT
	# ensure ost1 is connected
	stat $DIR/$tfile >/dev/null || error "can't stat"
	wait_osc_import_state client ost1 FULL
	# no locks, no reqs to let the connection idle
	cancel_lru_locks osc

#define OBD_FAIL_PTLRPC_IDLE_RACE	 0x533
	$LCTL set_param fail_loc=0x80000533
	sleep 15
	dd if=/dev/zero of=$DIR/$tfile count=1 conv=sync || error "dd failed"
}
run_test 812c "idle import vs lock enqueue race"

test_813() {
	local file_heat_sav=$($LCTL get_param -n llite.*.file_heat 2>/dev/null)
	[ -z "$file_heat_sav" ] && skip "no file heat support"

	local readsample
	local writesample
	local readbyte
	local writebyte
	local readsample1
	local writesample1
	local readbyte1
	local writebyte1

	local period_second=$($LCTL get_param -n llite.*.heat_period_second)
	local decay_pct=$($LCTL get_param -n llite.*.heat_decay_percentage)

	$LCTL set_param -n llite.*.file_heat=1
	echo "Turn on file heat"
	echo "Period second: $period_second, Decay percentage: $decay_pct"

	echo "QQQQ" > $DIR/$tfile
	echo "QQQQ" > $DIR/$tfile
	echo "QQQQ" > $DIR/$tfile
	cat $DIR/$tfile > /dev/null
	cat $DIR/$tfile > /dev/null
	cat $DIR/$tfile > /dev/null
	cat $DIR/$tfile > /dev/null

	local out=$($LFS heat_get $DIR/$tfile)

	$LFS heat_get $DIR/$tfile
	readsample=$(echo "$out" | grep 'readsample' | awk '{ print $2 }')
	writesample=$(echo "$out" | grep 'writesample' | awk '{ print $2 }')
	readbyte=$(echo "$out" | grep 'readbyte' | awk '{ print $2 }')
	writebyte=$(echo "$out" | grep 'writebyte' | awk '{ print $2 }')

	[ $readsample -le 4 ] || error "read sample ($readsample) is wrong"
	[ $writesample -le 3 ] || error "write sample ($writesample) is wrong"
	[ $readbyte -le 20 ] || error "read bytes ($readbyte) is wrong"
	[ $writebyte -le 15 ] || error "write bytes ($writebyte) is wrong"

	sleep $((period_second + 3))
	echo "Sleep $((period_second + 3)) seconds..."
	# The recursion formula to calculate the heat of the file f is as
	# follow:
	# Hi+1(f) = (1-P)*Hi(f)+ P*Ci
	# Where Hi is the heat value in the period between time points i*I and
	# (i+1)*I; Ci is the access count in the period; the symbol P refers
	# to the weight of Ci.
	out=$($LFS heat_get $DIR/$tfile)
	$LFS heat_get $DIR/$tfile
	readsample=$(echo "$out" | grep 'readsample' | awk '{ print $2 }')
	writesample=$(echo "$out" | grep 'writesample' | awk '{ print $2 }')
	readbyte=$(echo "$out" | grep 'readbyte' | awk '{ print $2 }')
	writebyte=$(echo "$out" | grep 'writebyte' | awk '{ print $2 }')

	[ $(bc <<< "$readsample <= 4 * $decay_pct / 100") -eq 1 ] ||
		error "read sample ($readsample) is wrong"
	[ $(bc <<< "$writesample <= 3 * $decay_pct / 100") -eq 1 ] ||
		error "write sample ($writesample) is wrong"
	[ $(bc <<< "$readbyte <= 20 * $decay_pct / 100") -eq 1 ] ||
		error "read bytes ($readbyte) is wrong"
	[ $(bc <<< "$writebyte <= 15 * $decay_pct / 100") -eq 1 ] ||
		error "write bytes ($writebyte) is wrong"

	echo "QQQQ" > $DIR/$tfile
	echo "QQQQ" > $DIR/$tfile
	echo "QQQQ" > $DIR/$tfile
	cat $DIR/$tfile > /dev/null
	cat $DIR/$tfile > /dev/null
	cat $DIR/$tfile > /dev/null
	cat $DIR/$tfile > /dev/null

	sleep $((period_second + 3))
	echo "Sleep $((period_second + 3)) seconds..."

	out=$($LFS heat_get $DIR/$tfile)
	$LFS heat_get $DIR/$tfile
	readsample1=$(echo "$out" | grep 'readsample' | awk '{ print $2 }')
	writesample1=$(echo "$out" | grep 'writesample' | awk '{ print $2 }')
	readbyte1=$(echo "$out" | grep 'readbyte' | awk '{ print $2 }')
	writebyte1=$(echo "$out" | grep 'writebyte' | awk '{ print $2 }')

	[ $(bc <<< "$readsample1 <= ($readsample * (100 - $decay_pct) + \
		4 * $decay_pct) / 100") -eq 1 ] ||
		error "read sample ($readsample1) is wrong"
	[ $(bc <<< "$writesample1 <= ($writesample * (100 - $decay_pct) + \
		3 * $decay_pct) / 100") -eq 1 ] ||
		error "write sample ($writesample1) is wrong"
	[ $(bc <<< "$readbyte1 <= ($readbyte * (100 - $decay_pct) + \
		20 * $decay_pct) / 100") -eq 1 ] ||
		error "read bytes ($readbyte1) is wrong"
	[ $(bc <<< "$writebyte1 <= ($writebyte * (100 - $decay_pct) + \
		15 * $decay_pct) / 100") -eq 1 ] ||
		error "write bytes ($writebyte1) is wrong"

	echo "Turn off file heat for the file $DIR/$tfile"
	$LFS heat_set -o $DIR/$tfile

	echo "QQQQ" > $DIR/$tfile
	echo "QQQQ" > $DIR/$tfile
	echo "QQQQ" > $DIR/$tfile
	cat $DIR/$tfile > /dev/null
	cat $DIR/$tfile > /dev/null
	cat $DIR/$tfile > /dev/null
	cat $DIR/$tfile > /dev/null

	out=$($LFS heat_get $DIR/$tfile)
	$LFS heat_get $DIR/$tfile
	readsample=$(echo "$out" | grep 'readsample' | awk '{ print $2 }')
	writesample=$(echo "$out" | grep 'writesample' | awk '{ print $2 }')
	readbyte=$(echo "$out" | grep 'readbyte' | awk '{ print $2 }')
	writebyte=$(echo "$out" | grep 'writebyte' | awk '{ print $2 }')

	[ $readsample -eq 0 ] || error "read sample ($readsample) is wrong"
	[ $writesample -eq 0 ] || error "write sample ($writesample) is wrong"
	[ $readbyte -eq 0 ] || error "read bytes ($readbyte) is wrong"
	[ $writebyte -eq 0 ] || error "write bytes ($writebyte) is wrong"

	echo "Trun on file heat for the file $DIR/$tfile"
	$LFS heat_set -O $DIR/$tfile

	echo "QQQQ" > $DIR/$tfile
	echo "QQQQ" > $DIR/$tfile
	echo "QQQQ" > $DIR/$tfile
	cat $DIR/$tfile > /dev/null
	cat $DIR/$tfile > /dev/null
	cat $DIR/$tfile > /dev/null
	cat $DIR/$tfile > /dev/null

	out=$($LFS heat_get $DIR/$tfile)
	$LFS heat_get $DIR/$tfile
	readsample=$(echo "$out" | grep 'readsample' | awk '{ print $2 }')
	writesample=$(echo "$out" | grep 'writesample' | awk '{ print $2 }')
	readbyte=$(echo "$out" | grep 'readbyte' | awk '{ print $2 }')
	writebyte=$(echo "$out" | grep 'writebyte' | awk '{ print $2 }')

	[ $readsample -gt 0 ] || error "read sample ($readsample) is wrong"
	[ $writesample -gt 0 ] || error "write sample ($writesample) is wrong"
	[ $readbyte -gt 0 ] || error "read bytes ($readbyte) is wrong"
	[ $writebyte -gt 0 ] || error "write bytes ($writebyte) is wrong"

	$LFS heat_set -c $DIR/$tfile
	$LCTL set_param -n llite.*.file_heat=0
	echo "Turn off file heat support for the Lustre filesystem"

	echo "QQQQ" > $DIR/$tfile
	echo "QQQQ" > $DIR/$tfile
	echo "QQQQ" > $DIR/$tfile
	cat $DIR/$tfile > /dev/null
	cat $DIR/$tfile > /dev/null
	cat $DIR/$tfile > /dev/null
	cat $DIR/$tfile > /dev/null

	out=$($LFS heat_get $DIR/$tfile)
	$LFS heat_get $DIR/$tfile
	readsample=$(echo "$out" | grep 'readsample' | awk '{ print $2 }')
	writesample=$(echo "$out" | grep 'writesample' | awk '{ print $2 }')
	readbyte=$(echo "$out" | grep 'readbyte' | awk '{ print $2 }')
	writebyte=$(echo "$out" | grep 'writebyte' | awk '{ print $2 }')

	[ $readsample -eq 0 ] || error "read sample ($readsample) is wrong"
	[ $writesample -eq 0 ] || error "write sample ($writesample) is wrong"
	[ $readbyte -eq 0 ] || error "read bytes ($readbyte) is wrong"
	[ $writebyte -eq 0 ] || error "write bytes ($writebyte) is wrong"

	$LCTL set_param -n llite.*.file_heat=$file_heat_sav
	rm -f $DIR/$tfile
}
run_test 813 "File heat verfication"

test_814()
{
	dd of=$DIR/$tfile seek=128 bs=1k < /dev/null
	echo -n y >> $DIR/$tfile
	cp --sparse=always $DIR/$tfile $DIR/${tfile}.cp || error "copy failed"
	diff $DIR/$tfile $DIR/${tfile}.cp || error "files should be same"
}
run_test 814 "sparse cp works as expected (LU-12361)"

test_815()
{
	writeme -b 100 $DIR/$tfile || error "write 100 bytes failed"
	writeme -b 0 $DIR/$tfile || error "write 0 byte failed"
}
run_test 815 "zero byte tiny write doesn't hang (LU-12382)"

test_816() {
	local ost1_imp=$(get_osc_import_name client ost1)
	local imp_name=$($LCTL list_param osc.$ost1_imp | head -n1 |
			 cut -d'.' -f2)
	local old

	old=$($LCTL get_param -n osc.*.idle_timeout | head -n 1)
	$LCTL set_param osc.*.idle_timeout=10
	stack_trap "$LCTL set_param osc.*.idle_timeout=$old" EXIT

	$LFS setstripe -c 1 -i 0 $DIR/$tfile
	# ensure ost1 is connected

	stat $DIR/$tfile >/dev/null || error "can't stat"
	wait_osc_import_state client ost1 FULL
	# no locks, no reqs to let the connection idle
	cancel_lru_locks osc
	lru_resize_disable osc
	local before
	local now
	before=$($LCTL get_param -n \
		 ldlm.namespaces.$imp_name.lru_size)

	wait_osc_import_state client ost1 IDLE
	dd if=/dev/null of=$DIR/$tfile bs=1k count=1 conv=sync
	now=$($LCTL get_param -n \
	      ldlm.namespaces.$imp_name.lru_size)
	[ $before == $now ] || error "lru_size changed $before != $now"
}
run_test 816 "do not reset lru_resize on idle reconnect"

cleanup_817() {
	umount $tmpdir
	exportfs -u localhost:$DIR/nfsexp
	rm -rf $DIR/nfsexp
}

test_817() {
	systemctl restart nfs-server.service || skip "failed to restart nfsd"

	mkdir -p $DIR/nfsexp
	exportfs -orw,no_root_squash localhost:$DIR/nfsexp ||
		error "failed to export nfs"

	tmpdir=$(mktemp -d /tmp/nfs-XXXXXX)
	stack_trap cleanup_817 EXIT

	mount -t nfs -orw localhost:$DIR/nfsexp $tmpdir ||
		error "failed to mount nfs to $tmpdir"

	cp /bin/true $tmpdir
	$DIR/nfsexp/true || error "failed to execute 'true' command"
}
run_test 817 "nfsd won't cache write lock for exec file"

test_818() {
	test_mkdir -i0 -c1 $DIR/$tdir
	$LFS setstripe -c1 -i0 $DIR/$tdir/$tfile
	$LFS setstripe -c1 -i1 $DIR/$tdir/$tfile
	stop $SINGLEMDS

	# restore osp-syn threads
	stack_trap "fail $SINGLEMDS"

	# disable console ratelimit
	local rl=$(do_facet mds1 $LCTL get_param -n console_ratelimit)
	do_facet mds1 $LCTL set_param console_ratelimit=0
	stack_trap "do_facet mds1 $LCTL set_param console_ratelimit=$rl"

	#define OBD_FAIL_OSP_CANT_PROCESS_LLOG		0x2105
	do_facet $SINGLEMDS lctl set_param fail_loc=0x80002105
	start $SINGLEMDS $(mdsdevname ${SINGLEMDS//mds/}) $MDS_MOUNT_OPTS ||
		error "start $SINGLEMDS failed"
	rm -rf $DIR/$tdir

	local testid=$(echo $TESTNAME | tr '_' ' ')

	do_facet mds1 dmesg | tac | sed "/$testid/,$ d" |
		grep "run LFSCK" || error "run LFSCK is not suggested"
}
run_test 818 "unlink with failed llog"

test_819a() {
	stack_trap "rm -f $DIR/$tfile"
	dd if=/dev/zero of=$DIR/$tfile bs=1M count=1
	cancel_lru_locks osc
	#define OBD_FAIL_OST_2BIG_NIOBUF		0x248
	do_facet $SINGLEMDS lctl set_param fail_loc=0x80000248
	dd if=$DIR/$tfile of=/dev/null bs=1M count=1
	rm -f $TDIR/$tfile
}
run_test 819a "too big niobuf in read"

test_819b() {
	stack_trap "rm -f $DIR/$tfile"
	#define OBD_FAIL_OST_2BIG_NIOBUF		0x248
	do_facet $SINGLEMDS lctl set_param fail_loc=0x80000248
	dd if=/dev/zero of=$DIR/$tfile bs=1M count=1
	cancel_lru_locks osc
	sleep 1
	rm -f $TDIR/$tfile
}
run_test 819b "too big niobuf in write"

function test_820_start_ost() {
	sleep 5

	for num in $(seq $OSTCOUNT); do
		start ost$num $(ostdevname $num) $OST_MOUNT_OPTS
	done
}

test_820() {
	[[ $MDSCOUNT -lt 2 ]] && skip_env "needs >= 2 MDTs"

	mkdir $DIR/$tdir
	umount_client $MOUNT || error "umount failed"
	for num in $(seq $OSTCOUNT); do
		stop ost$num
	done

	# mount client with no active OSTs
	# so that the client can't initialize max LOV EA size
	# from OSC notifications
	mount_client $MOUNT || error "mount failed"
	# delay OST starting to keep this 0 max EA size for a while
	test_820_start_ost &

	# create a directory on MDS2
	test_mkdir -i 1 -c1 $DIR/$tdir/mds2 ||
		error "Failed to create directory"
	# open intent should update default EA size
	# see mdc_update_max_ea_from_body()
	# notice this is the very first RPC to MDS2
	out=$(cp /etc/services $DIR/$tdir/mds2 2>&1)
	ret=$?
	echo $out
	# With SSK, this situation can lead to -EPERM being returned.
	# In that case, simply retry.
	if [ $ret -ne 0 ] && $SHARED_KEY; then
		if echo "$out" | grep -q "not permitted"; then
			cp /etc/services $DIR/$tdir/mds2
			ret=$?
		fi
	fi
	[ $ret -eq 0 ] || error "Failed to copy files to mds$n"
}
run_test 820 "update max EA from open intent"

test_823() {
	local p="$TMP/$TESTSUITE-$TESTNAME.parameters"
	local OST_MAX_PRECREATE=20000

	(( $MDS1_VERSION >= $(version_code 2.14.56) )) ||
		skip "Need MDS version at least 2.14.56"

	save_lustre_params mds1 \
		"osp.$FSNAME-OST*-osc-MDT0000.max_create_count" > $p
	do_facet $SINGLEMDS "$LCTL set_param -n \
		osp.$FSNAME-OST*MDT0000.max_create_count=0"
	do_facet $SINGLEMDS "$LCTL set_param -n \
		osp.$FSNAME-OST0000*MDT0000.max_create_count=$OST_MAX_PRECREATE"

	stack_trap "restore_lustre_params < $p; rm $p"

	do_facet $SINGLEMDS "$LCTL set_param -n \
		osp.$FSNAME-OST*-osc-MDT*.create_count=100200"

	local count=$(do_facet $SINGLEMDS "$LCTL get_param -n \
		      osp.$FSNAME-OST0000*MDT0000.create_count")
	local max=$(do_facet $SINGLEMDS "$LCTL get_param -n \
		    osp.$FSNAME-OST0000*MDT0000.max_create_count")
	local expect_count=$(((($max/2)/256) * 256))

	log "setting create_count to 100200:"
	log " -result- count: $count with max: $max, expecting: $expect_count"

	[[ $count -eq expect_count ]] ||
		error "Create count not set to max precreate."
}
run_test 823 "Setting create_count > OST_MAX_PRECREATE is lowered to maximum"

test_831() {
	[[ $MDS1_VERSION -lt $(version_code 2.14.56) ]] &&
		skip "Need MDS version 2.14.56"

	local sync_changes=$(do_facet $SINGLEMDS \
		$LCTL get_param -n osp.$FSNAME-OST0000-osc-MDT0000.sync_changes)

	[ "$sync_changes" -gt 100 ] &&
		skip "Sync changes $sync_changes > 100 already"

	local p="$TMP/$TESTSUITE-$TESTNAME.parameters"

	$LFS mkdir -i 0 $DIR/$tdir
	$LFS setstripe -c 1 -i 0 $DIR/$tdir

	save_lustre_params mds1 \
		"osp.$FSNAME-OST*-osc-MDT0000.max_sync_changes" > $p
	save_lustre_params mds1	\
		"osp.$FSNAME-OST*-osc-MDT0000.max_rpcs_in_progress" >> $p

	do_facet mds1 "$LCTL set_param -n \
		osp.$FSNAME-OST*-osc-MDT0000.max_sync_changes=100 \
		osp.$FSNAME-OST*-osc-MDT0000.max_rpcs_in_progress=128"
	stack_trap "restore_lustre_params < $p" EXIT

	createmany -o $DIR/$tdir/f- 1000
	unlinkmany $DIR/$tdir/f- 1000 &
	local UNLINK_PID=$!

	while sleep 1; do
		sync_changes=$(do_facet mds1 \
		$LCTL get_param -n osp.$FSNAME-OST0000-osc-MDT0000.sync_changes)
		# the check in the code is racy, fail the test
		# if the value above the limit by 10.
		[ $sync_changes -gt 110 ] && {
			kill -2 $UNLINK_PID
			wait
			error "osp changes throttling failed, $sync_changes>110"
		}
		kill -0 $UNLINK_PID 2> /dev/null || break
	done
	wait
}
run_test 831 "throttling unlink/setattr queuing on OSP"

test_832() {
	(( $MDSCOUNT >= 2 )) || skip "needs >= 2 MDTs"
	(( $MDS1_VERSION >= $(version_code 2.15.52) )) ||
		skip "Need MDS version 2.15.52+"
	is_rmentry_supported || skip "rm_entry not supported"

	mkdir_on_mdt0 $DIR/$tdir || error "mkdir $tdir failed"
	mkdir $DIR/$tdir/local_dir || error "mkdir local_dir failed"
	mkdir_on_mdt -i 1 $DIR/$tdir/remote_dir ||
		error "mkdir remote_dir failed"
	$LFS mkdir -c $MDSCOUNT $DIR/$tdir/striped_dir ||
		error "mkdir striped_dir failed"
	touch $DIR/$tdir/file || error "touch file failed"
	$LFS rm_entry $DIR/$tdir/* || error "lfs rm_entry $tdir/* failed"
	[ -z "$(ls -A $DIR/$tdir)" ] || error "$tdir not empty"
}
run_test 832 "lfs rm_entry"

test_833() {
	local file=$DIR/$tfile

	stack_trap "rm -f $file" EXIT
	dd if=/dev/zero of=$file bs=1M count=50 || error "Write $file failed"

	local wpid
	local rpid
	local rpid2

	# Buffered I/O write
	(
		while [ ! -e $DIR/sanity.833.lck ]; do
			dd if=/dev/zero of=$file bs=1M count=50 conv=notrunc ||
				error "failed to write $file"
			sleep 0.$((RANDOM % 4 + 1))
		done
	)&
	wpid=$!

	# Buffered I/O read
	(
		while [ ! -e $DIR/sanity.833.lck ]; do
			dd if=$file of=/dev/null bs=1M count=50 ||
				error "failed to read $file"
			sleep 0.$((RANDOM % 4 + 1))
		done
	)&
	rpid=$!

	# Direct I/O read
	(
		while [ ! -e $DIR/sanity.833.lck ]; do
			dd if=$file of=/dev/null bs=1M count=50 iflag=direct ||
				error "failed to read $file in direct I/O mode"
			sleep 0.$((RANDOM % 4 + 1))
		done
	)&
	rpid2=$!

	sleep 30
	touch $DIR/sanity.833.lck
	wait $wpid || error "$?: buffered write failed"
	wait $rpid || error "$?: buffered read failed"
	wait $rpid2 || error "$?: direct read failed"
}
run_test 833 "Mixed buffered/direct read and write should not return -EIO"

test_834() {
	local file=$DIR/$tfile

	dd if=/dev/zero of=$file bs=1M count=100 ||
		error "failed to write $file"
	cancel_lru_locks $OSC
	$LCTL set_param llite.*.read_ahead_stats=clear
	# Unfortunately we can not reproduce the panic with the following mmap
	# read with madvise(MADV_HUGEPAGE)...
	$MULTIOP $file OSMJRUc || "failed to $MULTIOP $file"
	$LCTL get_param llite.*.read_ahead_stats

	which fio || skip_env "no fio installed"
	fio --enghelp=mmap | grep 'thp' ||
		skip_env "fio mmap I/O engine does not support THP"

	$TRUNCATE $file $((5 * 1024 * 1024 * 1024)) ||
		error "failed to truncate $file"
	# "--thp=1" indicates to use MADV_HUGEPAGE madvise for fio testing
	# with mmap I/O engine.
	# However, this fio test still can not reproduce the panic also...
	fio --name=read_test --ioengine=mmap --filename=$file --rw=read \
		--bs=1m --thp=1 || error "failed to run fio on $file"
}
run_test 834 "mmap readahead for madvise with MADV_HUGEPAGE"

test_842() {
	(( $MDS1_VERSION >= $(version_code 2.15.62) )) ||
		skip "Need MDS version at least 2.15.62 for ldlm_extent module"

	local oss1=$(facet_host ost1)

	# Try to insert the module.  This will leave results in dmesg
	now=$(date +%s)
	log "STAMP $now" > /dev/kmsg
	do_rpc_nodes $oss1 load_module kunit/ldlm_extent ||
		error "$oss1 load_module ldlm_extent failed"

	do_node $oss1 dmesg | sed -n -e "1,/STAMP $now/d" -e '/ldlm_extent:/p'
	do_node $oss1 rmmod -v ldlm_extent ||
		error "rmmod failed (may trigger a failure in a later test)"
}
run_test 842 "Measure ldlm_extent performance"

test_850() {
	local dir=$DIR/$tdir
	local file=$dir/$tfile
	local statsfile=$dir/all_job_stats.txt

	test_mkdir -p $dir || error "failed to create dir $dir"
	echo "abcdefg" > $file || error "failed to create file $file"

	# read job_stats in the living system
	lljobstat -n 1 ||
		error "failed to run lljobstat on living system"

	$LCTL get_param *.*.job_stats > $statsfile
	lljobstat --statsfile=$statsfile ||
		error "failed to run lljobstat on file $statsfile"
}
run_test 850 "lljobstat can parse living and aggregated job_stats"

test_851() {
	local dir=$DIR/$tdir
	local file=$dir/f_test_851_$$
	local report=/tmp/report_test_851_$$
	local fanotify_prog=monitor_lustrefs
	local pid
	local i

	test_mkdir $dir || error "failed to create dir $dir"

	nice -n -10 $fanotify_prog $DIR > $report & pid=$!
	kill -0 $pid || error "failed to run $fanotify_prog"
	ps -q $pid -eo pid,ni,comm
	stack_trap "kill $pid"
	stack_trap "rm -f $report"

	for i in {1..30}; do
		if grep Started $report; then
			break
		else
			echo "$fanotify_prog did not start working, wait 1 second for $i times..."
			sleep 1
		fi
	done
	((i == 30)) && error "$fanotify_prog did not start working in 30 seconds"

	> $report

	echo "1234567890" > $file
	wait_update_cond $(facet_active_host client) "stat -c %s $report" "-gt" "0" 30 ||
		error "fanotify did not report anything after 30 seconds when file is created"
	grep -a -E "open.*:$file:" $report ||
		error "no open event for writing $file"
	grep -a -E "write.*:$file:" $report ||
		error "no write event for writing $file"
	grep -a -E "close.*:$file:" $report ||
		error "no close event for writing $file"

	> $report
	cat $file
	wait_update_cond $(facet_active_host client) "stat -c %s $report" "-gt" "0" 30 ||
		error "fanotify did not report anything after 30 seconds when file is read"
	grep -a -E "open.*:$file:" $report ||
		error "no open event for reading $file"
	grep -a -E "read.*:$file:" $report ||
		error "no write event for reading $file"
	grep -a -E "close.*:$file:" $report ||
		error "no close event for reading $file"
}
run_test 851 "fanotify can monitor open/read/write/close events for lustre fs"

test_852() {
	(( $MDSCOUNT >= 2 )) || skip "needs >= 2 MDTs"
	(( $MDS1_VERSION >= $(version_code v2_15_62-70-g668dfb53de) )) ||
		skip "Need MDS version at least 2.15.62.70 for intent mkdir"

	local save="$TMP/$TESTSUITE-$TESTNAME.parameters"

	save_lustre_params client "llite.*.intent_mkdir" > $save
	stack_trap "restore_lustre_params < $save; rm -f $save" EXIT
	$LCTL set_param llite.*.intent_mkdir=1

	test_mkdir -p -c$MDSCOUNT $DIR/$tdir
	if [ $MDSCOUNT -ge 2 ]; then
		$LFS setdirstripe -D -c$MDSCOUNT $DIR/$tdir ||
			error "set default dirstripe failed"
	fi

	mkdir $DIR/$tdir/tdir || error "mkdir tdir failed"
	mkdir $DIR/$tdir/tdir/tfile || error "mkdir tdir/tfile failed"
	touch -d "2020-08-25 15:08" $DIR/$tdir/tdir/tfile ||
		error "touch time failed"
	chown 0:0 $DIR/$tdir/tdir/tfile || error "chown 0:0 tdir/tfile failed"
	chmod 755 $DIR/$tdir/tdir/tfile || error "chmod 755 tdir/tfile failed"
}
run_test 852 "mkdir using intent lock for striped directory"

test_853() {
	local file=$DIR/$tfile
	local size=$((PAGE_SIZE * 2))

	dd if=/dev/zero of=$file bs=1M count=100 ||
		error "failed to write $file"
	cancel_lru_locks $OSC
	$LCTL set_param llite.*.read_ahead_stats=clear
	$MULTIOP $file or1048576c || error "failed to read $file"
	$LCTL get_param llite.*.read_ahead_stats

	cancel_lru_locks $OSC
	$LCTL set_param llite.*.read_ahead_stats=clear
	$MULTIOP $file oir1048576z1048576r${size}c ||
		error "failed to read $file"
	$LCTL get_param llite.*.read_ahead_stats

	local ranum=$($LCTL get_param -n llite.*.read_ahead_stats |
		      get_named_value 'readahead.pages' | calc_sum)

	(( ranum == 0 )) || error "should not trigger readahead"

	local rndnum=$($LCTL get_param -n llite.*.read_ahead_stats |
		       get_named_value 'forceread.pages' | calc_sum)

	(( rndnum == 2 )) || error "force random read: $rndnum, expected 2"
}
run_test 853 "Verify that random fadvise works as expected"

test_854() {
	# Save original parameters to use in test and restore later
	local ra_mb=$($LCTL get_param -n llite.*.max_read_ahead_mb) ||
		error "Failed to get max_read_ahead_mb"
	local ra_per_file_mb=$($LCTL get_param -n \
			       llite.*.max_read_ahead_per_file_mb) ||
		error "Failed to get max_read_ahead_per_file_mb"
	local ra_whole_mb=$($LCTL get_param -n \
			    llite.*.max_read_ahead_whole_mb) ||
		error "Failed to get max_read_ahead_whole_mb"

	# Get max_cached_mb value - extract just the numeric value
	local max_cached_mb=$($LCTL get_param llite.*.max_cached_mb |
        		      awk '/^max_cached_mb:/ { print $2 }') ||
        error "Failed to get max_cached_mb"

	# Get full output for max_cached_mb for debug information
	$LCTL get_param llite.*.max_cached_mb ||
		error "Failed to get max_cached_mb details"

	stack_trap "$LCTL set_param -n llite.*.max_read_ahead_mb=$ra_mb" ||
		error "Failed to set up stack_trap for max_read_ahead_mb"
	stack_trap "$LCTL set_param -n \
		llite.*.max_read_ahead_per_file_mb=$ra_per_file_mb" ||
		error "Failed to set stack_trap for max_read_ahead_per_file_mb"
	stack_trap "$LCTL set_param -n \
		llite.*.max_read_ahead_whole_mb=$ra_whole_mb" ||
		error "Failed to set up stack_trap for max_read_ahead_whole_mb"
	stack_trap "$LCTL set_param -n \
		llite.*.max_cached_mb=$max_cached_mb" ||
		error "Failed to set up stack_trap for max_cached_mb"

	log "Initial readahead: $ra_mb/$ra_per_file_mb/$ra_whole_mb MB"
	log "Initial max_cached_mb: $max_cached_mb MB"

	local total_ram_mb=$(($(facet_meminfo client MemTotal) / 1024))
	log "Total RAM: $total_ram_mb MB"

	# Set max_cached_mb to 75% of RAM for the test
	$LCTL set_param -n llite.*.max_cached_mb=75% ||
		error "Failed to set max_cached_mb to 75%"

	# Get new max_cached_mb value - extract just the numeric value
	local new_max_cached_mb=$($LCTL get_param llite.*.max_cached_mb |
				  awk '/^max_cached_mb:/ { print $2 }') ||
		error "Failed to get new max_cached_mb value"

	local exp_cached=$((total_ram_mb * 75 / 100))
	log "max_cached_mb=75%: $new_max_cached_mb MB, expect ~$exp_cached MB"

	(( new_max_cached_mb * 100 / total_ram_mb >= 74 &&
	 new_max_cached_mb * 100 / total_ram_mb <= 76 )) ||
		error "max_cached_mb not 75% of RAM"

	# Test 1: Set max_read_ahead_mb=25% of total RAM
	$LCTL set_param -n llite.*.max_read_ahead_mb=25% ||
		error "Failed to set max_read_ahead_mb to 25%"
	local expect=$((total_ram_mb * 25 / 100))
	ra_mb=$($LCTL get_param -n llite.*.max_read_ahead_mb) ||
		error "Failed to get updated max_read_ahead_mb"
	log "max_ra_mb=25%: got $ra_mb MB, expect ~$expect MB"

	# The actual implementation may limit value differently than expected
	# Accept any value that's at least 10% of RAM and not more than 30%
	(( ra_mb * 100 / total_ram_mb >= 10 &&
	 ra_mb * 100 / total_ram_mb <= 30 )) ||
		error "max_read_ahead_mb=$ra_mb MB not in range (10-30% of RAM)"

	# Test 2: Set max_read_ahead_per_file_mb=5% of total RAM
	$LCTL set_param -n llite.*.max_read_ahead_per_file_mb=5% ||
		error "Failed to set max_read_ahead_per_file_mb to 5%"
	expect=$((total_ram_mb * 5 / 100))
	ra_per_file_mb=$($LCTL get_param -n \
			 llite.*.max_read_ahead_per_file_mb) ||
		error "Failed to get updated max_read_ahead_per_file_mb"
	log "max_ra_per_file_mb=5%: got $ra_per_file_mb MB, expect ~$expect"

	# The actual implementation may limit value differently than expected
	# Just verify that the value is reasonable (not zero and not too large)
	(( ra_per_file_mb > 0 && ra_per_file_mb <= ra_mb )) ||
		error "max_ra_per_file_mb=$ra_per_file_mb MB not in (0-$ra_mb MB)"

	# Test 3: Set max_read_ahead_whole_mb=1% of total RAM
	$LCTL set_param -n llite.*.max_read_ahead_whole_mb=1% ||
		error "Failed to set max_read_ahead_whole_mb to 1%"
	expect=$((total_ram_mb * 1 / 100))
	ra_whole_mb=$($LCTL get_param -n llite.*.max_read_ahead_whole_mb) ||
		error "Failed to get updated max_read_ahead_whole_mb"
	log "max_ra_whole_mb=1%: got $ra_whole_mb MB, expect ~$expect"

	# The actual implementation may limit value differently than expected
	# Just verify that the value is reasonable (not too large)
	(( ra_whole_mb >= 0 && ra_whole_mb <= ra_per_file_mb )) ||
		error "max_ra_whole_mb=$ra_whole_mb MB not in (0-$ra_per_file_mb MB)"

	# Test 4: Verify setting max_read_ahead_mb > 50% is capped at 50%
	# The implementation should enforce the 50% limit by capping the value
	# First try with a value just over 50%
	log "Testing if max_read_ahead_mb=51% is capped at 50%"
	$LCTL set_param -n llite.*.max_read_ahead_mb=51% ||
		error "Failed to set max_read_ahead_mb to 51%"

	# Get the actual value set
	local ra_mb_51=$($LCTL get_param -n llite.*.max_read_ahead_mb) ||
		error "Failed to get max_read_ahead_mb after setting to 51%"
	log "max_read_ahead_mb is $ra_mb_51 MB"

	# Check if the value was actually capped at 50%
	local expect_50=$((total_ram_mb * 50 / 100))
	if (( ra_mb_51 > expect_50 )); then
		error "max_read_ahead_mb $ra_mb_51 MB > 50% of RAM ($expect_50 MB)"
	fi
	log "Value correctly capped at ~50% of RAM ($ra_mb_51 <= $expect_50)"

	# Now try with a much larger value to be sure
	log "Testing if max_read_ahead_mb=90% is capped at 50%"
	$LCTL set_param -n llite.*.max_read_ahead_mb=90% ||
		error "Failed to set max_read_ahead_mb to 90%"

	# Get the actual value set
	local ra_mb_90=$($LCTL get_param -n llite.*.max_read_ahead_mb) ||
		error "Failed to get max_read_ahead_mb after setting to 90%"
	log "max_read_ahead_mb is $ra_mb_90 MB"

	# Check if the value was actually capped at 50%
	if (( ra_mb_90 > expect_50 )); then
		error "max_read_ahead_mb $ra_mb_90 MB > 50% RAM ($expect_50 MB)"
	fi

	log "Value correctly capped at ~50% of RAM ($ra_mb_90 <= $expect_50)"

	# Test 5: Verify max_ra_per_file_mb is capped at max_ra_mb
	log "Test if max_read_ahead_per_file_mb > max_read_ahead_mb is capped"
	$LCTL set_param -n llite.*.max_read_ahead_per_file_mb=60% ||
		error "Failed to set max_read_ahead_per_file_mb to 60%"

	# Get the actual value set
	local ra_per_file_mb_60=$($LCTL get_param -n \
				  llite.*.max_read_ahead_per_file_mb) ||
		error "Fail to get max_read_ahead_per_file_mb after set to 60%"

	log "max_read_ahead_per_file_mb is $ra_per_file_mb_60 MB"

	# Check if the value was capped at max_ra_mb
	if (( ra_per_file_mb_60 > ra_mb_90 )); then
		error "max_read_ahead_per_file_mb $ra_per_file_mb_60 MB exceeds max_read_ahead_mb ($ra_mb_90 MB)"
	fi
	log "Value capped at max_read_ahead_mb ($ra_per_file_mb_60 <= $ra_mb_90)"

	# Test 6: Verify max_ra_whole_mb is capped at max_ra_per_file_mb
	log "Test if max_read_ahead_whole_mb > max_read_ahead_per_file_mb capped"
	$LCTL set_param -n llite.*.max_read_ahead_whole_mb=70% ||
		error "Failed to set max_read_ahead_whole_mb to 70%"

	# Get the actual value set
	local ra_whole_mb_70=$($LCTL get_param -n \
			       llite.*.max_read_ahead_whole_mb) ||
		error "Failed to get max_read_ahead_whole_mb after set to 70%"
	log "max_read_ahead_whole_mb is $ra_whole_mb_70 MB"

	# Check if the value was capped at max_ra_per_file_mb
	if (( ra_whole_mb_70 > ra_per_file_mb_60 )); then
		error "max_read_ahead_whole_mb $ra_whole_mb_70 MB exceeds max_read_ahead_per_file_mb ($ra_per_file_mb_60 MB)"
	fi
	log "Value capped at max_read_ahead_per_file_mb ($ra_whole_mb_70 <= $ra_per_file_mb_60)"

	# Verify max_cached_mb is still set correctly (we set it to 75% earlier)
	new_max_cached_mb=$($LCTL get_param llite.*.max_cached_mb |
			    awk '/^max_cached_mb:/ { print $2 }') ||
		error "Failed to get final max_cached_mb value"
	log "Final max_cached_mb: $new_max_cached_mb MB"

	# We set it to 75% earlier, verify it's still around that value
	(( new_max_cached_mb * 100 / total_ram_mb >= 74 &&
	 new_max_cached_mb * 100 / total_ram_mb <= 76 )) ||
		error "max_cached_mb=$new_max_cached_mb MB not close to 75% of RAM"

	log "max_cached_mb percentage functionality verified successfully"
}
run_test 854 "verify llite.*.max_cached_mb setting"

test_855() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
        [[ $($LCTL get_param mdc.*.import) =~ connect_flags.*readdir_open ]] ||
                skip "server does not support readdir_open"
	local nrfiles=1000
	local fname="$DIR/$tdir/$tfile"

	test_mkdir -c 1 -i 0 "$(dirname $fname)"

	stack_trap "simple_cleanup_common $nrfiles" EXIT

	local old=$($LCTL get_param -n llite.*.dir_read_on_open)
	$LCTL set_param -n llite.*.dir_read_on_open=1
	stack_trap "$LCTL set_param -n llite.*.dir_read_on_open=$old" EXIT

	createmany -m "$fname" $nrfiles

	cancel_lru_locks mdc
	lctl set_param mdc.*.stats clear
	local num_ls=$(ls -1 $DIR/$tdir | wc -l)
	local mds_readpage=$(calc_stats mdc.*.stats mds_readpage)
	(( $mds_readpage == 0 )) || error "readpages: $mds_readpage"
	(( $nrfiles == $num_ls )) || error "incorrect reading dir"
}
run_test 855 "readdir on open validation"

test_860() {
	local file=$DIR/$tfile
	local size

	# Create a test file with known content
	echo "0123456789ABCDEF" > $file
	size=$(stat -c%s $file)
	echo "File size: $size bytes"

	# Test Xe (SEEK_END with offset 0) - should return file size
	local result=$($MULTIOP $file oXepc)
	echo "Xe result: $result"
	(( result == size )) ||
		error "Xe failed: expected $size, got $result"

	# Test Xe with positive offset - seek past EOF
	result=$($MULTIOP $file oXe5pc)
	echo "Xe5 result: $result"
	(( result == size + 5 )) ||
		error "Xe5 failed: expected $((size + 5)), got $result"

	# Test Xe with negative offset - seek before EOF
	result=$($MULTIOP $file oXe-5pc)
	echo "Xe-5 result: $result"
	(( result == size - 5 )) ||
		error "Xe-5 failed: expected $((size - 5)), got $result"

	# Test that Xe actually positions the file pointer correctly
	# by seeking to EOF-3, writing 3 bytes, and verifying file size
	# doesn't change (we're overwriting existing bytes)
	local file2=$DIR/${tfile}.2
	echo "0123456789ABCDEF" > $file2
	local size2=$(stat -c%s $file2)
	$MULTIOP $file2 OXe-3w3c
	local new_size=$(stat -c%s $file2)
	(( new_size == size2 )) ||
		error "Xe-3 positioning failed: size changed from $size2 to $new_size"

	# Test XX reserved prefix - should error
	$MULTIOP $file oXXc 2>&1 | grep -q "reserved for future use" ||
		error "XX should be reserved"
}
run_test 860 "verify multiop Xe (SEEK_END) command"

#
# tests that do cleanup/setup should be run at the end
#

test_900() {
	[ $PARALLEL == "yes" ] && skip "skip parallel run"
	local ls

	#define OBD_FAIL_MGC_PAUSE_PROCESS_LOG   0x903
	$LCTL set_param fail_loc=0x903

	cancel_lru_locks MGC

	FAIL_ON_ERROR=true cleanup
	FAIL_ON_ERROR=true setup
}
run_test 900 "umount should not race with any mgc requeue thread"

# LUS-6253/LU-11185
test_901() {
	local old
	local count
	local oldc
	local newc
	local olds
	local news
	[ $PARALLEL == "yes" ] && skip "skip parallel run"

	# some get_param have a bug to handle dot in param name
	cancel_lru_locks MGC
	old=$(mount -t lustre | wc -l)
	# 1 config+sptlrpc
	# 2 params
	# 3 nodemap
	# 4 IR
	old=$((old * 4))
	oldc=0
	count=0
	while [ $old -ne $oldc ]; do
		oldc=$($LCTL get_param -n 'ldlm.namespaces.MGC*.lock_count')
		sleep 1
		((count++))
		if [ $count -ge $TIMEOUT ]; then
			error "too large timeout"
		fi
	done
	umount_client $MOUNT || error "umount failed"
	mount_client $MOUNT || error "mount failed"
	cancel_lru_locks MGC
	newc=$($LCTL get_param -n 'ldlm.namespaces.MGC*.lock_count')

	[ $oldc -lt $newc ] && error "mgc lock leak ($oldc != $newc)"

	return 0
}
run_test 901 "don't leak a mgc lock on client umount"

# LU-13377
test_902() {
	[ $CLIENT_VERSION -lt $(version_code 2.13.52) ] &&
		skip "client does not have LU-13377 fix"
	#define OBD_FAIL_LLITE_SHORT_COMMIT 0x1415
	$LCTL set_param fail_loc=0x1415
	dd if=/dev/zero of=$DIR/$tfile bs=1M count=1
	cancel_lru_locks osc
	rm -f $DIR/$tfile
}
run_test 902 "test short write doesn't hang lustre"

# LU-14711
test_903() {
	$LFS setstripe -i 0 -c 1 $DIR/$tfile $DIR/${tfile}-2
	echo "blah" > $DIR/${tfile}-2
	dd if=/dev/zero of=$DIR/$tfile bs=1M count=6 conv=fsync
	#define OBD_FAIL_OSC_SLOW_PAGE_EVICT 0x417
	$LCTL set_param fail_loc=0x417 fail_val=20

	mv $DIR/${tfile}-2 $DIR/$tfile # Destroys the big object
	sleep 1 # To start the destroy
	wait_destroy_complete 150 || error "Destroy taking too long"
	cat $DIR/$tfile > /dev/null || error "Evicted"
}
run_test 903 "Test long page discard does not cause evictions"

test_904() {
	[ "$mds1_FSTYPE" == "ldiskfs" ] || skip "ldiskfs only test"
	do_facet mds1 $DEBUGFS -R features $(mdsdevname 1) |
		grep -q project || skip "skip project quota not supported"

	local testfile="$DIR/$tdir/$tfile"
	local xattr="trusted.projid"
	local projid
	local mdts=$(mdts_nodes)
	local saved=$(do_facet mds1 $LCTL get_param -n \
		osd-ldiskfs.*MDT0000.enable_projid_xattr)

	do_nodes $mdts $LCTL set_param osd-ldiskfs.*MDT*.enable_projid_xattr=0
	stack_trap "do_nodes $mdts $LCTL set_param \
		osd-ldiskfs.*MDT*.enable_projid_xattr=$saved"

	mkdir -p $DIR/$tdir
	touch $testfile
	#hide projid xattr on server
	$LFS project -p 1 $testfile ||
		error "set $testfile project id failed"
	getfattr -m - $testfile | grep $xattr &&
		error "do not show trusted.projid when disabled on server"
	do_nodes $mdts $LCTL set_param osd-ldiskfs.*MDT*.enable_projid_xattr=1
	#should be hidden when projid is 0
	$LFS project -p 0 $testfile ||
		error "set $testfile project id failed"
	getfattr -m - $testfile | grep $xattr &&
		error "do not show trusted.projid with project ID 0"

	#still can getxattr explicitly
	projid=$(getfattr -n $xattr $testfile |
		sed -n 's/^trusted\.projid="\(.*\)"/\1/p')
	[ $projid == "0" ] ||
		error "projid expected 0 not $projid"

	#set the projid via setxattr
	setfattr -n $xattr -v "1000" $testfile ||
		error "setattr failed with $?"
	projid=($($LFS project $testfile))
	[ ${projid[0]} == "1000" ] ||
		error "projid expected 1000 not $projid"

	#check the new projid via getxattr
	$LFS project -p 1001 $testfile ||
		error "set $testfile project id failed"
	getfattr -m - $testfile | grep $xattr ||
		error "should show trusted.projid when project ID != 0"
	projid=$(getfattr -n $xattr $testfile |
		sed -n 's/^trusted\.projid="\(.*\)"/\1/p')
	[ $projid == "1001" ] ||
		error "projid expected 1001 not $projid"

	#try to set invalid projid
	setfattr -n $xattr -v "4294967295" $testfile &&
		error "set invalid projid should fail"

	#remove the xattr means setting projid to 0
	setfattr -x $xattr $testfile ||
		error "setfattr failed with $?"
	projid=($($LFS project $testfile))
	[ ${projid[0]} == "0" ] ||
		error "projid expected 0 not $projid"

	#should be hidden when parent has inherit flag and same projid
	$LFS project -srp 1002 $DIR/$tdir ||
		error "set $tdir project id failed"
	getfattr -m - $testfile | grep $xattr &&
		error "do not show trusted.projid with inherit flag"

	#still can getxattr explicitly
	projid=$(getfattr -n $xattr $testfile |
		sed -n 's/^trusted\.projid="\(.*\)"/\1/p')
	[ $projid == "1002" ] ||
		error "projid expected 1002 not $projid"
}
run_test 904 "virtual project ID xattr"

# LU-8582
test_905() {
	(( $OST1_VERSION >= $(version_code 2.15.50.220) )) ||
		skip "need OST version >= 2.15.50.220 for fail_loc"

	remote_ost_nodsh && skip "remote OST with nodsh"
	$LFS setstripe -c -1 -i 0 $DIR/$tfile || error "setstripe failed"

	$LFS ladvise -a willread $DIR/$tfile || error "ladvise does not work"

	#define OBD_FAIL_OST_OPCODE 0x253
	# OST_LADVISE = 21
	do_facet ost1 "$LCTL set_param fail_val=21 fail_loc=0x0253"
	$LFS ladvise -a willread $DIR/$tfile &&
		error "unexpected success of ladvise with fault injection"
	$LFS ladvise -a willread $DIR/$tfile |&
		grep -q "Operation not supported"
	(( $? == 0 )) || error "unexpected stderr of ladvise with fault injection"
}
run_test 905 "bad or new opcode should not stuck client"

test_906() {
	grep -q io_uring_setup /proc/kallsyms ||
		skip "Client OS does not support io_uring I/O engine"
	io_uring_probe || skip "kernel does not support io_uring fully"
	which fio || skip_env "no fio installed"
	fio --enghelp | grep -q io_uring ||
		skip_env "fio does not support io_uring I/O engine"

	local file=$DIR/$tfile
	local ioengine="io_uring"
	local numjobs=2
	local size=50M

	fio --name=seqwrite --ioengine=$ioengine	\
		--bs=$PAGE_SIZE --direct=1 --numjobs=$numjobs	\
		--iodepth=64 --size=$size --filename=$file --rw=write ||
		error "fio seqwrite $file failed"

	fio --name=seqread --ioengine=$ioengine	\
		--bs=$PAGE_SIZE --direct=1 --numjobs=$numjobs	\
		--iodepth=64 --size=$size --filename=$file --rw=read ||
		error "fio seqread $file failed"

	rm -f $file || error "rm -f $file failed"
}
run_test 906 "Simple test for io_uring I/O engine via fio"

test_907() {
	local max_pages=$($LCTL get_param -n osc.*.max_pages_per_rpc | head -n1)

	# set stripe size to max rpc size
	$LFS setstripe -i 0 -c 2 -S $((max_pages * PAGE_SIZE)) $DIR/$tfile
	$LFS getstripe $DIR/$tfile
#define OBD_FAIL_OST_EROFS               0x216
	do_facet ost1 "$LCTL set_param fail_val=3 fail_loc=0x80000216"

	local bs=$((max_pages * PAGE_SIZE / 16))

	# write full one stripe and one block
	dd if=/dev/zero of=$DIR/$tfile bs=$bs count=17 || error "dd failed"

	rm $DIR/$tfile || error "rm failed"
}
run_test 907 "write rpc error during unlink"

test_908a() {
	local patch_ver=$(version_code v2_16_50-161-ge33d196b93)
	(( $MGS_VERSION >= $patch_ver )) ||
		skip "need MGS >= 2.16.50.161 for llog change timestamps"
	[[ $(facet_fstype mgs) == ldiskfs ]] || skip "ldiskfs only test"

	local format_ver=($(do_facet mgs $LCTL llog_print --raw params |
			    awk '/version/ { print $10 }'))
        (( $(version_code $format_ver) > $patch_ver )) ||
                skip "MGS configured with version $format_ver need 2.16.50.161"

	local dev=$(facet_device mgs)
	local cmd="debugfs -c -R 'stat CONFIGS/params' $dev"

	# ctime: value from debugfs is in hex
	local base_time=$(date -d "24 hours ago" +%s)
	local ctime_mgs=$(do_facet mgs "$cmd" |&
			  awk -F'[: ]' '/ctime:/ { print $4 }')
	ctime_mgs=$((ctime_mgs))
	echo "ctime_mgs=$ctime_mgs, base_time=$base_time"
	(( "$ctime_mgs" > "$base_time" )) ||
		error "invalid ctime $ctime_mgs <= $base_time"
}
run_test 908a "llog created with valid ctime"

test_908b() {
	(( MDS1_VERSION >= $(version_code v2_16_50-161-ge33d196b93) )) ||
		skip "need MDS >= 2.16.50.161 for llog write timestamps"
	[[ "$mds1_FSTYPE" == ldiskfs ]] || skip "ldiskfs only test"

	local dev=$(mdsdevname 1)

	changelog_register || error "cannot register changelog user"
	# set changelog_mask to ALL
	changelog_chmask "ALL"
	changelog_clear

	for ((i=0; i<100; i++)); do
		echo "$i" > $DIR/$tfile${i}
		rm $DIR/$tfile${i}
	done
	sleep 5

	changelog_deregister || error "changelog_deregister failed"

	local cmd="debugfs -c -R 'stat changelog_catalog' $dev"

	# ctime: and mtime: values from debugfs are in hex
	local ctime_mds=$(do_facet mds1 "$cmd" |&
			  awk -F'[: ]' '/ctime:/ { print $4 }')
	ctime_mds=$((ctime_mds))
	local mtime_mds=$(do_facet mds1 "$cmd" |&
			  awk -F'[: ]' '/mtime:/ { print $4 }')
	mtime_mds=$((mtime_mds))

	echo "ctime_mds=$ctime_mds, mtime_mds=$mtime_mds"
	(( "$mtime_mds" > "$ctime_mds" )) ||
		error "invalid mtime $mtime_mds <= $ctime_mds"
}
run_test 908b "changelog stores valid mtime"

test_909() {
	(( $MDS1_VERSION >= $(version_code 2.16.56) )) ||
	skip "Need MDS version at least 2.16.56"
	(( $MDSCOUNT >= 2 )) || skip_env "needs >= 2 MDTs"

	test_mkdir -i 1 $DIR/$tdir || error "mkdir $DIR/$tdir failed"
	$LFS setstripe -E 1M -L mdt $DIR/$tdir/$tfile ||
	error "failed to create DoM-only file $DIR/$tdir/$tfile"
	mdt_index=$($LFS getstripe "$DIR/$tdir/$tfile" | \
		awk 'found && /lmm_mdt_index:/ { print $2; exit }
			/lmm_pattern:/ { found = ($2 == "mdt") }')
	[[ "$mdt_index" == "1" ]] ||
		error "invalid mdt index $mdt_index != 1"
}
run_test 909 "Verify mdt index"

test_910()
{
	local run_id=$RANDOM

	# Try to insert the module.
	load_module kunit/ec_test run_id=$run_id ||
		error "load_module failed"

	# Anything but success is a test failure
	dmesg | grep -q \
	    "lustre_ec_test_$run_id: EC test passed" ||
	    error "EC test failed"

	# Remove the test module
	rmmod -v ec_test ||
		error "rmmod failed (may trigger a failure in a later test)"
}
run_test 910 "Test the erasure_coding module"

test_911()
{
	local lfs_cmdlist="hsm mirror pcc"
	local lctl_cmdlist="barrier llog nodemap"
	local cmd

	for cmd in $lfs_cmdlist; do
		! $LFS $cmd --list-commands | grep -E "setstripe|find" ||
			error "lfs $cmd --list-commands not limiting output"
	done

	(( $MGS_VERSION >= $(version_code 2.17.50) )) ||
		skip "Need MGS version at least 2.17.50"
	for cmd in $lctl_cmdlist; do
		! do_facet mgs $LCTL $cmd --list-commands | grep -E "====" ||
			error "lctl $cmd --list-commands not limiting output"
	done
}
run_test 911 "Check lfs/lctl --list-commands"

test_920()
{
	mount | grep lustre
	mkdir -p $DIR/$tdir

	#define OBD_FAIL_FID_MULTI	0x1507
	do_facet $SINGLEMDS $LCTL set_param fail_loc=0x1507
	touch $DIR/$tdir/$tfile || error "touch failed"

	lfs path2fid $DIR/$tdir/$tfile  # Verify it's a normal FID
	stat $DIR/$tdir/$tfile || error "File not found after creation"
}
run_test 920 "Test multy LUFID"

complete_test $SECONDS
[ -f $EXT2_DEV ] && rm $EXT2_DEV || true
check_and_cleanup_lustre
if [ "$I_MOUNTED" != "yes" ]; then
	lctl set_param debug="$OLDDEBUG" 2> /dev/null || true
fi
exit_status