Whamcloud - gitweb
LU-19098 hsm: don't print progname twice with lhsmtool
[fs/lustre-release.git] / lustre / tests / test-framework.sh
1 #!/bin/bash
2
3 if ! $FRAMEWORK_NEEDS_INIT; then
4         return 0
5 fi
6 FRAMEWORK_NEEDS_INIT=false
7
8 trap 'print_summary && print_stack_trace | tee $TF_FAIL && \
9     echo "$TESTSUITE: FAIL: test-framework exiting on error"' ERR
10 set -e
11
12 export LANG=en_US
13 export REFORMAT=${REFORMAT:-""}
14 export WRITECONF=${WRITECONF:-""}
15 export VERBOSE=${VERBOSE:-false}
16 export GSS=${GSS:-false}
17 export GSS_SK=${GSS_SK:-false}
18 export GSS_KRB5=false
19 export SHARED_KEY=${SHARED_KEY:-false}
20 export SK_PATH=${SK_PATH:-/tmp/test-framework-keys}
21 export SK_OM_PATH=$SK_PATH'/tmp-request-mount'
22 export SK_MOUNTED=${SK_MOUNTED:-false}
23 export SK_FLAVOR=${SK_FLAVOR:-ski}
24 export SK_NO_KEY=${SK_NO_KEY:-true}
25 export SK_UNIQUE_NM=${SK_UNIQUE_NM:-false}
26 export SK_S2S=${SK_S2S:-false}
27 export SK_S2SNM=${SK_S2SNM:-TestFrameNM}
28 export SK_S2SNMCLI=${SK_S2SNMCLI:-TestFrameNMCli}
29 export SK_SKIPFIRST=${SK_SKIPFIRST:-true}
30 # whether identity upcall is enabled (true), disabled (false), or default
31 export IDENTITY_UPCALL=${IDENTITY_UPCALL:-default}
32 export QUOTA_AUTO=1
33 export FLAKEY=${FLAKEY:-true}
34 # specify environment variable containing batch job name for server statistics
35 export JOBID_VAR=${JOBID_VAR:-"procname_uid"}  # or "existing" or "disable"
36
37 #export PDSH="pdsh -S -Rssh -w"
38 export MOUNT_CMD=${MOUNT_CMD:-"mount -t lustre"}
39 export UMOUNT=${UMOUNT:-"umount -d"}
40
41 # A switch to enable kptr less restrictively
42 export KPTR_ON_MOUNT=${KPTR_ON_MOUNT:-true}
43
44 export LSNAPSHOT_CONF="/etc/ldev.conf"
45 export LSNAPSHOT_LOG="/var/log/lsnapshot.log"
46
47 export DATA_SEQ_MAX_WIDTH=0x1ffffff
48
49 # sles12 umount has a issue with -d option
50 [ -e /etc/SuSE-release ] && grep -w VERSION /etc/SuSE-release | grep -wq 12 && {
51         export UMOUNT="umount"
52 }
53
54 # function used by scripts run on remote nodes
55 LUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}
56 . $LUSTRE/tests/functions.sh
57 . $LUSTRE/tests/yaml.sh
58
59 export LD_LIBRARY_PATH=${LUSTRE}/utils/.libs:${LUSTRE}/utils:${LD_LIBRARY_PATH}
60
61 LUSTRE_TESTS_CFG_DIR=${LUSTRE_TESTS_CFG_DIR:-${LUSTRE}/tests/cfg}
62
63 EXCEPT_LIST_FILE=${EXCEPT_LIST_FILE:-${LUSTRE_TESTS_CFG_DIR}/tests-to-skip.sh}
64
65 if [ -f "$EXCEPT_LIST_FILE" ]; then
66         echo "Reading test skip list from $EXCEPT_LIST_FILE"
67         cat $EXCEPT_LIST_FILE
68         . $EXCEPT_LIST_FILE
69 fi
70
71 # check config files for options in decreasing order of preference
72 [ -z "$MODPROBECONF" -a -f /etc/modprobe.d/lustre.conf ] &&
73     MODPROBECONF=/etc/modprobe.d/lustre.conf
74 [ -z "$MODPROBECONF" -a -f /etc/modprobe.d/Lustre ] &&
75     MODPROBECONF=/etc/modprobe.d/Lustre
76 [ -z "$MODPROBECONF" -a -f /etc/modprobe.conf ] &&
77     MODPROBECONF=/etc/modprobe.conf
78
79 sanitize_parameters() {
80         for i in DIR DIR1 DIR2 MOUNT MOUNT1 MOUNT2
81         do
82                 local path=${!i}
83
84                 if [ -d "$path" ]; then
85                         eval export $i=$(echo $path | sed -r 's/\/+$//g')
86                 fi
87         done
88 }
89 assert_DIR () {
90         local failed=""
91         [[ $DIR/ = $MOUNT/* ]] ||
92                 { failed=1 && echo "DIR=$DIR not in $MOUNT. Aborting."; }
93         [[ $DIR1/ = $MOUNT1/* ]] ||
94                 { failed=1 && echo "DIR1=$DIR1 not in $MOUNT1. Aborting."; }
95         [[ $DIR2/ = $MOUNT2/* ]] ||
96                 { failed=1 && echo "DIR2=$DIR2 not in $MOUNT2. Aborting"; }
97
98         [ -n "$failed" ] && exit 99 || true
99 }
100
101 usage() {
102         echo "usage: $0 [-r] [-f cfgfile]"
103         echo "       -r: reformat"
104
105         exit
106 }
107
108 print_summary () {
109         trap 0
110         [ -z "$DEFAULT_SUITES" ] && return 0
111         [ -n "$ONLY" ] && echo "WARNING: ONLY is set to $(echo $ONLY)"
112         local details
113         local form="%-13s %-17s %-9s %s %s\n"
114
115         printf "$form" "status" "script" "Total(sec)" "E(xcluded) S(low)"
116         echo "---------------------------------------------------------------"
117         for O in $DEFAULT_SUITES; do
118                 O=$(echo $O  | tr "-" "_" | tr "[:lower:]" "[:upper:]")
119                 [ "${!O}" = "no" ] && continue || true
120                 local o=$(echo $O  | tr "[:upper:]_" "[:lower:]-")
121                 local log=${TMP}/${o}.log
122
123                 if is_sanity_benchmark $o; then
124                     log=${TMP}/sanity-benchmark.log
125                 fi
126                 local slow=
127                 local skipped=
128                 local total=
129                 local status=Unfinished
130
131                 if [ -f $log ]; then
132                         skipped=$(grep excluded $log |
133                                 awk '{ printf " %s", $3 }' | sed 's/test_//g')
134                         slow=$(egrep "^PASS|^FAIL" $log |
135                                 tr -d "("| sed s/s\)$//g | sort -nr -k 3 |
136                                 head -n5 |  awk '{ print $2":"$3"s" }')
137                         total=$(grep duration $log | awk '{ print $2 }')
138                         if [ "${!O}" = "done" ]; then
139                                 status=Done
140                         fi
141                         if $DDETAILS; then
142                                 local durations=$(egrep "^PASS|^FAIL" $log |
143                                         tr -d "("| sed s/s\)$//g |
144                                         awk '{ print $2":"$3"|" }')
145                                 details=$(printf "%s\n%s %s %s\n" "$details" \
146                                         "DDETAILS" "$O" "$(echo $durations)")
147                         fi
148                 fi
149                 printf "$form" $status "$O" "${total}" "E=$skipped"
150                 printf "$form" "-" "-" "-" "S=$(echo $slow)"
151         done
152
153         for O in $DEFAULT_SUITES; do
154                 O=$(echo $O  | tr "-" "_" | tr "[:lower:]" "[:upper:]")
155                         if [ "${!O}" = "no" ]; then
156                                 printf "$form" "Skipped" "$O" ""
157                         fi
158         done
159
160         # print the detailed tests durations if DDETAILS=true
161         if $DDETAILS; then
162                 echo "$details"
163         fi
164 }
165
166 reset_lustre() {
167         if $do_reset; then
168                 stopall
169                 setupall
170         fi
171 }
172
173 setup_if_needed() {
174         ! ${do_setup} && return
175         nfs_client_mode && return
176         AUSTER_CLEANUP=false
177
178         local MOUNTED=$(mounted_lustre_filesystems)
179
180         if $(echo $MOUNTED' ' | grep -w -q $MOUNT' '); then
181                 check_config_clients $MOUNT
182                 # init_facets_vars
183                 # init_param_vars
184                 return
185         fi
186
187         echo "Lustre is not mounted, trying to do setup ... "
188         $reformat && CLEANUP_DM_DEV=true formatall
189         setupall
190
191         MOUNTED=$(mounted_lustre_filesystems)
192         if ! $(echo $MOUNTED' ' | grep -w -q $MOUNT' '); then
193                 echo "Lustre is not mounted after setup! "
194                 exit 1
195         fi
196         AUSTER_CLEANUP=true
197 }
198
199 cleanup_if_needed() {
200         if $AUSTER_CLEANUP; then
201                 cleanupall
202         fi
203 }
204
205 find_script_in_path() {
206         target=$1
207         path=$2
208         for dir in $(tr : " " <<< $path); do
209                 if [ -f $dir/$target ]; then
210                         echo $dir/$target
211                         return 0
212                 fi
213                 if [ -f $dir/$target.sh ]; then
214                         echo $dir/$target.sh
215                         return 0
216                 fi
217         done
218         return 1
219 }
220
221 title() {
222         log "-----============= acceptance-small: "$*" ============----- `date`"
223 }
224
225 doit() {
226         if $dry_run; then
227                 printf "Would have run: %s\n" "$*"
228                 return 0
229         fi
230         if $verbose; then
231                 printf "Running: %s\n" "$*"
232         fi
233         "$@"
234 }
235
236
237 run_suite() {
238         local suite_name=$1
239         local suite_script=$2
240
241         title $suite_name
242         log_test $suite_name
243
244         rm -f $TF_FAIL
245         touch $TF_SKIP
246
247         local start_ts=$(date +%s)
248
249         doit $script_lang $suite_script
250
251         local rc=$?
252         local duration=$(($(date +%s) - $start_ts))
253         local status="PASS"
254
255         if [[ $rc -ne 0 || -f $TF_FAIL ]]; then
256                 status="FAIL"
257         elif [[ -f $TF_SKIP ]]; then
258                 status="SKIP"
259         fi
260         log_test_status $duration $status
261         [[ ! -f $TF_SKIP ]] || rm -f $TF_SKIP
262
263         # got STOP_NOW_RC, return immediately before reset
264         [[ $rc -eq $STOP_NOW_RC ]] &&
265                 echo "stop testing on rc $STOP_NOW_RC" &&
266                 return $STOP_NOW_RC
267
268         reset_lustre
269
270         return $rc
271 }
272
273 run_suite_logged() {
274         local suite_name=${1%.sh}
275         local suite=$(echo ${suite_name} | tr "[:lower:]-" "[:upper:]_")
276
277         suite_script=$(find_script_in_path $suite_name $LUSTRE/tests)
278
279         if [[ -z $suite_script ]]; then
280                 echo "Can't find test script for $suite_name"
281                 return 1
282         fi
283
284         echo "run_suite $suite_name $suite_script"
285
286         local log_name=${suite_name}.suite_log.$(hostname -s).log
287
288         if $verbose; then
289                 run_suite $suite_name $suite_script 2>&1 |tee  $LOGDIR/$log_name
290         else
291                 run_suite $suite_name $suite_script > $LOGDIR/$log_name 2>&1
292         fi
293
294         return ${PIPESTATUS[0]}
295 }
296
297 reset_logging() {
298         export LOGDIR=$1
299
300         unset YAML_LOG
301         init_logging
302 }
303
304 split_commas() {
305         echo "${*//,/ }"
306 }
307
308 run_suites() {
309         local n=0
310         local argv=("$@")
311
312         while ((n < repeat_count)); do
313                 local RC=0
314                 local logdir=${test_logs_dir}
315                 local first_suite=$FIRST_SUITE
316
317                 ((repeat_count > 1)) && logdir="$logdir/$n"
318                 reset_logging $logdir
319                 set -- "${argv[@]}"
320                 while [[ -n $1 ]]; do
321                         unset ONLY EXCEPT START_AT STOP_AT
322                         local opts=""
323                         local time_limit=""
324
325                         suite=$1
326                         shift;
327                         while [[ -n $1 ]]; do
328                         case "$1" in
329                                 --only)
330                                         shift;
331                                         export ONLY=$(split_commas $1)
332
333                                         opts+="ONLY=$ONLY ";;
334                                 --suite)
335                                         shift;
336                                         export SUITE=$(split_commas $1)
337
338                                         opts+="SUITE=$SUITE ";;
339                                 --pattern)
340                                         shift;
341                                         export PATTERN=$(split_commas $1)
342
343                                         opts+="PATTERN=$PATTERN ";;
344                                 --except)
345                                         shift;
346                                         export EXCEPT=$(split_commas $1)
347
348                                         opts+="EXCEPT=$EXCEPT ";;
349                                 --start-at)
350                                         shift;
351                                         export START_AT=$1
352
353                                         opts+="START_AT=$START_AT ";;
354                                 --stop-at)
355                                         shift;
356                                         export STOP_AT=$1
357
358                                         opts+="STOP_AT=$STOP_AT ";;
359                                 --stop-on-error)
360                                         shift;
361                                         export STOP_ON_ERROR=$(split_commas $1)
362
363                                         opts+="STOP_ON_ERROR=$STOP_ON_ERROR ";;
364                                 --time-limit)
365                                         shift;
366                                         time_limit=$1;;
367                                 *)
368                                         break;;
369                         esac
370                         shift
371                         done
372
373                 # If first_suite not set or this is the first suite
374                 if [ "x"$first_suite == "x" ] || [ $first_suite == $suite ]; then
375                         echo "running: $suite $opts"
376                         run_suite_logged $suite || RC=$?
377                         unset first_suite
378                         echo $suite returned $RC
379
380                         # stop testing immediately if rc is STOP_NOW_RC
381                         [[ $RC -eq $STOP_NOW_RC ]] && exit $STOP_NOW_RC
382                 fi
383                 done
384         if $upload_logs; then
385                 $upload_script $LOGDIR
386         fi
387         n=$((n + 1))
388         done
389 }
390
391 # Get information about the Lustre environment. The information collected
392 # will be used in Lustre tests.
393 # usage: get_lustre_env
394 # input: No required or optional arguments
395 # output: No return values, environment variables are exported
396
397 get_lustre_env() {
398         if ! $RPC_MODE; then
399                 export mds1_FSTYPE=${mds1_FSTYPE:-$(facet_fstype mds1)}
400                 export ost1_FSTYPE=${ost1_FSTYPE:-$(facet_fstype ost1)}
401
402                 export MGS_VERSION=$(lustre_version_code mgs)
403                 export MDS1_VERSION=$(lustre_version_code mds1)
404                 export OST1_VERSION=$(lustre_version_code ost1)
405                 export CLIENT_VERSION=$(lustre_version_code client)
406
407                 # import server-side version information into local variables
408                 # so they can be used in tests instead of checked separately
409                 # MGS_OS_VERSION_ID, MGS_OS_ID, MGS_OS_ID_LIKE,
410                 # MDS1_OS_VERSION_ID, MDS1_OS_ID, MDS1_OS_ID_LIKE,
411                 # OST1_OS_VERSION_ID, OST1_OS_ID, OST1_OS_ID_LIKE,
412                 # CLIENT_OS_VERSION_ID, CLIENT_OS_ID, CLIENT_OS_ID_LIKE
413                 lustre_os_release mgs
414                 lustre_os_release mds1
415                 lustre_os_release ost1
416                 lustre_os_release client
417         fi
418
419         # Prefer using "mds1" directly instead of SINGLEMDS.
420         # Keep this for compat until it is removed from scripts.
421         export SINGLEMDS=${SINGLEMDS:-mds1}
422 }
423
424 init_test_env() {
425         export LUSTRE=$(absolute_path $LUSTRE)
426         export TESTSUITE=$(basename $0 .sh)
427         export TEST_FAILED=false
428         export FAIL_ON_SKIP_ENV=${FAIL_ON_SKIP_ENV:-false}
429         export RPC_MODE=${RPC_MODE:-false}
430         export DO_CLEANUP=${DO_CLEANUP:-true}
431         export KEEP_ZPOOL=${KEEP_ZPOOL:-false}
432         export CLEANUP_DM_DEV=false
433         export PAGE_SIZE=$(get_page_size client)
434         export NAME=${NAME:-local}
435
436         . ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}
437
438         export MKE2FS=$MKE2FS
439         if [ -z "$MKE2FS" ]; then
440                 if which mkfs.ldiskfs >/dev/null 2>&1; then
441                         export MKE2FS=mkfs.ldiskfs
442                 else
443                         export MKE2FS=mke2fs
444                 fi
445         fi
446
447         export DEBUGFS=$DEBUGFS
448         if [ -z "$DEBUGFS" ]; then
449                 if which debugfs.ldiskfs >/dev/null 2>&1; then
450                         export DEBUGFS=debugfs.ldiskfs
451                 else
452                         export DEBUGFS=debugfs
453                 fi
454         fi
455
456         export TUNE2FS=$TUNE2FS
457         if [ -z "$TUNE2FS" ]; then
458                 if which tunefs.ldiskfs >/dev/null 2>&1; then
459                         export TUNE2FS=tunefs.ldiskfs
460                 else
461                         export TUNE2FS=tune2fs
462                 fi
463         fi
464
465         export E2LABEL=$E2LABEL
466         if [ -z "$E2LABEL" ]; then
467                 if which label.ldiskfs >/dev/null 2>&1; then
468                         export E2LABEL=label.ldiskfs
469                 else
470                         export E2LABEL=e2label
471                 fi
472         fi
473
474         export DUMPE2FS=$DUMPE2FS
475         if [ -z "$DUMPE2FS" ]; then
476                 if which dumpfs.ldiskfs >/dev/null 2>&1; then
477                         export DUMPE2FS=dumpfs.ldiskfs
478                 else
479                         export DUMPE2FS=dumpe2fs
480                 fi
481         fi
482
483         export E2FSCK=$E2FSCK
484         if [ -z "$E2FSCK" ]; then
485                 if which fsck.ldiskfs >/dev/null 2>&1; then
486                         export E2FSCK=fsck.ldiskfs
487                 else
488                          export E2FSCK=e2fsck
489                 fi
490         fi
491
492         export RESIZE2FS=$RESIZE2FS
493         if [ -z "$RESIZE2FS" ]; then
494                 if which resizefs.ldiskfs >/dev/null 2>&1; then
495                         export RESIZE2FS=resizefs.ldiskfs
496                 else
497                         export RESIZE2FS=resize2fs
498                 fi
499         fi
500
501         export LFSCK_ALWAYS=${LFSCK_ALWAYS:-"no"} # check fs after test suite
502         export FSCK_MAX_ERR=4   # File system errors left uncorrected
503
504         export ZFS=${ZFS:-zfs}
505         export ZPOOL=${ZPOOL:-zpool}
506         export ZDB=${ZDB:-zdb}
507         export PARTPROBE=${PARTPROBE:-partprobe}
508
509         #[ -d /r ] && export ROOT=${ROOT:-/r}
510         export TMP=${TMP:-$ROOT/tmp}
511         export TESTSUITELOG=${TMP}/${TESTSUITE}.log
512         export LOGDIR=${LOGDIR:-${TMP}/test_logs/$(date +%s)}
513         export TESTLOG_PREFIX=$LOGDIR/$TESTSUITE
514
515         export HOSTNAME=${HOSTNAME:-$(hostname -s)}
516         if ! echo $PATH | grep -q $LUSTRE/utils; then
517                 export PATH=$LUSTRE/utils:$PATH
518         fi
519         if ! echo $PATH | grep -q $LUSTRE/utils/gss; then
520                 export PATH=$LUSTRE/utils/gss:$PATH
521         fi
522         if ! echo $PATH | grep -q $LUSTRE/tests; then
523                 export PATH=$LUSTRE/tests:$PATH
524         fi
525         if ! echo $PATH | grep -q $LUSTRE/../lustre-iokit/sgpdd-survey; then
526                 export PATH=$LUSTRE/../lustre-iokit/sgpdd-survey:$PATH
527         fi
528         export LST=${LST:-"$LUSTRE/../lnet/utils/lst"}
529         [ ! -f "$LST" ] && export LST=$(which lst)
530         export LSTSH=${LSTSH:-"$LUSTRE/../lustre-iokit/lst-survey/lst.sh"}
531         [ ! -f "$LSTSH" ] && export LSTSH=$(which lst.sh)
532         export SGPDDSURVEY=${SGPDDSURVEY:-"$LUSTRE/../lustre-iokit/sgpdd-survey/sgpdd-survey")}
533         [ ! -f "$SGPDDSURVEY" ] && export SGPDDSURVEY=$(which sgpdd-survey)
534         export MCREATE=${MCREATE:-mcreate}
535         export MULTIOP=${MULTIOP:-multiop}
536         export MMAP_CAT=${MMAP_CAT:-mmap_cat}
537         export STATX=${STATX:-statx}
538         # Ubuntu, at least, has a truncate command in /usr/bin
539         # so fully path our truncate command.
540         export TRUNCATE=${TRUNCATE:-$LUSTRE/tests/truncate}
541         export FSX=${FSX:-$LUSTRE/tests/fsx}
542         export MDSRATE=${MDSRATE:-"$LUSTRE/tests/mpi/mdsrate"}
543         [ ! -f "$MDSRATE" ] && export MDSRATE=$(which mdsrate 2> /dev/null)
544         if ! echo $PATH | grep -q $LUSTRE/tests/racer; then
545                 export PATH=$LUSTRE/tests/racer:$PATH:
546         fi
547         if ! echo $PATH | grep -q $LUSTRE/tests/mpi; then
548                 export PATH=$LUSTRE/tests/mpi:$PATH
549         fi
550
551         export LNETCTL=${LNETCTL:-"$LUSTRE/../lnet/utils/lnetctl"}
552         [ ! -f "$LNETCTL" ] && export LNETCTL=$(which lnetctl 2> /dev/null)
553         export LCTL=${LCTL:-"$LUSTRE/utils/lctl"}
554         [ ! -f "$LCTL" ] && export LCTL=$(which lctl)
555         export LFS=${LFS:-"$LUSTRE/utils/lfs"}
556         [ ! -f "$LFS" ] && export LFS=$(which lfs)
557         export KSOCKLND_CONFIG=${KSOCKLND_CONFIG:-"$LUSTRE/scripts/ksocklnd-config"}
558         [ ! -f "$KSOCKLND_CONFIG" ] &&
559                 export KSOCKLND_CONFIG=$(which ksocklnd-config 2> /dev/null)
560         export LNET_SYSCTL_CONFIG=${LNET_SYSCTL_CONFIG:-"$LUSTRE/scripts/lnet-sysctl-config"}
561         [ ! -f "$LNET_SYSCTL_CONFIG" ] &&
562                 export LNET_SYSCTL_CONFIG=$(which lnet-sysctl-config 2> /dev/null)
563
564         export PERM_CMD=$(echo ${PERM_CMD:-"$LCTL conf_param"})
565
566         export L_GETIDENTITY=${L_GETIDENTITY:-"$LUSTRE/utils/l_getidentity"}
567         if [ ! -x "$L_GETIDENTITY" ]; then
568                 if $(which l_getidentity > /dev/null 2>&1); then
569                         export L_GETIDENTITY=$(which l_getidentity)
570                 else
571                         export L_GETIDENTITY=NONE
572                 fi
573         fi
574         export LL_DECODE_FILTER_FID=${LL_DECODE_FILTER_FID:-"$LUSTRE/utils/ll_decode_filter_fid"}
575         [ ! -f "$LL_DECODE_FILTER_FID" ] &&
576                 export LL_DECODE_FILTER_FID="ll_decode_filter_fid"
577         export LL_DECODE_LINKEA=${LL_DECODE_LINKEA:-"$LUSTRE/utils/ll_decode_linkea"}
578         [ ! -f "$LL_DECODE_LINKEA" ] &&
579                 export LL_DECODE_LINKEA="ll_decode_linkea"
580         export MKFS=${MKFS:-"$LUSTRE/utils/mkfs.lustre"}
581         [ ! -f "$MKFS" ] && export MKFS="mkfs.lustre"
582         export TUNEFS=${TUNEFS:-"$LUSTRE/utils/tunefs.lustre"}
583         [ ! -f "$TUNEFS" ] && export TUNEFS="tunefs.lustre"
584         export CHECKSTAT="${CHECKSTAT:-"checkstat -v"} "
585         export LUSTRE_RMMOD=${LUSTRE_RMMOD:-$LUSTRE/scripts/lustre_rmmod}
586         [ ! -f "$LUSTRE_RMMOD" ] &&
587                 export LUSTRE_RMMOD=$(which lustre_rmmod 2> /dev/null)
588         export LUSTRE_ROUTES_CONVERSION=${LUSTRE_ROUTES_CONVERSION:-$LUSTRE/scripts/lustre_routes_conversion}
589         [ ! -f "$LUSTRE_ROUTES_CONVERSION" ] &&
590                 export LUSTRE_ROUTES_CONVERSION=$(which lustre_routes_conversion 2> /dev/null)
591         export LFS_MIGRATE=${LFS_MIGRATE:-$LUSTRE/scripts/lfs_migrate}
592         [ ! -f "$LFS_MIGRATE" ] &&
593                 export LFS_MIGRATE=$(which lfs_migrate 2> /dev/null)
594         export LR_READER=${LR_READER:-"$LUSTRE/utils/lr_reader"}
595         [ ! -f "$LR_READER" ] &&
596                 export LR_READER=$(which lr_reader 2> /dev/null)
597         [ -z "$LR_READER" ] && export LR_READER="/usr/sbin/lr_reader"
598         export LSOM_SYNC=${LSOM_SYNC:-"$LUSTRE/utils/llsom_sync"}
599         [ ! -f "$LSOM_SYNC" ] &&
600                 export LSOM_SYNC=$(which llsom_sync 2> /dev/null)
601         [ -z "$LSOM_SYNC" ] && export LSOM_SYNC="/usr/sbin/llsom_sync"
602         export L_GETAUTH=${L_GETAUTH:-"$LUSTRE/utils/gss/l_getauth"}
603         [ ! -f "$L_GETAUTH" ] && export L_GETAUTH=$(which l_getauth 2> /dev/null)
604         export LSVCGSSD=${LSVCGSSD:-"$LUSTRE/utils/gss/lsvcgssd"}
605         [ ! -f "$LSVCGSSD" ] && export LSVCGSSD=$(which lsvcgssd 2> /dev/null)
606         export KRB5DIR=${KRB5DIR:-"/usr/kerberos"}
607         export DIR2
608         export SAVE_PWD=${SAVE_PWD:-$LUSTRE/tests}
609         export AT_MAX_PATH
610         export LDEV=${LDEV:-"$LUSTRE/scripts/ldev"}
611         [ ! -f "$LDEV" ] && export LDEV=$(which ldev 2> /dev/null)
612
613         export DMSETUP=${DMSETUP:-dmsetup}
614         export DM_DEV_PATH=${DM_DEV_PATH:-/dev/mapper}
615         export LOSETUP=${LOSETUP:-losetup}
616
617         if [ "$ACCEPTOR_PORT" ]; then
618                 export PORT_OPT="--port $ACCEPTOR_PORT"
619         fi
620
621         if $SHARED_KEY; then
622                 $RPC_MODE || echo "Using GSS shared-key feature"
623                 [ -n "$LGSS_SK" ] ||
624                         export LGSS_SK=$(which lgss_sk 2> /dev/null)
625                 [ -n "$LGSS_SK" ] ||
626                         export LGSS_SK="$LUSTRE/utils/gss/lgss_sk"
627                 [ -n "$LGSS_SK" ] ||
628                         error_exit "built with lgss_sk disabled! SEC=$SEC"
629                 GSS=true
630                 GSS_SK=true
631                 SEC=$SK_FLAVOR
632         fi
633
634         case "x$SEC" in
635                 xkrb5*)
636                 $RPC_MODE || echo "Using GSS/krb5 ptlrpc security flavor"
637                 which lgss_keyring > /dev/null 2>&1 ||
638                         error_exit "built with gss disabled! SEC=$SEC"
639                 GSS=true
640                 GSS_KRB5=true
641                 ;;
642         esac
643
644         export LOAD_MODULES_REMOTE=${LOAD_MODULES_REMOTE:-false}
645
646         # Paths on remote nodes, if different
647         export RLUSTRE=${RLUSTRE:-$LUSTRE}
648         export RPWD=${RPWD:-$PWD}
649         export I_MOUNTED=${I_MOUNTED:-"no"}
650         export AUSTER_CLEANUP=${AUSTER_CLEANUP:-false}
651         if [ ! -f /lib/modules/$(uname -r)/kernel/fs/lustre/mdt.ko -a \
652              ! -f /lib/modules/$(uname -r)/updates/kernel/fs/lustre/mdt.ko -a \
653              ! -f /lib/modules/$(uname -r)/extra/kernel/fs/lustre/mdt.ko -a \
654              ! -f $LUSTRE/mdt/mdt.ko ]; then
655             export CLIENTMODSONLY=yes
656         fi
657
658         export SHUTDOWN_ATTEMPTS=${SHUTDOWN_ATTEMPTS:-3}
659         export OSD_TRACK_DECLARES_LBUG=${OSD_TRACK_DECLARES_LBUG:-"yes"}
660
661         # command line
662
663         while getopts "rvwf:" opt $*; do
664                 case $opt in
665                         f) CONFIG=$OPTARG;;
666                         r) REFORMAT=yes;;
667                         v) VERBOSE=true;;
668                         w) WRITECONF=writeconf;;
669                         \?) usage;;
670                 esac
671         done
672
673         shift $((OPTIND - 1))
674         ONLY=${ONLY:-$*}
675
676         # print the durations of each test if "true"
677         DDETAILS=${DDETAILS:-false}
678         [ "$TESTSUITELOG" ] && rm -f $TESTSUITELOG || true
679         if ! $RPC_MODE; then
680                 rm -f $TMP/*active
681         fi
682
683         export TF_FAIL=${TF_FAIL:-$TMP/tf.fail}
684
685         # Constants used in more than one test script
686         export LOV_MAX_STRIPE_COUNT=2000
687         export LMV_MAX_STRIPES_PER_MDT=5
688         export DELETE_OLD_POOLS=${DELETE_OLD_POOLS:-false}
689         export KEEP_POOLS=${KEEP_POOLS:-false}
690         export PARALLEL=${PARALLEL:-"no"}
691
692         export BLCKSIZE=${BLCKSIZE:-4096}
693         export MACHINEFILE=${MACHINEFILE:-$TMP/$(basename $0 .sh).machines}
694         get_lustre_env
695         # use /dev/urandom when consuming space on ZFS to avoid compression
696         if [[ "$ost1_FSTYPE" == "zfs" ]]; then
697                 DD_DEV="/dev/urandom"
698         else
699                 DD_DEV="/dev/zero"
700         fi
701         DD="dd if=$DD_DEV bs=1M"
702
703         # use localrecov to enable recovery for local clients, LU-12722
704         [[ $MDS1_VERSION -lt $(version_code 2.13.52) ]] || {
705                 export MDS_MOUNT_OPTS=${MDS_MOUNT_OPTS:-"-o localrecov"}
706                 export MGS_MOUNT_OPTS=${MGS_MOUNT_OPTS:-"-o localrecov"}
707         }
708
709         [[ $OST1_VERSION -lt $(version_code 2.13.52) ]] ||
710                 export OST_MOUNT_OPTS=${OST_MOUNT_OPTS:-"-o localrecov"}
711
712         # Force large nid testing, if unset or false then large NIDs will only
713         # be used if they are the only addresses assigned to the LNet
714         # interfaces
715         export FORCE_LARGE_NID=${FORCE_LARGE_NID:-false}
716         if ${FORCE_LARGE_NID}; then
717                 export LNET_CONFIG_INIT_OPT="--all --large"
718                 export LNET_CONFIG_OPT="-l"
719         else
720                 export LNET_CONFIG_INIT_OPT="--all"
721                 export LNET_CONFIG_OPT=""
722         fi
723 }
724
725 check_cpt_number() {
726         local facet=$1
727         local ncpts
728
729         ncpts=$(do_facet $facet "lctl get_param -n " \
730                 "cpu_partition_table 2>/dev/null| wc -l" || echo 1)
731
732         if [ $ncpts -eq 0 ]; then
733                 echo "1"
734         else
735                 echo $ncpts
736         fi
737 }
738
739 # Return a numeric version code based on a version string.  The version
740 # code is useful for comparison two version strings to see which is newer.
741 version_code() {
742         # split arguments like "1.8.6-wc3" into "1", "8", "6", "3"
743         eval set -- $(tr "[:punct:][a-zA-Z]" " " <<< $*)
744
745         echo -n $(((${1:-0}<<24) | (${2:-0}<<16) | (${3:-0}<<8) | (${4:-0})))
746 }
747
748 export LINUX_VERSION=$(uname -r | sed -e "s/\([0-9]*\.[0-9]*\.[0-9]*\).*/\1/")
749 export LINUX_VERSION_CODE=$(version_code ${LINUX_VERSION//\./ })
750
751 # Report the Lustre build version string (e.g. 1.8.7.3 or 2.4.1).
752 #
753 # usage: lustre_build_version_node
754 #
755 # All Lustre versions support "lctl get_param" to report the version of the
756 # code running in the kernel (what our tests are interested in), but it
757 # doesn't work without modules loaded.  After 2.9.53 and in upstream kernels
758 # the "version" parameter doesn't include "lustre: " at the beginning.
759 # If that fails, call "lctl lustre_build_version" which prints either (or both)
760 # the userspace and kernel build versions, but until 2.8.55 required root
761 # access to get the Lustre kernel version.  If that also fails, fall back to
762 # using "lctl --version", which is easy to parse and works without the kernel
763 # modules, but was only added in 2.6.50 and only prints the lctl tool version,
764 # not the module version, though they are usually the same.
765 #
766 # Various commands and their output format for different Lustre versions:
767 # lctl get_param version:       2.9.55
768 # lctl get_param version:       lustre: 2.8.53
769 # lctl get_param version:       lustre: 2.6.52
770 #                               kernel: patchless_client
771 #                               build: v2_6_92_0-2.6.32-431.el6_lustre.x86_64
772 # lctl lustre_build_version:    Lustre version: 2.8.53_27_gae67fc01
773 # lctl lustre_build_version:    error: lustre_build_version: Permission denied
774 #       (as non-root user)      lctl   version: v2_6_92_0-2.6.32-431.el6.x86_64
775 # lctl lustre_build_version:    Lustre version: 2.5.3-2.6.32.26-175.fc12.x86_64
776 #                               lctl   version: 2.5.3-2.6.32..26-175fc12.x86_64
777 # lctl --version:               lctl 2.6.50
778 #
779 # output: prints version string to stdout in (up to 4) dotted-decimal values
780 lustre_build_version_node() {
781         local node=$1
782         local ver
783         local lver
784
785         # this is the currently-running version of the kernel modules
786         ver=$(do_node $node "$LCTL get_param -n version 2>/dev/null")
787         # we mostly test 2.10+ systems, only try others if the above fails
788         if [ -z "$ver" ]; then
789                 ver=$(do_node $node "$LCTL lustre_build_version 2>/dev/null")
790         fi
791         if [ -z "$ver" ]; then
792                 ver=$(do_node $node "$LCTL --version 2>/dev/null" |
793                       cut -d' ' -f2)
794         fi
795         local lver=$(egrep -i "lustre: |version: " <<<"$ver" | head -n 1)
796         [ -n "$lver" ] && ver="$lver"
797
798         lver=$(sed -e 's/[^:]*: //' -e 's/^v//' -e 's/[ -].*//' <<<$ver |
799                tr _ . | cut -d. -f1-4)
800
801         echo $lver
802 }
803
804 lustre_build_version() {
805         local facet=${1:-client}
806         local node=$(facet_active_host $facet)
807         local facet_version=${facet}_VERSION
808         local lver
809
810         # if the global variable is already set, then use that
811         [ -n "${!facet_version}" ] && echo ${!facet_version} && return
812
813         lver=$(lustre_build_version_node $node)
814         # save in global variable for the future
815         export $facet_version=$lver
816
817         echo $lver
818 }
819
820 # Report the Lustre numeric build version code for the supplied facet.
821 lustre_version_code() {
822         version_code $(lustre_build_version $1)
823 }
824
825 zfs_version_code() {
826         local facet=$1
827         local facet_version=${facet}_ZFS_VERSION
828
829         if [[ -z "${!facet_version}" ]]; then
830                 local zfs_ver=$(do_facet $facet "modinfo --field version zfs")
831
832                 export $facet_version=$(version_code ${zfs_ver%-*})
833         fi
834         echo ${!facet_version}
835 }
836
837 # Extract the server-side /etc/os-release information into local variables
838 # usage: lustre_os_release <facet>
839 # generates $facet_OS_ID, $facet_OS_ID_LIKE, $facet_VERSION_ID
840 # and also $facet_OS_VERSION_CODE=$(version_code $facet_VERSION_ID)
841 lustre_os_release() {
842         local facet=$1
843         local facet_os=$(tr "[:lower:]" "[:upper:]" <<<$facet)_OS_
844         local facet_version=${facet_os}VERSION_
845         local line
846
847         echo "$facet: $(do_facet $facet "cat /etc/system-release")"
848         do_facet $facet "test -r /etc/os-release" || {
849                 echo "$facet: has no /etc/os-release"
850                 do_facet $facet "uname -a; ls -s /etc/*release"
851                 return 0
852         }
853
854         while read line; do
855                 # more variables in os-release could be exported, but these
856                 # are the ones that looked enough for our needs here
857                 case $line in
858                 VERSION_ID=*|ID=*|ID_LIKE=*) eval export ${facet_os}$line ;;
859                 esac
860         done < <(do_facet $facet "cat /etc/os-release")
861
862         eval export ${facet_version}CODE=\$\(version_code \$${facet_version}ID\)
863         # add in the "self" ID to ID_LIKE so only one needs to be checked
864         eval export ${facet_os}ID_LIKE+=\" \$${facet_os}ID\"
865         env | grep "${facet_os}"
866 }
867
868 module_loaded () {
869         /sbin/lsmod | grep -q "^\<$1\>"
870 }
871
872 check_lfs_df_ret_val() {
873         # Ignore only EOPNOTSUPP (which is 95; Operation not supported) error
874         # returned by 'lfs df' for valid dentry but not a lustrefs.
875         #
876         # 'lfs df' historically always returned success(0) instead of
877         # EOPNOTSUPP. This function for compatibility reason, ignores and
878         # masquerades EOPNOTSUPP as success.
879         [[ $1 -eq 95 ]] && return 0
880         return $1
881 }
882
883 PRLFS=false
884 lustre_insmod() {
885         local module=$1
886         shift
887         local args="$@"
888         local msg
889         local rc=0
890
891         if ! $PRLFS; then
892                 msg="$(insmod $module $args 2>&1)" && return 0 || rc=$?
893         fi
894
895         # parallels can't load modules directly from prlfs, use /tmp instead
896         if $PRLFS || [[ "$(stat -f -c%t $module)" == "7c7c6673" ]]; then
897                 local target="$(mktemp)"
898
899                 cp "$module" "$target"
900                 insmod $target $args
901                 rc=$?
902                 [[ $rc == 0 ]] && PRLFS=true
903                 rm -f $target
904         else
905                 echo "$msg"
906         fi
907         return $rc
908 }
909
910 # Load a module on the system where this is running.
911 #
912 # usage: load_module module_name [module arguments for insmod/modprobe]
913 #
914 # If module arguments are not given but MODOPTS_<MODULE> is set, then its value
915 # will be used as the arguments.  Otherwise arguments will be obtained from
916 # /etc/modprobe.conf, from /etc/modprobe.d/Lustre, or else none will be used.
917 #
918 load_module() {
919         local module=$1 # '../libcfs/libcfs/libcfs', 'obdclass/obdclass', ...
920         shift
921         local ext=".ko"
922         local base=$(basename $module $ext)
923         local path
924         local -A module_is_loaded_aa
925         local optvar
926         local mod
927
928         for mod in $(lsmod | awk '{ print $1; }'); do
929                 module_is_loaded_aa[${mod//-/_}]=true
930         done
931
932         module_is_loaded() {
933                 ${module_is_loaded_aa[${1//-/_}]:-false}
934         }
935
936         if module_is_loaded $base; then
937                 return
938         fi
939
940         if [[ -f $LUSTRE/$module$ext ]]; then
941                 path=$LUSTRE/$module$ext
942         elif [[ "$base" == lnet_selftest ]] &&
943              [[ -f $LUSTRE/../lnet/selftest/$base$ext ]]; then
944                 path=$LUSTRE/../lnet/selftest/$base$ext
945         else
946                 path=''
947         fi
948
949         if [[ -n "$path" ]]; then
950                 # Try to load any non-Lustre modules that $module depends on.
951                 for mod in $(modinfo --field=depends $path | tr ',' ' '); do
952                         if ! module_is_loaded $mod; then
953                                 modprobe $mod
954                         fi
955                 done
956         fi
957
958         # If no module arguments were passed then get them from
959         # $MODOPTS_<MODULE>, otherwise from modprobe.conf.
960         if [ $# -eq 0 ]; then
961                 # $MODOPTS_<MODULE>; we could use associative arrays, but that's
962                 # not in Bash until 4.x, so we resort to eval.
963                 optvar="MODOPTS_$(basename $module | tr a-z A-Z)"
964                 eval set -- \$$optvar
965                 if [ $# -eq 0 -a -n "$MODPROBECONF" ]; then
966                         # Nothing in $MODOPTS_<MODULE>; try modprobe.conf
967                         local opt
968                         opt=$(awk -v var="^options $base" '$0 ~ var \
969                               {gsub("'"options $base"'",""); print}' \
970                                 $MODPROBECONF)
971                         set -- $(echo -n $opt)
972
973                         # Ensure we have accept=all for lnet
974                         if [[ "$base" == lnet ]]; then
975                                 # OK, this is a bit wordy...
976                                 local arg accept_all_present=false
977
978                                 for arg in "$@"; do
979                                         [[ "$arg" == accept=all ]] &&
980                                                 accept_all_present=true
981                                 done
982
983                                 $accept_all_present || set -- "$@" accept=all
984                         fi
985
986                         export $optvar="$*"
987                 fi
988         fi
989
990         [ $# -gt 0 ] && echo "${module} options: '$*'"
991
992         # Note that insmod will ignore anything in modprobe.conf, which is why
993         # we're passing options on the command-line. If $path does not exist
994         # then we must be testing a "make install" or"rpm" installation. Also
995         # note that failing to load ptlrpc_gss is not considered fatal.
996         if [[ -n "$path" ]]; then
997                 lustre_insmod $path "$@"
998         elif [[ "$base" == ptlrpc_gss ]]; then
999                 if ! modprobe $base "$@" 2>/dev/null; then
1000                         echo "gss/krb5 is not supported"
1001                 fi
1002         else
1003                 modprobe $base "$@"
1004         fi
1005 }
1006
1007 do_lnetctl() {
1008         $LCTL mark "$LNETCTL $*"
1009         echo "$LNETCTL $*"
1010         $LNETCTL "$@"
1011 }
1012
1013 do_lctl() {
1014         $LCTL mark "$LNETCTL $*"
1015         echo "$LCTL $*"
1016         $LCTL "$@"
1017 }
1018
1019 load_lnet() {
1020         # For kmemleak-enabled kernels we need clear all past state
1021         # that obviously has nothing to do with this Lustre run
1022         # Disable automatic memory scanning to avoid perf hit.
1023         if [ -f /sys/kernel/debug/kmemleak ] ; then
1024                 echo scan=off > /sys/kernel/debug/kmemleak || true
1025                 echo scan > /sys/kernel/debug/kmemleak || true
1026                 echo clear > /sys/kernel/debug/kmemleak || true
1027         fi
1028
1029         echo Loading modules from $LUSTRE
1030
1031         local ncpus
1032
1033         if [ -f /sys/devices/system/cpu/online ]; then
1034                 ncpus=$(($(cut -d "-" -f 2 /sys/devices/system/cpu/online) + 1))
1035                 echo "detected $ncpus online CPUs by sysfs"
1036         else
1037                 ncpus=$(getconf _NPROCESSORS_CONF 2>/dev/null)
1038                 local rc=$?
1039
1040                 if [ $rc -eq 0 ]; then
1041                         echo "detected $ncpus online CPUs by getconf"
1042                 else
1043                         echo "Can't detect number of CPUs"
1044                         ncpus=1
1045                 fi
1046         fi
1047
1048         # if there is only one CPU core, libcfs can only create one partition
1049         # if there is more than 4 CPU cores, libcfs should create multiple CPU
1050         # partitions. So we just force libcfs to create 2 partitions for
1051         # system with 2 or 4 cores
1052         local saved_opts="$MODOPTS_LIBCFS"
1053
1054         echo "MODOPTS_LIBCFS=$MODOPTS_LIBCFS"
1055         if ! [[ "$MODOPTS_LIBCFS" =~ "cpu_" ]] &&
1056            (( $ncpus <= 4 && $ncpus > 1 )); then
1057                 # force to enable multiple CPU partitions
1058                 echo "Force libcfs to create 2 CPU partitions"
1059                 MODOPTS_LIBCFS="cpu_npartitions=2 $MODOPTS_LIBCFS"
1060         else
1061                 echo "libcfs will create CPU partition based on online CPUs"
1062         fi
1063
1064         load_module ../libcfs/libcfs/libcfs
1065         # Prevent local MODOPTS_LIBCFS being passed as part of environment
1066         # variable to remote nodes
1067         unset MODOPTS_LIBCFS
1068
1069         set_default_debug "neterror net nettrace malloc"
1070         if [[ $1 == config_on_load=1 ]]; then
1071                 load_module ../lnet/lnet/lnet
1072         else
1073                 load_module ../lnet/lnet/lnet "$@"
1074         fi
1075
1076         LNDPATH=${LNDPATH:-"../lnet/klnds"}
1077         if [ -z "$LNETLND" ]; then
1078                 case $NETTYPE in
1079                 o2ib*)  [[ -f ${LNDPATH}/o2iblnd/ko2iblnd.ko ]] &&
1080                                 LNETLND="o2iblnd/ko2iblnd" ||
1081                                 LNETLND="in-kernel-o2iblnd/ko2iblnd";;
1082                 tcp*)   LNETLND="socklnd/ksocklnd" ;;
1083                 kfi*)   LNETLND="kfilnd/kkfilnd" ;;
1084                 gni*)   LNETLND="gnilnd/kgnilnd" ;;
1085                 *)      local lnd="${NETTYPE%%[0-9]}lnd"
1086                         [ -f "$LNDPATH/$lnd/k$lnd.ko" ] &&
1087                                 LNETLND="$lnd/k$lnd" ||
1088                                 LNETLND="socklnd/ksocklnd"
1089                 esac
1090         fi
1091         load_module ../lnet/klnds/$LNETLND
1092
1093         if [[ $1 == config_on_load=1 ]]; then
1094                 if $FORCE_LARGE_NID; then
1095                         do_lnetctl lnet configure -a -l ||
1096                                 return $?
1097                 else
1098                         do_lnetctl lnet configure -a ||
1099                                 return $?
1100                 fi
1101         fi
1102 }
1103
1104 load_modules_local() {
1105         if [ -n "$MODPROBE" ]; then
1106                 # use modprobe
1107                 echo "Using modprobe to load modules"
1108                 return 0
1109         fi
1110
1111         # Create special udev test rules on every node
1112         if [ -f $LUSTRE/lustre/conf/99-lustre.rules ]; then {
1113                 sed -e 's|/usr/sbin/lctl|$LCTL|g' $LUSTRE/lustre/conf/99-lustre.rules > /etc/udev/rules.d/99-lustre-test.rules
1114         } else {
1115                 echo "SUBSYSTEM==\"lustre\", ACTION==\"change\", ENV{PARAM}==\"?*\", RUN+=\"$LCTL set_param '\$env{PARAM}=\$env{SETTING}'\"" > /etc/udev/rules.d/99-lustre-test.rules
1116         } fi
1117         udevadm control --reload-rules
1118         udevadm trigger
1119
1120         if $FORCE_LARGE_NID; then
1121                 load_lnet config_on_load=1
1122         else
1123                 load_lnet
1124         fi
1125
1126         load_module obdclass/obdclass
1127         if ! client_only; then
1128                 MODOPTS_PTLRPC=${MODOPTS_PTLRPC:-"lbug_on_grant_miscount=1"}
1129         fi
1130         load_module ptlrpc/ptlrpc
1131         load_module ptlrpc/gss/ptlrpc_gss
1132         load_module fld/fld
1133         load_module fid/fid
1134         load_module lmv/lmv
1135         load_module osc/osc
1136         load_module lov/lov
1137         load_module mdc/mdc
1138         load_module mgc/mgc
1139         load_module obdecho/obdecho
1140         if ! client_only; then
1141                 load_module lfsck/lfsck
1142                 [ "$LQUOTA" != "no" ] &&
1143                         load_module quota/lquota $LQUOTAOPTS
1144                 if [[ $(node_fstypes $HOSTNAME) == *zfs* ]]; then
1145                         load_module osd-zfs/osd_zfs
1146                 elif [[ $(node_fstypes $HOSTNAME) == *ldiskfs* ]]; then
1147                         load_module ../ldiskfs/ldiskfs
1148                         load_module osd-ldiskfs/osd_ldiskfs
1149                 elif [[ $(node_fstypes $HOSTNAME) == *wbcfs* ]]; then
1150                         load_module osd-wbcfs/osd_wbcfs
1151                 fi
1152                 load_module mgs/mgs
1153                 load_module mdd/mdd
1154                 load_module mdt/mdt
1155                 # don't fail if ost module doesn't exist
1156                 load_module ost/ost 2>/dev/null || true;
1157                 load_module lod/lod
1158                 load_module ofd/ofd
1159                 load_module osp/osp
1160         fi
1161
1162         load_module llite/lustre
1163         [ -d /r ] && OGDB=${OGDB:-"/r/tmp"}
1164         OGDB=${OGDB:-$TMP}
1165         rm -f $OGDB/ogdb-$HOSTNAME
1166         $LCTL modules > $OGDB/ogdb-$HOSTNAME
1167
1168         # 'mount' doesn't look in $PATH, just sbin
1169         local mount_lustre=$LUSTRE/utils/mount.lustre
1170         if [ -f $mount_lustre ]; then
1171                 local sbin_mount=$(readlink -f /sbin)/mount.lustre
1172                 if grep -qw "$sbin_mount" /proc/mounts; then
1173                         cmp -s $mount_lustre $sbin_mount || umount $sbin_mount
1174                 fi
1175                 if ! grep -qw "$sbin_mount" /proc/mounts; then
1176                         [ ! -f "$sbin_mount" ] && touch "$sbin_mount"
1177                         if [ ! -s "$sbin_mount" -a -w "$sbin_mount" ]; then
1178                                 cat <<- EOF > "$sbin_mount"
1179                                 #!/bin/bash
1180                                 #STUB MARK
1181                                 echo "This $sbin_mount just a mountpoint." 1>&2
1182                                 echo "It is never supposed to be run." 1>&2
1183                                 logger -p emerg -- "using stub $sbin_mount $@"
1184                                 exit 1
1185                                 EOF
1186                                 chmod a+x $sbin_mount
1187                         fi
1188                         mount --bind $mount_lustre $sbin_mount ||
1189                                 error "can't bind $mount_lustre to $sbin_mount"
1190                         # ignore errors to symlink .libs for read-only /sbin
1191                         [[ -e /sbin/.libs ]] ||
1192                                 ln -sf $LUSTRE/utils/.libs /sbin/.libs || true
1193                 fi
1194         fi
1195 }
1196
1197 load_modules () {
1198         local facets
1199         local facet
1200         local failover
1201         load_modules_local
1202         # bug 19124
1203         # load modules on remote nodes optionally
1204         # lustre-tests have to be installed on these nodes
1205         if $LOAD_MODULES_REMOTE; then
1206                 local list=$(comma_list $(remote_nodes_list))
1207
1208                 # include failover nodes in case they are not in the list yet
1209                 facets=$(get_facets)
1210                 for facet in ${facets//,/ }; do
1211                         failover=$(facet_failover_host $facet)
1212                         [ -n "$list" ] && [[ ! "$list" =~ "$failover" ]] &&
1213                                 list="$list,$failover"
1214                 done
1215
1216                 if [ -n "$list" ]; then
1217                         echo "loading modules on: '$list'"
1218                         do_rpc_nodes "$list" load_modules_local
1219                 fi
1220         fi
1221 }
1222
1223 check_mem_leak () {
1224         LEAK_LUSTRE=$(dmesg | tail -n 30 | grep "obd_memory.*leaked" || true)
1225         LEAK_PORTALS=$(dmesg | tail -n 20 | egrep -i "libcfs.*memory leaked" ||
1226                 true)
1227         if [ "$LEAK_LUSTRE" -o "$LEAK_PORTALS" ]; then
1228                 echo "$LEAK_LUSTRE" 1>&2
1229                 echo "$LEAK_PORTALS" 1>&2
1230                 echo "Memory leaks detected"
1231                 if [ $DEBUG -a -z $DEBUG_RMMOD ]; then
1232                         debug_file=$TMP/debug-leak.$(date +%s)
1233                         mv $TMP/debug $debug_file &&
1234                         echo "Save $TMP/debug to $debug_file"
1235                 fi
1236                 [[ -n "$IGNORE_LEAK" ]] &&
1237                         { echo "ignoring leaks" && return 0; } || true
1238                 return 1
1239         fi
1240 }
1241
1242 unload_modules_local() {
1243         $LUSTRE_RMMOD ldiskfs || return 2
1244
1245         [ -f /etc/udev/rules.d/99-lustre-test.rules ] &&
1246                 rm /etc/udev/rules.d/99-lustre-test.rules
1247         udevadm control --reload-rules
1248         udevadm trigger
1249
1250         check_mem_leak || return 254
1251
1252         return 0
1253 }
1254
1255 unload_modules() {
1256         local rc=0
1257
1258         wait_exit_ST client # bug 12845
1259
1260         unload_modules_local || rc=$?
1261
1262         if $LOAD_MODULES_REMOTE; then
1263                 local list=$(comma_list $(remote_nodes_list))
1264
1265                 if (( MDS1_VERSION >= $(version_code 2.15.51) )); then
1266                         # unload_module_local is only available after 2.15.51
1267                         if [ -n "$list" ]; then
1268                                 echo "unloading modules via unload_modules_local on: '$list'"
1269                                 do_rpc_nodes "$list" unload_modules_local
1270                         fi
1271                 else
1272                         if [ -n "$list" ]; then
1273                                 echo "unloading modules on: '$list'"
1274                                 do_rpc_nodes "$list" $LUSTRE_RMMOD ldiskfs
1275                                 do_rpc_nodes "$list" check_mem_leak
1276                                 do_rpc_nodes "$list" "rm -f /etc/udev/rules.d/99-lustre-test.rules"
1277                                 do_rpc_nodes "$list" "udevadm control --reload-rules"
1278                                 do_rpc_nodes "$list" "udevadm trigger"
1279                         fi
1280                 fi
1281         fi
1282
1283         local sbin_mount=$(readlink -f /sbin)/mount.lustre
1284         if grep -qe "$sbin_mount " /proc/mounts; then
1285                 umount $sbin_mount || true
1286                 [ -s $sbin_mount ] && ! grep -q "STUB MARK" $sbin_mount ||
1287                         rm -f $sbin_mount
1288         fi
1289
1290         [ -L /sbin/.libs ] && rm /sbin/.libs
1291
1292         [[ $rc -eq 0 ]] && echo "modules unloaded."
1293
1294         return $rc
1295 }
1296
1297 fs_log_size() {
1298         local facet=${1:-ost1}
1299         local size=0
1300         local mult=$OSTCOUNT
1301
1302         case $(facet_fstype $facet) in
1303                 ldiskfs) size=32;; # largest seen is 64 with multiple OSTs
1304                 # grant_block_size is in bytes, allow at least 2x max blocksize
1305                 zfs)     size=$(lctl get_param osc.$FSNAME*.import |
1306                                 awk '/grant_block_size:/ {print $2/512; exit;}')
1307                           ;;
1308         esac
1309
1310         [[ $facet =~ mds ]] && mult=$MDTCOUNT
1311         echo -n $((size * mult))
1312 }
1313
1314 fs_inode_ksize() {
1315         local facet=${1:-$SINGLEMDS}
1316         local fstype=$(facet_fstype $facet)
1317         local size=0
1318         case $fstype in
1319                 ldiskfs) size=4;;  # ~4KB per inode
1320                 zfs)     size=11;; # 10 to 11KB per inode
1321         esac
1322
1323         echo -n $size
1324 }
1325
1326 runas_su() {
1327         local user=$1
1328         local cmd=$2
1329         shift 2
1330         local opts="$*"
1331
1332         if $VERBOSE; then
1333                 echo Running as $user: $cmd $opts
1334         fi
1335         cmd=$(which $cmd)
1336         su - $user -c "$cmd $opts"
1337 }
1338
1339 check_gss_daemon_nodes() {
1340         local list=$1
1341         local dname=$(basename "$2" | awk '{print $1}')
1342         local loopmax=10
1343         local loop
1344         local node
1345         local ret
1346
1347         do_nodesv $list "num=0;
1348 for proc in \\\$(pgrep $dname); do
1349 [ \\\$(ps -o ppid= -p \\\$proc) -ne 1 ] || ((num++))
1350 done;
1351 if [ \\\"\\\$num\\\" -ne 1 ]; then
1352     echo \\\$num instance of $dname;
1353     exit 1;
1354 fi; "
1355         ret=$?
1356         (( $ret == 0 )) || return $ret
1357
1358         for node in ${list//,/ }; do
1359                 loop=0
1360                 while (( $loop < $loopmax )); do
1361                         do_nodesv $node "$L_GETAUTH -d"
1362                         ret=$?
1363                         (( $ret == 0 )) && break
1364                         loop=$((loop + 1))
1365                         sleep 5
1366                 done
1367                 (( $loop < $loopmax )) || return 1
1368         done
1369         return 0
1370 }
1371
1372 check_gss_daemon_facet() {
1373         local facet=$1
1374         local dname=$(basename "$2" | awk '{print $1}')
1375         local num=$(do_facet $facet ps -o cmd -C $dname | grep -c $dname)
1376
1377         if (( $num != 1 )); then
1378                 echo "$num instance of $dname on $facet"
1379                 return 1
1380         fi
1381         return 0
1382 }
1383
1384 send_sigint() {
1385         local list=$1
1386
1387         shift
1388         echo "Stopping "$@" on $list"
1389         do_nodes $list "killall -2 $* 2>/dev/null || true"
1390 }
1391
1392 # start gss daemons on all nodes, or "daemon" on "nodes" if set
1393 start_gss_daemons() {
1394         local nodes=$1
1395         local daemon=$2
1396         local options=$3
1397
1398         if [ "$nodes" ] && [ "$daemon" ] ; then
1399                 echo "Starting gss daemon on nodes: $nodes"
1400                 do_nodes $nodes "$daemon" "$options" || return 8
1401                 check_gss_daemon_nodes $nodes "$daemon" || return 9
1402                 return 0
1403         fi
1404
1405         nodes=$(mdts_nodes)
1406         echo "Starting gss daemon on mds: $nodes"
1407         if $GSS_SK; then
1408                 # Start all versions, in case of switching
1409                 do_nodes $nodes "$LSVCGSSD -vvv -s -m -o -z $options" ||
1410                         return 1
1411         else
1412                 do_nodes $nodes "$LSVCGSSD -vvv $options" || return 1
1413         fi
1414
1415         nodes=$(osts_nodes)
1416         echo "Starting gss daemon on ost: $nodes"
1417         if $GSS_SK; then
1418                 # Start all versions, in case of switching
1419                 do_nodes $nodes "$LSVCGSSD -vvv -s -m -o -z $options" ||
1420                         return 3
1421         else
1422                 do_nodes $nodes "$LSVCGSSD -vvv $options" || return 3
1423         fi
1424         # starting on clients
1425
1426         local clients=${CLIENTS:-$HOSTNAME}
1427
1428         #
1429         # check daemons are running
1430         #
1431         check_gss_daemon_nodes $(tgts_nodes) "$LSVCGSSD" || return 5
1432 }
1433
1434 stop_gss_daemons() {
1435         local nodes=$(mdts_nodes)
1436
1437         send_sigint $nodes lsvcgssd lgssd
1438
1439         nodes=$(osts_nodes)
1440         send_sigint $nodes lsvcgssd
1441
1442         nodes=${CLIENTS:-$HOSTNAME}
1443         send_sigint $nodes lgssd
1444 }
1445
1446 add_sk_mntflag() {
1447         # Add mount flags for shared key
1448         local mt_opts=$@
1449
1450         if grep -q skpath <<< "$mt_opts" ; then
1451                 mt_opts=$(echo $mt_opts |
1452                         sed -e "s#skpath=[^ ,]*#skpath=$SK_PATH#")
1453         else
1454                 if [ -z "$mt_opts" ]; then
1455                         mt_opts="-o skpath=$SK_PATH"
1456                 else
1457                         mt_opts="$mt_opts,skpath=$SK_PATH"
1458                 fi
1459         fi
1460         echo -n $mt_opts
1461 }
1462
1463 from_build_tree() {
1464         local from_tree
1465
1466         case $LUSTRE in
1467         /usr/lib/lustre/* | /usr/lib64/lustre/* | /usr/lib/lustre | \
1468         /usr/lib64/lustre )
1469                 from_tree=false
1470                 ;;
1471         *)
1472                 from_tree=true
1473                 ;;
1474         esac
1475
1476         [ $from_tree = true ]
1477 }
1478
1479 init_gss() {
1480         if $SHARED_KEY; then
1481                 GSS=true
1482                 GSS_SK=true
1483         fi
1484
1485         if ! $GSS; then
1486                 return
1487         fi
1488
1489         if ! module_loaded ptlrpc_gss; then
1490                 load_module ptlrpc/gss/ptlrpc_gss
1491                 module_loaded ptlrpc_gss ||
1492                         error_exit "init_gss: GSS=$GSS, but gss/krb5 missing"
1493         fi
1494
1495         if $GSS_KRB5 || $GSS_SK; then
1496                 start_gss_daemons || error_exit "start gss daemon failed! rc=$?"
1497         fi
1498
1499         if $GSS_SK && ! $SK_NO_KEY; then
1500                 echo "Loading basic SSK keys on all servers"
1501                 do_nodes $(comma_list $(all_server_nodes)) \
1502                         "$LGSS_SK -t server -l $SK_PATH/$FSNAME.key || true"
1503                 do_nodes $(comma_list $(all_server_nodes)) \
1504                                 "keyctl show | grep lustre | cut -c1-11 |
1505                                 sed -e 's/ //g;' |
1506                                 xargs -IX keyctl setperm X 0x3f3f3f3f"
1507         fi
1508
1509         if $GSS_SK && $SK_NO_KEY; then
1510                 local numclients=${1:-$CLIENTCOUNT}
1511                 local clients=${CLIENTS:-$HOSTNAME}
1512
1513                 # security ctx config for keyring
1514                 SK_NO_KEY=false
1515                 local lgssc_conf_file="/etc/request-key.d/lgssc.conf"
1516
1517                 if from_build_tree; then
1518                         mkdir -p $SK_OM_PATH
1519                         if grep -q request-key /proc/mounts > /dev/null; then
1520                                 echo "SSK: Request key already mounted."
1521                         else
1522                                 mount -o bind $SK_OM_PATH /etc/request-key.d/
1523                         fi
1524                         local lgssc_conf_line='create lgssc * * '
1525                         lgssc_conf_line+=$(which lgss_keyring)
1526                         lgssc_conf_line+=' %o %k %t %d %c %u %g %T %P %S'
1527                         echo "$lgssc_conf_line" > $lgssc_conf_file
1528                 fi
1529
1530                 [ -e $lgssc_conf_file ] ||
1531                         error_exit "Could not find key options in $lgssc_conf_file"
1532                 echo "$lgssc_conf_file content is:"
1533                 cat $lgssc_conf_file
1534
1535                 if ! local_mode; then
1536                         if from_build_tree; then
1537                                 do_nodes $(comma_list $(all_nodes)) "mkdir -p \
1538                                         $SK_OM_PATH"
1539                                 do_nodes $(comma_list $(all_nodes)) "mount \
1540                                         -o bind $SK_OM_PATH \
1541                                         /etc/request-key.d/"
1542                                 do_nodes $(comma_list $(all_nodes)) "rsync \
1543                                         -aqv $HOSTNAME:$lgssc_conf_file \
1544                                         $lgssc_conf_file >/dev/null 2>&1"
1545                         else
1546                                 do_nodes $(comma_list $(all_nodes)) \
1547                                         "echo $lgssc_conf_file: ; \
1548                                         cat $lgssc_conf_file"
1549                         fi
1550                 fi
1551
1552                 # create shared key on all nodes
1553                 mkdir -p $SK_PATH/nodemap
1554                 rm -f $SK_PATH/$FSNAME.key $SK_PATH/nodemap/c*.key \
1555                         $SK_PATH/$FSNAME-*.key
1556                 # for nodemap testing each client may need own key,
1557                 # and S2S now requires keys as well, both for "client"
1558                 # and for "server"
1559                 if $SK_S2S; then
1560                         $LGSS_SK -t server -f$FSNAME -n $SK_S2SNMCLI \
1561                                 -w $SK_PATH/$FSNAME-nmclient.key \
1562                                 -d /dev/urandom >/dev/null 2>&1
1563                         $LGSS_SK -t mgs,server -f$FSNAME -n $SK_S2SNM \
1564                                 -w $SK_PATH/$FSNAME-s2s-server.key \
1565                                 -d /dev/urandom >/dev/null 2>&1
1566                 fi
1567                 # basic key create
1568                 $LGSS_SK -t server -f$FSNAME -w $SK_PATH/$FSNAME.key \
1569                         -d /dev/urandom >/dev/null 2>&1
1570                 # per-nodemap keys
1571                 for i in $(seq 0 $((numclients - 1))); do
1572                         $LGSS_SK -t server -f$FSNAME -n c$i \
1573                                 -w $SK_PATH/nodemap/c$i.key -d /dev/urandom \
1574                                 >/dev/null 2>&1
1575                 done
1576                 # Distribute keys
1577                 if ! local_mode; then
1578                         for lnode in $(all_nodes); do
1579                                 scp -r $SK_PATH ${lnode}:$(dirname $SK_PATH)/
1580                         done
1581                 fi
1582                 # Set client keys to client type to generate prime P
1583                 if local_mode; then
1584                         do_nodes $(all_nodes) "$LGSS_SK -t client,server -m \
1585                                 $SK_PATH/$FSNAME.key >/dev/null 2>&1"
1586                 else
1587                         do_nodes $clients "$LGSS_SK -t client -m \
1588                                 $SK_PATH/$FSNAME.key >/dev/null 2>&1"
1589                         do_nodes $clients "find $SK_PATH/nodemap \
1590                                 -name \*.key | xargs -IX $LGSS_SK -t client \
1591                                 -m X >/dev/null 2>&1"
1592                         # also have a client key available on server side,
1593                         # for local client mount
1594                         do_nodes $(comma_list $(all_server_nodes)) \
1595                         "cp $SK_PATH/$FSNAME.key $SK_PATH/${FSNAME}_cli.key && \
1596                          $LGSS_SK -t client -m \
1597                                 $SK_PATH/${FSNAME}_cli.key >/dev/null 2>&1"
1598                 fi
1599                 # This is required for servers as well, if S2S in use
1600                 if $SK_S2S; then
1601                         do_nodes $(tgts_nodes) \
1602                                 "cp $SK_PATH/$FSNAME-s2s-server.key \
1603                                 $SK_PATH/$FSNAME-s2s-client.key; $LGSS_SK \
1604                                 -t client -m $SK_PATH/$FSNAME-s2s-client.key \
1605                                 >/dev/null 2>&1"
1606                         do_nodes $clients "$LGSS_SK -t client \
1607                                 -m $SK_PATH/$FSNAME-nmclient.key \
1608                                  >/dev/null 2>&1"
1609                 fi
1610         fi
1611         if $GSS_SK; then
1612                 # mount options for servers and clients
1613                 MGS_MOUNT_OPTS=$(add_sk_mntflag $MGS_MOUNT_OPTS)
1614                 MDS_MOUNT_OPTS=$(add_sk_mntflag $MDS_MOUNT_OPTS)
1615                 OST_MOUNT_OPTS=$(add_sk_mntflag $OST_MOUNT_OPTS)
1616                 MOUNT_OPTS=$(add_sk_mntflag $MOUNT_OPTS)
1617                 SEC=$SK_FLAVOR
1618                 if [ -z "$LGSS_KEYRING_DEBUG" ]; then
1619                         LGSS_KEYRING_DEBUG=4
1620                 fi
1621         fi
1622
1623         if [ -n "$LGSS_KEYRING_DEBUG" ] && \
1624                ( local_mode || from_build_tree ); then
1625                 lctl set_param -n \
1626                      sptlrpc.gss.lgss_keyring.debug_level=$LGSS_KEYRING_DEBUG
1627         elif [ -n "$LGSS_KEYRING_DEBUG" ]; then
1628                 do_nodes $(comma_list $(all_nodes)) "modprobe ptlrpc_gss && \
1629                 lctl set_param -n \
1630                    sptlrpc.gss.lgss_keyring.debug_level=$LGSS_KEYRING_DEBUG"
1631         fi
1632
1633         do_nodesv $(comma_list $(all_server_nodes)) \
1634                 "$LCTL set_param sptlrpc.gss.rsi_upcall=$L_GETAUTH"
1635 }
1636
1637 cleanup_gss() {
1638         if $GSS; then
1639                 stop_gss_daemons
1640                 # maybe cleanup credential cache?
1641         fi
1642 }
1643
1644 cleanup_sk() {
1645         if $GSS_SK; then
1646                 if $SK_S2S; then
1647                         do_node $(mgs_node) "$LCTL nodemap_del $SK_S2SNM"
1648                         do_node $(mgs_node) "$LCTL nodemap_del $SK_S2SNMCLI"
1649                         $RPC_MODE || echo "Sleeping for 10 sec for Nodemap.."
1650                         sleep 10
1651                 fi
1652                 stop_gss_daemons
1653                 $RPC_MODE || echo "Cleaning up Shared Key.."
1654                 do_nodes $(comma_list $(all_nodes)) "rm -f \
1655                         $SK_PATH/$FSNAME*.key $SK_PATH/nodemap/$FSNAME*.key"
1656                 do_nodes $(comma_list $(all_nodes)) "keyctl show | \
1657                   awk '/lustre/ { print \\\$1 }' | xargs -IX keyctl unlink X"
1658                 if from_build_tree; then
1659                         # Remove the mount and clean up the files we added to
1660                         # SK_PATH
1661                         do_nodes $(comma_list $(all_nodes)) "while grep -q \
1662                                 request-key.d /proc/mounts; do umount \
1663                                 /etc/request-key.d/; done"
1664                         do_nodes $(comma_list $(all_nodes)) "rm -f \
1665                                 $SK_OM_PATH/lgssc.conf"
1666                         do_nodes $(comma_list $(all_nodes)) "rmdir $SK_OM_PATH"
1667                 fi
1668                 SK_NO_KEY=true
1669         fi
1670 }
1671
1672 facet_svc() {
1673         local facet=$1
1674         local var=${facet}_svc
1675
1676         echo -n ${!var}
1677 }
1678
1679 facet_type() {
1680         local facet=$1
1681
1682         echo -n $facet | sed -e 's/^fs[0-9]\+//' -e 's/[0-9_]\+//' |
1683                 tr '[:lower:]' '[:upper:]'
1684 }
1685
1686 facet_number() {
1687         local facet=$1
1688
1689         if [ $facet == mgs ] || [ $facet == client ]; then
1690                 return 1
1691         fi
1692
1693         echo -n $facet | sed -e 's/^fs[0-9]\+//' | sed -e 's/^[a-z]\+//'
1694 }
1695
1696 facet_fstype() {
1697         local facet=$1
1698         local var
1699
1700         var=${facet}_FSTYPE
1701         if [ -n "${!var}" ]; then
1702                 echo -n ${!var}
1703                 return
1704         fi
1705
1706         var=$(facet_type $facet)FSTYPE
1707         if [ -n "${!var}" ]; then
1708                 echo -n ${!var}
1709                 return
1710         fi
1711
1712         if [ -n "$FSTYPE" ]; then
1713                 echo -n $FSTYPE
1714                 return
1715         fi
1716
1717         if [[ $facet == mgs ]] && combined_mgs_mds; then
1718                 facet_fstype mds1
1719                 return
1720         fi
1721
1722         return 1
1723 }
1724
1725 node_fstypes() {
1726         local node=$1
1727         local fstypes
1728         local fstype
1729         local facets=$(get_facets)
1730         local facet
1731
1732         for facet in ${facets//,/ }; do
1733                 if [[ $node == $(facet_host $facet) ]] ||
1734                    [[ $node == "$(facet_failover_host $facet)" ]]; then
1735                         fstype=$(facet_fstype $facet)
1736                         if [[ $fstypes != *$fstype* ]]; then
1737                                 fstypes+="${fstypes:+,}$fstype"
1738                         fi
1739                 fi
1740         done
1741         echo -n $fstypes
1742 }
1743
1744 facet_index() {
1745         local facet=$1
1746         local num=$(facet_number $facet)
1747         local index
1748
1749         if [[ $(facet_type $facet) = OST ]]; then
1750                 index=OSTINDEX${num}
1751                 if [[ -n "${!index}" ]]; then
1752                         echo -n ${!index}
1753                         return
1754                 fi
1755
1756                 index=${OST_INDICES[num - 1]}
1757         fi
1758
1759         [[ -n "$index" ]] || index=$((num - 1))
1760         echo -n $index
1761 }
1762
1763 devicelabel() {
1764         local facet=$1
1765         local dev=$2
1766         local label
1767         local fstype=$(facet_fstype $facet)
1768
1769         case $fstype in
1770         ldiskfs)
1771                 label=$(do_facet ${facet} "$E2LABEL ${dev} 2>/dev/null");;
1772         zfs)
1773                 label=$(do_facet ${facet} "$ZFS get -H -o value lustre:svname \
1774                                            ${dev} 2>/dev/null");;
1775         wbcfs)
1776                 label="wbcfs-target";;
1777         *)
1778                 error "unknown fstype!";;
1779         esac
1780
1781         echo -n $label
1782 }
1783
1784 #
1785 # Get the device of a facet.
1786 #
1787 facet_device() {
1788         local facet=$1
1789         local device
1790
1791         case $facet in
1792                 mgs) device=$(mgsdevname) ;;
1793                 mds*) device=$(mdsdevname $(facet_number $facet)) ;;
1794                 ost*) device=$(ostdevname $(facet_number $facet)) ;;
1795                 fs2mds) device=$(mdsdevname 1_2) ;;
1796                 fs2ost) device=$(ostdevname 1_2) ;;
1797                 fs3ost) device=$(ostdevname 2_2) ;;
1798                 *) ;;
1799         esac
1800
1801         echo -n $device
1802 }
1803
1804 #
1805 # Get the virtual device of a facet.
1806 #
1807 facet_vdevice() {
1808         local facet=$1
1809         local device
1810
1811         case $facet in
1812                 mgs) device=$(mgsvdevname) ;;
1813                 mds*) device=$(mdsvdevname $(facet_number $facet)) ;;
1814                 ost*) device=$(ostvdevname $(facet_number $facet)) ;;
1815                 fs2mds) device=$(mdsvdevname 1_2) ;;
1816                 fs2ost) device=$(ostvdevname 1_2) ;;
1817                 fs3ost) device=$(ostvdevname 2_2) ;;
1818                 *) ;;
1819         esac
1820
1821         echo -n $device
1822 }
1823
1824 running_in_vm() {
1825         local virt=$(virt-what 2> /dev/null)
1826
1827         [ $? -eq 0 ] && [ -n "$virt" ] && { echo $virt; return; }
1828
1829         virt=$(dmidecode -s system-product-name | awk '{print $1}')
1830
1831         case $virt in
1832                 VMware|KVM|VirtualBox|Parallels|Bochs)
1833                         echo $virt | tr '[A-Z]' '[a-z]' && return;;
1834
1835                 *) ;;
1836         esac
1837
1838         virt=$(dmidecode -s system-manufacturer | awk '{print $1}')
1839         case $virt in
1840                 QEMU)
1841                         echo $virt | tr '[A-Z]' '[a-z]' && return;;
1842                 *) ;;
1843         esac
1844 }
1845
1846 #
1847 # Re-read the partition table on failover partner host.
1848 # After a ZFS storage pool is created on a shared device, the partition table
1849 # on the device may change. However, the operating system on the failover
1850 # host may not notice the change automatically. Without the up-to-date partition
1851 # block devices, 'zpool import ..' cannot find the labels, whose positions are
1852 # relative to partition rather than disk beginnings.
1853 #
1854 # This function performs partprobe on the failover host to make it re-read the
1855 # partition table.
1856 #
1857 refresh_partition_table() {
1858         local facet=$1
1859         local device=$2
1860         local host
1861
1862         host=$(facet_passive_host $facet)
1863         if [[ -n "$host" ]]; then
1864                 do_node $host "$PARTPROBE $device"
1865         fi
1866 }
1867
1868 #
1869 # Get ZFS storage pool name.
1870 #
1871 zpool_name() {
1872         local facet=$1
1873         local device
1874         local poolname
1875
1876         device=$(facet_device $facet)
1877         # poolname is string before "/"
1878         poolname="${device%%/*}"
1879
1880         echo -n $poolname
1881 }
1882
1883 #
1884 #
1885 # Get ZFS local fsname.
1886 #
1887 zfs_local_fsname() {
1888         local facet=$1
1889         local lfsname=$(basename $(facet_device $facet))
1890
1891         echo -n $lfsname
1892 }
1893
1894 #
1895 # Create ZFS storage pool.
1896 #
1897 create_zpool() {
1898         local facet=$1
1899         local poolname=$2
1900         local vdev=$3
1901         shift 3
1902         local opts=${@:-"-o cachefile=none"}
1903
1904         do_facet $facet "lsmod | grep zfs >&/dev/null || modprobe zfs;
1905                 $ZPOOL list -H $poolname >/dev/null 2>&1 ||
1906                 $ZPOOL create -f $opts $poolname $vdev"
1907 }
1908
1909 #
1910 # Create ZFS file system.
1911 #
1912 create_zfs() {
1913         local facet=$1
1914         local dataset=$2
1915         shift 2
1916         local opts=${@:-"-o mountpoint=legacy"}
1917
1918         do_facet $facet "$ZFS list -H $dataset >/dev/null 2>&1 ||
1919                 $ZFS create $opts $dataset"
1920 }
1921
1922 #
1923 # Export ZFS storage pool.
1924 # Before exporting the pool, all datasets within the pool should be unmounted.
1925 #
1926 export_zpool() {
1927         local facet=$1
1928         shift
1929         local opts="$@"
1930         local poolname
1931
1932         poolname=$(zpool_name $facet)
1933
1934         if [[ -n "$poolname" ]]; then
1935                 do_facet $facet "! $ZPOOL list -H $poolname >/dev/null 2>&1 ||
1936                         grep -q ^$poolname/ /proc/mounts ||
1937                         $ZPOOL export $opts $poolname"
1938         fi
1939 }
1940
1941 #
1942 # Destroy ZFS storage pool.
1943 # Destroy the given pool and free up any devices for other use. This command
1944 # tries to unmount any active datasets before destroying the pool.
1945 # -f    Force any active datasets contained within the pool to be unmounted.
1946 #
1947 destroy_zpool() {
1948         local facet=$1
1949         local poolname=${2:-$(zpool_name $facet)}
1950
1951         if [[ -n "$poolname" ]]; then
1952                 do_facet $facet "! $ZPOOL list -H $poolname >/dev/null 2>&1 ||
1953                         $ZPOOL destroy -f $poolname"
1954         fi
1955 }
1956
1957 #
1958 # Import ZFS storage pool.
1959 # Force importing, even if the pool appears to be potentially active.
1960 #
1961 import_zpool() {
1962         local facet=$1
1963         shift
1964         local opts=${@:-"-o cachefile=none -o failmode=panic"}
1965         local poolname
1966
1967         poolname=$(zpool_name $facet)
1968
1969         if [[ -n "$poolname" ]]; then
1970                 opts+=" -d $(dirname $(facet_vdevice $facet))"
1971                 do_facet $facet "lsmod | grep zfs >&/dev/null || modprobe zfs;
1972                         $ZPOOL list -H $poolname >/dev/null 2>&1 ||
1973                         $ZPOOL import -f $opts $poolname"
1974         fi
1975 }
1976
1977 #
1978 # Reimport ZFS storage pool with new name
1979 #
1980 reimport_zpool() {
1981         local facet=$1
1982         local newpool=$2
1983         local opts="-o cachefile=none"
1984         local poolname=$(zpool_name $facet)
1985
1986         opts+=" -d $(dirname $(facet_vdevice $facet))"
1987         do_facet $facet "$ZPOOL export $poolname;
1988                          $ZPOOL import $opts $poolname $newpool"
1989 }
1990
1991 #
1992 # Set the "cachefile=none" property on ZFS storage pool so that the pool
1993 # is not automatically imported on system startup.
1994 #
1995 # In a failover environment, this will provide resource level fencing which
1996 # will ensure that the same ZFS storage pool will not be imported concurrently
1997 # on different nodes.
1998 #
1999 disable_zpool_cache() {
2000         local facet=$1
2001         local poolname
2002
2003         poolname=$(zpool_name $facet)
2004
2005         if [[ -n "$poolname" ]]; then
2006                 do_facet $facet "$ZPOOL set cachefile=none $poolname"
2007         fi
2008 }
2009
2010 #
2011 # This and set_osd_param() shall be used to access OSD parameters
2012 # once existed under "obdfilter":
2013 #
2014 #   mntdev
2015 #   stats
2016 #   read_cache_enable
2017 #   writethrough_cache_enable
2018 #
2019 get_osd_param() {
2020         local nodes=$1
2021         local device=${2:-$FSNAME-OST*}
2022         local name=$3
2023
2024         do_nodes $nodes "$LCTL get_param -n osd-*.$device.$name"
2025 }
2026
2027 set_osd_param() {
2028         local nodes=$1
2029         local device=${2:-$FSNAME-OST*}
2030         local name=$3
2031         local value=$4
2032
2033         do_nodes $nodes "$LCTL set_param -n osd-*.$device.$name=$value"
2034 }
2035
2036 set_default_debug () {
2037         local debug=${1:-"$PTLDEBUG"}
2038         local subsys=${2:-"$SUBSYSTEM"}
2039         local debug_size=${3:-$DEBUG_SIZE}
2040
2041         [ -n "$debug" ] && lctl set_param debug="$debug" >/dev/null
2042         [ -n "$subsys" ] &&
2043                 lctl set_param subsystem_debug="${subsys# }" >/dev/null
2044         [ -n "$debug_size" ] &&
2045                 lctl set_param debug_mb="$debug_size" >/dev/null
2046
2047         return 0
2048 }
2049
2050 set_default_debug_nodes () {
2051         local nodes="$1"
2052         local debug="${2:-"$PTLDEBUG"}"
2053         local subsys="${3:-"$SUBSYSTEM"}"
2054         local debug_size="${4:-$DEBUG_SIZE}"
2055
2056         if [[ ,$nodes, = *,$HOSTNAME,* ]]; then
2057                 nodes=$(exclude_items_from_list "$nodes" "$HOSTNAME")
2058                 set_default_debug
2059         fi
2060
2061         [[ -z "$nodes" ]] ||
2062                 do_rpc_nodes "$nodes" set_default_debug \
2063                         \\\"$debug\\\" \\\"$subsys\\\" $debug_size || true
2064 }
2065
2066 set_default_debug_facet () {
2067         local facet=$1
2068         local debug="${2:-"$PTLDEBUG"}"
2069         local subsys="${3:-"$SUBSYSTEM"}"
2070         local debug_size="${4:-$DEBUG_SIZE}"
2071         local node=$(facet_active_host $facet)
2072
2073         [ -n "$node" ] || error "No host defined for facet $facet"
2074
2075         set_default_debug_nodes $node "$debug" "$subsys" $debug_size
2076 }
2077
2078 set_params_nodes() {
2079         (( $# >= 2 )) || return 0
2080         local nodes=$1
2081         shift || true
2082         local params="$@"
2083
2084         [[ -n "$params" ]] || return 0
2085
2086         do_nodes $nodes "$LCTL set_param $params"
2087 }
2088
2089 set_params_clients() {
2090         local clients=${1:-$CLIENTS}
2091         shift || true
2092         local params="${@:-$CLIENT_LCTL_SETPARAM_PARAM}"
2093
2094         set_params_nodes $clients $params
2095 }
2096
2097 set_params_mdts() {
2098         local mdts=${1:-$(mdts_nodes)}
2099         shift || true
2100         local params="${@:-$MDS_LCTL_SETPARAM_PARAM}"
2101
2102         set_params_nodes $mdts $params
2103 }
2104
2105 set_params_osts() {
2106         local osts=${1:-$(osts_nodes)}
2107         shift || true
2108         local params="${@:-$OSS_LCTL_SETPARAM_PARAM}"
2109
2110         set_params_nodes $osts $params
2111 }
2112
2113 set_hostid () {
2114         local hostid=${1:-$(hostid)}
2115
2116         if [ ! -s /etc/hostid ]; then
2117                 printf $(echo -n $hostid |
2118             sed 's/\(..\)\(..\)\(..\)\(..\)/\\x\4\\x\3\\x\2\\x\1/') >/etc/hostid
2119         fi
2120 }
2121
2122 # Facet functions
2123 mount_facets () {
2124         local facets=${1:-$(get_facets)}
2125         local facet
2126         local -a mountpids
2127         local total=0
2128         local ret=0
2129
2130         for facet in ${facets//,/ }; do
2131                 mount_facet $facet &
2132                 mountpids[total]=$!
2133                 total=$((total+1))
2134         done
2135         for ((index=0; index<$total; index++)); do
2136                 wait ${mountpids[index]}
2137                 local RC=$?
2138                 [ $RC -eq 0 ] && continue
2139
2140                 if [ "$TESTSUITE.$TESTNAME" = "replay-dual.test_0a" ]; then
2141                         skip_noexit "Restart of $facet failed!." &&
2142                                 touch $LU482_FAILED
2143                 else
2144                         error "Restart of $facet failed!"
2145                 fi
2146                 ret=$RC
2147         done
2148         return $ret
2149 }
2150
2151 #
2152 # Add argument "arg" (e.g., "loop") to the comma-separated list
2153 # of arguments for option "opt" (e.g., "-o") on command
2154 # line "opts" (e.g., "-o flock").
2155 #
2156 csa_add() {
2157         local opts=$1
2158         local opt=$2
2159         local arg=$3
2160         local opt_pattern="\([[:space:]]\+\|^\)$opt"
2161
2162         if echo "$opts" | grep -q $opt_pattern; then
2163                 opts=$(echo "$opts" | sed -e \
2164                         "s/$opt_pattern[[:space:]]*[^[:space:]]\+/&,$arg/")
2165         else
2166                 opts+="${opts:+ }$opt $arg"
2167         fi
2168         echo -n "$opts"
2169 }
2170
2171 #
2172 # Associate loop device with a given regular file.
2173 # Return the loop device.
2174 #
2175 setup_loop_device() {
2176         local facet=$1
2177         local file=$2
2178
2179         do_facet $facet "loop_dev=\\\$($LOSETUP -j $file | cut -d : -f 1);
2180                          if [[ -z \\\$loop_dev ]]; then
2181                                 loop_dev=\\\$($LOSETUP -f);
2182                                 $LOSETUP \\\$loop_dev $file || loop_dev=;
2183                          fi;
2184                          echo -n \\\$loop_dev"
2185 }
2186
2187 #
2188 # Detach a loop device.
2189 #
2190 cleanup_loop_device() {
2191         local facet=$1
2192         local loop_dev=$2
2193
2194         do_facet $facet "! $LOSETUP $loop_dev >/dev/null 2>&1 ||
2195                          $LOSETUP -d $loop_dev"
2196 }
2197
2198 #
2199 # Check if a given device is a block device.
2200 #
2201 is_blkdev() {
2202         local facet=$1
2203         local dev=$2
2204         local size=${3:-""}
2205
2206         [[ -n "$dev" ]] || return 1
2207         do_facet $facet "test -b $dev" || return 1
2208         if [[ -n "$size" ]]; then
2209                 local in=$(do_facet $facet "dd if=$dev of=/dev/null bs=1k \
2210                                             count=1 skip=$size 2>&1" |
2211                                             awk '($3 == "in") { print $1 }')
2212                 [[ "$in" = "1+0" ]] || return 1
2213         fi
2214 }
2215
2216 #
2217 # Check if a given device is a device-mapper device.
2218 #
2219 is_dm_dev() {
2220         local facet=$1
2221         local dev=$2
2222
2223         [[ -n "$dev" ]] || return 1
2224         do_facet $facet "$DMSETUP status $dev >/dev/null 2>&1"
2225 }
2226
2227 #
2228 # Check if a given device is a device-mapper flakey device.
2229 #
2230 is_dm_flakey_dev() {
2231         local facet=$1
2232         local dev=$2
2233         local type
2234
2235         [[ -n "$dev" ]] || return 1
2236
2237         type=$(do_facet $facet "$DMSETUP status $dev 2>&1" |
2238                awk '{print $3}')
2239         [[ $type = flakey ]] && return 0 || return 1
2240 }
2241
2242 #
2243 # Check if device-mapper flakey device is supported by the kernel
2244 # of $facet node or not.
2245 #
2246 dm_flakey_supported() {
2247         local facet=$1
2248
2249         $FLAKEY || return 1
2250         do_facet $facet "modprobe dm-flakey;
2251                          $DMSETUP targets | grep -q flakey" &> /dev/null
2252 }
2253
2254 #
2255 # Get the device-mapper flakey device name of a given facet.
2256 #
2257 dm_facet_devname() {
2258         local facet=$1
2259         [[ $facet = mgs ]] && combined_mgs_mds && facet=mds1
2260
2261         echo -n ${facet}_flakey
2262 }
2263
2264 #
2265 # Get the device-mapper flakey device of a given facet.
2266 # A device created by dmsetup will appear as /dev/mapper/<device-name>.
2267 #
2268 dm_facet_devpath() {
2269         local facet=$1
2270
2271         echo -n $DM_DEV_PATH/$(dm_facet_devname $facet)
2272 }
2273
2274 #
2275 # Set a device-mapper device with a new table.
2276 #
2277 # The table has the following format:
2278 # <logical_start_sector> <num_sectors> <target_type> <target_args>
2279 #
2280 # flakey <target_args> includes:
2281 # <destination_device> <offset> <up_interval> <down_interval> \
2282 # [<num_features> [<feature_arguments>]]
2283 #
2284 # linear <target_args> includes:
2285 # <destination_device> <start_sector>
2286 #
2287 dm_set_dev_table() {
2288         local facet=$1
2289         local dm_dev=$2
2290         local target_type=$3
2291         local num_sectors
2292         local real_dev
2293         local tmp
2294         local table
2295
2296         read tmp num_sectors tmp real_dev tmp \
2297                 <<< $(do_facet $facet "$DMSETUP table $dm_dev")
2298
2299         case $target_type in
2300         flakey)
2301                 table="0 $num_sectors flakey $real_dev 0 0 1800 1 drop_writes"
2302                 ;;
2303         linear)
2304                 table="0 $num_sectors linear $real_dev 0"
2305                 ;;
2306         *) error "invalid target type $target_type" ;;
2307         esac
2308
2309         do_facet $facet "$DMSETUP suspend --nolockfs --noflush $dm_dev" ||
2310                 error "failed to suspend $dm_dev"
2311         do_facet $facet "$DMSETUP load $dm_dev --table \\\"$table\\\"" ||
2312                 error "failed to load $target_type table into $dm_dev"
2313         do_facet $facet "$DMSETUP resume $dm_dev" ||
2314                 error "failed to resume $dm_dev"
2315 }
2316
2317 #
2318 # Set a device-mapper flakey device as "read-only" by using the "drop_writes"
2319 # feature parameter.
2320 #
2321 # drop_writes:
2322 #       All write I/O is silently ignored.
2323 #       Read I/O is handled correctly.
2324 #
2325 dm_set_dev_readonly() {
2326         local facet=$1
2327         local dm_dev=${2:-$(dm_facet_devpath $facet)}
2328
2329         dm_set_dev_table $facet $dm_dev flakey
2330 }
2331
2332 #
2333 # Set a device-mapper device to traditional linear mapping mode.
2334 #
2335 dm_clear_dev_readonly() {
2336         local facet=$1
2337         local dm_dev=${2:-$(dm_facet_devpath $facet)}
2338
2339         dm_set_dev_table $facet $dm_dev linear
2340 }
2341
2342 #
2343 # Set the device of a given facet as "read-only".
2344 #
2345 set_dev_readonly() {
2346         local facet=$1
2347         local svc=${facet}_svc
2348
2349         if [[ $(facet_fstype $facet) = zfs ]] ||
2350            ! dm_flakey_supported $facet; then
2351                 do_facet $facet $LCTL --device ${!svc} readonly
2352         else
2353                 dm_set_dev_readonly $facet
2354         fi
2355 }
2356
2357 #
2358 # Get size in 512-byte sectors (BLKGETSIZE64 / 512) of a given device.
2359 #
2360 get_num_sectors() {
2361         local facet=$1
2362         local dev=$2
2363         local num_sectors
2364
2365         num_sectors=$(do_facet $facet "blockdev --getsz $dev 2>/dev/null")
2366         [[ ${PIPESTATUS[0]} = 0 && -n "$num_sectors" ]] || num_sectors=0
2367         echo -n $num_sectors
2368 }
2369
2370 #
2371 # Create a device-mapper device with a given block device or regular file (will
2372 # be associated with loop device).
2373 # Return the full path of the device-mapper device.
2374 #
2375 dm_create_dev() {
2376         local facet=$1
2377         local real_dev=$2                                  # destination device
2378         local dm_dev_name=${3:-$(dm_facet_devname $facet)} # device name
2379         local dm_dev=$DM_DEV_PATH/$dm_dev_name            # device-mapper device
2380
2381         # check if the device-mapper device to be created already exists
2382         if is_dm_dev $facet $dm_dev; then
2383                 # if the existing device was set to "read-only", then clear it
2384                 ! is_dm_flakey_dev $facet $dm_dev ||
2385                         dm_clear_dev_readonly $facet $dm_dev
2386
2387                 echo -n $dm_dev
2388                 return 0
2389         fi
2390
2391         # check if the destination device is a block device, and if not,
2392         # associate it with a loop device
2393         is_blkdev $facet $real_dev ||
2394                 real_dev=$(setup_loop_device $facet $real_dev)
2395         [[ -n "$real_dev" ]] || { echo -n $real_dev; return 2; }
2396
2397         # now create the device-mapper device
2398         local num_sectors=$(get_num_sectors $facet $real_dev)
2399         local table="0 $num_sectors linear $real_dev 0"
2400         local rc=0
2401
2402         do_facet $facet "$DMSETUP create $dm_dev_name --table \\\"$table\\\"" ||
2403                 { rc=${PIPESTATUS[0]}; dm_dev=; }
2404         do_facet $facet "$DMSETUP mknodes >/dev/null 2>&1"
2405
2406         echo -n $dm_dev
2407         return $rc
2408 }
2409
2410 #
2411 # Map the facet name to its device variable name.
2412 #
2413 facet_device_alias() {
2414         local facet=$1
2415         local dev_alias=$facet
2416
2417         case $facet in
2418                 fs2mds) dev_alias=mds1_2 ;;
2419                 fs2ost) dev_alias=ost1_2 ;;
2420                 fs3ost) dev_alias=ost2_2 ;;
2421                 *) ;;
2422         esac
2423
2424         echo -n $dev_alias
2425 }
2426
2427 #
2428 # Save the original value of the facet device and export the new value.
2429 #
2430 export_dm_dev() {
2431         local facet=$1
2432         local dm_dev=$2
2433
2434         local active_facet=$(facet_active $facet)
2435         local dev_alias=$(facet_device_alias $active_facet)
2436         local dev_name=${dev_alias}_dev
2437         local dev=${!dev_name}
2438
2439         if [[ $active_facet = $facet ]]; then
2440                 local failover_dev=${dev_alias}failover_dev
2441                 if [[ ${!failover_dev} = $dev ]]; then
2442                         eval export ${failover_dev}_saved=$dev
2443                         eval export ${failover_dev}=$dm_dev
2444                 fi
2445         else
2446                 dev_alias=$(facet_device_alias $facet)
2447                 local facet_dev=${dev_alias}_dev
2448                 if [[ ${!facet_dev} = $dev ]]; then
2449                         eval export ${facet_dev}_saved=$dev
2450                         eval export ${facet_dev}=$dm_dev
2451                 fi
2452         fi
2453
2454         eval export ${dev_name}_saved=$dev
2455         eval export ${dev_name}=$dm_dev
2456 }
2457
2458 #
2459 # Restore the saved value of the facet device.
2460 #
2461 unexport_dm_dev() {
2462         local facet=$1
2463
2464         [[ $facet = mgs ]] && combined_mgs_mds && facet=mds1
2465         local dev_alias=$(facet_device_alias $facet)
2466
2467         local saved_dev=${dev_alias}_dev_saved
2468         [[ -z ${!saved_dev} ]] ||
2469                 eval export ${dev_alias}_dev=${!saved_dev}
2470
2471         saved_dev=${dev_alias}failover_dev_saved
2472         [[ -z ${!saved_dev} ]] ||
2473                 eval export ${dev_alias}failover_dev=${!saved_dev}
2474 }
2475
2476 #
2477 # Remove a device-mapper device.
2478 # If the destination device is a loop device, then also detach it.
2479 #
2480 dm_cleanup_dev() {
2481         local facet=$1
2482         local dm_dev=${2:-$(dm_facet_devpath $facet)}
2483         local major
2484         local minor
2485
2486         is_dm_dev $facet $dm_dev || return 0
2487
2488         read major minor <<< $(do_facet $facet "$DMSETUP table $dm_dev" |
2489                 awk '{ print $4 }' | awk -F: '{ print $1" "$2 }')
2490
2491         do_facet $facet "$DMSETUP remove $dm_dev"
2492         do_facet $facet "$DMSETUP mknodes >/dev/null 2>&1"
2493
2494         unexport_dm_dev $facet
2495
2496         # detach a loop device
2497         [[ $major -ne 7 ]] || cleanup_loop_device $facet /dev/loop$minor
2498
2499         # unload dm-flakey module
2500         do_facet $facet "modprobe -r dm-flakey" || true
2501 }
2502
2503 mount_facet() {
2504         local facet=$1
2505         shift
2506         local active_facet=$(facet_active $facet)
2507         local dev_alias=$(facet_device_alias $active_facet)
2508         local dev=${dev_alias}_dev
2509         local opt=${facet}_opt
2510         local mntpt=$(facet_mntpt $facet)
2511         local opts="${!opt} $@"
2512         local fstype=$(facet_fstype $facet)
2513         local devicelabel
2514         local dm_dev=${!dev}
2515         local index=$(facet_index $facet)
2516         local node_type=$(facet_type $facet)
2517
2518         [[ $dev == "mgsfailover_dev" ]] && combined_mgs_mds &&
2519                 dev=mds1failover_dev
2520
2521         module_loaded lustre || load_modules
2522
2523         case $fstype in
2524         ldiskfs)
2525                 if dm_flakey_supported $facet; then
2526                         dm_dev=$(dm_create_dev $facet ${!dev})
2527                         [[ -n "$dm_dev" ]] || dm_dev=${!dev}
2528                 fi
2529
2530                 is_blkdev $facet $dm_dev || opts=$(csa_add "$opts" -o loop)
2531
2532                 devicelabel=$(do_facet ${facet} "$E2LABEL $dm_dev");;
2533         zfs)
2534                 # import ZFS storage pool
2535                 import_zpool $facet || return ${PIPESTATUS[0]}
2536
2537                 devicelabel=$(do_facet ${facet} "$ZFS get -H -o value \
2538                                                 lustre:svname $dm_dev");;
2539         wbcfs)
2540                 :;;
2541         *)
2542                 error "unknown fstype!";;
2543         esac
2544
2545         # for testing LU-482 error handling in mount_facets() and test_0a()
2546         if [ -f $TMP/test-lu482-trigger ]; then
2547                 RC=2
2548         else
2549                 local seq_width=$(($OSTSEQWIDTH / $OSTCOUNT))
2550                 (( $seq_width >= 16384 )) || seq_width=16384
2551
2552                 case $fstype in
2553                 wbcfs)
2554                         echo "Start ${facet}: $MOUNT_CMD -v lustre-wbcfs $mntpt"
2555
2556                         export OSD_WBC_FSNAME="$FSNAME"
2557                         export OSD_WBC_INDEX="$index"
2558                         export OSD_WBC_MGS_NID="$MGSNID"
2559
2560                         case $node_type in
2561                         OST)
2562                                 export OSD_WBC_TGT_TYPE="OST"
2563                                 ;;
2564                         MDS)
2565                                 export OSD_WBC_TGT_TYPE="MDT"
2566                                 if (( $index == 0 )) &&
2567                                         [[ "$mds_HOST" == "$mgs_HOST" ]]; then
2568                                         export OSD_WBC_PRIMARY_MDT="1"
2569                                 else
2570                                         export OSD_WBC_PRIMARY_MDT="0"
2571                                 fi
2572                                 ;;
2573                         MGS)
2574                                 export OSD_WBC_TGT_TYPE="MGT"
2575                                 ;;
2576                         *)
2577                                 error "Unhandled node_type!"
2578                         esac
2579
2580                         do_facet ${facet} "mkdir -p $mntpt; \
2581                                  OSD_WBC_TGT_TYPE=$OSD_WBC_TGT_TYPE \
2582                                  OSD_WBC_INDEX=$OSD_WBC_INDEX \
2583                                  OSD_WBC_MGS_NID=$OSD_WBC_MGS_NID \
2584                                  OSD_WBC_PRIMARY_MDT=$OSD_WBC_PRIMARY_MDT \
2585                                  OSD_WBC_FSNAME=$OSD_WBC_FSNAME \
2586                                  $MOUNT_CMD -v lustre-wbcfs $mntpt"
2587                         ;;
2588                 *)
2589                         echo "Start ${facet}: $MOUNT_CMD $opts $dm_dev $mntpt"
2590                         do_facet ${facet} \
2591                                 "mkdir -p $mntpt; $MOUNT_CMD $opts $dm_dev $mntpt"
2592                 esac
2593
2594                 RC=${PIPESTATUS[0]}
2595                 if [[ ${facet} =~ ost ]] && [[ ! "$fstype" == "wbcfs" ]]; then
2596                         do_facet ${facet} "$LCTL set_param \
2597                                 seq.cli-$(devicelabel $facet $dm_dev)-super.width=$seq_width"
2598                 fi
2599         fi
2600
2601         if [ $RC -ne 0 ]; then
2602                 echo "Start of $dm_dev on ${facet} failed ${RC}"
2603                 return $RC
2604         fi
2605
2606         health=$(do_facet ${facet} "$LCTL get_param -n health_check")
2607         if [[ "$health" != "healthy" ]]; then
2608                 error "$facet is in a unhealthy state, got: '$health'"
2609         fi
2610
2611         set_default_debug_facet $facet
2612
2613         if [[ $opts =~ .*nosvc.* ]]; then
2614                 echo "Start $dm_dev without service"
2615         else
2616
2617                 case $fstype in
2618                 ldiskfs)
2619                         wait_update_facet ${facet} "$E2LABEL $dm_dev \
2620                                 2>/dev/null | grep -E ':[a-zA-Z]{3}[0-9]{4}'" \
2621                                 "" || error "$dm_dev failed to initialize!";;
2622                 zfs)
2623                         wait_update_facet ${facet} "$ZFS get -H -o value \
2624                                 lustre:svname $dm_dev 2>/dev/null | \
2625                                 grep -E ':[a-zA-Z]{3}[0-9]{4}'" "" ||
2626                                 error "$dm_dev failed to initialize!";;
2627
2628                 wbcfs)
2629                         :;;
2630                 *)
2631                         error "unknown fstype!";;
2632                 esac
2633         fi
2634
2635         # commit the device label change to disk
2636         if [[ $devicelabel =~ (:[a-zA-Z]{3}[0-9]{4}) ]]; then
2637                 echo "Commit the device label on ${!dev}"
2638                 do_facet $facet "sync; sleep 1; sync"
2639         fi
2640
2641
2642         label=$(devicelabel ${facet} $dm_dev)
2643         [ -z "$label" ] && echo no label for $dm_dev && exit 1
2644         eval export ${facet}_svc=${label}
2645         echo Started ${label}
2646
2647         export_dm_dev $facet $dm_dev
2648
2649         return $RC
2650 }
2651
2652 # start facet device options
2653 start() {
2654         local facet=$1
2655         shift
2656         local device=$1
2657         shift
2658         local dev_alias=$(facet_device_alias $facet)
2659
2660         eval export ${dev_alias}_dev=${device}
2661         eval export ${facet}_opt=\"$*\"
2662
2663         combined_mgs_mds && [[ ${dev_alias} == mds1 ]] &&
2664                 eval export mgs_dev=${device}
2665
2666         local varname=${dev_alias}failover_dev
2667         if [ -n "${!varname}" ] ; then
2668                 eval export ${dev_alias}failover_dev=${!varname}
2669         else
2670                 eval export ${dev_alias}failover_dev=$device
2671                 combined_mgs_mds && [[ ${dev_alias} == mds1 ]] &&
2672                         eval export mgsfailover_dev=${device}
2673
2674         fi
2675
2676         local mntpt=$(facet_mntpt $facet)
2677         do_facet ${facet} mkdir -p $mntpt
2678         eval export ${facet}_MOUNT=$mntpt
2679         mount_facet ${facet}
2680         RC=$?
2681
2682         if [[ $RC == 0 && $facet == *ost* && $OSTDEVBASE == */tmp/* ]]; then
2683                 varname="${facet}_FSTRIM"
2684                 if [[ -z ${!varname} ]]; then
2685                         if do_facet ${facet} "fstrim -v $mntpt"; then
2686                                 eval export $varname="yes"
2687                         else
2688                                 eval export $varname="no"
2689                         fi
2690                 fi
2691         fi
2692
2693         return $RC
2694 }
2695
2696 stop() {
2697         local running
2698         local facet=$1
2699         shift
2700         local HOST=$(facet_active_host $facet)
2701         [[ -z $HOST ]] && echo stop: no host for $facet && return 0
2702
2703         local mntpt=$(facet_mntpt $facet)
2704         running=$(do_facet ${facet} "grep -c $mntpt' ' /proc/mounts || true")
2705         if [ ${running} -ne 0 ]; then
2706                 echo "Stopping $mntpt (opts:$*) on $HOST"
2707                 do_facet ${facet} $UMOUNT "$@" $mntpt
2708         fi
2709
2710         # umount should block, but we should wait for unrelated obd's
2711         # like the MGS or MGC to also stop.
2712         wait_exit_ST ${facet} || return ${PIPESTATUS[0]}
2713
2714         if [[ $(facet_fstype $facet) == zfs ]]; then
2715                 # export ZFS storage pool
2716                 [ "$KEEP_ZPOOL" = "true" ] || export_zpool $facet
2717         elif dm_flakey_supported $facet; then
2718                 local host=${facet}_HOST
2719                 local failover_host=${facet}failover_HOST
2720                 if [[ -n ${!failover_host} && ${!failover_host} != ${!host} ]]||
2721                         $CLEANUP_DM_DEV || [[ $facet = fs* ]]; then
2722                         dm_cleanup_dev $facet
2723                 fi
2724         fi
2725 }
2726
2727 # get mdt quota type
2728 mdt_quota_type() {
2729         local varsvc=${SINGLEMDS}_svc
2730         do_facet $SINGLEMDS $LCTL get_param -n \
2731                 osd-$(facet_fstype $SINGLEMDS).${!varsvc}.quota_slave.enabled
2732 }
2733
2734 # get ost quota type
2735 ost_quota_type() {
2736         # All OSTs should have same quota type
2737         local varsvc=ost1_svc
2738         do_facet ost1 $LCTL get_param -n \
2739                 osd-$(facet_fstype ost1).${!varsvc}.quota_slave.enabled
2740 }
2741
2742 # restore old quota type settings
2743 restore_quota() {
2744         for usr in $QUOTA_USERS; do
2745                 echo "Setting up quota on $HOSTNAME:$MOUNT for $usr..."
2746                 for type in u g; do
2747                         cmd="$LFS setquota -$type $usr -b 0"
2748                         cmd="$cmd -B 0 -i 0 -I 0 $MOUNT"
2749                         echo "+ $cmd"
2750                         eval $cmd || error "$cmd FAILED!"
2751                 done
2752                 # display the quota status
2753                 echo "Quota settings for $usr : "
2754                 $LFS quota -v -u $usr $MOUNT || true
2755         done
2756         if [ "$old_MDT_QUOTA_TYPE" ]; then
2757                 if [[ $PERM_CMD == *"set_param -P"* ]]; then
2758                         do_facet mgs $PERM_CMD \
2759                                 osd-*.$FSNAME-MDT*.quota_slave.enabled = \
2760                                 $old_MDT_QUOTA_TYPE
2761                 else
2762                         do_facet mgs $PERM_CMD \
2763                                 $FSNAME.quota.mdt=$old_MDT_QUOTA_TYPE
2764                 fi
2765         fi
2766         if [ "$old_OST_QUOTA_TYPE" ]; then
2767                 if [[ $PERM_CMD == *"set_param -P"* ]]; then
2768                         do_facet mgs $PERM_CMD \
2769                                 osd-*.$FSNAME-OST*.quota_slave.enabled = \
2770                                 $old_OST_QUOTA_TYPE
2771                 else
2772                         do_facet mgs $LCTL conf_param \
2773                                 $FSNAME.quota.ost=$old_OST_QUOTA_TYPE
2774                 fi
2775         fi
2776 }
2777
2778 # Handle the case when there is a space in the lfs df
2779 # "filesystem summary" line the same as when there is no space.
2780 # This will allow fixing the "lfs df" summary line in the future.
2781 lfs_df() {
2782         $LFS df $* | sed -e 's/filesystem /filesystem_/'
2783         check_lfs_df_ret_val ${PIPESTATUS[0]}
2784 }
2785
2786 # Get free inodes on the MDT specified by mdt index, free indoes on
2787 # the whole filesystem will be returned when index == -1.
2788 mdt_free_inodes() {
2789         local index=$1
2790         local free_inodes
2791         local mdt_uuid
2792
2793         if [ $index -eq -1 ]; then
2794                 mdt_uuid="summary"
2795         else
2796                 mdt_uuid=$(mdtuuid_from_index $index)
2797         fi
2798
2799         free_inodes=$(lfs_df -i $MOUNT | grep $mdt_uuid | awk '{print $4}')
2800         echo $free_inodes
2801 }
2802
2803 #
2804 # Get the OST device status from 'lfs df' with a given OST index.
2805 #
2806 ost_dev_status() {
2807         local ost_idx=$1
2808         local mnt_pnt=${2:-$MOUNT}
2809         local opts=$3
2810         local ost_uuid
2811
2812         ost_uuid=$(ostuuid_from_index $ost_idx $mnt_pnt)
2813         lfs_df $opts $mnt_pnt | awk '/'$ost_uuid'/ { print $7 }'
2814 }
2815
2816 setup_quota(){
2817         local mntpt=$1
2818
2819         # save old quota type & set new quota type
2820         local mdt_qtype=$(mdt_quota_type)
2821         local ost_qtype=$(ost_quota_type)
2822
2823         echo "[HOST:$HOSTNAME] [old_mdt_qtype:$mdt_qtype]" \
2824                 "[old_ost_qtype:$ost_qtype] [new_qtype:$QUOTA_TYPE]"
2825
2826         export old_MDT_QUOTA_TYPE=$mdt_qtype
2827         export old_OST_QUOTA_TYPE=$ost_qtype
2828
2829         if [[ $PERM_CMD == *"set_param -P"* ]]; then
2830                 do_facet mgs $PERM_CMD \
2831                         osd-*.$FSNAME-MDT*.quota_slave.enabled=$QUOTA_TYPE
2832                 do_facet mgs $PERM_CMD \
2833                         osd-*.$FSNAME-OST*.quota_slave.enabled=$QUOTA_TYPE
2834         else
2835                 do_facet mgs $PERM_CMD $FSNAME.quota.mdt=$QUOTA_TYPE ||
2836                         error "set mdt quota type failed"
2837                 do_facet mgs $PERM_CMD $FSNAME.quota.ost=$QUOTA_TYPE ||
2838                         error "set ost quota type failed"
2839         fi
2840
2841         local quota_usrs=$QUOTA_USERS
2842
2843         # get_filesystem_size
2844         local disksz=$(lfs_df $mntpt | grep "summary" | awk '{print $2}')
2845         local blk_soft=$((disksz + 1024))
2846         local blk_hard=$((blk_soft + blk_soft / 20)) # Go 5% over
2847
2848         local inodes=$(lfs_df -i $mntpt | grep "summary" | awk '{print $2}')
2849         local i_soft=$inodes
2850         local i_hard=$((i_soft + i_soft / 20))
2851
2852         echo "Total disk size: $disksz  block-softlimit: $blk_soft" \
2853                 "block-hardlimit: $blk_hard inode-softlimit: $i_soft" \
2854                 "inode-hardlimit: $i_hard"
2855
2856         local cmd
2857         for usr in $quota_usrs; do
2858                 echo "Setting up quota on $HOSTNAME:$mntpt for $usr..."
2859                 for type in u g; do
2860                         cmd="$LFS setquota -$type $usr -b $blk_soft"
2861                         cmd="$cmd -B $blk_hard -i $i_soft -I $i_hard $mntpt"
2862                         echo "+ $cmd"
2863                         eval $cmd || error "$cmd FAILED!"
2864                 done
2865                 # display the quota status
2866                 echo "Quota settings for $usr : "
2867                 $LFS quota -v -u $usr $mntpt || true
2868         done
2869 }
2870
2871 zconf_mount() {
2872         local client=$1
2873         local mnt=$2
2874         local opts=${3:-$MOUNT_OPTS}
2875         opts=${opts:+-o $opts}
2876         local flags=${4:-$MOUNT_FLAGS}
2877
2878         local device=$MGSNID:/$FSNAME$FILESET
2879         if [ -z "$mnt" -o -z "$FSNAME" ]; then
2880                 echo "Bad mount command: opt=$flags $opts dev=$device " \
2881                      "mnt=$mnt"
2882                 exit 1
2883         fi
2884
2885         if $GSS_SK; then
2886                 # update mount option with skpath
2887                 opts=$(add_sk_mntflag $opts)
2888         fi
2889
2890         echo "Starting client: $client: $flags $opts $device $mnt"
2891         do_node $client mkdir -p $mnt
2892         if [ -n "$FILESET" -a -z "$SKIP_FILESET" ];then
2893                 do_node $client $MOUNT_CMD $flags $opts $MGSNID:/$FSNAME \
2894                         $mnt || return $?
2895                 #disable FILESET if not supported
2896                 do_nodes $client lctl get_param -n \
2897                         mdc.$FSNAME-MDT0000*.import | grep -q subtree ||
2898                                 device=$MGSNID:/$FSNAME
2899                 do_node $client "! grep -q $mnt' ' /proc/mounts ||
2900                         umount $mnt"
2901         fi
2902         if $GSS_SK && ($SK_UNIQUE_NM || $SK_S2S); then
2903                 # Mount using nodemap key
2904                 local mountkey=$SK_PATH/$FSNAME-nmclient.key
2905                 if $SK_UNIQUE_NM; then
2906                         mountkey=$SK_PATH/nodemap/c0.key
2907                 fi
2908                 local prunedopts=$(echo $opts |
2909                                 sed -e "s#skpath=[^,^ ]*#skpath=$mountkey#g")
2910                 do_node $client $MOUNT_CMD $flags $prunedopts $device $mnt ||
2911                                 return $?
2912         else
2913                 do_node $client $MOUNT_CMD $flags $opts $device $mnt ||
2914                                 return $?
2915         fi
2916
2917         set_default_debug_nodes $client
2918         set_params_clients $client
2919
2920         return 0
2921 }
2922
2923 zconf_umount() {
2924         local client=$1
2925         local mnt=$2
2926         local force
2927         local busy
2928         local need_kill
2929         local running=$(do_node $client "grep -c $mnt' ' /proc/mounts") || true
2930
2931         [ "$3" ] && force=-f
2932         [ $running -eq 0 ] && return 0
2933
2934         echo "Stopping client $client $mnt (opts:$force)"
2935         do_node $client lsof -t $mnt || need_kill=no
2936         if [ "x$force" != "x" ] && [ "x$need_kill" != "xno" ]; then
2937                 pids=$(do_node $client lsof -t $mnt | sort -u);
2938                 if [ -n "$pids" ]; then
2939                         do_node $client kill -9 $pids || true
2940                 fi
2941         fi
2942
2943         busy=$(do_node $client "umount $force $mnt 2>&1" | grep -c "busy") ||
2944                 true
2945         if [ $busy -ne 0 ] ; then
2946                 echo "$mnt is still busy, wait one second" && sleep 1
2947                 do_node $client umount $force $mnt
2948         fi
2949 }
2950
2951 # Mount the file system on the MDS
2952 mount_mds_client() {
2953         local host=$(facet_active_host $SINGLEMDS)
2954         echo $host
2955         zconf_mount $host $MOUNT2 $MOUNT_OPTS ||
2956                 error "unable to mount $MOUNT2 on $host with ($?)"
2957 }
2958
2959 # Unmount the file system on the MDS
2960 umount_mds_client() {
2961         local host=$(facet_active_host $SINGLEMDS)
2962         zconf_umount $host $MOUNT2
2963         do_facet $SINGLEMDS "rmdir $MOUNT2"
2964 }
2965
2966 # nodes is comma list
2967 sanity_mount_check_nodes () {
2968         local nodes=$1
2969         shift
2970         local mnts="$@"
2971         local mnt
2972
2973         # FIXME: assume that all cluster nodes run the same os
2974         [ "$(uname)" = Linux ] || return 0
2975
2976         local rc=0
2977         for mnt in $mnts ; do
2978                 do_nodes $nodes "running=\\\$(grep -c $mnt' ' /proc/mounts);
2979 mpts=\\\$(mount | grep -c $mnt' ');
2980 if [ \\\$running -ne \\\$mpts ]; then
2981     echo \\\$(hostname) env are INSANE!;
2982     exit 1;
2983 fi"
2984                 [ $? -eq 0 ] || rc=1
2985         done
2986         return $rc
2987 }
2988
2989 sanity_mount_check_servers () {
2990         [ -n "$CLIENTONLY" ] &&
2991                 { echo "CLIENTONLY mode, skip mount_check_servers"; return 0; } || true
2992         echo Checking servers environments
2993
2994         # FIXME: modify get_facets to display all facets wo params
2995         local facets="$(get_facets OST),$(get_facets MDS),mgs"
2996         local node
2997         local mntpt
2998         local facet
2999         for facet in ${facets//,/ }; do
3000         node=$(facet_host ${facet})
3001         mntpt=$(facet_mntpt $facet)
3002         sanity_mount_check_nodes $node $mntpt ||
3003                 { error "server $node environments are insane!"; return 1; }
3004         done
3005 }
3006
3007 sanity_mount_check_clients () {
3008         local clients=${1:-$CLIENTS}
3009         local mntpt=${2:-$MOUNT}
3010         local mntpt2=${3:-$MOUNT2}
3011
3012         [ -z $clients ] && clients=$(hostname)
3013         echo Checking clients $clients environments
3014
3015         sanity_mount_check_nodes $clients $mntpt $mntpt2 ||
3016                 error "clients environments are insane!"
3017 }
3018
3019 sanity_mount_check () {
3020         sanity_mount_check_servers || return 1
3021         sanity_mount_check_clients || return 2
3022 }
3023
3024 # mount clients if not mouted
3025 zconf_mount_clients() {
3026         local clients=$1
3027         local mnt=$2
3028         local opts=${3:-$MOUNT_OPTS}
3029         opts=${opts:+-o $opts}
3030         local flags=${4:-$MOUNT_FLAGS}
3031         local device=$MGSNID:/$FSNAME$FILESET
3032         if [ -z "$mnt" -o -z "$FSNAME" ]; then
3033                 echo "Bad conf mount command: opt=$flags $opts dev=$device " \
3034                      "mnt=$mnt"
3035                 exit 1
3036         fi
3037
3038         echo "Starting client $clients: $flags $opts $device $mnt"
3039         do_nodes $clients mkdir -p $mnt
3040         if [ -n "$FILESET" -a -z "$SKIP_FILESET" ]; then
3041                 if $GSS_SK && ($SK_UNIQUE_NM || $SK_S2S); then
3042                         # Mount with own nodemap key
3043                         local i=0
3044                         # Mount all server nodes first with per-NM keys
3045                         for nmclient in ${clients//,/ }; do
3046                                 do_nodes $(comma_list $(all_server_nodes)) \
3047                                 "$LGSS_SK -t server -l $SK_PATH/nodemap/c$i.key"
3048                                 i=$((i + 1))
3049                         done
3050                         # set perms for per-nodemap keys else permission denied
3051                         do_nodes $(comma_list $(all_nodes)) \
3052                                 "keyctl show | grep lustre | cut -c1-11 |
3053                                 sed -e 's/ //g;' |
3054                                 xargs -IX keyctl setperm X 0x3f3f3f3f"
3055                         local mountkey=$SK_PATH/$FSNAME-nmclient.key
3056                         i=0
3057                         for nmclient in ${clients//,/ }; do
3058                                 if $SK_UNIQUE_NM; then
3059                                         mountkey=$SK_PATH/nodemap/c$i.key
3060                                 fi
3061                                 do_node $nmclient "! grep -q $mnt' ' \
3062                                         /proc/mounts || umount $mnt"
3063                                 local prunedopts=$(add_sk_mntflag $opts);
3064                                 prunedopts=$(echo $prunedopts | sed -e \
3065                                         "s#skpath=[^ ^,]*#skpath=$mountkey#g")
3066                                 set -x
3067                                 do_nodes $(comma_list $(all_server_nodes)) \
3068                                         "keyctl show"
3069                                 set +x
3070                                 do_node $nmclient $MOUNT_CMD $flags \
3071                                         $prunedopts $MGSNID:/$FSNAME $mnt ||
3072                                         return 1
3073                                 i=$((i + 1))
3074                         done
3075                 else
3076                         do_nodes $clients "! grep -q $mnt' ' /proc/mounts ||
3077                                         umount $mnt"
3078                         do_nodes $clients $MOUNT_CMD $flags $opts \
3079                                         $MGSNID:/$FSNAME $mnt || return 1
3080                 fi
3081                 #disable FILESET if not supported
3082                 do_nodes $clients lctl get_param -n \
3083                         mdc.$FSNAME-MDT0000*.import | grep -q subtree ||
3084                                 device=$MGSNID:/$FSNAME
3085                 do_nodes $clients "! grep -q $mnt' ' /proc/mounts ||
3086                         umount $mnt"
3087         fi
3088
3089         if $GSS_SK && ($SK_UNIQUE_NM || $SK_S2S); then
3090                 # Mount with nodemap key
3091                 local i=0
3092                 local mountkey=$SK_PATH/$FSNAME-nmclient.key
3093                 for nmclient in ${clients//,/ }; do
3094                         if $SK_UNIQUE_NM; then
3095                                 mountkey=$SK_PATH/nodemap/c$i.key
3096                         fi
3097                         local prunedopts=$(echo $opts | sed -e \
3098                                 "s#skpath=[^ ^,]*#skpath=$mountkey#g");
3099                         do_node $nmclient "! grep -q $mnt' ' /proc/mounts ||
3100                                 umount $mnt"
3101                         do_node $nmclient "
3102                 running=\\\$(mount | grep -c $mnt' ');
3103                 rc=0;
3104                 if [ \\\$running -eq 0 ] ; then
3105                         mkdir -p $mnt;
3106                         $MOUNT_CMD $flags $prunedopts $device $mnt;
3107                         rc=\\\$?;
3108                 else
3109                         lustre_mnt_count=\\\$(mount | grep $mnt' ' | \
3110                                 grep 'type lustre' | wc -l);
3111                         if [ \\\$running -ne \\\$lustre_mnt_count ] ; then
3112                                 echo zconf_mount_clients FAILED: \
3113                                         mount count \\\$running, not matching \
3114                                         with mount count of 'type lustre' \
3115                                         \\\$lustre_mnt_count;
3116                                 rc=1;
3117                         fi;
3118                 fi;
3119         exit \\\$rc" || return ${PIPESTATUS[0]}
3120
3121                         i=$((i + 1))
3122                 done
3123         else
3124
3125                 local tmpopts=$opts
3126                 if $SHARED_KEY; then
3127                         tmpopts=$(add_sk_mntflag $opts)
3128                 fi
3129                 do_nodes $clients "
3130 running=\\\$(mount | grep -c $mnt' ');
3131 rc=0;
3132 if [ \\\$running -eq 0 ] ; then
3133         mkdir -p $mnt;
3134         $MOUNT_CMD $flags $tmpopts $device $mnt;
3135         rc=\\\$?;
3136 fi;
3137 exit \\\$rc" || return ${PIPESTATUS[0]}
3138         fi
3139
3140         echo "Started clients $clients: "
3141         do_nodes $clients "mount | grep $mnt' '"
3142
3143         set_default_debug_nodes $clients
3144         set_params_clients $clients
3145
3146         return 0
3147 }
3148
3149 zconf_umount_clients() {
3150         local clients=$1
3151         local mnt=$2
3152         local force
3153
3154         [ "$3" ] && force=-f
3155
3156         echo "Stopping clients: $clients $mnt (opts:$force)"
3157         do_nodes $clients "running=\\\$(grep -c $mnt' ' /proc/mounts);
3158 if [ \\\$running -ne 0 ] ; then
3159 echo Stopping client \\\$(hostname) $mnt opts:$force;
3160 lsof $mnt || need_kill=no;
3161 if [ "x$force" != "x" -a "x\\\$need_kill" != "xno" ]; then
3162     pids=\\\$(lsof -t $mnt | sort -u);
3163     if [ -n \\\"\\\$pids\\\" ]; then
3164              kill -9 \\\$pids;
3165     fi
3166 fi;
3167 while umount $force $mnt 2>&1 | grep -q "busy"; do
3168     echo "$mnt is still busy, wait one second" && sleep 1;
3169 done;
3170 fi"
3171 }
3172
3173 shutdown_node () {
3174         local node=$1
3175
3176         echo + $POWER_DOWN $node
3177         $POWER_DOWN $node
3178 }
3179
3180 shutdown_node_hard () {
3181         local host=$1
3182         local attempts=$SHUTDOWN_ATTEMPTS
3183
3184         for i in $(seq $attempts) ; do
3185                 shutdown_node $host
3186                 sleep 1
3187                 wait_for_function --quiet "! ping -w 3 -c 1 $host" 5 1 &&
3188                         return 0
3189                 echo "waiting for $host to fail attempts=$attempts"
3190                 [ $i -lt $attempts ] ||
3191                         { echo "$host still pingable after power down! attempts=$attempts" && return 1; }
3192         done
3193 }
3194
3195 shutdown_client() {
3196         local client=$1
3197         local mnt=${2:-$MOUNT}
3198         local attempts=3
3199
3200         if [ "$FAILURE_MODE" = HARD ]; then
3201                 shutdown_node_hard $client
3202         else
3203                 zconf_umount_clients $client $mnt -f
3204         fi
3205 }
3206
3207 facets_on_host () {
3208         local affected
3209         local host=$1
3210         local facets="$(get_facets OST),$(get_facets MDS)"
3211
3212         combined_mgs_mds || facets="$facets,mgs"
3213
3214         for facet in ${facets//,/ }; do
3215                 if [ $(facet_active_host $facet) == $host ]; then
3216                         affected="$affected $facet"
3217                 fi
3218         done
3219
3220         echo $(comma_list $affected)
3221 }
3222
3223 facet_up() {
3224         local facet=$1
3225         local host=${2:-$(facet_host $facet)}
3226
3227         local label=$(convert_facet2label $facet)
3228         do_node $host $LCTL dl | awk '{ print $4 }' | grep -q "^$label\$"
3229 }
3230
3231 facets_up_on_host () {
3232         local affected_up
3233         local host=$1
3234         local facets=$(facets_on_host $host)
3235
3236         for facet in ${facets//,/ }; do
3237                 if $(facet_up $facet $host); then
3238                         affected_up="$affected_up $facet"
3239                 fi
3240         done
3241
3242         echo $(comma_list $affected_up)
3243 }
3244
3245 shutdown_facet() {
3246         local facet=$1
3247         local affected_facet
3248         local affected_facets
3249
3250         if [[ "$FAILURE_MODE" = HARD ]]; then
3251                 if [[ $(facet_fstype $facet) = ldiskfs ]] &&
3252                         dm_flakey_supported $facet; then
3253                         affected_facets=$(affected_facets $facet)
3254                         for affected_facet in ${affected_facets//,/ }; do
3255                                 unexport_dm_dev $affected_facet
3256                         done
3257                 fi
3258
3259                 shutdown_node_hard $(facet_active_host $facet)
3260         else
3261                 stop $facet
3262         fi
3263 }
3264
3265 reboot_node() {
3266         local node=$1
3267
3268         echo + $POWER_UP $node
3269         $POWER_UP $node
3270 }
3271
3272 remount_facet() {
3273         local facet=$1
3274
3275         stop $facet
3276         mount_facet $@
3277 }
3278
3279 reboot_facet() {
3280         local facet=$1
3281         local node=$(facet_active_host $facet)
3282         local sleep_time=${2:-10}
3283
3284         if [ "$FAILURE_MODE" = HARD ]; then
3285                 boot_node $node
3286         else
3287                 sleep $sleep_time
3288         fi
3289 }
3290
3291 boot_node() {
3292         local node=$1
3293
3294         if [ "$FAILURE_MODE" = HARD ]; then
3295                 reboot_node $node
3296                 wait_for_host $node
3297                 if $LOAD_MODULES_REMOTE; then
3298                         echo "loading modules on $node: $facet"
3299                         do_rpc_nodes $node load_modules_local
3300                 fi
3301         fi
3302 }
3303
3304 facets_hosts () {
3305         local hosts
3306         local facets=$1
3307
3308         for facet in ${facets//,/ }; do
3309                 hosts=$(expand_list $hosts $(facet_host $facet) )
3310         done
3311
3312         echo $hosts
3313 }
3314
3315 _check_progs_installed () {
3316         local progs=$@
3317         local rc=0
3318
3319         for prog in $progs; do
3320                 if ! [ "$(which $prog)"  -o  "${!prog}" ]; then
3321                         echo $prog missing on $(hostname)
3322                         rc=1
3323                 fi
3324         done
3325         return $rc
3326 }
3327
3328 check_progs_installed () {
3329         local nodes=$1
3330         shift
3331
3332         do_rpc_nodes "$nodes" _check_progs_installed "$@"
3333 }
3334
3335 # recovery-scale functions
3336 node_var_name() {
3337     echo __$(echo $1 | tr '-' '_' | tr '.' '_')
3338 }
3339
3340 start_client_load() {
3341         local client=$1
3342         local load=$2
3343         local var=$(node_var_name $client)_load
3344         eval export ${var}=$load
3345
3346         do_node $client "PATH=$PATH MOUNT=$MOUNT ERRORS_OK=$ERRORS_OK \
3347                         END_RUN_FILE=$END_RUN_FILE \
3348                         LOAD_PID_FILE=$LOAD_PID_FILE \
3349                         TESTLOG_PREFIX=$TESTLOG_PREFIX \
3350                         TESTNAME=$TESTNAME \
3351                         DBENCH_LIB=$DBENCH_LIB \
3352                         DBENCH_SRC=$DBENCH_SRC \
3353                         CLIENT_COUNT=$((CLIENTCOUNT - 1)) \
3354                         RECOVERY_SCALE_ENABLE_REMOTE_DIRS=$RECOVERY_SCALE_ENABLE_REMOTE_DIRS \
3355                         RECOVERY_SCALE_ENABLE_STRIPED_DIRS=$RECOVERY_SCALE_ENABLE_STRIPED_DIRS \
3356                         LFS=$LFS \
3357                         LCTL=$LCTL \
3358                         FSNAME=$FSNAME \
3359                         MPI_USER=$MPI_USER \
3360                         MPIRUN=$MPIRUN \
3361                         MPIRUN_OPTIONS=\\\"$MPIRUN_OPTIONS\\\" \
3362                         MACHINEFILE_OPTION=\\\"$MACHINEFILE_OPTION\\\" \
3363                         num_clients=$(get_node_count ${CLIENTS//,/ }) \
3364                         ior_THREADS=$ior_THREADS ior_iteration=$ior_iteration \
3365                         ior_blockSize=$ior_blockSize \
3366                         ior_blockUnit=$ior_blockUnit \
3367                         ior_xferSize=$ior_xferSize ior_type=$ior_type \
3368                         ior_DURATION=$ior_DURATION \
3369                         ior_stripe_params=\\\"$ior_stripe_params\\\" \
3370                         ior_custom_params=\\\"$ior_custom_param\\\" \
3371                         mpi_ior_custom_threads=$mpi_ior_custom_threads \
3372                         run_${load}.sh" &
3373         local ppid=$!
3374         log "Started client load: ${load} on $client"
3375
3376         # get the children process IDs
3377         local pids=$(ps --ppid $ppid -o pid= | xargs)
3378         CLIENT_LOAD_PIDS="$CLIENT_LOAD_PIDS $ppid $pids"
3379         return 0
3380 }
3381
3382 start_client_loads () {
3383         local -a clients=(${1//,/ })
3384         local numloads=${#CLIENT_LOADS[@]}
3385
3386         for ((nodenum=0; nodenum < ${#clients[@]}; nodenum++ )); do
3387                 local load=$((nodenum % numloads))
3388                 start_client_load ${clients[nodenum]} ${CLIENT_LOADS[load]}
3389         done
3390         # bug 22169: wait the background threads to start
3391         sleep 2
3392 }
3393
3394 # only for remote client
3395 check_client_load () {
3396         local client=$1
3397         local var=$(node_var_name $client)_load
3398         local testload=run_${!var}.sh
3399
3400         ps auxww | grep -v grep | grep $client | grep -q $testload || return 1
3401
3402         # bug 18914: try to connect several times not only when
3403         # check ps, but  while check_node_health also
3404
3405         local tries=3
3406         local RC=254
3407         while [ $RC = 254 -a $tries -gt 0 ]; do
3408                 let tries=$tries-1
3409                 # assume success
3410                 RC=0
3411                 if ! check_node_health $client; then
3412                         RC=${PIPESTATUS[0]}
3413                         if [ $RC -eq 254 ]; then
3414                                 # FIXME: not sure how long we shuold sleep here
3415                                 sleep 10
3416                                 continue
3417                         fi
3418                         echo "check node health failed: RC=$RC "
3419                         return $RC
3420                 fi
3421         done
3422         # We can continue try to connect if RC=254
3423         # Just print the warning about this
3424         if [ $RC = 254 ]; then
3425                 echo "got a return status of $RC from do_node while checking " \
3426                 "node health on $client"
3427         fi
3428
3429         # see if the load is still on the client
3430         tries=3
3431         RC=254
3432         while [ $RC = 254 -a $tries -gt 0 ]; do
3433                 let tries=$tries-1
3434                 # assume success
3435                 RC=0
3436                 if ! do_node $client \
3437                         "ps auxwww | grep -v grep | grep -q $testload"; then
3438                         RC=${PIPESTATUS[0]}
3439                         sleep 30
3440                 fi
3441         done
3442         if [ $RC = 254 ]; then
3443                 echo "got a return status of $RC from do_node while checking " \
3444                 "(node health and 'ps') the client load on $client"
3445                 # see if we can diagnose a bit why this is
3446         fi
3447
3448         return $RC
3449 }
3450 check_client_loads () {
3451         local clients=${1//,/ }
3452         local client=
3453         local rc=0
3454
3455         for client in $clients; do
3456                 check_client_load $client
3457                 rc=${PIPESTATUS[0]}
3458                 if [ "$rc" != 0 ]; then
3459                         log "Client load failed on node $client, rc=$rc"
3460                         return $rc
3461                 fi
3462         done
3463 }
3464
3465 restart_client_loads () {
3466         local clients=${1//,/ }
3467         local expectedfail=${2:-""}
3468         local client=
3469         local rc=0
3470
3471         for client in $clients; do
3472                 check_client_load $client
3473                 rc=${PIPESTATUS[0]}
3474                 if [ "$rc" != 0 -a "$expectedfail" ]; then
3475                         local var=$(node_var_name $client)_load
3476
3477                         start_client_load $client ${!var}
3478                         echo "Restarted client load ${!var}: on $client. Checking ..."
3479                         check_client_load $client
3480                         rc=${PIPESTATUS[0]}
3481                         if [ "$rc" != 0 ]; then
3482                                 log "Client load failed to restart on node $client, rc=$rc"
3483                                 # failure one client load means test fail
3484                                 # we do not need to check other
3485                                 return $rc
3486                         fi
3487                 else
3488                         return $rc
3489                 fi
3490         done
3491 }
3492
3493 # Start vmstat and save its process ID in a file.
3494 start_vmstat() {
3495         local nodes=$1
3496         local pid_file=$2
3497
3498         [ -z "$nodes" -o -z "$pid_file" ] && return 0
3499
3500         do_nodes $nodes \
3501         "vmstat 1 > $TESTLOG_PREFIX.$TESTNAME.vmstat.\\\$(hostname -s).log \
3502         2>/dev/null </dev/null & echo \\\$! > $pid_file"
3503 }
3504
3505 # Display the nodes on which client loads failed.
3506 print_end_run_file() {
3507         local file=$1
3508         local node
3509
3510         [ -s $file ] || return 0
3511
3512         echo "Found the END_RUN_FILE file: $file"
3513         cat $file
3514
3515         # A client load will stop if it finds the END_RUN_FILE file.
3516         # That does not mean the client load actually failed though.
3517         # The first node in END_RUN_FILE is the one we are interested in.
3518         read node < $file
3519
3520         if [ -n "$node" ]; then
3521                 local var=$(node_var_name $node)_load
3522
3523                 local prefix=$TESTLOG_PREFIX
3524                 [ -n "$TESTNAME" ] && prefix=$prefix.$TESTNAME
3525                 local stdout_log=$prefix.run_${!var}_stdout.$node.log
3526                 local debug_log=$(echo $stdout_log |
3527                         sed 's/\(.*\)stdout/\1debug/')
3528
3529                 echo "Client load ${!var} failed on node $node:"
3530                 echo "$stdout_log"
3531                 echo "$debug_log"
3532         fi
3533 }
3534
3535 # Stop the process which had its PID saved in a file.
3536 stop_process() {
3537         local nodes=$1
3538         local pid_file=$2
3539
3540         [ -z "$nodes" -o -z "$pid_file" ] && return 0
3541
3542         do_nodes $nodes "test -f $pid_file &&
3543                 { kill -s TERM \\\$(cat $pid_file); rm -f $pid_file; }" || true
3544 }
3545
3546 # Stop all client loads.
3547 stop_client_loads() {
3548         local nodes=${1:-$CLIENTS}
3549         local pid_file=$2
3550
3551         # stop the client loads
3552         stop_process $nodes $pid_file
3553
3554         # clean up the processes that started them
3555         [ -n "$CLIENT_LOAD_PIDS" ] &&
3556                 kill -9 $CLIENT_LOAD_PIDS 2>/dev/null || true
3557 }
3558 # End recovery-scale functions
3559
3560 ##
3561 # wait for a command to return the expected result
3562 #
3563 # This will run @check on @node repeatedly until the output matches @expect
3564 # based on the supplied condition, or until @max_wait seconds have elapsed,
3565 # whichever comes first.  @cond may be one of the normal bash operators,
3566 # "-gt", "-ge", "-eq", "-le", "-lt", "==", "!=", or "=~", and must be quoted
3567 # in the caller to avoid unintentional evaluation by the shell in the caller.
3568 #
3569 # If @max_wait is not specified, the condition will be checked for up to 90s.
3570 #
3571 # If --verbose is passed as the first argument, the result is printed on each
3572 # value change, otherwise it is only printed after every 10s interval.
3573 #
3574 # If --quiet is passed as the first/second argument, the do_node() command
3575 # will not print the remote command before executing it each time.
3576 #
3577 # Using wait_update_cond() or related helper function is preferable to adding
3578 # a "long enough" wait for some state to change in the background, since
3579 # "long enough" may be too short due to tunables, system config, or running in
3580 # a VM, and must by necessity wait too long for most cases or risk failure.
3581 #
3582 # usage: wait_update_cond [--verbose] [--quiet] node check cond expect [max_wait]
3583 wait_update_cond() {
3584         local verbose
3585         local quiet
3586
3587         [[ "$1" == "--verbose" ]] && verbose="$1" && shift || true
3588         [[ "$1" == "--quiet" || "$1" == "-q" ]] && quiet="$1" && shift || true
3589
3590         local node=$1
3591         local check="$2"
3592         local cond="$3"
3593         local expect="$4"
3594         local max_wait=${5:-90}
3595         local result
3596         local prev_result
3597         local waited=0
3598         local begin=$SECONDS
3599         local sleep=1
3600         local print=10
3601
3602         while (( $waited <= $max_wait )); do
3603                 result=$(do_node $quiet $node "$check")
3604
3605                 if eval [[ "'$result'" $cond "'$expect'" ]]; then
3606                         [[ -z "$quiet" ]] || return 0
3607                         [[ -z "$result" || $waited -le $sleep ]] ||
3608                                 echo "Updated after ${waited}s: want '$expect' got '$result'"
3609                         return 0
3610                 fi
3611                 if [[ -n "$verbose" && "$result" != "$prev_result" ]]; then
3612                         [[ -n "$quiet" || -z "$prev_result" ]] ||
3613                                 echo "Changed after ${waited}s: from '$prev_result' to '$result'"
3614                         prev_result="$result"
3615                 fi
3616                 (( $waited % $print != 0 )) || {
3617                         [[ -z "$quiet" ]] &&
3618                         echo "Waiting $((max_wait - waited))s for '$expect'"
3619                 }
3620
3621                 sleep $sleep
3622                 waited=$((SECONDS - begin))
3623         done
3624
3625         [[ -n "$quiet" ]] ||
3626         echo "Update not seen after ${max_wait}s: want '$expect' got '$result'"
3627
3628         return 3
3629 }
3630
3631 # usage: wait_update [--verbose] [--quiet] node check expect [max_wait]
3632 wait_update() {
3633         local verbose
3634         local quiet
3635
3636         [[ "$1" == "--verbose" ]] && verbose="$1" && shift || true
3637         [[ "$1" == "--quiet" || "$1" == "-q" ]] && quiet="$1" && shift || true
3638
3639         local node="$1"
3640         local check="$2"
3641         local expect="$3"
3642         local max_wait=$4
3643
3644         wait_update_cond $verbose $quiet $node "$check" "==" "$expect" $max_wait
3645 }
3646
3647 # usage: wait_update_facet_cond [--verbose] facet check cond expect [max_wait]
3648 wait_update_facet_cond() {
3649         local verbose
3650         local quiet
3651
3652         [[ "$1" == "--verbose" ]] && verbose="$1" && shift
3653         [[ "$1" == "--quiet" || "$1" == "-q" ]] && quiet="$1" && shift
3654
3655         local node=$(facet_active_host $1)
3656         local check="$2"
3657         local cond="$3"
3658         local expect="$4"
3659         local max_wait=$5
3660
3661         wait_update_cond $verbose $quiet $node "$check" "$cond" "$expect" $max_wait
3662 }
3663
3664 # usage: wait_update_facet [--verbose] facet check expect [max_wait]
3665 wait_update_facet() {
3666         local verbose
3667         local quiet
3668
3669         [[ "$1" == "--verbose" ]] && verbose="$1" && shift
3670         [[ "$1" == "--quiet" || "$1" == "-q" ]] && quiet="$1" && shift
3671
3672         local node=$(facet_active_host $1)
3673         local check="$2"
3674         local expect="$3"
3675         local max_wait=$4
3676
3677         wait_update_cond $verbose $quiet $node "$check" "==" "$expect" $max_wait
3678 }
3679
3680 sync_all_data_mdts() {
3681         do_nodes $(mdts_nodes) "lctl set_param -n os[cd]*.*MDT*.force_sync=1"
3682 }
3683
3684 sync_all_data_osts() {
3685         do_nodes $(osts_nodes) "lctl set_param -n osd*.*OS*.force_sync=1" 2>&1 |
3686                 grep -v 'Found no match'
3687 }
3688
3689 sync_all_data() {
3690         sync_all_data_mdts
3691         sync_all_data_osts
3692 }
3693
3694 wait_zfs_commit() {
3695         local zfs_wait=${2:-5}
3696
3697         # the occupied disk space will be released
3698         # only after TXGs are committed
3699         if [[ $(facet_fstype $1) == zfs ]]; then
3700                 echo "sleep $zfs_wait for ZFS $(facet_type $1)"
3701                 sleep $zfs_wait
3702         fi
3703 }
3704
3705 fill_ost() {
3706         local filename=$1
3707         local ost_idx=$2
3708         local lwm=$3  #low watermark
3709         local size_mb #how many MB should we write to pass watermark
3710         local ost_name=$(ostname_from_index $ost_idx)
3711
3712         free_kb=$($LFS df $MOUNT | awk "/$ost_name/ { print \$4 }")
3713         size_mb=0
3714         if (( $free_kb / 1024 > lwm )); then
3715                 size_mb=$((free_kb / 1024 - lwm))
3716         fi
3717         #If 10% of free space cross low watermark use it
3718         if (( $free_kb / 10240 > size_mb )); then
3719                 size_mb=$((free_kb / 10240))
3720         else
3721                 #At least we need to store 1.1 of difference between
3722                 #free space and low watermark
3723                 size_mb=$((size_mb + size_mb / 10))
3724         fi
3725         if (( lwm <= $free_kb / 1024 )) ||
3726            [ ! -f $DIR/${filename}.fill_ost$ost_idx ]; then
3727                 $LFS setstripe -i $ost_idx -c1 $DIR/${filename}.fill_ost$ost_idx
3728                 $DD of=$DIR/${filename}.fill_ost$ost_idx \
3729                         count=$size_mb oflag=append conv=notrunc
3730         fi
3731
3732         sleep_maxage
3733
3734         free_kb=$($LFS df $MOUNT | awk "/$ost_name/ { print \$4 }")
3735         echo "OST still has $((free_kb / 1024)) MB free"
3736 }
3737
3738 # This checks only the primary MDS
3739 ost_watermarks_get() {
3740         local ost_idx=$1
3741         local ost_name=$(ostname_from_index $ost_idx)
3742         local mdtosc_proc=$(get_mdtosc_proc_path $SINGLEMDS $ost_name)
3743
3744         local hwm=$(do_facet $SINGLEMDS $LCTL get_param -n \
3745                         osp.$mdtosc_proc.reserved_mb_high)
3746         local lwm=$(do_facet $SINGLEMDS $LCTL get_param -n \
3747                         osp.$mdtosc_proc.reserved_mb_low)
3748
3749         echo "$lwm $hwm"
3750 }
3751
3752 # Note that we set watermarks on all MDSes (necessary for striped dirs)
3753 ost_watermarks_set() {
3754         local ost_idx=$1
3755         local lwm=$2
3756         local hwm=$3
3757         local ost_name=$(ostname_from_index $ost_idx)
3758         local facets=$(get_facets MDS)
3759
3760         do_nodes $(mdts_nodes) $LCTL set_param -n \
3761                 osp.*$ost_name*.reserved_mb_low=$lwm \
3762                 osp.*$ost_name*.reserved_mb_high=$hwm > /dev/null
3763
3764         # sleep to ensure we see the change
3765         sleep_maxage
3766 }
3767
3768 ost_watermarks_set_low_space() {
3769         local ost_idx=$1
3770         local wms=$(ost_watermarks_get $ost_idx)
3771         local ost_name=$(ostname_from_index $ost_idx)
3772
3773         local old_lwm=$(echo $wms | awk '{ print $1 }')
3774         local old_hwm=$(echo $wms | awk '{ print $2 }')
3775
3776         local blocks=$($LFS df $MOUNT | awk "/$ost_name/ { print \$4 }")
3777         # minimal extension size is 64M
3778         local new_lwm=50
3779         if (( $blocks / 1024 > 50 )); then
3780                 new_lwm=$((blocks / 1024 - 50))
3781         fi
3782         local new_hwm=$((new_lwm + 5))
3783
3784         ost_watermarks_set $ost_idx $new_lwm $new_hwm
3785         echo "watermarks: $old_lwm $old_hwm $new_lwm $new_hwm"
3786 }
3787
3788 # Set watermarks to ~current available space & then write data to fill it
3789 # Note OST is not *actually* full after this, it just reports ENOSPC in the
3790 # internal statfs used by the stripe allocator
3791 #
3792 # first parameter is the filename-prefix, which must get under t-f cleanup
3793 # requirements (rm -rf $DIR/[Rdfs][0-9]*), i.e. $tfile work fine
3794 ost_watermarks_set_enospc() {
3795         local filename=$1
3796         local ost_idx=$2
3797         # on the mdt's osc
3798         local ost_name=$(ostname_from_index $ost_idx)
3799         local facets=$(get_facets MDS)
3800         local wms
3801         local MDS
3802
3803         for MDS in ${facets//,/ }; do
3804                 local mdtosc_proc=$(get_mdtosc_proc_path $MDS $ost_name)
3805
3806                 do_facet $MDS $LCTL get_param -n \
3807                         osp.$mdtosc_proc.reserved_mb_high ||
3808                         skip  "remote MDS does not support reserved_mb_high"
3809         done
3810
3811         wms=$(ost_watermarks_set_low_space $ost_idx)
3812         local new_lwm=$(echo $wms | awk '{ print $4 }')
3813         fill_ost $filename $ost_idx $new_lwm
3814         #First enospc could execute orphan deletion so repeat
3815         fill_ost $filename $ost_idx $new_lwm
3816         echo $wms
3817 }
3818
3819 ost_watermarks_enospc_delete_files() {
3820         local filename=$1
3821         local ost_idx=$2
3822
3823         rm -f $DIR/${filename}.fill_ost$ost_idx
3824
3825         wait_delete_completed
3826         wait_mds_ost_sync
3827 }
3828
3829 # clean up from "ost_watermarks_set_enospc"
3830 ost_watermarks_clear_enospc() {
3831         local filename=$1
3832         local ost_idx=$2
3833         local old_lwm=$4
3834         local old_hwm=$5
3835
3836         ost_watermarks_enospc_delete_files $filename $ost_idx
3837         ost_watermarks_set $ost_idx $old_lwm $old_hwm
3838         echo "set OST$ost_idx lwm back to $old_lwm, hwm back to $old_hwm"
3839 }
3840
3841 wait_delete_completed_mds() {
3842         local max_wait=${1:-60}
3843         local mds2sync=""
3844         local stime=$(date +%s)
3845         local etime
3846         local node
3847         local changes
3848         local mdts=$(mdts_nodes)
3849
3850         # find MDS with pending deletions
3851         for node in ${mdts//,/ }; do
3852                 changes=$(do_node $node "$LCTL get_param -n osc.*MDT*.sync_*" \
3853                         2>/dev/null | calc_sum)
3854                 if [[ $changes -eq 0 ]]; then
3855                         continue
3856                 fi
3857                 mds2sync="$mds2sync $node"
3858         done
3859         if [ -z "$mds2sync" ]; then
3860                 wait_zfs_commit $SINGLEMDS
3861                 return 0
3862         fi
3863         mds2sync=$(comma_list $mds2sync)
3864
3865         # sync MDS transactions
3866         do_nodes $mds2sync "$LCTL set_param -n os[cd]*.*MD*.force_sync 1"
3867
3868         # wait till all changes are sent and commmitted by OSTs
3869         # for ldiskfs space is released upon execution, but DMU
3870         # do this upon commit
3871
3872         local WAIT=0
3873         while [[ $WAIT -ne $max_wait ]]; do
3874                 changes=$(do_nodes $mds2sync \
3875                         "$LCTL get_param -n osc.*MDT*.sync_*" | calc_sum)
3876                 #echo "$node: $changes changes on all"
3877                 if [[ $changes -eq 0 ]]; then
3878                         wait_zfs_commit $SINGLEMDS
3879
3880                         # the occupied disk space will be released
3881                         # only after TXGs are committed
3882                         wait_zfs_commit ost1
3883                         return 0
3884                 fi
3885                 sleep 1
3886                 WAIT=$((WAIT + 1))
3887         done
3888
3889         etime=$(date +%s)
3890         echo "Delete is not completed in $((etime - stime)) seconds"
3891         do_nodes $mds2sync "$LCTL get_param osc.*MDT*.sync_*"
3892         return 1
3893 }
3894
3895 wait_for_host() {
3896         local hostlist=$1
3897
3898         # we can use "for" here because we are waiting the slowest
3899         for host in ${hostlist//,/ }; do
3900                 check_network "$host" 900
3901         done
3902         while ! do_nodes $hostlist hostname; do sleep 5; done
3903 }
3904
3905 wait_for_facet() {
3906         local facetlist=$1
3907         local hostlist
3908
3909         for facet in ${facetlist//,/ }; do
3910                 hostlist=$(expand_list $hostlist $(facet_active_host $facet))
3911         done
3912         wait_for_host $hostlist
3913 }
3914
3915 _wait_recovery_complete () {
3916         local param=$1
3917
3918         # Use default policy if $2 is not passed by caller.
3919         local MAX=${2:-$(max_recovery_time)}
3920
3921         local WAIT=0
3922         local STATUS=
3923
3924         while [ $WAIT -lt $MAX ]; do
3925                 STATUS=$(lctl get_param -n $param | grep status)
3926                 echo $param $STATUS
3927                 [[ $STATUS == "status: COMPLETE" ||
3928                         $STATUS == "status: INACTIVE" ]] && return 0
3929                 sleep 5
3930                 WAIT=$((WAIT + 5))
3931                 echo "Waiting $((MAX - WAIT)) secs for $param recovery done. $STATUS"
3932         done
3933         echo "$param recovery not done in $MAX sec. $STATUS"
3934         return 1
3935 }
3936
3937 wait_recovery_complete () {
3938         local facet=$1
3939
3940         # with an assumption that at_max is the same on all nodes
3941         local MAX=${2:-$(max_recovery_time)}
3942
3943         local facets=$facet
3944         if [ "$FAILURE_MODE" = HARD ]; then
3945                 facets=$(facets_on_host $(facet_active_host $facet))
3946         fi
3947         echo affected facets: $facets
3948
3949         facets=${facets//,/ }
3950         # We can use "for" here because we are waiting the slowest.
3951         # The mgs not having the recovery_status proc entry, exclude it
3952         # from the facet list.
3953         for facet in ${facets//mgs/ }; do
3954                 local var_svc=${facet}_svc
3955                 local param="*.${!var_svc}.recovery_status"
3956
3957                 local host=$(facet_active_host $facet)
3958                 do_rpc_nodes "$host" _wait_recovery_complete $param $MAX
3959         done
3960 }
3961
3962 wait_mds_ost_sync () {
3963         # just because recovery is done doesn't mean we've finished
3964         # orphan cleanup. Wait for llogs to get synchronized.
3965         echo "Waiting for orphan cleanup..."
3966         # MAX value includes time needed for MDS-OST reconnection
3967         local MAX=$(( TIMEOUT * 2 ))
3968         local WAIT_TIMEOUT=${1:-$MAX}
3969         local WAIT=0
3970         local new_wait=true
3971         local list=$(mdts_nodes)
3972         local cmd="$LCTL get_param -n osp.*osc*.old_sync_processed"
3973         if ! do_facet $SINGLEMDS \
3974                 "$LCTL list_param osp.*osc*.old_sync_processed 2> /dev/null"
3975         then
3976                 # old way, use mds_sync
3977                 new_wait=false
3978                 list=$(osts_nodes)
3979                 cmd="$LCTL get_param -n obdfilter.*.mds_sync"
3980         fi
3981
3982         echo "wait $WAIT_TIMEOUT secs maximumly for $list mds-ost sync done."
3983         while [ $WAIT -lt $WAIT_TIMEOUT ]; do
3984                 local -a sync=($(do_nodes $list "$cmd"))
3985                 local con=1
3986                 local i
3987                 for ((i=0; i<${#sync[@]}; i++)); do
3988                         if $new_wait; then
3989                                 [ ${sync[$i]} -eq 1 ] && continue
3990                         else
3991                                 [ ${sync[$i]} -eq 0 ] && continue
3992                         fi
3993                         # there is a not finished MDS-OST synchronization
3994                         con=0
3995                         break;
3996                 done
3997                 sleep 2 # increase waiting time and cover statfs cache
3998                 [ ${con} -eq 1 ] && return 0
3999                 echo "Waiting $WAIT secs for $list $i mds-ost sync done."
4000                 WAIT=$((WAIT + 2))
4001         done
4002
4003         # show which nodes are not finished.
4004         cmd=$(echo $cmd | sed 's/-n//')
4005         do_nodes $list "$cmd"
4006         echo "$facet recovery node $i not done in $WAIT_TIMEOUT sec. $STATUS"
4007         return 1
4008 }
4009
4010 # Wait OSTs to be active on both client and MDT side.
4011 wait_osts_up() {
4012         local cmd="$LCTL get_param -n lov.$FSNAME-clilov-*.target_obd |
4013                 awk 'BEGIN {c = 0} /ACTIVE/{c += 1} END {printf \\\"%d\\\", c}'"
4014         wait_update $HOSTNAME "eval $cmd" $OSTCOUNT ||
4015                 error "wait_update OSTs up on client failed"
4016
4017         cmd="$LCTL get_param osp.$FSNAME-OST*-MDT0000.prealloc_last_id |
4018              awk '/=[1-9][0-9]/ { c += 1 } END { printf \\\"%d\\\", c }'"
4019         wait_update_facet $SINGLEMDS "eval $cmd" $OSTCOUNT ||
4020                 error "wait_update OSTs up on MDT0000 failed"
4021 }
4022
4023 wait_destroy_complete () {
4024         echo "Waiting for MDT destroys to complete"
4025         # MAX value shouldn't be big as this mean server responsiveness
4026         # never increase this just to make test pass but investigate
4027         # why it takes so long time
4028         local MAX=${1:-5}
4029         local WAIT=0
4030         local mdts=$(mdts_nodes)
4031         while [ $WAIT -lt $MAX ]; do
4032                 local -a RPCs=($(do_nodes $mdts $LCTL get_param -n osp.*.destroys_in_flight))
4033                 local con=1
4034                 local i
4035
4036                 for ((i=0; i<${#RPCs[@]}; i++)); do
4037                         [ ${RPCs[$i]} -eq 0 ] && continue
4038                         # there are still some destroy RPCs in flight
4039                         con=0
4040                         break;
4041                 done
4042                 [ ${con} -eq 1 ] && return 0 # done waiting
4043                 sleep 1
4044                 echo "Waiting ${WAIT}s for local destroys to complete"
4045                 WAIT=$((WAIT + 1))
4046         done
4047         echo "MDT destroys weren't done in $MAX sec."
4048         return 1
4049 }
4050
4051 fstrim_inram_devs() {
4052         local i
4053         local v
4054         local pids
4055
4056         [[ "$(facet_fstype ost1)" = "ldiskfs" ]] || return 0
4057         [[ $OSTDEVBASE == */tmp/* ]] || return 0
4058
4059         for (( i=1; i <= $OSTCOUNT; i++)); do
4060                 v="ost${i}_FSTRIM"
4061                 [[ ${!v} != "yes" ]] && continue
4062                 do_facet ost$i "fstrim $(facet_mntpt ost$i)" &
4063                 pids+=" $!"
4064         done
4065         [[ -n $pids ]] && wait $pids
4066
4067         return 0
4068 }
4069
4070 wait_delete_completed() {
4071         wait_delete_completed_mds $1 || return $?
4072         wait_destroy_complete || return $?
4073         fstrim_inram_devs
4074 }
4075
4076 wait_exit_ST () {
4077         local facet=$1
4078
4079         local WAIT=0
4080         local INTERVAL=1
4081         local running
4082         # conf-sanity 31 takes a long time cleanup
4083         while [ $WAIT -lt 300 ]; do
4084                 running=$(do_facet ${facet} "lsmod | grep lnet > /dev/null &&
4085 lctl dl | grep ' ST ' || true")
4086                 [ -z "${running}" ] && return 0
4087                 echo "waited $WAIT for${running}"
4088                 [ $INTERVAL -lt 64 ] && INTERVAL=$((INTERVAL + INTERVAL))
4089                 sleep $INTERVAL
4090                 WAIT=$((WAIT + INTERVAL))
4091         done
4092         echo "service didn't stop after $WAIT seconds.  Still running:"
4093         echo ${running}
4094         return 1
4095 }
4096
4097 wait_remote_prog () {
4098         local prog=$1
4099         local WAIT=0
4100         local INTERVAL=5
4101         local rc=0
4102
4103         [ "$PDSH" = "no_dsh" ] && return 0
4104
4105         while [ $WAIT -lt $2 ]; do
4106                 running=$(ps uax | grep "$PDSH.*$prog.*$MOUNT" |
4107                         grep -v grep) || true
4108                 [ -z "${running}" ] && return 0 || true
4109                 echo "waited $WAIT for: "
4110                 echo "$running"
4111                 [ $INTERVAL -lt 60 ] && INTERVAL=$((INTERVAL + INTERVAL))
4112                 sleep $INTERVAL
4113                 WAIT=$((WAIT + INTERVAL))
4114         done
4115         local pids=$(ps  uax | grep "$PDSH.*$prog.*$MOUNT" |
4116                         grep -v grep | awk '{print $2}')
4117         [ -z "$pids" ] && return 0
4118         echo "$PDSH processes still exists after $WAIT seconds.  Still running: $pids"
4119         # FIXME: not portable
4120         for pid in $pids; do
4121                 cat /proc/${pid}/status || true
4122                 cat /proc/${pid}/wchan || true
4123                 echo "Killing $pid"
4124                 kill -9 $pid || true
4125                 sleep 1
4126                 ps -P $pid && rc=1
4127         done
4128
4129         return $rc
4130 }
4131
4132 _lfs_df_check() {
4133         local clients=${1:-$CLIENTS}
4134         local rc=0
4135
4136         if [[ -z "$clients" ]]; then
4137                 $LFS df $MOUNT > /dev/null || rc=$?
4138         else
4139                 $PDSH $clients "$LFS df $MOUNT" > /dev/null || rc=$?
4140         fi
4141
4142         return $rc
4143 }
4144
4145 lfs_df_check() {
4146         local clients=${1:-$CLIENTS}
4147         local rc=0
4148
4149         _lfs_df_check "$clients" || rc=$?
4150
4151         check_lfs_df_ret_val $rc
4152 }
4153
4154 clients_up() {
4155         # not every config has many clients
4156         sleep 1
4157         lfs_df_check
4158 }
4159
4160 all_mds_up() {
4161         (( MDSCOUNT == 1 )) && return
4162
4163         # wait so that statfs data on MDT expire
4164         local delay=$(do_facet mds1 $LCTL \
4165                 get_param -n osp.*MDT*MDT0000.maxage | sort -n | tail -1)
4166
4167         [ -n "$delay" ] || error "fail to get maxage"
4168         sleep $delay
4169         local mdts=$(mdts_nodes)
4170
4171         # initiate statfs RPC, all to all MDTs
4172         do_nodes $mdts $LCTL get_param -N osp.*MDT*MDT*.filesfree >&/dev/null
4173         do_nodes $mdts $LCTL get_param -N osp.*MDT*MDT*.filesfree >&/dev/null
4174 }
4175
4176 client_up() {
4177         # usually checked on particular client or locally
4178         sleep 1
4179         lfs_df_check $1
4180 }
4181
4182 # usage: client_evicted client [evictor, mds1 by default]
4183 # return true if \a client was evicted by \a evictor in current test
4184 client_evicted() {
4185         local testid=$(echo $TESTNAME | tr '_' ' ')
4186         local client=$1
4187         local facet=${2:-mds1}
4188         local dev=$(facet_svc $facet)
4189
4190         client_up $client
4191         $PDSH $client "dmesg | tac | sed \"/$testid/,$ d\"" |
4192                 grep -q "client was evicted by ${dev}"
4193 }
4194
4195 client_reconnect_try() {
4196         local f=$MOUNT/recon
4197
4198         uname -n >> $f
4199         if [ -z "$CLIENTS" ]; then
4200                 $LFS df $MOUNT; uname -n >> $f
4201         else
4202                 do_nodes $CLIENTS "$LFS df $MOUNT; uname -n >> $f" > /dev/null
4203         fi
4204         echo "Connected clients: $(cat $f)"
4205         ls -l $f > /dev/null
4206         rm $f
4207 }
4208
4209 client_reconnect() {
4210         # one client_reconnect_try call does not always do the job...
4211         while true ; do
4212                 client_reconnect_try && break
4213                 sleep 1
4214         done
4215 }
4216
4217 affected_facets () {
4218         local facet=$1
4219
4220         local host=$(facet_active_host $facet)
4221         local affected=$facet
4222
4223         if [ "$FAILURE_MODE" = HARD ]; then
4224                 affected=$(facets_up_on_host $host)
4225         fi
4226         echo $affected
4227 }
4228
4229 facet_failover() {
4230         local E2FSCK_ON_MDT0=false
4231         if [ "$1" == "--fsck" ]; then
4232                 shift
4233                 [ $(facet_fstype $SINGLEMDS) == ldiskfs ] &&
4234                         E2FSCK_ON_MDT0=true
4235         fi
4236
4237         local facets=$1
4238         local sleep_time=$2
4239         local -a affecteds
4240         local facet
4241         local total=0
4242         local index=0
4243         local skip
4244
4245         #Because it will only get up facets, we need get affected
4246         #facets before shutdown
4247         #For HARD Failure mode, it needs make sure facets on the same
4248         #HOST will only be shutdown and reboot once
4249         for facet in ${facets//,/ }; do
4250                 local affected_facet
4251                 skip=0
4252                 #check whether facet has been included in other affected facets
4253                 for ((index=0; index<$total; index++)); do
4254                         [[ ,${affecteds[index]}, == *,$facet,* ]] && skip=1
4255                 done
4256
4257                 if [ $skip -eq 0 ]; then
4258                         affecteds[$total]=$(affected_facets $facet)
4259                         total=$((total+1))
4260                 fi
4261         done
4262
4263         for ((index=0; index<$total; index++)); do
4264                 facet=$(echo ${affecteds[index]} | tr -s " " | cut -d"," -f 1)
4265                 local host=$(facet_active_host $facet)
4266                 echo "Failing ${affecteds[index]} on $host"
4267                 shutdown_facet $facet
4268         done
4269
4270         echo "$(date +'%H:%M:%S (%s)') shut down"
4271
4272         local hostlist
4273         local waithostlist
4274
4275         for facet in ${facets//,/ }; do
4276                 local host=$(facet_active_host $facet)
4277
4278                 hostlist=$(expand_list $hostlist $host)
4279                 local fhost=$(facet_host $facet)
4280                 local ffhost=$(facet_failover_host $facet)
4281                 echo "facet: $facet facet_host: $fhost facet_failover_host: $ffhost"
4282                 if [ $(facet_host $facet) = \
4283                         $(facet_failover_host $facet) ]; then
4284                         waithostlist=$(expand_list $waithostlist $host)
4285                 fi
4286         done
4287
4288         if [ "$FAILURE_MODE" = HARD ]; then
4289                 for host in ${hostlist//,/ }; do
4290                         reboot_node $host
4291                 done
4292                 echo "$(date +'%H:%M:%S (%s)') $hostlist rebooted; waithostlist: $waithostlist"
4293                 # We need to wait the rebooted hosts in case if
4294                 # facet_HOST == facetfailover_HOST
4295                 if ! [ -z "$waithostlist" ]; then
4296                         wait_for_host $waithostlist
4297                         if $LOAD_MODULES_REMOTE; then
4298                                 echo "loading modules on $waithostlist"
4299                                 do_rpc_nodes $waithostlist load_modules_local
4300                         fi
4301                 fi
4302         else
4303                 sleep 10
4304         fi
4305
4306         if [[ " ${affecteds[@]} " =~ " $SINGLEMDS " ]]; then
4307                 change_active $SINGLEMDS
4308         fi
4309
4310         $E2FSCK_ON_MDT0 && (run_e2fsck $(facet_active_host $SINGLEMDS) \
4311                 $(facet_device $SINGLEMDS) "-n" || error "Running e2fsck")
4312
4313         local -a mountpids
4314
4315         for ((index=0; index<$total; index++)); do
4316                 if [[ ${affecteds[index]} != $SINGLEMDS ]]; then
4317                         change_active ${affecteds[index]}
4318                 fi
4319                 if $GSS_SK; then
4320                         init_gss
4321                         init_facets_vars_simple
4322                 fi
4323                 # start mgs first if it is affected
4324                 if ! combined_mgs_mds &&
4325                         list_member ${affecteds[index]} mgs; then
4326                         mount_facet mgs || error "Restart of mgs failed"
4327                         affecteds[index]=$(exclude_items_from_list \
4328                                 ${affecteds[index]} mgs)
4329                 fi
4330                 if [ -n "${affecteds[index]}" ]; then
4331                         echo mount facets: ${affecteds[index]}
4332                         mount_facets ${affecteds[index]} &
4333                         mountpids[index]=$!
4334                 fi
4335         done
4336         for ((index=0; index<$total; index++)); do
4337                 if [ -n "${affecteds[index]}" ]; then
4338                         wait ${mountpids[index]}
4339                 fi
4340
4341                 if $GSS_SK; then
4342                         do_nodes $(comma_list $(all_nodes)) \
4343                                 "keyctl show | grep lustre | cut -c1-11 |
4344                                 sed -e 's/ //g;' |
4345                                 xargs -IX keyctl setperm X 0x3f3f3f3f"
4346                 fi
4347         done
4348         echo "$(date +'%H:%M:%S (%s)') targets are mounted"
4349
4350         if [ "$FAILURE_MODE" = HARD ]; then
4351                 hostlist=$(exclude_items_from_list $hostlist $waithostlist)
4352                 if ! [ -z "$hostlist" ]; then
4353                         wait_for_host $hostlist
4354                         if $LOAD_MODULES_REMOTE; then
4355                                 echo "loading modules on $hostlist"
4356                                 do_rpc_nodes $hostlist load_modules_local
4357                         fi
4358                 fi
4359         fi
4360
4361         echo "$(date +'%H:%M:%S (%s)') facet_failover done"
4362 }
4363
4364 replay_barrier() {
4365         local facet=$1
4366         do_facet $facet "sync; sync; sync"
4367         $LFS df $MOUNT
4368
4369         # make sure there will be no seq change
4370         local clients=${CLIENTS:-$HOSTNAME}
4371         local f=fsa-\\\$\(hostname\)
4372         do_nodes $clients "mcreate $MOUNT/$f; rm $MOUNT/$f"
4373         do_nodes $clients "if [ -d $MOUNT2 ]; then mcreate $MOUNT2/$f; rm $MOUNT2/$f; fi"
4374
4375         local svc=${facet}_svc
4376         do_facet $facet $LCTL --device ${!svc} notransno
4377         #
4378         # If a ZFS OSD is made read-only here, its pool is "freezed". This
4379         # in-memory state has to be cleared by either rebooting the host or
4380         # exporting and reimporting the pool.
4381         #
4382         # Although the uberblocks are not updated when a pool is freezed,
4383         # transactions are still written to the disks. Modified blocks may be
4384         # cached in memory when tests try reading them back. The
4385         # export-and-reimport process also evicts any cached pool data from
4386         # memory to provide the correct "data loss" semantics.
4387         #
4388         # In the test framework, the exporting and importing operations are
4389         # handled by stop() and mount_facet() separately, which are used
4390         # inside fail() and fail_abort().
4391         #
4392         set_dev_readonly $facet
4393         do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
4394         $LCTL mark "local REPLAY BARRIER on ${!svc}"
4395 }
4396
4397 replay_barrier_nodf() {
4398         local facet=$1    echo running=${running}
4399         do_facet $facet "sync; sync; sync"
4400         local svc=${facet}_svc
4401         echo Replay barrier on ${!svc}
4402         do_facet $facet $LCTL --device ${!svc} notransno
4403         set_dev_readonly $facet
4404         do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
4405         $LCTL mark "local REPLAY BARRIER on ${!svc}"
4406 }
4407
4408 replay_barrier_nosync() {
4409         local facet=$1    echo running=${running}
4410         local svc=${facet}_svc
4411         echo Replay barrier on ${!svc}
4412         do_facet $facet $LCTL --device ${!svc} notransno
4413         set_dev_readonly $facet
4414         do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
4415         $LCTL mark "local REPLAY BARRIER on ${!svc}"
4416 }
4417
4418 #
4419 # Get Lustre client uuid for a given Lustre mount point.
4420 #
4421 get_client_uuid() {
4422         local mntpnt=${1:-$MOUNT}
4423
4424         echo -n $($LFS getname -u $mntpnt)
4425 }
4426
4427 mds_evict_client() {
4428         local mntpnt=${1:-$MOUNT}
4429         local uuid=$(get_client_uuid $mntpnt)
4430
4431         do_facet $SINGLEMDS \
4432                 "$LCTL set_param -n mdt.${mds1_svc}.evict_client $uuid"
4433 }
4434
4435 ost_evict_client() {
4436         local mntpnt=${1:-$MOUNT}
4437         local uuid=$(get_client_uuid $mntpnt)
4438
4439         do_facet ost1 \
4440                 "$LCTL set_param -n obdfilter.${ost1_svc}.evict_client $uuid"
4441 }
4442
4443 fail() {
4444         local facets=$1
4445         local clients=${CLIENTS:-$HOSTNAME}
4446
4447         SK_NO_KEY_save=$SK_NO_KEY
4448         if $GSS_SK; then
4449                 export SK_NO_KEY=false
4450         fi
4451         facet_failover $* || error "failover: $?"
4452         export SK_NO_KEY=$SK_NO_KEY_save
4453         # to initiate all OSC idling connections
4454         clients_up
4455         wait_clients_import_ready "$clients" "$facets"
4456         clients_up || error "post-failover stat: $?"
4457 }
4458
4459 fail_nodf() {
4460         local facet=$1
4461
4462         facet_failover $facet
4463 }
4464
4465 fail_abort() {
4466         local facet=$1
4467         local abort_type=${2:-"abort_recovery"}
4468
4469         stop $facet
4470         change_active $facet
4471         wait_for_facet $facet
4472         mount_facet $facet -o $abort_type
4473         clients_up || echo "first stat failed: $?"
4474         clients_up || error "post-failover stat: $?"
4475         all_mds_up
4476 }
4477
4478 # LU-16159: abort recovery will cancel update logs, which may leave broken
4479 # directories in the system, remove name entry if necessary
4480 fail_abort_cleanup() {
4481         rm -rf $DIR/$tdir/*
4482         find $DIR/$tdir -depth | while read D; do
4483                 rmdir "$D" || $LFS rm_entry "$D" || error "rm $D failed"
4484         done
4485 }
4486
4487 host_nids_address() {
4488         local nodes=$1
4489         local net=${2:-"."}
4490
4491         do_nodes $nodes "$LCTL list_nids | grep -w $net | cut -f 1 -d @"
4492 }
4493
4494 ip_is_v4() {
4495         local ipv4_re='^([0-9]{1,3}\.){3,3}[0-9]{1,3}$'
4496
4497         if ! [[ $1 =~ $ipv4_re ]]; then
4498                 return 1
4499         fi
4500
4501         local quads=(${1//\./ })
4502
4503         (( ${#quads[@]} == 4)) || return 1
4504
4505         (( quads[0] < 256 && quads[1] < 256 &&
4506            quads[2] < 256 && quads[3] < 256 )) || return 1
4507
4508         return 0
4509 }
4510
4511 ip_is_v6() {
4512         local ipv6_re='^([0-9a-f]{0,4}:){2,7}[0-9a-f]{0,4}$'
4513
4514         if ! [[ $1 =~ $ipv6_re ]]; then
4515                 return 1
4516         fi
4517
4518         local segment
4519         for segment in ${1//:/ }; do
4520                 ((0x$segment <= 0xFFFF)) || return 1
4521         done
4522
4523         return 0
4524 }
4525
4526 h2name_or_ip() {
4527         if [[ "$1" == '*' ]]; then
4528                 echo \'*\'
4529         elif ip_is_v4 "$1" || ip_is_v6 "$1" ; then
4530                 echo "$1@$2"
4531         else
4532                 local addr nidlist large_nidlist
4533                 local iplist=$(do_node $1 hostname -I | sed "s/$1://")
4534
4535                 for addr in ${iplist}; do
4536                         nid="${addr}@$2"
4537                         ip_is_v4 "$addr" &&
4538                                 nidlist="${nidlist:+$nidlist,}${nid}" ||
4539                                 large_nidlist="${large_nidlist:+$large_nidlist,}${nid}"
4540                 done
4541                 if [[ -n $nidlist ]] && [[ -n $large_nidlist ]]; then
4542                         if ${FORCE_LARGE_NID}; then
4543                                 echo "$large_nidlist"
4544                         else
4545                                 echo "$nidlist"
4546                         fi
4547                 elif [[ -n $nidlist ]]; then
4548                         echo "$nidlist"
4549                 elif [[ -n $large_nidlist ]]; then
4550                         echo "$large_nidlist"
4551                 else
4552                         echo "$1@$2"
4553                 fi
4554         fi
4555 }
4556
4557 h2nettype() {
4558         if [[ -n "$NETTYPE" ]]; then
4559                 h2name_or_ip "$1" "$NETTYPE"
4560         else
4561                 h2name_or_ip "$1" "$2"
4562         fi
4563 }
4564 declare -fx h2nettype
4565
4566 # This enables variables in cfg/"setup".sh files to support the pdsh HOSTLIST
4567 # expressions format. As a bonus we can then just pass in those variables
4568 # to pdsh. What this function does is take a HOSTLIST type string and
4569 # expand it into a space deliminated list for us.
4570 hostlist_expand() {
4571         local hostlist=$1
4572         local offset=$2
4573         local myList
4574         local item
4575         local list
4576
4577         [ -z "$hostlist" ] && return
4578
4579         # Translate the case of [..],..,[..] to [..] .. [..]
4580         list="${hostlist/],/] }"
4581         front=${list%%[*}
4582         [[ "$front" == *,* ]] && {
4583                 new="${list%,*} "
4584                 old="${list%,*},"
4585                 list=${list/${old}/${new}}
4586         }
4587
4588         for item in $list; do
4589         # Test if we have any []'s at all
4590                 if [ "$item" != "${item/\[/}" ]; then {
4591                 # Expand the [*] into list
4592                 name=${item%%[*}
4593                 back=${item#*]}
4594
4595                         if [ "$name" != "$item" ]; then
4596                                 group=${item#$name[*}
4597                                 group=${group%%]*}
4598
4599                                 for range in ${group//,/ }; do
4600                                         local order
4601
4602                                         begin=${range%-*}
4603                                         end=${range#*-}
4604
4605                                         # Number of leading zeros
4606                                         padlen=${#begin}
4607                                         padlen2=${#end}
4608                                         end=$(echo $end | sed 's/0*//')
4609                                         [[ -z "$end" ]] && end=0
4610                                         [[ $padlen2 -gt $padlen ]] && {
4611                                                 [[ $padlen2 -eq ${#end} ]] &&
4612                                                         padlen2=0
4613                                                 padlen=$padlen2
4614                                         }
4615                                         begin=$(echo $begin | sed 's/0*//')
4616                                         [ -z $begin ] && begin=0
4617
4618                                         if [ ! -z "${begin##[!0-9]*}" ]; then
4619                                                 order=$(seq -f "%0${padlen}g" $begin $end)
4620                                         else
4621                                                 order=$(eval echo {$begin..$end});
4622                                         fi
4623
4624                                         for num in $order; do
4625                                                 value="${name#*,}${num}${back}"
4626
4627                                                 [ "$value" != "${value/\[/}" ] && {
4628                                                     value=$(hostlist_expand "$value")
4629                                                 }
4630                                                 myList="$myList $value"
4631                                         done
4632                                 done
4633                         fi
4634                 } else {
4635                         myList="$myList $item"
4636                 } fi
4637         done
4638         myList=${myList//,/ }
4639         myList=${myList:1} # Remove first character which is a space
4640
4641         # Filter any duplicates without sorting
4642         list="$myList "
4643         myList="${list%% *}"
4644
4645         while [[ "$list" != ${myList##* } ]]; do
4646                 local tlist=" $list"
4647
4648                 list=${tlist// ${list%% *} / }
4649                 list=${list:1}
4650                 myList="$myList ${list%% *}"
4651         done
4652         myList="${myList%* }";
4653
4654         # We can select an object at an offset in the list
4655         [ $# -eq 2 ] && {
4656         cnt=0
4657         for item in $myList; do
4658                 let cnt=cnt+1
4659                 [ $cnt -eq $offset ] && {
4660                         myList=$item
4661                 }
4662         done
4663         [ $(get_node_count $myList) -ne 1 ] && myList=""
4664         }
4665         echo $myList
4666 }
4667
4668 facet_host() {
4669         local facet=$1
4670         local varname
4671
4672         [ "$facet" == client ] && echo -n $HOSTNAME && return
4673         varname=${facet}_HOST
4674         if [ -z "${!varname}" ]; then
4675                 if [ "${facet:0:3}" == "ost" ]; then
4676                         local fh=${facet%failover}_HOST
4677                         eval export ${facet}_HOST=${!fh}
4678                         if [ -z "${!varname}" ]; then
4679                                 eval export ${facet}_HOST=${ost_HOST}
4680                         fi
4681                 elif [ "${facet:0:3}" == "mdt" -o \
4682                         "${facet:0:3}" == "mds" -o \
4683                         "${facet:0:3}" == "mgs" ]; then
4684                         local temp
4685                         if [ "${facet}" == "mgsfailover" ] &&
4686                            [ -n "$mds1failover_HOST" ]; then
4687                                 temp=$mds1failover_HOST
4688                         else
4689                                 temp=${mds_HOST}
4690                         fi
4691                         eval export ${facet}_HOST=$temp
4692                 fi
4693         fi
4694         echo -n ${!varname}
4695 }
4696
4697 facet_failover_host() {
4698         local facet=$1
4699         local varname
4700
4701         var=${facet}failover_HOST
4702         if [ -n "${!var}" ]; then
4703                 echo ${!var}
4704                 return
4705         fi
4706
4707         if combined_mgs_mds && [ $facet == "mgs" ] &&
4708                 [ -n "$mds1failover_HOST" ]; then
4709                 echo $mds1failover_HOST
4710                 return
4711         fi
4712
4713         if [ "${facet:0:3}" == "mdt" -o "${facet:0:3}" == "mds" -o \
4714              "${facet:0:3}" == "mgs" ]; then
4715
4716                 eval export ${facet}failover_host=${mds_HOST}
4717                 echo ${mds_HOST}
4718                 return
4719         fi
4720
4721         if [[ $facet == ost* ]]; then
4722                 eval export ${facet}failover_host=${ost_HOST}
4723                 echo ${ost_HOST}
4724                 return
4725         fi
4726 }
4727
4728 facet_active() {
4729         local facet=$1
4730         local activevar=${facet}active
4731
4732         if [ -f $TMP/${facet}active ] ; then
4733                 source $TMP/${facet}active
4734         fi
4735
4736         active=${!activevar}
4737         if [ -z "$active" ] ; then
4738                 echo -n ${facet}
4739         else
4740                 echo -n ${active}
4741         fi
4742 }
4743
4744 facet_active_host() {
4745         facet_host $(facet_active $1)
4746 }
4747
4748 # Get the passive failover partner host of facet.
4749 facet_passive_host() {
4750         local facet=$1
4751         [[ $facet = client ]] && return
4752
4753         local host=${facet}_HOST
4754         local failover_host=${facet}failover_HOST
4755         local active_host=$(facet_active_host $facet)
4756
4757         [[ -z ${!failover_host} || ${!failover_host} = ${!host} ]] && return
4758
4759         if [[ $active_host = ${!host} ]]; then
4760                 echo -n ${!failover_host}
4761         else
4762                 echo -n ${!host}
4763         fi
4764 }
4765
4766 change_active() {
4767         local facetlist=$1
4768         local facet
4769
4770         for facet in ${facetlist//,/ }; do
4771                 local failover=${facet}failover
4772                 local host=`facet_host $failover`
4773
4774                 [ -z "$host" ] && return
4775
4776                 local curactive=`facet_active $facet`
4777
4778                 if [ -z "${curactive}" -o "$curactive" == "$failover" ] ; then
4779                         eval export ${facet}active=$facet
4780                 else
4781                         eval export ${facet}active=$failover
4782                 fi
4783                 # save the active host for this facet
4784                 local activevar=${facet}active
4785
4786                 echo "$activevar=${!activevar}" > $TMP/$activevar
4787                 [[ $facet = mds1 ]] && combined_mgs_mds && \
4788                 echo "mgsactive=${!activevar}" > $TMP/mgsactive
4789                 local TO=`facet_active_host $facet`
4790                 echo "Failover $facet to $TO"
4791         done
4792 }
4793
4794 do_node() {
4795         local verbose
4796         local quiet
4797
4798         # do not strip off hostname if verbose, b=19215
4799         [[ "$1" == "--verbose" ]] && verbose="$1" && shift
4800         [[ "$1" == "--quiet" || "$1" == "-q" ]] && quiet="$1" && shift
4801
4802         local HOST=$1
4803         shift
4804         local myPDSH=$PDSH
4805
4806         if [ "$HOST" = "$HOSTNAME" ]; then
4807                 myPDSH="no_dsh"
4808         elif [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" ]; then
4809                 echo "cannot run remote command on $HOST with $myPDSH"
4810                 return 128
4811         fi
4812         if $VERBOSE && [[ -z "$quiet" ]]; then
4813                 echo "CMD: $HOST $*" >&2
4814                 $myPDSH $HOST "$LCTL mark \"$*\"" > /dev/null 2>&1 || :
4815         fi
4816
4817         if [[ "$myPDSH" == "rsh" ]] ||
4818            [[ "$myPDSH" == *pdsh* && "$myPDSH" != *-S* ]]; then
4819                 # we need this because rsh and pdsh do not return
4820                 # exit code of an executed command
4821                 local command_status="$TMP/cs"
4822                 eval $myPDSH $HOST ":> $command_status"
4823                 eval $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests;
4824                                      PATH=\$PATH:/sbin:/usr/sbin;
4825                                      cd $RPWD;
4826                                      LUSTRE=\"$RLUSTRE\" bash -c \"$*\") ||
4827                                      echo command failed >$command_status"
4828                 [[ -n "$($myPDSH $HOST cat $command_status)" ]] && return 1 ||
4829                         return 0
4830         fi
4831
4832         if [[ -n "$verbose" ]]; then
4833                 # print HOSTNAME for myPDSH="no_dsh"
4834                 if [[ $myPDSH = no_dsh ]]; then
4835                         $myPDSH $HOST \
4836                         "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin;\
4837                         cd $RPWD; LUSTRE=\"$RLUSTRE\" bash -c \"$*\")" |
4838                         sed -e "s/^/${HOSTNAME}: /"
4839                 else
4840                         $myPDSH $HOST \
4841                         "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin;\
4842                         cd $RPWD; LUSTRE=\"$RLUSTRE\" bash -c \"$*\")"
4843                 fi
4844         else
4845                 $myPDSH $HOST \
4846                 "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin;\
4847                 cd $RPWD; LUSTRE=\"$RLUSTRE\" bash -c \"$*\")" |
4848                 sed "s/^${HOST}: //"
4849         fi
4850         return ${PIPESTATUS[0]}
4851 }
4852
4853 ##
4854 # Execute exact command line on host
4855 #
4856 # The \a host may be on a local or remote node, which is determined at
4857 # the time the command is run. Does careful argument quotation to
4858 # ensure that the exact command line is executed without any globbing,
4859 # substitution, or shell interpretation on the remote side. Does not
4860 # support --verbose or --quiet. Does not include "$host: " prefixes on
4861 # output. See also do_facet_vp().
4862 #
4863 # usage: do_node_vp "$host" "$command" "$arg"...
4864 do_node_vp() {
4865         local host="$1"
4866         shift
4867
4868         if [[ "$host" == "$HOSTNAME" ]]; then
4869                 bash -c "$(printf -- ' %q' "$@")"
4870                 return $?
4871         fi
4872
4873         if [[ "${PDSH}" != *pdsh* || "${PDSH}" != *-S* ]]; then
4874                 echo "cannot run '$*' on host '${host}' with PDSH='${PDSH}'" >&2
4875                 return 128
4876         fi
4877
4878         # -N Disable hostname: prefix on lines of output.
4879
4880         $PDSH "${host}" -N "cd $RPWD; PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; export LUSTRE=$RLUSTRE; $(printf -- ' %q' "$@")"
4881 }
4882
4883 single_local_node () {
4884         [ "$1" = "$HOSTNAME" ]
4885 }
4886
4887 # Outputs environment variable assignments that should be passed to remote nodes
4888 get_env_vars() {
4889         local var
4890         local value
4891         local facets=$(get_facets)
4892         local facet
4893
4894         for var in ${!MODOPTS_*}; do
4895                 value=${!var//\"/\\\"}
4896                 echo -n " ${var}=\"$value\""
4897         done
4898
4899         for facet in ${facets//,/ }; do
4900                 var=${facet}_FSTYPE
4901                 if [ -n "${!var}" ]; then
4902                         echo -n " $var=${!var}"
4903                 fi
4904         done
4905
4906         for var in MGSFSTYPE MDSFSTYPE OSTFSTYPE; do
4907                 if [ -n "${!var}" ]; then
4908                         echo -n " $var=${!var}"
4909                 fi
4910         done
4911
4912         for var in VERBOSE; do
4913                 if [ -n "${!var}" ]; then
4914                         echo -n " $var=${!var}"
4915                 fi
4916         done
4917
4918         if [ -n "$FSTYPE" ]; then
4919                 echo -n " FSTYPE=$FSTYPE"
4920         fi
4921
4922         for var in LNETLND NETTYPE; do
4923                 if [ -n "${!var}" ]; then
4924                         echo -n " $var=${!var}"
4925                 fi
4926         done
4927 }
4928
4929 do_nodes() {
4930         local verbose
4931         local quiet
4932
4933         # do not strip off hostname if verbose, b=19215
4934         [[ "$1" == "--verbose" ]] && verbose="$1" && shift
4935         [[ "$1" == "--quiet" || "$1" == "-q" ]] && quiet="$1" && shift
4936
4937         local rnodes=$1
4938         shift
4939
4940         if single_local_node $rnodes; then
4941                 do_node $verbose $quiet $rnodes "$@"
4942                 return $?
4943         fi
4944
4945         # This is part from do_node
4946         local myPDSH=$PDSH
4947
4948         [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" -o "$myPDSH" = "rsh" ] &&
4949                 echo "cannot run remote command on $rnodes with $myPDSH" &&
4950                 return 128
4951
4952         export FANOUT=$(get_node_count "${rnodes//,/ }")
4953         if $VERBOSE && [[ -z "$quiet" ]]; then
4954                 echo "CMD: $rnodes $*" >&2
4955                 $myPDSH $rnodes "$LCTL mark \"$*\"" > /dev/null 2>&1 || :
4956         fi
4957
4958         # do not replace anything from pdsh output if -N is used
4959         # -N     Disable hostname: prefix on lines of output.
4960         if [[ -n "$verbose" || $myPDSH = *-N* ]]; then
4961                 $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" $(get_env_vars) bash -c \"$*\")"
4962         else
4963                 $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" $(get_env_vars) bash -c \"$*\")" | sed -re "s/^[^:]*: //g"
4964         fi
4965         return ${PIPESTATUS[0]}
4966 }
4967
4968 ##
4969 # Execute commands on a single service's host
4970 #
4971 # The \a facet (service) may be on a local or remote node, which is
4972 # determined at the time the command is run.
4973 #
4974 # usage: do_facet $facet command [arg ...]
4975 do_facet() {
4976         local verbose
4977         local quiet
4978
4979         [[ "$1" == "--verbose" ]] && verbose="$1" && shift
4980         [[ "$1" == "--quiet" || "$1" == "-q" ]] && quiet="$1" && shift
4981
4982         local facet=$1
4983         shift
4984         local host=$(facet_active_host $facet)
4985
4986         [ -z "$host" ] && echo "No host defined for facet ${facet}" && exit 1
4987         do_node $verbose $quiet $host "$@"
4988 }
4989
4990 ##
4991 # Execute exact command line on the host of a facet
4992 #
4993 # The \a facet (service) may be on a local or remote node, which is
4994 # determined at the time the command is run. Does careful argument
4995 # quotation to ensure that the exact command line is executed without
4996 # any globbing, substitution, or shell interpretation on the remote
4997 # side. Does not support --verbose or --quiet. Does not include
4998 # "$host: " prefixes on output.
4999 #
5000 # usage: do_facet_vp "$facet" "$command" "$arg"...
5001 do_facet_vp() {
5002         local facet="$1"
5003         local host=$(facet_active_host "$facet")
5004         shift
5005
5006         if [[ -z "$host" ]]; then
5007                 echo "no host defined for facet ${facet}" >&2
5008                 exit 1
5009         fi
5010
5011         do_node_vp "$host" "$@"
5012 }
5013
5014 # Function: do_facet_random_file $FACET $FILE $SIZE
5015 # Creates FILE with random content on the given FACET of given SIZE
5016
5017 do_facet_random_file() {
5018         local facet="$1"
5019         local fpath="$2"
5020         local fsize="$3"
5021         local cmd="dd if=/dev/urandom of='$fpath' bs=$fsize count=1"
5022         do_facet $facet "$cmd 2>/dev/null"
5023 }
5024
5025 do_facet_create_file() {
5026         local facet="$1"
5027         local fpath="$2"
5028         local fsize="$3"
5029         local cmd="dd if=/dev/zero of='$fpath' bs=$fsize count=1"
5030         do_facet $facet "$cmd 2>/dev/null"
5031 }
5032
5033 do_nodesv() {
5034         do_nodes --verbose "$@"
5035 }
5036
5037 add() {
5038         local facet=$1
5039         shift
5040         # make sure its not already running
5041         stop ${facet} -f
5042         rm -f $TMP/${facet}active
5043         [[ $facet = mds1 ]] && combined_mgs_mds && rm -f $TMP/mgsactive
5044
5045         # make sure in-tree ldiskfs is loaded before mkfs
5046         if local_mode && [[ $(node_fstypes $HOSTNAME) == *ldiskfs* ]]; then
5047                 load_module ../ldiskfs/ldiskfs
5048         fi
5049
5050         do_facet ${facet} $MKFS $* || return ${PIPESTATUS[0]}
5051
5052         if [[ $(facet_fstype $facet) == zfs ]]; then
5053                 #
5054                 # After formatting a ZFS target, "cachefile=none" property will
5055                 # be set on the ZFS storage pool so that the pool is not
5056                 # automatically imported on system startup. And then the pool
5057                 # will be exported so as to leave the importing and exporting
5058                 # operations handled by mount_facet() and stop() separately.
5059                 #
5060                 refresh_partition_table $facet $(facet_vdevice $facet)
5061                 disable_zpool_cache $facet
5062                 export_zpool $facet
5063         fi
5064 }
5065
5066 # Device formatted as ost
5067 ostdevname() {
5068         local num=$1
5069         local DEVNAME=OSTDEV$num
5070
5071         local fstype=$(facet_fstype ost$num)
5072
5073         case $fstype in
5074                 ldiskfs )
5075                         local dev=ost${num}_dev
5076                         [[ -n ${!dev} ]] && eval DEVPTR=${!dev} ||
5077                         #if $OSTDEVn isn't defined, default is $OSTDEVBASE + num
5078                         eval DEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}};;
5079                 zfs )
5080                         #try $OSTZFSDEVn - independent of vdev
5081                         DEVNAME=OSTZFSDEV$num
5082                         eval DEVPTR=${!DEVNAME:=${FSNAME}-ost${num}/ost${num}};;
5083                 wbcfs )
5084                         :;;
5085                 * )
5086                         error "unknown fstype!";;
5087         esac
5088
5089         echo -n $DEVPTR
5090 }
5091
5092 # Physical device location of data
5093 ostvdevname() {
5094         local num=$1
5095         local DEVNAME
5096         local VDEVPTR
5097
5098         local fstype=$(facet_fstype ost$num)
5099
5100         case $fstype in
5101                 ldiskfs )
5102                         # vdevs are not supported by ldiskfs
5103                         eval VDEVPTR="";;
5104                 zfs )
5105                         #if $OSTDEVn isn't defined, default is $OSTDEVBASE{n}
5106                         # Device formatted by zfs
5107                         DEVNAME=OSTDEV$num
5108                         eval VDEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}};;
5109                 wbcfs )
5110                         :;;
5111                 * )
5112                         error "unknown fstype!";;
5113         esac
5114
5115         echo -n $VDEVPTR
5116 }
5117
5118 # Logical device formatted for lustre
5119 mdsdevname() {
5120         local num=$1
5121         local DEVNAME=MDSDEV$num
5122
5123         local fstype=$(facet_fstype mds$num)
5124
5125         case $fstype in
5126                 ldiskfs )
5127                         local dev=mds${num}_dev
5128                         [[ -n ${!dev} ]] && eval DEVPTR=${!dev} ||
5129                         #if $MDSDEVn isn't defined, default is $MDSDEVBASE{n}
5130                         eval DEVPTR=${!DEVNAME:=${MDSDEVBASE}${num}};;
5131                 zfs )
5132                         # try $MDSZFSDEVn - independent of vdev
5133                         DEVNAME=MDSZFSDEV$num
5134                         eval DEVPTR=${!DEVNAME:=${FSNAME}-mdt${num}/mdt${num}};;
5135                 wbcfs )
5136                         :;;
5137                 * )
5138                         error "unknown fstype!";;
5139         esac
5140
5141         echo -n $DEVPTR
5142 }
5143
5144 # Physical location of data
5145 mdsvdevname() {
5146         local VDEVPTR=""
5147         local num=$1
5148         local fstype=$(facet_fstype mds$num)
5149
5150         case $fstype in
5151                 ldiskfs )
5152                         # vdevs are not supported by ldiskfs
5153                         eval VDEVPTR="";;
5154                 zfs )
5155                         # if $MDSDEVn isn't defined, default is $MDSDEVBASE{n}
5156                         # Device formatted by ZFS
5157                         local DEVNAME=MDSDEV$num
5158                         eval VDEVPTR=${!DEVNAME:=${MDSDEVBASE}${num}};;
5159                 wbcfs )
5160                         :;;
5161                 * )
5162                         error "unknown fstype!";;
5163         esac
5164
5165         echo -n $VDEVPTR
5166 }
5167
5168 mgsdevname() {
5169         local DEVPTR
5170         local fstype=$(facet_fstype mgs)
5171
5172         case $fstype in
5173         ldiskfs )
5174                 if [ $(facet_host mgs) = $(facet_host mds1) ] &&
5175                    ( [ -z "$MGSDEV" ] || [ $MGSDEV = $MDSDEV1 ] ); then
5176                         DEVPTR=$(mdsdevname 1)
5177                 else
5178                         [[ -n $mgs_dev ]] && DEVPTR=$mgs_dev ||
5179                         DEVPTR=$MGSDEV
5180                 fi;;
5181         zfs )
5182                 if [ $(facet_host mgs) = $(facet_host mds1) ] &&
5183                     ( [ -z "$MGSZFSDEV" ] &&
5184                         [ -z "$MGSDEV" -o "$MGSDEV" = $(mdsvdevname 1) ] ); then
5185                         DEVPTR=$(mdsdevname 1)
5186                 else
5187                         DEVPTR=${MGSZFSDEV:-${FSNAME}-mgs/mgs}
5188                 fi;;
5189         wbcfs )
5190                 :;;
5191         * )
5192                 error "unknown fstype!";;
5193         esac
5194
5195         echo -n $DEVPTR
5196 }
5197
5198 mgsvdevname() {
5199         local VDEVPTR=""
5200
5201         local fstype=$(facet_fstype mgs)
5202
5203         case $fstype in
5204         ldiskfs )
5205                 # vdevs are not supported by ldiskfs
5206                 ;;
5207         zfs )
5208                 if [ $(facet_host mgs) = $(facet_host mds1) ] &&
5209                    ( [ -z "$MGSDEV" ] &&
5210                        [ -z "$MGSZFSDEV" -o "$MGSZFSDEV" = $(mdsdevname 1) ]); then
5211                         VDEVPTR=$(mdsvdevname 1)
5212                 elif [ -n "$MGSDEV" ]; then
5213                         VDEVPTR=$MGSDEV
5214                 fi;;
5215         wbcfs )
5216                 :;;
5217         * )
5218                 error "unknown fstype!";;
5219         esac
5220
5221         echo -n $VDEVPTR
5222 }
5223
5224 facet_mntpt () {
5225         local facet=$1
5226         [[ $facet = mgs ]] && combined_mgs_mds && facet="mds1"
5227
5228         local var=${facet}_MOUNT
5229         eval mntpt=${!var:-${MOUNT}-$facet}
5230
5231         echo -n $mntpt
5232 }
5233
5234 mount_ldiskfs() {
5235         local facet=$1
5236         local dev=$(facet_device $facet)
5237         local mnt=${2:-$(facet_mntpt $facet)}
5238         local opts
5239         local dm_dev=$dev
5240
5241         if dm_flakey_supported $facet; then
5242                 dm_dev=$(dm_create_dev $facet $dev)
5243                 [[ -n "$dm_dev" ]] || dm_dev=$dev
5244         fi
5245         is_blkdev $facet $dm_dev || opts=$(csa_add "$opts" -o loop)
5246         export_dm_dev $facet $dm_dev
5247
5248         do_facet $facet mount -t ldiskfs $opts $dm_dev $mnt
5249 }
5250
5251 unmount_ldiskfs() {
5252         local facet=$1
5253         local dev=$(facet_device $facet)
5254         local mnt=${2:-$(facet_mntpt $facet)}
5255
5256         do_facet $facet $UMOUNT $mnt
5257 }
5258
5259 var_name() {
5260         echo -n "$1" | tr -c '[:alnum:]\n' '_'
5261 }
5262
5263 mount_zfs() {
5264         local facet=$1
5265         local ds=$(facet_device $facet)
5266         local mnt=${2:-$(facet_mntpt $facet)}
5267         local canmnt
5268         local mntpt
5269
5270         import_zpool $facet
5271         canmnt=$(do_facet $facet $ZFS get -H -o value canmount $ds)
5272         mntpt=$(do_facet $facet $ZFS get -H -o value mountpoint $ds)
5273         do_facet $facet $ZFS set canmount=noauto $ds
5274         #
5275         # The "legacy" mount method is used here because "zfs unmount $mnt"
5276         # calls stat(2) on $mnt/../*, which may include $MOUNT.  If certain
5277         # targets are not available at the time, the stat(2) on $MOUNT will
5278         # hang.
5279         #
5280         do_facet $facet $ZFS set mountpoint=legacy $ds
5281         do_facet $facet mount -t zfs $ds $mnt
5282         eval export mz_$(var_name ${facet}_$ds)_canmount=$canmnt
5283         eval export mz_$(var_name ${facet}_$ds)_mountpoint=$mntpt
5284 }
5285
5286 unmount_zfs() {
5287         local facet=$1
5288         local ds=$(facet_device $facet)
5289         local mnt=${2:-$(facet_mntpt $facet)}
5290         local var_mntpt=mz_$(var_name ${facet}_$ds)_mountpoint
5291         local var_canmnt=mz_$(var_name ${facet}_$ds)_canmount
5292         local mntpt=${!var_mntpt}
5293         local canmnt=${!var_canmnt}
5294
5295         unset $var_mntpt
5296         unset $var_canmnt
5297         do_facet $facet umount $mnt
5298         do_facet $facet $ZFS set mountpoint=$mntpt $ds
5299         do_facet $facet $ZFS set canmount=$canmnt $ds
5300         export_zpool $facet
5301 }
5302
5303 mount_fstype() {
5304         local facet=$1
5305         local mnt=$2
5306         local fstype=$(facet_fstype $facet)
5307
5308         mount_$fstype $facet $mnt
5309 }
5310
5311 unmount_fstype() {
5312         local facet=$1
5313         local mnt=$2
5314         local fstype=$(facet_fstype $facet)
5315
5316         unmount_$fstype $facet $mnt
5317 }
5318
5319 ########
5320 ## MountConf setup
5321
5322 stopall() {
5323         # make sure we are using the primary server, so test-framework will
5324         # be able to clean up properly.
5325         activemds=`facet_active mds1`
5326         if [ $activemds != "mds1" ]; then
5327                 fail mds1
5328         fi
5329
5330         local clients=$CLIENTS
5331         [ -z $clients ] && clients=$(hostname)
5332
5333         zconf_umount_clients $clients $MOUNT "$*" || true
5334         [ -n "$MOUNT2" ] && zconf_umount_clients $clients $MOUNT2 "$*" || true
5335
5336         [ -n "$CLIENTONLY" ] && return
5337
5338         # The add fn does rm ${facet}active file, this would be enough
5339         # if we use do_facet <facet> only after the facet added, but
5340         # currently we use do_facet mds in local.sh
5341         local num
5342         for num in `seq $MDSCOUNT`; do
5343                 stop mds$num -f
5344                 rm -f ${TMP}/mds${num}active
5345         done
5346         combined_mgs_mds && rm -f $TMP/mgsactive
5347
5348         for num in `seq $OSTCOUNT`; do
5349                 stop ost$num -f
5350                 rm -f $TMP/ost${num}active
5351         done
5352
5353         if ! combined_mgs_mds ; then
5354                 stop mgs
5355         fi
5356
5357         if $SHARED_KEY; then
5358                 export SK_MOUNTED=false
5359         fi
5360
5361         return 0
5362 }
5363
5364 cleanup_echo_devs () {
5365         trap 0
5366         local dev
5367         local devs=$($LCTL dl | grep echo | awk '{print $4}')
5368
5369         for dev in $devs; do
5370                 $LCTL --device $dev cleanup
5371                 $LCTL --device $dev detach
5372         done
5373 }
5374
5375 # Allow %pK to print raw pointers and save the initial value
5376 kptr_enable_and_save() {
5377         # do not overwrite whatever was initially saved:
5378         [[ -f $TMP/kptr-$PPID-env ]] && return
5379
5380         declare -A kptr
5381         for node in $(all_nodes); do
5382                 kptr[$node]=$(do_node $node "sysctl --values kernel/kptr_restrict")
5383                 do_node $node "sysctl -wq kernel/kptr_restrict=1"
5384         done
5385         declare -p kptr > $TMP/kptr-$PPID-env
5386 }
5387
5388 # Restore the initial %pK settings
5389 kptr_restore() {
5390         [[ ! -f $TMP/kptr-$PPID-env ]] && return
5391
5392         source $TMP/kptr-$PPID-env
5393
5394         local param
5395         for node in $(all_nodes); do
5396                 [[ -z ${kptr[$node]} ]] && continue
5397                 param="kernel/kptr_restrict=${kptr[$node]}"
5398                 do_node $node "sysctl -wq ${param} || true"
5399         done
5400 }
5401
5402 cleanupall() {
5403         nfs_client_mode && return
5404         cifs_client_mode && return
5405
5406         cleanup_echo_devs
5407         CLEANUP_DM_DEV=true stopall $*
5408
5409         [[ $KPTR_ON_MOUNT ]] && kptr_restore
5410
5411         unload_modules
5412         cleanup_sk
5413         cleanup_gss
5414 }
5415
5416 combined_mgs_mds () {
5417         [[ "$(mdsdevname 1)" = "$(mgsdevname)" ]] &&
5418                 [[ "$(facet_host mds1)" = "$(facet_host mgs)" ]]
5419 }
5420
5421 lower() {
5422         echo -n "$1" | tr '[:upper:]' '[:lower:]'
5423 }
5424
5425 upper() {
5426         echo -n "$1" | tr '[:lower:]' '[:upper:]'
5427 }
5428
5429 squash_opt() {
5430         local var="$*"
5431         local other=""
5432         local opt_o=""
5433         local opt_e=""
5434         local first_e=0
5435         local first_o=0
5436         local take=""
5437
5438         var=$(echo "$var" | sed -e 's/,\( \)*/,/g')
5439         for i in $(echo "$var"); do
5440                 if [ "$i" == "-O" ]; then
5441                         take="o";
5442                         first_o=$(($first_o + 1))
5443                         continue;
5444                 fi
5445                 if [ "$i" == "-E" ]; then
5446                         take="e";
5447                         first_e=$(($first_e + 1 ))
5448                         continue;
5449                 fi
5450                 case $take in
5451                         "o")
5452                                 [ $first_o -gt 1 ] && opt_o+=",";
5453                                 opt_o+="$i";
5454                                 ;;
5455                         "e")
5456                                 [ $first_e -gt 1 ] && opt_e+=",";
5457                                 opt_e+="$i";
5458                                 ;;
5459                         *)
5460                                 other+=" $i";
5461                                 ;;
5462                 esac
5463                 take=""
5464         done
5465
5466         echo -n "$other"
5467         [ -n "$opt_o" ] && echo " -O $opt_o"
5468         [ -n "$opt_e" ] && echo " -E $opt_e"
5469 }
5470
5471 mkfs_opts() {
5472         local facet=$1
5473         local dev=$2
5474         local fsname=${3:-"$FSNAME"}
5475         local type=$(facet_type $facet)
5476         local index=$(facet_index $facet)
5477         local fstype=$(facet_fstype $facet)
5478         local host=$(facet_host $facet)
5479         local opts
5480         local fs_mkfs_opts
5481         local var
5482         local varbs=${facet}_BLOCKSIZE
5483
5484         if [ $type == MGS ] || ( [ $type == MDS ] &&
5485                                  [ "$dev" == $(mgsdevname) ] &&
5486                                  [ "$host" == "$(facet_host mgs)" ] ); then
5487                 opts="--mgs"
5488         else
5489                 opts="--mgsnode=$MGSNID"
5490         fi
5491
5492         if [ $type != MGS ]; then
5493                 opts+=" --fsname=$fsname --$(lower ${type/MDS/MDT}) \
5494                         --index=$index"
5495         fi
5496
5497         var=${facet}failover_HOST
5498         if [ -n "${!var}" ] && [ ${!var} != $(facet_host $facet) ]; then
5499                 opts+=" --failnode=$(h2nettype ${!var})"
5500         fi
5501
5502         opts+=${TIMEOUT:+" --param=sys.timeout=$TIMEOUT"}
5503         opts+=${LDLM_TIMEOUT:+" --param=sys.ldlm_timeout=$LDLM_TIMEOUT"}
5504
5505         if [ $type == MDS ]; then
5506                 opts+=${DEF_STRIPE_SIZE:+" --param=lov.stripesize=$DEF_STRIPE_SIZE"}
5507                 opts+=${DEF_STRIPE_COUNT:+" --param=lov.stripecount=$DEF_STRIPE_COUNT"}
5508                 opts+=${L_GETIDENTITY:+" --param=mdt.identity_upcall=$L_GETIDENTITY"}
5509
5510                 if [ $fstype == ldiskfs ]; then
5511                         var=${facet}_JRN
5512                         if [ -n "${!var}" ]; then
5513                                 fs_mkfs_opts+=" -J device=${!var}"
5514                         else
5515                                 fs_mkfs_opts+=${MDSJOURNALSIZE:+" -J size=$MDSJOURNALSIZE"}
5516                         fi
5517                         fs_mkfs_opts+=${MDSISIZE:+" -i $MDSISIZE"}
5518                 fi
5519         fi
5520
5521         if [ $type == OST ]; then
5522                 if [ $fstype == ldiskfs ]; then
5523                         var=${facet}_JRN
5524                         if [ -n "${!var}" ]; then
5525                                 fs_mkfs_opts+=" -J device=${!var}"
5526                         else
5527                                 fs_mkfs_opts+=${OSTJOURNALSIZE:+" -J size=$OSTJOURNALSIZE"}
5528                         fi
5529                 fi
5530         fi
5531
5532         opts+=" --backfstype=$fstype"
5533
5534         var=${type}SIZE
5535         if [ -n "${!var}" ]; then
5536                 opts+=" --device-size=${!var}"
5537         fi
5538
5539         var=$(upper $fstype)_MKFS_OPTS
5540         fs_mkfs_opts+=${!var:+" ${!var}"}
5541
5542         var=${type}_FS_MKFS_OPTS
5543         fs_mkfs_opts+=${!var:+" ${!var}"}
5544
5545         [[ "$QUOTA_TYPE" =~ "p" ]] && fs_mkfs_opts+=" -O project"
5546
5547         [ $fstype == ldiskfs ] && fs_mkfs_opts+=" -b ${!varbs:-$BLCKSIZE}"
5548         [ $fstype == ldiskfs ] && fs_mkfs_opts=$(squash_opt $fs_mkfs_opts)
5549
5550         if [ -n "${fs_mkfs_opts## }" ]; then
5551                 opts+=" --mkfsoptions=\\\"${fs_mkfs_opts## }\\\""
5552         fi
5553
5554         var=${type}OPT
5555         opts+=${!var:+" ${!var}"}
5556
5557         echo -n "$opts"
5558 }
5559
5560 mountfs_opts() {
5561         local facet=$1
5562         local type=$(facet_type $facet)
5563         local var=${type}_MOUNT_FS_OPTS
5564         local opts=""
5565         if [ -n "${!var}" ]; then
5566                 opts+=" --mountfsoptions=${!var}"
5567         fi
5568         echo -n "$opts"
5569 }
5570
5571 check_ost_indices() {
5572         local index_count=${#OST_INDICES[@]}
5573         [[ $index_count -eq 0 || $OSTCOUNT -le $index_count ]] && return 0
5574
5575         # OST count is greater than the index count in $OST_INDEX_LIST.
5576         # We need check whether there are duplicate indices.
5577         local i
5578         local j
5579         local index
5580         for i in $(seq $((index_count + 1)) $OSTCOUNT); do
5581                 index=$(facet_index ost$i)
5582                 for j in $(seq 0 $((index_count - 1))); do
5583                         [[ $index -ne ${OST_INDICES[j]} ]] ||
5584                         error "ost$i has the same index $index as ost$((j+1))"
5585                 done
5586         done
5587 }
5588
5589 __touch_device()
5590 {
5591         local facet_type=$1 # mgs || mds || ost
5592         local facet_num=$2
5593         local facet=${1}${2}
5594         local device
5595
5596         case "$(facet_fstype $facet)" in
5597         ldiskfs)
5598                 device=$(${facet_type}devname $facet_num)
5599                 ;;
5600         zfs)
5601                 device=$(${facet_type}vdevname $facet_num)
5602                 ;;
5603         *)
5604                 error "Unhandled filesystem type"
5605                 ;;
5606         esac
5607
5608         do_facet $facet "[ -e \"$device\" ]" && return
5609
5610         # Note: the following check only works with absolute paths
5611         [[ ! "$device" =~ ^/dev/ ]] || [[ "$device" =~ ^/dev/shm/ ]] ||
5612                 error "$facet: device '$device' does not exist"
5613
5614         # zpool create doesn't like empty files
5615         [[ $(facet_fstype $facet) == zfs ]] && return 0
5616
5617         do_facet $facet "touch \"${device}\""
5618 }
5619
5620 format_mgs() {
5621         local quiet
5622         local fstype=$(facet_fstype mgs)
5623
5624         [[ "$fstype" == "wbcfs" ]] && return
5625
5626         if ! $VERBOSE; then
5627                 quiet=yes
5628         fi
5629         echo "Format mgs: $(mgsdevname)"
5630         reformat_external_journal mgs
5631
5632         # touch "device" in case it is a loopback file for testing and needs to
5633         # be created. mkfs.lustre doesn't do this to avoid accidentally writing
5634         # to non-existent files in /dev if the admin made a typo during setup
5635         __touch_device mgs
5636
5637         add mgs $(mkfs_opts mgs $(mgsdevname)) $(mountfs_opts mgs) --reformat \
5638                 $(mgsdevname) $(mgsvdevname) ${quiet:+>/dev/null} || exit 10
5639 }
5640
5641 format_mdt() {
5642         local num=$1
5643         local quiet
5644         local fstype=$(facet_fstype mdt$num)
5645
5646         [[ "$fstype" == "wbcfs" ]] && return
5647
5648         if ! $VERBOSE; then
5649                 quiet=yes
5650         fi
5651         echo "Format mds$num: $(mdsdevname $num)"
5652         reformat_external_journal mds$num
5653
5654         __touch_device mds $num
5655
5656         add mds$num $(mkfs_opts mds$num $(mdsdevname ${num})) \
5657                 $(mountfs_opts mds$num) --reformat $(mdsdevname $num) \
5658                 $(mdsvdevname $num) ${quiet:+>/dev/null} || exit 10
5659 }
5660
5661 format_ost() {
5662         local num=$1
5663         local fstype=$(facet_fstype ost$num)
5664
5665         [[ "$fstype" == "wbcfs" ]] && return
5666
5667         if ! $VERBOSE; then
5668                 quiet=yes
5669         fi
5670         echo "Format ost$num: $(ostdevname $num)"
5671         reformat_external_journal ost$num
5672
5673         __touch_device ost $num
5674
5675         add ost$num $(mkfs_opts ost$num $(ostdevname ${num})) \
5676                 $(mountfs_opts ost$num) --reformat $(ostdevname $num) \
5677                 $(ostvdevname ${num}) ${quiet:+>/dev/null} || exit 10
5678 }
5679
5680 formatall() {
5681         stopall -f
5682         # Set hostid for ZFS/SPL zpool import protection
5683         # (Assumes MDS version is also OSS version)
5684         if [ $(lustre_version_code $SINGLEMDS) -ge $(version_code 2.8.54) ];
5685         then
5686                 do_rpc_nodes "$(comma_list $(all_server_nodes))" set_hostid
5687         fi
5688
5689         # We need ldiskfs here, may as well load them all
5690         load_modules
5691         [ -n "$CLIENTONLY" ] && return
5692         echo Formatting mgs, mds, osts
5693         if ! combined_mgs_mds ; then
5694                 format_mgs
5695         fi
5696
5697         for num in $(seq $MDSCOUNT); do
5698                 format_mdt $num
5699         done
5700
5701         export OST_INDICES=($(hostlist_expand "$OST_INDEX_LIST"))
5702         check_ost_indices
5703         for num in $(seq $OSTCOUNT); do
5704                 format_ost $num
5705         done
5706 }
5707
5708 mount_client() {
5709         grep " $1 " /proc/mounts || zconf_mount $HOSTNAME $*
5710 }
5711
5712 umount_client() {
5713         grep " $1 " /proc/mounts && zconf_umount $HOSTNAME $*
5714 }
5715
5716 # usage: switch_identity MDSNUM ENABLE_UPCALL
5717 #
5718 # return values:
5719 # 0: success, the identity upcall was previously enabled already.
5720 # 1: success, the identity upcall was previously disabled.
5721 # 2: fail.
5722 switch_identity() {
5723         local num=$1
5724         local enable=$2
5725         local facet=mds$num
5726         local MDT="$(mdtname_from_index $((num - 1)) $MOUNT)"
5727         local upcall="$L_GETIDENTITY"
5728
5729         [[ -n "$MDT" ]] || return 2
5730
5731         local param="mdt.$MDT.identity_upcall"
5732         local old="$(do_facet $facet "lctl get_param -n $param")"
5733
5734         [[ "$enable" == "true" ]] || upcall="NONE"
5735
5736         do_facet $facet "lctl set_param -n $param='$upcall'" || return 2
5737         do_facet $facet "lctl set_param -n mdt.$MDT.identity_flush=-1"
5738
5739         [[ "$old" != "NONE" ]] # implicit "&& return 0 || return 1"
5740 }
5741
5742 remount_client()
5743 {
5744         zconf_umount $HOSTNAME $1 || error "umount failed"
5745         zconf_mount $HOSTNAME $1 || error "mount failed with ($?)"
5746 }
5747
5748 writeconf_facet() {
5749         local facet=$1
5750         local dev=$2
5751
5752         stop ${facet} -f
5753         rm -f $TMP/${facet}active
5754         do_facet ${facet} "$TUNEFS --quiet --writeconf $dev" || return 1
5755         return 0
5756 }
5757
5758 writeconf_all () {
5759         local mdt_count=${1:-$MDSCOUNT}
5760         local ost_count=${2:-$OSTCOUNT}
5761         local rc=0
5762
5763         for num in $(seq $mdt_count); do
5764                 DEVNAME=$(mdsdevname $num)
5765                 writeconf_facet mds$num $DEVNAME || rc=$?
5766         done
5767
5768         for num in $(seq $ost_count); do
5769                 DEVNAME=$(ostdevname $num)
5770                 writeconf_facet ost$num $DEVNAME || rc=$?
5771         done
5772         return $rc
5773 }
5774
5775 mountmgs() {
5776         if ! combined_mgs_mds ; then
5777                 start mgs $(mgsdevname) $MGS_MOUNT_OPTS
5778                 do_facet mgs "$LCTL set_param -P debug_raw_pointers=Y"
5779         fi
5780 }
5781
5782 mountmds() {
5783         local num
5784         local devname
5785         local host
5786         local varname
5787         for num in $(seq $MDSCOUNT); do
5788                 devname=$(mdsdevname $num)
5789                 start mds$num $devname $MDS_MOUNT_OPTS
5790
5791                 # We started mds$num, now we should set mds${num}_HOST
5792                 # and mds${num}failover_HOST variables properly if they
5793                 # are not set.
5794                 host=$(facet_host mds$num)
5795                 for varname in mds${num}_HOST mds${num}failover_HOST; do
5796                         if [[ -z "${!varname}" ]]; then
5797                                 eval $varname=$host
5798                         fi
5799                 done
5800                 if [[ "$IDENTITY_UPCALL" != "default" ]]; then
5801                         switch_identity $num $IDENTITY_UPCALL
5802                 fi
5803         done
5804         if combined_mgs_mds ; then
5805                 do_facet mgs "$LCTL set_param -P debug_raw_pointers=Y"
5806         fi
5807 }
5808
5809 unmountoss() {
5810         local num
5811
5812         for num in $(seq $OSTCOUNT); do
5813                 stop ost$num -f
5814                 rm -f $TMP/ost${num}active
5815         done
5816 }
5817
5818 mountoss() {
5819         local num
5820         local devname
5821         local host
5822         local varname
5823         for num in $(seq $OSTCOUNT); do
5824                 devname=$(ostdevname $num)
5825                 start ost$num $devname $OST_MOUNT_OPTS
5826
5827                 # We started ost$num, now we should set ost${num}_HOST
5828                 # and ost${num}failover_HOST variables properly if they
5829                 # are not set.
5830                 host=$(facet_host ost$num)
5831                 for varname in ost${num}_HOST ost${num}failover_HOST; do
5832                         if [[ -z "${!varname}" ]]; then
5833                                 eval $varname=$host
5834                         fi
5835                 done
5836         done
5837 }
5838
5839 mountcli() {
5840         [ "$DAEMONFILE" ] && $LCTL debug_daemon start $DAEMONFILE $DAEMONSIZE
5841         if [ ! -z $arg1 ]; then
5842                 [ "$arg1" = "server_only" ] && return
5843         fi
5844         mount_client $MOUNT
5845         if [ -n "$CLIENTS" ]; then
5846                 zconf_mount_clients $CLIENTS $MOUNT
5847         fi
5848         clients_up
5849
5850         if [ "$MOUNT_2" ]; then
5851                 mount_client $MOUNT2
5852                 if [ -n "$CLIENTS" ]; then
5853                         zconf_mount_clients $CLIENTS $MOUNT2
5854                 fi
5855         fi
5856 }
5857
5858 sk_nodemap_setup() {
5859         local sk_map_name=${1:-$SK_S2SNM}
5860         local sk_map_nodes=${2:-$HOSTNAME}
5861         do_node $(mgs_node) "$LCTL nodemap_add $sk_map_name"
5862         for servernode in $sk_map_nodes; do
5863                 local nids=$(do_nodes $servernode "$LCTL list_nids")
5864                 for nid in $nids; do
5865                         do_node $(mgs_node) "$LCTL nodemap_add_range --name \
5866                                 $sk_map_name --range $nid"
5867                 done
5868         done
5869 }
5870
5871 setupall() {
5872         local arg1=$1
5873
5874         nfs_client_mode && return
5875         cifs_client_mode && return
5876
5877         sanity_mount_check || error "environments are insane!"
5878
5879         load_modules
5880
5881         init_gss
5882
5883         if [ -z "$CLIENTONLY" ]; then
5884                 echo Setup mgs, mdt, osts
5885                 echo $WRITECONF | grep -q "writeconf" && writeconf_all
5886
5887                 if $SK_MOUNTED; then
5888                         echo "Shared Key file system already mounted"
5889                 else
5890                         mountmgs
5891                         mountmds
5892                         mountoss
5893                         if $SHARED_KEY; then
5894                                 export SK_MOUNTED=true
5895                         fi
5896                 fi
5897                 if $GSS_SK; then
5898                         echo "GSS_SK: setting kernel keyring perms"
5899                         do_nodes $(comma_list $(all_nodes)) \
5900                                 "keyctl show | grep lustre | cut -c1-11 |
5901                                 sed -e 's/ //g;' |
5902                                 xargs -IX keyctl setperm X 0x3f3f3f3f"
5903
5904                         if $SK_S2S; then
5905                                 # Need to start one nodemap for servers,
5906                                 # and one for clients.
5907                                 sk_nodemap_setup $SK_S2SNM \
5908                                         $(comma_list $(all_server_nodes))
5909                                 mountcli
5910                                 sk_nodemap_setup $SK_S2SNMCLI \
5911                                         ${CLIENTS:-$HOSTNAME}
5912                                 echo "Nodemap set up for SK S2S, remounting."
5913                                 stopall
5914                                 mountmgs
5915                                 mountmds
5916                                 mountoss
5917                         fi
5918                 fi
5919         fi
5920
5921         # wait a while to allow sptlrpc configuration be propogated to targets,
5922         # only needed when mounting new target devices.
5923         if $GSS; then
5924                 sleep 10
5925         fi
5926
5927         mountcli
5928         init_param_vars
5929
5930         [[ $KPTR_ON_MOUNT ]] && kptr_enable_and_save
5931
5932         # by remounting mdt before ost, initial connect from mdt to ost might
5933         # timeout because ost is not ready yet. wait some time to its fully
5934         # recovery. initial obd_connect timeout is 5s; in GSS case it's
5935         # preceeded by a context negotiation rpc with $TIMEOUT.
5936         # FIXME better by monitoring import status.
5937         if $GSS; then
5938                 if $GSS_SK; then
5939                         set_rule $FSNAME any cli2mdt $SK_FLAVOR
5940                         set_rule $FSNAME any cli2ost $SK_FLAVOR
5941                         if $SK_SKIPFIRST; then
5942                                 export SK_SKIPFIRST=false
5943
5944                                 sleep 30
5945                                 do_nodes $CLIENTS \
5946                                          "lctl set_param osc.*.idle_connect=1"
5947                                 return
5948                         else
5949                                 wait_flavor cli2mdt $SK_FLAVOR
5950                                 wait_flavor cli2ost $SK_FLAVOR
5951                         fi
5952                 else
5953                         set_flavor_all $SEC
5954                 fi
5955                 sleep $((TIMEOUT + 5))
5956         else
5957                 sleep 5
5958         fi
5959 }
5960
5961 mounted_lustre_filesystems() {
5962         awk '($3 ~ "lustre" && $1 ~ ":") { print $2 }' /proc/mounts
5963 }
5964
5965 init_facet_vars () {
5966         [ -n "$CLIENTONLY" ] && return 0
5967         local facet=$1
5968         shift
5969         local device=$1
5970
5971         shift
5972
5973         eval export ${facet}_dev=${device}
5974         eval export ${facet}_opt=\"$*\"
5975
5976         local dev=${facet}_dev
5977
5978         # We need to loop for the label
5979         # in case its not initialized yet.
5980         for wait_time in {0,1,3,5,10}; do
5981
5982                 if [ $wait_time -gt 0 ]; then
5983                         echo "${!dev} not yet initialized,"\
5984                                 "waiting ${wait_time} seconds."
5985                         sleep $wait_time
5986                 fi
5987
5988                 local label=$(devicelabel ${facet} ${!dev})
5989
5990                 # Check to make sure the label does
5991                 # not include ffff at the end of the label.
5992                 # This indicates it has not been initialized yet.
5993
5994                 if [[ $label =~ [f|F]{4}$ ]]; then
5995                         # label is not initialized, unset the result
5996                         # and either try again or fail
5997                         unset label
5998                 else
5999                         break
6000                 fi
6001         done
6002
6003         [ -z "$label" ] && echo no label for ${!dev} && exit 1
6004
6005         eval export ${facet}_svc=${label}
6006
6007         local varname=${facet}failover_HOST
6008         if [ -z "${!varname}" ]; then
6009                 local temp
6010                 if combined_mgs_mds && [ $facet == "mgs" ] &&
6011                    [ -n "$mds1failover_HOST" ]; then
6012                         temp=$mds1failover_HOST
6013                 else
6014                         temp=$(facet_host $facet)
6015                 fi
6016                 eval export $varname=$temp
6017         fi
6018
6019         varname=${facet}_HOST
6020         if [ -z "${!varname}" ]; then
6021                 eval export $varname=$(facet_host $facet)
6022         fi
6023
6024         # ${facet}failover_dev is set in cfg file
6025         varname=${facet}failover_dev
6026         if [ -n "${!varname}" ] ; then
6027                 eval export ${facet}failover_dev=${!varname}
6028         else
6029                 eval export ${facet}failover_dev=$device
6030         fi
6031
6032         # get mount point of already mounted device
6033         # is facet_dev is already mounted then use the real
6034         #  mount point of this facet; otherwise use $(facet_mntpt $facet)
6035         # i.e. ${facet}_MOUNT if specified by user or default
6036         local mntpt=$(do_facet ${facet} cat /proc/mounts | \
6037                         awk '"'${!dev}'" == $1 && $3 == "lustre" { print $2 }')
6038         if [ -z $mntpt ]; then
6039                 mntpt=$(facet_mntpt $facet)
6040         fi
6041         eval export ${facet}_MOUNT=$mntpt
6042 }
6043
6044 init_facets_vars () {
6045         local DEVNAME
6046
6047         if ! remote_mds_nodsh; then
6048                 for num in $(seq $MDSCOUNT); do
6049                         DEVNAME=$(mdsdevname $num)
6050                         init_facet_vars mds$num $DEVNAME $MDS_MOUNT_OPTS
6051                 done
6052         fi
6053
6054         init_facet_vars mgs $(mgsdevname) $MGS_MOUNT_OPTS
6055
6056         if ! remote_ost_nodsh; then
6057                 for num in $(seq $OSTCOUNT); do
6058                         DEVNAME=$(ostdevname $num)
6059                         init_facet_vars ost$num $DEVNAME $OST_MOUNT_OPTS
6060                 done
6061         fi
6062 }
6063
6064 init_facets_vars_simple () {
6065         local devname
6066
6067         if ! remote_mds_nodsh; then
6068                 for num in $(seq $MDSCOUNT); do
6069                         devname=$(mdsdevname $num)
6070                         eval export mds${num}_dev=${devname}
6071                         eval export mds${num}_opt=\"${MDS_MOUNT_OPTS}\"
6072                 done
6073         fi
6074
6075         if ! combined_mgs_mds ; then
6076                 eval export mgs_dev=$(mgsdevname)
6077                 eval export mgs_opt=\"${MGS_MOUNT_OPTS}\"
6078         fi
6079
6080         if ! remote_ost_nodsh; then
6081                 for num in $(seq $OSTCOUNT); do
6082                         devname=$(ostdevname $num)
6083                         eval export ost${num}_dev=${devname}
6084                         eval export ost${num}_opt=\"${OST_MOUNT_OPTS}\"
6085                 done
6086         fi
6087 }
6088
6089 osc_ensure_active () {
6090         local facet=$1
6091         local timeout=$2
6092         local period=0
6093
6094         while [ $period -lt $timeout ]; do
6095                 count=$(do_facet $facet "lctl dl | grep ' IN osc ' 2>/dev/null | wc -l")
6096                 if [ $count -eq 0 ]; then
6097                         break
6098                 fi
6099
6100                 echo "$count OST inactive, wait $period seconds, and try again"
6101                 sleep 3
6102                 period=$((period+3))
6103         done
6104
6105         [ $period -lt $timeout ] ||
6106                 log "$count OST are inactive after $timeout seconds, give up"
6107 }
6108
6109 set_conf_param_and_check() {
6110         local myfacet=$1
6111         local TEST=$2
6112         local PARAM=$3
6113         local ORIG=$(do_facet $myfacet "$TEST")
6114         if [ $# -gt 3 ]; then
6115                 local FINAL=$4
6116         else
6117                 local -i FINAL
6118                 FINAL=$((ORIG + 5))
6119         fi
6120         echo "Setting $PARAM from $ORIG to $FINAL"
6121         do_facet mgs "$LCTL conf_param $PARAM='$FINAL'" ||
6122                 error "conf_param $PARAM failed"
6123
6124         wait_update_facet $myfacet "$TEST" "$FINAL" ||
6125                 error "check $PARAM failed!"
6126 }
6127
6128 set_persistent_param() {
6129         local myfacet=$1
6130         local test_param=$2
6131         local param=$3
6132         local orig=$(do_facet $myfacet "$LCTL get_param -n $test_param")
6133
6134         if [ $# -gt 3 ]; then
6135                 local final=$4
6136         else
6137                 local -i final
6138                 final=$((orig + 5))
6139         fi
6140
6141         if [[ $PERM_CMD == *"set_param -P"* ]]; then
6142                 echo "Setting $test_param from $orig to $final"
6143                 do_facet mgs "$PERM_CMD $test_param='$final'" ||
6144                         error "$PERM_CMD $test_param failed"
6145         else
6146                 echo "Setting $param from $orig to $final"
6147                 do_facet mgs "$PERM_CMD $param='$final'" ||
6148                         error "$PERM_CMD $param failed"
6149         fi
6150 }
6151
6152 set_persistent_param_and_check() {
6153         local myfacet=$1
6154         local test_param=$2
6155         local param=$3
6156         local orig=$(do_facet $myfacet "$LCTL get_param -n $test_param")
6157
6158         if [ $# -gt 3 ]; then
6159                 local final=$4
6160         else
6161                 local -i final
6162                 final=$((orig + 5))
6163         fi
6164
6165         set_persistent_param $myfacet $test_param $param "$final"
6166
6167         wait_update_facet $myfacet "$LCTL get_param -n $test_param" "$final" ||
6168                 error "check $param failed!"
6169 }
6170
6171 init_param_vars () {
6172         TIMEOUT=$(lctl get_param -n timeout)
6173         TIMEOUT=${TIMEOUT:-20}
6174
6175         if [ -n "$arg1" ]; then
6176                 [ "$arg1" = "server_only" ] && return
6177         fi
6178
6179         remote_mds_nodsh && log "Using TIMEOUT=$TIMEOUT" && return 0
6180
6181         TIMEOUT=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
6182         log "Using TIMEOUT=$TIMEOUT"
6183
6184         # tune down to speed up testing on (usually) small setups
6185         local mgc_timeout=/sys/module/mgc/parameters/mgc_requeue_timeout_min
6186         do_nodes $(comma_list $(nodes_list)) \
6187                 "[ -f $mgc_timeout ] && echo 1 > $mgc_timeout; exit 0"
6188
6189         osc_ensure_active $SINGLEMDS $TIMEOUT
6190         osc_ensure_active client $TIMEOUT
6191         $LCTL set_param osc.*.idle_timeout=debug
6192
6193         if [ -n "$(lctl get_param -n mdc.*.connect_flags|grep jobstats)" ]; then
6194                 local current_jobid_var=$($LCTL get_param -n jobid_var)
6195
6196                 if [ $JOBID_VAR = "existing" ]; then
6197                         echo "keeping jobstats as $current_jobid_var"
6198                 elif [ $current_jobid_var != $JOBID_VAR ]; then
6199                         echo "setting jobstats to $JOBID_VAR"
6200
6201                         set_persistent_param_and_check client \
6202                                 "jobid_var" "$FSNAME.sys.jobid_var" $JOBID_VAR
6203                 fi
6204         else
6205                 echo "jobstats not supported by server"
6206         fi
6207
6208         if [ $QUOTA_AUTO -ne 0 ]; then
6209                 if [ "$ENABLE_QUOTA" ]; then
6210                         echo "enable quota as required"
6211                         setup_quota $MOUNT || return 2
6212                 else
6213                         echo "disable quota as required"
6214                         # $LFS quotaoff -ug $MOUNT > /dev/null 2>&1
6215                 fi
6216         fi
6217
6218         (( MDS1_VERSION <= $(version_code 2.13.52) )) ||
6219                 do_facet mgs "$LCTL set_param -P lod.*.mdt_hash=crush"
6220         return 0
6221 }
6222
6223 nfs_client_mode () {
6224         if [ "$NFSCLIENT" ]; then
6225                 echo "NFSCLIENT mode: setup, cleanup, check config skipped"
6226                 local clients=$CLIENTS
6227
6228                 [ -z $clients ] && clients=$(hostname)
6229
6230                 # FIXME: remove hostname when 19215 fixed
6231                 do_nodes $clients "echo \\\$(hostname); grep ' '$MOUNT' ' /proc/mounts"
6232                 declare -a nfsexport=(`grep ' '$MOUNT' ' /proc/mounts |
6233                         awk '{print $1}' | awk -F: '{print $1 " "  $2}'`)
6234                 if [[ ${#nfsexport[@]} -eq 0 ]]; then
6235                         error_exit NFSCLIENT=$NFSCLIENT mode, but no NFS export found!
6236                 fi
6237                 do_nodes ${nfsexport[0]} "echo \\\$(hostname); df -T  ${nfsexport[1]}"
6238                 return
6239         fi
6240         return 1
6241 }
6242
6243 cifs_client_mode () {
6244         [ x$CIFSCLIENT = xyes ] &&
6245                 echo "CIFSCLIENT=$CIFSCLIENT mode: setup, cleanup, check config skipped"
6246 }
6247
6248 check_config_client () {
6249         local mntpt=$1
6250         local mounted=$(mount | grep " $mntpt ")
6251
6252         if [ -n "$CLIENTONLY" ]; then
6253                 # bug 18021
6254                 # CLIENTONLY should not depend on *_HOST settings
6255                 local mgc=$($LCTL device_list | awk '/MGC/ {print $4}')
6256                 # in theory someone could create a new,
6257                 # client-only config file that assumed lustre was already
6258                 # configured and didn't set the MGSNID. If MGSNID is not set,
6259                 # then we should use the mgs nid currently being used
6260                 # as the default value. bug 18021
6261                 [[ x$MGSNID = x ]] &&
6262                 MGSNID=${mgc//MGC/}
6263
6264                 if [[ x$mgc != xMGC$MGSNID ]]; then
6265                         if [ "$mgs_HOST" ]; then
6266                                 local mgc_ip=$(ping -q -c1 -w1 $mgs_HOST |
6267                                         grep PING | awk '{print $3}' |
6268                                         sed -e "s/(//g" -e "s/)//g")
6269
6270                                 # [[ x$mgc = xMGC$mgc_ip@$NETTYPE ]] ||
6271                                 # error_exit "MGSNID=$MGSNID, mounted: $mounted, MGC : $mgc"
6272                         fi
6273                 fi
6274                 return 0
6275         fi
6276
6277         echo Checking config lustre mounted on $mntpt
6278         local mgshost=$(mount | grep " $mntpt " | awk -F@ '{print $1}')
6279         mgshost=$(echo $mgshost | awk -F: '{print $1}')
6280
6281 }
6282
6283 check_config_clients () {
6284         local clients=${CLIENTS:-$HOSTNAME}
6285         local mntpt=$1
6286
6287         nfs_client_mode && return
6288         cifs_client_mode && return
6289
6290         do_rpc_nodes "$clients" check_config_client $mntpt
6291
6292         sanity_mount_check || error "environments are insane!"
6293 }
6294
6295 check_timeout () {
6296         local mdstimeout=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
6297         local cltimeout=$(lctl get_param -n timeout)
6298         if [ $mdstimeout -ne $TIMEOUT ] || [ $mdstimeout -ne $cltimeout ]; then
6299                 error "timeouts are wrong! mds: $mdstimeout, client: $cltimeout, TIMEOUT=$TIMEOUT"
6300                 return 1
6301         fi
6302 }
6303
6304 is_mounted () {
6305         local mntpt=$1
6306         [ -z $mntpt ] && return 1
6307         local mounted=$(mounted_lustre_filesystems)
6308
6309         echo $mounted' ' | grep -w -q $mntpt' '
6310 }
6311
6312 create_pools () {
6313         local pool=$1
6314         local ostsn=${2:-$OSTCOUNT}
6315         local npools=${FS_NPOOLS:-$((OSTCOUNT / ostsn))}
6316         local n
6317
6318         echo ostsn=$ostsn npools=$npools
6319         if [[ $ostsn -gt $OSTCOUNT ]];  then
6320                 echo "request to use $ostsn OSTs in the pool, \
6321                         using max available OSTCOUNT=$OSTCOUNT"
6322                 ostsn=$OSTCOUNT
6323         fi
6324         for (( n=0; n < $npools; n++ )); do
6325                 p=${pool}$n
6326                 if ! $DELETE_OLD_POOLS; then
6327                         log "request to not delete old pools: $FSNAME.$p exist?"
6328                         if ! check_pool_not_exist $FSNAME.$p; then
6329                                 echo "Using existing $FSNAME.$p"
6330                                 $LCTL pool_list $FSNAME.$p
6331                                 continue
6332                         fi
6333                 fi
6334                 create_pool $FSNAME.$p $KEEP_POOLS ||
6335                         error "create_pool $FSNAME.$p failed"
6336
6337                 local first=$(( (n * ostsn) % OSTCOUNT ))
6338                 local last=$(( (first + ostsn - 1) % OSTCOUNT ))
6339                 if [[ $first -le $last ]]; then
6340                         pool_add_targets $p $first $last ||
6341                                 error "pool_add_targets $p $first $last failed"
6342                 else
6343                         pool_add_targets $p $first $(( OSTCOUNT - 1 )) ||
6344                                 error "pool_add_targets $p $first \
6345                                         $(( OSTCOUNT - 1 )) failed"
6346                         pool_add_targets $p 0 $last ||
6347                                 error "pool_add_targets $p 0 $last failed"
6348                 fi
6349         done
6350 }
6351
6352 set_pools_quota () {
6353         local u
6354         local o
6355         local p
6356         local i
6357         local j
6358
6359         [[ $ENABLE_QUOTA ]] || error "Required Pool Quotas: \
6360                 $POOLS_QUOTA_USERS_SET, but ENABLE_QUOTA not set!"
6361
6362         # POOLS_QUOTA_USERS_SET=
6363         #              "quota15_1:20M          -- for all of the found pools
6364         #               quota15_2:1G:gpool0
6365         #               quota15_3              -- for global limit only
6366         #               quota15_4:200M:gpool0
6367         #               quota15_4:200M:gpool1"
6368
6369         declare -a pq_userset=(${POOLS_QUOTA_USERS_SET="mpiuser"})
6370         declare -a pq_users
6371         declare -A pq_limits
6372
6373         for ((i=0; i<${#pq_userset[@]}; i++)); do
6374                 u=${pq_userset[i]%%:*}
6375                 o=""
6376                 # user gets no pool limits if
6377                 # POOLS_QUOTA_USERS_SET does not specify it
6378                 [[ ${pq_userset[i]} =~ : ]] && o=${pq_userset[i]##$u:}
6379                 pq_limits[$u]+=" $o"
6380         done
6381         pq_users=(${!pq_limits[@]})
6382
6383         declare -a opts
6384         local pool
6385
6386         for ((i=0; i<${#pq_users[@]}; i++)); do
6387                 u=${pq_users[i]}
6388                 # set to max limit (_u64)
6389                 $LFS setquota -u $u -B $((2**24 - 1))T $DIR
6390                 opts=(${pq_limits[$u]})
6391                 for ((j=0; j<${#opts[@]}; j++)); do
6392                         p=${opts[j]##*:}
6393                         o=${opts[j]%%:*}
6394                         # Set limit for all existing pools if
6395                         # no pool specified
6396                         if [ $p == $o ];  then
6397                                 p=$(list_pool $FSNAME | sed "s/$FSNAME.//")
6398                                 echo "No pool specified for $u,
6399                                         set limit $o for all existing pools"
6400                         fi
6401                         for pool in $p; do
6402                                 $LFS setquota -u $u -B $o --pool $pool $DIR ||
6403                                         error "setquota -u $u -B $o \
6404                                                 --pool $pool failed"
6405                         done
6406                 done
6407                 $LFS quota -uv $u --pool  $DIR
6408         done
6409 }
6410
6411 do_check_and_setup_lustre() {
6412         # If auster does not want us to setup, then don't.
6413         ! ${do_setup} && return
6414
6415         log "=== $TESTSUITE: start setup $(date +'%H:%M:%S (%s)') ==="
6416
6417         sanitize_parameters
6418         nfs_client_mode && return
6419         cifs_client_mode && return
6420
6421         local MOUNTED=$(mounted_lustre_filesystems)
6422
6423         local do_check=true
6424         # 1.
6425         # both MOUNT and MOUNT2 are not mounted
6426         if ! is_mounted $MOUNT && ! is_mounted $MOUNT2; then
6427                 [ "$REFORMAT" = "yes" ] && CLEANUP_DM_DEV=true formatall
6428                 # setupall mounts both MOUNT and MOUNT2 (if MOUNT_2 is set)
6429                 setupall
6430                 is_mounted $MOUNT || error "NAME=$NAME not mounted"
6431                 export I_MOUNTED=yes
6432                 do_check=false
6433         # 2.
6434         # MOUNT2 is mounted
6435         elif is_mounted $MOUNT2; then
6436                 # 3.
6437                 # MOUNT2 is mounted, while MOUNT_2 is not set
6438                 if ! [ "$MOUNT_2" ]; then
6439                         cleanup_mount $MOUNT2
6440                         export I_UMOUNTED2=yes
6441
6442                 # 4.
6443                 # MOUNT2 is mounted, MOUNT_2 is set
6444                 else
6445                         # FIXME: what to do if check_config failed?
6446                         # i.e. if:
6447                         # 1) remote client has mounted other Lustre fs ?
6448                         # 2) it has insane env ?
6449                         # try to umount MOUNT2 on all clients and mount again:
6450                         if ! check_config_clients $MOUNT2; then
6451                                 cleanup_mount $MOUNT2
6452                                 restore_mount $MOUNT2
6453                                 export I_MOUNTED2=yes
6454                         fi
6455                 fi
6456         # 5.
6457         # MOUNT is mounted MOUNT2 is not mounted
6458         elif [ "$MOUNT_2" ]; then
6459                 restore_mount $MOUNT2
6460                 export I_MOUNTED2=yes
6461         fi
6462
6463         if $do_check; then
6464                 # FIXME: what to do if check_config failed?
6465                 # i.e. if:
6466                 # 1) remote client has mounted other Lustre fs?
6467                 # 2) lustre is mounted on remote_clients atall ?
6468                 check_config_clients $MOUNT
6469                 init_facets_vars
6470                 init_param_vars
6471
6472                 set_default_debug_nodes $(comma_list $(nodes_list))
6473                 set_params_clients
6474         fi
6475
6476         if [ -z "$CLIENTONLY" -a $(lower $OSD_TRACK_DECLARES_LBUG) == 'yes' ]; then
6477                 local facets=""
6478                 [ "$(facet_fstype ost1)" = "ldiskfs" ] &&
6479                         facets="$(get_facets OST)"
6480                 [ "$(facet_fstype mds1)" = "ldiskfs" ] &&
6481                         facets="$facets,$(get_facets MDS)"
6482                 [ "$(facet_fstype mgs)" = "ldiskfs" ] &&
6483                         facets="$facets,mgs"
6484                 local nodes="$(facets_hosts ${facets})"
6485                 if [ -n "$nodes" ] ; then
6486                         do_nodes $nodes "$LCTL set_param \
6487                                  osd-ldiskfs.track_declares_assert=1 || true"
6488                 fi
6489         fi
6490
6491         if [ -n "$fs_STRIPEPARAMS" ]; then
6492                 setstripe_getstripe $MOUNT $fs_STRIPEPARAMS
6493         fi
6494
6495         if $GSS_SK; then
6496                 set_flavor_all null
6497         elif $GSS; then
6498                 set_flavor_all $SEC
6499         fi
6500
6501         if $DELETE_OLD_POOLS; then
6502                 destroy_all_pools
6503         fi
6504
6505         if [[ -n "$FS_POOL" ]]; then
6506                 create_pools $FS_POOL $FS_POOL_NOSTS
6507         fi
6508
6509         if [[ -n "$POOLS_QUOTA_USERS_SET" ]]; then
6510                 set_pools_quota
6511         fi
6512
6513         # set tunable parameters passed to test environment
6514         set_params_clients
6515         set_params_mdts
6516         set_params_osts
6517
6518         TESTNAME="start setup" check_dmesg_for_errors ||
6519                 TESTNAME="test_setup" error "Error in dmesg detected"
6520
6521         log "=== $TESTSUITE: finish setup $(date +'%H:%M:%S (%s)') ==="
6522
6523         if [[ "$ONLY" == "setup" ]]; then
6524                 exit 0
6525         fi
6526 }
6527
6528 check_and_setup_lustre() {
6529         local start_stamp=$(date +%s)
6530         local saved_umask=$(umask)
6531         local log=$TESTLOG_PREFIX.test_setup.test_log.$(hostname -s).log
6532         local status='PASS'
6533         local stop_stamp=0
6534         local duration=0
6535         local error=''
6536         local rc=0
6537
6538         umask 0022
6539
6540         log_sub_test_begin test_setup
6541
6542         if ! do_check_and_setup_lustre 2>&1 > >(tee -i $log); then
6543                 error=$(tail -1 $log)
6544                 status='FAIL'
6545                 rc=1
6546         fi
6547
6548         stop_stamp=$(date +%s)
6549         duration=$((stop_stamp - start_stamp))
6550
6551         log_sub_test_end "$status" "$duration" "$rc" "$error"
6552
6553         umask $saved_umask
6554
6555         return $rc
6556 }
6557
6558 restore_mount () {
6559         local clients=${CLIENTS:-$HOSTNAME}
6560         local mntpt=$1
6561
6562         zconf_mount_clients $clients $mntpt
6563 }
6564
6565 cleanup_mount () {
6566         local clients=${CLIENTS:-$HOSTNAME}
6567         local mntpt=$1
6568
6569         zconf_umount_clients $clients $mntpt
6570 }
6571
6572 cleanup_and_setup_lustre() {
6573         if [[ "$ONLY" == "cleanup" ]] || grep -q "$MOUNT" /proc/mounts; then
6574                 lctl set_param debug=0 || true
6575                 cleanupall
6576
6577                 if [[ "$ONLY" == "cleanup" ]]; then
6578                         exit 0
6579                 fi
6580         fi
6581
6582         do_check_and_setup_lustre
6583 }
6584
6585 # Run e2fsck on MDT or OST device.
6586 run_e2fsck() {
6587         local node=$1
6588         local target_dev=$2
6589         local extra_opts=$3
6590         local cmd="$E2FSCK -d -v -t -t -f $extra_opts $target_dev"
6591         local log=$TMP/e2fsck.log
6592         local rc=0
6593
6594         # turn on pfsck if it is supported
6595         do_node $node $E2FSCK -h 2>&1 | grep -qw -- -m && cmd+=" -m8"
6596         echo $cmd
6597         do_node $node $cmd 2>&1 | tee $log
6598         rc=${PIPESTATUS[0]}
6599         if [ -n "$(grep "DNE mode isn't supported" $log)" ]; then
6600                 rm -f $log
6601                 if [ $MDSCOUNT -gt 1 ]; then
6602                         skip_noexit "DNE mode isn't supported!"
6603                         cleanupall
6604                         exit_status
6605                 else
6606                         error "It's not DNE mode."
6607                 fi
6608         fi
6609         rm -f $log
6610
6611         [ $rc -le $FSCK_MAX_ERR ] ||
6612                 error "$cmd returned $rc, should be <= $FSCK_MAX_ERR"
6613
6614         return 0
6615 }
6616
6617 #
6618 # Run resize2fs on MDT or OST device.
6619 #
6620 run_resize2fs() {
6621         local facet=$1
6622         local device=$2
6623         local size=$3
6624         shift 3
6625         local opts="$@"
6626
6627         do_facet $facet "$RESIZE2FS $opts $device $size"
6628 }
6629
6630 # verify a directory is shared among nodes.
6631 check_shared_dir() {
6632         local dir=$1
6633         local list=${2:-$(comma_list $(nodes_list))}
6634
6635         [ -z "$dir" ] && return 1
6636         do_rpc_nodes "$list" check_logdir $dir
6637         check_write_access $dir "$list" || return 1
6638         return 0
6639 }
6640
6641 run_lfsck() {
6642         do_nodes $(tgts_nodes) $LCTL set_param printk=+lfsck
6643         do_facet $SINGLEMDS "$LCTL lfsck_start -M $FSNAME-MDT0000 -r -A -t all"
6644
6645         for k in $(seq $MDSCOUNT); do
6646                 # wait up to 10+1 minutes for LFSCK to complete
6647                 wait_update_facet --verbose mds${k} "$LCTL get_param -n \
6648                         mdd.$(facet_svc mds${k}).lfsck_layout |
6649                         awk '/^status/ { print \\\$2 }'" "completed" 600 ||
6650                         error "MDS${k} layout isn't the expected 'completed'"
6651                 wait_update_facet --verbose mds${k} "$LCTL get_param -n \
6652                         mdd.$(facet_svc mds${k}).lfsck_namespace |
6653                         awk '/^status/ { print \\\$2 }'" "completed" 60 ||
6654                         error "MDS${k} namespace isn't the expected 'completed'"
6655         done
6656         local repaired=$(do_nodes $(tgts_nodes) \
6657                          "$LCTL get_param -n *.$FSNAME-*.lfsck_*" |
6658                          awk '/repaired/ { print $2 }' | calc_sum)
6659         (( repaired == 0 )) ||
6660                 error "lfsck repaired $rep_mdt MDT and $rep_ost OST errors"
6661 }
6662
6663 dump_file_contents() {
6664         local nodes=$1
6665         local dir=$2
6666         local logname=$3
6667         local node
6668
6669         if [ -z "$nodes" -o -z "$dir" -o -z "$logname" ]; then
6670                 error_noexit false \
6671                         "Invalid parameters for dump_file_contents()"
6672                 return 1
6673         fi
6674         for node in ${nodes//,/ }; do
6675                 do_node $node "for i in \\\$(find $dir -type f); do
6676                                 echo ====\\\${i}=======================;
6677                                 cat \\\${i};
6678                                 done" >> ${logname}.${node}.log
6679         done
6680 }
6681
6682 dump_command_output() {
6683         local nodes=$1
6684         local cmd=$2
6685         local logname=$3
6686         local node
6687
6688         if [ -z "$nodes" -o -z "$cmd" -o -z "$logname" ]; then
6689                 error_noexit false \
6690                         "Invalid parameters for dump_command_output()"
6691                 return 1
6692         fi
6693
6694         for node in ${nodes//,/ }; do
6695                 do_node $node "echo ====${cmd}=======================;
6696                                 $cmd" >> ${logname}.${node}.log
6697         done
6698 }
6699
6700 log_zfs_info() {
6701         local logname=$1
6702
6703         # dump file contents from /proc/spl in case of zfs test
6704         if [ "$(facet_fstype ost1)" = "zfs" ]; then
6705                 dump_file_contents "$(osts_nodes)" "/proc/spl" "${logname}"
6706                 dump_command_output \
6707                         "$(osts_nodes)" "zpool events -v" "${logname}"
6708         fi
6709
6710         if [ "$(facet_fstype $SINGLEMDS)" = "zfs" ]; then
6711                 dump_file_contents "$(mdts_nodes)" "/proc/spl" "${logname}"
6712                 dump_command_output \
6713                         "$(mdts_nodes)" "zpool events -v" "${logname}"
6714         fi
6715 }
6716
6717 do_check_and_cleanup_lustre() {
6718         log "=== $TESTSUITE: start cleanup $(date +'%H:%M:%S (%s)') ==="
6719
6720         if [[ "$LFSCK_ALWAYS" == "yes" && "$TESTSUITE" != "sanity-lfsck" && \
6721               "$TESTSUITE" != "sanity-scrub" ]]; then
6722                 run_lfsck
6723         fi
6724
6725         # FIXME: The cleanup takes too long, times out...
6726         if [[ "$FSTYPE" == "wbcfs" ]]; then
6727                 DO_CLEANUP=false
6728         fi
6729
6730         if is_mounted $MOUNT; then
6731                 if $DO_CLEANUP; then
6732                         [[ -n "$DIR" ]] && rm -rf $DIR/[Rdfs][0-9]* ||
6733                                 error "remove sub-test dirs failed"
6734                 else
6735                         echo "skip cleanup"
6736                 fi
6737                 [[ -n "$ENABLE_QUOTA" ]] && restore_quota || true
6738         fi
6739
6740         if [[ "$I_UMOUNTED2" == "yes" ]]; then
6741                 restore_mount $MOUNT2 || error "restore $MOUNT2 failed"
6742         fi
6743
6744         if [[ "$I_MOUNTED2" == "yes" ]]; then
6745                 cleanup_mount $MOUNT2
6746         fi
6747
6748         if [[ "$I_MOUNTED" == "yes" ]] && ! $AUSTER_CLEANUP; then
6749                 cleanupall -f || error "cleanup failed"
6750                 unset I_MOUNTED
6751         fi
6752
6753         TESTNAME="start cleanup" check_dmesg_for_errors ||
6754                 TESTNAME="test_cleanup" error "Error in dmesg detected"
6755
6756         log "=== $TESTSUITE: finish cleanup $(date +'%H:%M:%S (%s)') ==="
6757 }
6758
6759 check_and_cleanup_lustre() {
6760         local start_stamp=$(date +%s)
6761         local saved_umask=$(umask)
6762         local log=$TESTLOG_PREFIX.test_cleanup.test_log.$(hostname -s).log
6763         local status='PASS'
6764         local stop_stamp=0
6765         local duration=0
6766         local error=''
6767         local rc=0
6768
6769         umask 0022
6770
6771         log_sub_test_begin test_cleanup
6772
6773         if ! do_check_and_cleanup_lustre 2>&1 > >(tee -i $log); then
6774                 error=$(tail -1 $log)
6775                 status='FAIL'
6776                 rc=1
6777         fi
6778
6779         stop_stamp=$(date +%s)
6780         duration=$((stop_stamp - start_stamp))
6781
6782         log_sub_test_end "$status" "$duration" "$rc" "$error"
6783
6784         umask $saved_umask
6785
6786         return $rc
6787 }
6788
6789 #######
6790 # General functions
6791
6792 wait_for_function () {
6793         local quiet=""
6794
6795         # suppress fn both stderr and stdout
6796         if [ "$1" = "--quiet" ]; then
6797                 shift
6798                 quiet=" > /dev/null 2>&1"
6799         fi
6800
6801         local fn=$1
6802         local max=${2:-900}
6803         local sleep=${3:-5}
6804
6805         local wait=0
6806
6807         while true; do
6808
6809                 eval $fn $quiet && return 0
6810
6811                 [ $wait -lt $max ] || return 1
6812                 echo waiting $fn, $((max - wait)) secs left ...
6813                 wait=$((wait + sleep))
6814                 [ $wait -gt $max ] && ((sleep -= wait - max))
6815                 sleep $sleep
6816         done
6817 }
6818
6819 check_network() {
6820         local host=$1
6821         local max=$2
6822         local sleep=${3:-5}
6823
6824         [ "$host" = "$HOSTNAME" ] && return 0
6825
6826         if ! wait_for_function --quiet "ping -c 1 -w 3 $host" $max $sleep; then
6827                 echo "$(date +'%H:%M:%S (%s)') waited for $host network ${max}s"
6828                 exit 1
6829         fi
6830 }
6831
6832 no_dsh() {
6833         shift
6834         eval "$@"
6835 }
6836
6837 # Convert a space-delimited list to a comma-delimited list.  If the input is
6838 # only whitespace, ensure the output is empty (i.e. "") so [ -n $list ] works
6839 comma_list() {
6840         # echo is used to convert newlines to spaces, since it doesn't
6841         # introduce a trailing space as using "tr '\n' ' '" does
6842         echo $(tr -s ", " "\n" <<< $* | sort -b -u) | tr ' ' ','
6843 }
6844
6845 list_member () {
6846         local list=$1
6847         local item=$2
6848
6849         echo $list | grep -qw $item
6850 }
6851
6852 # list, excluded are the comma separated lists
6853 exclude_items_from_list () {
6854         local list=$1
6855         local excluded=$2
6856         local item
6857
6858         list=${list//,/ }
6859         for item in ${excluded//,/ }; do
6860                 list=$(echo " $list " | sed -re "s/\s+$item\s+/ /g")
6861         done
6862         echo $(comma_list $list)
6863 }
6864
6865 # list, expand  are the comma separated lists
6866 expand_list () {
6867         local list=${1//,/ }
6868         local expand=${2//,/ }
6869         local expanded=
6870
6871         expanded=$(for i in $list $expand; do echo $i; done | sort -u)
6872         echo $(comma_list $expanded)
6873 }
6874
6875 testslist_filter () {
6876         local script=$LUSTRE/tests/${TESTSUITE}.sh
6877
6878         [ -f $script ] || return 0
6879
6880         local start_at=$START_AT
6881         local stop_at=$STOP_AT
6882
6883         local var=${TESTSUITE//-/_}_START_AT
6884         [ x"${!var}" != x ] && start_at=${!var}
6885         var=${TESTSUITE//-/_}_STOP_AT
6886         [ x"${!var}" != x ] && stop_at=${!var}
6887
6888         sed -n 's/^test_\([^ (]*\).*/\1/p' $script |
6889         awk ' BEGIN { if ("'${start_at:-0}'" != 0) flag = 1 }
6890             /^'${start_at}'$/ {flag = 0}
6891             {if (flag == 1) print $0}
6892             /^'${stop_at}'$/ { flag = 1 }'
6893 }
6894
6895 absolute_path() {
6896         (cd `dirname $1`; echo $PWD/`basename $1`)
6897 }
6898
6899 get_facets () {
6900         local types=${*:-"OST MDS MGS"}
6901
6902         local list=""
6903
6904         for entry in $types; do
6905                 local name=$(echo $entry | tr "[:upper:]" "[:lower:]")
6906                 local type=$(echo $entry | tr "[:lower:]" "[:upper:]")
6907
6908                 case $type in
6909                         MGS ) list="$list $name";;
6910                         MDS|OST|AGT ) local count=${type}COUNT
6911                                 for ((i=1; i<=${!count}; i++)) do
6912                                         list="$list ${name}$i"
6913                                 done;;
6914                         * ) error "Invalid facet type"
6915                                 exit 1;;
6916                 esac
6917         done
6918         echo $(comma_list $list)
6919 }
6920
6921 ##################################
6922 # Adaptive Timeouts funcs
6923
6924 at_is_enabled() {
6925         # only check mds, we assume at_max is the same on all nodes
6926         local at_max=$(do_facet $SINGLEMDS "lctl get_param -n at_max")
6927
6928         if [ $at_max -eq 0 ]; then
6929                 return 1
6930         else
6931                 return 0
6932         fi
6933 }
6934
6935 at_get() {
6936         local facet=$1
6937         local at=$2
6938
6939         # suppose that all ost-s have the same $at value set
6940         [ $facet != "ost" ] || facet=ost1
6941
6942         do_facet $facet "lctl get_param -n $at"
6943 }
6944
6945 at_max_get() {
6946         at_get $1 at_max
6947 }
6948
6949 at_max_set() {
6950         local at_max=$1
6951         shift
6952
6953         local facet
6954         local hosts
6955
6956         for facet in "$@"; do
6957                 if [ $facet == "ost" ]; then
6958                         facet=$(get_facets OST)
6959                 elif [ $facet == "mds" ]; then
6960                         facet=$(get_facets MDS)
6961                 fi
6962                 hosts=$(expand_list $hosts $(facets_hosts $facet))
6963         done
6964
6965         do_nodes $hosts lctl set_param at_max=$at_max
6966 }
6967
6968 at_min_get() {
6969         at_get $1 at_min
6970 }
6971
6972 at_min_set() {
6973         local at_min=$1
6974         shift
6975
6976         local facet
6977         local hosts
6978
6979         for facet in "$@"; do
6980                 if [ $facet == "ost" ]; then
6981                         facet=$(get_facets OST)
6982                 elif [ $facet == "mds" ]; then
6983                         facet=$(get_facets MDS)
6984                 fi
6985                 hosts=$(expand_list $hosts $(facets_hosts $facet))
6986         done
6987
6988         do_nodes $hosts lctl set_param at_min=$at_min
6989 }
6990
6991 ##################################
6992 # OBD_FAIL funcs
6993
6994 drop_request() {
6995 # OBD_FAIL_MDS_ALL_REQUEST_NET
6996         RC=0
6997         do_facet $SINGLEMDS lctl set_param fail_val=0 fail_loc=0x123
6998         do_facet client "$1" || RC=$?
6999         do_facet $SINGLEMDS lctl set_param fail_loc=0
7000         return $RC
7001 }
7002
7003 drop_reply() {
7004 # OBD_FAIL_MDS_ALL_REPLY_NET
7005         RC=0
7006         do_facet $SINGLEMDS $LCTL set_param fail_loc=0x122
7007         eval "$@" || RC=$?
7008         do_facet $SINGLEMDS $LCTL set_param fail_loc=0
7009         return $RC
7010 }
7011
7012 drop_reint_reply() {
7013 # OBD_FAIL_MDS_REINT_NET_REP
7014         RC=0
7015         do_facet $SINGLEMDS $LCTL set_param fail_loc=0x119
7016         eval "$@" || RC=$?
7017         do_facet $SINGLEMDS $LCTL set_param fail_loc=0
7018         return $RC
7019 }
7020
7021 drop_update_reply() {
7022         local index=$1
7023         shift 1
7024         local rc=0
7025
7026         # OBD_FAIL_OUT_UPDATE_NET_REP                   0x1701
7027         do_facet mds${index} $LCTL set_param fail_loc=0x1701
7028         do_facet client "$@" || rc=$?
7029         do_facet mds${index} $LCTL set_param fail_loc=0
7030
7031         return $rc
7032 }
7033
7034 pause_bulk() {
7035         local cmd=${1:-0}
7036         local timeout=${2:-0}
7037         local rc=0
7038
7039         # default is (obd_timeout / 4) if unspecified
7040         echo "timeout is $timeout"
7041         #define OBD_FAIL_OST_BRW_PAUSE_BULK             0x214
7042         do_facet ost1 $LCTL set_param fail_val=$timeout fail_loc=0x80000214
7043         do_facet client "$cmd" || rc=$?
7044         do_facet client "sync"
7045         do_facet ost1 $LCTL set_param fail_loc=0
7046
7047         return $rc
7048 }
7049
7050 drop_ldlm_cancel() {
7051         local tgts=$(tgts_nodes)
7052         local rc=0
7053
7054         #define OBD_FAIL_LDLM_CANCEL_NET                0x304
7055         do_nodes $tgts $LCTL set_param fail_loc=0x304
7056         do_facet client "$@" || rc=$?
7057         do_nodes $tgts $LCTL set_param fail_loc=0
7058
7059         return $rc
7060 }
7061
7062 drop_bl_callback_once() {
7063         local rc=0
7064         do_facet client lctl set_param ldlm.namespaces.*.early_lock_cancel=0
7065 #define OBD_FAIL_LDLM_BL_CALLBACK_NET                   0x305
7066         do_facet client lctl set_param fail_loc=0x80000305
7067         do_facet client "$@" || rc=$?
7068         do_facet client lctl set_param fail_loc=0
7069         do_facet client lctl set_param fail_val=0
7070         do_facet client lctl set_param ldlm.namespaces.*.early_lock_cancel=1
7071         return $rc
7072 }
7073
7074 drop_bl_callback() {
7075         rc=0
7076         do_facet client lctl set_param ldlm.namespaces.*.early_lock_cancel=0
7077 #define OBD_FAIL_LDLM_BL_CALLBACK_NET                   0x305
7078         do_facet client lctl set_param fail_loc=0x305
7079         do_facet client "$@" || rc=$?
7080         do_facet client lctl set_param fail_loc=0
7081         do_facet client lctl set_param fail_val=0
7082         do_facet client lctl set_param ldlm.namespaces.*.early_lock_cancel=1
7083         return $rc
7084 }
7085
7086 drop_mdt_ldlm_reply() {
7087 #define OBD_FAIL_MDS_LDLM_REPLY_NET     0x157
7088         RC=0
7089         local mdts=$(mdts_nodes)
7090
7091         do_nodes $mdts lctl set_param fail_loc=0x157
7092
7093         do_facet client "$@" || RC=$?
7094
7095         do_nodes $mdts lctl set_param fail_loc=0
7096         return $RC
7097 }
7098
7099 drop_mdt_ldlm_reply_once() {
7100 #define OBD_FAIL_MDS_LDLM_REPLY_NET     0x157
7101         RC=0
7102         local mdts=$(mdts_nodes)
7103
7104         do_nodes $mdts lctl set_param fail_loc=0x80000157
7105
7106         do_facet client "$@" || RC=$?
7107
7108         do_nodes $mdts lctl set_param fail_loc=0
7109         return $RC
7110 }
7111
7112 clear_failloc() {
7113         local facet=$1
7114         local pause=$2
7115
7116         sleep $pause
7117         echo "clearing fail_loc on $facet"
7118         do_facet $facet "lctl set_param fail_loc=0 2>/dev/null || true"
7119 }
7120
7121 set_nodes_failloc () {
7122         local fv=${3:-0}
7123         do_nodes $(comma_list $1)  lctl set_param fail_val=$fv fail_loc=$2
7124 }
7125
7126 # Print the total of the lock_unused_count across all namespaces containing the
7127 # given wildcard. If the namespace wildcard is omitted, all namespaces will be
7128 # matched.
7129 # Usage: total_unused_locks [namespace_wildcard]
7130 total_unused_locks() {
7131         $LCTL get_param -n "ldlm.namespaces.*$1*.lock_unused_count" | calc_sum
7132 }
7133
7134 # Print the total of the lock_count across all namespaces containing the given
7135 # wildcard. If the namespace wilcard is omitted, all namespaces will be matched.
7136 # Usage: total_used_locks [namespace_wildcard]
7137 total_used_locks() {
7138         $LCTL get_param -n "ldlm.namespaces.*$1*.lock_count" | calc_sum
7139 }
7140
7141 # Cancel lru locks across all namespaces containing the given wildcard. If the
7142 # wilcard is omitted, lru locks will be canceled across all namespaces.
7143 # Usage: cancel_lru_locks [namespace_wildcard]
7144 cancel_lru_locks() {
7145         #$LCTL mark "cancel_lru_locks $1 start"
7146         $LCTL set_param -t4 -n "ldlm.namespaces.*$1*.lru_size=clear"
7147         $LCTL get_param "ldlm.namespaces.*$1*.lock_unused_count" | grep -v '=0'
7148         #$LCTL mark "cancel_lru_locks $1 stop"
7149 }
7150
7151 default_lru_size()
7152 {
7153         local nr_cpu=$(grep -c "processor" /proc/cpuinfo)
7154
7155         echo $((100 * nr_cpu))
7156 }
7157
7158 lru_resize_enable()
7159 {
7160         $LCTL set_param -n ldlm.namespaces.*$1*.lru_size=0
7161 }
7162
7163 lru_resize_disable()
7164 {
7165         local dev=${1}
7166         local lru_size=${2:-$(default_lru_size)}
7167         local size_param="ldlm.namespaces.*$dev*.lru_size"
7168         local age_param="ldlm.namespaces.*$dev*.lru_max_age"
7169         local old_age=($($LCTL get_param -n $age_param))
7170         # can't save/restore lru_size since it reports the *current* lru count
7171
7172         echo "$size_param=0->$lru_size"
7173         echo "$age_param=$old_age->3900s"
7174
7175         # increase lru_max_age also, to prevent lock cancel due to age
7176         $LCTL set_param -n $size_param=$lru_size
7177         $LCTL set_param -n $age_param=3900s
7178         stack_trap "cancel_lru_locks $dev || true"
7179         stack_trap "lru_resize_enable $dev || true"
7180         stack_trap "$LCTL set_param -n $age_param=$old_age || true"
7181 }
7182
7183 flock_is_enabled()
7184 {
7185         local mountpath=${1:-$MOUNT}
7186         local RC=0
7187
7188         [ -z "$(mount | grep "$mountpath .*flock" | grep -v noflock)" ] && RC=1
7189         return $RC
7190 }
7191
7192 pgcache_empty() {
7193         local FILE
7194
7195         for FILE in `lctl get_param -N "llite.*.dump_page_cache"`; do
7196                 if [ `lctl get_param -n $FILE | wc -l` -gt 1 ]; then
7197                         echo there is still data in page cache $FILE ?
7198                         lctl get_param -n $FILE
7199                         return 1
7200                 fi
7201         done
7202         return 0
7203 }
7204
7205 debugsave() {
7206         DEBUGSAVE="$(lctl get_param -n debug)"
7207         DEBUGSAVE_SERVER=$(do_facet $SINGLEMDS "$LCTL get_param -n debug")
7208 }
7209
7210 debugrestore() {
7211         [ -n "$DEBUGSAVE" ] &&
7212                 do_nodes $CLIENTS $LCTL set_param -n debug=${DEBUGSAVE// /+} ||
7213                 true
7214         DEBUGSAVE=""
7215
7216         [ -n "$DEBUGSAVE_SERVER" ] &&
7217                 do_nodes $(comma_list $(all_server_nodes)) \
7218                          $LCTL set_param -n debug=${DEBUGSAVE_SERVER// /+} ||
7219                          true
7220         DEBUGSAVE_SERVER=""
7221 }
7222
7223 debug_size_save() {
7224         DEBUG_SIZE_SAVED="$(lctl get_param -n debug_mb)"
7225 }
7226
7227 debug_size_restore() {
7228         [ -n "$DEBUG_SIZE_SAVED" ] &&
7229                 do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE_SAVED"
7230         DEBUG_SIZE_SAVED=""
7231 }
7232
7233 start_full_debug_logging() {
7234         debugsave
7235         debug_size_save
7236
7237         local fulldebug=-1
7238         local debug_size=150
7239         local nodes=$(comma_list $(nodes_list))
7240
7241         do_nodes $nodes "$LCTL set_param debug=$fulldebug debug_mb=$debug_size"
7242 }
7243
7244 stop_full_debug_logging() {
7245         debug_size_restore
7246         debugrestore
7247 }
7248
7249 # prints bash call stack
7250 print_stack_trace() {
7251         local skip=${1:-1}
7252         echo "  Trace dump:"
7253         for (( i=$skip; i < ${#BASH_LINENO[*]} ; i++ )) ; do
7254                 local src=${BASH_SOURCE[$i]}
7255                 local lineno=${BASH_LINENO[$i-1]}
7256                 local funcname=${FUNCNAME[$i]}
7257                 echo "  = $src:$lineno:$funcname()"
7258         done
7259 }
7260
7261 report_error() {
7262         local TYPE=${TYPE:-"FAIL"}
7263
7264         local dump=true
7265         # do not dump logs if $1=false
7266         if [ "x$1" = "xfalse" ]; then
7267                 shift
7268                 dump=false
7269         fi
7270
7271         log " ${TESTSUITE} ${TESTNAME}: @@@@@@ ${TYPE}: $* "
7272         (print_stack_trace 2) >&2
7273         mkdir -p $LOGDIR
7274         # We need to dump the logs on all nodes
7275         if $dump; then
7276                 gather_logs $(comma_list $(nodes_list))
7277         fi
7278
7279         debugrestore
7280         [ "$TESTSUITELOG" ] &&
7281                 echo "$TESTSUITE: $TYPE: $TESTNAME $*" >> $TESTSUITELOG
7282         if [ -z "$*" ]; then
7283                 echo "error() without useful message, please fix" > $LOGDIR/err
7284         else
7285                 if [[ `echo $TYPE | grep ^IGNORE` ]]; then
7286                         echo "$@" > $LOGDIR/ignore
7287                 else
7288                         echo "$@" > $LOGDIR/err
7289                 fi
7290         fi
7291
7292         # cleanup the env for failed tests
7293         reset_fail_loc
7294 }
7295
7296 ##################################
7297 # Test interface
7298 ##################################
7299
7300 # usage: stack_trap arg sigspec
7301 #
7302 # stack_trap() behaves like bash's built-in trap, except that it "stacks" the
7303 # command "arg" on top of previously defined commands for "sigspec" instead
7304 # of overwriting them.
7305 # stacked traps are executed in reverse order of their registration
7306 #
7307 # arg and sigspec have the same meaning as in man (1) trap
7308 stack_trap()
7309 {
7310         local arg="$1"
7311         local sigspec="${2:-EXIT}"
7312
7313         # Use "trap -p" to get the quoting right
7314         local old_trap="$(trap -p "$sigspec")"
7315         # Append ";" and remove the leading "trap -- '" added by "trap -p"
7316         old_trap="${old_trap:+"; ${old_trap#trap -- \'}"}"
7317
7318         # Once again, use "trap -p" to get the quoting right
7319         local new_trap="$(trap -- "$arg" "$sigspec"
7320                           trap -p "$sigspec"
7321                           trap -- '' "$sigspec")"
7322
7323         # Remove the trailing "' $sigspec" part added by "trap -p" and merge
7324         #
7325         # The resulting string should be safe to "eval" as it is (supposedly
7326         # correctly) quoted by "trap -p"
7327         eval "${new_trap%\' $sigspec}${old_trap:-"' $sigspec"}"
7328 }
7329
7330 error_noexit() {
7331         report_error "$@"
7332 }
7333
7334 exit_status () {
7335         local status=0
7336         local logs="$TESTSUITELOG $1"
7337
7338         for log in $logs; do
7339                 if [ -f "$log" ]; then
7340                         grep -qw FAIL $log && status=1
7341                 fi
7342         done
7343
7344         exit $status
7345 }
7346
7347 error() {
7348         report_error "$@"
7349         exit 1
7350 }
7351
7352 error_exit() {
7353         report_error "$@"
7354         exit 1
7355 }
7356
7357 # use only if we are ignoring failures for this test, bugno required.
7358 # (like ALWAYS_EXCEPT, but run the test and ignore the results.)
7359 # e.g. error_ignore bz5494 "your message" or
7360 # error_ignore LU-5494 "your message"
7361 error_ignore() {
7362         local TYPE="IGNORE ($1)"
7363         shift
7364         report_error false "$@"
7365 }
7366
7367 error_and_remount() {
7368         report_error "$@"
7369         remount_client $MOUNT
7370         exit 1
7371 }
7372
7373 # Throw an error if it's not running in vm - usually for performance
7374 # verification
7375 error_not_in_vm() {
7376         local virt=$(running_in_vm)
7377         if [[ -n "$virt" ]]; then
7378                 echo "running in VM '$virt', ignore error"
7379                 error_ignore env=$virt "$@"
7380         else
7381                 error "$@"
7382         fi
7383 }
7384
7385 #
7386 # Function: skip_env()
7387 # Purpose:  to skip a test during developer testing because some tool
7388 #           is missing, but fail the test in release testing because the test
7389 #           environment is not configured properly".
7390 #
7391 skip_env () {
7392         $FAIL_ON_SKIP_ENV && error false "$@" || skip "$@"
7393 }
7394
7395 skip_noexit() {
7396         echo
7397         log " SKIP: $TESTSUITE $TESTNAME $*"
7398
7399         if [[ -n "$ALWAYS_SKIPPED" ]]; then
7400                 skip_logged $TESTNAME "$@"
7401         else
7402                 mkdir -p $LOGDIR
7403                 echo "$@" > $LOGDIR/skip
7404         fi
7405
7406         [[ -n "$TESTSUITELOG" ]] &&
7407                 echo "$TESTSUITE: SKIP: $TESTNAME $*" >> $TESTSUITELOG || true
7408         unset TESTNAME
7409 }
7410
7411 skip() {
7412         skip_noexit "$@"
7413         exit 0
7414 }
7415
7416 #
7417 # For interop testing treate EOPNOTSUPP as success
7418 # and skip
7419 #
7420 skip_eopnotsupp() {
7421         local retstr=$@
7422
7423         echo $retstr | awk -F'|' '{print $1}' |
7424                 grep -E unsupported\|"(Operation not supported)"
7425         (( $? == 0 )) || error "$retstr"
7426         skip $retstr
7427 }
7428
7429 # Add a list of tests to ALWAYS_EXCEPT due to an issue.
7430 # Usage: always_except LU-4815 23 42q ...
7431 #
7432 function \
7433 always_except() {
7434         local issue="${1:-}" # single jira style issue ("LU-4815")
7435         local test_num
7436
7437         shift
7438
7439         if ! [[ "$issue" =~ ^[[:upper:]]+-[[:digit:]]+$ ]]; then
7440                 error "always_except: invalid issue '$issue' for tests '$*'"
7441         fi
7442
7443         for test_num in "$@"; do
7444                 ALWAYS_EXCEPT+=" $test_num"
7445         done
7446 }
7447
7448 build_test_filter() {
7449         EXCEPT="$EXCEPT $(testslist_filter)"
7450
7451         # allow test numbers separated by '+', or ',', in addition to ' '
7452         # to avoid issues with multiple arguments handling by shell/autotest
7453         for O in ${ONLY//[+,]/ }; do
7454                 if [[ $O =~ [0-9]*-[0-9]* ]]; then
7455                         for ((num=${O%-[0-9]*}; num <= ${O#[0-9]*-}; num++)); do
7456                                 eval ONLY_$num=true
7457                         done
7458                 else
7459                         eval ONLY_${O}=true
7460                 fi
7461         done
7462
7463         local nodes=$(comma_list $(facets_nodes mds1,ost1))
7464         local exceptions="$LUSTRE/tests/except/$TESTSUITE.*ex"
7465
7466         do_nodes --verbose $nodes "ls $exceptions || true"
7467         while read facet op need_ver jira subs; do
7468                 local have_ver_code=${facet^^*}_VERSION
7469                 local need_ver_code
7470
7471                 [[ "$facet" =~ "#" ]] && continue
7472                 [[ "$need_ver" =~ _VERSION ]] && need_ver_code=$need_ver ||
7473                         need_ver_code=$(version_code $need_ver)
7474
7475                 (( ${!have_ver_code} $op $need_ver_code )) &&
7476                         echo "- see $facet $op $need_ver for $jira, go $subs" ||
7477                 {
7478                         log "- need $facet $op $need_ver for $jira, skip $subs"
7479                         for E in $subs; do
7480                                 eval EXCEPT_${E}=true
7481                         done
7482                 }
7483         done < <(do_nodes $nodes "cat $exceptions 2>/dev/null ||true" | sort -u)
7484
7485         [[ -z "$EXCEPT$ALWAYS_EXCEPT" ]] ||
7486                 log "excepting tests: $(echo $EXCEPT $ALWAYS_EXCEPT)"
7487         [[ -z "$EXCEPT_SLOW" ]] ||
7488                 log "skipping tests SLOW=no: $(echo $EXCEPT_SLOW)"
7489         for E in ${EXCEPT//[+,]/ }; do
7490                 eval EXCEPT_${E}=true
7491         done
7492         for E in ${ALWAYS_EXCEPT//[+,]/ }; do
7493                 eval EXCEPT_ALWAYS_${E}=true
7494         done
7495         for E in ${EXCEPT_SLOW//[+,]/ }; do
7496                 eval EXCEPT_SLOW_${E}=true
7497         done
7498         for G in ${GRANT_CHECK_LIST//[+,]/ }; do
7499                 eval GCHECK_ONLY_${G}=true
7500         done
7501         # similar to $EXCEPT, STOP_ON_ERROR is a list of test numbers,
7502         # e.g. [30d, 34a].  Now set variable STOP_ON_ERROR_30d, etc.
7503         for T in $STOP_ON_ERROR; do
7504                 eval STOP_ON_ERROR_${T}=true
7505         done
7506 }
7507
7508 basetest() {
7509         if [[ $1 = [a-z]* ]]; then
7510                 echo $1
7511         else
7512                 echo ${1%%[a-zA-Z]*}
7513         fi
7514 }
7515
7516 # print a newline if the last test was skipped
7517 export LAST_SKIPPED=
7518 export ALWAYS_SKIPPED=
7519 #
7520 # Main entry into test-framework. This is called with the number and
7521 # description of a test. The number is used to find the function to run
7522 # the test using "test_$name".
7523 #
7524 # This supports a variety of methods of specifying specific test to
7525 # run or not run:
7526 # - ONLY= env variable with space-separated list of test numbers to run
7527 # - EXCEPT= env variable with space-separated list of test numbers to exclude
7528 #
7529 run_test() {
7530         assert_DIR
7531         local testnum=$1
7532         local testmsg=$2
7533         export base=$(basetest $testnum)
7534         export TESTNAME=test_$testnum
7535         LAST_SKIPPED=
7536         ALWAYS_SKIPPED=
7537
7538         # Check the EXCEPT, ALWAYS_EXCEPT and SLOW lists to see if we
7539         # need to skip the current test. If so, set the ALWAYS_SKIPPED flag.
7540         local isexcept=EXCEPT_$testnum
7541         local isexcept_base=EXCEPT_$base
7542         if [ ${!isexcept}x != x ]; then
7543                 ALWAYS_SKIPPED="y"
7544                 skip_message="skipping excluded test $testnum"
7545         elif [ ${!isexcept_base}x != x ]; then
7546                 ALWAYS_SKIPPED="y"
7547                 skip_message="skipping excluded test $testnum (base $base)"
7548         fi
7549
7550         isexcept=EXCEPT_ALWAYS_$testnum
7551         isexcept_base=EXCEPT_ALWAYS_$base
7552         if [ ${!isexcept}x != x ]; then
7553                 ALWAYS_SKIPPED="y"
7554                 skip_message="skipping ALWAYS excluded test $testnum"
7555         elif [ ${!isexcept_base}x != x ]; then
7556                 ALWAYS_SKIPPED="y"
7557                 skip_message="skipping ALWAYS excluded test $testnum (base $base)"
7558         fi
7559
7560         isexcept=EXCEPT_SLOW_$testnum
7561         isexcept_base=EXCEPT_SLOW_$base
7562         if [ ${!isexcept}x != x ]; then
7563                 ALWAYS_SKIPPED="y"
7564                 skip_message="skipping SLOW test $testnum"
7565         elif [ ${!isexcept_base}x != x ]; then
7566                 ALWAYS_SKIPPED="y"
7567                 skip_message="skipping SLOW test $testnum (base $base)"
7568         fi
7569
7570         # If there are tests on the ONLY list, check if the current test
7571         # is on that list and, if so, check if the test is to be skipped
7572         # and if we are supposed to honor the skip lists.
7573         if [ -n "$ONLY" ]; then
7574                 local isonly=ONLY_$testnum
7575                 local isonly_base=ONLY_$base
7576                 if [[ ${!isonly}x != x || ${!isonly_base}x != x ]]; then
7577
7578                         if [[ -n "$ALWAYS_SKIPPED" &&
7579                                         -n "$HONOR_EXCEPT" ]]; then
7580                                 LAST_SKIPPED="y"
7581                                 skip_noexit "$skip_message"
7582                                 return 0
7583                         else
7584                                 [ -n "$LAST_SKIPPED" ] &&
7585                                         echo "" && LAST_SKIPPED=
7586                                 ALWAYS_SKIPPED=
7587                                 run_one_logged $testnum "$testmsg"
7588                                 return $?
7589                         fi
7590
7591                 else
7592                         LAST_SKIPPED="y"
7593                         return 0
7594                 fi
7595         fi
7596
7597         if [ -n "$ALWAYS_SKIPPED" ]; then
7598                 LAST_SKIPPED="y"
7599                 skip_noexit "$skip_message"
7600                 return 0
7601         else
7602                 run_one_logged $testnum "$testmsg"
7603                 # TODO: Avoid running out of space!?
7604                 if [[ "$FSTYPE" == "wbcfs" ]]; then
7605                         rm -rf "$MOUNT/*"
7606                 fi
7607                 return $?
7608         fi
7609 }
7610
7611 log() {
7612         echo "$*" >&2
7613         load_module ../libcfs/libcfs/libcfs
7614
7615         local MSG="$*"
7616         # Get rid of '
7617         MSG=${MSG//\'/\\\'}
7618         MSG=${MSG//\*/\\\*}
7619         MSG=${MSG//\(/\\\(}
7620         MSG=${MSG//\)/\\\)}
7621         MSG=${MSG//\;/\\\;}
7622         MSG=${MSG//\|/\\\|}
7623         MSG=${MSG//\>/\\\>}
7624         MSG=${MSG//\</\\\<}
7625         MSG=${MSG//\//\\\/}
7626         do_nodes $(comma_list $(nodes_list)) $LCTL mark "$MSG" 2> /dev/null || true
7627 }
7628
7629 trace() {
7630         log "STARTING: $*"
7631         strace -o $TMP/$1.strace -ttt $*
7632         RC=$?
7633         log "FINISHED: $*: rc $RC"
7634         return 1
7635 }
7636
7637 complete_test() {
7638         local duration=$1
7639
7640         banner "test complete, duration $duration sec"
7641         [ -f "$TESTSUITELOG" ] && egrep .FAIL $TESTSUITELOG || true
7642         echo "duration $duration" >>$TESTSUITELOG
7643 }
7644
7645 pass() {
7646         # Set TEST_STATUS here. It will be used for logging the result.
7647         TEST_STATUS="PASS"
7648
7649         if [[ -f $LOGDIR/err ]]; then
7650                 TEST_STATUS="FAIL"
7651         elif [[ -f $LOGDIR/skip ]]; then
7652                 TEST_STATUS="SKIP"
7653         fi
7654         echo "$TEST_STATUS $*" 2>&1 | tee -a $TESTSUITELOG
7655 }
7656
7657 check_mds() {
7658         local FFREE=$(do_node $SINGLEMDS \
7659         lctl get_param -n osd*.*MDT*.filesfree | calc_sum)
7660         local FTOTAL=$(do_node $SINGLEMDS \
7661         lctl get_param -n osd*.*MDT*.filestotal | calc_sum)
7662
7663         [ $FFREE -ge $FTOTAL ] && error "files free $FFREE > total $FTOTAL" ||
7664                 true
7665 }
7666
7667 reset_fail_loc () {
7668         #echo -n "Resetting fail_loc on all nodes..."
7669         do_nodes --quiet $(comma_list $(nodes_list)) \
7670                 "lctl set_param -n fail_loc=0 fail_val=0 2>/dev/null" || true
7671         #echo done.
7672 }
7673
7674
7675 #
7676 # Log a message (on all nodes) padded with "=" before and after.
7677 # Also appends a timestamp and prepends the testsuite name.
7678 #
7679
7680 # ======================================================== 15:06:12 (1624050372)
7681 EQUALS="========================================================"
7682 banner() {
7683         msg="== ${TESTSUITE} $*"
7684         last=${msg: -1:1}
7685         [[ $last != "=" && $last != " " ]] && msg="$msg "
7686         msg=$(printf '%s%.*s'  "$msg"  $((${#EQUALS} - ${#msg})) $EQUALS )
7687         # always include at least == after the message
7688         log "$msg== $(date +"%H:%M:%S (%s)")"
7689 }
7690
7691 check_dmesg_for_errors() {
7692         local res
7693         local errors
7694         local testid=$(tr '_' ' ' <<< $TESTNAME)
7695
7696         errors="VFS: Busy inodes after unmount of"
7697         errors+="\|ldiskfs_check_descriptors: Checksum for group 0 failed"
7698         errors+="\|group descriptors corrupted"
7699         errors+="\|UBSAN\|KASAN"
7700
7701         res=$(do_nodes -q $(comma_list $(nodes_list)) "dmesg" |
7702                 tac | sed "/$testid/,$ d" | grep "$errors")
7703         [[ -n "$res" ]] || return 0
7704         echo "Kernel error detected: $res"
7705         return 1
7706 }
7707
7708 #
7709 # Run a single test function and cleanup after it.
7710 #
7711 # This function should be run in a subshell so the test func can
7712 # exit() without stopping the whole script.
7713 #
7714 run_one() {
7715         local testnum=$1
7716         local testmsg="$2"
7717         local SAVE_UMASK=`umask`
7718         umask 0022
7719
7720         if ! grep -q $DIR /proc/mounts; then
7721                 $SETUP
7722         fi
7723
7724         banner "test $testnum: $testmsg"
7725         test_${testnum} || error "test_$testnum failed with $?"
7726         cd $SAVE_PWD
7727         reset_fail_loc
7728         check_grant ${testnum} || error "check_grant $testnum failed with $?"
7729         check_node_health
7730         check_dmesg_for_errors || error "Error in dmesg detected"
7731         if [ "$PARALLEL" != "yes" ]; then
7732                 ps auxww | grep -v grep | grep -q "multiop " &&
7733                                         error "multiop still running"
7734         fi
7735         umask $SAVE_UMASK
7736         $CLEANUP
7737         return 0
7738 }
7739
7740 #
7741 # Wrapper around run_one to ensure:
7742 #  - test runs in subshell
7743 #  - output of test is saved to separate log file for error reporting
7744 #  - test result is saved to data file
7745 #
7746 run_one_logged() {
7747         local before=$SECONDS
7748         local testnum=$1
7749         local testmsg=$2
7750         export tfile=f${testnum}.${TESTSUITE}
7751         export tdir=d${testnum}.${TESTSUITE}
7752         local test_log=$TESTLOG_PREFIX.$TESTNAME.test_log.$(hostname -s).log
7753         local zfs_debug_log=$TESTLOG_PREFIX.$TESTNAME.zfs_log
7754         local SAVE_UMASK=$(umask)
7755         local rc=0
7756         local node
7757         umask 0022
7758
7759         [[ $KPTR_ON_MOUNT ]] || kptr_enable_and_save
7760
7761         rm -f $LOGDIR/err $LOGDIR/ignore $LOGDIR/skip
7762         echo
7763
7764         # process ONLY options:
7765         # - $ONLY_REPEAT will run the subtest $ONLY_REPEAT times
7766         # - $ONLY_MINUTES will run the subtest for $ONLY_MINUTES
7767         # - $ONLY_REPEAT and $ONLY_MINUTES can be set to run the subtest for
7768         #   $ONLY_REPEAT times but not to exceed $ONLY_MINUTES
7769         # - if $ONLY_REPEAT and ONLY_MINUTES are unset, subtest will run once
7770         local repeat=${ONLY:+$ONLY_REPEAT}
7771         if [[ -n "$ONLY" && "$ONLY_MINUTES" ]]; then
7772                 local repeat_end_sec=$((SECONDS + ONLY_MINUTES * 60))
7773         fi
7774
7775         export ONLY_REPEAT_ITER=1
7776         while true; do
7777                 local before_sub=$SECONDS
7778                 local iter
7779
7780                 log_sub_test_begin $TESTNAME
7781                 # remove temp files between repetitions to avoid test failures
7782                 if [[ -n "$append" ]]; then
7783                         [[ -n "$tdir" ]] && rm -rvf $DIR/$tdir*
7784                         [[ -n "$tfile" ]] && rm -vf $DIR/$tfile*
7785                         iter=" (repeat $ONLY_REPEAT_ITER/$repeat iter, $(((SECONDS-before)/60))/$ONLY_MINUTES min)"
7786                 fi
7787                 # loop around subshell so stack_trap EXIT triggers each time
7788                 (run_one $testnum "$testmsg$iter") 2>&1 | tee -i $append $test_log
7789                 rc=${PIPESTATUS[0]}
7790                 local append=-a
7791                 local duration_sub=$((SECONDS - before_sub))
7792                 local test_error
7793
7794                 [[ $rc != 0 && ! -f $LOGDIR/err ]] &&
7795                         echo "$TESTNAME returned $rc" | tee $LOGDIR/err
7796
7797                 if [[ -f $LOGDIR/err ]]; then
7798                         test_error=$(cat $LOGDIR/err)
7799                         TEST_STATUS="FAIL"
7800                 elif [[ -f $LOGDIR/ignore ]]; then
7801                         test_error=$(cat $LOGDIR/ignore)
7802                 elif [[ -f $LOGDIR/skip ]]; then
7803                         test_error=$(cat $LOGDIR/skip)
7804                         TEST_STATUS="SKIP"
7805                 else
7806                         TEST_STATUS="PASS"
7807                 fi
7808
7809                 pass "$testnum" "(${duration_sub}s)"
7810                 if [ -n "${DUMP_OK}" ]; then
7811                         gather_logs $(comma_list $(nodes_list))
7812                 fi
7813
7814                 log_sub_test_end $TEST_STATUS $duration_sub "$rc" "$test_error"
7815
7816                 # exit test suite if the failed test is in STOP_ON_ERROR list
7817                 [[ $TEST_STATUS == "FAIL" ]] &&
7818                         [[ -v STOP_ON_ERROR_$testnum ]] &&
7819                         exit $STOP_NOW_RC
7820
7821                 [[ $rc != 0 || "$TEST_STATUS" != "PASS" ]] && break
7822
7823                 # no repeat options were set, break after the first iteration
7824                 [[ -z "$repeat" && -z "$repeat_end_sec" ]] && break
7825                 # break if any repeat options were set and have been met
7826                 [[ -n "$repeat" ]] && (( ONLY_REPEAT_ITER >= repeat )) && break
7827                 [[ -n "$repeat_end_sec" ]] &&
7828                         (( $SECONDS >= $repeat_end_sec )) && break
7829                 ((ONLY_REPEAT_ITER++))
7830         done
7831
7832         [[ $KPTR_ON_MOUNT ]] || kptr_restore
7833
7834         if [[ "$TEST_STATUS" != "SKIP" && -f $TF_SKIP ]]; then
7835                 rm -f $TF_SKIP
7836         fi
7837
7838         if [ -f $LOGDIR/err ]; then
7839                 log_zfs_info "$zfs_debug_log"
7840                 $FAIL_ON_ERROR && exit $rc
7841         fi
7842
7843         umask $SAVE_UMASK
7844
7845         unset TESTNAME
7846         unset tdir
7847         unset tfile
7848
7849         return 0
7850 }
7851
7852 #
7853 # Print information of skipped tests to result.yml
7854 #
7855 skip_logged(){
7856         log_sub_test_begin $1
7857         shift
7858         log_sub_test_end "SKIP" "0" "0" "$@"
7859 }
7860
7861 grant_from_clients() {
7862         local nodes="$1"
7863
7864         # get client grant
7865         do_nodes $nodes "$LCTL get_param -n osc.${FSNAME}-*.cur_*grant_bytes" |
7866                 calc_sum
7867 }
7868
7869 grant_from_servers() {
7870         local nodes="$1"
7871
7872         # get server grant
7873         # which is tot_granted less grant_precreate
7874         do_nodes $nodes "$LCTL get_param obdfilter.${FSNAME}-OST*.tot_granted" \
7875                 " obdfilter.${FSNAME}-OST*.tot_pending" \
7876                 " obdfilter.${FSNAME}-OST*.grant_precreate" |
7877                 tr '=' ' ' | awk '/tot_granted/{ total += $2 };
7878                                   /tot_pending/{ total -= $2 };
7879                                   /grant_precreate/{ total -= $2 };
7880                                   END { printf("%0.0f", total) }'
7881 }
7882
7883 check_grant() {
7884         export base=$(basetest $1)
7885         [ "$CHECK_GRANT" == "no" ] && return 0
7886
7887         local isonly_base=GCHECK_ONLY_${base}
7888         local isonly=GCHECK_ONLY_$1
7889         [ ${!isonly_base}x == x -a ${!isonly}x == x ] && return 0
7890
7891         echo -n "checking grant......"
7892
7893         local osts=$(osts_nodes)
7894         local clients=$CLIENTS
7895         [ -z "$clients" ] && clients=$(hostname)
7896
7897         # sync all the data and make sure no pending data on server
7898         do_nodes $clients sync
7899         do_nodes $clients $LFS df # initiate all idling connections
7900
7901         # get client grant
7902         cli_grant=$(grant_from_clients $clients)
7903
7904         # get server grant
7905         # which is tot_granted less grant_precreate
7906         srv_grant=$(grant_from_servers $osts)
7907
7908         count=0
7909         # check whether client grant == server grant
7910         while [[ $cli_grant != $srv_grant && count++ -lt 30 ]]; do
7911                 echo "wait for client:$cli_grant == server:$srv_grant"
7912                 sleep 1
7913                 cli_grant=$(grant_from_clients $clients)
7914                 srv_grant=$(grant_from_servers $osts)
7915         done
7916         if [[ $cli_grant -ne $srv_grant ]]; then
7917                 do_nodes $osts "$LCTL get_param obdfilter.${FSNAME}-OST*.tot*" \
7918                         "obdfilter.${FSNAME}-OST*.grant_*"
7919                 do_nodes $clients "$LCTL get_param osc.${FSNAME}-*.cur_*_bytes"
7920                 error "failed grant check: client:$cli_grant server:$srv_grant"
7921         else
7922                 echo "pass grant check: client:$cli_grant server:$srv_grant"
7923         fi
7924 }
7925
7926 ########################
7927 # helper functions
7928
7929 osc_to_ost() {
7930         local osc=$1
7931
7932         echo ${osc/-osc*/}
7933 }
7934
7935 ostuuid_from_index() {
7936         # only print the first UUID, if 'lfs osts' shows multiple mountpoints
7937         local uuid=($($LFS osts $2 | sed -ne "/^$1: /s/.* \(.*\) .*$/\1/p"))
7938
7939         echo ${uuid}
7940 }
7941
7942 ostname_from_index() {
7943         local uuid=$(ostuuid_from_index $1 $2)
7944
7945         echo ${uuid/_UUID/}
7946 }
7947
7948 mdtuuid_from_index() {
7949         # only print the first UUID, if 'lfs osts' shows multiple mountpoints
7950         local uuid=($($LFS mdts $2 | sed -ne "/^$1: /s/.* \(.*\) .*$/\1/p"))
7951
7952         echo ${uuid}
7953 }
7954
7955 mdtname_from_index() {
7956         local uuid=$(mdtuuid_from_index $1 $2)
7957
7958         echo ${uuid/_UUID/}
7959 }
7960
7961 mdssize_from_index() {
7962         local mdt=$(mdtname_from_index $2)
7963
7964         $LFS df $1 | awk "/$mdt/ { print \$2 }"
7965 }
7966
7967 index_from_ostuuid()
7968 {
7969         # only print the first index, if 'lfs osts' shows multiple mountpoints
7970         local ostidx=($($LFS osts $2 | sed -ne "/${1}/s/\(.*\): .* .*$/\1/p"))
7971
7972         echo ${ostidx}
7973 }
7974
7975 # Description:
7976 #   Return unique identifier for given hostname
7977 host_id() {
7978         local host_name=$1
7979         echo $host_name | md5sum | cut -d' ' -f1
7980 }
7981
7982 # Description:
7983 #   Returns list of ip addresses for each interface
7984 local_addr_list() {
7985         ip -o a s | awk '{print $4}' | awk -F/ '{print $1}'
7986 }
7987
7988 # Description:
7989 #   Returns list of interfaces configured for LNet
7990 lnet_if_list() {
7991         local nids=( $($LCTL list_nids | xargs echo) )
7992
7993         [[ -z ${nids[@]} ]] &&
7994                 return 0
7995
7996         if [[ ${NETTYPE} =~ kfi* ]]; then
7997                 $LNETCTL net show 2>/dev/null | awk '/ cxi[0-9]+$/{print $NF}' |
7998                         sort -u | xargs echo
7999                 return 0
8000         fi
8001
8002         declare -a INTERFACES
8003
8004         for ((i = 0; i < ${#nids[@]}; i++)); do
8005                 ip=$(sed 's/^\(.*\)@.*$/\1/'<<<${nids[i]})
8006                 INTERFACES[i]=$(ip -o a s |
8007                                 awk '$4 ~ /^'$ip'\//{print $2}')
8008                 INTERFACES=($(echo "${INTERFACES[@]}" | tr ' ' '\n' | uniq | tr '\n' ' '))
8009                 if [[ -z ${INTERFACES[i]} ]]; then
8010                         error "Can't determine interface name for NID ${nids[i]}"
8011                 elif [[ 1 -ne $(wc -w <<<${INTERFACES[i]}) ]]; then
8012                         error "Found $(wc -w <<<${INTERFACES[i]}) interfaces for NID ${nids[i]}. Expect 1"
8013                 fi
8014         done
8015
8016         echo "${INTERFACES[@]}"
8017
8018         return 0
8019 }
8020
8021 # return 1 if addr is remote
8022 # return 0 if addr is local
8023 is_local_addr() {
8024         local addr=$1
8025         # Cache address list to avoid mutiple execution of local_addr_list
8026         LOCAL_ADDR_LIST=${LOCAL_ADDR_LIST:-$(local_addr_list)}
8027         local i
8028         for i in $LOCAL_ADDR_LIST ; do
8029                 [[ "$i" == "$addr" ]] && return 0
8030         done
8031         return 1
8032 }
8033
8034 # return true(0) if host_name is local
8035 # return false(1) if host_name is remote
8036 local_node() {
8037         local host_name=$1
8038         local is_local="IS_LOCAL_$(host_id $host_name)"
8039
8040         if [ -z "${!is_local-}" ] ; then
8041                 eval $is_local=false
8042                 local ip4=$(getent ahostsv4 $host_name |
8043                             awk 'NR == 1 { print $1 }')
8044                 local ip6=$(getent ahostsv6 $host_name |
8045                             awk 'NR == 1 { print $1 }')
8046                 if is_local_addr $ip4 || is_local_addr $ip6 ; then
8047                         eval $is_local=true
8048                 fi
8049         fi
8050         ${!is_local}
8051 }
8052
8053 remote_node() {
8054         local node=$1
8055
8056         ! local_node $node
8057 }
8058
8059 # return true if any MDT is on a remote node
8060 remote_mds()
8061 {
8062         local mdts=$(mdts_nodes)
8063         local node
8064
8065         for node in ${mdts//,/ }; do
8066                 remote_node $node && return 0
8067         done
8068
8069         return 1
8070 }
8071
8072 # return true if any MDT is on a remote node and no remote shell is configured
8073 remote_mds_nodsh()
8074 {
8075         [ -n "$CLIENTONLY" ] && return 0 || true
8076         remote_mds && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$mds_HOST" ]
8077 }
8078
8079 require_dsh_mds()
8080 {
8081         remote_mds_nodsh && echo "SKIP: $TESTSUITE: remote MDS with nodsh" &&
8082                 MSKIPPED=1 && return 1
8083         return 0
8084 }
8085
8086 # return true if any OST is on a remote node
8087 remote_ost()
8088 {
8089         local osts=$(osts_nodes)
8090         local node
8091
8092         for node in ${osts//,/ }; do
8093                 remote_node $node && return 0
8094         done
8095
8096         return 1
8097 }
8098
8099 # return true if any OST is on a remote node and no remote shell is configured
8100 remote_ost_nodsh()
8101 {
8102         [ -n "$CLIENTONLY" ] && return 0 || true
8103         remote_ost && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
8104 }
8105
8106 require_dsh_ost()
8107 {
8108         remote_ost_nodsh && echo "SKIP: $TESTSUITE: remote OST with nodsh" &&
8109                 OSKIPPED=1 && return 1
8110         return 0
8111 }
8112
8113 remote_mgs_nodsh()
8114 {
8115         [ -n "$CLIENTONLY" ] && return 0 || true
8116         local MGS
8117         MGS=$(facet_host mgs)
8118         remote_node $MGS && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
8119 }
8120
8121 local_mode ()
8122 {
8123         remote_mds_nodsh || remote_ost_nodsh ||
8124                 $(single_local_node $(comma_list $(nodes_list)))
8125 }
8126
8127 remote_servers () {
8128         remote_ost && remote_mds
8129 }
8130
8131 # Get the active nodes for facets.
8132 facets_nodes () {
8133         local facets=$1
8134         local facet
8135         local nodes
8136         local nodes_sort
8137         local i
8138
8139         for facet in ${facets//,/ }; do
8140                 nodes="$nodes $(facet_active_host $facet)"
8141         done
8142
8143         nodes_sort=$(for i in ${nodes//,/ }; do echo $i; done | sort -u)
8144         echo -n $nodes_sort
8145 }
8146
8147 # Get name of the active MGS node.
8148 mgs_node () {
8149         echo -n $(facets_nodes $(get_facets MGS))
8150 }
8151
8152 # Get all of the active MDS nodes.
8153 mdts_nodes() {
8154         comma_list $(facets_nodes $(get_facets MDS))
8155 }
8156
8157 # Get all of the active OSS nodes in a comma-separated list.
8158 osts_nodes() {
8159         comma_list $(facets_nodes $(get_facets OST))
8160 }
8161
8162 # Get all of the active server nodes in a comma-separated list.
8163 tgts_nodes() {
8164         comma_list $(facets_nodes $(get_facets MDS OST))
8165 }
8166
8167 # Get all of the client nodes and active server nodes.
8168 nodes_list () {
8169         local nodes=$HOSTNAME
8170         local nodes_sort
8171         local i
8172
8173         # CLIENTS (if specified) contains the local client
8174         [ -n "$CLIENTS" ] && nodes=${CLIENTS//,/ }
8175
8176         if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
8177                 nodes="$nodes $(facets_nodes $(get_facets))"
8178         fi
8179
8180         nodes_sort=$(for i in ${nodes//,/ }; do echo $i; done | sort -u)
8181         echo -n $nodes_sort
8182 }
8183
8184 # Get all of the remote client nodes and remote active server nodes.
8185 remote_nodes_list () {
8186         echo -n $(nodes_list) | sed -re "s/\<$HOSTNAME\>//g"
8187 }
8188
8189 # Get all of the MDS nodes, including active and passive nodes.
8190 all_mdts_nodes () {
8191         local host
8192         local failover_host
8193         local nodes
8194         local i
8195
8196         for ((i=1; i <= $MDSCOUNT; i++)); do
8197                 host=mds${i}_HOST
8198                 failover_host=mds${i}failover_HOST
8199                 nodes="$nodes ${!host} ${!failover_host}"
8200         done
8201
8202         comma_list $nodes
8203 }
8204
8205 # Get all of the OSS nodes, including active and passive nodes.
8206 all_osts_nodes() {
8207         local host
8208         local failover_host
8209         local nodes=""
8210         local i
8211
8212         for ((i = 1; i <= $OSTCOUNT; i++)); do
8213                 host=ost${i}_HOST
8214                 failover_host=ost${i}failover_HOST
8215                 nodes="$nodes ${!host} ${!failover_host}"
8216         done
8217
8218         comma_list $nodes
8219 }
8220
8221 # Get all of the server nodes, including active and passive nodes.
8222 all_server_nodes () {
8223         local nodes
8224         local nodes_sort
8225         local i
8226
8227         nodes="$mgs_HOST $mgsfailover_HOST $(all_mdts_nodes) $(all_osts_nodes)"
8228
8229         nodes_sort=$(for i in ${nodes//,/ }; do echo $i; done | sort -u)
8230         echo -n $nodes_sort
8231 }
8232
8233 # Get all of the client and server nodes, including active and passive nodes.
8234 all_nodes () {
8235         local nodes=$HOSTNAME
8236         local nodes_sort
8237         local i
8238
8239         # CLIENTS (if specified) contains the local client
8240         [ -n "$CLIENTS" ] && nodes=${CLIENTS//,/ }
8241
8242         if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
8243                 nodes="$nodes $(all_server_nodes)"
8244         fi
8245
8246         nodes_sort=$(for i in ${nodes//,/ }; do echo $i; done | sort -u)
8247         echo -n $nodes_sort
8248 }
8249
8250 init_clients_lists () {
8251         # Sanity check: exclude the local client from RCLIENTS
8252         local clients=$(hostlist_expand "$RCLIENTS")
8253         local rclients=$(exclude_items_from_list "$clients" $HOSTNAME)
8254
8255         # Sanity check: exclude the dup entries
8256         RCLIENTS=$(for i in ${rclients//,/ }; do echo $i; done | sort -u)
8257
8258         export CLIENT1=${CLIENT1:-$HOSTNAME}
8259         export SINGLECLIENT=$CLIENT1
8260
8261         clients="$SINGLECLIENT $HOSTNAME $RCLIENTS"
8262
8263         # Sanity check: exclude the dup entries from CLIENTS
8264         # for those configs which has SINGLCLIENT set to local client
8265         clients=$(for i in $clients; do echo $i; done | sort -u)
8266
8267         export CLIENTS=$(comma_list $clients)
8268         local -a remoteclients=($RCLIENTS)
8269         for ((i=0; $i<${#remoteclients[@]}; i++)); do
8270                 varname=CLIENT$((i + 2))
8271
8272                 eval export $varname=${remoteclients[i]}
8273         done
8274
8275         export CLIENTCOUNT=$((${#remoteclients[@]} + 1))
8276 }
8277
8278 get_random_entry () {
8279         local rnodes=$1
8280
8281         rnodes=${rnodes//,/ }
8282
8283         local -a nodes=($rnodes)
8284         local num=${#nodes[@]}
8285         local i=$((RANDOM * num * 2 / 65536))
8286
8287         echo ${nodes[i]}
8288 }
8289
8290 client_only () {
8291         [ -n "$CLIENTONLY" ] || [ "x$CLIENTMODSONLY" = "xyes" ]
8292 }
8293
8294 check_versions () {
8295         # this should already have been called, but just in case
8296         [[ -n "$CLIENT_VERSION" && -n "$MDS1_VERSION" && -n "$OST1_VERSION" ]]||
8297                 get_lustre_env
8298
8299         echo "client=$CLIENT_VERSION MDS=$MDS1_VERSION OSS=$OST1_VERSION"
8300
8301         [[ -n "$CLIENT_VERSION" && -n "$MDS1_VERSION" && -n "$OST1_VERSION" ]]||
8302                 error "unable to determine node versions"
8303
8304         (( "$CLIENT_VERSION" == "$MDS1_VERSION" &&
8305            "$CLIENT_VERSION" == "$OST1_VERSION"))
8306 }
8307
8308 get_node_count() {
8309         local nodes="$@"
8310
8311         echo ${nodes//,/ } | wc -w || true
8312 }
8313
8314 mixed_mdt_devs () {
8315         local nodes=$(mdts_nodes)
8316         local mdtcount=$(get_node_count "$nodes")
8317
8318         [ ! "$MDSCOUNT" = "$mdtcount" ]
8319 }
8320
8321 generate_machine_file() {
8322         local nodes=${1//,/ }
8323         local machinefile=$2
8324
8325         rm -f $machinefile
8326         for node in $nodes; do
8327                 echo $node >>$machinefile ||
8328                         { echo "can not generate machinefile $machinefile" &&
8329                                 return 1; }
8330         done
8331 }
8332
8333 get_stripe () {
8334         local file=$1/stripe
8335
8336         touch $file
8337         $LFS getstripe -v $file || error "getstripe $file failed"
8338         rm -f $file
8339 }
8340
8341 # Check and add a test group.
8342 add_group() {
8343         local group_id=$1
8344         local group_name=$2
8345         local rc=0
8346
8347         local gid=$(getent group $group_name | cut -d: -f3)
8348         if [[ -n "$gid" ]]; then
8349                 [[ "$gid" -eq "$group_id" ]] || {
8350                         error_noexit "inconsistent group ID:" \
8351                                      "new: $group_id, old: $gid"
8352                         rc=1
8353                 }
8354         else
8355                 echo "adding group $group_name:$group_id"
8356                 getent group $group_name || true
8357                 getent group $group_id || true
8358                 groupadd -g $group_id $group_name
8359                 rc=${PIPESTATUS[0]}
8360         fi
8361
8362         return $rc
8363 }
8364
8365 # Check and add a test user.
8366 add_user() {
8367         local user_id=$1
8368         shift
8369         local user_name=$1
8370         shift
8371         local group_name=$1
8372         shift
8373         local home=$1
8374         shift
8375         local opts="$@"
8376         local rc=0
8377
8378         local uid=$(getent passwd $user_name | cut -d: -f3)
8379         if [[ -n "$uid" ]]; then
8380                 if [[ "$uid" -eq "$user_id" ]]; then
8381                         local dir=$(getent passwd $user_name | cut -d: -f6)
8382                         if [[ "$dir" != "$home" ]]; then
8383                                 mkdir -p $home
8384                                 usermod -d $home $user_name
8385                                 rc=${PIPESTATUS[0]}
8386                         fi
8387                 else
8388                         error_noexit "inconsistent user ID:" \
8389                                      "new: $user_id, old: $uid"
8390                         rc=1
8391                 fi
8392         else
8393                 mkdir -p $home
8394                 useradd -M -u $user_id -d $home -g $group_name $opts $user_name
8395                 rc=${PIPESTATUS[0]}
8396         fi
8397
8398         return $rc
8399 }
8400
8401 check_runas_id_ret() {
8402         local myRC=0
8403         local myRUNAS_UID=$1
8404         local myRUNAS_GID=$2
8405         shift 2
8406         local myRUNAS=$@
8407
8408         if [ -z "$myRUNAS" ]; then
8409                 error_exit "check_runas_id_ret requires myRUNAS argument"
8410         fi
8411
8412         $myRUNAS true ||
8413                 error "Unable to execute $myRUNAS"
8414
8415         id $myRUNAS_UID > /dev/null ||
8416                 error "Invalid RUNAS_ID $myRUNAS_UID. Please set RUNAS_ID to " \
8417                       "some UID which exists on MDS and client or add user " \
8418                       "$myRUNAS_UID:$myRUNAS_GID on these nodes."
8419
8420         if $GSS_KRB5; then
8421                 $myRUNAS krb5_login.sh ||
8422                         error "Failed to refresh krb5 TGT for UID $myRUNAS_ID."
8423         fi
8424         mkdir $DIR/d0_runas_test
8425         chmod 0755 $DIR
8426         chown $myRUNAS_UID:$myRUNAS_GID $DIR/d0_runas_test
8427         $myRUNAS touch $DIR/d0_runas_test/f$$ || myRC=$?
8428         rm -rf $DIR/d0_runas_test
8429         return $myRC
8430 }
8431
8432 check_runas_id() {
8433         local myRUNAS_UID=$1
8434         local myRUNAS_GID=$2
8435         shift 2
8436         local myRUNAS=$@
8437
8438         check_runas_id_ret $myRUNAS_UID $myRUNAS_GID $myRUNAS || \
8439                 error "unable to write to $DIR/d0_runas_test as " \
8440                       "UID $myRUNAS_UID."
8441 }
8442
8443 # obtain the UID/GID for MPI_USER
8444 get_mpiuser_id() {
8445         local mpi_user=$1
8446
8447         if [[ -z "$MPI_USER_UID" ]]; then
8448                 MPI_USER_UID=$(do_facet client "getent passwd $mpi_user |
8449                                cut -d: -f3; exit \\\${PIPESTATUS[0]}") ||
8450                         skip_env "failed to get the UID for $mpi_user"
8451                 echo "mpi_user=$1 MPI_USER_UID=$MPI_USER_UID"
8452         fi
8453
8454         if [[ -z "$MPI_USER_GID" ]]; then
8455                 MPI_USER_GID=$(do_facet client "getent passwd $mpi_user |
8456                                cut -d: -f4; exit \\\${PIPESTATUS[0]}") ||
8457                         skip_env "failed to get the GID for $mpi_user"
8458                 echo "mpi_user=$1 MPI_USER_GID=$MPI_USER_GID"
8459         fi
8460 }
8461
8462 # obtain and cache Kerberos ticket-granting ticket
8463 refresh_krb5_tgt() {
8464         local myRUNAS_UID=$1
8465         local myRUNAS_GID=$2
8466         shift 2
8467         local myRUNAS=$@
8468         if [ -z "$myRUNAS" ]; then
8469                 error_exit "myRUNAS command must be specified for refresh_krb5_tgt"
8470         fi
8471
8472         CLIENTS=${CLIENTS:-$HOSTNAME}
8473         do_nodes $CLIENTS "set -x
8474 if ! $myRUNAS krb5_login.sh; then
8475     echo "Failed to refresh Krb5 TGT for UID/GID $myRUNAS_UID/$myRUNAS_GID."
8476     exit 1
8477 fi"
8478 }
8479
8480 # Run multiop in the background, but wait for it to print
8481 # "PAUSING" to its stdout before returning from this function.
8482 multiop_bg_pause() {
8483         MULTIOP_PROG=${MULTIOP_PROG:-$MULTIOP}
8484         FILE=$1
8485         ARGS=$2
8486
8487         TMPPIPE=/tmp/multiop_open_wait_pipe.$$
8488         mkfifo $TMPPIPE
8489
8490         echo "$MULTIOP_PROG $FILE v$ARGS"
8491         $MULTIOP_PROG $FILE v$ARGS > $TMPPIPE &
8492         local pid=$!
8493
8494         echo "TMPPIPE=${TMPPIPE}"
8495         read -t 60 multiop_output < $TMPPIPE
8496         if [ $? -ne 0 ]; then
8497                 rm -f $TMPPIPE
8498                 return 1
8499         fi
8500         rm -f $TMPPIPE
8501         if [ "$multiop_output" != "PAUSING" ]; then
8502                 echo "Incorrect multiop output: $multiop_output"
8503                 kill -9 $pid
8504                 return 1
8505         fi
8506
8507         return 0
8508 }
8509
8510 do_and_time () {
8511         local cmd="$1"
8512         local start
8513         local rc
8514
8515         start=$SECONDS
8516         eval '$cmd'
8517         [ ${PIPESTATUS[0]} -eq 0 ] || rc=1
8518
8519         echo $((SECONDS - start))
8520         return $rc
8521 }
8522
8523 inodes_available () {
8524         local IFree=$($LFS df -i $MOUNT | grep ^$FSNAME | awk '{ print $4 }' |
8525                 sort -un | head -n1) || return 1
8526
8527         echo $((IFree))
8528 }
8529
8530 mdsrate_inodes_available () {
8531         local min_inodes=$(inodes_available)
8532
8533         echo $((min_inodes * 99 / 100))
8534 }
8535
8536 bytes_available () {
8537         echo $(df -P -B 1 "$MOUNT" | awk 'END {print $4}')
8538 }
8539
8540 mdsrate_bytes_available () {
8541         local bytes=$(bytes_available)
8542
8543         echo $((bytes * 99 / 100))
8544 }
8545
8546 # reset stat counters
8547 clear_stats() {
8548         local paramfile="$1"
8549
8550         lctl set_param -n $paramfile=0
8551 }
8552
8553 # sum stat items
8554 calc_stats() {
8555         local paramfile="$1"
8556         local stat="$2"
8557
8558         lctl get_param -n $paramfile |
8559                 awk '/^'$stat' / { sum += $2 } END { printf("%0.0f", sum) }'
8560 }
8561
8562 calc_stats_sum() {
8563         local paramfile="$1"
8564         local stat="$2"
8565
8566         lctl get_param -n $paramfile |
8567                 awk '/^'$stat' / { sum += $7 } END { printf("%0.0f", sum) }'
8568 }
8569
8570 calc_sum () {
8571         awk '{sum += $1} END { printf("%0.0f", sum) }'
8572 }
8573
8574 calc_osc_kbytes () {
8575         $LFS df $MOUNT > /dev/null
8576         $LCTL get_param -n osc.*[oO][sS][cC][-_][0-9a-f]*.$1 | calc_sum
8577 }
8578
8579 free_min_max () {
8580         wait_delete_completed
8581         AVAIL=($(lctl get_param -n osc.*[oO][sS][cC]-[^M]*.kbytesavail))
8582         echo "OST kbytes available: ${AVAIL[*]}"
8583         MAXV=${AVAIL[0]}
8584         MAXI=0
8585         MINV=${AVAIL[0]}
8586         MINI=0
8587         for ((i = 0; i < ${#AVAIL[@]}; i++)); do
8588                 #echo OST $i: ${AVAIL[i]}kb
8589                 if [[ ${AVAIL[i]} -gt $MAXV ]]; then
8590                         MAXV=${AVAIL[i]}
8591                         MAXI=$i
8592                 fi
8593                 if [[ ${AVAIL[i]} -lt $MINV ]]; then
8594                         MINV=${AVAIL[i]}
8595                         MINI=$i
8596                 fi
8597         done
8598         echo "Min free space: OST $MINI: $MINV"
8599         echo "Max free space: OST $MAXI: $MAXV"
8600 }
8601
8602 # save_lustre_params(comma separated facet list, parameter_mask)
8603 # generate a stream of formatted strings (<facet> <param name>=<param value>)
8604 save_lustre_params() {
8605         local facets=$1
8606         local facet
8607         local facet_svc
8608
8609         for facet in ${facets//,/ }; do
8610                 facet_svc=$(facet_svc $facet)
8611                 do_facet $facet \
8612                         "params=\\\$($LCTL get_param $2);
8613                          [[ -z \\\"$facet_svc\\\" ]] && param= ||
8614                          param=\\\$(grep $facet_svc <<< \\\"\\\$params\\\");
8615                          [[ -z \\\$param ]] && param=\\\"\\\$params\\\";
8616                          while read s; do echo $facet \\\$s;
8617                          done <<< \\\"\\\$param\\\""
8618         done
8619 }
8620
8621 # restore lustre parameters from input stream, produces by save_lustre_params
8622 restore_lustre_params() {
8623         local facet
8624         local name
8625         local val
8626
8627         while IFS=" =" read facet name val; do
8628                 do_facet $facet "$LCTL set_param -n $name=$val"
8629         done
8630 }
8631
8632 check_node_health() {
8633         local nodes=${1:-$(comma_list $(nodes_list))}
8634         local health=$TMP/node_health.$$
8635
8636         do_nodes -q $nodes "$LCTL get_param catastrophe 2>&1" | tee $health |
8637                 grep "catastrophe=1" && error "LBUG/LASSERT detected"
8638         # Only check/report network health if get_param isn't reported, since
8639         # *clearly* the network is working if get_param returned something.
8640         if (( $(grep -c catastro $health) != $(wc -w <<< ${nodes//,/ }) )); then
8641                 for node in ${nodes//,/ }; do
8642                         check_network $node 60
8643                 done
8644         fi
8645         rm -f $health
8646 }
8647
8648 mdsrate_cleanup () {
8649         if [ -d $4 ]; then
8650                 mpi_run ${MACHINEFILE_OPTION} $2 -np $1 ${MDSRATE} --unlink \
8651                         --nfiles $3 --dir $4 --filefmt $5 $6
8652                 rmdir $4
8653         fi
8654 }
8655
8656 run_mdtest () {
8657         local test_type="$1"
8658         local file_size=0
8659         local num_files=0
8660         local num_cores=0
8661         local num_procs=0
8662         local num_hosts=0
8663         local free_space=0
8664         local num_inodes=0
8665         local num_entries=0
8666         local num_dirs=0
8667         local np=0
8668         local rc=0
8669
8670         local mdtest_basedir
8671         local mdtest_actions
8672         local mdtest_options
8673         local stripe_options
8674         local params_file
8675
8676         case "$test_type" in
8677         create-small)
8678                 stripe_options=(-c 1 -i 0)
8679                 mdtest_actions=(-F -R)
8680                 file_size=3901
8681                 num_files=100000
8682                 ;;
8683         create-large)
8684                 mdtest_actions=(-F -R)
8685                 num_files=1000000
8686                 ;;
8687         lookup-single)
8688                 stripe_options=(-c 1)
8689                 mdtest_actions=(-C -D -E -k -r)
8690                 num_dirs=1
8691                 num_files=100000
8692                 ;;
8693         lookup-multi)
8694                 stripe_options=(-c 1)
8695                 mdtest_actions=(-C -D -E -k -r)
8696                 num_dirs=100
8697                 num_files=1000
8698                 ;;
8699         *)
8700                 stripe_options=(-c -1)
8701                 mdtest_actions=()
8702                 num_files=100000
8703                 ;;
8704         esac
8705
8706         if [[ -n "$MDTEST_DEBUG" ]]; then
8707                 mdtest_options+=(-v -v -v)
8708         fi
8709
8710         num_dirs=${NUM_DIRS:-$num_dirs}
8711         num_files=${NUM_FILES:-$num_files}
8712         file_size=${FILE_SIZE:-$file_size}
8713         free_space=$(mdsrate_bytes_available)
8714
8715         if (( file_size * num_files > free_space )); then
8716                 file_size=$((free_space / num_files))
8717                 log "change file size to $file_size due to" \
8718                         "number of files $num_files and" \
8719                         "free space limit in $free_space"
8720         fi
8721
8722         if (( file_size > 0 )); then
8723                 log "set file size to $file_size"
8724                 mdtest_options+=(-w=$file_size)
8725         fi
8726
8727         params_file=$TMP/$TESTSUITE-$TESTNAME.parameters
8728         mdtest_basedir=$MOUNT/mdtest
8729         mdtest_options+=(-d=$mdtest_basedir)
8730
8731         num_cores=$(nproc)
8732         num_hosts=$(get_node_count ${CLIENTS//,/ })
8733         num_procs=$((num_cores * num_hosts))
8734         num_inodes=$(mdsrate_inodes_available)
8735
8736         if (( num_inodes < num_files )); then
8737                 log "change the number of files $num_files to the" \
8738                         "number of available inodes $num_inodes"
8739                 num_files=$num_inodes
8740         fi
8741
8742         if (( num_dirs > 1 )); then
8743                 num_entries=$((num_files / num_dirs))
8744                 # md_validate_tests requires items must be a multiple of
8745                 # items per directory
8746                 num_files=$((num_entries * num_dirs))
8747                 log "split $num_files files to $num_dirs" \
8748                         "with $num_entries files each"
8749                 mdtest_options+=(-I=$num_entries)
8750         fi
8751
8752         generate_machine_file $CLIENTS $MACHINEFILE ||
8753                 error "can not generate machinefile"
8754
8755         install -v -d -m 0777 $mdtest_basedir
8756
8757         setstripe_getstripe $mdtest_basedir ${stripe_options[@]}
8758
8759         save_lustre_params $(get_facets MDS) \
8760                 mdt.*.enable_remote_dir_gid > $params_file
8761
8762         do_nodes $(mdts_nodes) $LCTL set_param mdt.*.enable_remote_dir_gid=-1
8763
8764         stack_trap "restore_lustre_params < $params_file" EXIT
8765
8766         for np in 1 $num_procs; do
8767                 num_entries=$((num_files / np ))
8768
8769                 mpi_run $MACHINEFILE_OPTION $MACHINEFILE \
8770                         -np $np -npernode $num_cores $MDTEST \
8771                         ${mdtest_options[@]} -n=$num_entries \
8772                         ${mdtest_actions[@]} 2>&1 | tee -a "$LOG"
8773
8774                 rc=${PIPESTATUS[0]}
8775
8776                 if (( rc != 0 )); then
8777                         mpi_run $MACHINEFILE_OPTION $MACHINEFILE \
8778                                 -np $np -npernode $num_cores $MDTEST \
8779                                 ${mdtest_options[@]} -n=$num_entries \
8780                                 -r 2>&1 | tee -a "$LOG"
8781                         break
8782                 fi
8783         done
8784
8785         rmdir -v $mdtest_basedir
8786         rm -v $state $MACHINEFILE
8787
8788         return $rc
8789 }
8790
8791 ########################
8792
8793 convert_facet2label() {
8794         local facet=$1
8795
8796         if [ x$facet = xost ]; then
8797                 facet=ost1
8798         elif [ x$facet = xmgs ] && combined_mgs_mds ; then
8799                 facet=mds1
8800         fi
8801
8802         local varsvc=${facet}_svc
8803
8804         if [ -n "${!varsvc}" ]; then
8805                 echo ${!varsvc}
8806         else
8807                 # FIXME: Cannot find label correctly for some reason.
8808                 # Just assume wbcfs OSD and continue...
8809                 if [[ "$FSTYPE" == "wbcfs" ]]; then
8810                         echo "wbcfs-target"
8811                 else
8812                         error "No label for $facet!"
8813                 fi
8814         fi
8815 }
8816
8817 get_clientosc_proc_path() {
8818         echo "${1}-osc-[-0-9a-f]*"
8819 }
8820
8821 get_mdtosc_proc_path() {
8822         local mds_facet=$1
8823         local ost_label=${2:-"*OST*"}
8824
8825         [ "$mds_facet" = "mds" ] && mds_facet=$SINGLEMDS
8826         local mdt_label=$(convert_facet2label $mds_facet)
8827         local mdt_index=$(echo $mdt_label | sed -e 's/^.*-//')
8828
8829         if [[ $ost_label = *OST* ]]; then
8830                 echo "${ost_label}-osc-${mdt_index}"
8831         else
8832                 echo "${ost_label}-osp-${mdt_index}"
8833         fi
8834 }
8835
8836 get_osc_import_name() {
8837         local facet=$1
8838         local ost=$2
8839         local label=$(convert_facet2label $ost)
8840
8841         if [ "${facet:0:3}" = "mds" ]; then
8842                 get_mdtosc_proc_path $facet $label
8843                 return 0
8844         fi
8845
8846         get_clientosc_proc_path $label
8847         return 0
8848 }
8849
8850 _wait_import_state () {
8851         local expected="$1"
8852         local CONN_PROC="$2"
8853         local maxtime=${3:-$(max_recovery_time)}
8854         local err_on_fail=${4:-1}
8855         local CONN_STATE
8856         local i=0
8857
8858         CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2 | uniq)
8859         while ! echo "${CONN_STATE}" | egrep -q "^${expected}\$" ; do
8860                 if [[ "${expected}" == "DISCONN" ]]; then
8861                         # for disconn we can check after proc entry is removed
8862                         [[ -z "${CONN_STATE}" ]] && return 0
8863                         # with AT, we can have connect request timeout near
8864                         # reconnect timeout and test can't see real disconnect
8865                         [[ "${CONN_STATE}" == "CONNECTING" ]] && return 0
8866                 fi
8867                 if (( $i >= $maxtime )); then
8868                         (( $err_on_fail != 0 )) &&
8869                                 error "can't put import for $CONN_PROC into ${expected} state after $i sec, have ${CONN_STATE}"
8870                         return 1
8871                 fi
8872                 sleep 1
8873                 # Add uniq for multi-mount case
8874                 CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null |
8875                              cut -f2 | uniq)
8876                 i=$((i + 1))
8877         done
8878
8879         log "$CONN_PROC in ${CONN_STATE} state after $i sec"
8880         return 0
8881 }
8882
8883 wait_import_state() {
8884         local expected="$1"
8885         local params="$2"
8886         local maxtime=${3:-$(max_recovery_time)}
8887         local err_on_fail=${4:-1}
8888         local param
8889
8890         for param in ${params//,/ }; do
8891                 _wait_import_state "$expected" "$param" $maxtime $err_on_fail ||
8892                 return
8893         done
8894 }
8895
8896 wait_import_state_mount() {
8897         if ! is_mounted $MOUNT && ! is_mounted $MOUNT2; then
8898                 return 0
8899         fi
8900
8901         wait_import_state "$@"
8902 }
8903
8904 # One client request could be timed out because server was not ready
8905 # when request was sent by client.
8906 # The request timeout calculation details :
8907 # ptl_send_rpc ()
8908 #      /* We give the server rq_timeout secs to process the req, and
8909 #      add the network latency for our local timeout. */
8910 #      request->rq_deadline = request->rq_sent + request->rq_timeout +
8911 #           ptlrpc_at_get_net_latency(request) ;
8912 #
8913 # ptlrpc_connect_import ()
8914 #      request->rq_timeout = INITIAL_CONNECT_TIMEOUT
8915 #
8916 # init_imp_at () ->
8917 #   -> at_init(&at->iat_net_latency, 0, 0) -> iat_net_latency=0
8918 # ptlrpc_at_get_net_latency(request) ->
8919 #       at_get (max (iat_net_latency=0, at_min)) = at_min
8920 #
8921 # i.e.:
8922 # request->rq_timeout + ptlrpc_at_get_net_latency(request) =
8923 # INITIAL_CONNECT_TIMEOUT + at_min
8924 #
8925 # We will use obd_timeout instead of INITIAL_CONNECT_TIMEOUT
8926 # because we can not get this value in runtime,
8927 # the value depends on configure options, and it is not stored in /proc.
8928 # obd_support.h:
8929 # #define CONNECTION_SWITCH_MIN 5U
8930 # #define INITIAL_CONNECT_TIMEOUT max(CONNECTION_SWITCH_MIN,obd_timeout/20)
8931
8932 request_timeout () {
8933         local facet=$1
8934
8935         # request->rq_timeout = INITIAL_CONNECT_TIMEOUT
8936         local init_connect_timeout=$TIMEOUT
8937         [[ $init_connect_timeout -ge 5 ]] || init_connect_timeout=5
8938
8939         local at_min=$(at_get $facet at_min)
8940
8941         echo $(( init_connect_timeout + at_min ))
8942 }
8943
8944 _wait_osc_import_state() {
8945         local facet=$1
8946         local ost_facet=$2
8947         local expected=$3
8948         local target=$(get_osc_import_name $facet $ost_facet)
8949         local param="os[cp].${target}.ost_server_uuid"
8950         local params=$param
8951         local i=0
8952
8953         # 1. wait the deadline of client 1st request (it could be skipped)
8954         # 2. wait the deadline of client 2nd request
8955         local maxtime=$(( 2 * $(request_timeout $facet)))
8956
8957         if [[ $facet == client* ]]; then
8958                 # During setup time, the osc might not be setup, it need wait
8959                 # until list_param can return valid value.
8960                 params=$($LCTL list_param $param 2>/dev/null | head -1)
8961                 while [ -z "$params" ]; do
8962                         if [ $i -ge $maxtime ]; then
8963                                 echo "can't get $param in $maxtime secs"
8964                                 return 1
8965                         fi
8966                         sleep 1
8967                         i=$((i + 1))
8968                         params=$($LCTL list_param $param 2>/dev/null | head -1)
8969                 done
8970         fi
8971
8972         if [[ $ost_facet = mds* ]]; then
8973                 # no OSP connection to itself
8974                 if [[ $facet = $ost_facet ]]; then
8975                         return 0
8976                 fi
8977                 param="osp.${target}.mdt_server_uuid"
8978                 params=$param
8979         fi
8980
8981         local plist=$(comma_list $params)
8982         if ! do_rpc_nodes "$(facet_active_host $facet)" \
8983                         wait_import_state $expected $plist $maxtime; then
8984                 error "$facet: import is not in $expected state after $maxtime"
8985                 return 1
8986         fi
8987
8988         return 0
8989 }
8990
8991 wait_osc_import_state() {
8992         local facet=$1
8993         local ost_facet=$2
8994         local expected=$3
8995         local num
8996
8997         if [[ $facet = mds ]]; then
8998                 for num in $(seq $MDSCOUNT); do
8999                         _wait_osc_import_state mds$num "$ost_facet" "$expected"
9000                 done
9001         else
9002                 _wait_osc_import_state "$facet" "$ost_facet" "$expected"
9003         fi
9004 }
9005
9006 wait_osc_import_ready() {
9007         wait_osc_import_state $1 $2 "\(FULL\|IDLE\)"
9008 }
9009
9010 _wait_mgc_import_state() {
9011         local facet=$1
9012         local expected=$2
9013         local error_on_failure=${3:-1}
9014         local param="mgc.*.mgs_server_uuid"
9015         local params=$param
9016         local i=0
9017
9018         # 1. wait the deadline of client 1st request (it could be skipped)
9019         # 2. wait the deadline of client 2nd request
9020         local maxtime=$(( 2 * $(request_timeout $facet)))
9021
9022         if [[ $facet == client* ]]; then
9023                 # During setup time, the osc might not be setup, it need wait
9024                 # until list_param can return valid value. And also if there
9025                 # are mulitple osc entries we should list all of them before
9026                 # go to wait.
9027                 params=$($LCTL list_param $param 2>/dev/null || true)
9028                 while [ -z "$params" ]; do
9029                         if [ $i -ge $maxtime ]; then
9030                                 echo "can't get $param in $maxtime secs"
9031                                 return 1
9032                         fi
9033                         sleep 1
9034                         i=$((i + 1))
9035                         params=$($LCTL list_param $param 2>/dev/null || true)
9036                 done
9037         fi
9038         local plist=$(comma_list $params)
9039         if ! do_rpc_nodes "$(facet_active_host $facet)" \
9040                         wait_import_state $expected $plist $maxtime \
9041                                           $error_on_failure; then
9042                 if [ $error_on_failure -ne 0 ]; then
9043                     error "import is not in ${expected} state"
9044                 fi
9045                 return 1
9046         fi
9047
9048         return 0
9049 }
9050
9051 wait_mgc_import_state() {
9052         local facet=$1
9053         local expected=$2
9054         local error_on_failure=${3:-1}
9055         local num
9056
9057         if [[ $facet = mds ]]; then
9058                 for num in $(seq $MDSCOUNT); do
9059                         _wait_mgc_import_state mds$num "$expected" \
9060                                                $error_on_failure || return
9061                 done
9062         else
9063                 _wait_mgc_import_state "$facet" "$expected" \
9064                                        $error_on_failure || return
9065         fi
9066 }
9067
9068 wait_osp_import() {
9069         local facet=$1
9070         local remtgt=$(facet_svc $2)
9071         local expected=$3
9072         local loctgt=$(facet_svc $facet)
9073         local param="osp.$remtgt-os[pc]-${loctgt#*-}.*_server_uuid"
9074
9075         do_rpc_nodes "$(facet_active_host $facet)" \
9076                         wait_import_state $expected $param ||
9077                 error "$param: import is not in expected state"
9078 }
9079
9080 wait_dne_interconnect() {
9081         local num
9082
9083         if [ $MDSCOUNT -gt 1 ]; then
9084                 for num in $(seq $MDSCOUNT); do
9085                         wait_osc_import_ready mds mds$num
9086                 done
9087         fi
9088 }
9089
9090 get_clientmdc_proc_path() {
9091     echo "${1}-mdc-*"
9092 }
9093
9094 get_clientmgc_proc_path() {
9095     echo "*"
9096 }
9097
9098 do_rpc_nodes () {
9099         local quiet
9100
9101         [[ "$1" == "--quiet" || "$1" == "-q" ]] && quiet="$1" && shift
9102
9103         local list=$1
9104         shift
9105
9106         [ -z "$list" ] && return 0
9107
9108         # Add paths to lustre tests for 32 and 64 bit systems.
9109         local LIBPATH="/usr/lib/lustre/tests:/usr/lib64/lustre/tests:"
9110         local TESTPATH="$RLUSTRE/tests:"
9111         local RPATH="PATH=${TESTPATH}${LIBPATH}${PATH}:/sbin:/bin:/usr/sbin:"
9112         do_nodes ${quiet:-"--verbose"} $list "${RPATH} NAME=${NAME} \
9113                 TESTLOG_PREFIX=$TESTLOG_PREFIX TESTNAME=$TESTNAME \
9114                 CONFIG=${CONFIG} bash rpc.sh $* "
9115 }
9116
9117 wait_clients_import_state () {
9118         local list="$1"
9119         local facet="$2"
9120         local expected="$3"
9121         local facets="$facet"
9122
9123         if [ "$FAILURE_MODE" = HARD ]; then
9124                 facets=$(for f in ${facet//,/ }; do
9125                         facets_on_host $(facet_active_host $f) | tr "," "\n"
9126                 done | sort -u | paste -sd , )
9127         fi
9128
9129         for facet in ${facets//,/ }; do
9130                 local label=$(convert_facet2label $facet)
9131                 local proc_path
9132                 case $facet in
9133                 ost* ) proc_path="osc.$(get_clientosc_proc_path \
9134                                         $label).ost_server_uuid" ;;
9135                 mds* ) proc_path="mdc.$(get_clientmdc_proc_path \
9136                                         $label).mds_server_uuid" ;;
9137                 mgs* ) proc_path="mgc.$(get_clientmgc_proc_path \
9138                                         $label).mgs_server_uuid" ;;
9139                 *) error "unknown facet!" ;;
9140                 esac
9141
9142                 local params=$(expand_list $params $proc_path)
9143         done
9144
9145         if ! do_rpc_nodes "$list" wait_import_state_mount "$expected" $params;
9146         then
9147                 error "import is not in ${expected} state"
9148                 return 1
9149         fi
9150 }
9151
9152 wait_clients_import_ready() {
9153         wait_clients_import_state "$1" "$2" "\(FULL\|IDLE\)"
9154 }
9155
9156 import_param() {
9157         local tgt=$1
9158         local param=$2
9159
9160         $LCTL get_param osc.$tgt.import | awk "/$param/ { print \$2 }"
9161 }
9162
9163 wait_osp_active() {
9164         local facet=$1
9165         local tgt_name=$2
9166         local tgt_idx=$3
9167         local expected=$4
9168         local num
9169         local max=30
9170         local wait=0
9171
9172         # wait until all MDTs are in the expected state
9173         for ((num = 1; num <= $MDSCOUNT; num++)); do
9174                 local mdtosp=$(get_mdtosc_proc_path mds${num} ${tgt_name})
9175                 local mproc
9176
9177                 if [ $facet = "mds" ]; then
9178                         mproc="osp.$mdtosp.active"
9179                         [ $num -eq $((tgt_idx + 1)) ] && continue
9180                 else
9181                         mproc="osc.$mdtosp.active"
9182                 fi
9183
9184                 while true; do
9185                         local val rc=0
9186
9187                         val=$(do_facet mds${num} "$LCTL get_param -n $mproc")
9188                         rc=$?
9189                         if (( rc != 0 )); then
9190                                 echo "Can't read $mproc (rc = $rc)"
9191                         elif [[ "$val" == "$expected" ]]; then
9192                                 echo "$mproc updated after $wait sec (got $val)"
9193                                 break
9194                         fi
9195
9196                         (( wait < max )) ||
9197                                 error "$tgt_name: wanted $expected got $val"
9198
9199                         echo "Waiting $((max - wait)) secs for $mproc"
9200                         sleep 5
9201                         (( wait += 5 ))
9202                 done
9203         done
9204 }
9205
9206 oos_full() {
9207         local -a availa
9208         local -a granta
9209         local -a totala
9210         local oscfull=1
9211         local osts=$(osts_nodes)
9212
9213         availa=($(do_nodes $osts "$LCTL get_param obdfilter.*.kbytesavail"))
9214         granta=($(do_nodes $osts "$LCTL get_param -n obdfilter.*.tot_granted"))
9215         totala=($(do_nodes $osts "$LCTL get_param -n obdfilter.*.kbytestotal"))
9216         for ((i=0; i<${#availa[@]}; i++)); do
9217                 local -a avail1=(${availa[$i]//=/ })
9218                 local -a total=(${totala[$i]//=/ })
9219                 local grant=$((${granta[$i]}/1024))
9220                 # allow 1% of total space in bavail because of delayed
9221                 # allocation with ZFS which might release some free space after
9222                 # txg commit.  For small devices, we set a mininum of 8MB
9223                 local limit=$((total / 100 + 8000))
9224
9225                 echo -n $(echo ${avail1[0]} | cut -d"." -f2) avl=${avail1[1]} \
9226                           grnt=$grant diff=$((avail1[1] - grant)) limit=${limit}
9227                 [ $((avail1[1] - grant)) -lt $limit ] && oscfull=0 &&
9228                         echo " FULL" || echo
9229         done
9230
9231         return $oscfull
9232 }
9233
9234 list_pool() {
9235         echo -e "$(do_facet $SINGLEMDS $LCTL pool_list $1 | sed '1d')"
9236 }
9237
9238 check_pool_not_exist() {
9239         local fsname=${1%%.*}
9240         local poolname=${1##$fsname.}
9241         [[ $# -ne 1 ]] && return 0
9242         [[ x$poolname = x ]] &&  return 0
9243         list_pool $fsname | grep -w $1 && return 1
9244         return 0
9245 }
9246
9247 create_pool() {
9248         local fsname=${1%%.*}
9249         local poolname=${1##$fsname.}
9250         local keep_pools=${2:-false}
9251         local mdscount=${3:-$MDSCOUNT}
9252         # can't pass an empty argument to destroy_test_pools
9253         local dtp_fsname=${fsname:-$FSNAME}
9254
9255         stack_trap "destroy_test_pools $dtp_fsname $mdscount" EXIT
9256         do_facet mgs lctl pool_new $1
9257         local RC=$?
9258         # get param should return err unless pool is created
9259         [[ $RC -ne 0 ]] && return $RC
9260
9261         for ((mds_id = 1; mds_id < $mdscount; mds_id++)); do
9262                 local mdt_id=$((mds_id-1))
9263                 local lodname=$fsname-MDT$(printf "%04x" $mdt_id)-mdtlov
9264                 wait_update_facet mds$mds_id \
9265                         "lctl get_param -n lod.$lodname.pools.$poolname \
9266                                 2>/dev/null || echo foo" "" ||
9267                         error "mds$mds_id: pool_new failed $1"
9268         done
9269         wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
9270                 2>/dev/null || echo foo" "" || error "pool_new failed $1"
9271
9272         $keep_pools || add_pool_to_list $1
9273         return $RC
9274 }
9275
9276 add_pool_to_list () {
9277         local fsname=${1%%.*}
9278         local poolname=${1##$fsname.}
9279
9280         local listvar=${fsname}_CREATED_POOLS
9281         local temp=${listvar}=$(expand_list ${!listvar} $poolname)
9282         eval export $temp
9283 }
9284
9285 remove_pool_from_list () {
9286         local fsname=${1%%.*}
9287         local poolname=${1##$fsname.}
9288
9289         local listvar=${fsname}_CREATED_POOLS
9290         local temp=${listvar}=$(exclude_items_from_list "${!listvar}" $poolname)
9291         eval export $temp
9292 }
9293
9294 # cleanup all pools exist on $FSNAME
9295 destroy_all_pools () {
9296         local i
9297         for i in $(list_pool $FSNAME); do
9298                 destroy_pool $i
9299         done
9300 }
9301
9302 destroy_pool_int() {
9303         local ost
9304         local OSTS=$(list_pool $1)
9305         for ost in $OSTS; do
9306                 do_facet mgs lctl pool_remove $1 $ost
9307         done
9308         wait_update_facet $SINGLEMDS "lctl pool_list $1 | wc -l" "1" ||
9309                 error "MDS: pool_list $1 failed"
9310         do_facet mgs lctl pool_destroy $1
9311 }
9312
9313 # <fsname>.<poolname> or <poolname>
9314 destroy_pool() {
9315         local fsname=${1%%.*}
9316         local poolname=${1##$fsname.}
9317         local mdscount=${2:-$MDSCOUNT}
9318
9319         [[ x$fsname = x$poolname ]] && fsname=$FSNAME
9320
9321         local RC
9322
9323         check_pool_not_exist $fsname.$poolname && return 0 || true
9324
9325         destroy_pool_int $fsname.$poolname
9326         RC=$?
9327         [[ $RC -ne 0 ]] && return $RC
9328         for ((mds_id = 1; mds_id < $mdscount; mds_id++)); do
9329                 local mdt_id=$((mds_id-1))
9330                 local lodname=$fsname-MDT$(printf "%04x" $mdt_id)-mdtlov
9331                 wait_update_facet mds$mds_id \
9332                         "lctl get_param -n lod.$lodname.pools.$poolname \
9333                                 2>/dev/null || echo foo" "foo" ||
9334                         error "mds$mds_id: destroy pool failed $1"
9335         done
9336         wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
9337                 2>/dev/null || echo foo" "foo" || error "destroy pool failed $1"
9338
9339         remove_pool_from_list $fsname.$poolname
9340
9341         return $RC
9342 }
9343
9344 destroy_pools () {
9345         local fsname=${1:-$FSNAME}
9346         local mdscount=${2:-$MDSCOUNT}
9347         local poolname
9348         local listvar=${fsname}_CREATED_POOLS
9349
9350         [ x${!listvar} = x ] && return 0
9351
9352         echo "Destroy the created pools: ${!listvar}"
9353         for poolname in ${!listvar//,/ }; do
9354                 destroy_pool $fsname.$poolname $mdscount
9355         done
9356 }
9357
9358 destroy_test_pools () {
9359         local fsname=${1:-$FSNAME}
9360         local mdscount=${2:-$MDSCOUNT}
9361
9362         destroy_pools $fsname $mdscount || true
9363 }
9364
9365 gather_logs () {
9366         local list=$1
9367
9368         local ts=$(date +%s)
9369         local docp=true
9370
9371         if [[ ! -f "$YAML_LOG" ]]; then
9372                 # init_logging is not performed before gather_logs,
9373                 # so the $LOGDIR needs to be checked here
9374                 check_shared_dir $LOGDIR && touch $LOGDIR/shared
9375         fi
9376
9377         [ -f $LOGDIR/shared ] && docp=false
9378
9379         # dump lustre logs, dmesg, and journal if GSS_SK=true
9380
9381         prefix="$TESTLOG_PREFIX.$TESTNAME"
9382         suffix="$ts.log"
9383         echo "Dumping lctl log to ${prefix}.*.${suffix}"
9384
9385         if [ -n "$CLIENTONLY" -o "$PDSH" == "no_dsh" ]; then
9386                 echo "Dumping logs only on local client."
9387                 $LCTL dk > ${prefix}.debug_log.$(hostname -s).${suffix}
9388                 dmesg > ${prefix}.dmesg.$(hostname -s).${suffix}
9389                 [ "$SHARED_KEY" = true ] && find $SK_PATH -name '*.key' -exec \
9390                         $LGSS_SK -r {} \; &> \
9391                         ${prefix}.ssk_keys.$(hostname -s).${suffix}
9392                 [ "$SHARED_KEY" = true ] && lctl get_param 'nodemap.*.*' > \
9393                         ${prefix}.nodemaps.$(hostname -s).${suffix}
9394                 [ "$GSS" = true ] && keyctl show > \
9395                         ${prefix}.keyring.$(hostname -s).${suffix}
9396                 [ "$GSS" = true ] && journalctl -a > \
9397                         ${prefix}.journal.$(hostname -s).${suffix}
9398                 return
9399         fi
9400
9401         do_nodesv $list \
9402                 "$LCTL dk > ${prefix}.debug_log.\\\$(hostname -s).${suffix};
9403                 dmesg > ${prefix}.dmesg.\\\$(hostname -s).${suffix}"
9404         if [ "$SHARED_KEY" = true ]; then
9405                 do_nodesv $list "find $SK_PATH -name '*.key' -exec \
9406                         $LGSS_SK -r {} \; &> \
9407                         ${prefix}.ssk_keys.\\\$(hostname -s).${suffix}"
9408                 do_facet mds1 "lctl get_param 'nodemap.*.*' > \
9409                         ${prefix}.nodemaps.\\\$(hostname -s).${suffix}"
9410         fi
9411         if [ "$GSS" = true ]; then
9412                 do_nodesv $list "keyctl show > \
9413                         ${prefix}.keyring.\\\$(hostname -s).${suffix}"
9414                 do_nodesv $list "journalctl -a > \
9415                         ${prefix}.journal.\\\$(hostname -s).${suffix}"
9416         fi
9417
9418         if [ ! -f $LOGDIR/shared ]; then
9419                 local remote_nodes=$(exclude_items_from_list $list $HOSTNAME)
9420
9421                 for node in ${remote_nodes//,/ }; do
9422                         rsync -az -e ssh $node:${prefix}.'*'.${suffix} $LOGDIR &
9423                 done
9424         fi
9425 }
9426
9427 do_ls () {
9428         local mntpt_root=$1
9429         local num_mntpts=$2
9430         local dir=$3
9431         local i
9432         local cmd
9433         local pids
9434         local rc=0
9435
9436         for i in $(seq 0 $num_mntpts); do
9437                 cmd="ls -laf ${mntpt_root}$i/$dir"
9438                 echo + $cmd;
9439                 $cmd > /dev/null &
9440                 pids="$pids $!"
9441         done
9442         echo pids=$pids
9443         for pid in $pids; do
9444                 wait $pid || rc=$?
9445         done
9446
9447         return $rc
9448 }
9449
9450 # check_and_start_recovery_timer()
9451 #       service_time = at_est2timeout(service_time);
9452 #       service_time += 2 * INITIAL_CONNECT_TIMEOUT;
9453 #       service_time += 2 * (CONNECTION_SWITCH_MAX + CONNECTION_SWITCH_INC);
9454
9455 #define INITIAL_CONNECT_TIMEOUT max(CONNECTION_SWITCH_MIN, obd_timeout/20)
9456 #define CONNECTION_SWITCH_MAX min(50, max(CONNECTION_SWITCH_MIN, obd_timeout))
9457 #define CONNECTION_SWITCH_MIN 5
9458 #define CONNECTION_SWITCH_INC 5
9459 max_recovery_time() {
9460         local init_connect_timeout=$((TIMEOUT / 20))
9461         ((init_connect_timeout >= 5)) || init_connect_timeout=5
9462
9463         local service_time=$(($(at_max_get client) * 9 / 4 + 5))
9464         service_time=$((service_time + 2 * (init_connect_timeout + 50 + 5)))
9465
9466         echo -n $service_time
9467 }
9468
9469 recovery_time_min() {
9470         local connection_switch_min=5
9471         local connection_switch_inc=5
9472         local connection_switch_max
9473         local reconnect_delay_max
9474         local initial_connect_timeout
9475         local max
9476         local timout_20
9477
9478         #connection_switch_max=min(50, max($connection_switch_min,$TIMEOUT)
9479         (($connection_switch_min > $TIMEOUT)) &&
9480                 max=$connection_switch_min || max=$TIMEOUT
9481         (($max < 50)) && connection_switch_max=$max || connection_switch_max=50
9482
9483         #initial_connect_timeout = max(connection_switch_min, obd_timeout/20)
9484         timeout_20=$((TIMEOUT/20))
9485         (($connection_switch_min > $timeout_20)) &&
9486                 initial_connect_timeout=$connection_switch_min ||
9487                 initial_connect_timeout=$timeout_20
9488
9489         reconnect_delay_max=$((connection_switch_max + connection_switch_inc +
9490                                initial_connect_timeout))
9491         echo $((2 * reconnect_delay_max))
9492 }
9493
9494 get_clients_mount_count () {
9495         local clients=${CLIENTS:-$HOSTNAME}
9496
9497         # we need to take into account the clients mounts and
9498         # exclude mds/ost mounts if any;
9499         do_nodes $clients cat /proc/mounts | grep lustre |
9500                 grep -w $MOUNT | wc -l
9501 }
9502
9503 # gss functions
9504 PROC_CLI="srpc_info"
9505 PROC_CON="srpc_contexts"
9506
9507 combination()
9508 {
9509         local M=$1
9510         local N=$2
9511         local R=1
9512
9513         if [ $M -lt $N ]; then
9514                 R=0
9515         else
9516                 N=$((N + 1))
9517                 while [ $N -lt $M ]; do
9518                         R=$((R * N))
9519                         N=$((N + 1))
9520                 done
9521         fi
9522
9523         echo $R
9524         return 0
9525 }
9526
9527 calc_connection_cnt() {
9528         local dir=$1
9529
9530         # MDT->MDT = 2 * C(M, 2)
9531         # MDT->OST = M * O
9532         # CLI->OST = C * O
9533         # CLI->MDT = C * M
9534         comb_m2=$(combination $MDSCOUNT 2)
9535
9536         local num_clients=$(get_clients_mount_count)
9537
9538         local cnt_mdt2mdt=$((comb_m2 * 2))
9539         local cnt_mdt2ost=$((MDSCOUNT * OSTCOUNT))
9540         local cnt_cli2ost=$((num_clients * OSTCOUNT))
9541         local cnt_cli2mdt=$((num_clients * MDSCOUNT))
9542         if is_mounted $MOUNT2; then
9543                 cnt_cli2mdt=$((cnt_cli2mdt * 2))
9544                 cnt_cli2ost=$((cnt_cli2ost * 2))
9545         fi
9546         if local_mode; then
9547                 cnt_mdt2mdt=0
9548                 cnt_mdt2ost=0
9549                 cnt_cli2ost=2
9550                 cnt_cli2mdt=1
9551         fi
9552         local cnt_all2ost=$((cnt_mdt2ost + cnt_cli2ost))
9553         local cnt_all2mdt=$((cnt_mdt2mdt + cnt_cli2mdt))
9554         local cnt_all2all=$((cnt_mdt2ost + cnt_mdt2mdt \
9555                 + cnt_cli2ost + cnt_cli2mdt))
9556
9557         local var=cnt_$dir
9558         local res=${!var}
9559
9560         echo $res
9561 }
9562
9563 set_rule()
9564 {
9565         local tgt=$1
9566         local net=$2
9567         local dir=$3
9568         local flavor=$4
9569         local cmd="$tgt.srpc.flavor"
9570
9571         if [ $net == "any" ]; then
9572                 net="default"
9573         fi
9574         cmd="$cmd.$net"
9575
9576         if [ $dir != "any" ]; then
9577                 cmd="$cmd.$dir"
9578         fi
9579
9580         cmd="$cmd=$flavor"
9581         log "Setting sptlrpc rule: $cmd"
9582         do_facet mgs "$LCTL conf_param $cmd"
9583 }
9584
9585 count_contexts()
9586 {
9587         local output=$1
9588         local total_ctx=$(echo "$output" | grep -c "expire.*key.*hdl")
9589         echo $total_ctx
9590 }
9591
9592 count_flvr()
9593 {
9594         local output=$1
9595         local flavor=$2
9596         local count=0
9597
9598         rpc_flvr=`echo $flavor | awk -F - '{ print $1 }'`
9599         bulkspec=`echo $flavor | awk -F - '{ print $2 }'`
9600
9601         count=`echo "$output" | grep "rpc flavor" | grep $rpc_flvr | wc -l`
9602
9603         if [ "x$bulkspec" != "x" ]; then
9604                 algs=`echo $bulkspec | awk -F : '{ print $2 }'`
9605
9606                 if [ "x$algs" != "x" ]; then
9607                         bulk_count=`echo "$output" | grep "bulk flavor" |
9608                                 grep $algs | wc -l`
9609                 else
9610                         bulk=`echo $bulkspec | awk -F : '{ print $1 }'`
9611
9612                         if [ $bulk == "bulkn" ]; then
9613                                 bulk_count=`echo "$output" |
9614                                         grep "bulk flavor" | grep "null/null" |
9615                                         wc -l`
9616                         elif [ $bulk == "bulki" ]; then
9617                                 bulk_count=`echo "$output" |
9618                                         grep "bulk flavor" | grep "/null" |
9619                                         grep -v "null/" | wc -l`
9620                         else
9621                                 bulk_count=`echo "$output" |
9622                                         grep "bulk flavor" | grep -v "/null" |
9623                                         grep -v "null/" | wc -l`
9624                         fi
9625                 fi
9626                 [ $bulk_count -lt $count ] && count=$bulk_count
9627         fi
9628
9629         echo $count
9630 }
9631
9632 flvr_cnt_cli2mdt()
9633 {
9634         local flavor=$1
9635         local cnt
9636
9637         local clients=${CLIENTS:-$HOSTNAME}
9638
9639         for c in ${clients//,/ }; do
9640                 local output=$(do_node $c lctl get_param -n \
9641                          mdc.*-*-mdc-*.$PROC_CLI 2>/dev/null)
9642                 local tmpcnt=$(count_flvr "$output" $flavor)
9643
9644                 if $GSS_SK && [ $flavor != "null" ]; then
9645                         # tmpcnt=min(contexts,flavors) to ensure SK context is
9646                         # on
9647                         output=$(do_node $c lctl get_param -n \
9648                                  mdc.*-MDT*-mdc-*.$PROC_CON 2>/dev/null)
9649                         local outcon=$(count_contexts "$output")
9650
9651                         if [ "$outcon" -lt "$tmpcnt" ]; then
9652                                 tmpcnt=$outcon
9653                         fi
9654                 fi
9655                 cnt=$((cnt + tmpcnt))
9656         done
9657         echo $cnt
9658 }
9659
9660 flvr_dump_cli2mdt()
9661 {
9662         local clients=${CLIENTS:-$HOSTNAME}
9663
9664         for c in ${clients//,/ }; do
9665                 do_node $c lctl get_param \
9666                          mdc.*-*-mdc-*.$PROC_CLI 2>/dev/null
9667
9668                 if $GSS_SK; then
9669                         do_node $c lctl get_param \
9670                                  mdc.*-MDT*-mdc-*.$PROC_CON 2>/dev/null
9671                 fi
9672         done
9673 }
9674
9675 flvr_cnt_cli2ost()
9676 {
9677         local flavor=$1
9678         local cnt
9679
9680         local clients=${CLIENTS:-$HOSTNAME}
9681
9682         for c in ${clients//,/ }; do
9683                 # reconnect if idle
9684                 do_node $c lctl set_param osc.*.idle_connect=1 >/dev/null 2>&1
9685                 local output=$(do_node $c lctl get_param -n \
9686                          osc.*OST*-osc-[^M][^D][^T]*.$PROC_CLI 2>/dev/null)
9687                 local tmpcnt=$(count_flvr "$output" $flavor)
9688
9689                 if $GSS_SK && [ $flavor != "null" ]; then
9690                         # tmpcnt=min(contexts,flavors) to ensure SK context is on
9691                         output=$(do_node $c lctl get_param -n \
9692                                  osc.*OST*-osc-[^M][^D][^T]*.$PROC_CON 2>/dev/null)
9693                         local outcon=$(count_contexts "$output")
9694
9695                         if [ "$outcon" -lt "$tmpcnt" ]; then
9696                                 tmpcnt=$outcon
9697                         fi
9698                 fi
9699                 cnt=$((cnt + tmpcnt))
9700         done
9701         echo $cnt
9702 }
9703
9704 flvr_dump_cli2ost()
9705 {
9706         local clients=${CLIENTS:-$HOSTNAME}
9707
9708         for c in ${clients//,/ }; do
9709                 do_node $c lctl get_param \
9710                         osc.*OST*-osc-[^M][^D][^T]*.$PROC_CLI 2>/dev/null
9711
9712                 if $GSS_SK; then
9713                         do_node $c lctl get_param \
9714                                osc.*OST*-osc-[^M][^D][^T]*.$PROC_CON 2>/dev/null
9715                 fi
9716         done
9717 }
9718
9719 flvr_cnt_mdt2mdt()
9720 {
9721         local flavor=$1
9722         local cnt=0
9723
9724         if [ $MDSCOUNT -le 1 ]; then
9725                 echo 0
9726                 return
9727         fi
9728
9729         for num in `seq $MDSCOUNT`; do
9730                 local output=$(do_facet mds$num lctl get_param -n \
9731                         osp.*-MDT*osp-MDT*.$PROC_CLI 2>/dev/null)
9732                 local tmpcnt=$(count_flvr "$output" $flavor)
9733
9734                 if $GSS_SK && [ $flavor != "null" ]; then
9735                         # tmpcnt=min(contexts,flavors) to ensure SK context is on
9736                         output=$(do_facet mds$num lctl get_param -n \
9737                                 osp.*-MDT*osp-MDT*.$PROC_CON 2>/dev/null)
9738                         local outcon=$(count_contexts "$output")
9739
9740                         if [ "$outcon" -lt "$tmpcnt" ]; then
9741                                 tmpcnt=$outcon
9742                         fi
9743                 fi
9744                 cnt=$((cnt + tmpcnt))
9745         done
9746         echo $cnt;
9747 }
9748
9749 flvr_dump_mdt2mdt()
9750 {
9751         for num in `seq $MDSCOUNT`; do
9752                 do_facet mds$num lctl get_param \
9753                         osp.*-MDT*osp-MDT*.$PROC_CLI 2>/dev/null
9754
9755                 if $GSS_SK; then
9756                         do_facet mds$num lctl get_param \
9757                                 osp.*-MDT*osp-MDT*.$PROC_CON 2>/dev/null
9758                 fi
9759         done
9760 }
9761
9762 flvr_cnt_mdt2ost()
9763 {
9764         local flavor=$1
9765         local cnt=0
9766         local mdtosc
9767
9768         for num in `seq $MDSCOUNT`; do
9769                 mdtosc=$(get_mdtosc_proc_path mds$num)
9770                 mdtosc=${mdtosc/-MDT*/-MDT\*}
9771                 local output=$(do_facet mds$num lctl get_param -n \
9772                                 os[cp].$mdtosc.$PROC_CLI 2>/dev/null)
9773                 # Ensure SK context is on
9774                 local tmpcnt=$(count_flvr "$output" $flavor)
9775
9776                 if $GSS_SK && [ $flavor != "null" ]; then
9777                         output=$(do_facet mds$num lctl get_param -n \
9778                                  os[cp].$mdtosc.$PROC_CON 2>/dev/null)
9779                         local outcon=$(count_contexts "$output")
9780
9781                         if [ "$outcon" -lt "$tmpcnt" ]; then
9782                                 tmpcnt=$outcon
9783                         fi
9784                 fi
9785                 cnt=$((cnt + tmpcnt))
9786         done
9787         echo $cnt;
9788 }
9789
9790 flvr_dump_mdt2ost()
9791 {
9792         for num in `seq $MDSCOUNT`; do
9793                 mdtosc=$(get_mdtosc_proc_path mds$num)
9794                 mdtosc=${mdtosc/-MDT*/-MDT\*}
9795                 do_facet mds$num lctl get_param \
9796                                 os[cp].$mdtosc.$PROC_CLI 2>/dev/null
9797
9798                 if $GSS_SK; then
9799                         do_facet mds$num lctl get_param \
9800                                 os[cp].$mdtosc.$PROC_CON 2>/dev/null
9801                 fi
9802         done
9803 }
9804
9805 flvr_cnt_mgc2mgs()
9806 {
9807         local flavor=$1
9808
9809         local output=$(do_facet client lctl get_param -n mgc.*.$PROC_CLI \
9810                         2>/dev/null)
9811         count_flvr "$output" $flavor
9812 }
9813
9814 do_check_flavor()
9815 {
9816         local dir=$1        # from to
9817         local flavor=$2     # flavor expected
9818         local res=0
9819
9820         if [ $dir == "cli2mdt" ]; then
9821                 res=`flvr_cnt_cli2mdt $flavor`
9822         elif [ $dir == "cli2ost" ]; then
9823                 res=`flvr_cnt_cli2ost $flavor`
9824         elif [ $dir == "mdt2mdt" ]; then
9825                 res=`flvr_cnt_mdt2mdt $flavor`
9826         elif [ $dir == "mdt2ost" ]; then
9827                 res=`flvr_cnt_mdt2ost $flavor`
9828         elif [ $dir == "all2ost" ]; then
9829                 res1=`flvr_cnt_mdt2ost $flavor`
9830                 res2=`flvr_cnt_cli2ost $flavor`
9831                 res=$((res1 + res2))
9832         elif [ $dir == "all2mdt" ]; then
9833                 res1=`flvr_cnt_mdt2mdt $flavor`
9834                 res2=`flvr_cnt_cli2mdt $flavor`
9835                 res=$((res1 + res2))
9836         elif [ $dir == "all2all" ]; then
9837                 res1=`flvr_cnt_mdt2ost $flavor`
9838                 res2=`flvr_cnt_cli2ost $flavor`
9839                 res3=`flvr_cnt_mdt2mdt $flavor`
9840                 res4=`flvr_cnt_cli2mdt $flavor`
9841                 res=$((res1 + res2 + res3 + res4))
9842         fi
9843
9844         echo $res
9845 }
9846
9847 do_dump_imp_state()
9848 {
9849         local clients=${CLIENTS:-$HOSTNAME}
9850         local type=$1
9851
9852         for c in ${clients//,/ }; do
9853                 [ "$type" == "osc" ] &&
9854                         do_node $c lctl get_param osc.*.idle_timeout
9855                 do_node $c lctl get_param $type.*.import |
9856                         grep -E "name:|state:"
9857         done
9858 }
9859
9860 do_dump_flavor()
9861 {
9862         local dir=$1        # from to
9863
9864         if [ $dir == "cli2mdt" ]; then
9865                 do_dump_imp_state mdc
9866                 flvr_dump_cli2mdt
9867         elif [ $dir == "cli2ost" ]; then
9868                 do_dump_imp_state osc
9869                 flvr_dump_cli2ost
9870         elif [ $dir == "mdt2mdt" ]; then
9871                 flvr_dump_mdt2mdt
9872         elif [ $dir == "mdt2ost" ]; then
9873                 flvr_dump_mdt2ost
9874         elif [ $dir == "all2ost" ]; then
9875                 flvr_dump_mdt2ost
9876                 do_dump_imp_state osc
9877                 flvr_dump_cli2ost
9878         elif [ $dir == "all2mdt" ]; then
9879                 flvr_dump_mdt2mdt
9880                 do_dump_imp_state mdc
9881                 flvr_dump_cli2mdt
9882         elif [ $dir == "all2all" ]; then
9883                 flvr_dump_mdt2ost
9884                 do_dump_imp_state osc
9885                 flvr_dump_cli2ost
9886                 flvr_dump_mdt2mdt
9887                 do_dump_imp_state mdc
9888                 flvr_dump_cli2mdt
9889         fi
9890 }
9891
9892 wait_flavor()
9893 {
9894         local dir=$1        # from to
9895         local flavor=$2     # flavor expected
9896         local expect=${3:-$(calc_connection_cnt $dir)} # number expected
9897         local WAITFLAVOR_MAX=20 # how many retries before abort?
9898
9899         local res=0
9900         for ((i = 0; i < $WAITFLAVOR_MAX; i++)); do
9901                 echo -n "checking $dir..."
9902                 res=$(do_check_flavor $dir $flavor)
9903                 echo "found $res/$expect $flavor connections"
9904                 [ $res -ge $expect ] && return 0
9905                 sleep 4
9906         done
9907
9908         echo "Error checking $flavor of $dir: expect $expect, actual $res"
9909         do_nodes $(comma_list $(all_server_nodes)) "keyctl show"
9910         do_dump_flavor $dir
9911         if $dump; then
9912                 gather_logs $(comma_list $(nodes_list))
9913         fi
9914         return 1
9915 }
9916
9917 restore_to_default_flavor()
9918 {
9919         local proc="mgs.MGS.live.$FSNAME"
9920
9921         echo "restoring to default flavor..."
9922
9923         local nrule=$(do_facet mgs lctl get_param -n $proc 2>/dev/null |
9924                 grep ".srpc.flavor" | wc -l)
9925
9926         # remove all existing rules if any
9927         if [ $nrule -ne 0 ]; then
9928                 echo "$nrule existing rules"
9929                 for rule in $(do_facet mgs lctl get_param -n $proc 2>/dev/null |
9930                     grep ".srpc.flavor."); do
9931                         echo "remove rule: $rule"
9932                         spec=`echo $rule | awk -F = '{print $1}'`
9933                         do_facet mgs "$LCTL conf_param -d $spec"
9934                 done
9935         fi
9936
9937         # verify no rules left
9938         nrule=$(do_facet mgs lctl get_param -n $proc 2>/dev/null |
9939                 grep ".srpc.flavor." | wc -l)
9940         [ $nrule -ne 0 ] && error "still $nrule rules left"
9941
9942         # wait for default flavor to be applied
9943         if $GSS_SK; then
9944                 if $SK_S2S; then
9945                         set_rule $FSNAME any any $SK_FLAVOR
9946                         wait_flavor all2all $SK_FLAVOR
9947                 else
9948                         set_rule $FSNAME any cli2mdt $SK_FLAVOR
9949                         set_rule $FSNAME any cli2ost $SK_FLAVOR
9950                         wait_flavor cli2mdt $SK_FLAVOR
9951                         wait_flavor cli2ost $SK_FLAVOR
9952                 fi
9953                 echo "GSS_SK now at default flavor: $SK_FLAVOR"
9954         else
9955                 wait_flavor all2all null
9956         fi
9957 }
9958
9959 set_flavor_all()
9960 {
9961         local flavor=${1:-null}
9962         local maxtime=$(( 2 * $(request_timeout client)))
9963         local clients=${CLIENTS:-$HOSTNAME}
9964
9965         echo "setting all flavor to $flavor"
9966
9967         # make sure all oscs are connected
9968         for c in ${clients//,/ }; do
9969                 do_node $c lfs df -h
9970                 do_rpc_nodes $c wait_import_state "FULL" \
9971                         "osc.*.ost_server_uuid" $maxtime ||
9972                 error "OSCs not in FULL state for client $c"
9973         done
9974
9975         # FIXME need parameter to this fn
9976         # and remove global vars
9977         local cnt_all2all=$(calc_connection_cnt all2all)
9978
9979         local res=$(do_check_flavor all2all $flavor)
9980         if [ $res -eq $cnt_all2all ]; then
9981                 echo "already have total $res $flavor connections"
9982                 return
9983         fi
9984
9985         echo "found $res $flavor out of total $cnt_all2all connections"
9986         restore_to_default_flavor
9987
9988         [[ $flavor = null ]] && return 0
9989
9990         if $GSS_SK && [ $flavor != "null" ]; then
9991                 if $SK_S2S; then
9992                         set_rule $FSNAME any any $flavor
9993                         wait_flavor all2all $flavor
9994                 else
9995                         set_rule $FSNAME any cli2mdt $flavor
9996                         set_rule $FSNAME any cli2ost $flavor
9997                         set_rule $FSNAME any mdt2ost null
9998                         set_rule $FSNAME any mdt2mdt null
9999                         wait_flavor cli2mdt $flavor
10000                         wait_flavor cli2ost $flavor
10001                 fi
10002                 echo "GSS_SK now at flavor: $flavor"
10003         else
10004                 set_rule $FSNAME any cli2mdt $flavor
10005                 set_rule $FSNAME any cli2ost $flavor
10006                 set_rule $FSNAME any mdt2ost null
10007                 set_rule $FSNAME any mdt2mdt null
10008                 wait_flavor cli2mdt $flavor
10009                 wait_flavor cli2ost $flavor
10010         fi
10011 }
10012
10013
10014 check_logdir() {
10015         local dir=$1
10016         # Checking for shared logdir
10017         if [ ! -d $dir ]; then
10018                 # Not found. Create local logdir
10019                 mkdir -p $dir
10020         else
10021                 touch $dir/check_file.$(hostname -s)
10022         fi
10023         return 0
10024 }
10025
10026 check_write_access() {
10027         local dir=$1
10028         local list=${2:-$(comma_list $(nodes_list))}
10029         local node
10030         local file
10031
10032         for node in ${list//,/ }; do
10033                 file=$dir/check_file.$(short_nodename $node)
10034                 if [[ ! -f "$file" ]]; then
10035                         # Logdir not accessible/writable from this node.
10036                         return 1
10037                 fi
10038                 rm -f $file || return 1
10039         done
10040         return 0
10041 }
10042
10043 init_logging() {
10044         [[ -n $YAML_LOG ]] && return
10045         local save_umask=$(umask)
10046         umask 0000
10047
10048         export YAML_LOG=${LOGDIR}/results.yml
10049         mkdir -p $LOGDIR
10050         init_clients_lists
10051
10052         # If the yaml log already exists then we will just append to it
10053         if [ ! -f $YAML_LOG ]; then
10054                 if check_shared_dir $LOGDIR; then
10055                         touch $LOGDIR/shared
10056                         echo "Logging to shared log directory: $LOGDIR"
10057                 else
10058                         echo "Logging to local directory: $LOGDIR"
10059                 fi
10060
10061                 yml_nodes_file $LOGDIR >> $YAML_LOG
10062                 yml_results_file >> $YAML_LOG
10063         fi
10064
10065         umask $save_umask
10066
10067         # log actual client and server versions if needed for debugging
10068         log "Client: $(lustre_build_version client)"
10069         log "MDS: $(lustre_build_version mds1)"
10070         log "OSS: $(lustre_build_version ost1)"
10071 }
10072
10073 log_test() {
10074         yml_log_test $1 >> $YAML_LOG
10075 }
10076
10077 log_test_status() {
10078         yml_log_test_status "$@" >> $YAML_LOG
10079 }
10080
10081 log_sub_test_begin() {
10082         yml_log_sub_test_begin "$@" >> $YAML_LOG
10083 }
10084
10085 log_sub_test_end() {
10086         yml_log_sub_test_end "$@" >> $YAML_LOG
10087 }
10088
10089 run_llverdev()
10090 {
10091         local dev=$1; shift
10092         local llverdev_opts="$*"
10093         local devname=$(basename $dev)
10094         local size=$(awk "/$devname$/ {print \$3}" /proc/partitions)
10095         # loop devices aren't in /proc/partitions
10096         [[ -z "$size" ]] && size=$(stat -c %s $dev)
10097
10098         local size_gb=$((size / 1024 / 1024)) # Gb
10099
10100         local partial_arg=""
10101         # Run in partial (fast) mode if the size of a partition > 1 GB
10102         (( $size == 0 || $size_gb > 1 )) && partial_arg="-p"
10103
10104         llverdev --force $partial_arg $llverdev_opts $dev
10105 }
10106
10107 run_llverfs()
10108 {
10109         local dir=$1
10110         local llverfs_opts=$2
10111         local use_partial_arg=$3
10112         local partial_arg=""
10113         local size=$(df -B G $dir |tail -n 1 |awk '{print $2}' |sed 's/G//') #GB
10114
10115         # Run in partial (fast) mode if the size of a partition > 1 GB
10116         [ "x$use_partial_arg" != "xno" ] && [ $size -gt 1 ] && partial_arg="-p"
10117
10118         llverfs $partial_arg $llverfs_opts $dir
10119 }
10120
10121 run_sgpdd () {
10122         local devs=${1//,/ }
10123         shift
10124         local params=$@
10125         local rslt=$TMP/sgpdd_survey
10126
10127         # sgpdd-survey cleanups ${rslt}.* files
10128
10129         local cmd="rslt=$rslt $params scsidevs=\"$devs\" $SGPDDSURVEY"
10130         echo + $cmd
10131         eval $cmd
10132         cat ${rslt}.detail
10133 }
10134
10135 # returns the canonical name for an ldiskfs device
10136 ldiskfs_canon() {
10137         local dev="$1"
10138         local facet="$2"
10139
10140         do_facet $facet "dv=\\\$($LCTL get_param -n $dev);
10141                          if foo=\\\$(lvdisplay -c \\\$dv 2>/dev/null); then
10142                                 echo dm-\\\${foo##*:};
10143                          else
10144                                 name=\\\$(basename \\\$dv);
10145                                 if [[ \\\$name = *flakey* ]]; then
10146                                         name=\\\$(lsblk -o NAME,KNAME |
10147                                                 awk /\\\$name/'{print \\\$NF}');
10148                                 fi;
10149                                 echo \\\$name;
10150                          fi;"
10151 }
10152
10153 is_sanity_benchmark() {
10154         local benchmarks="dbench bonnie iozone fsx"
10155         local suite=$1
10156
10157         for b in $benchmarks; do
10158                 if [ "$b" == "$suite" ]; then
10159                         return 0
10160                 fi
10161         done
10162         return 1
10163 }
10164
10165 min_ost_size () {
10166         $LFS df | grep OST | awk '{print $4}' | sort -un | head -1
10167 }
10168
10169 #
10170 # Get the available size (KB) of a given obd target.
10171 #
10172 get_obd_size() {
10173         local facet=$1
10174         local obd=$2
10175         local size
10176
10177         [[ $facet != client ]] || return 0
10178
10179         size=$(do_facet $facet $LCTL get_param -n *.$obd.kbytesavail | head -n1)
10180         echo -n $size
10181 }
10182
10183 #
10184 # Get the page size (bytes) on a given facet node.
10185 # The local client page_size is directly available in PAGE_SIZE.
10186 #
10187 get_page_size() {
10188         local facet=$1
10189         local page_size=$(getconf PAGE_SIZE 2>/dev/null)
10190
10191         [ -z "$CLIENTONLY" -a "$facet" != "client" ] &&
10192                 page_size=$(do_facet $facet getconf PAGE_SIZE)
10193         echo -n ${page_size:-4096}
10194 }
10195
10196 #
10197 # Get the block count of the filesystem.
10198 #
10199 get_block_count() {
10200         local facet=$1
10201         local device=$2
10202         local count
10203
10204         [ -z "$CLIENTONLY" ] &&
10205                 count=$(do_facet $facet "$DUMPE2FS -h $device 2>&1" |
10206                         awk '/^Block count:/ {print $3}')
10207         echo -n ${count:-0}
10208 }
10209
10210 # Check whether the "ea_inode" feature is enabled or not, to allow
10211 # ldiskfs xattrs over one block in size.  Allow both the historical
10212 # Lustre feature name (large_xattr) and the upstream name (ea_inode).
10213 large_xattr_enabled() {
10214         [[ $(facet_fstype $SINGLEMDS) == zfs ]] && return 0
10215
10216         local mds_dev=$(mdsdevname ${SINGLEMDS//mds/})
10217
10218         do_facet $SINGLEMDS "$DUMPE2FS -h $mds_dev 2>&1 |
10219                 grep -E -q '(ea_inode|large_xattr)'"
10220         return ${PIPESTATUS[0]}
10221 }
10222
10223 # Get the maximum xattr size supported by the filesystem.
10224 max_xattr_size() {
10225         $LCTL get_param -n llite.*.max_easize
10226 }
10227
10228 # Dump the value of the named xattr from a file.
10229 get_xattr_value() {
10230         local xattr_name=$1
10231         local file=$2
10232
10233         echo "$(getfattr -n $xattr_name --absolute-names --only-values $file)"
10234 }
10235
10236 # Generate a string with size of $size bytes.
10237 generate_string() {
10238         local size=${1:-1024} # in bytes
10239
10240         echo "$(head -c $size < /dev/zero | tr '\0' y)"
10241 }
10242
10243 reformat_external_journal() {
10244         local facet=$1
10245         local var
10246
10247         var=${facet}_JRN
10248         local varbs=${facet}_BLOCKSIZE
10249         if [ -n "${!var}" ]; then
10250                 local rcmd="do_facet $facet"
10251                 local bs=${!varbs:-$BLCKSIZE}
10252
10253                 bs="-b $bs"
10254                 echo "reformat external journal on $facet:${!var}"
10255                 ${rcmd} mke2fs -O journal_dev $bs ${!var} || return 1
10256         fi
10257 }
10258
10259 # MDT file-level backup/restore
10260 mds_backup_restore() {
10261         local facet=$1
10262         local igif=$2
10263         local devname=$(mdsdevname $(facet_number $facet))
10264         local mntpt=$(facet_mntpt brpt)
10265         local rcmd="do_facet $facet"
10266         local metadata=${TMP}/backup_restore.tgz
10267         local opts=${MDS_MOUNT_FS_OPTS}
10268         local svc=${facet}_svc
10269
10270         if ! ${rcmd} test -b ${devname}; then
10271                 opts=$(csa_add "$opts" -o loop)
10272         fi
10273
10274         echo "file-level backup/restore on $facet:${devname}"
10275
10276         # step 1: build mount point
10277         ${rcmd} mkdir -p $mntpt
10278         # step 2: cleanup old backup
10279         ${rcmd} rm -f $metadata
10280         # step 3: mount dev
10281         ${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 3
10282         if [ ! -z $igif ]; then
10283                 # step 3.5: rm .lustre
10284                 ${rcmd} rm -rf $mntpt/ROOT/.lustre || return 3
10285         fi
10286         # step 4: backup metadata
10287         echo "backup data"
10288         ${rcmd} tar zcf $metadata --xattrs --xattrs-include="trusted.*" \
10289                 --sparse -C $mntpt/ . > /dev/null 2>&1 || return 4
10290         # step 5: umount
10291         ${rcmd} $UMOUNT $mntpt || return 5
10292         # step 6: reformat dev
10293         echo "reformat new device"
10294         format_mdt $(facet_number $facet)
10295         # step 7: mount dev
10296         ${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 7
10297         # step 8: restore metadata
10298         echo "restore data"
10299         ${rcmd} tar zxfp $metadata --xattrs --xattrs-include="trusted.*" \
10300                 --sparse -C $mntpt > /dev/null 2>&1 || return 8
10301         # step 9: remove recovery logs
10302         echo "remove recovery logs"
10303         ${rcmd} rm -fv $mntpt/OBJECTS/* $mntpt/CATALOGS
10304         # step 10: umount dev
10305         ${rcmd} $UMOUNT $mntpt || return 10
10306         # step 11: cleanup tmp backup
10307         ${rcmd} rm -f $metaea $metadata
10308         # step 12: reset device label - it's not virgin on
10309         ${rcmd} e2label $devname ${!svc}
10310 }
10311
10312 # remove OI files
10313 mds_remove_ois() {
10314         local facet=$1
10315         local idx=$2
10316         local devname=$(mdsdevname $(facet_number $facet))
10317         local mntpt=$(facet_mntpt brpt)
10318         local rcmd="do_facet $facet"
10319         local opts=${MDS_MOUNT_FS_OPTS}
10320
10321         if ! ${rcmd} test -b ${devname}; then
10322                 opts=$(csa_add "$opts" -o loop)
10323         fi
10324
10325         echo "removing OI files on $facet: idx=${idx}"
10326
10327         # step 1: build mount point
10328         ${rcmd} mkdir -p $mntpt
10329         # step 2: mount dev
10330         ${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 1
10331         if [ -z $idx ]; then
10332                 # step 3: remove all OI files
10333                 ${rcmd} rm -fv $mntpt/oi.16*
10334         elif [ $idx -lt 2 ]; then
10335                 ${rcmd} rm -fv $mntpt/oi.16.${idx}
10336         else
10337                 local i
10338
10339                 # others, rm oi.16.[idx, idx * idx, idx ** ...]
10340                 for ((i=${idx}; i<64; i=$((i * idx)))); do
10341                         ${rcmd} rm -fv $mntpt/oi.16.${i}
10342                 done
10343         fi
10344         # step 4: umount
10345         ${rcmd} $UMOUNT $mntpt || return 2
10346         # OI files will be recreated when mounted as lustre next time.
10347 }
10348
10349 # generate maloo upload-able log file name
10350 # \param logname specify unique part of file name
10351 generate_logname() {
10352         local logname=${1:-"default_logname"}
10353
10354         echo "$TESTLOG_PREFIX.$TESTNAME.$logname.$(hostname -s).log"
10355 }
10356
10357 # make directory on different MDTs
10358 test_mkdir() {
10359         local path
10360         local p_option
10361         local hash_type
10362         local hash_name=("all_char" "fnv_1a_64" "crush")
10363         local dirstripe_count=${DIRSTRIPE_COUNT:-"2"}
10364         local dirstripe_index=${DIRSTRIPE_INDEX:-$((base % $MDSCOUNT))}
10365         local OPTIND=1
10366         local overstripe_count
10367         local stripe_command="-c"
10368
10369         (( $MDS1_VERSION > $(version_code v2_15_50-185-g1ac4b9598a) )) &&
10370                 hash_name+=("crush2")
10371
10372         while getopts "c:C:H:i:p" opt; do
10373                 case $opt in
10374                         c) dirstripe_count=$OPTARG;;
10375                         C) overstripe_count=$OPTARG;;
10376                         H) hash_type=$OPTARG;;
10377                         i) dirstripe_index=$OPTARG;;
10378                         p) p_option="-p";;
10379                         \?) error "only support -c -H -i -p";;
10380                 esac
10381         done
10382
10383         shift $((OPTIND - 1))
10384         [ $# -eq 1 ] || error "Only creating single directory is supported"
10385         path="$*"
10386
10387         local parent=$(dirname $path)
10388         if [ "$p_option" == "-p" ]; then
10389                 [ -d $path ] && return 0
10390                 if [ ! -d ${parent} ]; then
10391                         mkdir -p ${parent} ||
10392                                 error "mkdir parent '$parent' failed"
10393                 fi
10394         fi
10395
10396         if [[ -n "$overstripe_count" ]]; then
10397                 stripe_command="-C"
10398                 dirstripe_count=$overstripe_count
10399         fi
10400
10401         if [ $MDSCOUNT -le 1 ] || ! is_lustre ${parent}; then
10402                 mkdir $path || error "mkdir '$path' failed"
10403         else
10404                 local mdt_index
10405
10406                 if [ $dirstripe_index -eq -1 ]; then
10407                         mdt_index=$((base % MDSCOUNT))
10408                 else
10409                         mdt_index=$dirstripe_index
10410                 fi
10411
10412                 # randomly choose hash type
10413                 [ -z "$hash_type" ] &&
10414                         hash_type=${hash_name[$((RANDOM % ${#hash_name[@]}))]}
10415
10416                 if (($MDS1_VERSION >= $(version_code 2.8.0))); then
10417                         if [ $dirstripe_count -eq -1 ]; then
10418                                 dirstripe_count=$((RANDOM % MDSCOUNT + 1))
10419                         fi
10420                 else
10421                         dirstripe_count=1
10422                 fi
10423
10424                 echo "striped dir -i$mdt_index $stripe_command$dirstripe_count -H $hash_type $path"
10425                 $LFS mkdir -i$mdt_index $stripe_command$dirstripe_count -H $hash_type $path ||
10426                         error "mkdir -i $mdt_index $stripe_command$dirstripe_count -H $hash_type $path failed"
10427         fi
10428 }
10429
10430 # free_fd: find the smallest and not in use file descriptor [above @last_fd]
10431 #
10432 # If called many times, passing @last_fd will avoid repeated searching
10433 # already-open FDs repeatedly if we know they are still in use.
10434 #
10435 # usage: free_fd [last_fd]
10436 free_fd()
10437 {
10438         local max_fd=$(ulimit -n)
10439         local fd=$((${1:-2} + 1))
10440
10441         while [[ $fd -le $max_fd && -e /proc/self/fd/$fd ]]; do
10442                 ((++fd))
10443         done
10444         [ $fd -lt $max_fd ] || error "finding free file descriptor failed"
10445         echo $fd
10446 }
10447
10448 check_mount_and_prep()
10449 {
10450         is_mounted $MOUNT || setupall
10451
10452         rm -rf $DIR/[df][0-9]* || error "Fail to cleanup the env!"
10453         mkdir_on_mdt0 $DIR/$tdir || error "Fail to mkdir $DIR/$tdir."
10454         for idx in $(seq $MDSCOUNT); do
10455                 local name="MDT$(printf '%04x' $((idx - 1)))"
10456                 rm -rf $MOUNT/.lustre/lost+found/$name/*
10457         done
10458 }
10459
10460 # calcule how many ost-objects to be created.
10461 precreated_ost_obj_count()
10462 {
10463         local mdt_idx=$1
10464         local ost_idx=$2
10465         local mdt_name="MDT$(printf '%04x' $mdt_idx)"
10466         local ost_name="OST$(printf '%04x' $ost_idx)"
10467         local proc_path="${FSNAME}-${ost_name}-osc-${mdt_name}"
10468         local last_id=$(do_facet mds$((mdt_idx + 1)) lctl get_param -n \
10469                         osp.$proc_path.prealloc_last_id)
10470         local next_id=$(do_facet mds$((mdt_idx + 1)) lctl get_param -n \
10471                         osp.$proc_path.prealloc_next_id)
10472         local ost_obj_count=$((last_id - next_id + 1))
10473
10474         echo " - precreated_ost_obj_count $proc_path" \
10475              "prealloc_last_id: $last_id" \
10476              "prealloc_next_id: $next_id" \
10477              "count: $ost_obj_count" 1>&2
10478
10479         echo $ost_obj_count
10480 }
10481
10482 check_file_in_pool()
10483 {
10484         local file=$1
10485         local pool=$2
10486         local tlist="$3"
10487         local res=$($LFS getstripe $file | grep 0x | cut -f2)
10488         for i in $res
10489         do
10490                 for t in $tlist ; do
10491                         [ "$i" -eq "$t" ] && continue 2
10492                 done
10493
10494                 echo "pool list: $tlist"
10495                 echo "striping: $res"
10496                 error_noexit "$file not allocated in $pool"
10497                 return 1
10498         done
10499         return 0
10500 }
10501
10502 pool_add() {
10503         local pool=$1
10504         local mdscount=${2:-$MDSCOUNT}
10505
10506         echo "Creating new pool $pool"
10507         create_pool $FSNAME.$pool false $mdscount ||
10508                 { error_noexit "No pool created, result code $?"; return 1; }
10509         [ $($LFS pool_list $FSNAME | grep -c "$FSNAME.${pool}\$") -eq 1 ] ||
10510                 { error_noexit "$pool not in lfs pool_list"; return 2; }
10511 }
10512
10513 pool_add_targets() {
10514         echo "Adding targets to pool"
10515         local pool=$1
10516         local first=$2
10517         local last=${3:-$first}
10518         local step=${4:-1}
10519         local mdscount=${5:-$MDSCOUNT}
10520
10521         local list=$(seq $first $step $last)
10522
10523         local t=$(for i in $list; do printf "$FSNAME-OST%04x_UUID " $i; done)
10524         local tg=$(for i in $list;
10525                 do printf -- "-e $FSNAME-OST%04x_UUID " $i; done)
10526         local firstx=$(printf "%04x" $first)
10527         local lastx=$(printf "%04x" $last)
10528
10529         do_facet mgs $LCTL pool_add \
10530                 $FSNAME.$pool $FSNAME-OST[$firstx-$lastx/$step]
10531         # ignore EEXIST(17)
10532         if (( $? != 0 && $? != 17 )); then
10533                 error_noexit "pool_add $FSNAME-OST[$firstx-$lastx/$step] failed"
10534                 return 3
10535         fi
10536
10537         # wait for OSTs to be added to the pool
10538         for ((mds_id = 1; mds_id < $mdscount; mds_id++)); do
10539                 local mdt_id=$((mds_id-1))
10540                 local lodname=$FSNAME-MDT$(printf "%04x" $mdt_id)-mdtlov
10541                 wait_update_facet mds$mds_id \
10542                         "lctl get_param -n lod.$lodname.pools.$pool |
10543                                 grep $tg | sort -u | tr '\n' ' '" "$t" || {
10544                         error_noexit "mds$mds_id: Add to pool failed"
10545                         return 2
10546                 }
10547         done
10548         wait_update $HOSTNAME "lctl get_param -n lov.$FSNAME-*.pools.$pool |
10549                         grep $tg | sort -u | tr '\n' ' ' " "$t" || {
10550                 error_noexit "Add to pool failed"
10551                 return 1
10552         }
10553 }
10554
10555 pool_set_dir() {
10556         local pool=$1
10557         local tdir=$2
10558         echo "Setting pool on directory $tdir"
10559
10560         $LFS setstripe -c 2 -p $pool $tdir && return 0
10561
10562         error_noexit "Cannot set pool $pool to $tdir"
10563         return 1
10564 }
10565
10566 pool_check_dir() {
10567         local pool=$1
10568         local tdir=$2
10569         echo "Checking pool on directory $tdir"
10570
10571         local res=$($LFS getstripe --pool $tdir | sed "s/\s*$//")
10572         [ "$res" = "$pool" ] && return 0
10573
10574         error_noexit "Pool on '$tdir' is '$res', not '$pool'"
10575         return 1
10576 }
10577
10578 pool_dir_rel_path() {
10579         echo "Testing relative path works well"
10580         local pool=$1
10581         local tdir=$2
10582         local root=$3
10583
10584         mkdir -p $root/$tdir/$tdir
10585         cd $root/$tdir
10586         pool_set_dir $pool $tdir          || return 1
10587         pool_set_dir $pool ./$tdir        || return 2
10588         pool_set_dir $pool ../$tdir       || return 3
10589         pool_set_dir $pool ../$tdir/$tdir || return 4
10590         rm -rf $tdir; cd - > /dev/null
10591 }
10592
10593 pool_alloc_files() {
10594         echo "Checking files allocation from directory pool"
10595         local pool=$1
10596         local tdir=$2
10597         local count=$3
10598         local tlist="$4"
10599
10600         local failed=0
10601         for i in $(seq -w 1 $count)
10602         do
10603                 local file=$tdir/file-$i
10604                 touch $file
10605                 check_file_in_pool $file $pool "$tlist" || \
10606                         failed=$((failed + 1))
10607         done
10608         [ "$failed" = 0 ] && return 0
10609
10610         error_noexit "$failed files not allocated in $pool"
10611         return 1
10612 }
10613
10614 pool_create_files() {
10615         echo "Creating files in pool"
10616         local pool=$1
10617         local tdir=$2
10618         local count=$3
10619         local tlist="$4"
10620
10621         mkdir -p $tdir
10622         local failed=0
10623         for i in $(seq -w 1 $count)
10624         do
10625                 local file=$tdir/spoo-$i
10626                 $LFS setstripe -p $pool $file
10627                 check_file_in_pool $file $pool "$tlist" || \
10628                         failed=$((failed + 1))
10629         done
10630         [ "$failed" = 0 ] && return 0
10631
10632         error_noexit "$failed files not allocated in $pool"
10633         return 1
10634 }
10635
10636 pool_lfs_df() {
10637         echo "Checking 'lfs df' output"
10638         local pool=$1
10639
10640         local t=$($LCTL get_param -n lov.$FSNAME-clilov-*.pools.$pool |
10641                         tr '\n' ' ')
10642         local res=$($LFS df --pool $FSNAME.$pool |
10643                         awk '{print $1}' |
10644                         grep "$FSNAME-OST" |
10645                         tr '\n' ' ')
10646         [ "$res" = "$t" ] && return 0
10647
10648         error_noexit "Pools OSTs '$t' is not '$res' that lfs df reports"
10649         return 1
10650 }
10651
10652 pool_file_rel_path() {
10653         echo "Creating files in a pool with relative pathname"
10654         local pool=$1
10655         local tdir=$2
10656
10657         mkdir -p $tdir ||
10658                 { error_noexit "unable to create $tdir"; return 1 ; }
10659         local file="/..$tdir/$tfile-1"
10660         $LFS setstripe -p $pool $file ||
10661                 { error_noexit "unable to create $file" ; return 2 ; }
10662
10663         cd $tdir
10664         $LFS setstripe -p $pool $tfile-2 || {
10665                 error_noexit "unable to create $tfile-2 in $tdir"
10666                 return 3
10667         }
10668 }
10669
10670 pool_remove_first_target() {
10671         echo "Removing first target from a pool"
10672         pool_remove_target $1 -1
10673 }
10674
10675 pool_remove_target() {
10676         local pool=$1
10677         local index=$2
10678
10679         local pname="lov.$FSNAME-*.pools.$pool"
10680         if [ $index -eq -1 ]; then
10681                 local t=$($LCTL get_param -n $pname | head -1)
10682         else
10683                 local t=$(printf "$FSNAME-OST%04x_UUID" $index)
10684         fi
10685
10686         echo "Removing $t from $pool"
10687         do_facet mgs $LCTL pool_remove $FSNAME.$pool $t
10688         for mds_id in $(seq $MDSCOUNT); do
10689                 local mdt_id=$((mds_id-1))
10690                 local lodname=$FSNAME-MDT$(printf "%04x" $mdt_id)-mdtlov
10691                 wait_update_facet mds$mds_id \
10692                         "lctl get_param -n lod.$lodname.pools.$pool |
10693                                 grep $t" "" || {
10694                         error_noexit "mds$mds_id: $t not removed from" \
10695                         "$FSNAME.$pool"
10696                         return 2
10697                 }
10698         done
10699         wait_update $HOSTNAME "lctl get_param -n $pname | grep $t" "" || {
10700                 error_noexit "$t not removed from $FSNAME.$pool"
10701                 return 1
10702         }
10703 }
10704
10705 pool_remove_all_targets() {
10706         echo "Removing all targets from pool"
10707         local pool=$1
10708         local file=$2
10709         local pname="lov.$FSNAME-*.pools.$pool"
10710         for t in $($LCTL get_param -n $pname | sort -u)
10711         do
10712                 do_facet mgs $LCTL pool_remove $FSNAME.$pool $t
10713         done
10714         for mds_id in $(seq $MDSCOUNT); do
10715                 local mdt_id=$((mds_id-1))
10716                 local lodname=$FSNAME-MDT$(printf "%04x" $mdt_id)-mdtlov
10717                 wait_update_facet mds$mds_id "lctl get_param -n \
10718                         lod.$lodname.pools.$pool" "" || {
10719                         error_noexit "mds$mds_id: Pool $pool not drained"
10720                         return 4
10721                 }
10722         done
10723         wait_update $HOSTNAME "lctl get_param -n $pname" "" || {
10724                 error_noexit "Pool $FSNAME.$pool cannot be drained"
10725                 return 1
10726         }
10727         # striping on an empty/nonexistant pool should fall back
10728         # to "pool of everything"
10729         touch $file || {
10730                 error_noexit "failed to use fallback striping for empty pool"
10731                 return 2
10732         }
10733         # setstripe on an empty pool should fail
10734         $LFS setstripe -p $pool $file 2>/dev/null && {
10735                 error_noexit "expected failure when creating file" \
10736                                                         "with empty pool"
10737                 return 3
10738         }
10739         return 0
10740 }
10741
10742 pool_remove() {
10743         echo "Destroying pool"
10744         local pool=$1
10745         local file=$2
10746
10747         do_facet mgs $LCTL pool_destroy $FSNAME.$pool
10748
10749         sleep 2
10750         # striping on an empty/nonexistant pool should fall back
10751         # to "pool of everything"
10752         touch $file || {
10753                 error_noexit "failed to use fallback striping for missing pool"
10754                 return 1
10755         }
10756         # setstripe on an empty pool should fail
10757         $LFS setstripe -p $pool $file 2>/dev/null && {
10758                 error_noexit "expected failure when creating file" \
10759                                                         "with missing pool"
10760                 return 2
10761         }
10762
10763         # get param should return err once pool is gone
10764         if wait_update $HOSTNAME "lctl get_param -n \
10765                 lov.$FSNAME-*.pools.$pool 2>/dev/null || echo foo" "foo"
10766         then
10767                 remove_pool_from_list $FSNAME.$pool
10768                 return 0
10769         fi
10770         error_noexit "Pool $FSNAME.$pool is not destroyed"
10771         return 3
10772 }
10773
10774 # Get and check the actual stripe count of one file.
10775 # Usage: check_stripe_count <file> <expected_stripe_count>
10776 check_stripe_count() {
10777         local file=$1
10778         local expected=$2
10779         local actual
10780
10781         [[ -z "$file" || -z "$expected" ]] &&
10782                 error "check_stripe_count: invalid argument"
10783
10784         local cmd="$LFS getstripe -c $file"
10785         actual=$($cmd) || error "$cmd failed"
10786         actual=${actual%% *}
10787
10788         if [[ $actual -ne $expected ]]; then
10789                 [[ $expected -eq -1 ]] || { $LFS getstripe $file;
10790                         error "$cmd not expected ($expected): found $actual"; }
10791                 [[ $actual -eq $OSTCOUNT ]] || { $LFS getstripe $file;
10792                         error "$cmd not OST count ($OSTCOUNT): found $actual"; }
10793         fi
10794 }
10795
10796 # Get and check the actual list of OST indices on one file.
10797 # Usage: check_obdidx <file> <expected_comma_separated_list_of_ost_indices>
10798 check_obdidx() {
10799         local file=$1
10800         local expected=$2
10801         local obdidx
10802
10803         [[ -z "$file" || -z "$expected" ]] &&
10804                 error "check_obdidx: invalid argument!"
10805
10806         obdidx=$(comma_list $($LFS getstripe $file | grep -A $OSTCOUNT obdidx |
10807                               grep -v obdidx | awk '{print $1}' | xargs))
10808
10809         [[ $obdidx = $expected ]] ||
10810                 error "list of OST indices on $file is $obdidx," \
10811                       "should be $expected"
10812 }
10813
10814 # Get and check the actual OST index of the first stripe on one file.
10815 # Usage: check_start_ost_idx <file> <expected_start_ost_idx>
10816 check_start_ost_idx() {
10817         local file=$1
10818         local expected=$2
10819         local start_ost_idx
10820
10821         [[ -z "$file" || -z "$expected" ]] &&
10822                 error "check_start_ost_idx: invalid argument!"
10823
10824         start_ost_idx=$($LFS getstripe $file | grep -A 1 obdidx |
10825                          grep -v obdidx | awk '{print $1}')
10826
10827         [[ $start_ost_idx = $expected ]] ||
10828                 error "OST index of the first stripe on $file is" \
10829                       "$start_ost_idx, should be $expected"
10830 }
10831
10832 killall_process () {
10833         local clients=${1:-$(hostname)}
10834         local name=$2
10835         local signal=$3
10836         local rc=0
10837
10838         do_nodes $clients "killall $signal $name"
10839 }
10840
10841 lsnapshot () {
10842         local cmd=$1
10843         shift
10844
10845         if (( $MDS1_VERSION >= $(version_code 2.16.50) )); then
10846                 do_facet mgs "$LCTL snapshot $cmd -F $FSNAME $*"
10847         else
10848                 do_facet mgs "$LCTL snapshot_$cmd -F $FSNAME $*"
10849         fi
10850 }
10851
10852 lsnapshot_create()
10853 {
10854         lsnapshot create $*
10855 }
10856
10857 lsnapshot_destroy()
10858 {
10859         lsnapshot destroy $*
10860 }
10861
10862 lsnapshot_modify()
10863 {
10864         lsnapshot modify $*
10865 }
10866
10867 lsnapshot_list()
10868 {
10869         lsnapshot list $*
10870 }
10871
10872 lsnapshot_mount()
10873 {
10874         lsnapshot mount $*
10875 }
10876
10877 lsnapshot_umount()
10878 {
10879         lsnapshot umount $*
10880 }
10881
10882 lss_err()
10883 {
10884         local msg=$1
10885
10886         do_facet mgs "cat $LSNAPSHOT_LOG"
10887         error $msg
10888 }
10889
10890 lss_cleanup()
10891 {
10892         echo "Cleaning test environment ..."
10893
10894         # Every lsnapshot command takes exclusive lock with others,
10895         # so can NOT destroy the snapshot during list with 'xargs'.
10896         while true; do
10897                 local ssname=$(lsnapshot_list | grep snapshot_name |
10898                         grep lss_ | awk '{ print $2 }' | head -n 1)
10899                 [ -z "$ssname" ] && break
10900
10901                 lsnapshot_destroy -n $ssname -f ||
10902                         lss_err "Fail to destroy $ssname by force"
10903         done
10904 }
10905
10906 lss_gen_conf_one()
10907 {
10908         local facet=$1
10909         local role=$2
10910         local idx=$3
10911
10912         local host=$(facet_active_host $facet)
10913         local dir=$(dirname $(facet_vdevice $facet))
10914         local pool=$(zpool_name $facet)
10915         local lfsname=$(zfs_local_fsname $facet)
10916         local label=${FSNAME}-${role}$(printf '%04x' $idx)
10917
10918         do_facet mgs \
10919                 "echo '$host - $label zfs:${dir}/${pool}/${lfsname} - -' >> \
10920                 $LSNAPSHOT_CONF"
10921 }
10922
10923 lss_gen_conf()
10924 {
10925         do_facet mgs "rm -f $LSNAPSHOT_CONF"
10926         echo "Generating $LSNAPSHOT_CONF on MGS ..."
10927
10928         if ! combined_mgs_mds ; then
10929                 [ $(facet_fstype mgs) != zfs ] &&
10930                         skip "Lustre snapshot 1 only works for ZFS backend"
10931
10932                 local host=$(facet_active_host mgs)
10933                 local dir=$(dirname $(facet_vdevice mgs))
10934                 local pool=$(zpool_name mgs)
10935                 local lfsname=$(zfs_local_fsname mgs)
10936
10937                 do_facet mgs \
10938                         "echo '$host - MGS zfs:${dir}/${pool}/${lfsname} - -' \
10939                         >> $LSNAPSHOT_CONF" || lss_err "generate lss conf (mgs)"
10940         fi
10941
10942         for num in `seq $MDSCOUNT`; do
10943                 [ $(facet_fstype mds$num) != zfs ] &&
10944                         skip "Lustre snapshot 1 only works for ZFS backend"
10945
10946                 lss_gen_conf_one mds$num MDT $((num - 1)) ||
10947                         lss_err "generate lss conf (mds$num)"
10948         done
10949
10950         for num in `seq $OSTCOUNT`; do
10951                 [ $(facet_fstype ost$num) != zfs ] &&
10952                         skip "Lustre snapshot 1 only works for ZFS backend"
10953
10954                 lss_gen_conf_one ost$num OST $((num - 1)) ||
10955                         lss_err "generate lss conf (ost$num)"
10956         done
10957
10958         do_facet mgs "cat $LSNAPSHOT_CONF"
10959 }
10960
10961 # Parse 'lfs getstripe -d <path_with_dir_name>' for non-composite dir
10962 parse_plain_dir_param()
10963 {
10964         local invalues=($1)
10965         local param=""
10966
10967         if [[ ${invalues[0]} =~ "stripe_count:" ]]; then
10968                 (( ${invalues[1]} == $OSTCOUNT - 1 )) &&
10969                         param="-c $OSTCOUNT" || param="-c ${invalues[1]}"
10970         fi
10971         if [[ ${invalues[2]} =~ "stripe_size:" ]]; then
10972                 param="$param -S ${invalues[3]}"
10973         fi
10974         if [[ ${invalues[4]} =~ "pattern:" ]]; then
10975                 if [[ ${invalues[5]} =~ "stripe_offset:" ]]; then
10976                         param="$param -i ${invalues[6]}"
10977                 else
10978                         param="$param -L ${invalues[5]} -i ${invalues[7]}"
10979                 fi
10980         elif [[ ${invalues[4]} =~ "stripe_offset:" ]]; then
10981                 param="$param -i ${invalues[5]}"
10982         fi
10983         echo "$param"
10984 }
10985
10986 parse_plain_param()
10987 {
10988         local line=$1
10989         local val=$(awk '{print $2}' <<< $line)
10990
10991         if [[ $line =~ ^"lmm_stripe_count:" ]]; then
10992                 (( $val == $OSTCOUNT - 1 )) &&
10993                         param="-c $OSTCOUNT" || param="-c $val"
10994                 echo "-c $val"
10995         elif [[ $line =~ ^"lmm_stripe_size:" ]]; then
10996                 echo "-S $val"
10997         elif [[ $line =~ ^"lmm_stripe_offset:" && $SKIP_INDEX != yes ]]; then
10998                 echo "-i $val"
10999         elif [[ $line =~ ^"lmm_pattern:" ]]; then
11000                 echo "-L $val"
11001         fi
11002 }
11003
11004 parse_dir_param()
11005 {
11006         local line=$1
11007         local val=$(awk '{print $2}' <<< $line)
11008
11009         if [[ $line =~ ^"lmv_stripe_count:" ]]; then
11010                 echo "-c $val"
11011         elif [[ $line =~ ^"lmv_stripe_offset:" ]]; then
11012                 echo "-i $val"
11013         elif [[ $line =~ ^"lmv_hash_type:" ]]; then
11014                 echo "-H $val"
11015         elif [[ $line =~ ^"lmv_max_inherit:" ]]; then
11016                 echo "-X $val"
11017         fi
11018 }
11019
11020 parse_layout_param()
11021 {
11022         local mode=""
11023         local val=""
11024         local param=""
11025
11026         while read line; do
11027                 if [[ ! -z $line ]]; then
11028                         if [[ -z $mode ]]; then
11029                                 if [[ $line =~ ^"stripe_count:" ]]; then
11030                                         mode="plain_dir"
11031                                 elif [[ $line =~ ^"lmm_stripe_count:" ]]; then
11032                                         mode="plain_file"
11033                                 elif [[ $line =~ ^"lcm_layout_gen:" ]]; then
11034                                         mode="pfl"
11035                                 elif [[ $line =~ ^"lmv_stripe_count" ]]; then
11036                                         mode="dne"
11037                                 fi
11038                         fi
11039
11040                         if [[ $mode = "plain_dir" ]]; then
11041                                 param=$(parse_plain_dir_param "$line")
11042                         elif [[ $mode = "plain_file" ]]; then
11043                                 val=$(parse_plain_param "$line")
11044                                 [[ ! -z $val ]] && param="$param $val"
11045                         elif [[ $mode = "pfl" ]]; then
11046                                 val=$(echo $line | awk '{print $2}')
11047                                 if [[ $line =~ ^"lcme_extent.e_end:" ]]; then
11048                                         if [[ $val = "EOF" ]]; then
11049                                                 param="$param -E -1"
11050                                         else
11051                                                 param="$param -E $val"
11052                                         fi
11053                                 elif [[ $line =~ ^"stripe_count:" ]]; then
11054                                         # pfl dir
11055                                         val=$(parse_plain_dir_param "$line")
11056                                         param="$param $val"
11057                                 else
11058                                         #pfl file
11059                                         val=$(parse_plain_param "$line")
11060                                         [[ ! -z $val ]] && param="$param $val"
11061                                 fi
11062                         elif [[ $mode = "dne" ]]; then
11063                                 val=$(parse_dir_param "$line")
11064                                 [[ ! -z $val ]] && param="$param $val"
11065                         fi
11066                 fi
11067         done
11068         echo "$param"
11069 }
11070
11071 get_layout_param()
11072 {
11073         local param=$($LFS getstripe -dy $1 | parse_layout_param)
11074         echo "$param"
11075 }
11076
11077 get_dir_layout_param()
11078 {
11079         local param=$($LFS getdirstripe -y $1 | parse_layout_param)
11080         echo "$param"
11081 }
11082
11083 lfsck_verify_pfid()
11084 {
11085         local f
11086         local rc=0
11087
11088         # Cancel locks before setting lfsck_verify_pfid so that errors are more
11089         # controllable
11090         cancel_lru_locks mdc
11091         cancel_lru_locks osc
11092
11093         # make sure PFID is set correctly for files
11094         do_nodes $(osts_nodes) \
11095                "$LCTL set_param -n obdfilter.${FSNAME}-OST*.lfsck_verify_pfid=1"
11096
11097         for f in "$@"; do
11098                 cat $f &> /dev/nullA ||
11099                         { rc=$?; echo "verify $f failed"; break; }
11100         done
11101
11102         do_nodes $(osts_nodes) \
11103                "$LCTL set_param -n obdfilter.${FSNAME}-OST*.lfsck_verify_pfid=0"
11104         return $rc
11105 }
11106
11107 # check that clients "oscs" was evicted after "before"
11108 check_clients_evicted() {
11109         local before=$1
11110         shift
11111         local oscs=${@}
11112         local osc
11113         local rc=0
11114
11115         for osc in $oscs; do
11116                 echo "Check state for $osc"
11117                 local evicted=$(do_facet client $LCTL get_param osc.$osc.state |
11118                         tail -n 5 | awk -F"[ ,]" \
11119                         '/EVICTED/ { if (mx<$4) { mx=$4; } } END { print mx }')
11120                 if (($? == 0)) && (($evicted > $before)); then
11121                         echo "$osc is evicted at $evicted"
11122                 else
11123                         ((rc++))
11124                         echo "$osc was not evicted after $before:"
11125                         do_facet client $LCTL get_param osc.$osc.state |
11126                                 tail -n 8
11127                 fi
11128         done
11129
11130         [ $rc -eq 0 ] || error "client not evicted from OST"
11131 }
11132
11133 # check that clients OSCS current_state is FULL
11134 check_clients_full() {
11135         local timeout=$1
11136         shift
11137         local oscs=${@}
11138
11139         for osc in $oscs; do
11140                 wait_update_facet client \
11141                         "lctl get_param -n osc.$osc.state |
11142                         grep 'current_state: FULL'" \
11143                         "current_state: FULL" $timeout
11144                 [ $? -eq 0 ] || error "$osc state is not FULL"
11145         done
11146 }
11147
11148 #Changelogs
11149 __changelog_deregister() {
11150         local facet=$1
11151         local mdt="$(facet_svc $facet)"
11152         local cl_user=$2
11153         local rc=0
11154
11155         if (( $MDS1_VERSION >= $(version_code 2.16.50) )); then
11156                 changelog_deregister="changelog deregister"
11157         else
11158                 changelog_deregister="changelog_deregister"
11159         fi
11160         # skip cleanup if no user registered for this MDT
11161         [ -z "$cl_user" ] && echo "$mdt: no changelog user" && return 0
11162         # user is no longer registered, skip cleanup
11163         changelog_users "$facet" | grep -q "$cl_user" ||
11164                 { echo "$mdt: changelog user '$cl_user' not found"; return 0; }
11165
11166         # From this point, if any operation fails, it is an error
11167         __changelog_clear $facet $cl_user 0 ||
11168                 error_noexit "$mdt: changelog_clear $cl_user 0 fail: $rc"
11169         do_facet $facet $LCTL --device $mdt $changelog_deregister $cl_user ||
11170                 error_noexit "$mdt: changelog_deregister '$cl_user' fail: $rc"
11171 }
11172
11173 declare -Ax CL_USERS
11174 changelog_register() {
11175         if (( $MDS1_VERSION >= $(version_code 2.16.50) )); then
11176                 changelog_register="changelog register"
11177         else
11178                 changelog_register="changelog_register"
11179         fi
11180         for M in $(seq $MDSCOUNT); do
11181                 local facet=mds$M
11182                 local mdt="$(facet_svc $facet)"
11183                 local cl_mask
11184
11185                 cl_mask=$(do_facet $facet $LCTL get_param \
11186                              mdd.${mdt}.changelog_mask -n)
11187                 stack_trap "do_facet $facet $LCTL \
11188                         set_param mdd.$mdt.changelog_mask=\'$cl_mask\' -n" EXIT
11189                 do_facet $facet $LCTL set_param mdd.$mdt.changelog_mask=+hsm ||
11190                         error "$mdt: changelog_mask=+hsm failed: $?"
11191
11192                 local cl_user
11193                 cl_user=$(do_facet $facet $LCTL --device $mdt \
11194                         $changelog_register -n "$@") ||
11195                         error "$mdt: register changelog user failed: $?"
11196                 stack_trap "__changelog_deregister $facet $cl_user" EXIT
11197
11198                 stack_trap "CL_USERS[$facet]='${CL_USERS[$facet]}'" EXIT
11199                 # Bash does not support nested arrays, but the format of a
11200                 # cl_user is constrained enough to use whitespaces as separators
11201                 CL_USERS[$facet]+="$cl_user "
11202         done
11203         echo "Registered $MDSCOUNT changelog users: '${CL_USERS[*]% }'"
11204 }
11205
11206 changelog_deregister() {
11207         local cl_user
11208         # bash assoc arrays do not guarantee to list keys in created order
11209         # so reorder to get same order than in changelog_register()
11210         local cl_facets=$(echo "${!CL_USERS[@]}" | tr " " "\n" | sort |
11211                           tr "\n" " ")
11212
11213         for facet in $cl_facets; do
11214                 for cl_user in ${CL_USERS[$facet]}; do
11215                         __changelog_deregister $facet $cl_user || return $?
11216                 done
11217                 unset CL_USERS[$facet]
11218         done
11219 }
11220
11221 changelog_users() {
11222         local facet=$1
11223         local service=$(facet_svc $facet)
11224
11225         do_facet $facet $LCTL get_param -n mdd.$service.changelog_users
11226 }
11227
11228 changelog_user_rec() {
11229         local facet=$1
11230         local cl_user=$2
11231         local service=$(facet_svc $facet)
11232
11233         changelog_users $facet | awk '$1 == "'$cl_user'" { print $2 }'
11234 }
11235
11236 changelog_chmask() {
11237         local mask=$1
11238
11239         do_nodes $(mdts_nodes) $LCTL set_param mdd.*.changelog_mask="$mask"
11240 }
11241
11242 # usage: __changelog_clear FACET CL_USER [+]INDEX
11243 __changelog_clear()
11244 {
11245         local facet=$1
11246         local mdt="$(facet_svc $facet)"
11247         local cl_user=$2
11248         local -i rec
11249
11250         case "$3" in
11251         +*)
11252                 # Remove the leading '+'
11253                 rec=${3:1}
11254                 rec+=$(changelog_user_rec $facet $cl_user)
11255                 ;;
11256         *)
11257                 rec=$3
11258                 ;;
11259         esac
11260
11261         if [ $rec -eq 0 ]; then
11262                 echo "$mdt: clear the changelog for $cl_user of all records"
11263         else
11264                 echo "$mdt: clear the changelog for $cl_user to record #$rec"
11265         fi
11266         $LFS changelog_clear $mdt $cl_user $rec
11267 }
11268
11269 # usage: changelog_clear [+]INDEX [facet]...
11270 #
11271 # If INDEX is prefixed with '+', increment every changelog user's record index
11272 # by INDEX. Otherwise, clear the changelog up to INDEX for every changelog
11273 # users.
11274 changelog_clear() {
11275         local rc
11276         local idx=$1
11277         shift
11278         local cl_facets="$@"
11279         # bash assoc arrays do not guarantee to list keys in created order
11280         # so reorder to get same order than in changelog_register()
11281         [[ -n "$cl_facets" ]] ||
11282                 cl_facets=$(echo "${!CL_USERS[@]}" | tr " " "\n" | sort |
11283                         tr "\n" " ")
11284         local cl_user
11285
11286         for facet in $cl_facets; do
11287                 for cl_user in ${CL_USERS[$facet]}; do
11288                         __changelog_clear $facet $cl_user $idx || rc=${rc:-$?}
11289                 done
11290         done
11291
11292         return ${rc:-0}
11293 }
11294
11295 changelog_dump() {
11296         local rc
11297
11298         for M in $(seq $MDSCOUNT); do
11299                 local facet=mds$M
11300                 local mdt="$(facet_svc $facet)"
11301                 local output
11302                 local ret
11303
11304                 output=$($LFS changelog $mdt)
11305                 ret=$?
11306                 if [ $ret -ne 0 ]; then
11307                         rc=${rc:-$ret}
11308                 elif [ -n "$output" ]; then
11309                         echo "$output" | sed -e 's/^/'$mdt'./'
11310                 fi
11311         done
11312
11313         return ${rc:-0}
11314 }
11315
11316 changelog_extract_field() {
11317         local cltype=$1
11318         local file=$2
11319         local identifier=$3
11320
11321         changelog_dump | gawk "/$cltype.*$file$/ {
11322                 print gensub(/^.* "$identifier'(\[[^\]]*\]).*$/,"\\1",1)}' |
11323                 tail -1
11324 }
11325
11326 # Prints a changelog record produced by "lfs changelog" as an associative array
11327 #
11328 # Example:
11329 # $> changelog2array 16 01CREAT 10:28:46.968438800 2018.03.09 0x0 \
11330 #                    t=[0x200000401:0x10:0x0] j=touch.501 ef=0xf u=501:501 \
11331 #                    nid=0@lo p=[0x200000007:0x1:0x0] blob
11332 # ([index]='16' [type]='CREAT' [time]='10:28:46.968438800'
11333 #  [date]='2018.03.09' [flags]=0x0 ['target-fid']='[0x200000401:0x10:0x0]'
11334 #  ['jobid']='touch.501' ['extra-flags']='0x0f' [uid]='0' ['gid']='0'
11335 #  ['nid']='0@lo' ['parent-fid']='[0x200000007:0x1:0x0]')
11336 #
11337 # Note that the changelog record is not quoted
11338 # Also note that the line breaks in the output were only added for readability
11339 #
11340 # Typically, you want to eval the output of the command to fill an actual
11341 # associative array, like this:
11342 # $> eval declare -A changelog=$(changelog2array $entry)
11343 #
11344 # It can then be accessed like any bash associative array:
11345 # $> echo "${changelog[index]}" "${changelog[type]}" "${changelog[flags]}"
11346 # 16 CREAT 0x0
11347 # $> echo "${changelog[uid]}":"${changelog[gid]}"
11348 # 501:501
11349 #
11350 changelog2array()
11351 {
11352         # Start the array
11353         printf '('
11354
11355         # A changelog, as printed by "lfs changelog" typically looks like this:
11356         # <index> <type> <time> <date> <flags> <key1=value1> <key2=value2> ...
11357
11358         # Parse the positional part of the changelog
11359
11360         # changelog_dump() prefixes records with their mdt's name
11361         local index="${1##*.}"
11362
11363         printf "[index]='%s' [type]='%s' [time]='%s' [date]='%s' [flags]='%s'" \
11364                "$index" "${2:2}" "$3" "$4" "$5"
11365
11366         # Parse the key/value part of the changelog
11367         for arg in "${@:5}"; do
11368                 # Check it matches a key=value syntax
11369                 [[ "$arg" =~ ^[[:alpha:]]+= ]] || continue
11370
11371                 local key="${arg%%=*}"
11372                 local value="${arg#*=}"
11373
11374                 case "$key" in
11375                 u)
11376                         # u is actually for uid AND gid: u=UID:GID
11377                         printf " [uid]='%s'" "${value%:*}"
11378                         key=gid
11379                         value="${value#*:}"
11380                         ;;
11381                 t)
11382                         key=target-fid
11383                         value="${value#[}"
11384                         value="${value%]}"
11385                         ;;
11386                 j)
11387                         key=jobid
11388                         ;;
11389                 p)
11390                         key=parent-fid
11391                         value="${value#[}"
11392                         value="${value%]}"
11393                         ;;
11394                 ef)
11395                         key=extra-flags
11396                         ;;
11397                 m)
11398                         key=mode
11399                         ;;
11400                 x)
11401                         key=xattr
11402                         ;;
11403                 s)
11404                         key=source-fid
11405                         value="${value#[}"
11406                         value="${value%]}"
11407                         ;;
11408                 *)
11409                         ;;
11410                 esac
11411
11412                 printf " ['%s']='%s'" "$key" "$value"
11413         done
11414
11415         # end the array
11416         printf ')'
11417 }
11418
11419 # Format and print a changelog record
11420 #
11421 # Interpreted sequences are:
11422 #       %%      a single %
11423 #       %f      the "flags" attribute of a changelog record
11424 __changelog_printf()
11425 {
11426         local format="$1"
11427
11428         local -i i
11429         for ((i = 0; i < ${#format}; i++)); do
11430                 local char="${format:$i:1}"
11431                 if [ "$char" != % ]; then
11432                         printf '%c' "$char"
11433                         continue
11434                 fi
11435
11436                 i+=1
11437                 char="${format:$i:1}"
11438                 case "$char" in
11439                 f)
11440                         printf '%s' "${changelog[flags]}"
11441                         ;;
11442                 %)
11443                         printf '%'
11444                         ;;
11445                 esac
11446         done
11447         printf '\n'
11448 }
11449
11450 # Filter changelog records
11451 changelog_find()
11452 {
11453         local -A filter
11454         local action='print'
11455         local format
11456
11457         while [ $# -gt 0 ]; do
11458                 case "$1" in
11459                 -print)
11460                         action='print'
11461                         ;;
11462                 -printf)
11463                         action='printf'
11464                         format="$2"
11465                         shift
11466                         ;;
11467                 -*)
11468                         filter[${1#-}]="$2"
11469                         shift
11470                         ;;
11471                 esac
11472                 shift
11473         done
11474
11475         local found=false
11476         local record
11477         changelog_dump | { while read -r record; do
11478                 eval local -A changelog=$(changelog2array $record)
11479                 for key in "${!filter[@]}"; do
11480                         case "$key" in
11481                         *)
11482                                 [ "${changelog[$key]}" == "${filter[$key]}" ]
11483                                 ;;
11484                         esac || continue 2
11485                 done
11486
11487                 found=true
11488
11489                 case "${action:-print}" in
11490                 print)
11491                         printf '%s\n' "$record"
11492                         ;;
11493                 printf)
11494                         __changelog_printf "$format"
11495                         ;;
11496                 esac
11497         done; $found; }
11498 }
11499
11500 restore_layout() {
11501         local dir=$1
11502         local layout=$2
11503
11504         [ ! -d "$dir" ] && return
11505
11506         [ -z "$layout" ] && {
11507                 $LFS setstripe -d $dir || error "error deleting stripe '$dir'"
11508                 return
11509         }
11510
11511         setfattr -n trusted.lov -v $layout $dir ||
11512                 error "error restoring layout '$layout' to '$dir'"
11513 }
11514
11515 # save the layout of a directory, the returned string will be used by
11516 # restore_layout() to restore the layout
11517 save_layout() {
11518         local dir=$1
11519         local str=$(getfattr -n trusted.lov --absolute-names -e hex $dir \
11520                     2> /dev/null | awk -F'=' '/trusted.lov/{ print $2 }')
11521         echo "$str"
11522 }
11523
11524 # save layout of a directory and restore it at exit
11525 save_layout_restore_at_exit() {
11526         local dir=$1
11527         local layout=$(save_layout $dir)
11528
11529         stack_trap "restore_layout $dir $layout" EXIT
11530 }
11531
11532 init_stripe_dir_params() {
11533         local varremote=$1
11534         local varstriped=$2
11535
11536         if ((MDSCOUNT > 1 &&
11537                 $MDS1_VERSION >=
11538                 $(version_code 2.8.0))); then
11539                 eval $varremote=${!varremote:-true}
11540                 eval $varstriped=${!varstriped:-true}
11541         elif ((MDSCOUNT > 1 &&
11542                 $MDS1_VERSION >=
11543                 $(version_code 2.5.0))); then
11544                 eval $varremote=${!varremote:-true}
11545                 eval $varstriped=${!varstriped:-false}
11546         fi
11547
11548         eval $varremote=${!varremote:-false}
11549         eval $varstriped=${!varstriped:-false}
11550 }
11551
11552 verify_yaml_layout() {
11553         local src=$1
11554         local dst=$2
11555         local temp=$3
11556         local msg_prefix=$4
11557
11558         echo "$msg_prefix: getstripe --yaml $src"
11559         $LFS getstripe --yaml $src > $temp ||
11560                 error "$msg_prefix: getstripe $src failed"
11561         echo "$msg_prefix: setstripe --yaml=$temp $dst"
11562         $LFS setstripe --yaml=$temp $dst || {
11563                 $LFS df -v $dst
11564                 $LFS df -i $dst
11565                 sed -e "s/^/$msg_prefix-yaml: /" $temp
11566                 getfattr -d -m - -e hex $src
11567                 getfattr -d -m - -e hex $dst
11568                 error "$msg_prefix: setstripe '$dst' failed"
11569         }
11570
11571         echo "$msg_prefix: compare"
11572         local layout_src=$(get_layout_param $src)
11573         local layout_dst=$(get_layout_param $dst)
11574         # compare their layout info
11575         [ "$layout_src" == "$layout_dst" ] || {
11576                 sed -e "s/^/$msg_prefix-src: /" <<< $layout_src
11577                 sed -e "s/^/$msg_prefix-dst: /" <<< $layout_dst
11578                 error "$msg_prefix: $src/$dst layouts are not equal"
11579         }
11580 }
11581
11582 is_project_quota_supported() {
11583         $ENABLE_PROJECT_QUOTAS || return 1
11584         [[ -z "$SAVE_PROJECT_SUPPORTED" ]] || return $SAVE_PROJECT_SUPPORTED
11585         local save_project_supported=1
11586
11587         [[ "$(facet_fstype $SINGLEMDS)" == "ldiskfs" &&
11588            $(lustre_version_code $SINGLEMDS) -gt $(version_code 2.9.55) ]] &&
11589                 do_facet mds1 lfs --list-commands |& grep -q project &&
11590                         save_project_supported=0
11591
11592         [[ "$(facet_fstype $SINGLEMDS)" == "zfs" &&
11593            $(lustre_version_code $SINGLEMDS) -gt $(version_code 2.10.53) ]] &&
11594                 do_facet mds1 $ZPOOL get all | grep -q project_quota &&
11595                         save_project_supported=0
11596
11597         # cache state of project quotas once instead of re-checking each time
11598         export SAVE_PROJECT_SUPPORTED=$save_project_supported
11599         echo "using SAVE_PROJECT_SUPPORTED=$SAVE_PROJECT_SUPPORTED"
11600
11601         return $save_project_supported
11602 }
11603
11604 # ZFS project quota enable/disable:
11605 #   This  feature  will  become  active as soon as it is enabled and will never
11606 #   return to being disabled. Each filesystem will be upgraded automatically
11607 #   when remounted or when [a] new file is created under that filesystem. The
11608 #   upgrade can also be triggered on filesystems via `zfs set version=current
11609 #   <pool/fs>`. The upgrade process runs in the background and may take a
11610 #   while to complete for the filesystems containing a large number of files.
11611 enable_project_quota() {
11612         is_project_quota_supported || return 0
11613         local zkeeper=${KEEP_ZPOOL}
11614         stack_trap "KEEP_ZPOOL=$zkeeper" EXIT
11615         KEEP_ZPOOL="true"
11616         stopall || error "failed to stopall (1)"
11617
11618         local zfeat_en="feature@project_quota=enabled"
11619         for facet in $(seq -f mds%g $MDSCOUNT) $(seq -f ost%g $OSTCOUNT); do
11620                 local facet_fstype=${facet:0:3}1_FSTYPE
11621                 local devname
11622
11623                 if [ "${!facet_fstype}" = "zfs" ]; then
11624                         devname=$(zpool_name ${facet})
11625                         do_facet ${facet} $ZPOOL set "$zfeat_en" $devname ||
11626                                 error "$ZPOOL set $zfeat_en $devname"
11627                 else
11628                         [ ${facet:0:3} == "mds" ] &&
11629                                 devname=$(mdsdevname ${facet:3}) ||
11630                                 devname=$(ostdevname ${facet:3})
11631                         do_facet ${facet} $TUNE2FS -O project $devname ||
11632                                 error "tune2fs $devname failed"
11633                 fi
11634         done
11635
11636         KEEP_ZPOOL="${zkeeper}"
11637         mount
11638         setupall
11639 }
11640
11641 disable_project_quota() {
11642         is_project_quota_supported || return 0
11643         [ "$mds1_FSTYPE" != "ldiskfs" ] && return 0
11644         stopall || error "failed to stopall (1)"
11645
11646         for num in $(seq $MDSCOUNT); do
11647                 do_facet mds$num $TUNE2FS -Q ^prj $(mdsdevname $num) ||
11648                         error "tune2fs $(mdsdevname $num) failed"
11649         done
11650
11651         for num in $(seq $OSTCOUNT); do
11652                 do_facet ost$num $TUNE2FS -Q ^prj $(ostdevname $num) ||
11653                         error "tune2fs $(ostdevname $num) failed"
11654         done
11655
11656         mount
11657         setupall
11658 }
11659
11660 change_project() {
11661         echo "$LFS project $*"
11662         $LFS project $* || error "$LFS project $* failed"
11663 }
11664
11665 # get quota for a user or a group
11666 # usage: getquota -u|-g|-p <username>|<groupname>|<projid> global|<obd_uuid> \
11667 #                 bhardlimit|bsoftlimit|bgrace|ihardlimit|isoftlimit|igrace \
11668 #                 <pool_name>
11669 getquota() {
11670         local type=$1
11671         local id=$2
11672         local uuid
11673         local spec=$4
11674         local pool=$5
11675         local pool_arg
11676
11677         sync_all_data > /dev/null 2>&1 || true
11678
11679         [[ "$#" != 4 && "$#" != 5 ]] &&
11680                 error "getquota: wrong number of arguments: $#"
11681         [[ "$type" != "-u" && "$type" != "-g" && "$type" != "-p" ]] &&
11682                 error "getquota: wrong u/g/p specifier $1 passed"
11683
11684         [[ "$spec" =~ "curspace" ]] && spec="space"
11685         [[ "$spec" =~ "curinode" ]] && spec="inodes"
11686         [[ ! -z "$pool" ]] && pool_arg="--pool $pool "
11687         [[ "$3" =~ "OST" ]] && uuid="--ost $(echo "$3" | tail -c 4) "
11688         [[ "$3" =~ "MDT" ]] && uuid="--mdt $(echo "$3" | tail -c 4) "
11689
11690         echo -n "$type $id $uuid $spec:" 1>&2
11691         $LFS quota -q $uuid --$spec "$type" "$id" $pool_arg$DIR | tr -d "*" 1>&2
11692         $LFS quota -q $uuid --$spec "$type" "$id" $pool_arg$DIR | tr -d "*"
11693 }
11694
11695 # set mdt quota type
11696 # usage: set_mdt_qtype ugp|u|g|p|none
11697 set_mdt_qtype() {
11698         local qtype=$1
11699         local varsvc
11700         local mdts=$(get_facets MDS)
11701         local cmd
11702         [[ "$qtype" =~ "p" ]] && ! is_project_quota_supported &&
11703                 qtype=$(tr -d 'p' <<<$qtype)
11704
11705         if [[ $PERM_CMD == *"set_param -P"* ]]; then
11706                 do_facet mgs $PERM_CMD \
11707                         osd-*.$FSNAME-MDT*.quota_slave.enabled=$qtype
11708         else
11709                 do_facet mgs $PERM_CMD $FSNAME.quota.mdt=$qtype
11710         fi
11711         # we have to make sure each MDT received config changes
11712         for mdt in ${mdts//,/ }; do
11713                 varsvc=${mdt}_svc
11714                 cmd="$LCTL get_param -n "
11715                 cmd=${cmd}osd-$(facet_fstype $mdt).${!varsvc}
11716                 cmd=${cmd}.quota_slave.enabled
11717
11718                 if $(facet_up $mdt); then
11719                         wait_update_facet $mdt "$cmd" "$qtype" || return 1
11720                 fi
11721         done
11722         return 0
11723 }
11724
11725 # set ost quota type
11726 # usage: set_ost_qtype ugp|u|g|p|none
11727 set_ost_qtype() {
11728         local qtype=$1
11729         local varsvc
11730         local osts=$(get_facets OST)
11731         local cmd
11732         [[ "$qtype" =~ "p" ]] && ! is_project_quota_supported &&
11733                 qtype=$(tr -d 'p' <<<$qtype)
11734
11735         if [[ $PERM_CMD == *"set_param -P"* ]]; then
11736                 do_facet mgs $PERM_CMD \
11737                         osd-*.$FSNAME-OST*.quota_slave.enabled=$qtype
11738         else
11739                 do_facet mgs $PERM_CMD $FSNAME.quota.ost=$qtype
11740         fi
11741         # we have to make sure each OST received config changes
11742         for ost in ${osts//,/ }; do
11743                 varsvc=${ost}_svc
11744                 cmd="$LCTL get_param -n "
11745                 cmd=${cmd}osd-$(facet_fstype $ost).${!varsvc}
11746                 cmd=${cmd}.quota_slave.enabled
11747
11748                 if $(facet_up $ost); then
11749                         wait_update_facet $ost "$cmd" "$qtype" || return 1
11750                 fi
11751         done
11752         return 0
11753 }
11754
11755 #
11756 # In order to test multiple remote HSM agents, a new facet type named "AGT" and
11757 # the following associated variables are added:
11758 #
11759 # AGTCOUNT: number of agents
11760 # AGTDEV{N}: target HSM mount point (root path of the backend)
11761 # agt{N}_HOST: hostname of the agent agt{N}
11762 # SINGLEAGT: facet of the single agent
11763 #
11764 # The number of agents is initialized as the number of remote client nodes.
11765 # By default, only single copytool is started on a remote client/agent. If there
11766 # was no remote client, then the copytool will be started on the local client.
11767 #
11768 init_agt_vars() {
11769         local n
11770         local agent
11771
11772         export AGTCOUNT=${AGTCOUNT:-$((CLIENTCOUNT - 1))}
11773         [[ $AGTCOUNT -gt 0 ]] || AGTCOUNT=1
11774
11775         export SHARED_DIRECTORY=${SHARED_DIRECTORY:-$TMP}
11776         if [[ $CLIENTCOUNT -gt 1 ]] &&
11777                 ! check_shared_dir $SHARED_DIRECTORY $CLIENTS; then
11778                 skip_env "SHARED_DIRECTORY should be accessible"\
11779                          "on all client nodes"
11780                 exit 0
11781         fi
11782
11783         # We used to put the HSM archive in $SHARED_DIRECTORY but that
11784         # meant NFS issues could hose sanity-hsm sessions. So now we
11785         # use $TMP instead.
11786         for n in $(seq $AGTCOUNT); do
11787                 eval export AGTDEV$n=\$\{AGTDEV$n:-"$TMP/arc$n"\}
11788                 agent=CLIENT$((n + 1))
11789                 if [[ -z "${!agent}" ]]; then
11790                         [[ $CLIENTCOUNT -eq 1 ]] && agent=CLIENT1 ||
11791                                 agent=CLIENT2
11792                 fi
11793                 eval export agt${n}_HOST=\$\{agt${n}_HOST:-${!agent}\}
11794                 local var=agt${n}_HOST
11795                 [[ ! -z "${!var}" ]] || error "agt${n}_HOST is empty!"
11796         done
11797
11798         export SINGLEAGT=${SINGLEAGT:-agt1}
11799
11800         export HSMTOOL=${HSMTOOL:-"lhsmtool_posix"}
11801         export HSMTOOL_PID_FILE=${HSMTOOL_PID_FILE:-"/var/run/lhsmtool_posix.pid"}
11802         export HSMTOOL_VERBOSE=${HSMTOOL_VERBOSE:-""}
11803         export HSMTOOL_UPDATE_INTERVAL=${HSMTOOL_UPDATE_INTERVAL:=""}
11804         export HSMTOOL_EVENT_FIFO=${HSMTOOL_EVENT_FIFO:=""}
11805         export HSMTOOL_TESTDIR
11806         export HSMTOOL_ARCHIVE_FORMAT=${HSMTOOL_ARCHIVE_FORMAT:-v2}
11807
11808         if ! [[ $HSMTOOL =~ hsmtool ]]; then
11809                 echo "HSMTOOL = '$HSMTOOL' does not contain 'hsmtool', GLWT" >&2
11810         fi
11811
11812         HSM_ARCHIVE_NUMBER=2
11813
11814         # The test only support up to 10 MDTs
11815         MDT_PREFIX="mdt.$FSNAME-MDT000"
11816         HSM_PARAM="${MDT_PREFIX}0.hsm"
11817
11818         # archive is purged at copytool setup
11819         HSM_ARCHIVE_PURGE=true
11820
11821         # Don't allow copytool error upon start/setup
11822         HSMTOOL_NOERROR=false
11823 }
11824
11825 # Get the backend root path for the given agent facet.
11826 copytool_device() {
11827         local facet=$1
11828         local dev=AGTDEV$(facet_number $facet)
11829
11830         echo -n ${!dev}
11831 }
11832
11833 get_mdt_devices() {
11834         local mdtno
11835         # get MDT device for each mdc
11836         for mdtno in $(seq 1 $MDSCOUNT); do
11837                 local idx=$(($mdtno - 1))
11838                 MDT[$idx]=$($LCTL get_param -n \
11839                         mdc.$FSNAME-MDT000${idx}-mdc-*.mds_server_uuid |
11840                         awk '{gsub(/_UUID/,""); print $1}' | head -n1)
11841         done
11842 }
11843
11844 pkill_copytools() {
11845         local hosts="$1"
11846         local signal="$2"
11847
11848         do_nodes "$hosts" \
11849                 "pkill --pidfile=$HSMTOOL_PID_FILE --signal=$signal hsmtool"
11850 }
11851
11852 copytool_continue() {
11853         local agents=${1:-$(facet_active_host $SINGLEAGT)}
11854
11855         pkill_copytools "$agents" CONT || return 0
11856         echo "Copytool is continued on $agents"
11857 }
11858
11859 kill_copytools() {
11860         local hosts=${1:-$(facet_active_host $SINGLEAGT)}
11861
11862         echo "Killing existing copytools on $hosts"
11863         pkill_copytools "$hosts" TERM || return 0
11864         copytool_continue "$hosts"
11865 }
11866
11867 copytool_monitor_cleanup() {
11868         local facet=${1:-$SINGLEAGT}
11869         local agent=$(facet_active_host $facet)
11870
11871         if [ -n "$HSMTOOL_MONITOR_DIR" ]; then
11872                 # Should die when the copytool dies, but just in case.
11873                 local cmd="kill \\\$(cat $HSMTOOL_MONITOR_DIR/monitor_pid)"
11874                 cmd+=" 2>/dev/null || true"
11875                 do_node $agent "$cmd"
11876                 do_node $agent "rm -fr $HSMTOOL_MONITOR_DIR"
11877                 export HSMTOOL_MONITOR_DIR=
11878         fi
11879
11880         # The pdsh should die on its own when the monitor dies. Just
11881         # in case, though, try to clean up to avoid any cruft.
11882         if [ -n "$HSMTOOL_MONITOR_PDSH" ]; then
11883                 kill $HSMTOOL_MONITOR_PDSH 2>/dev/null || true
11884                 export HSMTOOL_MONITOR_PDSH=
11885         fi
11886 }
11887
11888 copytool_logfile()
11889 {
11890         local host="$(facet_host "$1")"
11891         local prefix=$TESTLOG_PREFIX
11892         [ -n "$TESTNAME" ] && prefix+=.$TESTNAME
11893
11894         printf "${prefix}.copytool${archive_id}_log.${host}.log"
11895 }
11896
11897 __lhsmtool_rebind()
11898 {
11899         do_facet $facet $HSMTOOL \
11900                 "${hsmtool_options[@]}" --rebind "$@" "$mountpoint"
11901 }
11902
11903 __lhsmtool_import()
11904 {
11905         mkdir -p "$(dirname "$2")" ||
11906                 error "cannot create directory '$(dirname "$2")'"
11907         do_facet $facet $HSMTOOL \
11908                 "${hsmtool_options[@]}" --import "$@" "$mountpoint"
11909 }
11910
11911 __lhsmtool_setup()
11912 {
11913         local host="$(facet_host "$facet")"
11914         local cmd="$HSMTOOL ${hsmtool_options[@]} --daemon --pid-file=$HSMTOOL_PID_FILE"
11915
11916         [ -n "$bandwidth" ] && cmd+=" --bandwidth $bandwidth"
11917         [ -n "$archive_id" ] && cmd+=" --archive $archive_id"
11918         #       [ ${#misc_options[@]} -gt 0 ] &&
11919 #               cmd+=" $(IFS=" " echo "$@")"
11920         cmd+=" $@ \"$mountpoint\""
11921
11922         echo "Starting copytool '$facet' on '$host' with cmdline '$cmd'"
11923         stack_trap "pkill_copytools $host TERM || true" EXIT
11924         do_node "$host" "$cmd < /dev/null > \"$(copytool_logfile $facet)\" 2>&1"
11925 }
11926
11927 hsm_root() {
11928         local facet="${1:-$SINGLEAGT}"
11929
11930         printf "$(copytool_device "$facet")/${TESTSUITE}.${TESTNAME}/"
11931 }
11932
11933 # Main entry point to perform copytool related operations
11934 #
11935 # Sub-commands:
11936 #
11937 #       setup   setup a copytool to run in the background, that copytool will be
11938 #               killed on EXIT
11939 #       import  import a file from an HSM backend
11940 #       rebind  rebind an archived file to a new fid
11941 #
11942 # Although the semantics might suggest otherwise, one does not need to 'setup'
11943 # a copytool before a call to 'copytool import' or 'copytool rebind'.
11944 #
11945 copytool()
11946 {
11947         local action=$1
11948         shift
11949
11950         # Use default values
11951         local facet=$SINGLEAGT
11952         local mountpoint="${MOUNT2:-$MOUNT}"
11953
11954         # Parse arguments
11955         local fail_on_error=true
11956         local -a hsmtool_options=()
11957         local -a action_options=()
11958
11959         if [[ -n "$HSMTOOL_ARCHIVE_FORMAT" ]]; then
11960                 hsmtool_options+=("--archive-format=$HSMTOOL_ARCHIVE_FORMAT")
11961         fi
11962
11963         if [[ -n "$HSMTOOL_VERBOSE" ]]; then
11964                 hsmtool_options+=("$HSMTOOL_VERBOSE")
11965         fi
11966
11967         while [ $# -gt 0 ]; do
11968                 case "$1" in
11969                 -f|--facet)
11970                         shift
11971                         facet="$1"
11972                         ;;
11973                 -m|--mountpoint)
11974                         shift
11975                         mountpoint="$1"
11976                         ;;
11977                 -a|--archive-id)
11978                         shift
11979                         local archive_id="$1"
11980                         ;;
11981                 -h|--hsm-root)
11982                         shift
11983                         local hsm_root="$1"
11984                         ;;
11985                 -b|--bwlimit)
11986                         shift
11987                         local bandwidth="$1" # in MB/s
11988                         ;;
11989                 -n|--no-fail)
11990                         local fail_on_error=false
11991                         ;;
11992                 *)
11993                         # Uncommon(/copytool dependent) option
11994                         action_options+=("$1")
11995                         ;;
11996                 esac
11997                 shift
11998         done
11999
12000         local hsm_root="${hsm_root:-$(hsm_root "$facet")}"
12001         hsmtool_options+=("--hsm-root=$hsm_root")
12002
12003         stack_trap "do_facet $facet rm -rf '$hsm_root'" EXIT
12004         do_facet $facet mkdir -p "$hsm_root" ||
12005                 error "mkdir '$hsm_root' failed"
12006
12007         case "$HSMTOOL" in
12008         lhsmtool_posix)
12009                 local copytool=lhsmtool
12010                 ;;
12011         esac
12012
12013         __${copytool}_${action} "${action_options[@]}"
12014         if [ $? -ne 0 ]; then
12015                 local error_msg
12016
12017                 case $action in
12018                 setup)
12019                         local host="$(facet_host $facet)"
12020                         error_msg="Failed to start copytool $facet on '$host'"
12021                         ;;
12022                 import)
12023                         local src="${action_options[0]}"
12024                         local dest="${action_options[1]}"
12025                         error_msg="Failed to import '$src' to '$dest'"
12026                         ;;
12027                 rebind)
12028                         error_msg="could not rebind file"
12029                         ;;
12030                 esac
12031
12032                 $fail_on_error && error "$error_msg" || echo "$error_msg"
12033         fi
12034 }
12035
12036 needclients() {
12037         local client_count=$1
12038         if [[ $CLIENTCOUNT -lt $client_count ]]; then
12039                 skip "Need $client_count or more clients, have $CLIENTCOUNT"
12040                 return 1
12041         fi
12042         return 0
12043 }
12044
12045 path2fid() {
12046         $LFS path2fid $1 | tr -d '[]'
12047         return ${PIPESTATUS[0]}
12048 }
12049
12050 get_hsm_flags() {
12051         local f=$1
12052         local u=$2
12053         local st
12054
12055         if [[ $u == "user" ]]; then
12056                 st=$($RUNAS $LFS hsm_state $f)
12057         else
12058                 u=root
12059                 st=$($LFS hsm_state $f)
12060         fi
12061
12062         [[ $? == 0 ]] || error "$LFS hsm_state $f failed (run as $u)"
12063
12064         st=$(echo $st | cut -f 2 -d" " | tr -d "()," )
12065         echo $st
12066 }
12067
12068 check_hsm_flags() {
12069         local f=$1
12070         local fl=$2
12071
12072         local st=$(get_hsm_flags $f)
12073         [[ $st == $fl ]] || error "hsm flags on $f are $st != $fl"
12074 }
12075
12076 mdts_set_param() {
12077         local arg=$1
12078         local key=$2
12079         local value=$3
12080         local mdtno
12081         local rc=0
12082         if [[ "$value" != "" ]]; then
12083                 value="='$value'"
12084         fi
12085         for mdtno in $(seq 1 $MDSCOUNT); do
12086                 local idx=$(($mdtno - 1))
12087                 local facet=mds${mdtno}
12088                 # if $arg include -P option, run 1 set_param per MDT on the MGS
12089                 # else, run set_param on each MDT
12090                 [[ $arg = *"-P"* ]] && facet=mgs
12091                 do_facet $facet $LCTL set_param $arg mdt.${MDT[$idx]}.$key$value ||
12092                         rc=$?
12093         done
12094         return $rc
12095 }
12096
12097 mdts_check_param() {
12098         local key="$1"
12099         local target="$2"
12100         local timeout="$3"
12101         local mdtno
12102
12103         for mdtno in $(seq 1 $MDSCOUNT); do
12104                 local idx=$(($mdtno - 1))
12105                 wait_update_facet --verbose mds${mdtno} \
12106                         "$LCTL get_param -n $MDT_PREFIX${idx}.$key" "$target" \
12107                         $timeout ||
12108                         error "$key state is not '$target' on mds${mdtno}"
12109         done
12110 }
12111
12112 cdt_set_mount_state() {
12113         mdts_set_param "-P" hsm_control "$1"
12114         # set_param -P is asynchronous operation and could race with set_param.
12115         # In such case configs could be retrieved and applied at mgc after
12116         # set_param -P completion. Sleep here to avoid race with set_param.
12117         # We need at least 20 seconds. 10 for mgc_requeue_thread to wake up
12118         # MGC_TIMEOUT_MIN_SECONDS + MGC_TIMEOUT_RAND_CENTISEC(5 + 5)
12119         # and 10 seconds to retrieve config from server.
12120         sleep 20
12121 }
12122
12123 cdt_check_state() {
12124         mdts_check_param hsm_control "$1" 20
12125 }
12126
12127 cdt_set_sanity_policy() {
12128         if [[ "$CDT_POLICY_HAD_CHANGED" ]]
12129         then
12130                 # clear all
12131                 mdts_set_param "" hsm.policy "+NRA"
12132                 mdts_set_param "" hsm.policy "-NBR"
12133                 CDT_POLICY_HAD_CHANGED=
12134         fi
12135 }
12136
12137 set_hsm_param() {
12138         local param=$1
12139         local value=$2
12140         local opt=$3
12141         mdts_set_param "$opt -n" "hsm.$param" "$value"
12142         return $?
12143 }
12144
12145 wait_request_state() {
12146         local fid=$1
12147         local request=$2
12148         local state=$3
12149         # 4th arg (mdt index) is optional
12150         local mdtidx=${4:-0}
12151         local mds=mds$(($mdtidx + 1))
12152
12153         local cmd="$LCTL get_param -n ${MDT_PREFIX}${mdtidx}.hsm.actions"
12154         cmd+=" | awk '/'$fid'.*action='$request'/ {print \\\$13}' | cut -f2 -d="
12155
12156         wait_update_facet --verbose $mds "$cmd" "$state" 200 ||
12157                 error "request on $fid is not $state on $mds"
12158 }
12159
12160
12161 rmultiop_start() {
12162         local client=$1
12163         local file=$2
12164         local cmds=$3
12165         local WAIT_MAX=${4:-60}
12166         local wait_time=0
12167
12168         # We need to run do_node in bg, because pdsh does not exit
12169         # if child process of run script exists.
12170         # I.e. pdsh does not exit when runmultiop_bg_pause exited,
12171         # because of multiop_bg_pause -> $MULTIOP_PROG &
12172         # By the same reason we need sleep a bit after do_nodes starts
12173         # to let runmultiop_bg_pause start muliop and
12174         # update /tmp/multiop_bg.pid ;
12175         # The rm /tmp/multiop_bg.pid guarantees here that
12176         # we have the updated by runmultiop_bg_pause
12177         # /tmp/multiop_bg.pid file
12178
12179         local pid_file=$TMP/multiop_bg.pid.$$
12180
12181         do_node $client "MULTIOP_PID_FILE=$pid_file LUSTRE= \
12182                         runmultiop_bg_pause $file $cmds" &
12183         local pid=$!
12184         local multiop_pid
12185
12186         while [[ $wait_time -lt $WAIT_MAX ]]; do
12187                 sleep 3
12188                 wait_time=$((wait_time + 3))
12189                 multiop_pid=$(do_node $client cat $pid_file)
12190                 if [ -n "$multiop_pid" ]; then
12191                         break
12192                 fi
12193         done
12194
12195         [ -n "$multiop_pid" ] ||
12196                 error "$client : Can not get multiop_pid from $pid_file "
12197
12198         eval export $(node_var_name $client)_multiop_pid=$multiop_pid
12199         eval export $(node_var_name $client)_do_node_pid=$pid
12200         local var=$(node_var_name $client)_multiop_pid
12201         echo client $client multiop_bg started multiop_pid=${!var}
12202         return $?
12203 }
12204
12205 rmultiop_stop() {
12206         local client=$1
12207         local multiop_pid=$(node_var_name $client)_multiop_pid
12208         local do_node_pid=$(node_var_name $client)_do_node_pid
12209
12210         echo "Stopping multiop_pid=${!multiop_pid} (kill ${!multiop_pid} on $client)"
12211         do_node $client kill -USR1 ${!multiop_pid}
12212
12213         wait ${!do_node_pid}
12214 }
12215
12216 sleep_maxage() {
12217         local delay=$(do_facet mds1 lctl get_param -n lod.*.qos_maxage |
12218                       awk '{ print $1 + 5; exit; }')
12219         sleep $delay
12220 }
12221
12222 sleep_maxage_lmv() {
12223         local delay=$(lctl get_param -n lmv.*.qos_maxage |
12224                       awk '{ print $1 + 5; exit; }')
12225         sleep $delay
12226 }
12227
12228 check_component_count() {
12229         local comp_cnt=$($LFS getstripe --component-count $1)
12230         [ $comp_cnt -eq $2 ] || error "$1, component count $comp_cnt != $2"
12231 }
12232
12233 # Verify there are no init components with "extension" flag
12234 verify_no_init_extension() {
12235         local flg_opts="--component-flags init,extension"
12236         local found=$($LFS find $flg_opts $1 | wc -l)
12237         [ $found -eq 0 ] || error "$1 has component with initialized extension"
12238 }
12239
12240 # Verify there is at least one component starting at 0
12241 verify_comp_at_zero() {
12242         flg_opts="--component-flags init"
12243         found=$($LFS find --component-start 0M $flg_opts $1 | wc -l)
12244         [ $found -eq 1 ] ||
12245                 error "No component starting at zero(!)"
12246 }
12247
12248 # version after which Self-Extending Layouts are available
12249 SEL_VER="2.12.55"
12250
12251 sel_layout_sanity() {
12252         local file=$1
12253         local comp_cnt=$2
12254
12255         verify_no_init_extension $file
12256         verify_comp_at_zero $file
12257         check_component_count $file $comp_cnt
12258 }
12259
12260 statx_supported() {
12261         $STATX --quiet --version
12262         return $?
12263 }
12264
12265 # lfs rm_entry is disabled on native client
12266 is_rmentry_supported() {
12267         $LFS rm_entry $DIR/dir/not/exists > /dev/null
12268         # is return code ENOENT?
12269         (( $? == 2 ))
12270 }
12271
12272 #
12273 # wrappers for createmany and unlinkmany
12274 # to set debug=0 if number of creates is high enough
12275 # this is to speedup testing
12276 #
12277 function createmany() {
12278         local count=${!#}
12279         local rc
12280
12281         if (( count > 100 )); then
12282                 debugsave
12283                 do_nodes $(comma_list $(all_nodes)) $LCTL set_param -n debug=ha
12284         fi
12285         $LUSTRE/tests/createmany $*
12286         rc=$?
12287         debugrestore > /dev/null
12288
12289         return $rc
12290 }
12291
12292 function unlinkmany() {
12293         local count=${!#}
12294         local rc
12295
12296         if (( count > 100 )); then
12297                 debugsave
12298                 do_nodes $(comma_list $(all_nodes)) $LCTL set_param -n debug=0
12299         fi
12300         $LUSTRE/tests/unlinkmany $*
12301         rc=$?
12302         debugrestore > /dev/null
12303
12304         return $rc
12305 }
12306
12307 # Check if fallocate on facet is working. Returns fallocate mode if enabled.
12308 # Takes optional facet name as argument, to allow separate MDS/OSS checks.
12309 function check_fallocate_supported()
12310 {
12311         local facet=${1:-ost1}
12312         local supported="FALLOCATE_SUPPORTED_$facet"
12313         local fstype="${facet}_FSTYPE"
12314
12315         if [[ -n "${!supported}" ]]; then
12316                 echo "${!supported}"
12317                 return 0
12318         fi
12319         if [[ -z "${!fstype}" ]]; then
12320                 eval export $fstype=$(facet_fstype $facet)
12321         fi
12322         if [[ "${!fstype}" != "ldiskfs" ]]; then
12323                 echo "fallocate on ${!fstype} doesn't consume space" 1>&2
12324                 return 1
12325         fi
12326
12327         local fa_mode="osd-ldiskfs.$(facet_svc $facet).fallocate_zero_blocks"
12328         local mode=$(do_facet $facet $LCTL get_param -n $fa_mode 2>/dev/null |
12329                      head -n 1)
12330         ! [[ "$facet" =~ "mds" ]] || # older MDS doesn't support fallocate
12331                 (( MDS1_VERSION >= $(version_code v2_14_53-10-g163870abfb) )) ||
12332                         mode=""
12333
12334         if [[ -z "$mode" ]]; then
12335                 echo "fallocate not supported on $facet" 1>&2
12336                 return 1
12337         fi
12338         eval export $supported="$mode"
12339
12340         echo ${!supported}
12341         return 0
12342 }
12343
12344 # Check if fallocate supported on OSTs, enable if unset, skip if unavailable.
12345 # Takes optional facet name as argument.
12346 function check_fallocate_or_skip()
12347 {
12348         local facet=$1
12349
12350         check_fallocate_supported $1 || skip "fallocate not supported"
12351 }
12352
12353 # Check if fallocate supported on OSTs, enable if unset, default mode=0
12354 # Optionally pass the OST fallocate mode (0=unwritten extents, 1=zero extents)
12355 function check_set_fallocate()
12356 {
12357         local new_mode="$1"
12358         local fa_mode="osd-ldiskfs.*.fallocate_zero_blocks"
12359         local old_mode="$(check_fallocate_supported)"
12360
12361         [[ -n "$old_mode" ]] || { echo "fallocate not supported"; return 1; }
12362         [[ -z "$new_mode" && "$old_mode" != "-1" ]] &&
12363                 { echo "keep default fallocate mode: $old_mode"; return 0; }
12364         [[ "$new_mode" && "$old_mode" == "$new_mode" ]] &&
12365                 { echo "keep current fallocate mode: $old_mode"; return 0; }
12366         local osts=$(osts_nodes)
12367
12368         stack_trap "do_nodes $osts $LCTL set_param $fa_mode=$old_mode"
12369         do_nodes $osts $LCTL set_param $fa_mode=${new_mode:-0} ||
12370                 error "set $fa_mode=$new_mode"
12371 }
12372
12373 # Check if fallocate supported on OSTs, enable if unset, skip if unavailable
12374 function check_set_fallocate_or_skip()
12375 {
12376         check_set_fallocate || skip "need >= 2.13.57 and ldiskfs for fallocate"
12377 }
12378
12379 function disable_opencache()
12380 {
12381         local state=$($LCTL get_param -n "llite.*.opencache_threshold_count" |
12382                         head -1)
12383
12384         test -z "${saved_OPENCACHE_value}" &&
12385                                         export saved_OPENCACHE_value="$state"
12386
12387         [[ "$state" = "off" ]] && return
12388
12389         $LCTL set_param -n "llite.*.opencache_threshold_count"=off
12390 }
12391
12392 function set_opencache()
12393 {
12394         local newvalue="$1"
12395         local state=$($LCTL get_param -n "llite.*.opencache_threshold_count")
12396
12397         [[ -n "$newvalue" ]] || return
12398
12399         [[ -n "${saved_OPENCACHE_value}" ]] ||
12400                                         export saved_OPENCACHE_value="$state"
12401
12402         $LCTL set_param -n "llite.*.opencache_threshold_count"=$newvalue
12403 }
12404
12405
12406
12407 function restore_opencache()
12408 {
12409         [[ -z "${saved_OPENCACHE_value}" ]] ||
12410                 $LCTL set_param -n "llite.*.opencache_threshold_count"=${saved_OPENCACHE_value}
12411 }
12412
12413 # LU-13417: XXX lots of tests assume the directory to be created under MDT0,
12414 # created on MDT0, use this function to create directory on specific MDT
12415 # explicitly, and set default LMV to create subdirs on the same MDT too.
12416 mkdir_on_mdt() {
12417         local mdt
12418         local OPTIND=1
12419
12420         while getopts "i:" opt $*; do
12421                 case $opt in
12422                         i) mdt=$OPTARG;;
12423                 esac
12424         done
12425
12426         shift $((OPTIND - 1))
12427
12428         $LFS mkdir -i $mdt -c 1 $*
12429 }
12430
12431 mkdir_on_mdt0() {
12432         mkdir_on_mdt -i0 $*
12433 }
12434
12435 # Wait for nodemap synchronization
12436 wait_nm_sync() {
12437         local nodemap_name=$1
12438         local key=$2
12439         local value=$3
12440         local opt=$4
12441         local proc_param
12442         local is_active=$(do_facet mgs $LCTL get_param -n nodemap.active)
12443         local max_retries=20
12444         local is_sync
12445         local out1=""
12446         local out2
12447         local mgs_ip=$(host_nids_address $mgs_HOST $NETTYPE | cut -d' ' -f1)
12448         local i
12449
12450         if [ "$nodemap_name" == "active" ]; then
12451                 proc_param="active"
12452         elif [ -z "$key" ]; then
12453                 proc_param=${nodemap_name}
12454         else
12455                 proc_param="${nodemap_name}.${key}"
12456         fi
12457         if [ "$opt" == "inactive" ]; then
12458                 # check nm sync even if nodemap is not activated
12459                 is_active=1
12460                 opt=""
12461         fi
12462         (( is_active == 0 )) && [ "$proc_param" != "active" ] && return
12463
12464         if [ -z "$value" ]; then
12465                 out1=$(do_facet mgs $LCTL get_param $opt \
12466                         nodemap.${proc_param} 2>/dev/null)
12467                 echo "On MGS ${mgs_ip}, ${proc_param} = $out1"
12468         else
12469                 out1=$value;
12470         fi
12471
12472         # if servers run on the same node, it is impossible to tell if they get
12473         # synced with the mgs, so just wait an arbitrary 10 seconds
12474         if [ $(facet_active_host mgs) == $(facet_active_host mds) ] &&
12475            [ $(facet_active_host mgs) == $(facet_active_host ost1) ]; then
12476                 echo "waiting 10 secs for sync"
12477                 sleep 10
12478                 return
12479         fi
12480
12481         # wait up to 10 seconds for other servers to sync with mgs
12482         for i in $(seq 1 10); do
12483                 for node in $(all_server_nodes); do
12484                         local node_ip=$(host_nids_address $node $NETTYPE |
12485                                         cut -d' ' -f1)
12486
12487                         is_sync=true
12488                         if [ -z "$value" ]; then
12489                                 [ $node_ip == $mgs_ip ] && continue
12490                         fi
12491
12492                         out2=$(do_node $node $LCTL get_param $opt \
12493                                nodemap.$proc_param 2>/dev/null)
12494                         echo "On $node ${node_ip}, ${proc_param} = $out2"
12495                         [ "$out1" != "$out2" ] && is_sync=false && break
12496                 done
12497                 $is_sync && break
12498                 sleep 1
12499         done
12500         if ! $is_sync; then
12501                 echo MGS
12502                 echo $out1
12503                 echo OTHER - IP: $node_ip
12504                 echo $out2
12505                 error "mgs and $nodemap_name ${key} mismatch, $i attempts"
12506         fi
12507         echo "waited $((i - 1)) seconds for sync"
12508 }
12509
12510 consume_precreations() {
12511         local dir=$1
12512         local mfacet=$2
12513         local OSTIDX=$3
12514         local extra=${4:-2}
12515         local OST=$(ostname_from_index $OSTIDX $dir)
12516
12517         mkdir_on_mdt -i $(facet_index $mfacet) $dir/${OST}
12518         $LFS setstripe -i $OSTIDX -c 1 ${dir}/${OST}
12519
12520         # on the mdt's osc
12521         local mdtosc_proc=$(get_mdtosc_proc_path $mfacet $OST)
12522         local last_id=$(do_facet $mfacet $LCTL get_param -n \
12523                         osp.$mdtosc_proc.prealloc_last_id)
12524         local next_id=$(do_facet $mfacet $LCTL get_param -n \
12525                         osp.$mdtosc_proc.prealloc_next_id)
12526         echo "Creating to objid $last_id on ost $OST..."
12527         createmany -o $dir/${OST}/f $next_id $((last_id - next_id + extra))
12528 }
12529
12530 __exhaust_precreations() {
12531         local OSTIDX=$1
12532         local FAILLOC=$2
12533         local FAILIDX=${3:-$OSTIDX}
12534         local ofacet=ost$((OSTIDX + 1))
12535
12536         mkdir_on_mdt0 $DIR/$tdir
12537         local mdtidx=$($LFS getstripe -m $DIR/$tdir)
12538         local mfacet=mds$((mdtidx + 1))
12539         echo OSTIDX=$OSTIDX MDTIDX=$mdtidx
12540
12541         local mdtosc_proc=$(get_mdtosc_proc_path $mfacet)
12542         do_facet $mfacet $LCTL get_param osp.$mdtosc_proc.prealloc*
12543
12544 #define OBD_FAIL_OST_ENOSPC              0x215
12545         do_facet $ofacet $LCTL set_param fail_val=$FAILIDX fail_loc=0x215
12546
12547         consume_precreations $DIR/$tdir $mfacet $OSTIDX
12548
12549         do_facet $mfacet $LCTL get_param osp.$mdtosc_proc.prealloc*
12550         do_facet $ofacet $LCTL set_param fail_loc=$FAILLOC
12551 }
12552
12553 exhaust_precreations() {
12554         __exhaust_precreations $1 $2 $3
12555         sleep_maxage
12556 }
12557
12558 exhaust_all_precreations() {
12559         local i
12560         for (( i=0; i < OSTCOUNT; i++ )) ; do
12561                 __exhaust_precreations $i $1 -1
12562         done
12563         sleep_maxage
12564 }
12565
12566 force_new_seq_ost() {
12567         local dir=$1
12568         local mfacet=$2
12569         local OSTIDX=$3
12570         local OST=$(ostname_from_index $OSTIDX)
12571         local mdtosc_proc=$(get_mdtosc_proc_path $mfacet $OST)
12572
12573         do_facet $mfacet $LCTL set_param \
12574                 osp.$mdtosc_proc.prealloc_force_new_seq=1
12575         # consume preallocated objects, to wake up precreate thread
12576         consume_precreations $dir $mfacet $OSTIDX
12577         do_facet $mfacet $LCTL set_param \
12578                 osp.$mdtosc_proc.prealloc_force_new_seq=0
12579 }
12580
12581 force_new_seq() {
12582         local mfacet=$1
12583         local MDTIDX=$(facet_index $mfacet)
12584         local MDT=$(mdtname_from_index $MDTIDX $DIR)
12585         local i
12586
12587         mkdir_on_mdt -i $MDTIDX $DIR/${MDT}
12588         for (( i=0; i < OSTCOUNT; i++ )) ; do
12589                 force_new_seq_ost $DIR/${MDT} $mfacet $i &
12590         done
12591         wait
12592         rm -rf $DIR/${MDT}
12593 }
12594
12595 force_new_seq_all() {
12596         local i
12597
12598         for (( i=0; i < MDSCOUNT; i++ )) ; do
12599                 force_new_seq mds$((i + 1)) &
12600         done
12601         wait
12602         sleep_maxage
12603 }
12604
12605 ost_set_temp_seq_width_all() {
12606         local osts=$(osts_nodes)
12607         local width=$(do_facet ost1 $LCTL get_param -n seq.*OST0000-super.width)
12608
12609         (( $width != $1 )) || return 0
12610
12611         do_nodes $osts $LCTL set_param seq.*OST*-super.width=$1
12612         stack_trap "do_nodes $osts $LCTL set_param seq.*OST*-super.width=$width"
12613 }
12614
12615 verify_yaml_available() {
12616         python3 -c "import yaml; yaml.safe_load('''a: b''')"
12617 }
12618
12619 verify_yaml() {
12620         python3 -c "import sys, yaml; obj = yaml.safe_load(sys.stdin)"
12621 }
12622
12623 verify_compare_yaml() {
12624         python3 -c "import sys, yaml; f=open(\"$1\", \"r\"); obj1 = yaml.safe_load(f); f=open(\"$2\", \"r\"); obj2 = yaml.safe_load(f); sys.exit(obj1 != obj2)"
12625 }
12626
12627 zfs_or_rotational() {
12628         local ost_idx=0
12629         local ost_name=$(ostname_from_index $ost_idx $MOUNT)
12630         local param="get_param -n osd-*.${ost_name}.nonrotational"
12631         local nonrotat=$(do_facet ost1 $LCTL $param)
12632
12633         if [[ -z "$nonrotat" ]]; then
12634                 # At this point there is no point moving ahead.
12635                 # Will stop here and dump all the info
12636                 set -x
12637                 local ost_name=$(ostname_from_index $ost_idx)
12638                 set +x
12639                 error "$LCTL $input_str"
12640         fi
12641
12642         if [[ "$ost1_FSTYPE" == "zfs" ]] || (( "$nonrotat" == 0 )); then
12643                 return 0
12644         else
12645                 return 1
12646         fi
12647 }
12648
12649 ost_fid2_objpath() {
12650         local facet=$1
12651         local fid=$2
12652
12653         fid=$(echo $fid | tr -d '[]')
12654
12655         seq=$(echo $fid | awk -F ':' '{ print $1 }' | sed -e "s/^0x//g")
12656         oidhex=$(echo $fid | awk -F ':' '{ print $2 }')
12657
12658         if [ $seq == 0 ] || [ $(facet_fstype $facet) == zfs ]; then
12659                 oid=$((16#${oidhex#0x}))
12660         else
12661                 oid=${oidhex#0x}
12662         fi
12663
12664         echo "O/$seq/d$((oidhex%32))/$oid"
12665 }
12666
12667 check_seq_oid()
12668 {
12669         log "check file $1"
12670
12671         lmm_count=$($LFS getstripe -c $1)
12672         lmm_seq=$($LFS getstripe -v $1 | awk '/lmm_seq/ { print $2 }')
12673         lmm_oid=$($LFS getstripe -v $1 | awk '/lmm_object_id/ { print $2 }')
12674
12675         local old_ifs="$IFS"
12676         IFS=$'[:]'
12677         fid=($($LFS path2fid $1))
12678         IFS="$old_ifs"
12679
12680         log "FID seq ${fid[1]}, oid ${fid[2]} ver ${fid[3]}"
12681         log "LOV seq $lmm_seq, oid $lmm_oid, count: $lmm_count"
12682
12683         # compare lmm_seq and lu_fid->f_seq
12684         [ $lmm_seq = ${fid[1]} ] || error "SEQ mismatch"
12685         # compare lmm_object_id and lu_fid->oid
12686         [ $lmm_oid = ${fid[2]} ] || error "OID mismatch"
12687
12688         # check the trusted.fid attribute of the OST objects of the file
12689         local have_obdidx=false
12690         local stripe_nr=0
12691         $LFS getstripe $1 | while read obdidx oid hex seq; do
12692                 # skip lines up to and including "obdidx"
12693                 [ -z "$obdidx" ] && break
12694                 [ "$obdidx" = "obdidx" ] && have_obdidx=true && continue
12695                 $have_obdidx || continue
12696
12697                 local ost=$((obdidx + 1))
12698                 local dev=$(ostdevname $ost)
12699
12700                 log "want: stripe:$stripe_nr ost:$obdidx oid:$oid/$hex seq:$seq"
12701
12702                 local obj_file=$(ost_fid2_objpath ost$ost "$seq:$hex:0")
12703
12704                 local ff=""
12705                 #
12706                 # Don't unmount/remount the OSTs if we don't need to do that.
12707                 # LU-2577 changes filter_fid to be smaller, so debugfs needs
12708                 # update too, until that use mount/ll_decode_filter_fid/mount.
12709                 # Re-enable when debugfs will understand new filter_fid.
12710                 #
12711                 if [ $(facet_fstype ost$ost) == ldiskfs ]; then
12712                         ff=$(do_facet ost$ost "$DEBUGFS -c -R 'stat $obj_file' \
12713                                 $dev 2>/dev/null" | grep "parent=")
12714                 fi
12715                 if [ -z "$ff" ]; then
12716                         stop ost$ost
12717                         mount_fstype ost$ost
12718                         ff=$(do_facet ost$ost $LL_DECODE_FILTER_FID \
12719                                 $(facet_mntpt ost$ost)/$obj_file)
12720                         unmount_fstype ost$ost
12721                         start ost$ost $dev $OST_MOUNT_OPTS
12722                         clients_up
12723                 fi
12724
12725                 [ -z "$ff" ] && error "$obj_file: no filter_fid info"
12726
12727                 echo "$ff" | sed -e 's#.*objid=#got: objid=#'
12728
12729                 # /mnt/O/0/d23/23: objid=23 seq=0 parent=[0x200000400:0x1e:0x1]
12730                 # fid: objid=23 seq=0 parent=[0x200000400:0x1e:0x0] stripe=1
12731                 #
12732                 # fid: parent=[0x200000400:0x1e:0x0] stripe=1 stripe_count=2 \
12733                 #       stripe_size=1048576 component_id=1 component_start=0 \
12734                 #       component_end=33554432
12735                 local ff_parent=$(sed -e 's/.*parent=.//' <<<$ff)
12736                 local ff_pseq=$(cut -d: -f1 <<<$ff_parent)
12737                 local ff_poid=$(cut -d: -f2 <<<$ff_parent)
12738                 local ff_pstripe
12739                 if grep -q 'stripe=' <<<$ff; then
12740                         ff_pstripe=$(sed -e 's/.*stripe=//' -e 's/ .*//' <<<$ff)
12741                 else
12742                         # $LL_DECODE_FILTER_FID does not print "stripe="; look
12743                         # into f_ver in this case.  See comment on ff_parent.
12744                         ff_pstripe=$(cut -d: -f3 <<<$ff_parent | sed -e 's/]//')
12745                 fi
12746
12747                 # compare lmm_seq and filter_fid->ff_parent.f_seq
12748                 [ $ff_pseq = $lmm_seq ] ||
12749                         error "FF parent SEQ $ff_pseq != $lmm_seq"
12750                 # compare lmm_object_id and filter_fid->ff_parent.f_oid
12751                 [ $ff_poid = $lmm_oid ] ||
12752                         error "FF parent OID $ff_poid != $lmm_oid"
12753                 (($ff_pstripe == $stripe_nr)) ||
12754                         error "FF stripe $ff_pstripe != $stripe_nr"
12755
12756                 stripe_nr=$((stripe_nr + 1))
12757                 [ $CLIENT_VERSION -lt $(version_code 2.9.55) ] &&
12758                         continue
12759                 if grep -q 'stripe_count=' <<<$ff; then
12760                         local ff_scnt=$(sed -e 's/.*stripe_count=//' \
12761                                             -e 's/ .*//' <<<$ff)
12762                         [ $lmm_count = $ff_scnt ] ||
12763                                 error "FF stripe count $lmm_count != $ff_scnt"
12764                 fi
12765         done
12766 }