Whamcloud - gitweb
LU-4371 gss: Generalize testing of GSSAPI code
[fs/lustre-release.git] / lustre / tests / test-framework.sh
1 #!/bin/bash
2
3 trap 'print_summary && touch $TF_FAIL && \
4     echo "test-framework exiting on error"' ERR
5 set -e
6 #set -x
7
8 export LANG=en_US
9 export EJOURNAL=${EJOURNAL:-""}
10 export REFORMAT=${REFORMAT:-""}
11 export WRITECONF=${WRITECONF:-""}
12 export VERBOSE=${VERBOSE:-false}
13 export CATASTROPHE=${CATASTROPHE:-/proc/sys/lnet/catastrophe}
14 export GSS=false
15 export GSS_KRB5=false
16 export GSS_PIPEFS=false
17 export IDENTITY_UPCALL=default
18 export QUOTA_AUTO=1
19 # specify environment variable containing batch job name for server statistics
20 export JOBID_VAR=${JOBID_VAR:-"procname_uid"}  # or "existing" or "disable"
21
22 # LOAD_LLOOP: LU-409: only load llite_lloop module if kernel < 2.6.32 or
23 #             LOAD_LLOOP is true. LOAD_LLOOP is false by default.
24 export LOAD_LLOOP=${LOAD_LLOOP:-false}
25
26 #export PDSH="pdsh -S -Rssh -w"
27
28 # function used by scripts run on remote nodes
29 LUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}
30 . $LUSTRE/tests/functions.sh
31 . $LUSTRE/tests/yaml.sh
32
33 export LD_LIBRARY_PATH=${LUSTRE}/utils:${LD_LIBRARY_PATH}
34
35 LUSTRE_TESTS_CFG_DIR=${LUSTRE_TESTS_CFG_DIR:-${LUSTRE}/tests/cfg}
36
37 EXCEPT_LIST_FILE=${EXCEPT_LIST_FILE:-${LUSTRE_TESTS_CFG_DIR}/tests-to-skip.sh}
38
39 if [ -f "$EXCEPT_LIST_FILE" ]; then
40     echo "Reading test skip list from $EXCEPT_LIST_FILE"
41     cat $EXCEPT_LIST_FILE
42     . $EXCEPT_LIST_FILE
43 fi
44
45 # check config files for options in decreasing order of preference
46 [ -z "$MODPROBECONF" -a -f /etc/modprobe.d/lustre.conf ] &&
47     MODPROBECONF=/etc/modprobe.d/lustre.conf
48 [ -z "$MODPROBECONF" -a -f /etc/modprobe.d/Lustre ] &&
49     MODPROBECONF=/etc/modprobe.d/Lustre
50 [ -z "$MODPROBECONF" -a -f /etc/modprobe.conf ] &&
51     MODPROBECONF=/etc/modprobe.conf
52
53 assert_DIR () {
54     local failed=""
55     [[ $DIR/ = $MOUNT/* ]] || \
56         { failed=1 && echo "DIR=$DIR not in $MOUNT. Aborting."; }
57     [[ $DIR1/ = $MOUNT1/* ]] || \
58         { failed=1 && echo "DIR1=$DIR1 not in $MOUNT1. Aborting."; }
59     [[ $DIR2/ = $MOUNT2/* ]] || \
60         { failed=1 && echo "DIR2=$DIR2 not in $MOUNT2. Aborting"; }
61
62     [ -n "$failed" ] && exit 99 || true
63 }
64
65 usage() {
66     echo "usage: $0 [-r] [-f cfgfile]"
67     echo "       -r: reformat"
68
69     exit
70 }
71
72 print_summary () {
73     trap 0
74     [ "$TESTSUITE" == "lfsck" ] && return 0
75     [ -n "$ONLY" ] && echo "WARNING: ONLY is set to $(echo $ONLY)"
76     local details
77     local form="%-13s %-17s %-9s %s %s\n"
78     printf "$form" "status" "script" "Total(sec)" "E(xcluded) S(low)"
79     echo "------------------------------------------------------------------------------------"
80     for O in $DEFAULT_SUITES; do
81         O=$(echo $O  | tr "-" "_" | tr "[:lower:]" "[:upper:]")
82         [ "${!O}" = "no" ] && continue || true
83         local o=$(echo $O  | tr "[:upper:]_" "[:lower:]-")
84         local log=${TMP}/${o}.log
85         if is_sanity_benchmark $o; then
86             log=${TMP}/sanity-benchmark.log
87         fi
88         local slow=
89         local skipped=
90         local total=
91         local status=Unfinished
92         if [ -f $log ]; then
93             skipped=$(grep excluded $log | awk '{ printf " %s", $3 }' | sed 's/test_//g')
94             slow=$(egrep "^PASS|^FAIL" $log | tr -d "("| sed s/s\)$//g | sort -nr -k 3  | head -5 |  awk '{ print $2":"$3"s" }')
95             total=$(grep duration $log | awk '{ print $2}')
96             if [ "${!O}" = "done" ]; then
97                 status=Done
98             fi
99             if $DDETAILS; then
100                 local durations=$(egrep "^PASS|^FAIL" $log |  tr -d "("| sed s/s\)$//g | awk '{ print $2":"$3"|" }')
101                 details=$(printf "%s\n%s %s %s\n" "$details" "DDETAILS" "$O" "$(echo $durations)")
102             fi
103         fi
104         printf "$form" $status "$O" "${total}" "E=$skipped"
105         printf "$form" "-" "-" "-" "S=$(echo $slow)"
106     done
107
108     for O in $DEFAULT_SUITES; do
109         O=$(echo $O  | tr "-" "_" | tr "[:lower:]" "[:upper:]")
110         if [ "${!O}" = "no" ]; then
111             printf "$form" "Skipped" "$O" ""
112         fi
113     done
114
115     # print the detailed tests durations if DDETAILS=true
116     if $DDETAILS; then
117         echo "$details"
118     fi
119 }
120
121 init_test_env() {
122         export LUSTRE=$(absolute_path $LUSTRE)
123         export TESTSUITE=$(basename $0 .sh)
124         export TEST_FAILED=false
125         export FAIL_ON_SKIP_ENV=${FAIL_ON_SKIP_ENV:-false}
126         export RPC_MODE=${RPC_MODE:-false}
127
128     export MKE2FS=$MKE2FS
129     if [ -z "$MKE2FS" ]; then
130         if which mkfs.ldiskfs >/dev/null 2>&1; then
131             export MKE2FS=mkfs.ldiskfs
132         else
133             export MKE2FS=mke2fs
134         fi
135     fi
136
137     export DEBUGFS=$DEBUGFS
138     if [ -z "$DEBUGFS" ]; then
139         if which debugfs.ldiskfs >/dev/null 2>&1; then
140             export DEBUGFS=debugfs.ldiskfs
141         else
142             export DEBUGFS=debugfs
143         fi
144     fi
145
146     export TUNE2FS=$TUNE2FS
147     if [ -z "$TUNE2FS" ]; then
148         if which tunefs.ldiskfs >/dev/null 2>&1; then
149             export TUNE2FS=tunefs.ldiskfs
150         else
151             export TUNE2FS=tune2fs
152         fi
153     fi
154
155     export E2LABEL=$E2LABEL
156     if [ -z "$E2LABEL" ]; then
157         if which label.ldiskfs >/dev/null 2>&1; then
158             export E2LABEL=label.ldiskfs
159         else
160             export E2LABEL=e2label
161         fi
162     fi
163
164     export DUMPE2FS=$DUMPE2FS
165     if [ -z "$DUMPE2FS" ]; then
166         if which dumpfs.ldiskfs >/dev/null 2>&1; then
167             export DUMPE2FS=dumpfs.ldiskfs
168         else
169             export DUMPE2FS=dumpe2fs
170         fi
171     fi
172
173     export E2FSCK=$E2FSCK
174     if [ -z "$E2FSCK" ]; then
175         if which fsck.ldiskfs >/dev/null 2>&1; then
176             export E2FSCK=fsck.ldiskfs
177         else
178             export E2FSCK=e2fsck
179         fi
180     fi
181
182         export RESIZE2FS=$RESIZE2FS
183         if [ -z "$RESIZE2FS" ]; then
184                 if which resizefs.ldiskfs >/dev/null 2>&1; then
185                         export RESIZE2FS=resizefs.ldiskfs
186                 else
187                         export RESIZE2FS=resize2fs
188                 fi
189         fi
190
191     export LFSCK_BIN=${LFSCK_BIN:-lfsck}
192     export LFSCK_ALWAYS=${LFSCK_ALWAYS:-"no"} # check fs after each test suite
193     export FSCK_MAX_ERR=4   # File system errors left uncorrected
194
195         export ZFS=${ZFS:-zfs}
196         export ZPOOL=${ZPOOL:-zpool}
197         export ZDB=${ZDB:-zdb}
198         export PARTPROBE=${PARTPROBE:-partprobe}
199
200     #[ -d /r ] && export ROOT=${ROOT:-/r}
201     export TMP=${TMP:-$ROOT/tmp}
202     export TESTSUITELOG=${TMP}/${TESTSUITE}.log
203     export LOGDIR=${LOGDIR:-${TMP}/test_logs/$(date +%s)}
204     export TESTLOG_PREFIX=$LOGDIR/$TESTSUITE
205
206     export HOSTNAME=${HOSTNAME:-$(hostname -s)}
207     if ! echo $PATH | grep -q $LUSTRE/utils; then
208         export PATH=$LUSTRE/utils:$PATH
209     fi
210     if ! echo $PATH | grep -q $LUSTRE/utils/gss; then
211         export PATH=$LUSTRE/utils/gss:$PATH
212     fi
213     if ! echo $PATH | grep -q $LUSTRE/tests; then
214         export PATH=$LUSTRE/tests:$PATH
215     fi
216     if ! echo $PATH | grep -q $LUSTRE/../lustre-iokit/sgpdd-survey; then
217         export PATH=$LUSTRE/../lustre-iokit/sgpdd-survey:$PATH
218     fi
219     export LST=${LST:-"$LUSTRE/../lnet/utils/lst"}
220     [ ! -f "$LST" ] && export LST=$(which lst)
221     export SGPDDSURVEY=${SGPDDSURVEY:-"$LUSTRE/../lustre-iokit/sgpdd-survey/sgpdd-survey")}
222     [ ! -f "$SGPDDSURVEY" ] && export SGPDDSURVEY=$(which sgpdd-survey)
223     # Ubuntu, at least, has a truncate command in /usr/bin
224     # so fully path our truncate command.
225     export TRUNCATE=${TRUNCATE:-$LUSTRE/tests/truncate}
226     export MDSRATE=${MDSRATE:-"$LUSTRE/tests/mpi/mdsrate"}
227     [ ! -f "$MDSRATE" ] && export MDSRATE=$(which mdsrate 2> /dev/null)
228     if ! echo $PATH | grep -q $LUSTRE/tests/racer; then
229         export PATH=$LUSTRE/tests/racer:$PATH:
230     fi
231     if ! echo $PATH | grep -q $LUSTRE/tests/mpi; then
232         export PATH=$LUSTRE/tests/mpi:$PATH
233     fi
234     export RSYNC_RSH=${RSYNC_RSH:-rsh}
235
236     export LCTL=${LCTL:-"$LUSTRE/utils/lctl"}
237     [ ! -f "$LCTL" ] && export LCTL=$(which lctl)
238     export LFS=${LFS:-"$LUSTRE/utils/lfs"}
239     [ ! -f "$LFS" ] && export LFS=$(which lfs)
240     SETSTRIPE=${SETSTRIPE:-"$LFS setstripe"}
241     GETSTRIPE=${GETSTRIPE:-"$LFS getstripe"}
242
243     export L_GETIDENTITY=${L_GETIDENTITY:-"$LUSTRE/utils/l_getidentity"}
244     if [ ! -f "$L_GETIDENTITY" ]; then
245         if `which l_getidentity > /dev/null 2>&1`; then
246             export L_GETIDENTITY=$(which l_getidentity)
247         else
248             export L_GETIDENTITY=NONE
249         fi
250     fi
251     export LL_DECODE_FILTER_FID=${LL_DECODE_FILTER_FID:-"$LUSTRE/utils/ll_decode_filter_fid"}
252     [ ! -f "$LL_DECODE_FILTER_FID" ] && export LL_DECODE_FILTER_FID="ll_decode_filter_fid"
253     export MKFS=${MKFS:-"$LUSTRE/utils/mkfs.lustre"}
254     [ ! -f "$MKFS" ] && export MKFS="mkfs.lustre"
255     export TUNEFS=${TUNEFS:-"$LUSTRE/utils/tunefs.lustre"}
256     [ ! -f "$TUNEFS" ] && export TUNEFS="tunefs.lustre"
257     export CHECKSTAT="${CHECKSTAT:-"checkstat -v"} "
258     export LUSTRE_RMMOD=${LUSTRE_RMMOD:-$LUSTRE/scripts/lustre_rmmod}
259     [ ! -f "$LUSTRE_RMMOD" ] &&
260         export LUSTRE_RMMOD=$(which lustre_rmmod 2> /dev/null)
261     export LFS_MIGRATE=${LFS_MIGRATE:-$LUSTRE/scripts/lfs_migrate}
262     [ ! -f "$LFS_MIGRATE" ] &&
263         export LFS_MIGRATE=$(which lfs_migrate 2> /dev/null)
264     export NAME=${NAME:-local}
265     export LGSSD=${LGSSD:-"$LUSTRE/utils/gss/lgssd"}
266     [ "$GSS_PIPEFS" = "true" ] && [ ! -f "$LGSSD" ] && \
267         export LGSSD=$(which lgssd)
268     export LSVCGSSD=${LSVCGSSD:-"$LUSTRE/utils/gss/lsvcgssd"}
269     [ ! -f "$LSVCGSSD" ] && export LSVCGSSD=$(which lsvcgssd 2> /dev/null)
270     export KRB5DIR=${KRB5DIR:-"/usr/kerberos"}
271     export DIR2
272     export SAVE_PWD=${SAVE_PWD:-$LUSTRE/tests}
273     export AT_MAX_PATH
274
275     if [ "$ACCEPTOR_PORT" ]; then
276         export PORT_OPT="--port $ACCEPTOR_PORT"
277     fi
278
279     case "x$SEC" in
280         xkrb5*)
281             echo "Using GSS/krb5 ptlrpc security flavor"
282             which lgss_keyring > /dev/null 2>&1 || \
283                 error_exit "built with gss disabled! SEC=$SEC"
284             GSS=true
285             GSS_KRB5=true
286             ;;
287     esac
288
289     case "x$IDUP" in
290         xtrue)
291             IDENTITY_UPCALL=true
292             ;;
293         xfalse)
294             IDENTITY_UPCALL=false
295             ;;
296     esac
297
298     export LOAD_MODULES_REMOTE=${LOAD_MODULES_REMOTE:-false}
299
300     # Paths on remote nodes, if different
301     export RLUSTRE=${RLUSTRE:-$LUSTRE}
302     export RPWD=${RPWD:-$PWD}
303     export I_MOUNTED=${I_MOUNTED:-"no"}
304         if [ ! -f /lib/modules/$(uname -r)/kernel/fs/lustre/mdt.ko -a \
305              ! -f /lib/modules/$(uname -r)/updates/kernel/fs/lustre/mdt.ko -a \
306              ! -f /lib/modules/$(uname -r)/extra/kernel/fs/lustre/mdt.ko -a \
307              ! -f $LUSTRE/mdt/mdt.ko ]; then
308             export CLIENTMODSONLY=yes
309         fi
310
311         export SHUTDOWN_ATTEMPTS=${SHUTDOWN_ATTEMPTS:-3}
312         export OSD_TRACK_DECLARES_LBUG=${OSD_TRACK_DECLARES_LBUG:-"yes"}
313
314     # command line
315
316     while getopts "rvwf:" opt $*; do
317         case $opt in
318             f) CONFIG=$OPTARG;;
319             r) REFORMAT=--reformat;;
320             v) VERBOSE=true;;
321             w) WRITECONF=writeconf;;
322             \?) usage;;
323         esac
324     done
325
326     shift $((OPTIND - 1))
327     ONLY=${ONLY:-$*}
328
329         # print the durations of each test if "true"
330         DDETAILS=${DDETAILS:-false}
331         [ "$TESTSUITELOG" ] && rm -f $TESTSUITELOG || true
332         if ! $RPC_MODE; then
333                 rm -f $TMP/*active
334         fi
335 }
336
337 check_cpt_number() {
338         local facet=$1
339         local ncpts
340
341         ncpts=$(do_facet $facet "lctl get_param -n " \
342                 "cpu_partition_table 2>/dev/null| wc -l" || echo 1)
343
344         if [ $ncpts -eq 0 ]; then
345                 echo "1"
346         else
347                 echo $ncpts
348         fi
349 }
350
351 version_code() {
352     # split arguments like "1.8.6-wc3" into "1", "8", "6", "wc3"
353     eval set -- $(tr "[:punct:]" " " <<< $*)
354
355     echo -n "$((($1 << 16) | ($2 << 8) | $3))"
356 }
357
358 export LINUX_VERSION=$(uname -r | sed -e "s/[-.]/ /3" -e "s/ .*//")
359 export LINUX_VERSION_CODE=$(version_code ${LINUX_VERSION//\./ })
360
361 module_loaded () {
362    /sbin/lsmod | grep -q "^\<$1\>"
363 }
364
365 # Load a module on the system where this is running.
366 #
367 # Synopsis: load_module module_name [module arguments for insmod/modprobe]
368 #
369 # If module arguments are not given but MODOPTS_<MODULE> is set, then its value
370 # will be used as the arguments.  Otherwise arguments will be obtained from
371 # /etc/modprobe.conf, from /etc/modprobe.d/Lustre, or else none will be used.
372 #
373 load_module() {
374     local optvar
375     EXT=".ko"
376     module=$1
377     shift
378     BASE=`basename $module $EXT`
379
380     module_loaded ${BASE} && return
381
382     # If no module arguments were passed, get them from $MODOPTS_<MODULE>, else from
383     # modprobe.conf
384     if [ $# -eq 0 ]; then
385         # $MODOPTS_<MODULE>; we could use associative arrays, but that's not in
386         # Bash until 4.x, so we resort to eval.
387         optvar="MODOPTS_$(basename $module | tr a-z A-Z)"
388         eval set -- \$$optvar
389         if [ $# -eq 0 -a -n "$MODPROBECONF" ]; then
390                 # Nothing in $MODOPTS_<MODULE>; try modprobe.conf
391                 local opt
392                 opt=$(awk -v var="^options $BASE" '$0 ~ var \
393                         {gsub("'"options $BASE"'",""); print}' $MODPROBECONF)
394                 set -- $(echo -n $opt)
395
396                 # Ensure we have accept=all for lnet
397                 if [ $(basename $module) = lnet ]; then
398                         # OK, this is a bit wordy...
399                         local arg accept_all_present=false
400
401                         for arg in "$@"; do
402                                 [ "$arg" = accept=all ] && \
403                                         accept_all_present=true
404                         done
405                         $accept_all_present || set -- "$@" accept=all
406                 fi
407                 export $optvar="$*"
408         fi
409     fi
410
411     [ $# -gt 0 ] && echo "${module} options: '$*'"
412
413     # Note that insmod will ignore anything in modprobe.conf, which is why we're
414     # passing options on the command-line.
415     if [ "$BASE" == "lnet_selftest" ] && \
416             [ -f ${LUSTRE}/../lnet/selftest/${module}${EXT} ]; then
417         insmod ${LUSTRE}/../lnet/selftest/${module}${EXT}
418     elif [ -f ${LUSTRE}/${module}${EXT} ]; then
419         insmod ${LUSTRE}/${module}${EXT} "$@"
420     else
421         # must be testing a "make install" or "rpm" installation
422         # note failed to load ptlrpc_gss is considered not fatal
423         if [ "$BASE" == "ptlrpc_gss" ]; then
424             modprobe $BASE "$@" 2>/dev/null || echo "gss/krb5 is not supported"
425         else
426             modprobe $BASE "$@"
427         fi
428     fi
429 }
430
431 llite_lloop_enabled() {
432     local n1=$(uname -r | cut -d. -f1)
433     local n2=$(uname -r | cut -d. -f2)
434     local n3=$(uname -r | cut -d- -f1 | cut -d. -f3)
435
436     # load the llite_lloop module for < 2.6.32 kernels
437     if [[ $n1 -lt 2 ]] || [[ $n1 -eq 2 && $n2 -lt 6 ]] || \
438        [[ $n1 -eq 2 && $n2 -eq 6 && $n3 -lt 32 ]] || \
439         $LOAD_LLOOP; then
440         return 0
441     fi
442     return 1
443 }
444
445 load_modules_local() {
446         if [ -n "$MODPROBE" ]; then
447                 # use modprobe
448                 echo "Using modprobe to load modules"
449                 return 0
450         fi
451
452         echo Loading modules from $LUSTRE
453
454         local ncpus
455
456         if [ -f /sys/devices/system/cpu/online ]; then
457                 ncpus=$(($(cut -d "-" -f 2 /sys/devices/system/cpu/online) + 1))
458                 echo "detected $ncpus online CPUs by sysfs"
459         else
460                 ncpus=$(getconf _NPROCESSORS_CONF 2>/dev/null)
461                 local rc=$?
462                 if [ $rc -eq 0 ]; then
463                         echo "detected $ncpus online CPUs by getconf"
464                 else
465                         echo "Can't detect number of CPUs"
466                         ncpus=1
467                 fi
468         fi
469
470         # if there is only one CPU core, libcfs can only create one partition
471         # if there is more than 4 CPU cores, libcfs should create multiple CPU
472         # partitions. So we just force libcfs to create 2 partitions for
473         # system with 2 or 4 cores
474         if [ $ncpus -le 4 ] && [ $ncpus -gt 1 ]; then
475                 # force to enable multiple CPU partitions
476                 echo "Force libcfs to create 2 CPU partitions"
477                 MODOPTS_LIBCFS="cpu_npartitions=2 $MODOPTS_LIBCFS"
478         else
479                 echo "libcfs will create CPU partition based on online CPUs"
480         fi
481
482         load_module ../libcfs/libcfs/libcfs
483
484     [ "$PTLDEBUG" ] && lctl set_param debug="$PTLDEBUG"
485     [ "$SUBSYSTEM" ] && lctl set_param subsystem_debug="${SUBSYSTEM# }"
486     load_module ../lnet/lnet/lnet
487     LNETLND=${LNETLND:-"socklnd/ksocklnd"}
488     load_module ../lnet/klnds/$LNETLND
489     load_module obdclass/obdclass
490     load_module ptlrpc/ptlrpc
491     load_module ptlrpc/gss/ptlrpc_gss
492     load_module fld/fld
493     load_module fid/fid
494     load_module lmv/lmv
495     load_module mdc/mdc
496     load_module osc/osc
497     load_module lov/lov
498     load_module mgc/mgc
499     load_module obdecho/obdecho
500     if ! client_only; then
501         SYMLIST=/proc/kallsyms
502         grep -q crc16 $SYMLIST || { modprobe crc16 2>/dev/null || true; }
503         grep -q -w jbd $SYMLIST || { modprobe jbd 2>/dev/null || true; }
504         grep -q -w jbd2 $SYMLIST || { modprobe jbd2 2>/dev/null || true; }
505                 load_module lfsck/lfsck
506                 [ "$LQUOTA" != "no" ] && load_module quota/lquota $LQUOTAOPTS
507                 if [[ $(node_fstypes $HOSTNAME) == *zfs* ]]; then
508                         modprobe zfs
509                         load_module osd-zfs/osd_zfs
510                 fi
511                 if [[ $(node_fstypes $HOSTNAME) == *ldiskfs* ]]; then
512                         grep -q exportfs_decode_fh $SYMLIST ||
513                                 { modprobe exportfs 2> /dev/null || true; }
514                         load_module ../ldiskfs/ldiskfs
515                         load_module osd-ldiskfs/osd_ldiskfs
516                 fi
517                 load_module nodemap/nodemap
518                 load_module mgs/mgs
519                 load_module mdd/mdd
520                 load_module mdt/mdt
521                 load_module ost/ost
522                 load_module lod/lod
523                 load_module osp/osp
524                 load_module ofd/ofd
525                 load_module osp/osp
526     fi
527
528
529     load_module llite/lustre
530     llite_lloop_enabled && load_module llite/llite_lloop
531     [ -d /r ] && OGDB=${OGDB:-"/r/tmp"}
532     OGDB=${OGDB:-$TMP}
533     rm -f $OGDB/ogdb-$HOSTNAME
534     $LCTL modules > $OGDB/ogdb-$HOSTNAME
535
536     # 'mount' doesn't look in $PATH, just sbin
537     if [ -f $LUSTRE/utils/mount.lustre ] && \
538        ! grep -qe "/sbin/mount\.lustre " /proc/mounts; then
539         [ ! -f /sbin/mount.lustre ] && touch /sbin/mount.lustre
540         mount --bind $LUSTRE/utils/mount.lustre /sbin/mount.lustre || true
541     fi
542 }
543
544 load_modules () {
545         load_modules_local
546         # bug 19124
547         # load modules on remote nodes optionally
548         # lustre-tests have to be installed on these nodes
549         if $LOAD_MODULES_REMOTE; then
550                 local list=$(comma_list $(remote_nodes_list))
551                 if [ -n "$list" ]; then
552                         echo "loading modules on: '$list'"
553                         do_rpc_nodes "$list" load_modules_local
554                 fi
555         fi
556 }
557
558 check_mem_leak () {
559     LEAK_LUSTRE=$(dmesg | tail -n 30 | grep "obd_memory.*leaked" || true)
560     LEAK_PORTALS=$(dmesg | tail -n 20 | grep "Portals memory leaked" || true)
561     if [ "$LEAK_LUSTRE" -o "$LEAK_PORTALS" ]; then
562         echo "$LEAK_LUSTRE" 1>&2
563         echo "$LEAK_PORTALS" 1>&2
564         mv $TMP/debug $TMP/debug-leak.`date +%s` || true
565         echo "Memory leaks detected"
566         [ -n "$IGNORE_LEAK" ] && { echo "ignoring leaks" && return 0; } || true
567         return 1
568     fi
569 }
570
571 unload_modules() {
572         wait_exit_ST client # bug 12845
573
574         $LUSTRE_RMMOD ldiskfs || return 2
575
576         if $LOAD_MODULES_REMOTE; then
577                 local list=$(comma_list $(remote_nodes_list))
578                 if [ -n "$list" ]; then
579                         echo "unloading modules on: '$list'"
580                         do_rpc_nodes "$list" $LUSTRE_RMMOD ldiskfs
581                         do_rpc_nodes "$list" check_mem_leak
582                 fi
583         fi
584
585     if grep -qe "/sbin/mount\.lustre" /proc/mounts; then
586         umount /sbin/mount.lustre || true
587         [ -w /sbin/mount.lustre -a ! -s /sbin/mount.lustre ] && \
588             rm -f /sbin/mount.lustre || true
589     fi
590
591     check_mem_leak || return 254
592
593     echo "modules unloaded."
594     return 0
595 }
596
597 fs_log_size() {
598         local facet=${1:-$SINGLEMDS}
599         local fstype=$(facet_fstype $facet)
600         local size=0
601         case $fstype in
602                 ldiskfs) size=50;; # largest seen is 44, leave some headroom
603                 zfs)     size=400;; # largest seen is 384
604         esac
605
606         echo -n $size
607 }
608
609 check_gss_daemon_nodes() {
610     local list=$1
611     dname=$2
612
613     do_nodesv $list "num=\\\$(ps -o cmd -C $dname | grep $dname | wc -l);
614 if [ \\\"\\\$num\\\" -ne 1 ]; then
615     echo \\\$num instance of $dname;
616     exit 1;
617 fi; "
618 }
619
620 check_gss_daemon_facet() {
621     facet=$1
622     dname=$2
623
624     num=`do_facet $facet ps -o cmd -C $dname | grep $dname | wc -l`
625     if [ $num -ne 1 ]; then
626         echo "$num instance of $dname on $facet"
627         return 1
628     fi
629     return 0
630 }
631
632 send_sigint() {
633     local list=$1
634     shift
635     echo Stopping $@ on $list
636     do_nodes $list "killall -2 $@ 2>/dev/null || true"
637 }
638
639 # start gss daemons on all nodes, or
640 # "daemon" on "list" if set
641 start_gss_daemons() {
642     local list=$1
643     local daemon=$2
644
645     if [ "$list" ] && [ "$daemon" ] ; then
646         echo "Starting gss daemon on nodes: $list"
647         do_nodes $list "$daemon" || return 8
648         return 0
649     fi
650
651     local list=$(comma_list $(mdts_nodes))
652     echo "Starting gss daemon on mds: $list"
653     do_nodes $list "$LSVCGSSD -v" || return 1
654     if $GSS_PIPEFS; then
655         do_nodes $list "$LGSSD -v" || return 2
656     fi
657
658     list=$(comma_list $(osts_nodes))
659     echo "Starting gss daemon on ost: $list"
660     do_nodes $list "$LSVCGSSD -v" || return 3
661     # starting on clients
662
663     local clients=${CLIENTS:-`hostname`}
664     if $GSS_PIPEFS; then
665         echo "Starting $LGSSD on clients $clients "
666         do_nodes $clients  "$LGSSD -v" || return 4
667     fi
668
669     # wait daemons entering "stable" status
670     sleep 5
671
672     #
673     # check daemons are running
674     #
675     list=$(comma_list $(mdts_nodes) $(osts_nodes))
676     check_gss_daemon_nodes $list lsvcgssd || return 5
677     if $GSS_PIPEFS; then
678         list=$(comma_list $(mdts_nodes))
679         check_gss_daemon_nodes $list lgssd || return 6
680     fi
681     if $GSS_PIPEFS; then
682         check_gss_daemon_nodes $clients lgssd || return 7
683     fi
684 }
685
686 stop_gss_daemons() {
687     local list=$(comma_list $(mdts_nodes))
688     
689     send_sigint $list lsvcgssd lgssd
690
691     list=$(comma_list $(osts_nodes))
692     send_sigint $list lsvcgssd
693
694     list=${CLIENTS:-`hostname`}
695     send_sigint $list lgssd
696 }
697
698 init_gss() {
699     if $GSS; then
700         if ! module_loaded ptlrpc_gss; then
701             load_module ptlrpc/gss/ptlrpc_gss
702             module_loaded ptlrpc_gss ||
703                 error_exit "init_gss : GSS=$GSS, but gss/krb5 is not supported!"
704         fi
705         if $GSS_KRB5; then
706                 start_gss_daemons || error_exit "start gss daemon failed! rc=$?"
707         fi
708
709         if [ -n "$LGSS_KEYRING_DEBUG" ]; then
710             echo $LGSS_KEYRING_DEBUG > /proc/fs/lustre/sptlrpc/gss/lgss_keyring/debug_level
711         fi
712     fi
713 }
714
715 cleanup_gss() {
716     if $GSS; then
717         stop_gss_daemons
718         # maybe cleanup credential cache?
719     fi
720 }
721
722 facet_svc() {
723         local facet=$1
724         local var=${facet}_svc
725
726         echo -n ${!var}
727 }
728
729 facet_type() {
730         local facet=$1
731
732         echo -n $facet | sed -e 's/^fs[0-9]\+//' -e 's/[0-9_]\+//' |
733                 tr '[:lower:]' '[:upper:]'
734 }
735
736 facet_number() {
737         local facet=$1
738
739         if [ $facet == mgs ]; then
740                 return 1
741         fi
742
743         echo -n $facet | sed -e 's/^fs[0-9]\+//' | sed -e 's/^[a-z]\+//'
744 }
745
746 facet_fstype() {
747         local facet=$1
748         local var
749
750         var=${facet}_FSTYPE
751         if [ -n "${!var}" ]; then
752                 echo -n ${!var}
753                 return
754         fi
755
756         var=$(facet_type $facet)FSTYPE
757         if [ -n "${!var}" ]; then
758                 echo -n ${!var}
759                 return
760         fi
761
762         if [ -n "$FSTYPE" ]; then
763                 echo -n $FSTYPE
764                 return
765         fi
766
767         if [[ $facet == mgs ]] && combined_mgs_mds; then
768                 facet_fstype mds1
769                 return
770         fi
771
772         return 1
773 }
774
775 node_fstypes() {
776         local node=$1
777         local fstypes
778         local fstype
779         local facets=$(get_facets)
780         local facet
781
782         for facet in ${facets//,/ }; do
783                 if [ $node == $(facet_host $facet) ] ||
784                    [ $node == "$(facet_failover_host $facet)" ]; then
785                         fstype=$(facet_fstype $facet)
786                         if [[ $fstypes != *$fstype* ]]; then
787                                 fstypes+="${fstypes:+,}$fstype"
788                         fi
789                 fi
790         done
791         echo -n $fstypes
792 }
793
794 devicelabel() {
795         local facet=$1
796         local dev=$2
797         local label
798         local fstype=$(facet_fstype $facet)
799
800         case $fstype in
801         ldiskfs)
802                 label=$(do_facet ${facet} "$E2LABEL ${dev} 2>/dev/null");;
803         zfs)
804                 label=$(do_facet ${facet} "$ZFS get -H -o value lustre:svname \
805                                            ${dev} 2>/dev/null");;
806         *)
807                 error "unknown fstype!";;
808         esac
809
810         echo -n $label
811 }
812
813 mdsdevlabel() {
814         local num=$1
815         local device=$(mdsdevname $num)
816         local label=$(devicelabel mds$num ${device} | grep -v "CMD: ")
817         echo -n $label
818 }
819
820 ostdevlabel() {
821         local num=$1
822         local device=$(ostdevname $num)
823         local label=$(devicelabel ost$num ${device} | grep -v "CMD: ")
824         echo -n $label
825 }
826
827 #
828 # Get the device of a facet.
829 #
830 facet_device() {
831         local facet=$1
832         local device
833
834         case $facet in
835                 mgs) device=$(mgsdevname) ;;
836                 mds*) device=$(mdsdevname $(facet_number $facet)) ;;
837                 ost*) device=$(ostdevname $(facet_number $facet)) ;;
838                 fs2mds) device=$(mdsdevname 1_2) ;;
839                 fs2ost) device=$(ostdevname 1_2) ;;
840                 fs3ost) device=$(ostdevname 2_2) ;;
841                 *) ;;
842         esac
843
844         echo -n $device
845 }
846
847 #
848 # Get the virtual device of a facet.
849 #
850 facet_vdevice() {
851         local facet=$1
852         local device
853
854         case $facet in
855                 mgs) device=$(mgsvdevname) ;;
856                 mds*) device=$(mdsvdevname $(facet_number $facet)) ;;
857                 ost*) device=$(ostvdevname $(facet_number $facet)) ;;
858                 fs2mds) device=$(mdsvdevname 1_2) ;;
859                 fs2ost) device=$(ostvdevname 1_2) ;;
860                 fs3ost) device=$(ostvdevname 2_2) ;;
861                 *) ;;
862         esac
863
864         echo -n $device
865 }
866
867 #
868 # Re-read the partition table on failover partner host.
869 # After a ZFS storage pool is created on a shared device, the partition table
870 # on the device may change. However, the operating system on the failover
871 # host may not notice the change automatically. Without the up-to-date partition
872 # block devices, 'zpool import ..' cannot find the labels, whose positions are
873 # relative to partition rather than disk beginnings.
874 #
875 # This function performs partprobe on the failover host to make it re-read the
876 # partition table.
877 #
878 refresh_partition_table() {
879         local facet=$1
880         local device=$2
881         local host
882
883         host=$(facet_passive_host $facet)
884         if [[ -n "$host" ]]; then
885                 do_node $host "$PARTPROBE $device"
886         fi
887 }
888
889 #
890 # Get ZFS storage pool name.
891 #
892 zpool_name() {
893         local facet=$1
894         local device
895         local poolname
896
897         device=$(facet_device $facet)
898         # poolname is string before "/"
899         poolname="${device%%/*}"
900
901         echo -n $poolname
902 }
903
904 #
905 # Create ZFS storage pool.
906 #
907 create_zpool() {
908         local facet=$1
909         local poolname=$2
910         local vdev=$3
911         shift 3
912         local opts=${@:-"-o cachefile=none"}
913
914         do_facet $facet "$ZPOOL list -H $poolname >/dev/null 2>&1 ||
915                 $ZPOOL create -f $opts $poolname $vdev"
916 }
917
918 #
919 # Create ZFS file system.
920 #
921 create_zfs() {
922         local facet=$1
923         local dataset=$2
924         shift 2
925         local opts=${@:-"-o mountpoint=legacy"}
926
927         do_facet $facet "$ZFS list -H $dataset >/dev/null 2>&1 ||
928                 $ZFS create $opts $dataset"
929 }
930
931 #
932 # Export ZFS storage pool.
933 # Before exporting the pool, all datasets within the pool should be unmounted.
934 #
935 export_zpool() {
936         local facet=$1
937         shift
938         local opts="$@"
939         local poolname
940
941         poolname=$(zpool_name $facet)
942
943         if [[ -n "$poolname" ]]; then
944                 do_facet $facet "! $ZPOOL list -H $poolname >/dev/null 2>&1 ||
945                         grep -q ^$poolname/ /proc/mounts ||
946                         $ZPOOL export $opts $poolname"
947         fi
948 }
949
950 #
951 # Destroy ZFS storage pool.
952 # Destroy the given pool and free up any devices for other use. This command
953 # tries to unmount any active datasets before destroying the pool.
954 # -f    Force any active datasets contained within the pool to be unmounted.
955 #
956 destroy_zpool() {
957         local facet=$1
958         local poolname=${2:-$(zpool_name $facet)}
959
960         if [[ -n "$poolname" ]]; then
961                 do_facet $facet "! $ZPOOL list -H $poolname >/dev/null 2>&1 ||
962                         $ZPOOL destroy -f $poolname"
963         fi
964 }
965
966 #
967 # Import ZFS storage pool.
968 # Force importing, even if the pool appears to be potentially active.
969 #
970 import_zpool() {
971         local facet=$1
972         shift
973         local opts=${@:-"-o cachefile=none"}
974         local poolname
975
976         poolname=$(zpool_name $facet)
977
978         if [[ -n "$poolname" ]]; then
979                 opts+=" -d $(dirname $(facet_vdevice $facet))"
980                 do_facet $facet "$ZPOOL list -H $poolname >/dev/null 2>&1 ||
981                         $ZPOOL import -f $opts $poolname"
982         fi
983 }
984
985 #
986 # Set the "cachefile=none" property on ZFS storage pool so that the pool
987 # is not automatically imported on system startup.
988 #
989 # In a failover environment, this will provide resource level fencing which
990 # will ensure that the same ZFS storage pool will not be imported concurrently
991 # on different nodes.
992 #
993 disable_zpool_cache() {
994         local facet=$1
995         local poolname
996
997         poolname=$(zpool_name $facet)
998
999         if [[ -n "$poolname" ]]; then
1000                 do_facet $facet "$ZPOOL set cachefile=none $poolname"
1001         fi
1002 }
1003
1004 #
1005 # This and set_osd_param() shall be used to access OSD parameters
1006 # once existed under "obdfilter":
1007 #
1008 #   mntdev
1009 #   stats
1010 #   read_cache_enable
1011 #   writethrough_cache_enable
1012 #
1013 get_osd_param() {
1014         local nodes=$1
1015         local device=${2:-$FSNAME-OST*}
1016         local name=$3
1017
1018         do_nodes $nodes "$LCTL get_param -n obdfilter.$device.$name \
1019                 osd-*.$device.$name 2>&1" | grep -v 'Found no match'
1020 }
1021
1022 set_osd_param() {
1023         local nodes=$1
1024         local device=${2:-$FSNAME-OST*}
1025         local name=$3
1026         local value=$4
1027
1028         do_nodes $nodes "$LCTL set_param -n obdfilter.$device.$name=$value \
1029                 osd-*.$device.$name=$value 2>&1" | grep -v 'Found no match'
1030 }
1031
1032 set_debug_size () {
1033     local dz=${1:-$DEBUG_SIZE}
1034
1035     if [ -f /sys/devices/system/cpu/possible ]; then
1036         local cpus=$(($(cut -d "-" -f 2 /sys/devices/system/cpu/possible)+1))
1037     else
1038         local cpus=$(getconf _NPROCESSORS_CONF)
1039     fi
1040
1041     # bug 19944, adjust size to be -gt num_possible_cpus()
1042     # promise 2MB for every cpu at least
1043     if [ -n "$cpus" ] && [ $((cpus * 2)) -gt $dz ]; then
1044         dz=$((cpus * 2))
1045     fi
1046     lctl set_param debug_mb=$dz
1047 }
1048
1049 set_default_debug () {
1050     local debug=${1:-"$PTLDEBUG"}
1051     local subsys=${2:-"$SUBSYSTEM"}
1052     local debug_size=${3:-$DEBUG_SIZE}
1053
1054     [ -n "$debug" ] && lctl set_param debug="$debug" >/dev/null
1055     [ -n "$subsys" ] && lctl set_param subsystem_debug="${subsys# }" >/dev/null
1056
1057     [ -n "$debug_size" ] && set_debug_size $debug_size > /dev/null
1058 }
1059
1060 set_default_debug_nodes () {
1061         local nodes="$1"
1062
1063         if [[ ,$nodes, = *,$HOSTNAME,* ]]; then
1064                 nodes=$(exclude_items_from_list "$nodes" "$HOSTNAME")
1065                 set_default_debug
1066         fi
1067
1068         do_rpc_nodes "$nodes" set_default_debug \
1069                 \\\"$PTLDEBUG\\\" \\\"$SUBSYSTEM\\\" $DEBUG_SIZE || true
1070 }
1071
1072 set_default_debug_facet () {
1073     local facet=$1
1074     local node=$(facet_active_host $facet)
1075     [ -z "$node" ] && echo "No host defined for facet $facet" && exit 1
1076
1077     set_default_debug_nodes $node
1078 }
1079
1080 # Facet functions
1081 mount_facets () {
1082         local facets=${1:-$(get_facets)}
1083         local facet
1084
1085         for facet in ${facets//,/ }; do
1086                 mount_facet $facet
1087                 local RC=$?
1088                 [ $RC -eq 0 ] && continue
1089
1090                 if [ "$TESTSUITE.$TESTNAME" = "replay-dual.test_0a" ]; then
1091                         skip "Restart of $facet failed!." && touch $LU482_FAILED
1092                 else
1093                         error "Restart of $facet failed!"
1094                 fi
1095                 return $RC
1096         done
1097 }
1098
1099 #
1100 # Add argument "arg" (e.g., "loop") to the comma-separated list
1101 # of arguments for option "opt" (e.g., "-o") on command
1102 # line "opts" (e.g., "-o flock").
1103 #
1104 csa_add() {
1105         local opts=$1
1106         local opt=$2
1107         local arg=$3
1108         local opt_pattern="\([[:space:]]\+\|^\)$opt"
1109
1110         if echo "$opts" | grep -q $opt_pattern; then
1111                 opts=$(echo "$opts" | sed -e \
1112                         "s/$opt_pattern[[:space:]]*[^[:space:]]\+/&,$arg/")
1113         else
1114                 opts+="${opts:+ }$opt $arg"
1115         fi
1116         echo -n "$opts"
1117 }
1118
1119 mount_facet() {
1120         local facet=$1
1121         shift
1122         local dev=$(facet_active $facet)_dev
1123         local opt=${facet}_opt
1124         local mntpt=$(facet_mntpt $facet)
1125         local opts="${!opt} $@"
1126
1127         if [ $(facet_fstype $facet) == ldiskfs ] &&
1128            ! do_facet $facet test -b ${!dev}; then
1129                 opts=$(csa_add "$opts" -o loop)
1130         fi
1131
1132         if [[ $(facet_fstype $facet) == zfs ]]; then
1133                 # import ZFS storage pool
1134                 import_zpool $facet || return ${PIPESTATUS[0]}
1135         fi
1136
1137         echo "Starting ${facet}: $opts ${!dev} $mntpt"
1138         # for testing LU-482 error handling in mount_facets() and test_0a()
1139         if [ -f $TMP/test-lu482-trigger ]; then
1140                 RC=2
1141         else
1142                 do_facet ${facet} "mkdir -p $mntpt; mount -t lustre $opts \
1143                                    ${!dev} $mntpt"
1144                 RC=${PIPESTATUS[0]}
1145         fi
1146         if [ $RC -ne 0 ]; then
1147                 echo "Start of ${!dev} on ${facet} failed ${RC}"
1148     else
1149         set_default_debug_facet $facet
1150
1151                 label=$(devicelabel ${facet} ${!dev})
1152         [ -z "$label" ] && echo no label for ${!dev} && exit 1
1153         eval export ${facet}_svc=${label}
1154         echo Started ${label}
1155     fi
1156     return $RC
1157 }
1158
1159 # start facet device options
1160 start() {
1161     local facet=$1
1162     shift
1163     local device=$1
1164     shift
1165     eval export ${facet}_dev=${device}
1166     eval export ${facet}_opt=\"$@\"
1167
1168     local varname=${facet}failover_dev
1169     if [ -n "${!varname}" ] ; then
1170         eval export ${facet}failover_dev=${!varname}
1171     else
1172         eval export ${facet}failover_dev=$device
1173     fi
1174
1175     local mntpt=$(facet_mntpt $facet)
1176     do_facet ${facet} mkdir -p $mntpt
1177     eval export ${facet}_MOUNT=$mntpt
1178     mount_facet ${facet}
1179     RC=$?
1180     return $RC
1181 }
1182
1183 stop() {
1184     local running
1185     local facet=$1
1186     shift
1187     local HOST=`facet_active_host $facet`
1188     [ -z $HOST ] && echo stop: no host for $facet && return 0
1189
1190     local mntpt=$(facet_mntpt $facet)
1191     running=$(do_facet ${facet} "grep -c $mntpt' ' /proc/mounts") || true
1192     if [ ${running} -ne 0 ]; then
1193         echo "Stopping $mntpt (opts:$@) on $HOST"
1194         do_facet ${facet} umount -d $@ $mntpt
1195     fi
1196
1197         # umount should block, but we should wait for unrelated obd's
1198         # like the MGS or MGC to also stop.
1199         wait_exit_ST ${facet} || return ${PIPESTATUS[0]}
1200
1201         if [[ $(facet_fstype $facet) == zfs ]]; then
1202                 # export ZFS storage pool
1203                 export_zpool $facet
1204         fi
1205 }
1206
1207 # save quota version (both administrative and operational quotas)
1208 # add an additional parameter if mountpoint is ever different from $MOUNT
1209 #
1210 # XXX This function is kept for interoperability with old server (< 2.3.50),
1211 #     it should be removed whenever we drop the interoperability for such
1212 #     server.
1213 quota_save_version() {
1214     local fsname=${2:-$FSNAME}
1215     local spec=$1
1216     local ver=$(tr -c -d "123" <<< $spec)
1217     local type=$(tr -c -d "ug" <<< $spec)
1218
1219     [ -n "$ver" -a "$ver" != "3" ] && error "wrong quota version specifier"
1220
1221     [ -n "$type" ] && { $LFS quotacheck -$type $MOUNT || error "quotacheck has failed"; }
1222
1223     do_facet mgs "lctl conf_param ${fsname}-MDT*.mdd.quota_type=$spec"
1224     local varsvc
1225     local osts=$(get_facets OST)
1226     for ost in ${osts//,/ }; do
1227         varsvc=${ost}_svc
1228         do_facet mgs "lctl conf_param ${!varsvc}.ost.quota_type=$spec"
1229     done
1230 }
1231
1232 # client could mount several lustre
1233 #
1234 # XXX This function is kept for interoperability with old server (< 2.3.50),
1235 #     it should be removed whenever we drop the interoperability for such
1236 #     server.
1237 quota_type() {
1238         local fsname=${1:-$FSNAME}
1239         local rc=0
1240         do_facet $SINGLEMDS lctl get_param mdd.${fsname}-MDT*.quota_type ||
1241                 rc=$?
1242         do_nodes $(comma_list $(osts_nodes)) \
1243                 lctl get_param obdfilter.${fsname}-OST*.quota_type || rc=$?
1244         return $rc 
1245 }
1246
1247 # XXX This function is kept for interoperability with old server (< 2.3.50),
1248 #     it should be removed whenever we drop the interoperability for such
1249 #     server.
1250 restore_quota_old() {
1251         local mntpt=${1:-$MOUNT}
1252         local quota_type=$(quota_type $FSNAME | grep MDT | cut -d "=" -f2)
1253         if [ ! "$old_QUOTA_TYPE" ] ||
1254                 [ "$quota_type" = "$old_QUOTA_TYPE" ]; then
1255                 return
1256         fi
1257         quota_save_version $old_QUOTA_TYPE
1258 }
1259
1260 # XXX This function is kept for interoperability with old server (< 2.3.50),
1261 #     it should be removed whenever we drop the interoperability for such
1262 #     server.
1263 setup_quota_old(){
1264         local mntpt=$1
1265
1266         # no quota enforcement for now and accounting works out of the box
1267         return
1268
1269     # We need save the original quota_type params, and restore them after testing
1270
1271     # Suppose that quota type the same on mds and ost
1272     local quota_type=$(quota_type | grep MDT | cut -d "=" -f2)
1273     [ ${PIPESTATUS[0]} -eq 0 ] || error "quota_type failed!"
1274     echo "[HOST:$HOSTNAME] [old_quota_type:$quota_type] [new_quota_type:$QUOTA_TYPE]"
1275     if [ "$quota_type" != "$QUOTA_TYPE" ]; then
1276         export old_QUOTA_TYPE=$quota_type
1277         quota_save_version $QUOTA_TYPE
1278     else
1279         qtype=$(tr -c -d "ug" <<< $QUOTA_TYPE)
1280         $LFS quotacheck -$qtype $mntpt || error "quotacheck has failed for $type"
1281     fi
1282
1283     local quota_usrs=$QUOTA_USERS
1284
1285     # get_filesystem_size
1286     local disksz=$(lfs_df $mntpt | grep "summary"  | awk '{print $2}')
1287     local blk_soft=$((disksz + 1024))
1288     local blk_hard=$((blk_soft + blk_soft / 20)) # Go 5% over
1289
1290     local Inodes=$(lfs_df -i $mntpt | grep "summary"  | awk '{print $2}')
1291     local i_soft=$Inodes
1292     local i_hard=$((i_soft + i_soft / 20))
1293
1294     echo "Total disk size: $disksz  block-softlimit: $blk_soft block-hardlimit:
1295         $blk_hard inode-softlimit: $i_soft inode-hardlimit: $i_hard"
1296
1297     local cmd
1298     for usr in $quota_usrs; do
1299         echo "Setting up quota on $HOSTNAME:$mntpt for $usr..."
1300         for type in u g; do
1301             cmd="$LFS setquota -$type $usr -b $blk_soft -B $blk_hard -i $i_soft -I $i_hard $mntpt"
1302             echo "+ $cmd"
1303             eval $cmd || error "$cmd FAILED!"
1304         done
1305         # display the quota status
1306         echo "Quota settings for $usr : "
1307         $LFS quota -v -u $usr $mntpt || true
1308     done
1309 }
1310
1311 # get mdt quota type
1312 mdt_quota_type() {
1313         local varsvc=${SINGLEMDS}_svc
1314         do_facet $SINGLEMDS $LCTL get_param -n \
1315                 osd-$(facet_fstype $SINGLEMDS).${!varsvc}.quota_slave.enabled
1316 }
1317
1318 # get ost quota type
1319 ost_quota_type() {
1320         # All OSTs should have same quota type
1321         local varsvc=ost1_svc
1322         do_facet ost1 $LCTL get_param -n \
1323                 osd-$(facet_fstype ost1).${!varsvc}.quota_slave.enabled
1324 }
1325
1326 # restore old quota type settings
1327 restore_quota() {
1328         if [ $(lustre_version_code $SINGLEMDS) -lt $(version_code 2.3.50) ]; then
1329                 restore_quota_old
1330                 return
1331         fi
1332
1333         if [ "$old_MDT_QUOTA_TYPE" ]; then
1334                 do_facet mgs $LCTL conf_param \
1335                         $FSNAME.quota.mdt=$old_MDT_QUOTA_TYPE
1336         fi
1337         if [ "$old_OST_QUOTA_TYPE" ]; then
1338                 do_facet mgs $LCTL conf_param \
1339                         $FSNAME.quota.ost=$old_OST_QUOTA_TYPE
1340         fi
1341 }
1342
1343 # Handle the case when there is a space in the lfs df
1344 # "filesystem summary" line the same as when there is no space.
1345 # This will allow fixing the "lfs df" summary line in the future.
1346 lfs_df() {
1347         $LFS df $* | sed -e 's/filesystem /filesystem_/'
1348 }
1349
1350 # Get free inodes on the MDT specified by mdt index, free indoes on
1351 # the whole filesystem will be returned when index == -1.
1352 mdt_free_inodes() {
1353         local index=$1
1354         local free_inodes
1355         local mdt_uuid
1356
1357         if [ $index -eq -1 ]; then
1358                 mdt_uuid="summary"
1359         else
1360                 mdt_uuid=$(mdtuuid_from_index $index)
1361         fi
1362
1363         free_inodes=$(lfs_df -i $MOUNT | grep $mdt_uuid | awk '{print $4}')
1364         echo $free_inodes
1365 }
1366
1367 setup_quota(){
1368         if [ $(lustre_version_code $SINGLEMDS) -lt $(version_code 2.3.50) ]; then
1369                 setup_quota_old $1
1370                 return
1371         fi
1372
1373         local mntpt=$1
1374
1375         # save old quota type & set new quota type
1376         local mdt_qtype=$(mdt_quota_type)
1377         local ost_qtype=$(ost_quota_type)
1378
1379         echo "[HOST:$HOSTNAME] [old_mdt_qtype:$mdt_qtype]" \
1380                 "[old_ost_qtype:$ost_qtype] [new_qtype:$QUOTA_TYPE]"
1381
1382         export old_MDT_QUOTA_TYPE=$mdt_qtype
1383         export old_OST_QUOTA_TYPE=$ost_qtype
1384
1385         do_facet mgs $LCTL conf_param $FSNAME.quota.mdt=$QUOTA_TYPE ||
1386                 error "set mdt quota type failed"
1387         do_facet mgs $LCTL conf_param $FSNAME.quota.ost=$QUOTA_TYPE ||
1388                 error "set ost quota type failed"
1389
1390         local quota_usrs=$QUOTA_USERS
1391
1392         # get_filesystem_size
1393         local disksz=$(lfs_df $mntpt | grep "summary" | awk '{print $2}')
1394         local blk_soft=$((disksz + 1024))
1395         local blk_hard=$((blk_soft + blk_soft / 20)) # Go 5% over
1396
1397         local inodes=$(lfs_df -i $mntpt | grep "summary" | awk '{print $2}')
1398         local i_soft=$inodes
1399         local i_hard=$((i_soft + i_soft / 20))
1400
1401         echo "Total disk size: $disksz  block-softlimit: $blk_soft" \
1402                 "block-hardlimit: $blk_hard inode-softlimit: $i_soft" \
1403                 "inode-hardlimit: $i_hard"
1404
1405         local cmd
1406         for usr in $quota_usrs; do
1407                 echo "Setting up quota on $HOSTNAME:$mntpt for $usr..."
1408                 for type in u g; do
1409                         cmd="$LFS setquota -$type $usr -b $blk_soft"
1410                         cmd="$cmd -B $blk_hard -i $i_soft -I $i_hard $mntpt"
1411                         echo "+ $cmd"
1412                         eval $cmd || error "$cmd FAILED!"
1413                 done
1414                 # display the quota status
1415                 echo "Quota settings for $usr : "
1416                 $LFS quota -v -u $usr $mntpt || true
1417         done
1418 }
1419
1420 zconf_mount() {
1421     local client=$1
1422     local mnt=$2
1423     local OPTIONS=${3:-$MOUNTOPT}
1424
1425     local device=$MGSNID:/$FSNAME
1426     if [ -z "$mnt" -o -z "$FSNAME" ]; then
1427         echo Bad zconf mount command: opt=$OPTIONS dev=$device mnt=$mnt
1428         exit 1
1429     fi
1430
1431     echo "Starting client: $client: $OPTIONS $device $mnt"
1432     do_node $client mkdir -p $mnt
1433     do_node $client mount -t lustre $OPTIONS $device $mnt || return 1
1434
1435     set_default_debug_nodes $client
1436
1437     return 0
1438 }
1439
1440 zconf_umount() {
1441     local client=$1
1442     local mnt=$2
1443     local force
1444     local busy 
1445     local need_kill
1446
1447     [ "$3" ] && force=-f
1448     local running=$(do_node $client "grep -c $mnt' ' /proc/mounts") || true
1449     if [ $running -ne 0 ]; then
1450         echo "Stopping client $client $mnt (opts:$force)"
1451         do_node $client lsof -t $mnt || need_kill=no
1452         if [ "x$force" != "x" -a "x$need_kill" != "xno" ]; then
1453             pids=$(do_node $client lsof -t $mnt | sort -u);
1454             if [ -n $pids ]; then
1455                 do_node $client kill -9 $pids || true
1456             fi
1457         fi
1458
1459         busy=$(do_node $client "umount $force $mnt 2>&1" | grep -c "busy") || true
1460         if [ $busy -ne 0 ] ; then
1461             echo "$mnt is still busy, wait one second" && sleep 1
1462             do_node $client umount $force $mnt
1463         fi
1464     fi
1465 }
1466
1467 # nodes is comma list
1468 sanity_mount_check_nodes () {
1469     local nodes=$1
1470     shift
1471     local mnts="$@"
1472     local mnt
1473
1474     # FIXME: assume that all cluster nodes run the same os
1475     [ "$(uname)" = Linux ] || return 0
1476
1477     local rc=0
1478     for mnt in $mnts ; do
1479         do_nodes $nodes "running=\\\$(grep -c $mnt' ' /proc/mounts);
1480 mpts=\\\$(mount | grep -c $mnt' ');
1481 if [ \\\$running -ne \\\$mpts ]; then
1482     echo \\\$(hostname) env are INSANE!;
1483     exit 1;
1484 fi"
1485     [ $? -eq 0 ] || rc=1 
1486     done
1487     return $rc
1488 }
1489
1490 sanity_mount_check_servers () {
1491     [ "$CLIENTONLY" ] && 
1492         { echo "CLIENTONLY mode, skip mount_check_servers"; return 0; } || true
1493     echo Checking servers environments
1494
1495     # FIXME: modify get_facets to display all facets wo params
1496     local facets="$(get_facets OST),$(get_facets MDS),mgs"
1497     local node
1498     local mntpt
1499     local facet
1500     for facet in ${facets//,/ }; do
1501         node=$(facet_host ${facet})
1502         mntpt=$(facet_mntpt $facet)
1503         sanity_mount_check_nodes $node $mntpt ||
1504             { error "server $node environments are insane!"; return 1; }
1505     done
1506 }
1507
1508 sanity_mount_check_clients () {
1509     local clients=${1:-$CLIENTS}
1510     local mntpt=${2:-$MOUNT}
1511     local mntpt2=${3:-$MOUNT2}
1512
1513     [ -z $clients ] && clients=$(hostname)
1514     echo Checking clients $clients environments
1515
1516     sanity_mount_check_nodes $clients $mntpt $mntpt2 ||
1517        error "clients environments are insane!"
1518 }
1519
1520 sanity_mount_check () {
1521     sanity_mount_check_servers || return 1
1522     sanity_mount_check_clients || return 2
1523 }
1524
1525 # mount clients if not mouted
1526 zconf_mount_clients() {
1527     local clients=$1
1528     local mnt=$2
1529     local OPTIONS=${3:-$MOUNTOPT}
1530
1531     local device=$MGSNID:/$FSNAME
1532     if [ -z "$mnt" -o -z "$FSNAME" ]; then
1533         echo Bad zconf mount command: opt=$OPTIONS dev=$device mnt=$mnt
1534         exit 1
1535     fi
1536
1537     echo "Starting client $clients: $OPTIONS $device $mnt"
1538
1539     do_nodes $clients "
1540 running=\\\$(mount | grep -c $mnt' ');
1541 rc=0;
1542 if [ \\\$running -eq 0 ] ; then
1543     mkdir -p $mnt;
1544     mount -t lustre $OPTIONS $device $mnt;
1545     rc=\\\$?;
1546 fi;
1547 exit \\\$rc" || return ${PIPESTATUS[0]}
1548
1549     echo "Started clients $clients: "
1550     do_nodes $clients "mount | grep $mnt' '"
1551
1552     set_default_debug_nodes $clients
1553
1554     return 0
1555 }
1556
1557 zconf_umount_clients() {
1558     local clients=$1
1559     local mnt=$2
1560     local force
1561
1562     [ "$3" ] && force=-f
1563
1564     echo "Stopping clients: $clients $mnt (opts:$force)"
1565     do_nodes $clients "running=\\\$(grep -c $mnt' ' /proc/mounts);
1566 if [ \\\$running -ne 0 ] ; then
1567 echo Stopping client \\\$(hostname) $mnt opts:$force;
1568 lsof $mnt || need_kill=no;
1569 if [ "x$force" != "x" -a "x\\\$need_kill" != "xno" ]; then
1570     pids=\\\$(lsof -t $mnt | sort -u);
1571     if [ -n \\\"\\\$pids\\\" ]; then
1572              kill -9 \\\$pids;
1573     fi
1574 fi;
1575 while umount $force $mnt 2>&1 | grep -q "busy"; do
1576     echo "$mnt is still busy, wait one second" && sleep 1;
1577 done;
1578 fi"
1579 }
1580
1581 shutdown_node () {
1582     local node=$1
1583     echo + $POWER_DOWN $node
1584     $POWER_DOWN $node
1585 }
1586
1587 shutdown_node_hard () {
1588     local host=$1
1589     local attempts=$SHUTDOWN_ATTEMPTS
1590
1591     for i in $(seq $attempts) ; do
1592         shutdown_node $host
1593         sleep 1
1594         wait_for_function --quiet "! ping -w 3 -c 1 $host" 5 1 && return 0
1595         echo "waiting for $host to fail attempts=$attempts"
1596         [ $i -lt $attempts ] || \
1597             { echo "$host still pingable after power down! attempts=$attempts" && return 1; } 
1598     done
1599 }
1600
1601 shutdown_client() {
1602     local client=$1
1603     local mnt=${2:-$MOUNT}
1604     local attempts=3
1605
1606     if [ "$FAILURE_MODE" = HARD ]; then
1607         shutdown_node_hard $client
1608     else
1609        zconf_umount_clients $client $mnt -f
1610     fi
1611 }
1612
1613 facets_on_host () {
1614     local host=$1
1615     local facets="$(get_facets OST),$(get_facets MDS)"
1616     local affected
1617
1618     combined_mgs_mds || facets="$facets,mgs"
1619
1620     for facet in ${facets//,/ }; do
1621         if [ $(facet_active_host $facet) == $host ]; then
1622            affected="$affected $facet"
1623         fi
1624     done
1625
1626     echo $(comma_list $affected)
1627 }
1628
1629 facet_up() {
1630         local facet=$1
1631         local host=${2:-$(facet_host $facet)}
1632
1633         local label=$(convert_facet2label $facet)
1634         do_node $host $LCTL dl | awk '{print $4}' | grep -q -x $label
1635 }
1636
1637 facets_up_on_host () {
1638     local host=$1
1639     local facets=$(facets_on_host $host)
1640     local affected_up
1641
1642     for facet in ${facets//,/ }; do
1643         if $(facet_up $facet $host); then
1644             affected_up="$affected_up $facet"
1645         fi
1646     done
1647
1648     echo $(comma_list $affected_up)
1649 }
1650
1651 shutdown_facet() {
1652     local facet=$1
1653
1654     if [ "$FAILURE_MODE" = HARD ]; then
1655         shutdown_node_hard $(facet_active_host $facet)
1656     else
1657         stop $facet
1658     fi
1659 }
1660
1661 reboot_node() {
1662     local node=$1
1663     echo + $POWER_UP $node
1664     $POWER_UP $node
1665 }
1666
1667 remount_facet() {
1668     local facet=$1
1669
1670     stop $facet
1671     mount_facet $facet
1672 }
1673
1674 reboot_facet() {
1675         local facet=$1
1676         if [ "$FAILURE_MODE" = HARD ]; then
1677                 reboot_node $(facet_active_host $facet)
1678         else
1679                 sleep 10
1680         fi
1681 }
1682
1683 boot_node() {
1684     local node=$1
1685     if [ "$FAILURE_MODE" = HARD ]; then
1686        reboot_node $node
1687        wait_for_host $node
1688     fi
1689 }
1690
1691 facets_hosts () {
1692     local facets=$1
1693     local hosts
1694
1695     for facet in ${facets//,/ }; do
1696         hosts=$(expand_list $hosts $(facet_host $facet) )
1697     done
1698
1699     echo $hosts
1700 }
1701
1702 _check_progs_installed () {
1703     local progs=$@
1704     local rc=0
1705
1706     for prog in $progs; do
1707         if ! [ "$(which $prog)"  -o  "${!prog}" ]; then
1708            echo $prog missing on $(hostname)
1709            rc=1
1710         fi
1711     done
1712     return $rc
1713 }
1714
1715 check_progs_installed () {
1716         local nodes=$1
1717         shift
1718
1719         do_rpc_nodes "$nodes" _check_progs_installed $@
1720 }
1721
1722 # recovery-scale functions
1723 node_var_name() {
1724     echo __$(echo $1 | tr '-' '_' | tr '.' '_')
1725 }
1726
1727 start_client_load() {
1728     local client=$1
1729     local load=$2
1730     local var=$(node_var_name $client)_load
1731     eval export ${var}=$load
1732
1733     do_node $client "PATH=$PATH MOUNT=$MOUNT ERRORS_OK=$ERRORS_OK \
1734 BREAK_ON_ERROR=$BREAK_ON_ERROR \
1735 END_RUN_FILE=$END_RUN_FILE \
1736 LOAD_PID_FILE=$LOAD_PID_FILE \
1737 TESTLOG_PREFIX=$TESTLOG_PREFIX \
1738 TESTNAME=$TESTNAME \
1739 DBENCH_LIB=$DBENCH_LIB \
1740 DBENCH_SRC=$DBENCH_SRC \
1741 CLIENT_COUNT=$((CLIENTCOUNT - 1)) \
1742 LFS=$LFS \
1743 run_${load}.sh" &
1744     local ppid=$!
1745     log "Started client load: ${load} on $client"
1746
1747     # get the children process IDs
1748     local pids=$(ps --ppid $ppid -o pid= | xargs)
1749     CLIENT_LOAD_PIDS="$CLIENT_LOAD_PIDS $ppid $pids"
1750     return 0
1751 }
1752
1753 start_client_loads () {
1754     local -a clients=(${1//,/ })
1755     local numloads=${#CLIENT_LOADS[@]}
1756     local testnum
1757
1758     for ((nodenum=0; nodenum < ${#clients[@]}; nodenum++ )); do
1759         testnum=$((nodenum % numloads))
1760         start_client_load ${clients[nodenum]} ${CLIENT_LOADS[testnum]}
1761     done
1762     # bug 22169: wait the background threads to start
1763     sleep 2
1764 }
1765
1766 # only for remote client
1767 check_client_load () {
1768     local client=$1
1769     local var=$(node_var_name $client)_load
1770     local TESTLOAD=run_${!var}.sh
1771
1772     ps auxww | grep -v grep | grep $client | grep -q "$TESTLOAD" || return 1
1773
1774     # bug 18914: try to connect several times not only when
1775     # check ps, but  while check_catastrophe also
1776     local tries=3
1777     local RC=254
1778     while [ $RC = 254 -a $tries -gt 0 ]; do
1779         let tries=$tries-1
1780         # assume success
1781         RC=0
1782         if ! check_catastrophe $client; then
1783             RC=${PIPESTATUS[0]}
1784             if [ $RC -eq 254 ]; then
1785                 # FIXME: not sure how long we shuold sleep here
1786                 sleep 10
1787                 continue
1788             fi
1789             echo "check catastrophe failed: RC=$RC "
1790             return $RC
1791         fi
1792     done
1793     # We can continue try to connect if RC=254
1794     # Just print the warning about this
1795     if [ $RC = 254 ]; then
1796         echo "got a return status of $RC from do_node while checking catastrophe on $client"
1797     fi
1798
1799     # see if the load is still on the client
1800     tries=3
1801     RC=254
1802     while [ $RC = 254 -a $tries -gt 0 ]; do
1803         let tries=$tries-1
1804         # assume success
1805         RC=0
1806         if ! do_node $client "ps auxwww | grep -v grep | grep -q $TESTLOAD"; then
1807             RC=${PIPESTATUS[0]}
1808             sleep 30
1809         fi
1810     done
1811     if [ $RC = 254 ]; then
1812         echo "got a return status of $RC from do_node while checking (catastrophe and 'ps') the client load on $client"
1813         # see if we can diagnose a bit why this is
1814     fi
1815
1816     return $RC
1817 }
1818 check_client_loads () {
1819    local clients=${1//,/ }
1820    local client=
1821    local rc=0
1822
1823    for client in $clients; do
1824       check_client_load $client
1825       rc=${PIPESTATUS[0]}
1826       if [ "$rc" != 0 ]; then
1827         log "Client load failed on node $client, rc=$rc"
1828         return $rc
1829       fi
1830    done
1831 }
1832
1833 restart_client_loads () {
1834     local clients=${1//,/ }
1835     local expectedfail=${2:-""}
1836     local client=
1837     local rc=0
1838
1839     for client in $clients; do
1840         check_client_load $client
1841         rc=${PIPESTATUS[0]}
1842         if [ "$rc" != 0 -a "$expectedfail" ]; then
1843             local var=$(node_var_name $client)_load
1844             start_client_load $client ${!var}
1845             echo "Restarted client load ${!var}: on $client. Checking ..."
1846             check_client_load $client
1847             rc=${PIPESTATUS[0]}
1848             if [ "$rc" != 0 ]; then
1849                 log "Client load failed to restart on node $client, rc=$rc"
1850                 # failure one client load means test fail
1851                 # we do not need to check other
1852                 return $rc
1853             fi
1854         else
1855             return $rc
1856         fi
1857     done
1858 }
1859
1860 # Start vmstat and save its process ID in a file.
1861 start_vmstat() {
1862     local nodes=$1
1863     local pid_file=$2
1864
1865     [ -z "$nodes" -o -z "$pid_file" ] && return 0
1866
1867     do_nodes $nodes \
1868         "vmstat 1 > $TESTLOG_PREFIX.$TESTNAME.vmstat.\\\$(hostname -s).log \
1869         2>/dev/null </dev/null & echo \\\$! > $pid_file"
1870 }
1871
1872 # Display the nodes on which client loads failed.
1873 print_end_run_file() {
1874     local file=$1
1875     local node
1876
1877     [ -s $file ] || return 0
1878
1879     echo "Found the END_RUN_FILE file: $file"
1880     cat $file
1881
1882     # A client load will stop if it finds the END_RUN_FILE file.
1883     # That does not mean the client load actually failed though.
1884     # The first node in END_RUN_FILE is the one we are interested in.
1885     read node < $file
1886
1887     if [ -n "$node" ]; then
1888         local var=$(node_var_name $node)_load
1889
1890         local prefix=$TESTLOG_PREFIX
1891         [ -n "$TESTNAME" ] && prefix=$prefix.$TESTNAME
1892         local stdout_log=$prefix.run_${!var}_stdout.$node.log
1893         local debug_log=$(echo $stdout_log | sed 's/\(.*\)stdout/\1debug/')
1894
1895         echo "Client load ${!var} failed on node $node:"
1896         echo "$stdout_log"
1897         echo "$debug_log"
1898     fi
1899 }
1900
1901 # Stop the process which had its PID saved in a file.
1902 stop_process() {
1903     local nodes=$1
1904     local pid_file=$2
1905
1906     [ -z "$nodes" -o -z "$pid_file" ] && return 0
1907
1908     do_nodes $nodes "test -f $pid_file &&
1909         { kill -s TERM \\\$(cat $pid_file); rm -f $pid_file; }" || true
1910 }
1911
1912 # Stop all client loads.
1913 stop_client_loads() {
1914     local nodes=${1:-$CLIENTS}
1915     local pid_file=$2
1916
1917     # stop the client loads
1918     stop_process $nodes $pid_file
1919
1920     # clean up the processes that started them
1921     [ -n "$CLIENT_LOAD_PIDS" ] && kill -9 $CLIENT_LOAD_PIDS 2>/dev/null || true
1922 }
1923 # End recovery-scale functions
1924
1925 # verify that lustre actually cleaned up properly
1926 cleanup_check() {
1927     [ -f $CATASTROPHE ] && [ `cat $CATASTROPHE` -ne 0 ] && \
1928         error "LBUG/LASSERT detected"
1929     BUSY=`dmesg | grep -i destruct || true`
1930     if [ "$BUSY" ]; then
1931         echo "$BUSY" 1>&2
1932         [ -e $TMP/debug ] && mv $TMP/debug $TMP/debug-busy.`date +%s`
1933         exit 205
1934     fi
1935
1936     check_mem_leak || exit 204
1937
1938         [ "`lctl dl 2> /dev/null | wc -l`" -gt 0 ] && lctl dl &&
1939                 echo "$TESTSUITE: lustre didn't clean up..." 1>&2 &&
1940                 return 202 || true
1941
1942         if module_loaded lnet || module_loaded libcfs; then
1943                 echo "$TESTSUITE: modules still loaded..." 1>&2
1944                 /sbin/lsmod 1>&2
1945                 return 203
1946         fi
1947         return 0
1948 }
1949
1950 wait_update () {
1951         local verbose=false
1952         if [[ "$1" == "--verbose" ]]; then
1953                 shift
1954                 verbose=true
1955         fi
1956
1957         local node=$1
1958         local TEST=$2
1959         local FINAL=$3
1960         local MAX=${4:-90}
1961         local RESULT
1962         local PREV_RESULT
1963         local WAIT=0
1964         local sleep=1
1965         local print=10
1966
1967         PREV_RESULT=$(do_node $node "$TEST")
1968         while [ true ]; do
1969                 RESULT=$(do_node $node "$TEST")
1970                 if [[ "$RESULT" == "$FINAL" ]]; then
1971                         [[ -z "$RESULT" || $WAIT -le $sleep ]] ||
1972                                 echo "Updated after ${WAIT}s: wanted '$FINAL'"\
1973                                      "got '$RESULT'"
1974                         return 0
1975                 fi
1976                 if [[ $verbose && "$RESULT" != "$PREV_RESULT" ]]; then
1977                         echo "Changed after ${WAIT}s: from '$PREV_RESULT'"\
1978                              "to '$RESULT'"
1979                         PREV_RESULT=$RESULT
1980                 fi
1981                 [[ $WAIT -ge $MAX ]] && break
1982                 [[ $((WAIT % print)) -eq 0 ]] &&
1983                         echo "Waiting $((MAX - WAIT)) secs for update"
1984                 WAIT=$((WAIT + sleep))
1985                 sleep $sleep
1986         done
1987         echo "Update not seen after ${MAX}s: wanted '$FINAL' got '$RESULT'"
1988         return 3
1989 }
1990
1991 wait_update_facet() {
1992         local facet=$1
1993         shift
1994         wait_update $(facet_active_host $facet) "$@"
1995 }
1996
1997 sync_all_data() {
1998         do_nodes $(comma_list $(mdts_nodes)) \
1999             "lctl set_param -n osd*.*MDT*.force_sync 1"
2000         do_nodes $(comma_list $(osts_nodes)) \
2001             "lctl set_param -n osd*.*OS*.force_sync 1" 2>&1 |
2002                 grep -v 'Found no match'
2003 }
2004
2005 wait_delete_completed_mds() {
2006         local MAX_WAIT=${1:-20}
2007         local mds2sync=""
2008         local stime=`date +%s`
2009         local etime
2010         local node
2011         local changes
2012
2013         # find MDS with pending deletions
2014         for node in $(mdts_nodes); do
2015                 changes=$(do_node $node "lctl get_param -n osc.*MDT*.sync_*" \
2016                         2>/dev/null | calc_sum)
2017                 if [ -z "$changes" ] || [ $changes -eq 0 ]; then
2018                         continue
2019                 fi
2020                 mds2sync="$mds2sync $node"
2021         done
2022         if [ "$mds2sync" == "" ]; then
2023                 return
2024         fi
2025         mds2sync=$(comma_list $mds2sync)
2026
2027         # sync MDS transactions
2028         do_nodes $mds2sync "lctl set_param -n osd*.*MD*.force_sync 1"
2029
2030         # wait till all changes are sent and commmitted by OSTs
2031         # for ldiskfs space is released upon execution, but DMU
2032         # do this upon commit
2033
2034         local WAIT=0
2035         while [ "$WAIT" -ne "$MAX_WAIT" ]; do
2036                 changes=$(do_nodes $mds2sync "lctl get_param -n osc.*MDT*.sync_*" \
2037                         | calc_sum)
2038                 #echo "$node: $changes changes on all"
2039                 if [ "$changes" -eq "0" ]; then
2040                         etime=`date +%s`
2041                         #echo "delete took $((etime - stime)) seconds"
2042                         return
2043                 fi
2044                 sleep 1
2045                 WAIT=$(( WAIT + 1))
2046         done
2047
2048         etime=`date +%s`
2049         echo "Delete is not completed in $((etime - stime)) seconds"
2050         do_nodes $mds2sync "lctl get_param osc.*MDT*.sync_*"
2051 }
2052
2053 wait_for_host() {
2054     local hostlist=$1
2055
2056     # we can use "for" here because we are waiting the slowest
2057     for host in ${hostlist//,/ }; do
2058         check_network "$host" 900
2059     done
2060     while ! do_nodes $hostlist hostname  > /dev/null; do sleep 5; done
2061 }
2062
2063 wait_for_facet() {
2064     local facetlist=$1
2065     local hostlist
2066
2067     for facet in ${facetlist//,/ }; do
2068         hostlist=$(expand_list $hostlist $(facet_active_host $facet))
2069     done
2070     wait_for_host $hostlist
2071 }
2072
2073 _wait_recovery_complete () {
2074     local param=$1
2075
2076     # Use default policy if $2 is not passed by caller.
2077     local MAX=${2:-$(max_recovery_time)}
2078
2079     local WAIT=0
2080     local STATUS=
2081
2082     while [ $WAIT -lt $MAX ]; do
2083         STATUS=$(lctl get_param -n $param | grep status)
2084         echo $param $STATUS
2085         [[ $STATUS = "status: COMPLETE" || $STATUS = "status: INACTIVE" ]] && return 0
2086         sleep 5
2087         WAIT=$((WAIT + 5))
2088         echo "Waiting $((MAX - WAIT)) secs for $param recovery done. $STATUS"
2089     done
2090     echo "$param recovery not done in $MAX sec. $STATUS"
2091     return 1
2092 }
2093
2094 wait_recovery_complete () {
2095     local facet=$1
2096
2097     # with an assumption that at_max is the same on all nodes
2098     local MAX=${2:-$(max_recovery_time)}
2099
2100     local facets=$facet
2101     if [ "$FAILURE_MODE" = HARD ]; then
2102         facets=$(facets_on_host $(facet_active_host $facet))
2103     fi
2104     echo affected facets: $facets
2105
2106         # we can use "for" here because we are waiting the slowest
2107         for facet in ${facets//,/ }; do
2108                 local var_svc=${facet}_svc
2109                 local param="*.${!var_svc}.recovery_status"
2110
2111                 local host=$(facet_active_host $facet)
2112                 do_rpc_nodes "$host" _wait_recovery_complete $param $MAX
2113         done
2114 }
2115
2116 wait_mds_ost_sync () {
2117         # just because recovery is done doesn't mean we've finished
2118         # orphan cleanup. Wait for llogs to get synchronized.
2119         echo "Waiting for orphan cleanup..."
2120         # MAX value includes time needed for MDS-OST reconnection
2121         local MAX=$(( TIMEOUT * 2 ))
2122         local WAIT_TIMEOUT=${1:-$MAX}
2123         local WAIT=0
2124         local new_wait=true
2125         local list=$(comma_list $(mdts_nodes))
2126         local cmd="$LCTL get_param -n osp.*osc*.old_sync_processed"
2127         if ! do_facet $SINGLEMDS \
2128                 "$LCTL list_param osp.*osc*.old_sync_processed 2> /dev/null"
2129         then
2130                 # old way, use mds_sync
2131                 new_wait=false
2132                 list=$(comma_list $(osts_nodes))
2133                 cmd="$LCTL get_param -n obdfilter.*.mds_sync"
2134         fi
2135
2136         echo "wait $WAIT_TIMEOUT secs maximumly for $list mds-ost sync done."
2137         while [ $WAIT -lt $WAIT_TIMEOUT ]; do
2138                 local -a sync=($(do_nodes $list "$cmd"))
2139                 local con=1
2140                 local i
2141                 for ((i=0; i<${#sync[@]}; i++)); do
2142                         if $new_wait; then
2143                                 [ ${sync[$i]} -eq 1 ] && continue
2144                         else
2145                                 [ ${sync[$i]} -eq 0 ] && continue
2146                         fi
2147                         # there is a not finished MDS-OST synchronization
2148                         con=0
2149                         break;
2150                 done
2151                 sleep 2 # increase waiting time and cover statfs cache
2152                 [ ${con} -eq 1 ] && return 0
2153                 echo "Waiting $WAIT secs for $list $i mds-ost sync done."
2154                 WAIT=$((WAIT + 2))
2155         done
2156
2157         # show which nodes are not finished.
2158         do_nodes $list "$cmd"
2159         echo "$facet recovery node $i not done in $WAIT_TIMEOUT sec. $STATUS"
2160         return 1
2161 }
2162
2163 wait_destroy_complete () {
2164         echo "Waiting for local destroys to complete"
2165         # MAX value shouldn't be big as this mean server responsiveness
2166         # never increase this just to make test pass but investigate
2167         # why it takes so long time
2168         local MAX=5
2169         local WAIT=0
2170         while [ $WAIT -lt $MAX ]; do
2171                 local -a RPCs=($($LCTL get_param -n osc.*.destroys_in_flight))
2172                 local con=1
2173                 local i
2174
2175                 for ((i=0; i<${#RPCs[@]}; i++)); do
2176                         [ ${RPCs[$i]} -eq 0 ] && continue
2177                         # there are still some destroy RPCs in flight
2178                         con=0
2179                         break;
2180                 done
2181                 sleep 1
2182                 [ ${con} -eq 1 ] && return 0 # done waiting
2183                 echo "Waiting ${WAIT}s for local destroys to complete"
2184                 WAIT=$((WAIT + 1))
2185         done
2186         echo "Local destroys weren't done in $MAX sec."
2187         return 1
2188 }
2189
2190 wait_delete_completed() {
2191         wait_delete_completed_mds $1 || return $?
2192         wait_destroy_complete
2193 }
2194
2195 wait_exit_ST () {
2196     local facet=$1
2197
2198     local WAIT=0
2199     local INTERVAL=1
2200     local running
2201     # conf-sanity 31 takes a long time cleanup
2202     while [ $WAIT -lt 300 ]; do
2203         running=$(do_facet ${facet} "lsmod | grep lnet > /dev/null && lctl dl | grep ' ST '") || true
2204         [ -z "${running}" ] && return 0
2205         echo "waited $WAIT for${running}"
2206         [ $INTERVAL -lt 64 ] && INTERVAL=$((INTERVAL + INTERVAL))
2207         sleep $INTERVAL
2208         WAIT=$((WAIT + INTERVAL))
2209     done
2210     echo "service didn't stop after $WAIT seconds.  Still running:"
2211     echo ${running}
2212     return 1
2213 }
2214
2215 wait_remote_prog () {
2216    local prog=$1
2217    local WAIT=0
2218    local INTERVAL=5
2219    local rc=0
2220
2221    [ "$PDSH" = "no_dsh" ] && return 0
2222
2223    while [ $WAIT -lt $2 ]; do
2224         running=$(ps uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep) || true
2225         [ -z "${running}" ] && return 0 || true
2226         echo "waited $WAIT for: "
2227         echo "$running"
2228         [ $INTERVAL -lt 60 ] && INTERVAL=$((INTERVAL + INTERVAL))
2229         sleep $INTERVAL
2230         WAIT=$((WAIT + INTERVAL))
2231     done
2232     local pids=$(ps  uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep | awk '{print $2}')
2233     [ -z "$pids" ] && return 0
2234     echo "$PDSH processes still exists after $WAIT seconds.  Still running: $pids"
2235     # FIXME: not portable
2236     for pid in $pids; do
2237         cat /proc/${pid}/status || true
2238         cat /proc/${pid}/wchan || true
2239         echo "Killing $pid"
2240         kill -9 $pid || true
2241         sleep 1
2242         ps -P $pid && rc=1
2243     done
2244
2245     return $rc
2246 }
2247
2248 clients_up() {
2249     # not every config has many clients
2250     sleep 1
2251     if [ ! -z "$CLIENTS" ]; then
2252         $PDSH $CLIENTS "stat -f $MOUNT" > /dev/null
2253     else
2254         stat -f $MOUNT > /dev/null
2255     fi
2256 }
2257
2258 client_up() {
2259     local client=$1
2260     # usually checked on particular client or locally
2261     sleep 1
2262     if [ ! -z "$client" ]; then
2263         $PDSH $client "stat -f $MOUNT" > /dev/null
2264     else
2265         stat -f $MOUNT > /dev/null
2266     fi
2267 }
2268
2269 client_evicted() {
2270     ! client_up $1
2271 }
2272
2273 client_reconnect() {
2274     uname -n >> $MOUNT/recon
2275     if [ -z "$CLIENTS" ]; then
2276         df $MOUNT; uname -n >> $MOUNT/recon
2277     else
2278         do_nodes $CLIENTS "df $MOUNT; uname -n >> $MOUNT/recon" > /dev/null
2279     fi
2280     echo Connected clients:
2281     cat $MOUNT/recon
2282     ls -l $MOUNT/recon > /dev/null
2283     rm $MOUNT/recon
2284 }
2285
2286 affected_facets () {
2287     local facet=$1
2288
2289     local host=$(facet_active_host $facet)
2290     local affected=$facet
2291
2292     if [ "$FAILURE_MODE" = HARD ]; then
2293         affected=$(facets_up_on_host $host)
2294     fi
2295     echo $affected
2296 }
2297
2298 facet_failover() {
2299         local facets=$1
2300         local sleep_time=$2
2301         local -a affecteds
2302         local facet
2303         local total=0
2304         local index=0
2305         local skip
2306
2307         #Because it will only get up facets, we need get affected
2308         #facets before shutdown
2309         #For HARD Failure mode, it needs make sure facets on the same
2310         #HOST will only be shutdown and reboot once
2311         for facet in ${facets//,/ }; do
2312                 local affected_facet
2313                 skip=0
2314                 #check whether facet has been included in other affected facets
2315                 for ((index=0; index<$total; index++)); do
2316                         [[ *,$facet,* == ,${affecteds[index]}, ]] && skip=1
2317                 done
2318
2319                 if [ $skip -eq 0 ]; then
2320                         affecteds[$total]=$(affected_facets $facet)
2321                         total=$((total+1))
2322                 fi
2323         done
2324
2325         for ((index=0; index<$total; index++)); do
2326                 facet=$(echo ${affecteds[index]} | tr -s " " | cut -d"," -f 1)
2327                 local host=$(facet_active_host $facet)
2328                 echo "Failing ${affecteds[index]} on $host"
2329                 shutdown_facet $facet
2330         done
2331
2332         for ((index=0; index<$total; index++)); do
2333                 facet=$(echo ${affecteds[index]} | tr -s " " | cut -d"," -f 1)
2334                 echo reboot facets: ${affecteds[index]}
2335
2336                 reboot_facet $facet
2337
2338                 change_active ${affecteds[index]}
2339
2340                 wait_for_facet ${affecteds[index]}
2341                 # start mgs first if it is affected
2342                 if ! combined_mgs_mds &&
2343                         list_member ${affecteds[index]} mgs; then
2344                         mount_facet mgs || error "Restart of mgs failed"
2345                 fi
2346                 # FIXME; has to be changed to mount all facets concurrently
2347                 affected=$(exclude_items_from_list ${affecteds[index]} mgs)
2348                 echo mount facets: ${affecteds[index]}
2349                 mount_facets ${affecteds[index]}
2350         done
2351 }
2352
2353 obd_name() {
2354     local facet=$1
2355 }
2356
2357 replay_barrier() {
2358         local facet=$1
2359         do_facet $facet "sync; sync; sync"
2360         df $MOUNT
2361
2362         # make sure there will be no seq change
2363         local clients=${CLIENTS:-$HOSTNAME}
2364         local f=fsa-\\\$\(hostname\)
2365         do_nodes $clients "mcreate $MOUNT/$f; rm $MOUNT/$f"
2366         do_nodes $clients "if [ -d $MOUNT2 ]; then mcreate $MOUNT2/$f; rm $MOUNT2/$f; fi"
2367
2368         local svc=${facet}_svc
2369         do_facet $facet $LCTL --device ${!svc} notransno
2370         #
2371         # If a ZFS OSD is made read-only here, its pool is "freezed". This
2372         # in-memory state has to be cleared by either rebooting the host or
2373         # exporting and reimporting the pool.
2374         #
2375         # Although the uberblocks are not updated when a pool is freezed,
2376         # transactions are still written to the disks. Modified blocks may be
2377         # cached in memory when tests try reading them back. The
2378         # export-and-reimport process also evicts any cached pool data from
2379         # memory to provide the correct "data loss" semantics.
2380         #
2381         # In the test framework, the exporting and importing operations are
2382         # handled by stop() and mount_facet() separately, which are used
2383         # inside fail() and fail_abort().
2384         #
2385         do_facet $facet $LCTL --device ${!svc} readonly
2386         do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
2387         $LCTL mark "local REPLAY BARRIER on ${!svc}"
2388 }
2389
2390 replay_barrier_nodf() {
2391         local facet=$1    echo running=${running}
2392         do_facet $facet "sync; sync; sync"
2393         local svc=${facet}_svc
2394         echo Replay barrier on ${!svc}
2395         do_facet $facet $LCTL --device ${!svc} notransno
2396         do_facet $facet $LCTL --device ${!svc} readonly
2397         do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
2398         $LCTL mark "local REPLAY BARRIER on ${!svc}"
2399 }
2400
2401 replay_barrier_nosync() {
2402         local facet=$1    echo running=${running}
2403         local svc=${facet}_svc
2404         echo Replay barrier on ${!svc}
2405         do_facet $facet $LCTL --device ${!svc} notransno
2406         do_facet $facet $LCTL --device ${!svc} readonly
2407         do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
2408         $LCTL mark "local REPLAY BARRIER on ${!svc}"
2409 }
2410
2411 #
2412 # Get Lustre client uuid for a given Lustre mount point.
2413 #
2414 get_client_uuid() {
2415         local mntpnt=${1:-$MOUNT}
2416
2417         local name=$($LFS getname $mntpnt | cut -d' ' -f1)
2418         local uuid=$($LCTL get_param -n llite.$name.uuid)
2419
2420         echo -n $uuid
2421 }
2422
2423 mds_evict_client() {
2424         local mntpnt=${1:-$MOUNT}
2425         local uuid=$(get_client_uuid $mntpnt)
2426
2427         do_facet $SINGLEMDS \
2428                 "$LCTL set_param -n mdt.${mds1_svc}.evict_client $uuid"
2429 }
2430
2431 ost_evict_client() {
2432         local mntpnt=${1:-$MOUNT}
2433         local uuid=$(get_client_uuid $mntpnt)
2434
2435         do_facet ost1 \
2436                 "$LCTL set_param -n obdfilter.${ost1_svc}.evict_client $uuid"
2437 }
2438
2439 fail() {
2440         local facets=$1
2441         local clients=${CLIENTS:-$HOSTNAME}
2442
2443         facet_failover $* || error "failover: $?"
2444         wait_clients_import_state "$clients" "$facets" FULL
2445         clients_up || error "post-failover df: $?"
2446 }
2447
2448 fail_nodf() {
2449         local facet=$1
2450         facet_failover $facet
2451 }
2452
2453 fail_abort() {
2454         local facet=$1
2455         stop $facet
2456         change_active $facet
2457         wait_for_facet $facet
2458         mount_facet $facet -o abort_recovery
2459         clients_up || echo "first df failed: $?"
2460         clients_up || error "post-failover df: $?"
2461 }
2462
2463 do_lmc() {
2464     echo There is no lmc.  This is mountconf, baby.
2465     exit 1
2466 }
2467
2468 host_nids_address() {
2469     local nodes=$1
2470     local kind=$2
2471
2472     if [ -n "$kind" ]; then
2473         nids=$(do_nodes $nodes "$LCTL list_nids | grep $kind | cut -f 1 -d '@'")
2474     else
2475         nids=$(do_nodes $nodes "$LCTL list_nids all | cut -f 1 -d '@'")
2476     fi
2477     echo $nids
2478 }
2479
2480 h2name_or_ip() {
2481         if [ "$1" = "'*'" ]; then echo \'*\'; else
2482                 echo $1"@$2"
2483         fi
2484 }
2485
2486 h2ptl() {
2487         if [ "$1" = "'*'" ]; then echo \'*\'; else
2488                 ID=`xtprocadmin -n $1 2>/dev/null | egrep -v 'NID' | \
2489                                                         awk '{print $1}'`
2490                 if [ -z "$ID" ]; then
2491                         echo "Could not get a ptl id for $1..."
2492                         exit 1
2493                 fi
2494                 echo $ID"@ptl"
2495         fi
2496 }
2497 declare -fx h2ptl
2498
2499 h2tcp() {
2500         h2name_or_ip "$1" "tcp"
2501 }
2502 declare -fx h2tcp
2503
2504 h2elan() {
2505         if [ "$1" = "'*'" ]; then echo \'*\'; else
2506                 if type __h2elan >/dev/null 2>&1; then
2507                         ID=$(__h2elan $1)
2508                 else
2509                         ID=`echo $1 | sed 's/[^0-9]*//g'`
2510                 fi
2511                 echo $ID"@elan"
2512         fi
2513 }
2514 declare -fx h2elan
2515
2516 h2o2ib() {
2517         h2name_or_ip "$1" "o2ib"
2518 }
2519 declare -fx h2o2ib
2520
2521 # This enables variables in cfg/"setup".sh files to support the pdsh HOSTLIST
2522 # expressions format. As a bonus we can then just pass in those variables
2523 # to pdsh. What this function does is take a HOSTLIST type string and
2524 # expand it into a space deliminated list for us.
2525 hostlist_expand() {
2526     local hostlist=$1
2527     local offset=$2
2528     local myList
2529     local item
2530     local list
2531
2532     [ -z "$hostlist" ] && return
2533
2534     # Translate the case of [..],..,[..] to [..] .. [..]
2535     list="${hostlist/],/] }"
2536     front=${list%%[*}
2537     [[ "$front" == *,* ]] && {
2538         new="${list%,*} "
2539         old="${list%,*},"
2540         list=${list/${old}/${new}}
2541     }
2542
2543     for item in $list; do
2544         # Test if we have any []'s at all
2545         if [ "$item" != "${item/\[/}" ]; then {
2546             # Expand the [*] into list
2547             name=${item%%[*}
2548             back=${item#*]}
2549
2550             if [ "$name" != "$item" ]; then
2551                 group=${item#$name[*}
2552                 group=${group%%]*}
2553
2554                 for range in ${group//,/ }; do
2555                     begin=${range%-*}
2556                     end=${range#*-}
2557
2558                     # Number of leading zeros
2559                     padlen=${#begin}
2560                     padlen2=${#end}
2561                     end=$(echo $end | sed 's/0*//')
2562                     [[ -z "$end" ]] && end=0
2563                     [[ $padlen2 -gt $padlen ]] && {
2564                         [[ $padlen2 -eq ${#end} ]] && padlen2=0
2565                         padlen=$padlen2
2566                     }
2567                     begin=$(echo $begin | sed 's/0*//')
2568                     [ -z $begin ] && begin=0
2569
2570                     for num in $(seq -f "%0${padlen}g" $begin $end); do
2571                         value="${name#*,}${num}${back}"
2572                         [ "$value" != "${value/\[/}" ] && {
2573                             value=$(hostlist_expand "$value")
2574                         }
2575                         myList="$myList $value"
2576                     done
2577                 done
2578             fi
2579         } else {
2580             myList="$myList $item"
2581         } fi
2582     done
2583     myList=${myList//,/ }
2584     myList=${myList:1} # Remove first character which is a space
2585
2586     # Filter any duplicates without sorting
2587     list="$myList "
2588     myList="${list%% *}"
2589
2590     while [[ "$list" != ${myList##* } ]]; do
2591         list=${list//${list%% *} /}
2592         myList="$myList ${list%% *}"
2593     done
2594     myList="${myList%* }";
2595
2596     # We can select an object at a offset in the list
2597     [ $# -eq 2 ] && {
2598         cnt=0
2599         for item in $myList; do
2600             let cnt=cnt+1
2601             [ $cnt -eq $offset ] && {
2602                 myList=$item
2603             }
2604         done
2605         [ $(get_node_count $myList) -ne 1 ] && myList=""
2606     }
2607     echo $myList
2608 }
2609
2610 facet_host() {
2611         local facet=$1
2612         local varname
2613
2614         [ "$facet" == client ] && echo -n $HOSTNAME && return
2615         varname=${facet}_HOST
2616         if [ -z "${!varname}" ]; then
2617                 if [ "${facet:0:3}" == "ost" ]; then
2618                         local fh=${facet%failover}_HOST
2619                         eval export ${facet}_HOST=${!fh}
2620                         if [ -z "${!varname}" ]; then
2621                                 eval export ${facet}_HOST=${ost_HOST}
2622                         fi
2623                 elif [ "${facet:0:3}" == "mdt" -o \
2624                         "${facet:0:3}" == "mds" -o \
2625                         "${facet:0:3}" == "mgs" ]; then
2626                         eval export ${facet}_HOST=${mds_HOST}
2627                 fi
2628         fi
2629         echo -n ${!varname}
2630 }
2631
2632 facet_failover_host() {
2633         local facet=$1
2634         local varname
2635
2636         var=${facet}failover_HOST
2637         if [ -n "${!var}" ]; then
2638                 echo ${!var}
2639                 return
2640         fi
2641
2642         if [ "${facet:0:3}" == "mdt" -o "${facet:0:3}" == "mds" -o \
2643              "${facet:0:3}" == "mgs" ]; then
2644
2645                 eval export ${facet}failover_host=${mds_HOST}
2646                 echo ${mds_HOST}
2647                 return
2648         fi
2649
2650         if [[ $facet == ost* ]]; then
2651                 eval export ${facet}failover_host=${ost_HOST}
2652                 echo ${ost_HOST}
2653                 return
2654         fi
2655 }
2656
2657 facet_active() {
2658     local facet=$1
2659     local activevar=${facet}active
2660
2661     if [ -f $TMP/${facet}active ] ; then
2662         source $TMP/${facet}active
2663     fi
2664
2665     active=${!activevar}
2666     if [ -z "$active" ] ; then
2667         echo -n ${facet}
2668     else
2669         echo -n ${active}
2670     fi
2671 }
2672
2673 facet_active_host() {
2674     local facet=$1
2675     local active=`facet_active $facet`
2676     if [ "$facet" == client ]; then
2677         echo $HOSTNAME
2678     else
2679         echo `facet_host $active`
2680     fi
2681 }
2682
2683 # Get the passive failover partner host of facet.
2684 facet_passive_host() {
2685         local facet=$1
2686         [[ $facet = client ]] && return
2687
2688         local host=${facet}_HOST
2689         local failover_host=${facet}failover_HOST
2690         local active_host=$(facet_active_host $facet)
2691
2692         [[ -z ${!failover_host} || ${!failover_host} = ${!host} ]] && return
2693
2694         if [[ $active_host = ${!host} ]]; then
2695                 echo -n ${!failover_host}
2696         else
2697                 echo -n ${!host}
2698         fi
2699 }
2700
2701 change_active() {
2702     local facetlist=$1
2703     local facet
2704
2705     facetlist=$(exclude_items_from_list $facetlist mgs)
2706
2707     for facet in ${facetlist//,/ }; do
2708     local failover=${facet}failover
2709     local host=`facet_host $failover`
2710     [ -z "$host" ] && return
2711
2712     local curactive=`facet_active $facet`
2713     if [ -z "${curactive}" -o "$curactive" == "$failover" ] ; then
2714         eval export ${facet}active=$facet
2715     else
2716         eval export ${facet}active=$failover
2717     fi
2718     # save the active host for this facet
2719     local activevar=${facet}active
2720     echo "$activevar=${!activevar}" > $TMP/$activevar
2721     [[ $facet = mds1 ]] && combined_mgs_mds && \
2722         echo "mgsactive=${!activevar}" > $TMP/mgsactive
2723     local TO=`facet_active_host $facet`
2724     echo "Failover $facet to $TO"
2725     done
2726 }
2727
2728 do_node() {
2729     local verbose=false
2730     # do not stripe off hostname if verbose, bug 19215
2731     if [ x$1 = x--verbose ]; then
2732         shift
2733         verbose=true
2734     fi
2735
2736     local HOST=$1
2737     shift
2738     local myPDSH=$PDSH
2739     if [ "$HOST" = "$HOSTNAME" ]; then
2740         myPDSH="no_dsh"
2741     elif [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" ]; then
2742         echo "cannot run remote command on $HOST with $myPDSH"
2743         return 128
2744     fi
2745     if $VERBOSE; then
2746         echo "CMD: $HOST $@" >&2
2747         $myPDSH $HOST "$LCTL mark \"$@\"" > /dev/null 2>&1 || :
2748     fi
2749
2750     if [ "$myPDSH" = "rsh" ]; then
2751 # we need this because rsh does not return exit code of an executed command
2752         local command_status="$TMP/cs"
2753         rsh $HOST ":> $command_status"
2754         rsh $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin;
2755                     cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\") ||
2756                     echo command failed >$command_status"
2757         [ -n "$($myPDSH $HOST cat $command_status)" ] && return 1 || true
2758         return 0
2759     fi
2760
2761     if $verbose ; then
2762         # print HOSTNAME for myPDSH="no_dsh"
2763         if [[ $myPDSH = no_dsh ]]; then
2764             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")" | sed -e "s/^/${HOSTNAME}: /"
2765         else
2766             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")"
2767         fi
2768     else
2769         $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")" | sed "s/^${HOST}: //"
2770     fi
2771     return ${PIPESTATUS[0]}
2772 }
2773
2774 do_nodev() {
2775     do_node --verbose "$@"
2776 }
2777
2778 single_local_node () {
2779    [ "$1" = "$HOSTNAME" ]
2780 }
2781
2782 # Outputs environment variable assignments that should be passed to remote nodes
2783 get_env_vars() {
2784         local var
2785         local value
2786         local facets=$(get_facets)
2787         local facet
2788
2789         for var in ${!MODOPTS_*}; do
2790                 value=${!var}
2791                 echo -n " ${var}=\"$value\""
2792         done
2793
2794         for facet in ${facets//,/ }; do
2795                 var=${facet}_FSTYPE
2796                 if [ -n "${!var}" ]; then
2797                         echo -n " $var=${!var}"
2798                 fi
2799         done
2800
2801         for var in MGSFSTYPE MDSFSTYPE OSTFSTYPE; do
2802                 if [ -n "${!var}" ]; then
2803                         echo -n " $var=${!var}"
2804                 fi
2805         done
2806
2807         if [ -n "$FSTYPE" ]; then
2808                 echo -n " FSTYPE=$FSTYPE"
2809         fi
2810 }
2811
2812 do_nodes() {
2813     local verbose=false
2814     # do not stripe off hostname if verbose, bug 19215
2815     if [ x$1 = x--verbose ]; then
2816         shift
2817         verbose=true
2818     fi
2819
2820     local rnodes=$1
2821     shift
2822
2823     if single_local_node $rnodes; then
2824         if $verbose; then
2825            do_nodev $rnodes "$@"
2826         else
2827            do_node $rnodes "$@"
2828         fi
2829         return $?
2830     fi
2831
2832     # This is part from do_node
2833     local myPDSH=$PDSH
2834
2835     [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" -o "$myPDSH" = "rsh" ] && \
2836         echo "cannot run remote command on $rnodes with $myPDSH" && return 128
2837
2838     export FANOUT=$(get_node_count "${rnodes//,/ }")
2839     if $VERBOSE; then
2840         echo "CMD: $rnodes $@" >&2
2841         $myPDSH $rnodes "$LCTL mark \"$@\"" > /dev/null 2>&1 || :
2842     fi
2843
2844     # do not replace anything from pdsh output if -N is used
2845     # -N     Disable hostname: prefix on lines of output.
2846     if $verbose || [[ $myPDSH = *-N* ]]; then
2847         $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" $(get_env_vars) sh -c \"$@\")"
2848     else
2849         $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" $(get_env_vars) sh -c \"$@\")" | sed -re "s/^[^:]*: //g"
2850     fi
2851     return ${PIPESTATUS[0]}
2852 }
2853
2854 do_facet() {
2855     local facet=$1
2856     shift
2857     local HOST=`facet_active_host $facet`
2858     [ -z $HOST ] && echo No host defined for facet ${facet} && exit 1
2859     do_node $HOST "$@"
2860 }
2861
2862 # Function: do_facet_random_file $FACET $FILE $SIZE
2863 # Creates FILE with random content on the given FACET of given SIZE
2864
2865 do_facet_random_file() {
2866         local facet="$1"
2867         local fpath="$2"
2868         local fsize="$3"
2869         local cmd="dd if=/dev/urandom of='$fpath' bs=$fsize count=1"
2870         do_facet $facet "$cmd 2>/dev/null"
2871 }
2872
2873 do_facet_create_file() {
2874         local facet="$1"
2875         local fpath="$2"
2876         local fsize="$3"
2877         local cmd="dd if=/dev/zero of='$fpath' bs=$fsize count=1"
2878         do_facet $facet "$cmd 2>/dev/null"
2879 }
2880
2881 do_nodesv() {
2882     do_nodes --verbose "$@"
2883 }
2884
2885 add() {
2886         local facet=$1
2887         shift
2888         # make sure its not already running
2889         stop ${facet} -f
2890         rm -f $TMP/${facet}active
2891         [[ $facet = mds1 ]] && combined_mgs_mds && rm -f $TMP/mgsactive
2892         do_facet ${facet} $MKFS $* || return ${PIPESTATUS[0]}
2893
2894         if [[ $(facet_fstype $facet) == zfs ]]; then
2895                 #
2896                 # After formatting a ZFS target, "cachefile=none" property will
2897                 # be set on the ZFS storage pool so that the pool is not
2898                 # automatically imported on system startup. And then the pool
2899                 # will be exported so as to leave the importing and exporting
2900                 # operations handled by mount_facet() and stop() separately.
2901                 #
2902                 refresh_partition_table $facet $(facet_vdevice $facet)
2903                 disable_zpool_cache $facet
2904                 export_zpool $facet
2905         fi
2906 }
2907
2908 # Device formatted as ost
2909 ostdevname() {
2910         local num=$1
2911         local DEVNAME=OSTDEV$num
2912
2913         local fstype=$(facet_fstype ost$num)
2914
2915         case $fstype in
2916                 ldiskfs )
2917                         #if $OSTDEVn isn't defined, default is $OSTDEVBASE + num
2918                         eval DEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}};;
2919                 zfs )
2920                         #try $OSTZFSDEVn - independent of vdev
2921                         DEVNAME=OSTZFSDEV$num
2922                         eval DEVPTR=${!DEVNAME:=${FSNAME}-ost${num}/ost${num}};;
2923                 * )
2924                         error "unknown fstype!";;
2925         esac
2926
2927     echo -n $DEVPTR
2928 }
2929
2930 # Physical device location of data
2931 ostvdevname() {
2932         local num=$1
2933         local DEVNAME
2934         local VDEVPTR
2935
2936         local fstype=$(facet_fstype ost$num)
2937
2938         case $fstype in
2939                 ldiskfs )
2940                         # vdevs are not supported by ldiskfs
2941                         eval VDEVPTR="";;
2942                 zfs )
2943                         #if $OSTDEVn isn't defined, default is $OSTDEVBASE{n}
2944                         # Device formated by zfs
2945                         DEVNAME=OSTDEV$num
2946                         eval VDEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}};;
2947                 * )
2948                         error "unknown fstype!";;
2949         esac
2950
2951         echo -n $VDEVPTR
2952 }
2953
2954 # Logical device formated for lustre
2955 mdsdevname() {
2956         local num=$1
2957         local DEVNAME=MDSDEV$num
2958
2959         local fstype=$(facet_fstype mds$num)
2960
2961         case $fstype in
2962                 ldiskfs )
2963                         #if $MDSDEVn isn't defined, default is $MDSDEVBASE{n}
2964                         eval DEVPTR=${!DEVNAME:=${MDSDEVBASE}${num}};;
2965                 zfs )
2966                         # try $MDSZFSDEVn - independent of vdev
2967                         DEVNAME=MDSZFSDEV$num
2968                         eval DEVPTR=${!DEVNAME:=${FSNAME}-mdt${num}/mdt${num}};;
2969                 * )
2970                         error "unknown fstype!";;
2971         esac
2972
2973         echo -n $DEVPTR
2974 }
2975
2976 # Physical location of data
2977 mdsvdevname() {
2978         local VDEVPTR=""
2979         local num=$1
2980         local fstype=$(facet_fstype mds$num)
2981
2982         case $fstype in
2983                 ldiskfs )
2984                         # vdevs are not supported by ldiskfs
2985                         eval VDEVPTR="";;
2986                 zfs )
2987                         # if $MDSDEVn isn't defined, default is $MDSDEVBASE{n}
2988                         # Device formated by ZFS
2989                         local DEVNAME=MDSDEV$num
2990                         eval VDEVPTR=${!DEVNAME:=${MDSDEVBASE}${num}};;
2991                 * )
2992                         error "unknown fstype!";;
2993         esac
2994
2995         echo -n $VDEVPTR
2996 }
2997
2998 mgsdevname() {
2999         local DEVPTR
3000         local fstype=$(facet_fstype mgs)
3001
3002         case $fstype in
3003         ldiskfs )
3004                 if [ $(facet_host mgs) = $(facet_host mds1) ] &&
3005                    ( [ -z "$MGSDEV" ] || [ $MGSDEV = $(mdsdevname 1) ] ); then
3006                         DEVPTR=$(mdsdevname 1)
3007                 else
3008                         DEVPTR=$MGSDEV
3009                 fi;;
3010         zfs )
3011                 if [ $(facet_host mgs) = $(facet_host mds1) ] &&
3012                     ( [ -z "$MGSZFSDEV" ] &&
3013                         [ -z "$MGSDEV" -o "$MGSDEV" = $(mdsvdevname 1) ] ); then
3014                         DEVPTR=$(mdsdevname 1)
3015                 else
3016                         DEVPTR=${MGSZFSDEV:-${FSNAME}-mgs/mgs}
3017                 fi;;
3018         * )
3019                 error "unknown fstype!";;
3020         esac
3021
3022         echo -n $DEVPTR
3023 }
3024
3025 mgsvdevname() {
3026         local VDEVPTR=""
3027
3028         local fstype=$(facet_fstype mgs)
3029
3030         case $fstype in
3031         ldiskfs )
3032                 # vdevs are not supported by ldiskfs
3033                 ;;
3034         zfs )
3035                 if [ $(facet_host mgs) = $(facet_host mds1) ] &&
3036                    ( [ -z "$MGSDEV" ] &&
3037                        [ -z "$MGSZFSDEV" -o "$MGSZFSDEV" = $(mdsdevname 1) ]); then
3038                         VDEVPTR=$(mdsvdevname 1)
3039                 elif [ -n "$MGSDEV" ]; then
3040                         VDEVPTR=$MGSDEV
3041                 fi;;
3042         * )
3043                 error "unknown fstype!";;
3044         esac
3045
3046         echo -n $VDEVPTR
3047 }
3048
3049 facet_mntpt () {
3050     local facet=$1
3051     [[ $facet = mgs ]] && combined_mgs_mds && facet="mds1"
3052
3053     local var=${facet}_MOUNT
3054     eval mntpt=${!var:-${MOUNT%/*}/$facet}
3055
3056     echo -n $mntpt
3057 }
3058
3059 mount_ldiskfs() {
3060         local facet=$1
3061         local dev=$(facet_device $facet)
3062         local mnt=$(facet_mntpt $facet)
3063         local opts
3064
3065         if ! do_facet $facet test -b $dev; then
3066                 opts="-o loop"
3067         fi
3068         do_facet $facet mount -t ldiskfs $opts $dev $mnt
3069 }
3070
3071 unmount_ldiskfs() {
3072         local facet=$1
3073         local dev=$(facet_device $facet)
3074         local mnt=$(facet_mntpt $facet)
3075
3076         do_facet $facet umount -d $mnt
3077 }
3078
3079 var_name() {
3080         echo -n "$1" | tr -c '[:alnum:]\n' '_'
3081 }
3082
3083 mount_zfs() {
3084         local facet=$1
3085         local ds=$(facet_device $facet)
3086         local mnt=$(facet_mntpt $facet)
3087         local canmnt
3088         local mntpt
3089
3090         import_zpool $facet
3091         canmnt=$(do_facet $facet $ZFS get -H -o value canmount $ds)
3092         mntpt=$(do_facet $facet $ZFS get -H -o value mountpoint $ds)
3093         do_facet $facet $ZFS set canmount=noauto $ds
3094         #
3095         # The "legacy" mount method is used here because "zfs unmount $mnt"
3096         # calls stat(2) on $mnt/../*, which may include $MOUNT.  If certain
3097         # targets are not available at the time, the stat(2) on $MOUNT will
3098         # hang.
3099         #
3100         do_facet $facet $ZFS set mountpoint=legacy $ds
3101         do_facet $facet mount -t zfs $ds $mnt
3102         eval export mz_$(var_name ${facet}_$ds)_canmount=$canmnt
3103         eval export mz_$(var_name ${facet}_$ds)_mountpoint=$mntpt
3104 }
3105
3106 unmount_zfs() {
3107         local facet=$1
3108         local ds=$(facet_device $facet)
3109         local mnt=$(facet_mntpt $facet)
3110         local var_mntpt=mz_$(var_name ${facet}_$ds)_mountpoint
3111         local var_canmnt=mz_$(var_name ${facet}_$ds)_canmount
3112         local mntpt=${!var_mntpt}
3113         local canmnt=${!var_canmnt}
3114
3115         unset $var_mntpt
3116         unset $var_canmnt
3117         do_facet $facet umount $mnt
3118         do_facet $facet $ZFS set mountpoint=$mntpt $ds
3119         do_facet $facet $ZFS set canmount=$canmnt $ds
3120         export_zpool $facet
3121 }
3122
3123 mount_fstype() {
3124         local facet=$1
3125         local fstype=$(facet_fstype $facet)
3126
3127         mount_$fstype $facet
3128 }
3129
3130 unmount_fstype() {
3131         local facet=$1
3132         local fstype=$(facet_fstype $facet)
3133
3134         unmount_$fstype $facet
3135 }
3136
3137 ########
3138 ## MountConf setup
3139
3140 stopall() {
3141     # make sure we are using the primary server, so test-framework will
3142     # be able to clean up properly.
3143     activemds=`facet_active mds1`
3144     if [ $activemds != "mds1" ]; then
3145         fail mds1
3146     fi
3147
3148     local clients=$CLIENTS
3149     [ -z $clients ] && clients=$(hostname)
3150
3151     zconf_umount_clients $clients $MOUNT "$*" || true
3152     [ -n "$MOUNT2" ] && zconf_umount_clients $clients $MOUNT2 "$*" || true
3153
3154     [ "$CLIENTONLY" ] && return
3155     # The add fn does rm ${facet}active file, this would be enough
3156     # if we use do_facet <facet> only after the facet added, but
3157     # currently we use do_facet mds in local.sh
3158     for num in `seq $MDSCOUNT`; do
3159         stop mds$num -f
3160         rm -f ${TMP}/mds${num}active
3161     done
3162     combined_mgs_mds && rm -f $TMP/mgsactive
3163
3164     for num in `seq $OSTCOUNT`; do
3165         stop ost$num -f
3166         rm -f $TMP/ost${num}active
3167     done
3168
3169     if ! combined_mgs_mds ; then
3170         stop mgs
3171     fi
3172
3173     return 0
3174 }
3175
3176 cleanup_echo_devs () {
3177     local devs=$($LCTL dl | grep echo | awk '{print $4}')
3178
3179     for dev in $devs; do
3180         $LCTL --device $dev cleanup
3181         $LCTL --device $dev detach
3182     done
3183 }
3184
3185 cleanupall() {
3186     nfs_client_mode && return
3187
3188     stopall $*
3189     cleanup_echo_devs
3190
3191     unload_modules
3192     cleanup_gss
3193 }
3194
3195 combined_mgs_mds () {
3196         [[ "$(mdsdevname 1)" = "$(mgsdevname)" ]] &&
3197                 [[ "$(facet_host mds1)" = "$(facet_host mgs)" ]]
3198 }
3199
3200 lower() {
3201         echo -n "$1" | tr '[:upper:]' '[:lower:]'
3202 }
3203
3204 upper() {
3205         echo -n "$1" | tr '[:lower:]' '[:upper:]'
3206 }
3207
3208 mkfs_opts() {
3209         local facet=$1
3210         local dev=$2
3211         local fsname=${3:-"$FSNAME"}
3212         local type=$(facet_type $facet)
3213         local index=$(($(facet_number $facet) - 1))
3214         local fstype=$(facet_fstype $facet)
3215         local host=$(facet_host $facet)
3216         local opts
3217         local fs_mkfs_opts
3218         local var
3219
3220         if [ $type == MGS ] && combined_mgs_mds; then
3221                 return 1
3222         fi
3223
3224         if [ $type == MGS ] || ( [ $type == MDS ] &&
3225                                  [ "$dev" == $(mgsdevname) ] &&
3226                                  [ "$host" == "$(facet_host mgs)" ] ); then
3227                 opts="--mgs"
3228         else
3229                 opts="--mgsnode=$MGSNID"
3230         fi
3231
3232         if [ $type != MGS ]; then
3233                 opts+=" --fsname=$fsname --$(lower ${type/MDS/MDT}) \
3234                         --index=$index"
3235         fi
3236
3237         var=${facet}failover_HOST
3238         if [ -n "${!var}" ] && [ ${!var} != $(facet_host $facet) ]; then
3239                 opts+=" --failnode=$(h2$NETTYPE ${!var})"
3240         fi
3241
3242         opts+=${TIMEOUT:+" --param=sys.timeout=$TIMEOUT"}
3243         opts+=${LDLM_TIMEOUT:+" --param=sys.ldlm_timeout=$LDLM_TIMEOUT"}
3244
3245         if [ $type == MDS ]; then
3246                 opts+=${SECLEVEL:+" --param=mdt.sec_level"}
3247                 opts+=${MDSCAPA:+" --param-mdt.capa=$MDSCAPA"}
3248                 opts+=${STRIPE_BYTES:+" --param=lov.stripesize=$STRIPE_BYTES"}
3249                 opts+=${STRIPES_PER_OBJ:+" --param=lov.stripecount=$STRIPES_PER_OBJ"}
3250                 opts+=${L_GETIDENTITY:+" --param=mdt.identity_upcall=$L_GETIDENTITY"}
3251
3252                 if [ $fstype == ldiskfs ]; then
3253                         # Check for wide striping
3254                         if [ $OSTCOUNT -gt 160 ]; then
3255                                 MDSJOURNALSIZE=${MDSJOURNALSIZE:-4096}
3256                                 fs_mkfs_opts+="-O large_xattr"
3257                         fi
3258
3259                         fs_mkfs_opts+=${MDSJOURNALSIZE:+" -J size=$MDSJOURNALSIZE"}
3260                         if [ ! -z $EJOURNAL ]; then
3261                                 fs_mkfs_opts+=${MDSJOURNALSIZE:+" device=$EJOURNAL"}
3262                         fi
3263                         fs_mkfs_opts+=${MDSISIZE:+" -i $MDSISIZE"}
3264                 fi
3265         fi
3266
3267         if [ $type == OST ]; then
3268                 opts+=${SECLEVEL:+" --param=ost.sec_level"}
3269                 opts+=${OSSCAPA:+" --param=ost.capa=$OSSCAPA"}
3270
3271                 if [ $fstype == ldiskfs ]; then
3272                         fs_mkfs_opts+=${OSTJOURNALSIZE:+" -J size=$OSTJOURNALSIZE"}
3273                 fi
3274         fi
3275
3276         opts+=" --backfstype=$fstype"
3277
3278         var=${type}SIZE
3279         if [ -n "${!var}" ]; then
3280                 opts+=" --device-size=${!var}"
3281         fi
3282
3283         var=$(upper $fstype)_MKFS_OPTS
3284         fs_mkfs_opts+=${!var:+" ${!var}"}
3285
3286         var=${type}_FS_MKFS_OPTS
3287         fs_mkfs_opts+=${!var:+" ${!var}"}
3288
3289         if [ -n "${fs_mkfs_opts## }" ]; then
3290                 opts+=" --mkfsoptions=\\\"${fs_mkfs_opts## }\\\""
3291         fi
3292
3293         var=${type}OPT
3294         opts+=${!var:+" ${!var}"}
3295
3296         echo -n "$opts"
3297 }
3298
3299 formatall() {
3300         local quiet
3301
3302         if ! $VERBOSE; then
3303                 quiet=yes
3304         fi
3305
3306         stopall
3307         # We need ldiskfs here, may as well load them all
3308         load_modules
3309         [ "$CLIENTONLY" ] && return
3310         echo Formatting mgs, mds, osts
3311         if ! combined_mgs_mds ; then
3312                 echo "Format mgs: $(mgsdevname)"
3313                 add mgs $(mkfs_opts mgs $(mgsdevname)) --reformat \
3314                         $(mgsdevname) $(mgsvdevname) ${quiet:+>/dev/null} ||
3315                         exit 10
3316         fi
3317
3318         for num in $(seq $MDSCOUNT); do
3319                 echo "Format mds$num: $(mdsdevname $num)"
3320                 add mds$num $(mkfs_opts mds$num $(mdsdevname ${num})) \
3321                         --reformat $(mdsdevname $num) $(mdsvdevname $num) \
3322                         ${quiet:+>/dev/null} || exit 10
3323         done
3324
3325         for num in $(seq $OSTCOUNT); do
3326                 echo "Format ost$num: $(ostdevname $num)"
3327                 add ost$num $(mkfs_opts ost$num $(ostdevname ${num})) \
3328                         --reformat $(ostdevname $num) $(ostvdevname ${num}) \
3329                         ${quiet:+>/dev/null} || exit 10
3330         done
3331 }
3332
3333 mount_client() {
3334     grep " $1 " /proc/mounts || zconf_mount $HOSTNAME $*
3335 }
3336
3337 umount_client() {
3338     grep " $1 " /proc/mounts && zconf_umount `hostname` $*
3339 }
3340
3341 # return value:
3342 # 0: success, the old identity set already.
3343 # 1: success, the old identity does not set.
3344 # 2: fail.
3345 switch_identity() {
3346     local num=$1
3347     local switch=$2
3348     local j=`expr $num - 1`
3349     local MDT="`(do_facet mds$num lctl get_param -N mdt.*MDT*$j 2>/dev/null | cut -d"." -f2 2>/dev/null) || true`"
3350
3351     if [ -z "$MDT" ]; then
3352         return 2
3353     fi
3354
3355     local old="`do_facet mds$num "lctl get_param -n mdt.$MDT.identity_upcall"`"
3356
3357     if $switch; then
3358         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"$L_GETIDENTITY\""
3359     else
3360         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"NONE\""
3361     fi
3362
3363     do_facet mds$num "lctl set_param -n mdt/$MDT/identity_flush=-1"
3364
3365     if [ $old = "NONE" ]; then
3366         return 1
3367     else
3368         return 0
3369     fi
3370 }
3371
3372 remount_client()
3373 {
3374         zconf_umount `hostname` $1 || error "umount failed"
3375         zconf_mount `hostname` $1 || error "mount failed"
3376 }
3377
3378 writeconf_facet() {
3379         local facet=$1
3380         local dev=$2
3381
3382         stop ${facet} -f
3383         rm -f $TMP/${facet}active
3384         do_facet ${facet} "$TUNEFS --quiet --writeconf $dev" || return 1
3385         return 0
3386 }
3387
3388 writeconf_all () {
3389         local mdt_count=${1:-$MDSCOUNT}
3390         local ost_count=${2:-$OSTCOUNT}
3391         local rc=0
3392
3393         for num in $(seq $mdt_count); do
3394                 DEVNAME=$(mdsdevname $num)
3395                 writeconf_facet mds$num $DEVNAME || rc=$?
3396         done
3397
3398         for num in $(seq $ost_count); do
3399                 DEVNAME=$(ostdevname $num)
3400                 writeconf_facet ost$num $DEVNAME || rc=$?
3401         done
3402         return $rc
3403 }
3404
3405 setupall() {
3406     nfs_client_mode && return
3407
3408     sanity_mount_check ||
3409         error "environments are insane!"
3410
3411     load_modules
3412
3413     if [ -z "$CLIENTONLY" ]; then
3414         echo Setup mgs, mdt, osts
3415         echo $WRITECONF | grep -q "writeconf" && \
3416             writeconf_all
3417         if ! combined_mgs_mds ; then
3418                         start mgs $(mgsdevname) $MGS_MOUNT_OPTS
3419         fi
3420
3421         for num in `seq $MDSCOUNT`; do
3422             DEVNAME=$(mdsdevname $num)
3423             start mds$num $DEVNAME $MDS_MOUNT_OPTS
3424
3425             # We started mds, now we should set failover variables properly.
3426             # Set mds${num}failover_HOST if it is not set (the default failnode).
3427             local varname=mds${num}failover_HOST
3428             if [ -z "${!varname}" ]; then
3429                 eval mds${num}failover_HOST=$(facet_host mds$num)
3430             fi
3431
3432             if [ $IDENTITY_UPCALL != "default" ]; then
3433                 switch_identity $num $IDENTITY_UPCALL
3434             fi
3435         done
3436         for num in `seq $OSTCOUNT`; do
3437             DEVNAME=$(ostdevname $num)
3438             start ost$num $DEVNAME $OST_MOUNT_OPTS
3439
3440             # We started ost$num, now we should set ost${num}failover variable properly.
3441             # Set ost${num}failover_HOST if it is not set (the default failnode).
3442             varname=ost${num}failover_HOST
3443             if [ -z "${!varname}" ]; then
3444                 eval ost${num}failover_HOST=$(facet_host ost${num})
3445             fi
3446
3447         done
3448     fi
3449
3450     init_gss
3451
3452     # wait a while to allow sptlrpc configuration be propogated to targets,
3453     # only needed when mounting new target devices.
3454     if $GSS; then
3455         sleep 10
3456     fi
3457
3458     [ "$DAEMONFILE" ] && $LCTL debug_daemon start $DAEMONFILE $DAEMONSIZE
3459     mount_client $MOUNT
3460     [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT
3461     clients_up
3462
3463     if [ "$MOUNT_2" ]; then
3464         mount_client $MOUNT2
3465         [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT2
3466     fi
3467
3468     init_param_vars
3469
3470     # by remounting mdt before ost, initial connect from mdt to ost might
3471     # timeout because ost is not ready yet. wait some time to its fully
3472     # recovery. initial obd_connect timeout is 5s; in GSS case it's preceeded
3473     # by a context negotiation rpc with $TIMEOUT.
3474     # FIXME better by monitoring import status.
3475     if $GSS; then
3476         set_flavor_all $SEC
3477         sleep $((TIMEOUT + 5))
3478     else
3479         sleep 5
3480     fi
3481 }
3482
3483 mounted_lustre_filesystems() {
3484         awk '($3 ~ "lustre" && $1 ~ ":") { print $2 }' /proc/mounts
3485 }
3486
3487 init_facet_vars () {
3488         [ "$CLIENTONLY" ] && return 0
3489         local facet=$1
3490         shift
3491         local device=$1
3492
3493         shift
3494
3495         eval export ${facet}_dev=${device}
3496         eval export ${facet}_opt=\"$@\"
3497
3498         local dev=${facet}_dev
3499
3500         # We need to loop for the label
3501         # in case its not initialized yet.
3502         for wait_time in {0,1,3,5,10}; do
3503
3504                 if [ $wait_time -gt 0 ]; then
3505                         echo "${!dev} not yet initialized,"\
3506                                 "waiting ${wait_time} seconds."
3507                         sleep $wait_time
3508                 fi
3509
3510                 local label=$(devicelabel ${facet} ${!dev})
3511
3512                 # Check to make sure the label does
3513                 # not include ffff at the end of the label.
3514                 # This indicates it has not been initialized yet.
3515
3516                 if [[ $label =~ [f|F]{4}$ ]]; then
3517                         # label is not initialized, unset the result
3518                         # and either try again or fail
3519                         unset label
3520                 else
3521                         break
3522                 fi
3523         done
3524
3525         [ -z "$label" ] && echo no label for ${!dev} && exit 1
3526
3527         eval export ${facet}_svc=${label}
3528
3529         local varname=${facet}failover_HOST
3530         if [ -z "${!varname}" ]; then
3531                 eval export $varname=$(facet_host $facet)
3532         fi
3533
3534         varname=${facet}_HOST
3535         if [ -z "${!varname}" ]; then
3536                 eval export $varname=$(facet_host $facet)
3537         fi
3538
3539         # ${facet}failover_dev is set in cfg file
3540         varname=${facet}failover_dev
3541         if [ -n "${!varname}" ] ; then
3542                 eval export ${facet}failover_dev=${!varname}
3543         else
3544                 eval export ${facet}failover_dev=$device
3545         fi
3546
3547         # get mount point of already mounted device
3548         # is facet_dev is already mounted then use the real
3549         #  mount point of this facet; otherwise use $(facet_mntpt $facet)
3550         # i.e. ${facet}_MOUNT if specified by user or default
3551         local mntpt=$(do_facet ${facet} cat /proc/mounts | \
3552                         awk '"'${!dev}'" == $1 && $3 == "lustre" { print $2 }')
3553         if [ -z $mntpt ]; then
3554                 mntpt=$(facet_mntpt $facet)
3555         fi
3556         eval export ${facet}_MOUNT=$mntpt
3557 }
3558
3559 init_facets_vars () {
3560         local DEVNAME
3561
3562         if ! remote_mds_nodsh; then
3563                 for num in $(seq $MDSCOUNT); do
3564                         DEVNAME=`mdsdevname $num`
3565                         init_facet_vars mds$num $DEVNAME $MDS_MOUNT_OPTS
3566                 done
3567         fi
3568
3569         combined_mgs_mds || init_facet_vars mgs $(mgsdevname) $MGS_MOUNT_OPTS
3570
3571         if ! remote_ost_nodsh; then
3572                 for num in $(seq $OSTCOUNT); do
3573                         DEVNAME=$(ostdevname $num)
3574                         init_facet_vars ost$num $DEVNAME $OST_MOUNT_OPTS
3575                 done
3576         fi
3577 }
3578
3579 osc_ensure_active () {
3580     local facet=$1
3581     local timeout=$2
3582     local period=0
3583
3584     while [ $period -lt $timeout ]; do
3585         count=$(do_facet $facet "lctl dl | grep ' IN osc ' 2>/dev/null | wc -l")
3586         if [ $count -eq 0 ]; then
3587             break
3588         fi
3589
3590         echo "There are $count OST are inactive, wait $period seconds, and try again"
3591         sleep 3
3592         period=$((period+3))
3593     done
3594
3595     [ $period -lt $timeout ] || log "$count OST are inactive after $timeout seconds, give up"
3596 }
3597
3598 set_conf_param_and_check() {
3599         local myfacet=$1
3600         local TEST=$2
3601         local PARAM=$3
3602         local ORIG=$(do_facet $myfacet "$TEST")
3603         if [ $# -gt 3 ]; then
3604                 local FINAL=$4
3605         else
3606                 local -i FINAL
3607                 FINAL=$((ORIG + 5))
3608         fi
3609         echo "Setting $PARAM from $ORIG to $FINAL"
3610         do_facet mgs "$LCTL conf_param $PARAM='$FINAL'" ||
3611                 error "conf_param $PARAM failed"
3612
3613         wait_update $(facet_host $myfacet) "$TEST" "$FINAL" ||
3614                 error "check $PARAM failed!"
3615 }
3616
3617 init_param_vars () {
3618         remote_mds_nodsh ||
3619                 TIMEOUT=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
3620
3621         log "Using TIMEOUT=$TIMEOUT"
3622
3623         osc_ensure_active $SINGLEMDS $TIMEOUT
3624         osc_ensure_active client $TIMEOUT
3625
3626         if [ -n "$(lctl get_param -n mdc.*.connect_flags|grep jobstats)" ]; then
3627                 local current_jobid_var=$($LCTL get_param -n jobid_var)
3628
3629                 if [ $JOBID_VAR = "existing" ]; then
3630                         echo "keeping jobstats as $current_jobid_var"
3631                 elif [ $current_jobid_var != $JOBID_VAR ]; then
3632                         echo "seting jobstats to $JOBID_VAR"
3633
3634                         set_conf_param_and_check client                 \
3635                                 "$LCTL get_param -n jobid_var"          \
3636                                 "$FSNAME.sys.jobid_var" $JOBID_VAR
3637                 fi
3638         else
3639                 echo "jobstats not supported by server"
3640         fi
3641
3642         if [ $QUOTA_AUTO -ne 0 ]; then
3643                 if [ "$ENABLE_QUOTA" ]; then
3644                         echo "enable quota as required"
3645                         setup_quota $MOUNT || return 2
3646                 else
3647                         echo "disable quota as required"
3648                         # $LFS quotaoff -ug $MOUNT > /dev/null 2>&1
3649                 fi
3650         fi
3651         return 0
3652 }
3653
3654 nfs_client_mode () {
3655     if [ "$NFSCLIENT" ]; then
3656         echo "NFSCLIENT mode: setup, cleanup, check config skipped"
3657         local clients=$CLIENTS
3658         [ -z $clients ] && clients=$(hostname)
3659
3660         # FIXME: remove hostname when 19215 fixed
3661         do_nodes $clients "echo \\\$(hostname); grep ' '$MOUNT' ' /proc/mounts"
3662         declare -a nfsexport=(`grep ' '$MOUNT' ' /proc/mounts | awk '{print $1}' | awk -F: '{print $1 " "  $2}'`)
3663         if [[ ${#nfsexport[@]} -eq 0 ]]; then
3664                 error_exit NFSCLIENT=$NFSCLIENT mode, but no NFS export found!
3665         fi
3666         do_nodes ${nfsexport[0]} "echo \\\$(hostname); df -T  ${nfsexport[1]}"
3667         return
3668     fi
3669     return 1
3670 }
3671
3672 check_config_client () {
3673     local mntpt=$1
3674
3675     local mounted=$(mount | grep " $mntpt ")
3676     if [ "$CLIENTONLY" ]; then
3677         # bug 18021
3678         # CLIENTONLY should not depend on *_HOST settings
3679         local mgc=$($LCTL device_list | awk '/MGC/ {print $4}')
3680         # in theory someone could create a new,
3681         # client-only config file that assumed lustre was already
3682         # configured and didn't set the MGSNID. If MGSNID is not set,
3683         # then we should use the mgs nid currently being used 
3684         # as the default value. bug 18021
3685         [[ x$MGSNID = x ]] &&
3686             MGSNID=${mgc//MGC/}
3687
3688         if [[ x$mgc != xMGC$MGSNID ]]; then
3689             if [ "$mgs_HOST" ]; then
3690                 local mgc_ip=$(ping -q -c1 -w1 $mgs_HOST | grep PING | awk '{print $3}' | sed -e "s/(//g" -e "s/)//g")
3691 #                [[ x$mgc = xMGC$mgc_ip@$NETTYPE ]] ||
3692 #                    error_exit "MGSNID=$MGSNID, mounted: $mounted, MGC : $mgc"
3693             fi
3694         fi
3695         return 0
3696     fi
3697
3698     local myMGS_host=$mgs_HOST   
3699     if [ "$NETTYPE" = "ptl" ]; then
3700         myMGS_host=$(h2ptl $mgs_HOST | sed -e s/@ptl//) 
3701     fi
3702
3703     echo Checking config lustre mounted on $mntpt
3704     local mgshost=$(mount | grep " $mntpt " | awk -F@ '{print $1}')
3705     mgshost=$(echo $mgshost | awk -F: '{print $1}')
3706
3707 #    if [ "$mgshost" != "$myMGS_host" ]; then
3708 #            log "Bad config file: lustre is mounted with mgs $mgshost, but mgs_HOST=$mgs_HOST, NETTYPE=$NETTYPE
3709 #                   Please use correct config or set mds_HOST correctly!"
3710 #    fi
3711
3712 }
3713
3714 check_config_clients () {
3715         local clients=${CLIENTS:-$HOSTNAME}
3716         local mntpt=$1
3717
3718         nfs_client_mode && return
3719
3720         do_rpc_nodes "$clients" check_config_client $mntpt
3721
3722         sanity_mount_check || error "environments are insane!"
3723 }
3724
3725 check_timeout () {
3726     local mdstimeout=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
3727     local cltimeout=$(lctl get_param -n timeout)
3728     if [ $mdstimeout -ne $TIMEOUT ] || [ $mdstimeout -ne $cltimeout ]; then
3729         error "timeouts are wrong! mds: $mdstimeout, client: $cltimeout, TIMEOUT=$TIMEOUT"
3730         return 1
3731     fi
3732 }
3733
3734 is_mounted () {
3735     local mntpt=$1
3736     [ -z $mntpt ] && return 1
3737     local mounted=$(mounted_lustre_filesystems)
3738
3739     echo $mounted' ' | grep -w -q $mntpt' '
3740 }
3741
3742 is_empty_dir() {
3743         [ $(find $1 -maxdepth 1 -print | wc -l) = 1 ] && return 0
3744         return 1
3745 }
3746
3747 # empty lustre filesystem may have empty directories lost+found and .lustre
3748 is_empty_fs() {
3749         # exclude .lustre & lost+found
3750         [ $(find $1 -maxdepth 1 -name lost+found -o -name .lustre -prune -o \
3751                 -print | wc -l) = 1 ] || return 1
3752         [ ! -d $1/lost+found ] || is_empty_dir $1/lost+found || return 1
3753         if [ $(lustre_version_code $SINGLEMDS) -gt $(version_code 2.4.0) ]; then
3754                 # exclude .lustre/fid (LU-2780)
3755                 [ $(find $1/.lustre -maxdepth 1 -name fid -prune -o \
3756                         -print | wc -l) = 1 ] || return 1
3757         else
3758                 [ ! -d $1/.lustre ] || is_empty_dir $1/.lustre || return 1
3759         fi
3760         return 0
3761 }
3762
3763 check_and_setup_lustre() {
3764     nfs_client_mode && return
3765
3766     local MOUNTED=$(mounted_lustre_filesystems)
3767
3768     local do_check=true
3769     # 1.
3770     # both MOUNT and MOUNT2 are not mounted
3771     if ! is_mounted $MOUNT && ! is_mounted $MOUNT2; then
3772         [ "$REFORMAT" ] && formatall
3773         # setupall mounts both MOUNT and MOUNT2 (if MOUNT_2 is set)
3774         setupall
3775         is_mounted $MOUNT || error "NAME=$NAME not mounted"
3776         export I_MOUNTED=yes
3777         do_check=false
3778     # 2.
3779     # MOUNT2 is mounted
3780     elif is_mounted $MOUNT2; then
3781             # 3.
3782             # MOUNT2 is mounted, while MOUNT_2 is not set
3783             if ! [ "$MOUNT_2" ]; then
3784                 cleanup_mount $MOUNT2
3785                 export I_UMOUNTED2=yes
3786
3787             # 4.
3788             # MOUNT2 is mounted, MOUNT_2 is set
3789             else
3790                 # FIXME: what to do if check_config failed?
3791                 # i.e. if:
3792                 # 1) remote client has mounted other Lustre fs ?
3793                 # 2) it has insane env ?
3794                 # let's try umount MOUNT2 on all clients and mount it again:
3795                 if ! check_config_clients $MOUNT2; then
3796                     cleanup_mount $MOUNT2
3797                     restore_mount $MOUNT2
3798                     export I_MOUNTED2=yes
3799                 fi
3800             fi 
3801
3802     # 5.
3803     # MOUNT is mounted MOUNT2 is not mounted
3804     elif [ "$MOUNT_2" ]; then
3805         restore_mount $MOUNT2
3806         export I_MOUNTED2=yes
3807     fi
3808
3809     if $do_check; then
3810         # FIXME: what to do if check_config failed?
3811         # i.e. if:
3812         # 1) remote client has mounted other Lustre fs?
3813         # 2) lustre is mounted on remote_clients atall ?
3814         check_config_clients $MOUNT
3815         init_facets_vars
3816         init_param_vars
3817
3818         set_default_debug_nodes $(comma_list $(nodes_list))
3819     fi
3820
3821         if [ $(lower $OSD_TRACK_DECLARES_LBUG) == 'yes' ] ; then
3822                 local facets=""
3823                 [ "$(facet_fstype ost1)" = "ldiskfs" ] &&
3824                         facets="$(get_facets OST)"
3825                 [ "$(facet_fstype mds1)" = "ldiskfs" ] &&
3826                         facets="$facets,$(get_facets MDS)"
3827                 [ "$(facet_fstype mgs)" = "ldiskfs" ] &&
3828                         facets="$facets,mgs"
3829                 local nodes="$(facets_hosts ${facets})"
3830                 if [ -n "$nodes" ] ; then
3831                         do_nodes $nodes "$LCTL set_param \
3832                                  osd-ldiskfs.track_declares_assert=1 || true"
3833                 fi
3834         fi
3835
3836         init_gss
3837         if $GSS; then
3838                 set_flavor_all $SEC
3839         fi
3840
3841         if [ "$ONLY" == "setup" ]; then
3842                 exit 0
3843         fi
3844 }
3845
3846 restore_mount () {
3847    local clients=${CLIENTS:-$HOSTNAME}
3848    local mntpt=$1
3849
3850    zconf_mount_clients $clients $mntpt
3851 }
3852
3853 cleanup_mount () {
3854         local clients=${CLIENTS:-$HOSTNAME}
3855         local mntpt=$1
3856
3857         zconf_umount_clients $clients $mntpt
3858 }
3859
3860 cleanup_and_setup_lustre() {
3861     if [ "$ONLY" == "cleanup" -o "`mount | grep $MOUNT`" ]; then
3862         lctl set_param debug=0 || true
3863         cleanupall
3864         if [ "$ONLY" == "cleanup" ]; then
3865             exit 0
3866         fi
3867     fi
3868     check_and_setup_lustre
3869 }
3870
3871 # Get all of the server target devices from a given server node and type.
3872 get_mnt_devs() {
3873         local node=$1
3874         local type=$2
3875         local devs
3876         local dev
3877
3878         if [ "$type" == ost ]; then
3879                 devs=$(get_osd_param $node "" mntdev)
3880         else
3881                 devs=$(do_node $node $LCTL get_param -n osd-*.$FSNAME-M*.mntdev)
3882         fi
3883         for dev in $devs; do
3884                 case $dev in
3885                 *loop*) do_node $node "losetup $dev" | \
3886                                 sed -e "s/.*(//" -e "s/).*//" ;;
3887                 *) echo $dev ;;
3888                 esac
3889         done
3890 }
3891
3892 # Get all of the server target devices.
3893 get_svr_devs() {
3894         local node
3895         local i
3896
3897         # Master MDS parameters used by lfsck
3898         MDTNODE=$(facet_active_host $SINGLEMDS)
3899         MDTDEV=$(echo $(get_mnt_devs $MDTNODE mdt) | awk '{print $1}')
3900
3901         # MDT devices
3902         i=0
3903         for node in $(mdts_nodes); do
3904                 MDTDEVS[i]=$(get_mnt_devs $node mdt)
3905                 i=$((i + 1))
3906         done
3907
3908         # OST devices
3909         i=0
3910         for node in $(osts_nodes); do
3911                 OSTDEVS[i]=$(get_mnt_devs $node ost)
3912                 i=$((i + 1))
3913         done
3914 }
3915
3916 # Run e2fsck on MDT or OST device.
3917 run_e2fsck() {
3918         local node=$1
3919         local target_dev=$2
3920         local extra_opts=$3
3921         local cmd="$E2FSCK -d -v -t -t -f $extra_opts $target_dev"
3922         local log=$TMP/e2fsck.log
3923         local rc=0
3924
3925         echo $cmd
3926         do_node $node $cmd 2>&1 | tee $log
3927         rc=${PIPESTATUS[0]}
3928         if [ -n "$(grep "DNE mode isn't supported" $log)" ]; then
3929                 rm -f $log
3930                 if [ $MDSCOUNT -gt 1 ]; then
3931                         skip "DNE mode isn't supported!"
3932                         cleanupall
3933                         exit_status
3934                 else
3935                         error "It's not DNE mode."
3936                 fi
3937         fi
3938         rm -f $log
3939
3940         [ $rc -le $FSCK_MAX_ERR ] ||
3941                 error "$cmd returned $rc, should be <= $FSCK_MAX_ERR"
3942
3943         return 0
3944 }
3945
3946 #
3947 # Run resize2fs on MDT or OST device.
3948 #
3949 run_resize2fs() {
3950         local facet=$1
3951         local device=$2
3952         local size=$3
3953         shift 3
3954         local opts="$@"
3955
3956         do_facet $facet "$RESIZE2FS $opts $device $size"
3957 }
3958
3959 # verify a directory is shared among nodes.
3960 check_shared_dir() {
3961         local dir=$1
3962         local list=${2:-$(comma_list $(nodes_list))}
3963
3964         [ -z "$dir" ] && return 1
3965         do_rpc_nodes "$list" check_logdir $dir
3966         check_write_access $dir "$list" || return 1
3967         return 0
3968 }
3969
3970 # Run e2fsck on MDT and OST(s) to generate databases used for lfsck.
3971 generate_db() {
3972         local i
3973         local ostidx
3974         local dev
3975         local node
3976
3977         [[ $(lustre_version_code $SINGLEMDS) -ne $(version_code 2.2.0) ]] ||
3978                 { skip "Lustre 2.2.0 lacks the patch for LU-1255"; exit 0; }
3979
3980         check_shared_dir $SHARED_DIRECTORY ||
3981                 error "$SHARED_DIRECTORY isn't a shared directory"
3982
3983         export MDSDB=$SHARED_DIRECTORY/mdsdb
3984         export OSTDB=$SHARED_DIRECTORY/ostdb
3985
3986         # DNE is not supported, so when running e2fsck on a DNE filesystem,
3987         # we only pass master MDS parameters.
3988         run_e2fsck $MDTNODE $MDTDEV "-n --mdsdb $MDSDB"
3989
3990     i=0
3991     ostidx=0
3992     OSTDB_LIST=""
3993     for node in $(osts_nodes); do
3994         for dev in ${OSTDEVS[i]}; do
3995             run_e2fsck $node $dev "-n --mdsdb $MDSDB --ostdb $OSTDB-$ostidx"
3996             OSTDB_LIST="$OSTDB_LIST $OSTDB-$ostidx"
3997             ostidx=$((ostidx + 1))
3998         done
3999         i=$((i + 1))
4000     done
4001 }
4002
4003 # Run lfsck on server node if lfsck can't be found on client (LU-2571)
4004 run_lfsck_remote() {
4005         local cmd="$LFSCK_BIN -c -l --mdsdb $MDSDB --ostdb $OSTDB_LIST $MOUNT"
4006         local client=$1
4007         local mounted=true
4008         local rc=0
4009
4010         #Check if lustre is already mounted
4011         do_rpc_nodes $client is_mounted $MOUNT || mounted=false
4012         if ! $mounted; then
4013                 zconf_mount $client $MOUNT ||
4014                         error "failed to mount Lustre on $client"
4015         fi
4016         #Run lfsck
4017         echo $cmd
4018         do_node $client $cmd || rc=$?
4019         #Umount if necessary
4020         if ! $mounted; then
4021                 zconf_umount $client $MOUNT ||
4022                         error "failed to unmount Lustre on $client"
4023         fi
4024
4025         [ $rc -le $FSCK_MAX_ERR ] ||
4026                 error "$cmd returned $rc, should be <= $FSCK_MAX_ERR"
4027         echo "lfsck finished with rc=$rc"
4028
4029         return $rc
4030 }
4031
4032 run_lfsck() {
4033         local facets="client $SINGLEMDS"
4034         local found=false
4035         local facet
4036         local node
4037         local rc=0
4038
4039         for facet in $facets; do
4040                 node=$(facet_active_host $facet)
4041                 if check_progs_installed $node $LFSCK_BIN; then
4042                         found=true
4043                         break
4044                 fi
4045         done
4046         ! $found && error "None of \"$facets\" supports lfsck"
4047
4048         run_lfsck_remote $node || rc=$?
4049
4050         rm -rvf $MDSDB* $OSTDB* || true
4051         return $rc
4052 }
4053
4054 check_and_cleanup_lustre() {
4055     if [ "$LFSCK_ALWAYS" = "yes" -a "$TESTSUITE" != "lfsck" ]; then
4056         get_svr_devs
4057         generate_db
4058         run_lfsck
4059     fi
4060
4061         if is_mounted $MOUNT; then
4062                 [ -n "$DIR" ] && rm -rf $DIR/[Rdfs][0-9]* ||
4063                         error "remove sub-test dirs failed"
4064                 [ "$ENABLE_QUOTA" ] && restore_quota || true
4065         fi
4066
4067     if [ "$I_UMOUNTED2" = "yes" ]; then
4068         restore_mount $MOUNT2 || error "restore $MOUNT2 failed"
4069     fi
4070
4071     if [ "$I_MOUNTED2" = "yes" ]; then
4072         cleanup_mount $MOUNT2
4073     fi
4074
4075     if [ "$I_MOUNTED" = "yes" ]; then
4076         cleanupall -f || error "cleanup failed"
4077         unset I_MOUNTED
4078     fi
4079 }
4080
4081 #######
4082 # General functions
4083
4084 wait_for_function () {
4085     local quiet=""
4086
4087     # suppress fn both stderr and stdout
4088     if [ "$1" = "--quiet" ]; then
4089         shift
4090         quiet=" > /dev/null 2>&1"
4091
4092     fi
4093
4094     local fn=$1
4095     local max=${2:-900}
4096     local sleep=${3:-5}
4097
4098     local wait=0
4099
4100     while true; do
4101
4102         eval $fn $quiet && return 0
4103
4104         wait=$((wait + sleep))
4105         [ $wait -lt $max ] || return 1
4106         echo waiting $fn, $((max - wait)) secs left ...
4107         sleep $sleep
4108     done
4109 }
4110
4111 check_network() {
4112     local host=$1
4113     local max=$2
4114     local sleep=${3:-5}
4115
4116     echo `date +"%H:%M:%S (%s)"` waiting for $host network $max secs ...
4117     if ! wait_for_function --quiet "ping -c 1 -w 3 $host" $max $sleep ; then
4118         echo "Network not available!"
4119         exit 1
4120     fi
4121
4122     echo `date +"%H:%M:%S (%s)"` network interface is UP
4123 }
4124
4125 no_dsh() {
4126     shift
4127     eval $@
4128 }
4129
4130 # Convert a space-delimited list to a comma-delimited list.  If the input is
4131 # only whitespace, ensure the output is empty (i.e. "") so [ -n $list ] works
4132 comma_list() {
4133         # echo is used to convert newlines to spaces, since it doesn't
4134         # introduce a trailing space as using "tr '\n' ' '" does
4135         echo $(tr -s " " "\n" <<< $* | sort -b -u) | tr ' ' ','
4136 }
4137
4138 list_member () {
4139     local list=$1
4140     local item=$2
4141     echo $list | grep -qw $item
4142 }
4143
4144 # list, excluded are the comma separated lists
4145 exclude_items_from_list () {
4146     local list=$1
4147     local excluded=$2
4148     local item
4149
4150     list=${list//,/ }
4151     for item in ${excluded//,/ }; do
4152         list=$(echo " $list " | sed -re "s/\s+$item\s+/ /g")
4153     done
4154     echo $(comma_list $list)
4155 }
4156
4157 # list, expand  are the comma separated lists
4158 expand_list () {
4159     local list=${1//,/ }
4160     local expand=${2//,/ }
4161     local expanded=
4162
4163     expanded=$(for i in $list $expand; do echo $i; done | sort -u)
4164     echo $(comma_list $expanded)
4165 }
4166
4167 testslist_filter () {
4168     local script=$LUSTRE/tests/${TESTSUITE}.sh
4169
4170     [ -f $script ] || return 0
4171
4172     local start_at=$START_AT
4173     local stop_at=$STOP_AT
4174
4175     local var=${TESTSUITE//-/_}_START_AT
4176     [ x"${!var}" != x ] && start_at=${!var}
4177     var=${TESTSUITE//-/_}_STOP_AT
4178     [ x"${!var}" != x ] && stop_at=${!var}
4179
4180     sed -n 's/^test_\([^ (]*\).*/\1/p' $script | \
4181         awk ' BEGIN { if ("'${start_at:-0}'" != 0) flag = 1 }
4182             /^'${start_at}'$/ {flag = 0}
4183             {if (flag == 1) print $0}
4184             /^'${stop_at}'$/ { flag = 1 }'
4185 }
4186
4187 absolute_path() {
4188     (cd `dirname $1`; echo $PWD/`basename $1`)
4189 }
4190
4191 get_facets () {
4192     local types=${1:-"OST MDS MGS"}
4193
4194     local list=""
4195
4196     for entry in $types; do
4197         local name=$(echo $entry | tr "[:upper:]" "[:lower:]")
4198         local type=$(echo $entry | tr "[:lower:]" "[:upper:]")
4199
4200         case $type in
4201                 MGS ) list="$list $name";;
4202             MDS|OST|AGT ) local count=${type}COUNT
4203                        for ((i=1; i<=${!count}; i++)) do
4204                           list="$list ${name}$i"
4205                       done;;
4206                   * ) error "Invalid facet type"
4207                  exit 1;;
4208         esac
4209     done
4210     echo $(comma_list $list)
4211 }
4212
4213 ##################################
4214 # Adaptive Timeouts funcs
4215
4216 at_is_enabled() {
4217     # only check mds, we assume at_max is the same on all nodes
4218     local at_max=$(do_facet $SINGLEMDS "lctl get_param -n at_max")
4219     if [ $at_max -eq 0 ]; then
4220         return 1
4221     else
4222         return 0
4223     fi
4224 }
4225
4226 at_get() {
4227     local facet=$1
4228     local at=$2
4229
4230     # suppose that all ost-s have the same $at value set
4231     [ $facet != "ost" ] || facet=ost1
4232
4233     do_facet $facet "lctl get_param -n $at"
4234 }
4235
4236 at_max_get() {
4237     at_get $1 at_max
4238 }
4239
4240 at_min_get() {
4241         at_get $1 at_min
4242 }
4243
4244 at_max_set() {
4245     local at_max=$1
4246     shift
4247
4248     local facet
4249     local hosts
4250     for facet in $@; do
4251         if [ $facet == "ost" ]; then
4252             facet=$(get_facets OST)
4253         elif [ $facet == "mds" ]; then
4254             facet=$(get_facets MDS)
4255         fi
4256         hosts=$(expand_list $hosts $(facets_hosts $facet))
4257     done
4258
4259     do_nodes $hosts lctl set_param at_max=$at_max
4260 }
4261
4262 ##################################
4263 # OBD_FAIL funcs
4264
4265 drop_request() {
4266 # OBD_FAIL_MDS_ALL_REQUEST_NET
4267     RC=0
4268     do_facet $SINGLEMDS lctl set_param fail_loc=0x123
4269     do_facet client "$1" || RC=$?
4270     do_facet $SINGLEMDS lctl set_param fail_loc=0
4271     return $RC
4272 }
4273
4274 drop_reply() {
4275 # OBD_FAIL_MDS_ALL_REPLY_NET
4276     RC=0
4277     do_facet $SINGLEMDS lctl set_param fail_loc=0x122
4278     do_facet client "$@" || RC=$?
4279     do_facet $SINGLEMDS lctl set_param fail_loc=0
4280     return $RC
4281 }
4282
4283 drop_reint_reply() {
4284 # OBD_FAIL_MDS_REINT_NET_REP
4285     RC=0
4286     do_facet $SINGLEMDS lctl set_param fail_loc=0x119
4287     do_facet client "$@" || RC=$?
4288     do_facet $SINGLEMDS lctl set_param fail_loc=0
4289     return $RC
4290 }
4291
4292 drop_update_reply() {
4293 # OBD_FAIL_UPDATE_OBJ_NET_REP
4294         local index=$1
4295         shift 1
4296         RC=0
4297         do_facet mds${index} lctl set_param fail_loc=0x1701
4298         do_facet client "$@" || RC=$?
4299         do_facet mds${index} lctl set_param fail_loc=0
4300         return $RC
4301 }
4302
4303 pause_bulk() {
4304 #define OBD_FAIL_OST_BRW_PAUSE_BULK      0x214
4305         RC=0
4306
4307         local timeout=${2:-0}
4308         # default is (obd_timeout / 4) if unspecified
4309         echo "timeout is $timeout/$2"
4310         do_facet ost1 lctl set_param fail_val=$timeout fail_loc=0x80000214
4311         do_facet client "$1" || RC=$?
4312         do_facet client "sync"
4313         do_facet ost1 lctl set_param fail_loc=0
4314         return $RC
4315 }
4316
4317 drop_ldlm_cancel() {
4318 #define OBD_FAIL_LDLM_CANCEL_NET                        0x304
4319         local RC=0
4320         local list=$(comma_list $(mdts_nodes) $(osts_nodes))
4321         do_nodes $list lctl set_param fail_loc=0x304
4322
4323         do_facet client "$@" || RC=$?
4324
4325         do_nodes $list lctl set_param fail_loc=0
4326         return $RC
4327 }
4328
4329 drop_bl_callback() {
4330 #define OBD_FAIL_LDLM_BL_CALLBACK_NET                   0x305
4331         RC=0
4332         do_facet client lctl set_param fail_loc=0x80000305
4333         do_facet client "$@" || RC=$?
4334         do_facet client lctl set_param fail_loc=0
4335         return $RC
4336 }
4337
4338 drop_ldlm_reply() {
4339 #define OBD_FAIL_LDLM_REPLY              0x30c
4340     RC=0
4341     do_facet $SINGLEMDS lctl set_param fail_loc=0x30c
4342     do_facet client "$@" || RC=$?
4343     do_facet $SINGLEMDS lctl set_param fail_loc=0
4344     return $RC
4345 }
4346
4347 clear_failloc() {
4348     facet=$1
4349     pause=$2
4350     sleep $pause
4351     echo "clearing fail_loc on $facet"
4352     do_facet $facet "lctl set_param fail_loc=0 2>/dev/null || true"
4353 }
4354
4355 set_nodes_failloc () {
4356         do_nodes $(comma_list $1)  lctl set_param fail_val=0 fail_loc=$2
4357 }
4358
4359 cancel_lru_locks() {
4360     $LCTL mark "cancel_lru_locks $1 start"
4361     for d in `lctl get_param -N ldlm.namespaces.*.lru_size | egrep -i $1`; do
4362         $LCTL set_param -n $d=clear
4363     done
4364     $LCTL get_param ldlm.namespaces.*.lock_unused_count | egrep -i $1 | grep -v '=0'
4365     $LCTL mark "cancel_lru_locks $1 stop"
4366 }
4367
4368 default_lru_size()
4369 {
4370         NR_CPU=$(grep -c "processor" /proc/cpuinfo)
4371         DEFAULT_LRU_SIZE=$((100 * NR_CPU))
4372         echo "$DEFAULT_LRU_SIZE"
4373 }
4374
4375 lru_resize_enable()
4376 {
4377     lctl set_param ldlm.namespaces.*$1*.lru_size=0
4378 }
4379
4380 lru_resize_disable()
4381 {
4382     lctl set_param ldlm.namespaces.*$1*.lru_size $(default_lru_size)
4383 }
4384
4385 pgcache_empty() {
4386     local FILE
4387     for FILE in `lctl get_param -N "llite.*.dump_page_cache"`; do
4388         if [ `lctl get_param -n $FILE | wc -l` -gt 1 ]; then
4389             echo there is still data in page cache $FILE ?
4390             lctl get_param -n $FILE
4391             return 1
4392         fi
4393     done
4394     return 0
4395 }
4396
4397 debugsave() {
4398     DEBUGSAVE="$(lctl get_param -n debug)"
4399 }
4400
4401 debugrestore() {
4402     [ -n "$DEBUGSAVE" ] && \
4403         do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug=\\\"${DEBUGSAVE}\\\";"
4404     DEBUGSAVE=""
4405 }
4406
4407 debug_size_save() {
4408     DEBUG_SIZE_SAVED="$(lctl get_param -n debug_mb)"
4409 }
4410
4411 debug_size_restore() {
4412     [ -n "$DEBUG_SIZE_SAVED" ] && \
4413         do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE_SAVED"
4414     DEBUG_SIZE_SAVED=""
4415 }
4416
4417 start_full_debug_logging() {
4418     debugsave
4419     debug_size_save
4420
4421     local FULLDEBUG=-1
4422     local DEBUG_SIZE=150
4423
4424     do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE"
4425     do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug=$FULLDEBUG;"
4426 }
4427
4428 stop_full_debug_logging() {
4429     debug_size_restore
4430     debugrestore
4431 }
4432
4433 # prints bash call stack
4434 log_trace_dump() {
4435         echo "  Trace dump:"
4436         for (( i=1; i < ${#BASH_LINENO[*]} ; i++ )) ; do
4437                 local s=${BASH_SOURCE[$i]}
4438                 local l=${BASH_LINENO[$i-1]}
4439                 local f=${FUNCNAME[$i]}
4440                 echo "  = $s:$l:$f()"
4441         done
4442 }
4443
4444 ##################################
4445 # Test interface
4446 ##################################
4447
4448 error_noexit() {
4449         local TYPE=${TYPE:-"FAIL"}
4450
4451         local dump=true
4452         # do not dump logs if $1=false
4453         if [ "x$1" = "xfalse" ]; then
4454                 shift
4455                 dump=false
4456         fi
4457
4458
4459         log " ${TESTSUITE} ${TESTNAME}: @@@@@@ ${TYPE}: $@ "
4460         log_trace_dump
4461
4462         mkdir -p $LOGDIR
4463         # We need to dump the logs on all nodes
4464         if $dump; then
4465                 gather_logs $(comma_list $(nodes_list))
4466         fi
4467
4468         debugrestore
4469         [ "$TESTSUITELOG" ] &&
4470                 echo "$TESTSUITE: $TYPE: $TESTNAME $@" >> $TESTSUITELOG
4471         if [ -z "$*" ]; then
4472                 echo "error() without useful message, please fix" > $LOGDIR/err
4473         else
4474                 if [[ `echo $TYPE | grep ^IGNORE` ]]; then
4475                         echo "$@" > $LOGDIR/ignore
4476                 else
4477                         echo "$@" > $LOGDIR/err
4478                 fi
4479         fi
4480 }
4481
4482 exit_status () {
4483         local status=0
4484         local log=$TESTSUITELOG
4485
4486         [ -f "$log" ] && grep -q FAIL $log && status=1
4487         exit $status
4488 }
4489
4490 error() {
4491         error_noexit "$@"
4492         exit 1
4493 }
4494
4495 error_exit() {
4496         error "$@"
4497 }
4498
4499 # use only if we are ignoring failures for this test, bugno required.
4500 # (like ALWAYS_EXCEPT, but run the test and ignore the results.)
4501 # e.g. error_ignore bz5494 "your message" or
4502 # error_ignore LU-5494 "your message"
4503 error_ignore() {
4504         local TYPE="IGNORE ($1)"
4505         shift
4506         error_noexit "$@"
4507 }
4508
4509 error_and_remount() {
4510         error_noexit "$@"
4511         remount_client $MOUNT
4512         exit 1
4513 }
4514
4515 skip_env () {
4516         $FAIL_ON_SKIP_ENV && error false $@ || skip $@
4517 }
4518
4519 skip() {
4520         echo
4521         log " SKIP: $TESTSUITE $TESTNAME $@"
4522
4523         if [[ -n "$ALWAYS_SKIPPED" ]]; then
4524                 skip_logged $TESTNAME "$@"
4525         else
4526                 mkdir -p $LOGDIR
4527                 echo "$@" > $LOGDIR/skip
4528         fi
4529
4530         [[ -n "$TESTSUITELOG" ]] &&
4531                 echo "$TESTSUITE: SKIP: $TESTNAME $@" >> $TESTSUITELOG || true
4532 }
4533
4534 build_test_filter() {
4535     EXCEPT="$EXCEPT $(testslist_filter)"
4536
4537         for O in $ONLY; do
4538                 if [[ $O = [0-9]*-[0-9]* ]]; then
4539                         for num in $(seq $(echo $O | tr '-' ' ')); do
4540                                 eval ONLY_$num=true
4541                         done
4542                 else
4543                         eval ONLY_${O}=true
4544                 fi
4545         done
4546
4547     [ "$EXCEPT$ALWAYS_EXCEPT" ] && \
4548         log "excepting tests: `echo $EXCEPT $ALWAYS_EXCEPT`"
4549     [ "$EXCEPT_SLOW" ] && \
4550         log "skipping tests SLOW=no: `echo $EXCEPT_SLOW`"
4551     for E in $EXCEPT; do
4552         eval EXCEPT_${E}=true
4553     done
4554     for E in $ALWAYS_EXCEPT; do
4555         eval EXCEPT_ALWAYS_${E}=true
4556     done
4557     for E in $EXCEPT_SLOW; do
4558         eval EXCEPT_SLOW_${E}=true
4559     done
4560     for G in $GRANT_CHECK_LIST; do
4561         eval GCHECK_ONLY_${G}=true
4562         done
4563 }
4564
4565 basetest() {
4566     if [[ $1 = [a-z]* ]]; then
4567         echo $1
4568     else
4569         echo ${1%%[a-z]*}
4570     fi
4571 }
4572
4573 # print a newline if the last test was skipped
4574 export LAST_SKIPPED=
4575 export ALWAYS_SKIPPED=
4576 #
4577 # Main entry into test-framework. This is called with the name and
4578 # description of a test. The name is used to find the function to run
4579 # the test using "test_$name".
4580 #
4581 # This supports a variety of methods of specifying specific test to
4582 # run or not run.  These need to be documented...
4583 #
4584 run_test() {
4585     assert_DIR
4586
4587     export base=`basetest $1`
4588     if [ ! -z "$ONLY" ]; then
4589         testname=ONLY_$1
4590         if [ ${!testname}x != x ]; then
4591             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
4592             run_one_logged $1 "$2"
4593             return $?
4594         fi
4595         testname=ONLY_$base
4596         if [ ${!testname}x != x ]; then
4597             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
4598             run_one_logged $1 "$2"
4599             return $?
4600         fi
4601         LAST_SKIPPED="y"
4602         return 0
4603     fi
4604
4605         LAST_SKIPPED="y"
4606         ALWAYS_SKIPPED="y"
4607     testname=EXCEPT_$1
4608     if [ ${!testname}x != x ]; then
4609         TESTNAME=test_$1 skip "skipping excluded test $1"
4610         return 0
4611     fi
4612     testname=EXCEPT_$base
4613     if [ ${!testname}x != x ]; then
4614         TESTNAME=test_$1 skip "skipping excluded test $1 (base $base)"
4615         return 0
4616     fi
4617     testname=EXCEPT_ALWAYS_$1
4618     if [ ${!testname}x != x ]; then
4619         TESTNAME=test_$1 skip "skipping ALWAYS excluded test $1"
4620         return 0
4621     fi
4622     testname=EXCEPT_ALWAYS_$base
4623     if [ ${!testname}x != x ]; then
4624         TESTNAME=test_$1 skip "skipping ALWAYS excluded test $1 (base $base)"
4625         return 0
4626     fi
4627     testname=EXCEPT_SLOW_$1
4628     if [ ${!testname}x != x ]; then
4629         TESTNAME=test_$1 skip "skipping SLOW test $1"
4630         return 0
4631     fi
4632     testname=EXCEPT_SLOW_$base
4633     if [ ${!testname}x != x ]; then
4634         TESTNAME=test_$1 skip "skipping SLOW test $1 (base $base)"
4635         return 0
4636     fi
4637
4638     LAST_SKIPPED=
4639     ALWAYS_SKIPPED=
4640     run_one_logged $1 "$2"
4641
4642     return $?
4643 }
4644
4645 log() {
4646     echo "$*"
4647     module_loaded lnet || load_modules
4648
4649     local MSG="$*"
4650     # Get rid of '
4651     MSG=${MSG//\'/\\\'}
4652     MSG=${MSG//\(/\\\(}
4653     MSG=${MSG//\)/\\\)}
4654     MSG=${MSG//\;/\\\;}
4655     MSG=${MSG//\|/\\\|}
4656     MSG=${MSG//\>/\\\>}
4657     MSG=${MSG//\</\\\<}
4658     MSG=${MSG//\//\\\/}
4659     do_nodes $(comma_list $(nodes_list)) $LCTL mark "$MSG" 2> /dev/null || true
4660 }
4661
4662 trace() {
4663         log "STARTING: $*"
4664         strace -o $TMP/$1.strace -ttt $*
4665         RC=$?
4666         log "FINISHED: $*: rc $RC"
4667         return 1
4668 }
4669
4670 complete () {
4671     local duration=$1
4672
4673     banner test complete, duration $duration sec
4674     [ -f "$TESTSUITELOG" ] && egrep .FAIL $TESTSUITELOG || true
4675     echo duration $duration >>$TESTSUITELOG
4676 }
4677
4678 pass() {
4679         # Set TEST_STATUS here. It will be used for logging the result.
4680         TEST_STATUS="PASS"
4681
4682         if [[ -f $LOGDIR/err ]]; then
4683                 TEST_STATUS="FAIL"
4684         elif [[ -f $LOGDIR/skip ]]; then
4685                 TEST_STATUS="SKIP"
4686         fi
4687         echo "$TEST_STATUS $@" 2>&1 | tee -a $TESTSUITELOG
4688 }
4689
4690 check_mds() {
4691     local FFREE=$(do_node $SINGLEMDS \
4692         lctl get_param -n osd*.*MDT*.filesfree | calc_sum)
4693     local FTOTAL=$(do_node $SINGLEMDS \
4694         lctl get_param -n osd*.*MDT*.filestotal | calc_sum)
4695
4696     [ $FFREE -ge $FTOTAL ] && error "files free $FFREE > total $FTOTAL" || true
4697 }
4698
4699 reset_fail_loc () {
4700     echo -n "Resetting fail_loc on all nodes..."
4701     do_nodes $(comma_list $(nodes_list)) "lctl set_param -n fail_loc=0 2>/dev/null || true"
4702     echo done.
4703 }
4704
4705
4706 #
4707 # Log a message (on all nodes) padded with "=" before and after. 
4708 # Also appends a timestamp and prepends the testsuite name.
4709
4710
4711 EQUALS="===================================================================================================="
4712 banner() {
4713     msg="== ${TESTSUITE} $*"
4714     last=${msg: -1:1}
4715     [[ $last != "=" && $last != " " ]] && msg="$msg "
4716     msg=$(printf '%s%.*s'  "$msg"  $((${#EQUALS} - ${#msg})) $EQUALS )
4717     # always include at least == after the message
4718     log "$msg== $(date +"%H:%M:%S (%s)")"
4719 }
4720
4721 #
4722 # Run a single test function and cleanup after it.
4723 #
4724 # This function should be run in a subshell so the test func can
4725 # exit() without stopping the whole script.
4726 #
4727 run_one() {
4728         local testnum=$1
4729         local message=$2
4730         export tfile=f${testnum}.${TESTSUITE}
4731         export tdir=d${testnum}.${TESTSUITE}
4732         export TESTNAME=test_$testnum
4733         local SAVE_UMASK=`umask`
4734         umask 0022
4735
4736         banner "test $testnum: $message"
4737         test_${testnum} || error "test_$testnum failed with $?"
4738         cd $SAVE_PWD
4739         reset_fail_loc
4740         check_grant ${testnum} || error "check_grant $testnum failed with $?"
4741         check_catastrophe || error "LBUG/LASSERT detected"
4742         if [ "$PARALLEL" != "yes" ]; then
4743                 ps auxww | grep -v grep | grep -q multiop &&
4744                                         error "multiop still running"
4745         fi
4746         unset TESTNAME
4747         unset tdir
4748         unset tfile
4749         umask $SAVE_UMASK
4750         return 0
4751 }
4752
4753 #
4754 # Wrapper around run_one to ensure:
4755 #  - test runs in subshell
4756 #  - output of test is saved to separate log file for error reporting
4757 #  - test result is saved to data file
4758 #
4759 run_one_logged() {
4760         local BEFORE=`date +%s`
4761         local TEST_ERROR
4762         local name=${TESTSUITE}.test_${1}.test_log.$(hostname -s).log
4763         local test_log=$LOGDIR/$name
4764         rm -rf $LOGDIR/err
4765         rm -rf $LOGDIR/ignore
4766         rm -rf $LOGDIR/skip
4767         local SAVE_UMASK=`umask`
4768         umask 0022
4769
4770         echo
4771         log_sub_test_begin test_${1}
4772         (run_one $1 "$2") 2>&1 | tee -i $test_log
4773         local RC=${PIPESTATUS[0]}
4774
4775         [ $RC -ne 0 ] && [ ! -f $LOGDIR/err ] &&
4776                 echo "test_$1 returned $RC" | tee $LOGDIR/err
4777
4778         duration=$((`date +%s` - $BEFORE))
4779         pass "$1" "(${duration}s)"
4780
4781         if [[ -f $LOGDIR/err ]]; then
4782                 TEST_ERROR=$(cat $LOGDIR/err)
4783         elif [[ -f $LOGDIR/ignore ]]; then
4784                 TEST_ERROR=$(cat $LOGDIR/ignore)
4785         elif [[ -f $LOGDIR/skip ]]; then
4786                 TEST_ERROR=$(cat $LOGDIR/skip)
4787         fi
4788         log_sub_test_end $TEST_STATUS $duration "$RC" "$TEST_ERROR"
4789
4790         if [[ "$TEST_STATUS" != "SKIP" ]] && [[ -f $TF_SKIP ]]; then
4791                 rm -f $TF_SKIP
4792         fi
4793
4794         if [ -f $LOGDIR/err ]; then
4795                 $FAIL_ON_ERROR && exit $RC
4796         fi
4797
4798         umask $SAVE_UMASK
4799
4800         return 0
4801 }
4802
4803 #
4804 # Print information of skipped tests to result.yml
4805 #
4806 skip_logged(){
4807         log_sub_test_begin $1
4808         shift
4809         log_sub_test_end "SKIP" "0" "0" "$@"
4810 }
4811
4812 canonical_path() {
4813     (cd `dirname $1`; echo $PWD/`basename $1`)
4814 }
4815
4816
4817 check_grant() {
4818     export base=`basetest $1`
4819     [ "$CHECK_GRANT" == "no" ] && return 0
4820
4821         testname=GCHECK_ONLY_${base}
4822         [ ${!testname}x == x ] && return 0
4823
4824     echo -n "checking grant......"
4825
4826         local clients=$CLIENTS
4827         [ -z $clients ] && clients=$(hostname)
4828
4829     # sync all the data and make sure no pending data on server
4830     do_nodes $clients sync
4831
4832     # get client grant
4833     client_grant=`do_nodes $clients \
4834                     "$LCTL get_param -n osc.${FSNAME}-*.cur_*grant_bytes" | \
4835                     awk '{total += $1} END{print total}'`
4836
4837     # get server grant
4838     server_grant=`do_nodes $(comma_list $(osts_nodes)) \
4839                     "$LCTL get_param -n obdfilter.${FSNAME}-OST*.tot_granted" |
4840                     awk '{total += $1} END{print total}'`
4841
4842     # check whether client grant == server grant
4843     if [ $client_grant -ne $server_grant ]; then
4844         echo "failed: client:${client_grant} server: ${server_grant}."
4845         do_nodes $(comma_list $(osts_nodes)) \
4846                    "$LCTL get_param obdfilter.${FSNAME}-OST*.tot*"
4847         do_nodes $clients "$LCTL get_param osc.${FSNAME}-*.cur_*_bytes"
4848         return 1
4849     else
4850         echo "pass: client:${client_grant} server: ${server_grant}"
4851     fi
4852
4853 }
4854
4855 ########################
4856 # helper functions
4857
4858 osc_to_ost()
4859 {
4860     osc=$1
4861     ost=`echo $1 | awk -F_ '{print $3}'`
4862     if [ -z $ost ]; then
4863         ost=`echo $1 | sed 's/-osc.*//'`
4864     fi
4865     echo $ost
4866 }
4867
4868 ostuuid_from_index()
4869 {
4870     $LFS osts $2 | sed -ne "/^$1: /s/.* \(.*\) .*$/\1/p"
4871 }
4872
4873 ostname_from_index() {
4874     local uuid=$(ostuuid_from_index $1)
4875     echo ${uuid/_UUID/}
4876 }
4877
4878 index_from_ostuuid()
4879 {
4880     $LFS osts $2 | sed -ne "/${1}/s/\(.*\): .* .*$/\1/p"
4881 }
4882
4883 mdtuuid_from_index()
4884 {
4885     $LFS mdts $2 | sed -ne "/^$1: /s/.* \(.*\) .*$/\1/p"
4886 }
4887
4888 # Description:
4889 #   Return unique identifier for given hostname
4890 host_id() {
4891         local host_name=$1
4892         echo $host_name | md5sum | cut -d' ' -f1
4893 }
4894
4895 # Description:
4896 #   Returns list of ip addresses for each interface
4897 local_addr_list() {
4898         ip addr | awk '/inet\ / {print $2}' | awk -F\/ '{print $1}'
4899 }
4900
4901 is_local_addr() {
4902         local addr=$1
4903         # Cache address list to avoid mutiple execution of local_addr_list
4904         LOCAL_ADDR_LIST=${LOCAL_ADDR_LIST:-$(local_addr_list)}
4905         local i
4906         for i in $LOCAL_ADDR_LIST ; do
4907                 [[ "$i" == "$addr" ]] && return 0
4908         done
4909         return 1
4910 }
4911
4912 local_node() {
4913         local host_name=$1
4914         local is_local="IS_LOCAL_$(host_id $host_name)"
4915         if [ -z "${!is_local-}" ] ; then
4916                 eval $is_local=0
4917                 local host_ip=$($LUSTRE/tests/resolveip $host_name)
4918                 is_local_addr "$host_ip" && eval $is_local=1
4919         fi
4920         [[ "${!is_local}" == "1" ]]
4921 }
4922
4923 remote_node () {
4924         local node=$1
4925         local_node $node && return 1
4926         return 0
4927 }
4928
4929 remote_mds ()
4930 {
4931     local node
4932     for node in $(mdts_nodes); do
4933         remote_node $node && return 0
4934     done
4935     return 1
4936 }
4937
4938 remote_mds_nodsh()
4939 {
4940     [ "$CLIENTONLY" ] && return 0 || true
4941     remote_mds && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$mds_HOST" ]
4942 }
4943
4944 require_dsh_mds()
4945 {
4946         remote_mds_nodsh && echo "SKIP: $TESTSUITE: remote MDS with nodsh" && \
4947             MSKIPPED=1 && return 1
4948         return 0
4949 }
4950
4951 remote_ost ()
4952 {
4953     local node
4954     for node in $(osts_nodes) ; do
4955         remote_node $node && return 0
4956     done
4957     return 1
4958 }
4959
4960 remote_ost_nodsh()
4961 {
4962     [ "$CLIENTONLY" ] && return 0 || true 
4963     remote_ost && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
4964 }
4965
4966 require_dsh_ost()
4967 {
4968         remote_ost_nodsh && echo "SKIP: $TESTSUITE: remote OST with nodsh" && \
4969             OSKIPPED=1 && return 1
4970         return 0
4971 }
4972
4973 remote_mgs_nodsh()
4974 {
4975     local MGS 
4976     MGS=$(facet_host mgs)
4977     remote_node $MGS && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
4978 }
4979
4980 local_mode ()
4981 {
4982     remote_mds_nodsh || remote_ost_nodsh || \
4983         $(single_local_node $(comma_list $(nodes_list)))
4984 }
4985
4986 remote_servers () {
4987     remote_ost && remote_mds
4988 }
4989
4990 # Get the active nodes for facets.
4991 facets_nodes () {
4992         local facets=$1
4993         local facet
4994         local nodes
4995         local nodes_sort
4996         local i
4997
4998         for facet in ${facets//,/ }; do
4999                 nodes="$nodes $(facet_active_host $facet)"
5000         done
5001
5002         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5003         echo -n $nodes_sort
5004 }
5005
5006 # Get all of the active MDS nodes.
5007 mdts_nodes () {
5008         echo -n $(facets_nodes $(get_facets MDS))
5009 }
5010
5011 # Get all of the active OSS nodes.
5012 osts_nodes () {
5013         echo -n $(facets_nodes $(get_facets OST))
5014 }
5015
5016 # Get all of the active AGT (HSM agent) nodes.
5017 agts_nodes () {
5018         echo -n $(facets_nodes $(get_facets AGT))
5019 }
5020
5021 # Get all of the client nodes and active server nodes.
5022 nodes_list () {
5023         local nodes=$HOSTNAME
5024         local nodes_sort
5025         local i
5026
5027         # CLIENTS (if specified) contains the local client
5028         [ -n "$CLIENTS" ] && nodes=${CLIENTS//,/ }
5029
5030         if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
5031                 nodes="$nodes $(facets_nodes $(get_facets))"
5032         fi
5033
5034         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5035         echo -n $nodes_sort
5036 }
5037
5038 # Get all of the remote client nodes and remote active server nodes.
5039 remote_nodes_list () {
5040         echo -n $(nodes_list) | sed -re "s/\<$HOSTNAME\>//g"
5041 }
5042
5043 # Get all of the MDS nodes, including active and passive nodes.
5044 all_mdts_nodes () {
5045         local host
5046         local failover_host
5047         local nodes
5048         local nodes_sort
5049         local i
5050
5051         for i in $(seq $MDSCOUNT); do
5052                 host=mds${i}_HOST
5053                 failover_host=mds${i}failover_HOST
5054                 nodes="$nodes ${!host} ${!failover_host}"
5055         done
5056
5057         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5058         echo -n $nodes_sort
5059 }
5060
5061 # Get all of the OSS nodes, including active and passive nodes.
5062 all_osts_nodes () {
5063         local host
5064         local failover_host
5065         local nodes
5066         local nodes_sort
5067         local i
5068
5069         for i in $(seq $OSTCOUNT); do
5070                 host=ost${i}_HOST
5071                 failover_host=ost${i}failover_HOST
5072                 nodes="$nodes ${!host} ${!failover_host}"
5073         done
5074
5075         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5076         echo -n $nodes_sort
5077 }
5078
5079 # Get all of the server nodes, including active and passive nodes.
5080 all_server_nodes () {
5081         local nodes
5082         local nodes_sort
5083         local i
5084
5085         nodes="$mgs_HOST $mgsfailover_HOST $(all_mdts_nodes) $(all_osts_nodes)"
5086
5087         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5088         echo -n $nodes_sort
5089 }
5090
5091 # Get all of the client and server nodes, including active and passive nodes.
5092 all_nodes () {
5093         local nodes=$HOSTNAME
5094         local nodes_sort
5095         local i
5096
5097         # CLIENTS (if specified) contains the local client
5098         [ -n "$CLIENTS" ] && nodes=${CLIENTS//,/ }
5099
5100         if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
5101                 nodes="$nodes $(all_server_nodes)"
5102         fi
5103
5104         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5105         echo -n $nodes_sort
5106 }
5107
5108 init_clients_lists () {
5109     # Sanity check: exclude the local client from RCLIENTS
5110     local clients=$(hostlist_expand "$RCLIENTS")
5111     local rclients=$(exclude_items_from_list "$clients" $HOSTNAME)
5112
5113     # Sanity check: exclude the dup entries
5114     RCLIENTS=$(for i in ${rclients//,/ }; do echo $i; done | sort -u)
5115
5116     clients="$SINGLECLIENT $HOSTNAME $RCLIENTS"
5117
5118     # Sanity check: exclude the dup entries from CLIENTS
5119     # for those configs which has SINGLCLIENT set to local client
5120     clients=$(for i in $clients; do echo $i; done | sort -u)
5121
5122     CLIENTS=$(comma_list $clients)
5123     local -a remoteclients=($RCLIENTS)
5124     for ((i=0; $i<${#remoteclients[@]}; i++)); do
5125             varname=CLIENT$((i + 2))
5126             eval $varname=${remoteclients[i]}
5127     done
5128
5129     CLIENTCOUNT=$((${#remoteclients[@]} + 1))
5130 }
5131
5132 get_random_entry () {
5133     local rnodes=$1
5134
5135     rnodes=${rnodes//,/ }
5136
5137     local -a nodes=($rnodes)
5138     local num=${#nodes[@]} 
5139     local i=$((RANDOM * num * 2 / 65536))
5140
5141     echo ${nodes[i]}
5142 }
5143
5144 client_only () {
5145     [ "$CLIENTONLY" ] || [ "$CLIENTMODSONLY" = yes ]
5146 }
5147
5148 is_patchless ()
5149 {
5150     lctl get_param version | grep -q patchless
5151 }
5152
5153 check_versions () {
5154     [ "$(lustre_version_code client)" = "$(lustre_version_code $SINGLEMDS)" -a \
5155       "$(lustre_version_code client)" = "$(lustre_version_code ost1)" ]
5156 }
5157
5158 get_node_count() {
5159     local nodes="$@"
5160     echo $nodes | wc -w || true
5161 }
5162
5163 mixed_ost_devs () {
5164     local nodes=$(osts_nodes)
5165     local osscount=$(get_node_count "$nodes")
5166     [ ! "$OSTCOUNT" = "$osscount" ]
5167 }
5168
5169 mixed_mdt_devs () {
5170     local nodes=$(mdts_nodes)
5171     local mdtcount=$(get_node_count "$nodes")
5172     [ ! "$MDSCOUNT" = "$mdtcount" ]
5173 }
5174
5175 generate_machine_file() {
5176     local nodes=${1//,/ }
5177     local machinefile=$2
5178     rm -f $machinefile
5179     for node in $nodes; do
5180         echo $node >>$machinefile || \
5181             { echo "can not generate machinefile $machinefile" && return 1; }
5182     done
5183 }
5184
5185 get_stripe () {
5186         local file=$1/stripe
5187
5188         touch $file
5189         $LFS getstripe -v $file || error "getstripe $file failed"
5190         rm -f $file
5191 }
5192
5193 setstripe_nfsserver () {
5194     local dir=$1
5195
5196     local nfsserver=$(awk '"'$dir'" ~ $2 && $3 ~ "nfs" && $2 != "/" \
5197                 { print $1 }' /proc/mounts | cut -f 1 -d : | head -1)
5198
5199     [ -z $nfsserver ] && echo "$dir is not nfs mounted" && return 1
5200
5201     do_nodev $nfsserver lfs setstripe "$@"
5202 }
5203
5204 # Check and add a test group.
5205 add_group() {
5206         local group_id=$1
5207         local group_name=$2
5208         local rc=0
5209
5210         local gid=$(getent group $group_name | cut -d: -f3)
5211         if [[ -n "$gid" ]]; then
5212                 [[ "$gid" -eq "$group_id" ]] || {
5213                         error_noexit "inconsistent group ID:" \
5214                                      "new: $group_id, old: $gid"
5215                         rc=1
5216                 }
5217         else
5218                 groupadd -g $group_id $group_name
5219                 rc=${PIPESTATUS[0]}
5220         fi
5221
5222         return $rc
5223 }
5224
5225 # Check and add a test user.
5226 add_user() {
5227         local user_id=$1
5228         shift
5229         local user_name=$1
5230         shift
5231         local group_name=$1
5232         shift
5233         local home=$1
5234         shift
5235         local opts="$@"
5236         local rc=0
5237
5238         local uid=$(getent passwd $user_name | cut -d: -f3)
5239         if [[ -n "$uid" ]]; then
5240                 if [[ "$uid" -eq "$user_id" ]]; then
5241                         local dir=$(getent passwd $user_name | cut -d: -f6)
5242                         if [[ "$dir" != "$home" ]]; then
5243                                 mkdir -p $home
5244                                 usermod -d $home $user_name
5245                                 rc=${PIPESTATUS[0]}
5246                         fi
5247                 else
5248                         error_noexit "inconsistent user ID:" \
5249                                      "new: $user_id, old: $uid"
5250                         rc=1
5251                 fi
5252         else
5253                 mkdir -p $home
5254                 useradd -M -u $user_id -d $home -g $group_name $opts $user_name
5255                 rc=${PIPESTATUS[0]}
5256         fi
5257
5258         return $rc
5259 }
5260
5261 check_runas_id_ret() {
5262     local myRC=0
5263     local myRUNAS_UID=$1
5264     local myRUNAS_GID=$2
5265     shift 2
5266     local myRUNAS=$@
5267     if [ -z "$myRUNAS" ]; then
5268         error_exit "myRUNAS command must be specified for check_runas_id"
5269     fi
5270     if $GSS_KRB5; then
5271         $myRUNAS krb5_login.sh || \
5272             error "Failed to refresh Kerberos V5 TGT for UID $myRUNAS_ID."
5273     fi
5274     mkdir $DIR/d0_runas_test
5275     chmod 0755 $DIR
5276     chown $myRUNAS_UID:$myRUNAS_GID $DIR/d0_runas_test
5277     $myRUNAS touch $DIR/d0_runas_test/f$$ || myRC=$?
5278     rm -rf $DIR/d0_runas_test
5279     return $myRC
5280 }
5281
5282 check_runas_id() {
5283     local myRUNAS_UID=$1
5284     local myRUNAS_GID=$2
5285     shift 2
5286     local myRUNAS=$@
5287     check_runas_id_ret $myRUNAS_UID $myRUNAS_GID $myRUNAS || \
5288         error "unable to write to $DIR/d0_runas_test as UID $myRUNAS_UID.
5289         Please set RUNAS_ID to some UID which exists on MDS and client or
5290         add user $myRUNAS_UID:$myRUNAS_GID on these nodes."
5291 }
5292
5293 # obtain the UID/GID for MPI_USER
5294 get_mpiuser_id() {
5295     local mpi_user=$1
5296
5297     MPI_USER_UID=$(do_facet client "getent passwd $mpi_user | cut -d: -f3;
5298 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the UID for $mpi_user"
5299
5300     MPI_USER_GID=$(do_facet client "getent passwd $mpi_user | cut -d: -f4;
5301 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the GID for $mpi_user"
5302 }
5303
5304 # obtain and cache Kerberos ticket-granting ticket
5305 refresh_krb5_tgt() {
5306     local myRUNAS_UID=$1
5307     local myRUNAS_GID=$2
5308     shift 2
5309     local myRUNAS=$@
5310     if [ -z "$myRUNAS" ]; then
5311         error_exit "myRUNAS command must be specified for refresh_krb5_tgt"
5312     fi
5313
5314     CLIENTS=${CLIENTS:-$HOSTNAME}
5315     do_nodes $CLIENTS "set -x
5316 if ! $myRUNAS krb5_login.sh; then
5317     echo "Failed to refresh Krb5 TGT for UID/GID $myRUNAS_UID/$myRUNAS_GID."
5318     exit 1
5319 fi"
5320 }
5321
5322 # Run multiop in the background, but wait for it to print
5323 # "PAUSING" to its stdout before returning from this function.
5324 multiop_bg_pause() {
5325     MULTIOP_PROG=${MULTIOP_PROG:-$MULTIOP}
5326     FILE=$1
5327     ARGS=$2
5328
5329     TMPPIPE=/tmp/multiop_open_wait_pipe.$$
5330     mkfifo $TMPPIPE
5331
5332     echo "$MULTIOP_PROG $FILE v$ARGS"
5333     $MULTIOP_PROG $FILE v$ARGS > $TMPPIPE &
5334
5335     echo "TMPPIPE=${TMPPIPE}"
5336     read -t 60 multiop_output < $TMPPIPE
5337     if [ $? -ne 0 ]; then
5338         rm -f $TMPPIPE
5339         return 1
5340     fi
5341     rm -f $TMPPIPE
5342     if [ "$multiop_output" != "PAUSING" ]; then
5343         echo "Incorrect multiop output: $multiop_output"
5344         kill -9 $PID
5345         return 1
5346     fi
5347
5348     return 0
5349 }
5350
5351 do_and_time () {
5352     local cmd=$1
5353     local rc
5354
5355     SECONDS=0
5356     eval '$cmd'
5357     
5358     [ ${PIPESTATUS[0]} -eq 0 ] || rc=1
5359
5360     echo $SECONDS
5361     return $rc
5362 }
5363
5364 inodes_available () {
5365     local IFree=$($LFS df -i $MOUNT | grep ^$FSNAME | awk '{print $4}' | sort -un | head -1) || return 1
5366     echo $IFree
5367 }
5368
5369 mdsrate_inodes_available () {
5370     local min_inodes=$(inodes_available)
5371     echo $((min_inodes * 99 / 100))
5372 }
5373
5374 # reset llite stat counters
5375 clear_llite_stats(){
5376         lctl set_param -n llite.*.stats 0
5377 }
5378
5379 # sum llite stat items
5380 calc_llite_stats() {
5381         local res=$(lctl get_param -n llite.*.stats |
5382                     awk 'BEGIN {s = 0} END {print s} /^'"$1"'/ {s += $2}')
5383         echo $res
5384 }
5385
5386 # reset osc stat counters
5387 clear_osc_stats(){
5388         lctl set_param -n osc.*.osc_stats 0
5389 }
5390
5391 # sum osc stat items
5392 calc_osc_stats() {
5393         local res=$(lctl get_param -n osc.*.osc_stats |
5394                     awk 'BEGIN {s = 0} END {print s} /^'"$1"'/ {s += $2}')
5395         echo $res
5396 }
5397
5398 calc_sum () {
5399         awk 'BEGIN {s = 0}; {s += $1}; END {print s}'
5400 }
5401
5402 calc_osc_kbytes () {
5403         df $MOUNT > /dev/null
5404         $LCTL get_param -n osc.*[oO][sS][cC][-_][0-9a-f]*.$1 | calc_sum
5405 }
5406
5407 # save_lustre_params(comma separated facet list, parameter_mask)
5408 # generate a stream of formatted strings (<facet> <param name>=<param value>)
5409 save_lustre_params() {
5410         local facets=$1
5411         local facet
5412         local nodes
5413         local node
5414
5415         for facet in ${facets//,/ }; do
5416                 node=$(facet_active_host $facet)
5417                 [[ *\ $node\ * = " $nodes " ]] && continue
5418                 nodes="$nodes $node"
5419
5420                 do_node $node "$LCTL get_param $2 |
5421                         while read s; do echo $facet \\\$s; done"
5422         done
5423 }
5424
5425 # restore lustre parameters from input stream, produces by save_lustre_params
5426 restore_lustre_params() {
5427         local facet
5428         local name
5429         local val
5430
5431         while IFS=" =" read facet name val; do
5432                 do_facet $facet "$LCTL set_param -n $name $val"
5433         done
5434 }
5435
5436 check_catastrophe() {
5437         local rnodes=${1:-$(comma_list $(remote_nodes_list))}
5438         local C=$CATASTROPHE
5439         [ -f $C ] && [ $(cat $C) -ne 0 ] && return 1
5440
5441         [ -z "$rnodes" ] && return 0
5442
5443         local data
5444         data=$(do_nodes "$rnodes" "rc=\\\$([ -f $C ] &&
5445                 echo \\\$(< $C) || echo 0);
5446                 if [ \\\$rc -ne 0 ]; then echo \\\$(hostname): \\\$rc; fi
5447                 exit \\\$rc")
5448         local rc=$?
5449         if [ -n "$data" ]; then
5450             echo $data
5451             return $rc
5452         fi
5453         return 0
5454 }
5455
5456 # CMD: determine mds index where directory inode presents
5457 get_mds_dir () {
5458     local dir=$1
5459     local file=$dir/f0.get_mds_dir_tmpfile
5460
5461     mkdir -p $dir
5462     rm -f $file
5463     sleep 1
5464     local iused=$(lfs df -i $dir | grep MDT | awk '{print $3}')
5465     local -a oldused=($iused)
5466
5467     openfile -f O_CREAT:O_LOV_DELAY_CREATE -m 0644 $file > /dev/null
5468     sleep 1
5469     iused=$(lfs df -i $dir | grep MDT | awk '{print $3}')
5470     local -a newused=($iused)
5471
5472     local num=0
5473     for ((i=0; i<${#newused[@]}; i++)); do
5474          if [ ${oldused[$i]} -lt ${newused[$i]} ];  then
5475              echo $(( i + 1 ))
5476              rm -f $file
5477              return 0
5478          fi
5479     done
5480     error "mdt-s : inodes count OLD ${oldused[@]} NEW ${newused[@]}"
5481 }
5482
5483 mdsrate_cleanup () {
5484         if [ -d $4 ]; then
5485                 mpi_run ${MACHINEFILE_OPTION} $2 -np $1 ${MDSRATE} --unlink \
5486                         --nfiles $3 --dir $4 --filefmt $5 $6
5487                 rmdir $4
5488         fi
5489 }
5490
5491 delayed_recovery_enabled () {
5492     local var=${SINGLEMDS}_svc
5493     do_facet $SINGLEMDS lctl get_param -n mdd.${!var}.stale_export_age > /dev/null 2>&1
5494 }
5495
5496 ########################
5497
5498 convert_facet2label() {
5499     local facet=$1
5500
5501     if [ x$facet = xost ]; then
5502        facet=ost1
5503     fi
5504
5505     local varsvc=${facet}_svc
5506
5507     if [ -n ${!varsvc} ]; then
5508         echo ${!varsvc}
5509     else
5510         error "No lablel for $facet!"
5511     fi
5512 }
5513
5514 get_clientosc_proc_path() {
5515     echo "${1}-osc-*"
5516 }
5517
5518 get_lustre_version () {
5519     local facet=${1:-"$SINGLEMDS"}    
5520     do_facet $facet $LCTL get_param -n version | awk '/^lustre:/ {print $2}'
5521 }
5522
5523 lustre_version_code() {
5524     local facet=${1:-"$SINGLEMDS"}
5525     version_code $(get_lustre_version $1)
5526 }
5527
5528 # If the 2.0 MDS was mounted on 1.8 device, then the OSC and LOV names
5529 # used by MDT would not be changed.
5530 # mdt lov: fsname-mdtlov
5531 # mdt osc: fsname-OSTXXXX-osc
5532 mds_on_old_device() {
5533     local mds=${1:-"$SINGLEMDS"}
5534
5535     if [ $(lustre_version_code $mds) -gt $(version_code 1.9.0) ]; then
5536         do_facet $mds "lctl list_param osc.$FSNAME-OST*-osc \
5537             > /dev/null 2>&1" && return 0
5538     fi
5539     return 1
5540 }
5541
5542 get_mdtosc_proc_path() {
5543     local mds_facet=$1
5544     local ost_label=${2:-"*OST*"}
5545
5546     [ "$mds_facet" = "mds" ] && mds_facet=$SINGLEMDS
5547     local mdt_label=$(convert_facet2label $mds_facet)
5548     local mdt_index=$(echo $mdt_label | sed -e 's/^.*-//')
5549
5550     if [ $(lustre_version_code $mds_facet) -le $(version_code 1.8.0) ] ||
5551        mds_on_old_device $mds_facet; then
5552         echo "${ost_label}-osc"
5553     else
5554         echo "${ost_label}-osc-${mdt_index}"
5555     fi
5556 }
5557
5558 get_osc_import_name() {
5559     local facet=$1
5560     local ost=$2
5561     local label=$(convert_facet2label $ost)
5562
5563     if [ "${facet:0:3}" = "mds" ]; then
5564         get_mdtosc_proc_path $facet $label
5565         return 0
5566     fi
5567
5568     get_clientosc_proc_path $label
5569     return 0
5570 }
5571
5572 _wait_import_state () {
5573     local expected=$1
5574     local CONN_PROC=$2
5575     local maxtime=${3:-$(max_recovery_time)}
5576     local CONN_STATE
5577     local i=0
5578
5579         CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2 | uniq)
5580     while [ "${CONN_STATE}" != "${expected}" ]; do
5581         if [ "${expected}" == "DISCONN" ]; then
5582             # for disconn we can check after proc entry is removed
5583             [ "x${CONN_STATE}" == "x" ] && return 0
5584             #  with AT enabled, we can have connect request timeout near of
5585             # reconnect timeout and test can't see real disconnect
5586             [ "${CONN_STATE}" == "CONNECTING" ] && return 0
5587         fi
5588         [ $i -ge $maxtime ] && \
5589             error "can't put import for $CONN_PROC into ${expected} state after $i sec, have ${CONN_STATE}" && \
5590             return 1
5591         sleep 1
5592         # Add uniq for multi-mount case
5593         CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2 | uniq)
5594         i=$(($i + 1))
5595     done
5596
5597     log "$CONN_PROC in ${CONN_STATE} state after $i sec"
5598     return 0
5599 }
5600
5601 wait_import_state() {
5602     local state=$1
5603     local params=$2
5604     local maxtime=${3:-$(max_recovery_time)}
5605     local param
5606
5607     for param in ${params//,/ }; do
5608         _wait_import_state $state $param $maxtime || return
5609     done
5610 }
5611
5612 wait_import_state_mount() {
5613         if ! is_mounted $MOUNT && ! is_mounted $MOUNT2; then
5614                 return 0
5615         fi
5616
5617         wait_import_state $*
5618 }
5619
5620 # One client request could be timed out because server was not ready
5621 # when request was sent by client.
5622 # The request timeout calculation details :
5623 # ptl_send_rpc ()
5624 #      /* We give the server rq_timeout secs to process the req, and
5625 #      add the network latency for our local timeout. */
5626 #      request->rq_deadline = request->rq_sent + request->rq_timeout +
5627 #           ptlrpc_at_get_net_latency(request) ;
5628 #
5629 # ptlrpc_connect_import ()
5630 #      request->rq_timeout = INITIAL_CONNECT_TIMEOUT
5631 #
5632 # init_imp_at () ->
5633 #   -> at_init(&at->iat_net_latency, 0, 0) -> iat_net_latency=0
5634 # ptlrpc_at_get_net_latency(request) ->
5635 #       at_get (max (iat_net_latency=0, at_min)) = at_min
5636 #
5637 # i.e.:
5638 # request->rq_timeout + ptlrpc_at_get_net_latency(request) =
5639 # INITIAL_CONNECT_TIMEOUT + at_min
5640 #
5641 # We will use obd_timeout instead of INITIAL_CONNECT_TIMEOUT
5642 # because we can not get this value in runtime,
5643 # the value depends on configure options, and it is not stored in /proc.
5644 # obd_support.h:
5645 # #define CONNECTION_SWITCH_MIN 5U
5646 # #define INITIAL_CONNECT_TIMEOUT max(CONNECTION_SWITCH_MIN,obd_timeout/20)
5647
5648 request_timeout () {
5649     local facet=$1
5650
5651     # request->rq_timeout = INITIAL_CONNECT_TIMEOUT
5652     local init_connect_timeout=$TIMEOUT
5653     [[ $init_connect_timeout -ge 5 ]] || init_connect_timeout=5
5654
5655     local at_min=$(at_get $facet at_min)
5656
5657     echo $(( init_connect_timeout + at_min ))
5658 }
5659
5660 _wait_osc_import_state() {
5661         local facet=$1
5662         local ost_facet=$2
5663         local expected=$3
5664         local ost=$(get_osc_import_name $facet $ost_facet)
5665         local param="osc.${ost}.ost_server_uuid"
5666         local params=$param
5667         local i=0
5668
5669         # 1. wait the deadline of client 1st request (it could be skipped)
5670         # 2. wait the deadline of client 2nd request
5671         local maxtime=$(( 2 * $(request_timeout $facet)))
5672
5673         if [[ $facet == client* ]]; then
5674                 # During setup time, the osc might not be setup, it need wait
5675                 # until list_param can return valid value. And also if there
5676                 # are mulitple osc entries we should list all of them before
5677                 # go to wait.
5678                 params=$($LCTL list_param $param 2>/dev/null || true)
5679                 while [ -z "$params" ]; do
5680                         if [ $i -ge $maxtime ]; then
5681                                 echo "can't get $param in $maxtime secs"
5682                                 return 1
5683                         fi
5684                         sleep 1
5685                         i=$((i + 1))
5686                         params=$($LCTL list_param $param 2>/dev/null || true)
5687                 done
5688         fi
5689         if ! do_rpc_nodes "$(facet_active_host $facet)" \
5690                         wait_import_state $expected "$params" $maxtime; then
5691                 error "import is not in ${expected} state"
5692                 return 1
5693         fi
5694
5695         return 0
5696 }
5697
5698 wait_osc_import_state() {
5699         local facet=$1
5700         local ost_facet=$2
5701         local expected=$3
5702         local num
5703
5704         if [[ $facet = mds ]]; then
5705                 for num in $(seq $MDSCOUNT); do
5706                         _wait_osc_import_state mds$num "$ost_facet" "$expected"
5707                 done
5708         else
5709                 _wait_osc_import_state "$facet" "$ost_facet" "$expected"
5710         fi
5711 }
5712
5713 get_clientmdc_proc_path() {
5714     echo "${1}-mdc-*"
5715 }
5716
5717 do_rpc_nodes () {
5718         local list=$1
5719         shift
5720
5721         [ -z "$list" ] && return 0
5722
5723         # Add paths to lustre tests for 32 and 64 bit systems.
5724         local LIBPATH="/usr/lib/lustre/tests:/usr/lib64/lustre/tests:"
5725         local TESTPATH="$RLUSTRE/tests:"
5726         local RPATH="PATH=${TESTPATH}${LIBPATH}${PATH}:/sbin:/bin:/usr/sbin:"
5727         do_nodesv $list "${RPATH} NAME=${NAME} sh rpc.sh $@ "
5728 }
5729
5730 wait_clients_import_state () {
5731     local list=$1
5732     local facet=$2
5733     local expected=$3
5734
5735     local facets=$facet
5736
5737     if [ "$FAILURE_MODE" = HARD ]; then
5738         facets=$(facets_on_host $(facet_active_host $facet))
5739     fi
5740
5741     for facet in ${facets//,/ }; do
5742     local label=$(convert_facet2label $facet)
5743     local proc_path
5744     case $facet in
5745         ost* ) proc_path="osc.$(get_clientosc_proc_path $label).ost_server_uuid" ;;
5746         mds* ) proc_path="mdc.$(get_clientmdc_proc_path $label).mds_server_uuid" ;;
5747         *) error "unknown facet!" ;;
5748     esac
5749     local params=$(expand_list $params $proc_path)
5750     done
5751
5752         if ! do_rpc_nodes "$list" wait_import_state_mount $expected $params; then
5753                 error "import is not in ${expected} state"
5754                 return 1
5755         fi
5756 }
5757
5758 oos_full() {
5759         local -a AVAILA
5760         local -a GRANTA
5761         local -a TOTALA
5762         local OSCFULL=1
5763         AVAILA=($(do_nodes $(comma_list $(osts_nodes)) \
5764                   $LCTL get_param obdfilter.*.kbytesavail))
5765         GRANTA=($(do_nodes $(comma_list $(osts_nodes)) \
5766                   $LCTL get_param -n obdfilter.*.tot_granted))
5767         TOTALA=($(do_nodes $(comma_list $(osts_nodes)) \
5768                   $LCTL get_param -n obdfilter.*.kbytestotal))
5769         for ((i=0; i<${#AVAILA[@]}; i++)); do
5770                 local -a AVAIL1=(${AVAILA[$i]//=/ })
5771                 local -a TOTAL=(${TOTALA[$i]//=/ })
5772                 GRANT=$((${GRANTA[$i]}/1024))
5773                 # allow 1% of total space in bavail because of delayed
5774                 # allocation with ZFS which might release some free space after
5775                 # txg commit.  For small devices, we set a mininum of 8MB
5776                 local LIMIT=$((${TOTAL} / 100 + 8000))
5777                 echo -n $(echo ${AVAIL1[0]} | cut -d"." -f2) avl=${AVAIL1[1]} \
5778                         grnt=$GRANT diff=$((AVAIL1[1] - GRANT)) limit=${LIMIT}
5779                 [ $((AVAIL1[1] - GRANT)) -lt $LIMIT ] && OSCFULL=0 && \
5780                         echo " FULL" || echo
5781         done
5782         return $OSCFULL
5783 }
5784
5785 pool_list () {
5786    do_facet mgs lctl pool_list $1
5787 }
5788
5789 create_pool() {
5790     local fsname=${1%%.*}
5791     local poolname=${1##$fsname.}
5792
5793     do_facet mgs lctl pool_new $1
5794     local RC=$?
5795     # get param should return err unless pool is created
5796     [[ $RC -ne 0 ]] && return $RC
5797
5798     wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
5799         2>/dev/null || echo foo" "" || RC=1
5800     if [[ $RC -eq 0 ]]; then
5801         add_pool_to_list $1
5802     else
5803         error "pool_new failed $1"
5804     fi
5805     return $RC
5806 }
5807
5808 add_pool_to_list () {
5809     local fsname=${1%%.*}
5810     local poolname=${1##$fsname.}
5811
5812     local listvar=${fsname}_CREATED_POOLS
5813     eval export ${listvar}=$(expand_list ${!listvar} $poolname)
5814 }
5815
5816 remove_pool_from_list () {
5817     local fsname=${1%%.*}
5818     local poolname=${1##$fsname.}
5819
5820     local listvar=${fsname}_CREATED_POOLS
5821     eval export ${listvar}=$(exclude_items_from_list ${!listvar} $poolname)
5822 }
5823
5824 destroy_pool_int() {
5825     local ost
5826     local OSTS=$(do_facet $SINGLEMDS lctl pool_list $1 | \
5827         awk '$1 !~ /^Pool:/ {print $1}')
5828     for ost in $OSTS; do
5829         do_facet mgs lctl pool_remove $1 $ost
5830     done
5831     do_facet mgs lctl pool_destroy $1
5832 }
5833
5834 # <fsname>.<poolname> or <poolname>
5835 destroy_pool() {
5836     local fsname=${1%%.*}
5837     local poolname=${1##$fsname.}
5838
5839     [[ x$fsname = x$poolname ]] && fsname=$FSNAME
5840
5841     local RC
5842
5843     pool_list $fsname.$poolname || return $?
5844
5845     destroy_pool_int $fsname.$poolname
5846     RC=$?
5847     [[ $RC -ne 0 ]] && return $RC
5848
5849     wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
5850       2>/dev/null || echo foo" "foo" || RC=1
5851
5852     if [[ $RC -eq 0 ]]; then
5853         remove_pool_from_list $fsname.$poolname
5854     else
5855         error "destroy pool failed $1"
5856     fi
5857     return $RC
5858 }
5859
5860 destroy_pools () {
5861     local fsname=${1:-$FSNAME}
5862     local poolname
5863     local listvar=${fsname}_CREATED_POOLS
5864
5865     pool_list $fsname
5866
5867     [ x${!listvar} = x ] && return 0
5868
5869     echo destroy the created pools: ${!listvar}
5870     for poolname in ${!listvar//,/ }; do
5871         destroy_pool $fsname.$poolname
5872     done
5873 }
5874
5875 cleanup_pools () {
5876     local fsname=${1:-$FSNAME}
5877     trap 0
5878     destroy_pools $fsname
5879 }
5880
5881 gather_logs () {
5882     local list=$1
5883
5884     local ts=$(date +%s)
5885     local docp=true
5886
5887     if [[ ! -f "$YAML_LOG" ]]; then
5888         # init_logging is not performed before gather_logs,
5889         # so the $LOGDIR needs to be checked here
5890         check_shared_dir $LOGDIR && touch $LOGDIR/shared
5891     fi
5892
5893     [ -f $LOGDIR/shared ] && docp=false
5894
5895     # dump lustre logs, dmesg
5896
5897     prefix="$TESTLOG_PREFIX.$TESTNAME"
5898     suffix="$ts.log"
5899     echo "Dumping lctl log to ${prefix}.*.${suffix}"
5900
5901     if [ "$CLIENTONLY" -o "$PDSH" == "no_dsh" ]; then
5902         echo "Dumping logs only on local client."
5903         $LCTL dk > ${prefix}.debug_log.$(hostname -s).${suffix}
5904         dmesg > ${prefix}.dmesg.$(hostname -s).${suffix}
5905         return
5906     fi
5907
5908     do_nodesv $list \
5909         "$LCTL dk > ${prefix}.debug_log.\\\$(hostname -s).${suffix};
5910          dmesg > ${prefix}.dmesg.\\\$(hostname -s).${suffix}"
5911     if [ ! -f $LOGDIR/shared ]; then
5912         do_nodes $list rsync -az "${prefix}.*.${suffix}" $HOSTNAME:$LOGDIR
5913     fi
5914 }
5915
5916 do_ls () {
5917     local mntpt_root=$1
5918     local num_mntpts=$2
5919     local dir=$3
5920     local i
5921     local cmd
5922     local pids
5923     local rc=0
5924
5925     for i in $(seq 0 $num_mntpts); do
5926         cmd="ls -laf ${mntpt_root}$i/$dir"
5927         echo + $cmd;
5928         $cmd > /dev/null &
5929         pids="$pids $!"
5930     done
5931     echo pids=$pids
5932     for pid in $pids; do
5933         wait $pid || rc=$?
5934     done
5935
5936     return $rc
5937 }
5938
5939 # target_start_and_reset_recovery_timer()
5940 #        service_time = at_est2timeout(service_time);
5941 #        service_time += 2 * (CONNECTION_SWITCH_MAX + CONNECTION_SWITCH_INC +
5942 #                             INITIAL_CONNECT_TIMEOUT);
5943 # CONNECTION_SWITCH_MAX : min(25U, max(CONNECTION_SWITCH_MIN,obd_timeout))
5944 #define CONNECTION_SWITCH_INC 1
5945 #define INITIAL_CONNECT_TIMEOUT max(CONNECTION_SWITCH_MIN,obd_timeout/20)
5946 #define CONNECTION_SWITCH_MIN 5U
5947
5948 max_recovery_time () {
5949     local init_connect_timeout=$(( TIMEOUT / 20 ))
5950     [[ $init_connect_timeout -ge 5 ]] || init_connect_timeout=5
5951
5952     local service_time=$(( $(at_max_get client) + $(( 2 * $(( 25 + 1  + init_connect_timeout)) )) ))
5953
5954     echo $service_time 
5955 }
5956
5957 get_clients_mount_count () {
5958     local clients=${CLIENTS:-`hostname`}
5959
5960     # we need to take into account the clients mounts and
5961     # exclude mds/ost mounts if any;
5962     do_nodes $clients cat /proc/mounts | grep lustre | grep $MOUNT | wc -l
5963 }
5964
5965 # gss functions
5966 PROC_CLI="srpc_info"
5967
5968 combination()
5969 {
5970     local M=$1
5971     local N=$2
5972     local R=1
5973
5974     if [ $M -lt $N ]; then
5975         R=0
5976     else
5977         N=$((N + 1))
5978         while [ $N -lt $M ]; do
5979             R=$((R * N))
5980             N=$((N + 1))
5981         done
5982     fi
5983
5984     echo $R
5985     return 0
5986 }
5987
5988 calc_connection_cnt() {
5989     local dir=$1
5990
5991     # MDT->MDT = 2 * C(M, 2)
5992     # MDT->OST = M * O
5993     # CLI->OST = C * O
5994     # CLI->MDT = C * M
5995     comb_m2=$(combination $MDSCOUNT 2)
5996
5997     local num_clients=$(get_clients_mount_count)
5998
5999     local cnt_mdt2mdt=$((comb_m2 * 2))
6000     local cnt_mdt2ost=$((MDSCOUNT * OSTCOUNT))
6001     local cnt_cli2ost=$((num_clients * OSTCOUNT))
6002     local cnt_cli2mdt=$((num_clients * MDSCOUNT))
6003     local cnt_all2ost=$((cnt_mdt2ost + cnt_cli2ost))
6004     local cnt_all2mdt=$((cnt_mdt2mdt + cnt_cli2mdt))
6005     local cnt_all2all=$((cnt_mdt2ost + cnt_mdt2mdt + cnt_cli2ost + cnt_cli2mdt))
6006
6007     local var=cnt_$dir
6008     local res=${!var}
6009
6010     echo $res
6011 }
6012
6013 set_rule()
6014 {
6015     local tgt=$1
6016     local net=$2
6017     local dir=$3
6018     local flavor=$4
6019     local cmd="$tgt.srpc.flavor"
6020
6021     if [ $net == "any" ]; then
6022         net="default"
6023     fi
6024     cmd="$cmd.$net"
6025
6026     if [ $dir != "any" ]; then
6027         cmd="$cmd.$dir"
6028     fi
6029
6030     cmd="$cmd=$flavor"
6031     log "Setting sptlrpc rule: $cmd"
6032     do_facet mgs "$LCTL conf_param $cmd"
6033 }
6034
6035 count_flvr()
6036 {
6037     local output=$1
6038     local flavor=$2
6039     local count=0
6040
6041     rpc_flvr=`echo $flavor | awk -F - '{ print $1 }'`
6042     bulkspec=`echo $flavor | awk -F - '{ print $2 }'`
6043
6044     count=`echo "$output" | grep "rpc flavor" | grep $rpc_flvr | wc -l`
6045
6046     if [ "x$bulkspec" != "x" ]; then
6047         algs=`echo $bulkspec | awk -F : '{ print $2 }'`
6048
6049         if [ "x$algs" != "x" ]; then
6050             bulk_count=`echo "$output" | grep "bulk flavor" | grep $algs | wc -l`
6051         else
6052             bulk=`echo $bulkspec | awk -F : '{ print $1 }'`
6053             if [ $bulk == "bulkn" ]; then
6054                 bulk_count=`echo "$output" | grep "bulk flavor" \
6055                             | grep "null/null" | wc -l`
6056             elif [ $bulk == "bulki" ]; then
6057                 bulk_count=`echo "$output" | grep "bulk flavor" \
6058                             | grep "/null" | grep -v "null/" | wc -l`
6059             else
6060                 bulk_count=`echo "$output" | grep "bulk flavor" \
6061                             | grep -v "/null" | grep -v "null/" | wc -l`
6062             fi
6063         fi
6064
6065         [ $bulk_count -lt $count ] && count=$bulk_count
6066     fi
6067
6068     echo $count
6069 }
6070
6071 flvr_cnt_cli2mdt()
6072 {
6073     local flavor=$1
6074     local cnt
6075
6076     local clients=${CLIENTS:-`hostname`}
6077
6078     for c in ${clients//,/ }; do
6079         output=`do_node $c lctl get_param -n mdc.*-MDT*-mdc-*.$PROC_CLI 2>/dev/null`
6080         tmpcnt=`count_flvr "$output" $flavor`
6081         cnt=$((cnt + tmpcnt))
6082     done
6083     echo $cnt
6084 }
6085
6086 flvr_cnt_cli2ost()
6087 {
6088     local flavor=$1
6089     local cnt
6090
6091     local clients=${CLIENTS:-`hostname`}
6092
6093     for c in ${clients//,/ }; do
6094         output=`do_node $c lctl get_param -n osc.*OST*-osc-[^M][^D][^T]*.$PROC_CLI 2>/dev/null`
6095         tmpcnt=`count_flvr "$output" $flavor`
6096         cnt=$((cnt + tmpcnt))
6097     done
6098     echo $cnt
6099 }
6100
6101 flvr_cnt_mdt2mdt()
6102 {
6103     local flavor=$1
6104     local cnt=0
6105
6106     if [ $MDSCOUNT -le 1 ]; then
6107         echo 0
6108         return
6109     fi
6110
6111     for num in `seq $MDSCOUNT`; do
6112         output=`do_facet mds$num lctl get_param -n mdc.*-MDT*-mdc[0-9]*.$PROC_CLI 2>/dev/null`
6113         tmpcnt=`count_flvr "$output" $flavor`
6114         cnt=$((cnt + tmpcnt))
6115     done
6116     echo $cnt;
6117 }
6118
6119 flvr_cnt_mdt2ost()
6120 {
6121     local flavor=$1
6122     local cnt=0
6123     local mdtosc
6124
6125     for num in `seq $MDSCOUNT`; do
6126         mdtosc=$(get_mdtosc_proc_path mds$num)
6127         mdtosc=${mdtosc/-MDT*/-MDT\*}
6128         output=$(do_facet mds$num lctl get_param -n \
6129             osc.$mdtosc.$PROC_CLI 2>/dev/null)
6130         tmpcnt=`count_flvr "$output" $flavor`
6131         cnt=$((cnt + tmpcnt))
6132     done
6133     echo $cnt;
6134 }
6135
6136 flvr_cnt_mgc2mgs()
6137 {
6138     local flavor=$1
6139
6140     output=`do_facet client lctl get_param -n mgc.*.$PROC_CLI 2>/dev/null`
6141     count_flvr "$output" $flavor
6142 }
6143
6144 do_check_flavor()
6145 {
6146     local dir=$1        # from to
6147     local flavor=$2     # flavor expected
6148     local res=0
6149
6150     if [ $dir == "cli2mdt" ]; then
6151         res=`flvr_cnt_cli2mdt $flavor`
6152     elif [ $dir == "cli2ost" ]; then
6153         res=`flvr_cnt_cli2ost $flavor`
6154     elif [ $dir == "mdt2mdt" ]; then
6155         res=`flvr_cnt_mdt2mdt $flavor`
6156     elif [ $dir == "mdt2ost" ]; then
6157         res=`flvr_cnt_mdt2ost $flavor`
6158     elif [ $dir == "all2ost" ]; then
6159         res1=`flvr_cnt_mdt2ost $flavor`
6160         res2=`flvr_cnt_cli2ost $flavor`
6161         res=$((res1 + res2))
6162     elif [ $dir == "all2mdt" ]; then
6163         res1=`flvr_cnt_mdt2mdt $flavor`
6164         res2=`flvr_cnt_cli2mdt $flavor`
6165         res=$((res1 + res2))
6166     elif [ $dir == "all2all" ]; then
6167         res1=`flvr_cnt_mdt2ost $flavor`
6168         res2=`flvr_cnt_cli2ost $flavor`
6169         res3=`flvr_cnt_mdt2mdt $flavor`
6170         res4=`flvr_cnt_cli2mdt $flavor`
6171         res=$((res1 + res2 + res3 + res4))
6172     fi
6173
6174     echo $res
6175 }
6176
6177 wait_flavor()
6178 {
6179     local dir=$1        # from to
6180     local flavor=$2     # flavor expected
6181     local expect=${3:-$(calc_connection_cnt $dir)}     # number expected
6182
6183     local res=0
6184
6185     for ((i=0;i<20;i++)); do
6186         echo -n "checking $dir..."
6187         res=$(do_check_flavor $dir $flavor)
6188         echo "found $res/$expect $flavor connections"
6189         [ $res -ge $expect ] && return 0
6190         sleep 4
6191     done
6192
6193     echo "Error checking $flavor of $dir: expect $expect, actual $res"
6194     return 1
6195 }
6196
6197 restore_to_default_flavor()
6198 {
6199     local proc="mgs.MGS.live.$FSNAME"
6200
6201     echo "restoring to default flavor..."
6202
6203     nrule=`do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor." | wc -l`
6204
6205     # remove all existing rules if any
6206     if [ $nrule -ne 0 ]; then
6207         echo "$nrule existing rules"
6208         for rule in `do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor."`; do
6209             echo "remove rule: $rule"
6210             spec=`echo $rule | awk -F = '{print $1}'`
6211             do_facet mgs "$LCTL conf_param -d $spec"
6212         done
6213     fi
6214
6215     # verify no rules left
6216     nrule=`do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor." | wc -l`
6217     [ $nrule -ne 0 ] && error "still $nrule rules left"
6218
6219     # wait for default flavor to be applied
6220     # currently default flavor for all connections are 'null'
6221     wait_flavor all2all null
6222     echo "now at default flavor settings"
6223 }
6224
6225 set_flavor_all()
6226 {
6227     local flavor=${1:-null}
6228
6229     echo "setting all flavor to $flavor"
6230
6231     # FIXME need parameter to this fn
6232     # and remove global vars
6233     local cnt_all2all=$(calc_connection_cnt all2all)
6234
6235     local res=$(do_check_flavor all2all $flavor)
6236     if [ $res -eq $cnt_all2all ]; then
6237         echo "already have total $res $flavor connections"
6238         return
6239     fi
6240
6241     echo "found $res $flavor out of total $cnt_all2all connections"
6242     restore_to_default_flavor
6243
6244     [[ $flavor = null ]] && return 0
6245
6246     set_rule $FSNAME any any $flavor
6247     wait_flavor all2all $flavor
6248 }
6249
6250
6251 check_logdir() {
6252     local dir=$1
6253     # Checking for shared logdir
6254     if [ ! -d $dir ]; then
6255         # Not found. Create local logdir
6256         mkdir -p $dir
6257     else
6258         touch $dir/check_file.$(hostname -s)
6259     fi
6260     return 0
6261 }
6262
6263 check_write_access() {
6264         local dir=$1
6265         local list=${2:-$(comma_list $(nodes_list))}
6266         local node
6267         local file
6268
6269         for node in ${list//,/ }; do
6270                 file=$dir/check_file.$(short_nodename $node)
6271                 if [[ ! -f "$file" ]]; then
6272                         # Logdir not accessible/writable from this node.
6273                         return 1
6274                 fi
6275                 rm -f $file || return 1
6276         done
6277         return 0
6278 }
6279
6280 init_logging() {
6281     if [[ -n $YAML_LOG ]]; then
6282         return
6283     fi
6284     local SAVE_UMASK=`umask`
6285     umask 0000
6286
6287     export YAML_LOG=${LOGDIR}/results.yml
6288     mkdir -p $LOGDIR
6289     init_clients_lists
6290
6291     if [ ! -f $YAML_LOG ]; then       # If the yaml log already exists then we will just append to it
6292       if check_shared_dir $LOGDIR; then
6293           touch $LOGDIR/shared
6294           echo "Logging to shared log directory: $LOGDIR"
6295       else
6296           echo "Logging to local directory: $LOGDIR"
6297       fi
6298
6299       yml_nodes_file $LOGDIR >> $YAML_LOG
6300       yml_results_file >> $YAML_LOG
6301     fi
6302
6303     umask $SAVE_UMASK
6304 }
6305
6306 log_test() {
6307     yml_log_test $1 >> $YAML_LOG
6308 }
6309
6310 log_test_status() {
6311      yml_log_test_status $@ >> $YAML_LOG
6312 }
6313
6314 log_sub_test_begin() {
6315     yml_log_sub_test_begin "$@" >> $YAML_LOG
6316 }
6317
6318 log_sub_test_end() {
6319     yml_log_sub_test_end "$@" >> $YAML_LOG
6320 }
6321
6322 run_llverdev()
6323 {
6324         local dev=$1
6325         local llverdev_opts=$2
6326         local devname=$(basename $1)
6327         local size=$(grep "$devname"$ /proc/partitions | awk '{print $3}')
6328         # loop devices aren't in /proc/partitions
6329         [ "x$size" == "x" ] && local size=$(ls -l $dev | awk '{print $5}')
6330
6331         size=$(($size / 1024 / 1024)) # Gb
6332
6333         local partial_arg=""
6334         # Run in partial (fast) mode if the size
6335         # of a partition > 1 GB
6336         [ $size -gt 1 ] && partial_arg="-p"
6337
6338         llverdev --force $partial_arg $llverdev_opts $dev
6339 }
6340
6341 run_llverfs()
6342 {
6343         local dir=$1
6344         local llverfs_opts=$2
6345         local use_partial_arg=$3
6346         local partial_arg=""
6347         local size=$(df -B G $dir |tail -n 1 |awk '{print $2}' |sed 's/G//') #GB
6348
6349         # Run in partial (fast) mode if the size
6350         # of a partition > 1 GB
6351         [ "x$use_partial_arg" != "xno" ] && [ $size -gt 1 ] && partial_arg="-p"
6352
6353         llverfs $partial_arg $llverfs_opts $dir
6354 }
6355
6356 #Remove objects from OST
6357 remove_ost_objects() {
6358         local facet=$1
6359         local ostdev=$2
6360         local group=$3
6361         shift 3
6362         local objids="$@"
6363         local mntpt=$(facet_mntpt $facet)
6364         local opts=$OST_MOUNT_OPTS
6365         local i
6366         local rc
6367
6368         echo "removing objects from $ostdev on $facet: $objids"
6369         if ! test -b $ostdev; then
6370                 opts=$(csa_add "$opts" -o loop)
6371         fi
6372         mount -t $(facet_fstype $facet) $opts $ostdev $mntpt ||
6373                 return $?
6374         rc=0
6375         for i in $objids; do
6376                 rm $mntpt/O/$group/d$((i % 32))/$i || { rc=$?; break; }
6377         done
6378         umount -f $mntpt || return $?
6379         return $rc
6380 }
6381
6382 #Remove files from MDT
6383 remove_mdt_files() {
6384         local facet=$1
6385         local mdtdev=$2
6386         shift 2
6387         local files="$@"
6388         local mntpt=$(facet_mntpt $facet)
6389         local opts=$MDS_MOUNT_OPTS
6390
6391         echo "removing files from $mdtdev on $facet: $files"
6392         if [ $(facet_fstype $facet) == ldiskfs ] &&
6393            ! do_facet $facet test -b $mdtdev; then
6394                 opts=$(csa_add "$opts" -o loop)
6395         fi
6396         mount -t $(facet_fstype $facet) $opts $mdtdev $mntpt ||
6397                 return $?
6398         rc=0
6399         for f in $files; do
6400                 rm $mntpt/ROOT/$f || { rc=$?; break; }
6401         done
6402         umount -f $mntpt || return $?
6403         return $rc
6404 }
6405
6406 duplicate_mdt_files() {
6407         local facet=$1
6408         local mdtdev=$2
6409         shift 2
6410         local files="$@"
6411         local mntpt=$(facet_mntpt $facet)
6412         local opts=$MDS_MOUNT_OPTS
6413
6414         echo "duplicating files on $mdtdev on $facet: $files"
6415         mkdir -p $mntpt || return $?
6416         if [ $(facet_fstype $facet) == ldiskfs ] &&
6417            ! do_facet $facet test -b $mdtdev; then
6418                 opts=$(csa_add "$opts" -o loop)
6419         fi
6420         mount -t $(facet_fstype $facet) $opts $mdtdev $mntpt ||
6421                 return $?
6422
6423     do_umount() {
6424         trap 0
6425         popd > /dev/null
6426         rm $tmp
6427         umount -f $mntpt
6428     }
6429     trap do_umount EXIT
6430
6431     tmp=$(mktemp $TMP/setfattr.XXXXXXXXXX)
6432     pushd $mntpt/ROOT > /dev/null || return $?
6433     rc=0
6434     for f in $files; do
6435         touch $f.bad || return $?
6436         getfattr -n trusted.lov $f | sed "s#$f#&.bad#" > $tmp
6437         rc=${PIPESTATUS[0]}
6438         [ $rc -eq 0 ] || return $rc
6439         setfattr --restore $tmp || return $?
6440     done
6441     do_umount
6442 }
6443
6444 run_sgpdd () {
6445     local devs=${1//,/ }
6446     shift
6447     local params=$@
6448     local rslt=$TMP/sgpdd_survey
6449
6450     # sgpdd-survey cleanups ${rslt}.* files
6451
6452     local cmd="rslt=$rslt $params scsidevs=\"$devs\" $SGPDDSURVEY"
6453     echo + $cmd
6454     eval $cmd
6455     cat ${rslt}.detail
6456 }
6457
6458 # returns the canonical name for an ldiskfs device
6459 ldiskfs_canon() {
6460         local dev="$1"
6461         local facet="$2"
6462
6463         do_facet $facet "dv=\\\$(lctl get_param -n $dev);
6464 if foo=\\\$(lvdisplay -c \\\$dv 2>/dev/null); then
6465     echo dm-\\\${foo##*:};
6466 else
6467     echo \\\$(basename \\\$dv);
6468 fi;"
6469 }
6470
6471 is_sanity_benchmark() {
6472     local benchmarks="dbench bonnie iozone fsx"
6473     local suite=$1
6474     for b in $benchmarks; do
6475         if [ "$b" == "$suite" ]; then
6476             return 0
6477         fi
6478     done
6479     return 1
6480 }
6481
6482 min_ost_size () {
6483     $LCTL get_param -n osc.*.kbytesavail | sort -n | head -n1
6484 }
6485
6486 #
6487 # Get the available size (KB) of a given obd target.
6488 #
6489 get_obd_size() {
6490         local facet=$1
6491         local obd=$2
6492         local size
6493
6494         [[ $facet != client ]] || return 0
6495
6496         size=$(do_facet $facet $LCTL get_param -n *.$obd.kbytesavail | head -n1)
6497         echo -n $size
6498 }
6499
6500 #
6501 # Get the page size (bytes) on a given facet node.
6502 #
6503 get_page_size() {
6504         local facet=$1
6505         local size
6506
6507         size=$(do_facet $facet getconf PAGE_SIZE)
6508         [[ ${PIPESTATUS[0]} = 0 && -n "$size" ]] || size=4096
6509         echo -n $size
6510 }
6511
6512 #
6513 # Get the block count of the filesystem.
6514 #
6515 get_block_count() {
6516         local facet=$1
6517         local device=$2
6518         local count
6519
6520         count=$(do_facet $facet "$DUMPE2FS -h $device 2>&1" |
6521                 awk '/^Block count:/ {print $3}')
6522         echo -n $count
6523 }
6524
6525 # Get the block size of the filesystem.
6526 get_block_size() {
6527     local facet=$1
6528     local device=$2
6529     local size
6530
6531     size=$(do_facet $facet "$DUMPE2FS -h $device 2>&1" |
6532            awk '/^Block size:/ {print $3}')
6533     echo $size
6534 }
6535
6536 # Check whether the "large_xattr" feature is enabled or not.
6537 large_xattr_enabled() {
6538         [[ $(facet_fstype $SINGLEMDS) == zfs ]] && return 0
6539
6540         local mds_dev=$(mdsdevname ${SINGLEMDS//mds/})
6541
6542         do_facet $SINGLEMDS "$DUMPE2FS -h $mds_dev 2>&1 |
6543                 grep -E -q '(ea_inode|large_xattr)'"
6544         return ${PIPESTATUS[0]}
6545 }
6546
6547 # Get the maximum xattr size supported by the filesystem.
6548 max_xattr_size() {
6549     local size
6550
6551     if large_xattr_enabled; then
6552         # include/linux/limits.h: #define XATTR_SIZE_MAX 65536
6553         size=65536
6554     else
6555         local mds_dev=$(mdsdevname ${SINGLEMDS//mds/})
6556         local block_size=$(get_block_size $SINGLEMDS $mds_dev)
6557
6558         # maximum xattr size = size of block - size of header -
6559         #                      size of 1 entry - 4 null bytes
6560         size=$((block_size - 32 - 32 - 4))
6561     fi
6562
6563     echo $size
6564 }
6565
6566 # Dump the value of the named xattr from a file.
6567 get_xattr_value() {
6568     local xattr_name=$1
6569     local file=$2
6570
6571     echo "$(getfattr -n $xattr_name --absolute-names --only-values $file)"
6572 }
6573
6574 # Generate a string with size of $size bytes.
6575 generate_string() {
6576     local size=${1:-1024} # in bytes
6577
6578     echo "$(head -c $size < /dev/zero | tr '\0' y)"
6579 }
6580
6581 reformat_external_journal() {
6582         local facet=$1
6583
6584         if [ ! -z ${EJOURNAL} ]; then
6585                 local rcmd="do_facet $facet"
6586
6587                 echo "reformat external journal on $facet:${EJOURNAL}"
6588                 ${rcmd} mke2fs -O journal_dev ${EJOURNAL} || return 1
6589         fi
6590 }
6591
6592 # MDT file-level backup/restore
6593 mds_backup_restore() {
6594         local facet=$1
6595         local igif=$2
6596         local devname=$(mdsdevname $(facet_number $facet))
6597         local mntpt=$(facet_mntpt brpt)
6598         local rcmd="do_facet $facet"
6599         local metaea=${TMP}/backup_restore.ea
6600         local metadata=${TMP}/backup_restore.tgz
6601         local opts=${MDS_MOUNT_OPTS}
6602         local svc=${facet}_svc
6603
6604         if ! ${rcmd} test -b ${devname}; then
6605                 opts=$(csa_add "$opts" -o loop)
6606         fi
6607
6608         echo "file-level backup/restore on $facet:${devname}"
6609
6610         # step 1: build mount point
6611         ${rcmd} mkdir -p $mntpt
6612         # step 2: cleanup old backup
6613         ${rcmd} rm -f $metaea $metadata
6614         # step 3: mount dev
6615         ${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 1
6616         if [ ! -z $igif ]; then
6617                 # step 3.5: rm .lustre
6618                 ${rcmd} rm -rf $mntpt/ROOT/.lustre || return 1
6619         fi
6620         # step 4: backup metaea
6621         echo "backup EA"
6622         ${rcmd} "cd $mntpt && getfattr -R -d -m '.*' -P . > $metaea && cd -" ||
6623                 return 2
6624         # step 5: backup metadata
6625         echo "backup data"
6626         ${rcmd} tar zcf $metadata -C $mntpt/ . > /dev/null 2>&1 || return 3
6627         # step 6: umount
6628         ${rcmd} umount -d $mntpt || return 4
6629         # step 7: reformat external journal if needed
6630         reformat_external_journal $facet || return 5
6631         # step 8: reformat dev
6632         echo "reformat new device"
6633         add $facet $(mkfs_opts $facet ${devname}) --backfstype ldiskfs \
6634                 --reformat ${devname} $(mdsvdevname $(facet_number $facet)) \
6635                 > /dev/null || exit 6
6636         # step 9: mount dev
6637         ${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 7
6638         # step 10: restore metadata
6639         echo "restore data"
6640         ${rcmd} tar zxfp $metadata -C $mntpt > /dev/null 2>&1 || return 8
6641         # step 11: restore metaea
6642         echo "restore EA"
6643         ${rcmd} "cd $mntpt && setfattr --restore=$metaea && cd - " || return 9
6644         # step 12: remove recovery logs
6645         echo "remove recovery logs"
6646         ${rcmd} rm -fv $mntpt/OBJECTS/* $mntpt/CATALOGS
6647         # step 13: umount dev
6648         ${rcmd} umount -d $mntpt || return 10
6649         # step 14: cleanup tmp backup
6650         ${rcmd} rm -f $metaea $metadata
6651         # step 15: reset device label - it's not virgin on
6652         ${rcmd} e2label $devname ${!svc}
6653 }
6654
6655 # remove OI files
6656 mds_remove_ois() {
6657         local facet=$1
6658         local idx=$2
6659         local devname=$(mdsdevname $(facet_number $facet))
6660         local mntpt=$(facet_mntpt brpt)
6661         local rcmd="do_facet $facet"
6662         local opts=${MDS_MOUNT_OPTS}
6663
6664         if ! ${rcmd} test -b ${devname}; then
6665                 opts=$(csa_add "$opts" -o loop)
6666         fi
6667
6668         echo "removing OI files on $facet: idx=${idx}"
6669
6670         # step 1: build mount point
6671         ${rcmd} mkdir -p $mntpt
6672         # step 2: mount dev
6673         ${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 1
6674         if [ -z $idx ]; then
6675                 # step 3: remove all OI files
6676                 ${rcmd} rm -fv $mntpt/oi.16*
6677         elif [ $idx -lt 2 ]; then
6678                 ${rcmd} rm -fv $mntpt/oi.16.${idx}
6679         else
6680                 local i
6681
6682                 # others, rm oi.16.[idx, idx * idx, idx ** ...]
6683                 for ((i=${idx}; i<64; i=$((i * idx)))); do
6684                         ${rcmd} rm -fv $mntpt/oi.16.${i}
6685                 done
6686         fi
6687         # step 4: umount
6688         ${rcmd} umount -d $mntpt || return 2
6689         # OI files will be recreated when mounted as lustre next time.
6690 }
6691
6692 # generate maloo upload-able log file name
6693 # \param logname specify unique part of file name
6694 generate_logname() {
6695         local logname=${1:-"default_logname"}
6696
6697         echo "$TESTLOG_PREFIX.$TESTNAME.$logname.$(hostname -s).log"
6698 }
6699
6700 # make directory on different MDTs
6701 test_mkdir() {
6702         local option
6703         local parent
6704         local child
6705         local path
6706         local p_option
6707         local option2
6708         local stripe_count=2
6709         local rc=0
6710
6711         case $# in
6712                 1) path=$1;;
6713                 2) option=$1
6714                    path=$2;;
6715                 3) option=$1
6716                    option2=$2
6717                    path=$3;;
6718                 *) error "Only creating single directory is supported";;
6719         esac
6720
6721         child=$(basename $path)
6722         parent=$(dirname $path)
6723
6724         if [ "$option" == "-p" -o "$option2" == "-p" ]; then
6725                 if [ -d $parent/$child ]; then
6726                         return $rc
6727                 fi
6728                 p_option="-p"
6729         fi
6730
6731         if [ "${option:0:2}" == "-c" ]; then
6732                 stripe_count=$(echo $option | sed 's/^-c//')
6733         fi
6734
6735         if [ "${option2:0:2}" == "-c" ]; then
6736                 stripe_count=$(echo $option2 | sed 's/^-c//')
6737         fi
6738
6739         if [ ! -d ${parent} ]; then
6740                 if [ "$p_option" == "-p" ]; then
6741                         mkdir -p ${parent}
6742                 else
6743                         return 1
6744                 fi
6745         fi
6746
6747         if [ $MDSCOUNT -le 1 ]; then
6748                 mkdir $p_option $parent/$child || rc=$?
6749         else
6750                 local mdt_idx=$($LFS getstripe -M $parent)
6751                 local test_num=$(echo $testnum | sed -e 's/[^0-9]*//g')
6752
6753                 mdt_idx=$((test_num % MDSCOUNT))
6754                 echo "striped dir -i$mdt_idx -c$stripe_count $path"
6755                 $LFS setdirstripe -i$mdt_idx -c$stripe_count $path || rc=$?
6756         fi
6757         return $rc
6758 }
6759
6760 # find the smallest and not in use file descriptor
6761 free_fd()
6762 {
6763         local max_fd=$(ulimit -n)
6764         local fd=3
6765         while [[ $fd -le $max_fd && -e /proc/self/fd/$fd ]]; do
6766                 ((++fd))
6767         done
6768         [ $fd -lt $max_fd ] || error "finding free file descriptor failed"
6769         echo $fd
6770 }