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