overlay: configure TEST/SCRATCH vars to base fs
[xfstests-dev.git] / common / rc
1 ##/bin/bash
2 #-----------------------------------------------------------------------
3 #  Copyright (c) 2000-2006 Silicon Graphics, Inc.  All Rights Reserved.
4 #  This program is free software; you can redistribute it and/or modify
5 #  it under the terms of the GNU General Public License as published by
6 #  the Free Software Foundation; either version 2 of the License, or
7 #  (at your option) any later version.
8 #
9 #  This program is distributed in the hope that it will be useful,
10 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
11 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 #  GNU General Public License for more details.
13 #
14 #  You should have received a copy of the GNU General Public License
15 #  along with this program; if not, write to the Free Software
16 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
17 #  USA
18 #
19 #  Contact information: Silicon Graphics, Inc., 1500 Crittenden Lane,
20 #  Mountain View, CA 94043, USA, or: http://www.sgi.com
21 #-----------------------------------------------------------------------
22
23 BC=$(which bc 2> /dev/null) || BC=
24
25 # Valid test names start with 3 digits "NNN":
26 #  "[0-9]\{3\}"
27 # followed by an optional "-":
28 #  "-\?"
29 # followed by an optional combination of alphanumeric and "-" chars:
30 #  "[[:alnum:]-]*"
31 # e.g. 999-the-mark-of-fstests
32 #
33 VALID_TEST_ID="[0-9]\{3\}"
34 VALID_TEST_NAME="$VALID_TEST_ID-\?[[:alnum:]-]*"
35
36 _require_math()
37 {
38         if [ -z "$BC" ]; then
39                 _notrun "this test requires 'bc' tool for doing math operations"
40         fi
41 }
42
43 _math()
44 {
45         [ $# -le 0 ] && return
46         if [ "$BC" ]; then
47                 result=$(LANG=C echo "scale=0; $@" | "$BC" -q 2> /dev/null)
48         else
49                 _notrun "this test requires 'bc' tool for doing math operations"
50         fi
51         echo "$result"
52 }
53
54 dd()
55 {
56    if [ "$HOSTOS" == "Linux" ]
57    then 
58         command dd --help 2>&1 | grep noxfer >/dev/null
59         
60         if [ "$?" -eq 0 ]
61             then
62                 command dd status=noxfer $@
63             else
64                 command dd $@
65         fi
66    else
67         command dd $@
68    fi
69 }
70
71 # Prints the md5 checksum of a given file
72 _md5_checksum()
73 {
74         md5sum $1 | cut -d ' ' -f1
75 }
76
77 # Write a byte into a range of a file
78 _pwrite_byte() {
79         pattern="$1"
80         offset="$2"
81         len="$3"
82         file="$4"
83         xfs_io_args="$5"
84
85         $XFS_IO_PROG $xfs_io_args -f -c "pwrite -S $pattern $offset $len" "$file"
86 }
87
88 # mmap-write a byte into a range of a file
89 _mwrite_byte() {
90         pattern="$1"
91         offset="$2"
92         len="$3"
93         mmap_len="$4"
94         file="$5"
95
96         $XFS_IO_PROG -f -c "mmap -rw 0 $mmap_len" -c "mwrite -S $pattern $offset $len" "$file"
97 }
98
99 # ls -l w/ selinux sometimes puts a dot at the end:
100 # -rwxrw-r--. id1 id2 file1
101 # Also filter out lost+found directory on extN file system if present
102
103 _ls_l()
104 {
105         ls -l $* | sed "s/\(^[-rwxdlbcpsStT]*\)\. /\1 /" | grep -v 'lost+found'
106 }
107
108 # we need common/config
109 if [ "$iam" != "check" ]
110 then
111     if ! . ./common/config
112         then
113         echo "$iam: failed to source common/config"
114         exit 1
115     fi
116 fi
117
118 # make sure we have a standard umask
119 umask 022
120
121 # check for correct setup and source the $FSTYP specific functions now
122 case "$FSTYP" in
123     xfs)
124          [ "$XFS_LOGPRINT_PROG" = "" ] && _fatal "xfs_logprint not found"
125          [ "$XFS_REPAIR_PROG" = "" ] && _fatal "xfs_repair not found"
126          [ "$XFS_DB_PROG" = "" ] && _fatal "xfs_db not found"
127          [ "$MKFS_XFS_PROG" = "" ] && _fatal "mkfs_xfs not found"
128
129          . ./common/xfs
130          ;;
131     udf)
132          [ "$MKFS_UDF_PROG" = "" ] && _fatal "mkfs_udf/mkudffs not found"
133          ;;
134     btrfs)
135          [ "$MKFS_BTRFS_PROG" = "" ] && _fatal "mkfs.btrfs not found"
136
137          . ./common/btrfs
138          ;;
139     ext4)
140          [ "$MKFS_EXT4_PROG" = "" ] && _fatal "mkfs.ext4 not found"
141          ;;
142     f2fs)
143          [ "$MKFS_F2FS_PROG" = "" ] && _fatal "mkfs.f2fs not found"
144          ;;
145     nfs)
146          ;;
147     cifs)
148          ;;
149     ceph)
150          ;;
151     overlay)
152          ;;
153     reiser4)
154          [ "$MKFS_REISER4_PROG" = "" ] && _fatal "mkfs.reiser4 not found"
155          ;;
156 esac
157
158 _mount()
159 {
160     $MOUNT_PROG `_mount_ops_filter $*`
161 }
162
163 # Call _mount to do mount operation but also save mountpoint to
164 # MOUNTED_POINT_STACK. Note that the mount point must be the last parameter
165 _get_mount()
166 {
167         local mnt_point=${!#}
168
169         _mount $*
170         if [ $? -eq 0 ]; then
171                 MOUNTED_POINT_STACK="$mnt_point $MOUNTED_POINT_STACK"
172         else
173                 return 1
174         fi
175 }
176
177 # Unmount the last mounted mountpoint in MOUNTED_POINT_STACK
178 # and return it to caller
179 _put_mount()
180 {
181         local last_mnt=`echo $MOUNTED_POINT_STACK | awk '{print $1}'`
182
183         if [ -n "$last_mnt" ]; then
184                 $UMOUNT_PROG $last_mnt
185         fi
186         MOUNTED_POINT_STACK=`echo $MOUNTED_POINT_STACK | cut -d\  -f2-`
187 }
188
189 # Unmount all mountpoints in MOUNTED_POINT_STACK and clear the stack
190 _clear_mount_stack()
191 {
192         if [ -n "$MOUNTED_POINT_STACK" ]; then
193                 $UMOUNT_PROG $MOUNTED_POINT_STACK
194         fi
195         MOUNTED_POINT_STACK=""
196 }
197
198 _scratch_options()
199 {
200     type=$1
201     SCRATCH_OPTIONS=""
202
203     if [ "$FSTYP" != "xfs" ]; then
204         return
205     fi
206
207     case $type in
208     mkfs)
209         [ "$HOSTOS" != "IRIX" ] && SCRATCH_OPTIONS="$SCRATCH_OPTIONS -f"
210         rt_opt="-r"
211         log_opt="-l"
212         ;;
213     mount)
214         rt_opt="-o"
215         log_opt="-o"
216         ;;
217     esac
218     [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_RTDEV" ] && \
219         SCRATCH_OPTIONS="$SCRATCH_OPTIONS ${rt_opt}rtdev=$SCRATCH_RTDEV"
220     [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_LOGDEV" ] && \
221         SCRATCH_OPTIONS="$SCRATCH_OPTIONS ${log_opt}logdev=$SCRATCH_LOGDEV"
222 }
223
224 _test_options()
225 {
226     type=$1
227     TEST_OPTIONS=""
228
229     if [ "$FSTYP" != "xfs" ]; then
230         return
231     fi
232
233     case $type in
234     mkfs)
235         rt_opt="-r"
236         log_opt="-l"
237         ;;
238     mount)
239         rt_opt="-o"
240         log_opt="-o"
241         ;;
242     esac
243     [ "$USE_EXTERNAL" = yes -a ! -z "$TEST_RTDEV" ] && \
244         TEST_OPTIONS="$TEST_OPTIONS ${rt_opt}rtdev=$TEST_RTDEV"
245     [ "$USE_EXTERNAL" = yes -a ! -z "$TEST_LOGDEV" ] && \
246         TEST_OPTIONS="$TEST_OPTIONS ${log_opt}logdev=$TEST_LOGDEV"
247 }
248
249 _mount_ops_filter()
250 {
251     params="$*"
252     
253     #get mount point to handle dmapi mtpt option correctly
254     let last_index=$#-1
255     [ $last_index -gt 0 ] && shift $last_index
256     FS_ESCAPED=$1
257     
258     # irix is fussy about how it is fed its mount options
259     # - multiple -o's are not allowed
260     # - no spaces between comma delimitered options
261     # the sed script replaces all -o's (except the first) with a comma
262     # not required for linux, but won't hurt
263     
264     echo $params | sed -e 's/[[:space:]]\+-o[[:space:]]*/UnIqUe/1; s/[[:space:]]\+-o[[:space:]]*/,/g; s/UnIqUe/ -o /1' \
265         | sed -e 's/dmapi/dmi/' \
266         | $PERL_PROG -ne "s#mtpt=[^,|^\n|^\s]*#mtpt=$FS_ESCAPED\1\2#; print;"
267
268 }
269
270 # Used for mounting non-scratch devices (e.g. loop, dm constructs)
271 # with the safe set of scratch mount options (e.g. loop image may be
272 # hosted on $SCRATCH_DEV, so can't use external scratch devices).
273 _common_dev_mount_options()
274 {
275         echo $MOUNT_OPTIONS $SELINUX_MOUNT_OPTIONS $*
276 }
277
278 _overlay_basic_mount_options()
279 {
280         echo "-o lowerdir=$1/$OVL_LOWER,upperdir=$1/$OVL_UPPER,workdir=$1/$OVL_WORK"
281 }
282
283 _overlay_mount_options()
284 {
285         echo `_common_dev_mount_options` \
286              `_overlay_basic_mount_options $1` \
287              $OVERLAY_MOUNT_OPTIONS
288 }
289
290 _scratch_mount_options()
291 {
292         _scratch_options mount
293
294         if [ "$FSTYP" == "overlay" ]; then
295                 echo `_overlay_mount_options $OVL_BASE_SCRATCH_MNT`
296                 return 0
297         fi
298         echo `_common_dev_mount_options $*` $SCRATCH_OPTIONS \
299                                         $SCRATCH_DEV $SCRATCH_MNT
300 }
301
302 _supports_filetype()
303 {
304         local dir=$1
305
306         local fstyp=`$DF_PROG $dir | tail -1 | $AWK_PROG '{print $2}'`
307         case "$fstyp" in
308         xfs)
309                 xfs_info $dir | grep -q "ftype=1"
310                 ;;
311         ext2|ext3|ext4)
312                 local dev=`$DF_PROG $dir | tail -1 | $AWK_PROG '{print $1}'`
313                 tune2fs -l $dev | grep -q filetype
314                 ;;
315         *)
316                 local testfile=$dir/$$.ftype
317                 touch $testfile
318                 # look for DT_UNKNOWN files
319                 local unknowns=$(src/t_dir_type $dir u | wc -l)
320                 rm $testfile
321                 # 0 unknowns is success
322                 return $unknowns
323                 ;;
324         esac
325 }
326
327 # helper function to do the actual overlayfs mount operation
328 _overlay_mount_dirs()
329 {
330         local lowerdir=$1
331         local upperdir=$2
332         local workdir=$3
333         shift 3
334
335         $MOUNT_PROG -t overlay -o lowerdir=$lowerdir -o upperdir=$upperdir \
336                     -o workdir=$workdir $*
337 }
338
339 _overlay_mkdirs()
340 {
341         local dir=$1
342
343         mkdir -p $dir/$OVL_UPPER
344         mkdir -p $dir/$OVL_LOWER
345         mkdir -p $dir/$OVL_WORK
346         mkdir -p $dir/$OVL_MNT
347 }
348
349 # Given a base fs dir, set up overlay directories and mount on the given mnt.
350 # The dir is used as the mount device so it can be seen from df or mount
351 _overlay_mount()
352 {
353         local dir=$1
354         local mnt=$2
355         shift 2
356
357         _supports_filetype $dir || _notrun "upper fs needs to support d_type"
358
359         _overlay_mkdirs $dir
360
361         _overlay_mount_dirs $dir/$OVL_LOWER $dir/$OVL_UPPER \
362                             $dir/$OVL_WORK $OVERLAY_MOUNT_OPTIONS \
363                             $SELINUX_MOUNT_OPTIONS $* $dir $mnt
364 }
365
366 _overlay_test_mount()
367 {
368         _overlay_mount $OVL_BASE_TEST_DIR $TEST_DIR $*
369 }
370
371 _overlay_scratch_mount()
372 {
373         _overlay_mount $OVL_BASE_SCRATCH_MNT $SCRATCH_MNT $*
374 }
375
376 _overlay_test_unmount()
377 {
378         $UMOUNT_PROG $TEST_DIR
379 }
380
381 _overlay_scratch_unmount()
382 {
383         $UMOUNT_PROG $SCRATCH_MNT
384 }
385
386 _scratch_mount()
387 {
388     if [ "$FSTYP" == "overlay" ]; then
389         _overlay_scratch_mount $*
390         return $?
391     fi
392     _mount -t $FSTYP `_scratch_mount_options $*`
393 }
394
395 _scratch_unmount()
396 {
397         case "$FSTYP" in
398         overlay)
399                 _overlay_scratch_unmount
400                 ;;
401         btrfs)
402                 $UMOUNT_PROG $SCRATCH_MNT
403                 ;;
404         *)
405                 $UMOUNT_PROG $SCRATCH_DEV
406                 ;;
407         esac
408 }
409
410 _scratch_remount()
411 {
412     local opts="$1"
413
414     if test -n "$opts"; then
415         mount -o "remount,$opts" $SCRATCH_MNT
416     fi
417 }
418
419 _scratch_cycle_mount()
420 {
421     local opts="$1"
422
423     if [ "$FSTYP" = tmpfs ]; then
424         _scratch_remount "$opts"
425         return
426     fi
427     if test -n "$opts"; then
428         opts="-o $opts"
429     fi
430     _scratch_unmount
431     _scratch_mount "$opts"
432 }
433
434 _test_mount()
435 {
436     if [ "$FSTYP" == "overlay" ]; then
437         _overlay_test_mount $*
438         return $?
439     fi
440     _test_options mount
441     _mount -t $FSTYP $TEST_OPTIONS $TEST_FS_MOUNT_OPTS $SELINUX_MOUNT_OPTIONS $* $TEST_DEV $TEST_DIR
442 }
443
444 _test_unmount()
445 {
446         if [ "$FSTYP" == "overlay" ]; then
447                 _overlay_test_unmount
448         else
449                 $UMOUNT_PROG $TEST_DEV
450         fi
451 }
452
453 _test_cycle_mount()
454 {
455     if [ "$FSTYP" = tmpfs ]; then
456         return
457     fi
458     _test_unmount
459     _test_mount
460 }
461
462 _scratch_mkfs_options()
463 {
464     _scratch_options mkfs
465     echo $SCRATCH_OPTIONS $MKFS_OPTIONS $* $SCRATCH_DEV
466 }
467
468 # Do the actual mkfs work on SCRATCH_DEV. Firstly mkfs with both MKFS_OPTIONS
469 # and user specified mkfs options, if that fails (due to conflicts between mkfs
470 # options), do a second mkfs with only user provided mkfs options.
471 #
472 # First param is the mkfs command without any mkfs options and device.
473 # Second param is the filter to remove unnecessary messages from mkfs stderr.
474 # Other extra mkfs options are followed.
475 _scratch_do_mkfs()
476 {
477         local mkfs_cmd=$1
478         local mkfs_filter=$2
479         shift 2
480         local extra_mkfs_options=$*
481         local mkfs_status
482         local tmp=`mktemp`
483
484         # save mkfs output in case conflict means we need to run again.
485         # only the output for the mkfs that applies should be shown
486         eval "$mkfs_cmd $MKFS_OPTIONS $extra_mkfs_options $SCRATCH_DEV" \
487                 2>$tmp.mkfserr 1>$tmp.mkfsstd
488         mkfs_status=$?
489
490         # a mkfs failure may be caused by conflicts between $MKFS_OPTIONS and
491         # $extra_mkfs_options
492         if [ $mkfs_status -ne 0 -a -n "$extra_mkfs_options" ]; then
493                 (
494                 echo -n "** mkfs failed with extra mkfs options "
495                 echo "added to \"$MKFS_OPTIONS\" by test $seq **"
496                 echo -n "** attempting to mkfs using only test $seq "
497                 echo "options: $extra_mkfs_options **"
498                 ) >> $seqres.full
499
500                 # running mkfs again. overwrite previous mkfs output files
501                 eval "$mkfs_cmd $extra_mkfs_options $SCRATCH_DEV" \
502                         2>$tmp.mkfserr 1>$tmp.mkfsstd
503                 mkfs_status=$?
504         fi
505
506         # output stored mkfs output, filtering unnecessary output from stderr
507         cat $tmp.mkfsstd
508         eval "cat $tmp.mkfserr | $mkfs_filter" >&2
509
510         rm -f $tmp*
511         return $mkfs_status
512 }
513
514 _scratch_metadump()
515 {
516         dumpfile=$1
517         shift
518         options=
519
520         [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_LOGDEV" ] && \
521                 options="-l $SCRATCH_LOGDEV"
522
523         xfs_metadump $options "$@" $SCRATCH_DEV $dumpfile
524 }
525
526 _setup_large_ext4_fs()
527 {
528         fs_size=$1
529         local tmp_dir=/tmp/
530
531         [ "$LARGE_SCRATCH_DEV" != yes ] && return 0
532         [ -z "$SCRATCH_DEV_EMPTY_SPACE" ] && SCRATCH_DEV_EMPTY_SPACE=0
533         [ $SCRATCH_DEV_EMPTY_SPACE -ge $fs_size ] && return 0
534
535         # Default free space in the FS is 50GB, but you can specify more via
536         # SCRATCH_DEV_EMPTY_SPACE
537         space_to_consume=$(($fs_size - 50*1024*1024*1024 - $SCRATCH_DEV_EMPTY_SPACE))
538
539         # mount the filesystem and create 16TB - 4KB files until we consume
540         # all the necessary space.
541         _scratch_mount 2>&1 >$tmp_dir/mnt.err
542         local status=$?
543         if [ $status -ne 0 ]; then
544                 echo "mount failed"
545                 cat $tmp_dir/mnt.err >&2
546                 rm -f $tmp_dir/mnt.err
547                 return $status
548         fi
549         rm -f $tmp_dir/mnt.err
550
551         file_size=$((16*1024*1024*1024*1024 - 4096))
552         nfiles=0
553         while [ $space_to_consume -gt $file_size ]; do
554
555                 xfs_io -F -f \
556                         -c "truncate $file_size" \
557                         -c "falloc -k 0 $file_size" \
558                         $SCRATCH_MNT/.use_space.$nfiles 2>&1
559                 status=$?
560                 if [ $status -ne 0 ]; then
561                         break;
562                 fi
563
564                 space_to_consume=$(( $space_to_consume - $file_size ))
565                 nfiles=$(($nfiles + 1))
566         done
567
568         # consume the remaining space.
569         if [ $space_to_consume -gt 0 ]; then
570                 xfs_io -F -f \
571                         -c "truncate $space_to_consume" \
572                         -c "falloc -k 0 $space_to_consume" \
573                         $SCRATCH_MNT/.use_space.$nfiles 2>&1
574                 status=$?
575         fi
576         export NUM_SPACE_FILES=$nfiles
577
578         _scratch_unmount
579         if [ $status -ne 0 ]; then
580                 echo "large file prealloc failed"
581                 cat $tmp_dir/mnt.err >&2
582                 return $status
583         fi
584         return 0
585 }
586
587 _scratch_mkfs_ext4()
588 {
589         local mkfs_cmd="$MKFS_EXT4_PROG -F"
590         local mkfs_filter="grep -v -e ^Warning: -e \"^mke2fs \""
591         local tmp=`mktemp`
592         local mkfs_status
593
594
595         _scratch_do_mkfs "$mkfs_cmd" "$mkfs_filter" $* 2>$tmp.mkfserr 1>$tmp.mkfsstd
596         mkfs_status=$?
597
598         if [ $mkfs_status -eq 0 -a "$LARGE_SCRATCH_DEV" = yes ]; then
599                 # manually parse the mkfs output to get the fs size in bytes
600                 fs_size=`cat $tmp.mkfsstd | awk ' \
601                         /^Block size/ { split($2, a, "="); bs = a[2] ; } \
602                         / inodes, / { blks = $3 } \
603                         /reserved for the super user/ { resv = $1 } \
604                         END { fssize = bs * blks - resv; print fssize }'`
605
606                 _setup_large_ext4_fs $fs_size
607                 mkfs_status=$?
608         fi
609
610         # output mkfs stdout and stderr
611         cat $tmp.mkfsstd
612         cat $tmp.mkfserr >&2
613
614         return $mkfs_status
615 }
616
617 _test_mkfs()
618 {
619     case $FSTYP in
620     nfs*)
621         # do nothing for nfs
622         ;;
623     cifs)
624         # do nothing for cifs
625         ;;
626     ceph)
627         # do nothing for ceph
628         ;;
629     overlay)
630         # do nothing for overlay
631         ;;
632     udf)
633         $MKFS_UDF_PROG $MKFS_OPTIONS $* $TEST_DEV > /dev/null
634         ;;
635     btrfs)
636         $MKFS_BTRFS_PROG $MKFS_OPTIONS $* $TEST_DEV > /dev/null
637         ;;
638     ext2|ext3|ext4)
639         $MKFS_PROG -t $FSTYP -- -F $MKFS_OPTIONS $* $TEST_DEV
640         ;;
641     *)
642         yes | $MKFS_PROG -t $FSTYP -- $MKFS_OPTIONS $* $TEST_DEV
643         ;;
644     esac
645 }
646
647 _mkfs_dev()
648 {
649     case $FSTYP in
650     nfs*)
651         # do nothing for nfs
652         ;;
653     overlay)
654         # do nothing for overlay
655         ;;
656     udf)
657         $MKFS_UDF_PROG $MKFS_OPTIONS $* 2>$tmp_dir.mkfserr 1>$tmp_dir.mkfsstd
658         ;;
659     btrfs)
660         $MKFS_BTRFS_PROG $MKFS_OPTIONS $* 2>$tmp_dir.mkfserr 1>$tmp_dir.mkfsstd
661         ;;
662     ext2|ext3|ext4)
663         $MKFS_PROG -t $FSTYP -- -F $MKFS_OPTIONS $* \
664                 2>$tmp_dir.mkfserr 1>$tmp_dir.mkfsstd
665         ;;
666
667     *)
668         yes | $MKFS_PROG -t $FSTYP -- $MKFS_OPTIONS $* \
669                 2>$tmp_dir.mkfserr 1>$tmp_dir.mkfsstd
670         ;;
671     esac
672
673     if [ $? -ne 0 ]; then
674         # output stored mkfs output
675         cat $tmp_dir.mkfserr >&2
676         cat $tmp_dir.mkfsstd
677         status=1
678         exit 1
679     fi
680     rm -f $tmp_dir.mkfserr $tmp_dir.mkfsstd
681 }
682
683 # remove all files in $SCRATCH_MNT, useful when testing on NFS/CIFS
684 _scratch_cleanup_files()
685 {
686         case $FSTYP in
687         overlay)
688                 # Avoid rm -rf /* if we messed up
689                 [ -n "$OVL_BASE_SCRATCH_MNT" ] || return 1
690                 rm -rf $OVL_BASE_SCRATCH_MNT/*
691                 ;;
692         *)
693                 [ -n "$SCRATCH_MNT" ] || return 1
694                 _scratch_mount
695                 rm -rf $SCRATCH_MNT/*
696                 _scratch_unmount
697                 ;;
698         esac
699 }
700
701 _scratch_mkfs()
702 {
703         local mkfs_cmd=""
704         local mkfs_filter=""
705         local mkfs_status
706
707         case $FSTYP in
708         nfs*|cifs|ceph|overlay)
709                 # unable to re-create this fstyp, just remove all files in
710                 # $SCRATCH_MNT to avoid EEXIST caused by the leftover files
711                 # created in previous runs
712                 _scratch_cleanup_files
713                 return 0
714                 ;;
715         tmpfs)
716                 # do nothing for tmpfs
717                 return 0
718                 ;;
719         ext4)
720                 _scratch_mkfs_ext4 $*
721                 return $?
722                 ;;
723         xfs)
724                 _scratch_mkfs_xfs $*
725                 return $?
726                 ;;
727         udf)
728                 mkfs_cmd="$MKFS_UDF_PROG"
729                 mkfs_filter="cat"
730                 ;;
731         btrfs)
732                 mkfs_cmd="$MKFS_BTRFS_PROG"
733                 mkfs_filter="cat"
734                 ;;
735         ext2|ext3)
736                 mkfs_cmd="$MKFS_PROG -t $FSTYP -- -F"
737                 mkfs_filter="grep -v -e ^Warning: -e \"^mke2fs \""
738                 ;;
739         f2fs)
740                 mkfs_cmd="$MKFS_F2FS_PROG"
741                 mkfs_filter="cat"
742                 ;;
743         ocfs2)
744                 mkfs_cmd="yes | $MKFS_PROG -t $FSTYP --"
745                 mkfs_filter="grep -v -e ^mkfs\.ocfs2"
746                 ;;
747         *)
748                 mkfs_cmd="yes | $MKFS_PROG -t $FSTYP --"
749                 mkfs_filter="cat"
750                 ;;
751         esac
752
753         _scratch_do_mkfs "$mkfs_cmd" "$mkfs_filter" $*
754         return $?
755 }
756
757 # Helper function to get a spare or replace-target device from
758 # configured SCRATCH_DEV_POLL, must call _scratch_dev_pool_get()
759 # before _spare_dev_get(). Replace-target-device/Spare-device will
760 # be assigned to SPARE_DEV.
761 # As of now only one replace-target-device/spare-device can be
762 # assigned.
763 #
764 # Usage:
765 #  _scratch_dev_pool_get() <ndevs>
766 #     _spare_dev_get()
767 #     :: do stuff
768 #     _spare_dev_put()
769 #  _scratch_dev_pool_put()
770 #
771 _spare_dev_get()
772 {
773         typeset -p SCRATCH_DEV_POOL_SAVED >/dev/null 2>&1
774         if [ $? -ne 0 ]; then
775                 _fail "Bug: unset val, must call _scratch_dev_pool_get before _spare_dev_get"
776         fi
777
778         if [ -z "$SCRATCH_DEV_POOL_SAVED" ]; then
779                 _fail "Bug: str empty, must call _scratch_dev_pool_get before _spare_dev_get"
780         fi
781
782         # Check if the spare is already assigned
783         typeset -p SPARE_DEV >/dev/null 2>&1
784         if [ $? -eq 0 ]; then
785                 if [ ! -z "$SPARE_DEV" ]; then
786                         _fail "Bug: SPARE_DEV = $SPARE_DEV already assigned"
787                 fi
788         fi
789
790         local ndevs=`echo $SCRATCH_DEV_POOL| wc -w`
791         local config_ndevs=`echo $SCRATCH_DEV_POOL_SAVED| wc -w`
792
793         if [ $ndevs -eq $config_ndevs ]; then
794                 _notrun "All devs used no spare"
795         fi
796         # Get a dev that is not used
797         local devs[]="( $SCRATCH_DEV_POOL_SAVED )"
798         SPARE_DEV=${devs[@]:$ndevs:1}
799         export SPARE_DEV
800 }
801
802 _spare_dev_put()
803 {
804         typeset -p SPARE_DEV >/dev/null 2>&1
805         if [ $? -ne 0 ]; then
806                 _fail "Bug: unset val, must call _spare_dev_get before its put"
807         fi
808
809         if [ -z "$SPARE_DEV" ]; then
810                 _fail "Bug: str empty, must call _spare_dev_get before its put"
811         fi
812
813         export SPARE_DEV=""
814 }
815
816 #
817 # Generally test cases will have..
818 #   _require_scratch_dev_pool X
819 # to make sure it has the enough scratch devices including
820 # replace-target and spare device. Now arg1 here is the
821 # required number of scratch devices by a-test-case excluding
822 # the replace-target and spare device. So this function will
823 # set SCRATCH_DEV_POOL to the specified number of devices.
824 #
825 # Usage:
826 #  _scratch_dev_pool_get() <ndevs>
827 #     :: do stuff
828 #
829 #  _scratch_dev_pool_put()
830 #
831 _scratch_dev_pool_get()
832 {
833         if [ $# -ne 1 ]; then
834                 _fail "Usage: _scratch_dev_pool_get ndevs"
835         fi
836
837         local test_ndevs=$1
838         local config_ndevs=`echo $SCRATCH_DEV_POOL| wc -w`
839         local devs[]="( $SCRATCH_DEV_POOL )"
840
841         typeset -p config_ndevs >/dev/null 2>&1
842         if [ $? -ne 0 ]; then
843                 _fail "Bug: cant find SCRATCH_DEV_POOL ndevs"
844         fi
845
846         if [ $config_ndevs -lt $test_ndevs ]; then
847                 _notrun "Need at least test requested number of ndevs $test_ndevs"
848         fi
849
850         SCRATCH_DEV_POOL_SAVED=${SCRATCH_DEV_POOL}
851         export SCRATCH_DEV_POOL_SAVED
852         SCRATCH_DEV_POOL=${devs[@]:0:$test_ndevs}
853         export SCRATCH_DEV_POOL
854 }
855
856 _scratch_dev_pool_put()
857 {
858         typeset -p SCRATCH_DEV_POOL_SAVED >/dev/null 2>&1
859         if [ $? -ne 0 ]; then
860                 _fail "Bug: unset val, must call _scratch_dev_pool_get before _scratch_dev_pool_put"
861         fi
862
863         if [ -z "$SCRATCH_DEV_POOL_SAVED" ]; then
864                 _fail "Bug: str empty, must call _scratch_dev_pool_get before _scratch_dev_pool_put"
865         fi
866
867         export SCRATCH_DEV_POOL=$SCRATCH_DEV_POOL_SAVED
868         export SCRATCH_DEV_POOL_SAVED=""
869 }
870
871 _scratch_pool_mkfs()
872 {
873     case $FSTYP in
874     btrfs)
875         # if dup profile is in mkfs options call _scratch_mkfs instead
876         # because dup profile only works with single device
877         if [[ "$*" =~ dup ]]; then
878             _scratch_mkfs $*
879         else
880             $MKFS_BTRFS_PROG $MKFS_OPTIONS $* $SCRATCH_DEV_POOL > /dev/null
881         fi
882         ;;
883     *)
884         echo "_scratch_pool_mkfs is not implemented for $FSTYP" 1>&2
885         ;;
886     esac
887 }
888
889 # Return the amount of free memory available on the system
890 _free_memory_bytes()
891 {
892     free -b | grep ^Mem | awk '{print $4}'
893 }
894
895 # Create fs of certain size on scratch device
896 # _scratch_mkfs_sized <size in bytes> [optional blocksize]
897 _scratch_mkfs_sized()
898 {
899     fssize=$1
900     blocksize=$2
901
902     case $FSTYP in
903     xfs)
904         def_blksz=`echo $MKFS_OPTIONS|sed -rn 's/.*-b ?size= ?+([0-9]+).*/\1/p'`
905         ;;
906     ext2|ext3|ext4|ext4dev|udf|btrfs|reiser4|ocfs2)
907         def_blksz=`echo $MKFS_OPTIONS| sed -rn 's/.*-b ?+([0-9]+).*/\1/p'`
908         ;;
909     esac
910
911     [ -n "$def_blksz" ] && blocksize=$def_blksz
912     [ -z "$blocksize" ] && blocksize=4096
913
914
915     re='^[0-9]+$'
916     if ! [[ $fssize =~ $re ]] ; then
917         _notrun "error: _scratch_mkfs_sized: fs size \"$fssize\" not an integer."
918     fi
919     if ! [[ $blocksize =~ $re ]] ; then
920         _notrun "error: _scratch_mkfs_sized: block size \"$blocksize\" not an integer."
921     fi
922
923     blocks=`expr $fssize / $blocksize`
924
925     if [ "$HOSTOS" == "Linux" -a -b "$SCRATCH_DEV" ]; then
926         devsize=`blockdev --getsize64 $SCRATCH_DEV`
927         [ "$fssize" -gt "$devsize" ] && _notrun "Scratch device too small"
928     fi
929
930     case $FSTYP in
931     xfs)
932         # don't override MKFS_OPTIONS that set a block size.
933         echo $MKFS_OPTIONS |egrep -q "b?size="
934         if [ $? -eq 0 ]; then
935                 _scratch_mkfs_xfs -d size=$fssize
936         else
937                 _scratch_mkfs_xfs -d size=$fssize -b size=$blocksize
938         fi
939         ;;
940     ext2|ext3|ext4|ext4dev)
941         ${MKFS_PROG}.$FSTYP -F $MKFS_OPTIONS -b $blocksize $SCRATCH_DEV $blocks
942         ;;
943     ocfs2)
944         yes | ${MKFS_PROG}.$FSTYP -F $MKFS_OPTIONS -b $blocksize $SCRATCH_DEV $blocks
945         ;;
946     udf)
947         $MKFS_UDF_PROG $MKFS_OPTIONS -b $blocksize $SCRATCH_DEV $blocks
948         ;;
949     btrfs)
950         local mixed_opt=
951         (( fssize <= 100 * 1024 * 1024 )) && mixed_opt='--mixed'
952         $MKFS_BTRFS_PROG $MKFS_OPTIONS $mixed_opt -b $fssize $SCRATCH_DEV
953         ;;
954     reiser4)
955         # mkfs.resier4 requires size in KB as input for creating filesystem
956         $MKFS_REISER4_PROG $MKFS_OPTIONS -y -b $blocksize $SCRATCH_DEV \
957                            `expr $fssize / 1024`
958         ;;
959     f2fs)
960         # mkfs.f2fs requires # of sectors as an input for the size
961         sector_size=`blockdev --getss $SCRATCH_DEV`
962         $MKFS_F2FS_PROG $MKFS_OPTIONS $SCRATCH_DEV `expr $fssize / $sector_size`
963         ;;
964     tmpfs)
965         free_mem=`_free_memory_bytes`
966         if [ "$free_mem" -lt "$fssize" ] ; then
967            _notrun "Not enough memory ($free_mem) for tmpfs with $fssize bytes"
968         fi
969         export MOUNT_OPTIONS="-o size=$fssize $TMPFS_MOUNT_OPTIONS"
970         ;;
971     *)
972         _notrun "Filesystem $FSTYP not supported in _scratch_mkfs_sized"
973         ;;
974     esac
975 }
976
977 # Emulate an N-data-disk stripe w/ various stripe units
978 # _scratch_mkfs_geom <sunit bytes> <swidth multiplier> [optional blocksize]
979 _scratch_mkfs_geom()
980 {
981     sunit_bytes=$1
982     swidth_mult=$2
983     blocksize=$3
984     [ -z "$blocksize" ] && blocksize=4096
985
986     let sunit_blocks=$sunit_bytes/$blocksize
987     let swidth_blocks=$sunit_blocks*$swidth_mult
988
989     case $FSTYP in
990     xfs)
991         MKFS_OPTIONS+=" -b size=$blocksize, -d su=$sunit_bytes,sw=$swidth_mult"
992         ;;
993     ext4|ext4dev)
994         MKFS_OPTIONS+=" -b $blocksize -E stride=$sunit_blocks,stripe_width=$swidth_blocks"
995         ;;
996     *)
997         _notrun "can't mkfs $FSTYP with geometry"
998         ;;
999     esac
1000     _scratch_mkfs
1001 }
1002
1003 # Create fs of certain blocksize on scratch device
1004 # _scratch_mkfs_blocksized blocksize
1005 _scratch_mkfs_blocksized()
1006 {
1007     blocksize=$1
1008
1009     re='^[0-9]+$'
1010     if ! [[ $blocksize =~ $re ]] ; then
1011         _notrun "error: _scratch_mkfs_sized: block size \"$blocksize\" not an integer."
1012     fi
1013
1014     case $FSTYP in
1015     xfs)
1016         _scratch_mkfs_xfs $MKFS_OPTIONS -b size=$blocksize
1017         ;;
1018     ext2|ext3|ext4)
1019         ${MKFS_PROG}.$FSTYP -F $MKFS_OPTIONS -b $blocksize $SCRATCH_DEV
1020         ;;
1021     ocfs2)
1022         yes | ${MKFS_PROG}.$FSTYP -F $MKFS_OPTIONS -b $blocksize -C $blocksize $SCRATCH_DEV
1023         ;;
1024     *)
1025         _notrun "Filesystem $FSTYP not supported in _scratch_mkfs_blocksized"
1026         ;;
1027     esac
1028 }
1029
1030 _scratch_resvblks()
1031 {
1032         case $FSTYP in
1033         xfs)
1034                 xfs_io -x -c "resblks $1" $SCRATCH_MNT
1035                 ;;
1036         *)
1037                 ;;
1038         esac
1039 }
1040
1041
1042 # Repair scratch filesystem.  Returns 0 if the FS is good to go (either no
1043 # errors found or errors were fixed) and nonzero otherwise; also spits out
1044 # a complaint on stderr if fsck didn't tell us that the FS is good to go.
1045 _repair_scratch_fs()
1046 {
1047     case $FSTYP in
1048     xfs)
1049         _scratch_xfs_repair "$@" 2>&1
1050         res=$?
1051         if [ "$res" -ne 0 ]; then
1052                 echo "xfs_repair returns $res; replay log?"
1053                 _scratch_mount
1054                 res=$?
1055                 if [ "$res" -gt 0 ]; then
1056                         echo "mount returns $res; zap log?"
1057                         _scratch_xfs_repair -L 2>&1
1058                         echo "log zap returns $?"
1059                 else
1060                         umount "$SCRATCH_MNT"
1061                 fi
1062                 _scratch_xfs_repair "$@" 2>&1
1063                 res=$?
1064         fi
1065         test $res -ne 0 && >&2 echo "xfs_repair failed, err=$res"
1066         return $res
1067         ;;
1068     *)
1069         # Let's hope fsck -y suffices...
1070         fsck -t $FSTYP -y $SCRATCH_DEV 2>&1
1071         res=$?
1072         case $res in
1073         0|1|2)
1074                 res=0
1075                 ;;
1076         *)
1077                 >&2 echo "fsck.$FSTYP failed, err=$res"
1078                 ;;
1079         esac
1080         return $res
1081         ;;
1082     esac
1083 }
1084
1085 _get_pids_by_name()
1086 {
1087     if [ $# -ne 1 ]
1088     then
1089         echo "Usage: _get_pids_by_name process-name" 1>&2
1090         exit 1
1091     fi
1092
1093     # Algorithm ... all ps(1) variants have a time of the form MM:SS or
1094     # HH:MM:SS before the psargs field, use this as the search anchor.
1095     #
1096     # Matches with $1 (process-name) occur if the first psarg is $1
1097     # or ends in /$1 ... the matching uses sed's regular expressions,
1098     # so passing a regex into $1 will work.
1099
1100     ps $PS_ALL_FLAGS \
1101     | sed -n \
1102         -e 's/$/ /' \
1103         -e 's/[         ][      ]*/ /g' \
1104         -e 's/^ //' \
1105         -e 's/^[^ ]* //' \
1106         -e "/[0-9]:[0-9][0-9]  *[^ ]*\/$1 /s/ .*//p" \
1107         -e "/[0-9]:[0-9][0-9]  *$1 /s/ .*//p"
1108 }
1109
1110 # fix malloc libs output
1111 #
1112 _fix_malloc()
1113 {
1114     # filter out the Electric Fence notice
1115     $PERL_PROG -e '
1116         while (<>) {
1117             if (defined $o && /^\s+Electric Fence/) {
1118                 chomp($o);
1119                 print "$o";
1120                 undef $o;
1121                 next;
1122             }
1123             print $o if (defined $o);
1124
1125             $o=$_;
1126         }
1127         print $o if (defined $o);
1128     '
1129 }
1130
1131 #
1132 # _df_device : get an IRIX style df line for a given device
1133 #
1134 #       - returns "" if not mounted
1135 #       - returns fs type in field two (ala IRIX)
1136 #       - joins line together if split by fancy df formatting
1137 #       - strips header etc
1138 #
1139
1140 _df_device()
1141 {
1142     if [ $# -ne 1 ]
1143     then
1144         echo "Usage: _df_device device" 1>&2
1145         exit 1
1146     fi
1147
1148     # Note that we use "==" here so awk doesn't try to interpret an NFS over
1149     # IPv6 server as a regular expression.
1150     $DF_PROG 2>/dev/null | $AWK_PROG -v what=$1 '
1151         ($1==what) && (NF==1) {
1152             v=$1
1153             getline
1154             print v, $0
1155             exit
1156         }
1157         ($1==what) {
1158             print
1159             exit
1160         }
1161     '
1162 }
1163
1164 #
1165 # _df_dir : get an IRIX style df line for device where a directory resides
1166 #
1167 #       - returns fs type in field two (ala IRIX)
1168 #       - joins line together if split by fancy df formatting
1169 #       - strips header etc
1170 #
1171
1172 _df_dir()
1173 {
1174     if [ $# -ne 1 ]
1175     then
1176         echo "Usage: _df_dir device" 1>&2
1177         exit 1
1178     fi
1179
1180     $DF_PROG $1 2>/dev/null | $AWK_PROG -v what=$1 '
1181         NR == 2 && NF==1 {
1182             v=$1
1183             getline
1184             print v, $0;
1185             exit 0
1186         }
1187         NR == 2 {
1188             print;
1189             exit 0
1190         }
1191         {}
1192     '
1193     # otherwise, nada
1194 }
1195
1196 # return percentage used disk space for mounted device
1197
1198 _used()
1199 {
1200     if [ $# -ne 1 ]
1201     then
1202         echo "Usage: _used device" 1>&2
1203         exit 1
1204     fi
1205
1206     _df_device $1 | $AWK_PROG '{ sub("%", "") ; print $6 }'
1207 }
1208
1209 # return the FS type of a mounted device
1210 #
1211 _fs_type()
1212 {
1213     if [ $# -ne 1 ]
1214     then
1215         echo "Usage: _fs_type device" 1>&2
1216         exit 1
1217     fi
1218
1219     #
1220     # The Linux kernel shows NFSv4 filesystems in df output as
1221     # filesystem type nfs4, although we mounted it as nfs earlier.
1222     # Fix the filesystem type up here so that the callers don't
1223     # have to bother with this quirk.
1224     #
1225     _df_device $1 | $AWK_PROG '{ print $2 }' | sed -e 's/nfs4/nfs/'
1226 }
1227
1228 # return the FS mount options of a mounted device
1229 #
1230 # should write a version which just parses the output of mount for IRIX
1231 # compatibility, but since this isn't used at all, at the moment I'll leave
1232 # this for now
1233 #
1234 _fs_options()
1235 {
1236     if [ $# -ne 1 ]
1237     then
1238         echo "Usage: _fs_options device" 1>&2
1239         exit 1
1240     fi
1241
1242     $AWK_PROG -v dev=$1 '
1243         match($1,dev) { print $4 }
1244     ' </proc/mounts
1245 }
1246
1247 # returns device number if a file is a block device
1248 #
1249 _is_block_dev()
1250 {
1251     if [ $# -ne 1 ]
1252     then
1253         echo "Usage: _is_block_dev dev" 1>&2
1254         exit 1
1255     fi
1256
1257     _dev=$1
1258     if [ -L "${_dev}" ]; then
1259         _dev=`readlink -f "${_dev}"`
1260     fi
1261
1262     if [ -b "${_dev}" ]; then
1263         src/lstat64 "${_dev}" | $AWK_PROG '/Device type:/ { print $9 }'
1264     fi
1265 }
1266
1267 # Do a command, log it to $seqres.full, optionally test return status
1268 # and die if command fails. If called with one argument _do executes the
1269 # command, logs it, and returns its exit status. With two arguments _do
1270 # first prints the message passed in the first argument, and then "done"
1271 # or "fail" depending on the return status of the command passed in the
1272 # second argument. If the command fails and the variable _do_die_on_error
1273 # is set to "always" or the two argument form is used and _do_die_on_error
1274 # is set to "message_only" _do will print an error message to
1275 # $seqres.out and exit.
1276
1277 _do()
1278 {
1279     if [ $# -eq 1 ]; then
1280         _cmd=$1
1281     elif [ $# -eq 2 ]; then
1282         _note=$1
1283         _cmd=$2
1284         echo -n "$_note... "
1285     else
1286         echo "Usage: _do [note] cmd" 1>&2
1287         status=1; exit
1288     fi
1289
1290     (eval "echo '---' \"$_cmd\"") >>$seqres.full
1291     (eval "$_cmd") >$tmp._out 2>&1; ret=$?
1292     cat $tmp._out | _fix_malloc >>$seqres.full
1293     if [ $# -eq 2 ]; then
1294         if [ $ret -eq 0 ]; then
1295             echo "done"
1296         else
1297             echo "fail"
1298         fi
1299     fi
1300     if [ $ret -ne 0  ] \
1301         && [ "$_do_die_on_error" = "always" \
1302             -o \( $# -eq 2 -a "$_do_die_on_error" = "message_only" \) ]
1303     then
1304         [ $# -ne 2 ] && echo
1305         eval "echo \"$_cmd\" failed \(returned $ret\): see $seqres.full"
1306         status=1; exit
1307     fi
1308
1309     return $ret
1310 }
1311
1312 # bail out, setting up .notrun file. Need to kill the filesystem check files
1313 # here, otherwise they are set incorrectly for the next test.
1314 #
1315 _notrun()
1316 {
1317     echo "$*" > $seqres.notrun
1318     echo "$seq not run: $*"
1319     rm -f ${RESULT_DIR}/require_test*
1320     rm -f ${RESULT_DIR}/require_scratch*
1321
1322     status=0
1323     exit
1324 }
1325
1326 # just plain bail out
1327 #
1328 _fail()
1329 {
1330     echo "$*" | tee -a $seqres.full
1331     echo "(see $seqres.full for details)"
1332     status=1
1333     exit 1
1334 }
1335
1336 # tests whether $FSTYP is one of the supported filesystems for a test
1337 #
1338 _supported_fs()
1339 {
1340     for f
1341     do
1342         if [ "$f" = "$FSTYP" -o "$f" = "generic" ]
1343         then
1344             return
1345         fi
1346     done
1347
1348     _notrun "not suitable for this filesystem type: $FSTYP"
1349 }
1350
1351
1352 # tests whether $FSTYP is one of the supported OSes for a test
1353 #
1354 _supported_os()
1355 {
1356     for h
1357     do
1358         if [ "$h" = "$HOSTOS" ]
1359         then
1360             return
1361         fi
1362     done
1363
1364     _notrun "not suitable for this OS: $HOSTOS"
1365 }
1366
1367 # check if a FS on a device is mounted
1368 # if so, verify that it is mounted on mount point
1369 # if fstype is given as argument, verify that it is also
1370 # mounted with correct fs type
1371 #
1372 _check_mounted_on()
1373 {
1374         local devname=$1
1375         local dev=$2
1376         local mntname=$3
1377         local mnt=$4
1378         local type=$5
1379
1380         # Note that we use -F here so grep doesn't try to interpret an NFS over
1381         # IPv6 server as a regular expression.  Because of that, we cannot use
1382         # ^$dev so we use "$dev on " to avoid matching $dev to mount point field
1383         # for overlay case, where $dev is a directory.
1384         local mount_rec=`_mount | grep -F "$dev on "`
1385         [ -n "$mount_rec" ] || return 1 # 1 = not mounted
1386
1387         # if it's mounted, make sure its on $mnt
1388         if ! (echo $mount_rec | grep -q "$dev on $mnt")
1389         then
1390                 echo "$devname=$dev is mounted but not on $mntname=$mnt - aborting"
1391                 echo "Already mounted result:"
1392                 echo $mount_rec
1393                 return 2 # 2 = mounted on wrong mnt
1394         fi
1395
1396         if [ -n "$type" -a "`_fs_type $dev`" != "$type" ]
1397         then
1398                 echo "$devname=$dev is mounted but not a type $type filesystem"
1399                 # raw $DF_PROG cannot handle NFS/CIFS/overlay correctly
1400                 _df_device $dev
1401                 return 3 # 3 = mounted as wrong type
1402         fi
1403         return 0 # 0 = mounted as expected
1404 }
1405
1406 # this test needs a scratch partition - check we're ok & unmount it
1407 # No post-test check of the device is required. e.g. the test intentionally
1408 # finishes the test with the filesystem in a corrupt state
1409 _require_scratch_nocheck()
1410 {
1411     case "$FSTYP" in
1412         nfs*|ceph)
1413                 echo $SCRATCH_DEV | grep -q ":/" > /dev/null 2>&1
1414                 if [ -z "$SCRATCH_DEV" -o "$?" != "0" ]; then
1415                         _notrun "this test requires a valid \$SCRATCH_DEV"
1416                 fi
1417                 if [ ! -d "$SCRATCH_MNT" ]; then
1418                         _notrun "this test requires a valid \$SCRATCH_MNT"
1419                 fi
1420                 ;;
1421         cifs)
1422                 echo $SCRATCH_DEV | grep -q "//" > /dev/null 2>&1
1423                 if [ -z "$SCRATCH_DEV" -o "$?" != "0" ]; then
1424                         _notrun "this test requires a valid \$SCRATCH_DEV"
1425                 fi
1426                 if [ ! -d "$SCRATCH_MNT" ]; then
1427                      _notrun "this test requires a valid \$SCRATCH_MNT"
1428                 fi
1429                 ;;
1430         overlay)
1431                 if [ -z "$OVL_BASE_SCRATCH_MNT" -o ! -d "$OVL_BASE_SCRATCH_MNT" ]; then
1432                         _notrun "this test requires a valid \$OVL_BASE_SCRATCH_MNT as ovl base dir"
1433                 fi
1434                 # if $SCRATCH_MNT is derived from $OVL_BASE_SCRATCH_MNT then
1435                 # don't check $SCRATCH_MNT dir here because base fs may not be mounted
1436                 # and we will create the mount point anyway on _overlay_mount
1437                 if [ "$SCRATCH_MNT" != "$OVL_BASE_SCRATCH_MNT/$OVL_MNT" -a ! -d "$SCRATCH_MNT" ]; then
1438                         _notrun "this test requires a valid \$SCRATCH_MNT"
1439                 fi
1440                 ;;
1441         tmpfs)
1442                 if [ -z "$SCRATCH_DEV" -o ! -d "$SCRATCH_MNT" ];
1443                 then
1444                     _notrun "this test requires a valid \$SCRATCH_MNT and unique $SCRATCH_DEV"
1445                 fi
1446                 ;;
1447         *)
1448                  if [ -z "$SCRATCH_DEV" -o "`_is_block_dev "$SCRATCH_DEV"`" = "" ]
1449                  then
1450                      _notrun "this test requires a valid \$SCRATCH_DEV"
1451                  fi
1452                  if [ "`_is_block_dev "$SCRATCH_DEV"`" = "`_is_block_dev "$TEST_DEV"`" ]
1453                  then
1454                      _notrun "this test requires a valid \$SCRATCH_DEV"
1455                  fi
1456                 if [ ! -d "$SCRATCH_MNT" ]
1457                 then
1458                      _notrun "this test requires a valid \$SCRATCH_MNT"
1459                 fi
1460                  ;;
1461     esac
1462
1463     _check_mounted_on SCRATCH_DEV $SCRATCH_DEV SCRATCH_MNT $SCRATCH_MNT
1464     local err=$?
1465     [ $err -le 1 ] || exit 1
1466     if [ $err -eq 0 ]
1467     then
1468         # if it's mounted, unmount it
1469         if ! _scratch_unmount
1470         then
1471             echo "failed to unmount $SCRATCH_DEV"
1472             exit 1
1473         fi
1474     fi
1475     rm -f ${RESULT_DIR}/require_scratch
1476 }
1477
1478 # we need the scratch device and it should be checked post test.
1479 _require_scratch()
1480 {
1481         _require_scratch_nocheck
1482         touch ${RESULT_DIR}/require_scratch
1483 }
1484
1485
1486 # this test needs a test partition - check we're ok & mount it
1487 #
1488 _require_test()
1489 {
1490     case "$FSTYP" in
1491         nfs*|ceph)
1492                 echo $TEST_DEV | grep -q ":/" > /dev/null 2>&1
1493                 if [ -z "$TEST_DEV" -o "$?" != "0" ]; then
1494                         _notrun "this test requires a valid \$TEST_DEV"
1495                 fi
1496                 if [ ! -d "$TEST_DIR" ]; then
1497                         _notrun "this test requires a valid \$TEST_DIR"
1498                 fi
1499                 ;;
1500         cifs)
1501                 echo $TEST_DEV | grep -q "//" > /dev/null 2>&1
1502                 if [ -z "$TEST_DEV" -o "$?" != "0" ]; then
1503                         _notrun "this test requires a valid \$TEST_DEV"
1504                 fi
1505                 if [ ! -d "$TEST_DIR" ]; then
1506                      _notrun "this test requires a valid \$TEST_DIR"
1507                 fi
1508                 ;;
1509         overlay)
1510                 if [ -z "$OVL_BASE_TEST_DIR" -o ! -d "$OVL_BASE_TEST_DIR" ]; then
1511                         _notrun "this test requires a valid \$TEST_DIR as ovl base dir"
1512                 fi
1513                 if [ ! -d "$TEST_DIR" ]; then
1514                         _notrun "this test requires a valid \$TEST_DIR"
1515                 fi
1516                 ;;
1517         tmpfs)
1518                 if [ -z "$TEST_DEV" -o ! -d "$TEST_DIR" ];
1519                 then
1520                     _notrun "this test requires a valid \$TEST_DIR and unique $TEST_DEV"
1521                 fi
1522                 ;;
1523         *)
1524                  if [ -z "$TEST_DEV" ] || [ "`_is_block_dev "$TEST_DEV"`" = "" ]
1525                  then
1526                      _notrun "this test requires a valid \$TEST_DEV"
1527                  fi
1528                  if [ "`_is_block_dev "$SCRATCH_DEV"`" = "`_is_block_dev "$TEST_DEV"`" ]
1529                  then
1530                      _notrun "this test requires a valid \$TEST_DEV"
1531                  fi
1532                 if [ ! -d "$TEST_DIR" ]
1533                 then
1534                      _notrun "this test requires a valid \$TEST_DIR"
1535                 fi
1536                  ;;
1537     esac
1538
1539     _check_mounted_on TEST_DEV $TEST_DEV TEST_DIR $TEST_DIR
1540     local err=$?
1541     [ $err -le 1 ] || exit 1
1542     if [ $err -ne 0 ]
1543     then
1544         if ! _test_mount
1545         then
1546                 echo "!!! failed to mount $TEST_DEV on $TEST_DIR"
1547                 exit 1
1548         fi
1549     fi
1550     touch ${RESULT_DIR}/require_test
1551 }
1552
1553 # this test needs a logdev
1554 #
1555 _require_logdev()
1556 {
1557     [ -z "$SCRATCH_LOGDEV" -o ! -b "$SCRATCH_LOGDEV" ] && \
1558         _notrun "This test requires a valid \$SCRATCH_LOGDEV"
1559     [ "$USE_EXTERNAL" != yes ] && \
1560         _notrun "This test requires USE_EXTERNAL to be enabled"
1561
1562     # ensure its not mounted
1563     $UMOUNT_PROG $SCRATCH_LOGDEV 2>/dev/null
1564 }
1565
1566 # this test requires loopback device support
1567 #
1568 _require_loop()
1569 {
1570     if [ "$HOSTOS" != "Linux" ]
1571     then
1572         _notrun "This test requires linux for loopback device support"
1573     fi
1574
1575     modprobe loop >/dev/null 2>&1
1576     if grep loop /proc/devices >/dev/null 2>&1
1577     then
1578         :
1579     else
1580         _notrun "This test requires loopback device support"
1581     fi
1582 }
1583
1584 # this test requires ext2 filesystem support
1585 #
1586 _require_ext2()
1587 {
1588     if [ "$HOSTOS" != "Linux" ]
1589     then
1590         _notrun "This test requires linux for ext2 filesystem support"
1591     fi
1592
1593     modprobe ext2 >/dev/null 2>&1
1594     if grep ext2 /proc/filesystems >/dev/null 2>&1
1595     then
1596         :
1597     else
1598         _notrun "This test requires ext2 filesystem support"
1599     fi
1600 }
1601
1602 # this test requires tmpfs filesystem support
1603 #
1604 _require_tmpfs()
1605 {
1606         modprobe tmpfs >/dev/null 2>&1
1607         grep -q tmpfs /proc/filesystems ||
1608                 _notrun "this test requires tmpfs support"
1609 }
1610
1611 # this test requires that (large) loopback device files are not in use
1612 #
1613 _require_no_large_scratch_dev()
1614 {
1615     [ "$LARGE_SCRATCH_DEV" = yes ] && \
1616         _notrun "Large filesystem testing in progress, skipped this test"
1617 }
1618
1619 # this test requires that a realtime subvolume is in use, and
1620 # that the kernel supports realtime as well.
1621 #
1622 _require_realtime()
1623 {
1624     [ "$USE_EXTERNAL" = yes ] || \
1625         _notrun "External volumes not in use, skipped this test"
1626     [ "$SCRATCH_RTDEV" = "" ] && \
1627         _notrun "Realtime device required, skipped this test"
1628 }
1629
1630 # this test requires that a specified command (executable) exists
1631 # $1 - command, $2 - name for error message
1632 #
1633 # Note: the command string might have parameters, so strip them before checking
1634 # whether it is executable.
1635 _require_command()
1636 {
1637         if [ $# -eq 2 ]; then
1638                 _name="$2"
1639         elif [ $# -eq 1 ]; then
1640                 _name="$1"
1641         else
1642                 _fail "usage: _require_command <command> [<name>]"
1643         fi
1644
1645         _command=`echo "$1" | awk '{ print $1 }'`
1646         if [ ! -x "$_command" ]; then
1647                 _notrun "$_name utility required, skipped this test"
1648         fi
1649 }
1650
1651 # this test requires the device to be valid block device
1652 # $1 - device
1653 _require_block_device()
1654 {
1655         if [ -z "$1" ]; then
1656                 echo "Usage: _require_block_device <dev>" 1>&2
1657                 exit 1
1658         fi
1659         if [ "`_is_block_dev "$1"`" == "" ]; then
1660                 _notrun "require $1 to be valid block disk"
1661         fi
1662 }
1663
1664 # brd based ram disks erase the device when they receive a flush command when no
1665 # active references are present. This causes problems for DM devices sitting on
1666 # top of brd devices as DM doesn't hold active references to the brd device.
1667 _require_sane_bdev_flush()
1668 {
1669         echo $1 | grep -q "^/dev/ram[0-9]\+$"
1670         if [ $? -eq 0 ]; then
1671                 _notrun "This test requires a sane block device flush"
1672         fi
1673 }
1674
1675 # this test requires a specific device mapper target
1676 _require_dm_target()
1677 {
1678         _target=$1
1679
1680         # require SCRATCH_DEV to be a valid block device with sane BLKFLSBUF
1681         # behaviour
1682         _require_block_device $SCRATCH_DEV
1683         _require_sane_bdev_flush $SCRATCH_DEV
1684         _require_command "$DMSETUP_PROG" dmsetup
1685
1686         modprobe dm-$_target >/dev/null 2>&1
1687
1688         $DMSETUP_PROG targets 2>&1 | grep -q ^$_target
1689         if [ $? -ne 0 ]; then
1690                 _notrun "This test requires dm $_target support"
1691         fi
1692 }
1693
1694 # this test requires the ext4 kernel support crc feature on scratch device
1695 #
1696 _require_scratch_ext4_crc()
1697 {
1698         _scratch_mkfs_ext4 >/dev/null 2>&1
1699         dumpe2fs -h $SCRATCH_DEV 2> /dev/null | grep -q metadata_csum || _notrun "metadata_csum not supported by this filesystem"
1700         _scratch_mount >/dev/null 2>&1 \
1701            || _notrun "Kernel doesn't support metadata_csum feature"
1702         _scratch_unmount
1703 }
1704
1705 # this test requires the bigalloc feature to be available in mkfs.ext4
1706 #
1707 _require_ext4_mkfs_bigalloc()
1708 {
1709         $MKFS_EXT4_PROG -F -O bigalloc -n $SCRATCH_DEV 512m >/dev/null 2>&1 \
1710            || _notrun "mkfs.ext4 doesn't have bigalloc feature"
1711 }
1712
1713 # this test requires the ext4 kernel support bigalloc feature
1714 #
1715 _require_ext4_bigalloc()
1716 {
1717         $MKFS_EXT4_PROG -F -O bigalloc $SCRATCH_DEV 512m >/dev/null 2>&1
1718         _scratch_mount >/dev/null 2>&1 \
1719            || _notrun "Ext4 kernel doesn't support bigalloc feature"
1720         _scratch_unmount
1721 }
1722
1723 # this test requires that external log/realtime devices are not in use
1724 #
1725 _require_nonexternal()
1726 {
1727     [ "$USE_EXTERNAL" = yes ] && \
1728         _notrun "External device testing in progress, skipped this test"
1729 }
1730
1731 # this test requires that a (specified) aio-dio executable exists
1732 # $1 - command (optional)
1733 #
1734 _require_aiodio()
1735 {
1736     if [ -z "$1" ]
1737     then
1738         AIO_TEST=src/aio-dio-regress/aiodio_sparse2
1739         [ -x $AIO_TEST ] || _notrun "aio-dio utilities required"
1740     else
1741         AIO_TEST=src/aio-dio-regress/$1
1742         [ -x $AIO_TEST ] || _notrun "$AIO_TEST not built"
1743     fi
1744     _require_odirect
1745 }
1746
1747 # this test requires that a test program exists under src/
1748 # $1 - command (require)
1749 #
1750 _require_test_program()
1751 {
1752     SRC_TEST=src/$1
1753     [ -x $SRC_TEST ] || _notrun "$SRC_TEST not built"
1754 }
1755
1756 # run an aio-dio program
1757 # $1 - command
1758 _run_aiodio()
1759 {
1760     if [ -z "$1" ]
1761     then
1762         echo "usage: _run_aiodio command_name" 2>&1
1763         status=1; exit 1
1764     fi
1765
1766     _require_aiodio $1
1767
1768     local testtemp=$TEST_DIR/aio-testfile
1769     rm -f $testtemp
1770     $AIO_TEST $testtemp 2>&1
1771     status=$?
1772     rm -f $testtemp
1773
1774     return $status
1775 }
1776
1777 # this test requires y2038 sysfs switch and filesystem
1778 # timestamp ranges support.
1779 _require_y2038()
1780 {
1781         local device=${1:-$TEST_DEV}
1782         local sysfsdir=/proc/sys/fs/fs-timestamp-check-on
1783
1784         if [ ! -e $sysfsdir ]; then
1785                 _notrun "no kernel support for y2038 sysfs switch"
1786         fi
1787
1788         local tsmin tsmax
1789         read tsmin tsmax <<<$(_filesystem_timestamp_range $device)
1790         if [ $tsmin -eq -1 -a $tsmax -eq -1 ]; then
1791                 _notrun "filesystem $FSTYP timestamp bounds are unknown"
1792         fi
1793 }
1794
1795 _filesystem_timestamp_range()
1796 {
1797         device=${1:-$TEST_DEV}
1798         case $FSTYP in
1799         ext4)
1800                 if [ $(dumpe2fs -h $device 2>/dev/null | grep "Inode size:" | cut -d: -f2) -gt 128 ]; then
1801                         echo "-2147483648 15032385535"
1802                 else
1803                         echo "-2147483648 2147483647"
1804                 fi
1805                 ;;
1806
1807         xfs)
1808                 echo "-2147483648 2147483647"
1809                 ;;
1810         jfs)
1811                 echo "0 4294967295"
1812                 ;;
1813         f2fs)
1814                 echo "-2147483648 2147483647"
1815                 ;;
1816         *)
1817                 echo "-1 -1"
1818                 ;;
1819         esac
1820 }
1821
1822 # indicate whether YP/NIS is active or not
1823 #
1824 _yp_active()
1825 {
1826         local dn
1827         dn=$(domainname 2>/dev/null)
1828         test -n "${dn}" -a "${dn}" != "(none)" -a "${dn}" != "localdomain"
1829         echo $?
1830 }
1831
1832 # cat the password file
1833 #
1834 _cat_passwd()
1835 {
1836         [ $(_yp_active) -eq 0 ] && ypcat passwd
1837         cat /etc/passwd
1838 }
1839
1840 # cat the group file
1841 #
1842 _cat_group()
1843 {
1844         [ $(_yp_active) -eq 0 ] && ypcat group
1845         cat /etc/group
1846 }
1847
1848 # check for a user on the machine, fsgqa as default
1849 #
1850 _require_user()
1851 {
1852     qa_user=fsgqa
1853     if [ -n "$1" ];then
1854         qa_user=$1
1855     fi
1856     _cat_passwd | grep -q $qa_user
1857     [ "$?" == "0" ] || _notrun "$qa_user user not defined."
1858     echo /bin/true | su $qa_user
1859     [ "$?" == "0" ] || _notrun "$qa_user cannot execute commands."
1860 }
1861
1862 # check for a group on the machine, fsgqa as default
1863 #
1864 _require_group()
1865 {
1866     qa_group=fsgqa
1867     if [ -n "$1" ];then
1868         qa_group=$1
1869     fi
1870     _cat_group | grep -q $qa_group
1871     [ "$?" == "0" ] || _notrun "$qa_group user not defined."
1872 }
1873
1874 _filter_user_do()
1875 {
1876         perl -ne "
1877 s,.*Permission\sdenied.*,Permission denied,;
1878 s,.*no\saccess\sto\stty.*,,;
1879 s,.*no\sjob\scontrol\sin\sthis\sshell.*,,;
1880 s,^\s*$,,;
1881         print;"
1882 }
1883
1884 _user_do()
1885 {
1886     if [ "$HOSTOS" == "IRIX" ]
1887         then
1888         echo $1 | /bin/bash "su $qa_user 2>&1" | _filter_user_do
1889     else
1890         echo $1 | su -s /bin/bash $qa_user 2>&1 | _filter_user_do
1891     fi
1892 }
1893
1894 _require_xfs_io_command()
1895 {
1896         if [ -z "$1" ]
1897         then
1898                 echo "Usage: _require_xfs_io_command command [switch]" 1>&2
1899                 exit 1
1900         fi
1901         command=$1
1902         shift
1903         param="$*"
1904
1905         testfile=$TEST_DIR/$$.xfs_io
1906         case $command in
1907         "chproj")
1908                 testio=`$XFS_IO_PROG -F -f -c "chproj 0" $testfile 2>&1`
1909                 ;;
1910         "falloc" )
1911                 testio=`$XFS_IO_PROG -F -f -c "falloc 0 1m" $testfile 2>&1`
1912                 ;;
1913         "fpunch" | "fcollapse" | "zero" | "fzero" | "finsert" | "funshare")
1914                 testio=`$XFS_IO_PROG -F -f -c "pwrite 0 20k" -c "fsync" \
1915                         -c "$command 4k 8k" $testfile 2>&1`
1916                 ;;
1917         "fiemap")
1918                 testio=`$XFS_IO_PROG -F -f -c "pwrite 0 20k" -c "fsync" \
1919                         -c "fiemap -v" $testfile 2>&1`
1920                 ;;
1921         "flink" )
1922                 testio=`$XFS_IO_PROG -T -F -c "flink $testfile" \
1923                         $TEST_DIR 2>&1`
1924                 echo $testio | egrep -q "invalid option|Is a directory" && \
1925                         _notrun "xfs_io $command support is missing"
1926                 ;;
1927         "fsmap" )
1928                 testio=`$XFS_IO_PROG -f -c "fsmap" $testfile 2>&1`
1929                 echo $testio | egrep -q "Inappropriate ioctl" && \
1930                         _notrun "xfs_io $command support is missing"
1931                 ;;
1932         "open")
1933                 # -c "open $f" is broken in xfs_io <= 4.8. Along with the fix,
1934                 # a new -C flag was introduced to execute one shot commands.
1935                 # Check for -C flag support as an indication for the bug fix.
1936                 testio=`$XFS_IO_PROG -F -f -C "open $testfile" $testfile 2>&1`
1937                 echo $testio | egrep -q "invalid option" && \
1938                         _notrun "xfs_io $command support is missing"
1939                 ;;
1940         "utimes" )
1941                 testio=`$XFS_IO_PROG -f -c "utimes" 0 0 0 0 $testfile 2>&1`
1942                 ;;
1943         *)
1944                 testio=`$XFS_IO_PROG -c "$command help" 2>&1`
1945         esac
1946
1947         rm -f $testfile 2>&1 > /dev/null
1948         echo $testio | grep -q "not found" && \
1949                 _notrun "xfs_io $command support is missing"
1950         echo $testio | grep -q "Operation not supported" && \
1951                 _notrun "xfs_io $command failed (old kernel/wrong fs?)"
1952         echo $testio | grep -q "foreign file active" && \
1953                 _notrun "xfs_io $command not supported on $FSTYP"
1954
1955         test -z "$param" && return
1956         $XFS_IO_PROG -c "help $command" | grep -q "^ $param --" || \
1957                 _notrun "xfs_io $command doesn't support $param"
1958 }
1959
1960 # check that kernel and filesystem support direct I/O
1961 _require_odirect()
1962 {
1963         if [ $FSTYP = "ext4" ] ; then
1964                 if echo "$MOUNT_OPTIONS" | grep -q "test_dummy_encryption"; then
1965                         _notrun "ext4 encryption doesn't support O_DIRECT"
1966                 fi
1967         fi
1968         testfile=$TEST_DIR/$$.direct
1969         $XFS_IO_PROG -F -f -d -c "pwrite 0 20k" $testfile > /dev/null 2>&1
1970         if [ $? -ne 0 ]; then
1971                 _notrun "O_DIRECT is not supported"
1972         fi
1973         rm -f $testfile 2>&1 > /dev/null
1974 }
1975
1976 # Check that the filesystem supports swapfiles
1977 _require_scratch_swapfile()
1978 {
1979         _require_scratch
1980
1981         _scratch_mkfs >/dev/null
1982         _scratch_mount
1983
1984         # Minimum size for mkswap is 10 pages
1985         local size=$(($(get_page_size) * 10))
1986
1987         _pwrite_byte 0x61 0 "$size" "$SCRATCH_MNT/swap" >/dev/null 2>&1
1988         mkswap "$SCRATCH_MNT/swap" >/dev/null 2>&1
1989         if ! swapon "$SCRATCH_MNT/swap" >/dev/null 2>&1; then
1990                 _scratch_unmount
1991                 _notrun "swapfiles are not supported"
1992         fi
1993
1994         swapoff "$SCRATCH_MNT/swap" >/dev/null 2>&1
1995         _scratch_unmount
1996 }
1997
1998 # Check that a fs has enough free space (in 1024b blocks)
1999 #
2000 _require_fs_space()
2001 {
2002         MNT=$1
2003         BLOCKS=$2       # in units of 1024
2004         let GB=$BLOCKS/1024/1024
2005
2006         FREE_BLOCKS=`df -kP $MNT | grep -v Filesystem | awk '{print $4}'`
2007         [ $FREE_BLOCKS -lt $BLOCKS ] && \
2008                 _notrun "This test requires at least ${GB}GB free on $MNT to run"
2009 }
2010
2011 #
2012 # Check if the filesystem supports sparse files.
2013 #
2014 # Unfortunately there is no better way to do this than a manual black list.
2015 #
2016 _require_sparse_files()
2017 {
2018     case $FSTYP in
2019     hfsplus)
2020         _notrun "Sparse files not supported by this filesystem type: $FSTYP"
2021         ;;
2022     *)
2023         ;;
2024     esac
2025 }
2026
2027 _require_debugfs()
2028 {
2029     #boot_params always present in debugfs
2030     [ -d "$DEBUGFS_MNT/boot_params" ] || _notrun "Debugfs not mounted"
2031 }
2032
2033 _require_fail_make_request()
2034 {
2035     [ -f "$DEBUGFS_MNT/fail_make_request/probability" ] \
2036         || _notrun "$DEBUGFS_MNT/fail_make_request \
2037  not found. Seems that CONFIG_FAIL_MAKE_REQUEST kernel config option not enabled"
2038 }
2039
2040 #
2041 # Check if the file system supports seek_data/hole
2042 #
2043 _require_seek_data_hole()
2044 {
2045     testfile=$TEST_DIR/$$.seek
2046     testseek=`$here/src/seek_sanity_test -t $testfile 2>&1`
2047     rm -f $testfile &>/dev/null
2048     echo $testseek | grep -q "Kernel does not support" && \
2049         _notrun "File system does not support llseek(2) SEEK_DATA/HOLE"
2050 }
2051
2052 _require_runas()
2053 {
2054         _require_test_program "runas"
2055 }
2056
2057 _runas()
2058 {
2059         "$here/src/runas" "$@"
2060 }
2061
2062 _require_richacl_prog()
2063 {
2064         _require_command "$GETRICHACL_PROG" getrichacl
2065         _require_command "$SETRICHACL_PROG" setrichacl
2066 }
2067
2068 _require_scratch_richacl_xfs()
2069 {
2070         _scratch_mkfs_xfs_supported -m richacl=1 >/dev/null 2>&1 \
2071                 || _notrun "mkfs.xfs doesn't have richacl feature"
2072         _scratch_mkfs_xfs -m richacl=1 >/dev/null 2>&1
2073         _scratch_mount >/dev/null 2>&1 \
2074                 || _notrun "kernel doesn't support richacl feature on $FSTYP"
2075         _scratch_unmount
2076 }
2077
2078 _require_scratch_richacl_ext4()
2079 {
2080         _scratch_mkfs -O richacl >/dev/null 2>&1 \
2081                 || _notrun "can't mkfs $FSTYP with option -O richacl"
2082         _scratch_mount >/dev/null 2>&1 \
2083                 || _notrun "kernel doesn't support richacl feature on $FSTYP"
2084         _scratch_unmount
2085 }
2086
2087 _require_scratch_richacl_support()
2088 {
2089         _scratch_mount
2090         $GETFATTR_PROG -n system.richacl >/dev/null 2>&1 \
2091                 || _notrun "this test requires richacl support on \$SCRATCH_DEV"
2092         _scratch_unmount
2093 }
2094
2095 _require_scratch_richacl()
2096 {
2097         case "$FSTYP" in
2098         xfs)    _require_scratch_richacl_xfs
2099                 ;;
2100         ext4)   _require_scratch_richacl_ext4
2101                 ;;
2102         nfs*|cifs|overlay)
2103                 _require_scratch_richacl_support
2104                 ;;
2105         *)      _notrun "this test requires richacl support on \$SCRATCH_DEV"
2106                 ;;
2107         esac
2108 }
2109
2110 _scratch_mkfs_richacl()
2111 {
2112         case "$FSTYP" in
2113         xfs)    _scratch_mkfs_xfs -m richacl=1
2114                 ;;
2115         ext4)   _scratch_mkfs -O richacl
2116                 ;;
2117         nfs*|cifs|overlay)
2118                 _scratch_mkfs
2119                 ;;
2120         esac
2121 }
2122
2123 # check that a FS on a device is mounted
2124 # if so, return mount point
2125 #
2126 _is_mounted()
2127 {
2128     if [ $# -ne 1 ]
2129     then
2130         echo "Usage: _is_mounted device" 1>&2
2131         exit 1
2132     fi
2133
2134     device=$1
2135
2136     if _mount | grep "$device " | $AWK_PROG -v pattern="type $FSTYP" '
2137         pattern        { print $3 ; exit 0 }
2138         END            { exit 1 }
2139     '
2140     then
2141         echo "_is_mounted: $device is not a mounted $FSTYP FS"
2142         exit 1
2143     fi
2144 }
2145
2146 # remount a FS to a new mode (ro or rw)
2147 #
2148 _remount()
2149 {
2150     if [ $# -ne 2 ]
2151     then
2152         echo "Usage: _remount device ro/rw" 1>&2
2153         exit 1
2154     fi
2155     device=$1
2156     mode=$2
2157
2158     if ! mount -o remount,$mode $device
2159     then
2160         echo "_remount: failed to remount filesystem on $device as $mode"
2161         exit 1
2162     fi
2163 }
2164
2165 # Run the appropriate repair/check on a filesystem
2166 #
2167 # if the filesystem is mounted, it's either remounted ro before being
2168 # checked or it's unmounted and then remounted
2169 #
2170
2171 # If set, we remount ro instead of unmounting for fsck
2172 USE_REMOUNT=0
2173
2174 _umount_or_remount_ro()
2175 {
2176     if [ $# -ne 1 ]
2177     then
2178         echo "Usage: _umount_or_remount_ro <device>" 1>&2
2179         exit 1
2180     fi
2181
2182     device=$1
2183     mountpoint=`_is_mounted $device`
2184
2185     if [ $USE_REMOUNT -eq 0 ]; then
2186         $UMOUNT_PROG $device
2187     else
2188         _remount $device ro
2189     fi
2190     echo "$mountpoint"
2191 }
2192
2193 _mount_or_remount_rw()
2194 {
2195         if [ $# -ne 3 ]; then
2196                 echo "Usage: _mount_or_remount_rw <opts> <dev> <mnt>" 1>&2
2197                 exit 1
2198         fi
2199         mount_opts=$1
2200         device=$2
2201         mountpoint=$3
2202
2203         if [ $USE_REMOUNT -eq 0 ]; then
2204                 if [ "$FSTYP" != "overlay" ]; then
2205                         _mount -t $FSTYP $mount_opts $device $mountpoint
2206                 else
2207                         _overlay_mount $device $mountpoint
2208                 fi
2209                 if [ $? -ne 0 ]; then
2210                         echo "!!! failed to remount $device on $mountpoint"
2211                         return 0 # ok=0
2212                 fi
2213         else
2214                 _remount $device rw
2215         fi
2216
2217         return 1 # ok=1
2218 }
2219
2220 # Check a generic filesystem in no-op mode; this assumes that the
2221 # underlying fsck program accepts "-n" for a no-op (check-only) run,
2222 # and that it will still return an errno for corruption in this mode.
2223 #
2224 # Filesystems which don't support this will need to define their
2225 # own check routine.
2226 #
2227 _check_generic_filesystem()
2228 {
2229     device=$1
2230
2231     # If type is set, we're mounted
2232     type=`_fs_type $device`
2233     ok=1
2234
2235     if [ "$type" = "$FSTYP" ]
2236     then
2237         # mounted ...
2238         mountpoint=`_umount_or_remount_ro $device`
2239     fi
2240
2241     fsck -t $FSTYP $FSCK_OPTIONS $device >$tmp.fsck 2>&1
2242     if [ $? -ne 0 ]
2243     then
2244         echo "_check_generic_filesystem: filesystem on $device is inconsistent (see $seqres.full)"
2245
2246         echo "_check_generic filesystem: filesystem on $device is inconsistent" >>$seqres.full
2247         echo "*** fsck.$FSTYP output ***"       >>$seqres.full
2248         cat $tmp.fsck                           >>$seqres.full
2249         echo "*** end fsck.$FSTYP output"       >>$seqres.full
2250
2251         ok=0
2252     fi
2253     rm -f $tmp.fsck
2254
2255     if [ $ok -eq 0 ]
2256     then
2257         echo "*** mount output ***"             >>$seqres.full
2258         _mount                                  >>$seqres.full
2259         echo "*** end mount output"             >>$seqres.full
2260     elif [ "$type" = "$FSTYP" ]
2261     then
2262         # was mounted ...
2263         _mount_or_remount_rw "$MOUNT_OPTIONS" $device $mountpoint
2264         ok=$?
2265     fi
2266
2267     if [ $ok -eq 0 ]; then
2268         status=1
2269         if [ "$iam" != "check" ]; then
2270                 exit 1
2271         fi
2272         return 1
2273     fi
2274
2275     return 0
2276 }
2277
2278 # Filter the knowen errors the UDF Verifier reports.
2279 _udf_test_known_error_filter()
2280 {
2281         egrep -v "PVD  60  Error: Interchange Level: 1, Maximum Interchange Level: 0|FSD  28  Error: Interchange Level: 1, Maximum Interchange Level: 1,|PVD  72  Warning: Volume Set Identifier: \"\*IRIX UDF\",|Warning: [0-9]+ unused blocks NOT marked as unallocated."
2282
2283 }
2284
2285 _check_udf_filesystem()
2286 {
2287     [ "$DISABLE_UDF_TEST" == "1" ] && return
2288
2289     if [ $# -ne 1 -a $# -ne 2 ]
2290     then
2291         echo "Usage: _check_udf_filesystem device [last_block]" 1>&2
2292         exit 1
2293     fi
2294
2295     if [ ! -x $here/src/udf_test ]
2296     then
2297         echo "udf_test not installed, please download and build the Philips"
2298         echo "UDF Verification Software from http://www.extra.research.philips.com/udf/."
2299         echo "Then copy the udf_test binary to $here/src/."
2300         echo "If you do not wish to run udf_test then set environment variable DISABLE_UDF_TEST"
2301         echo "to 1."
2302         return
2303     fi
2304
2305     device=$1
2306     if [ $# -eq 2 ];
2307     then
2308         LAST_BLOCK=`expr \( $2 - 1 \)`
2309         OPT_ARG="-lastvalidblock $LAST_BLOCK"
2310     fi
2311
2312     rm -f $seqres.checkfs
2313     sleep 1 # Due to a problem with time stamps in udf_test
2314     $here/src/udf_test $OPT_ARG $device | tee $seqres.checkfs | egrep "Error|Warning" | \
2315         _udf_test_known_error_filter | \
2316         egrep -iv "Error count:.*[0-9]+.*total occurrences:.*[0-9]+|Warning count:.*[0-9]+.*total occurrences:.*[0-9]+" && \
2317         echo "Warning UDF Verifier reported errors see $seqres.checkfs." && return 1
2318     return 0
2319 }
2320
2321 _check_test_fs()
2322 {
2323     case $FSTYP in
2324     xfs)
2325         _check_xfs_test_fs
2326         ;;
2327     nfs)
2328         # no way to check consistency for nfs
2329         ;;
2330     cifs)
2331         # no way to check consistency for cifs
2332         ;;
2333     ceph)
2334         # no way to check consistency for CephFS
2335         ;;
2336     overlay)
2337         # no way to check consistency for overlay
2338         ;;
2339     udf)
2340         # do nothing for now
2341         ;;
2342     btrfs)
2343         _check_btrfs_filesystem $TEST_DEV
2344         ;;
2345     tmpfs)
2346         # no way to check consistency for tmpfs
2347         ;;
2348     *)
2349         _check_generic_filesystem $TEST_DEV
2350         ;;
2351     esac
2352 }
2353
2354 _check_scratch_fs()
2355 {
2356     device=$SCRATCH_DEV
2357     [ $# -eq 1 ] && device=$1
2358
2359     case $FSTYP in
2360     xfs)
2361         SCRATCH_LOG="none"
2362         SCRATCH_RT="none"
2363         [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_LOGDEV" ] && \
2364             SCRATCH_LOG="$SCRATCH_LOGDEV"
2365
2366         [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_RTDEV" ] && \
2367             SCRATCH_RT="$SCRATCH_RTDEV"
2368
2369         _check_xfs_filesystem $device $SCRATCH_LOG $SCRATCH_RT
2370         ;;
2371     udf)
2372         _check_udf_filesystem $device $udf_fsize
2373         ;;
2374     nfs*)
2375         # Don't know how to check an NFS filesystem, yet.
2376         ;;
2377     cifs)
2378         # Don't know how to check a CIFS filesystem, yet.
2379         ;;
2380     ceph)
2381         # no way to check consistency for CephFS
2382         ;;
2383     overlay)
2384         # no way to check consistency for overlay
2385         ;;
2386     btrfs)
2387         _check_btrfs_filesystem $device
2388         ;;
2389     tmpfs)
2390         # no way to check consistency for tmpfs
2391         ;;
2392     *)
2393         _check_generic_filesystem $device
2394         ;;
2395     esac
2396 }
2397
2398 _full_fstyp_details()
2399 {
2400      [ -z "$FSTYP" ] && FSTYP=xfs
2401      if [ $FSTYP = xfs ]; then
2402         if [ -d /proc/fs/xfs ]; then
2403             if grep -q 'debug 0' /proc/fs/xfs/stat; then
2404                 FSTYP="$FSTYP (non-debug)"
2405             elif grep -q 'debug 1' /proc/fs/xfs/stat; then
2406                 FSTYP="$FSTYP (debug)"
2407             fi
2408         else
2409             if uname -a | grep -qi 'debug'; then
2410                 FSTYP="$FSTYP (debug)"
2411             else
2412                 FSTYP="$FSTYP (non-debug)"
2413             fi
2414         fi
2415      fi
2416      echo $FSTYP
2417 }
2418
2419 _full_platform_details()
2420 {
2421      os=`uname -s`
2422      host=`hostname -s`
2423      kernel=`uname -r`
2424      platform=`uname -m`
2425      echo "$os/$platform $host $kernel"
2426 }
2427
2428 _get_os_name()
2429 {
2430         if [ "`uname`" == "IRIX64" ] || [ "`uname`" == "IRIX" ]; then
2431                 echo 'irix'
2432         elif [ "`uname`" == "Linux" ]; then
2433                 echo 'linux'
2434         else
2435                 echo Unknown operating system: `uname`
2436                 exit
2437         fi
2438 }
2439
2440 _link_out_file_named()
2441 {
2442         export FEATURES=$2
2443         SUFFIX=$(perl -e '
2444                 my %feathash;
2445                 my $feature, $result, $suffix, $opts;
2446
2447                 foreach $feature (split(/,/, $ENV{"FEATURES"})) {
2448                         $feathash{$feature} = 1;
2449                 }
2450                 $result = "default";
2451                 while (<>) {
2452                         my $found = 1;
2453
2454                         chomp;
2455                         ($opts, $suffix) = split(/ *: */);
2456                         foreach my $opt (split(/,/, $opts)) {
2457                                 if (!exists($feathash{$opt})) {
2458                                         $found = 0;
2459                                         last;
2460                                 }
2461                         }
2462                         if ($found == 1) {
2463                                 $result = $suffix;
2464                                 last;
2465                         }
2466                 }
2467                 print $result
2468                 ' <$seqfull.cfg)
2469         rm -f $1
2470         SRC=$(basename $1)
2471         ln -fs $SRC.$SUFFIX $1
2472 }
2473
2474 _link_out_file()
2475 {
2476         if [ $# -eq 0 ]; then
2477                 FEATURES="$(_get_os_name)"
2478                 if [ -n "$MOUNT_OPTIONS" ]; then
2479                         FEATURES=$FEATURES,${MOUNT_OPTIONS##"-o "}
2480                 fi
2481         else
2482                 FEATURES=$1
2483         fi
2484
2485         _link_out_file_named $seqfull.out "$FEATURES"
2486 }
2487
2488 _die()
2489 {
2490         echo $@
2491         exit 1
2492 }
2493
2494 # convert urandom incompressible data to compressible text data
2495 _ddt()
2496 {
2497         od /dev/urandom | dd iflag=fullblock ${*}
2498 }
2499
2500 #takes files, randomdata
2501 _nfiles()
2502 {
2503         f=0
2504         while [ $f -lt $1 ]
2505         do
2506                 file=f$f
2507                 echo > $file
2508                 if [ $size -gt 0 ]; then
2509                     if [ "$2" == "false" ]; then
2510                         dd if=/dev/zero of=$file bs=1024 count=$size 2>&1 | _filter_dd
2511                     elif [ "$2" == "comp" ]; then
2512                         _ddt of=$file bs=1024 count=$size 2>&1 | _filter_dd
2513                     else
2514                         dd if=/dev/urandom of=$file bs=1024 count=$size 2>&1 | _filter_dd
2515                     fi
2516                 fi
2517                 let f=$f+1
2518         done
2519 }
2520
2521 # takes dirname, depth, randomdata
2522 _descend()
2523 {
2524         dirname=$1; depth=$2; randomdata=$3
2525         mkdir $dirname  || die "mkdir $dirname failed"
2526         cd $dirname
2527
2528         _nfiles $files $randomdata          # files for this dir and data type
2529
2530         [ $depth -eq 0 ] && return
2531         let deep=$depth-1 # go 1 down
2532
2533         [ $verbose = true ] && echo "descending, depth from leaves = $deep"
2534
2535         d=0
2536         while [ $d -lt $dirs ]
2537         do
2538                 _descend d$d $deep &
2539                 let d=$d+1
2540                 wait
2541         done
2542 }
2543
2544 # Populate a filesystem with inodes for performance experiments
2545 #
2546 # usage: populate [-v] [-n ndirs] [-f nfiles] [-d depth] [-r root] [-s size] [-x]
2547 #
2548 _populate_fs()
2549 {
2550     here=`pwd`
2551     dirs=5          # ndirs in each subdir till leaves
2552     size=0          # sizeof files in K
2553     files=100       # num files in _each_ subdir
2554     depth=2         # depth of tree from root to leaves
2555     verbose=false
2556     root=root       # path of initial root of directory tree
2557     randomdata=false # -x data type urandom, zero or compressible
2558
2559     OPTIND=1
2560     while getopts "d:f:n:r:s:v:x:c" c
2561     do
2562         case $c in
2563         d)      depth=$OPTARG;;
2564         n)      dirs=$OPTARG;;
2565         f)      files=$OPTARG;;
2566         s)      size=$OPTARG;;
2567         v)      verbose=true;;
2568         r)      root=$OPTARG;;
2569         x)      randomdata=true;;
2570         c)      randomdata=comp;;
2571         esac
2572     done
2573
2574     _descend $root $depth $randomdata
2575     wait
2576
2577     cd $here
2578
2579     [ $verbose = true ] && echo done
2580 }
2581
2582 # query whether the given file has the given inode flag set
2583 #
2584 _test_inode_flag()
2585 {
2586         flag=$1
2587         file=$2
2588
2589         if $XFS_IO_PROG -r -c 'lsattr -v' "$file" | grep -q "$flag" ; then
2590                 return 0
2591         fi
2592         return 1
2593 }
2594
2595 # query the given files extsize allocator hint in bytes (if any)
2596 #
2597 _test_inode_extsz()
2598 {
2599         file=$1
2600         blocks=""
2601
2602         blocks=`$XFS_IO_PROG -r -c 'stat' "$file" | \
2603                 awk '/^xattr.extsize =/ { print $3 }'`
2604         [ -z "$blocks" ] && blocks="0"
2605         echo $blocks
2606 }
2607
2608 # scratch_dev_pool should contain the disks pool for the btrfs raid
2609 _require_scratch_dev_pool()
2610 {
2611         local i
2612         local ndevs
2613
2614         if [ -z "$SCRATCH_DEV_POOL" ]; then
2615                 _notrun "this test requires a valid \$SCRATCH_DEV_POOL"
2616         fi
2617
2618         if [ -z "$1" ]; then
2619                 ndevs=2
2620         else
2621                 ndevs=$1
2622         fi
2623
2624         # btrfs test case needs ndevs or more scratch_dev_pool; other FS not sure
2625         # so fail it
2626         case $FSTYP in
2627         btrfs)
2628                 if [ "`echo $SCRATCH_DEV_POOL|wc -w`" -lt $ndevs ]; then
2629                         _notrun "btrfs and this test needs $ndevs or more disks in SCRATCH_DEV_POOL"
2630                 fi
2631         ;;
2632         *)
2633                 _notrun "dev_pool is not supported by fstype \"$FSTYP\""
2634         ;;
2635         esac
2636
2637         for i in $SCRATCH_DEV_POOL; do
2638                 if [ "`_is_block_dev "$i"`" = "" ]; then
2639                         _notrun "this test requires valid block disk $i"
2640                 fi
2641                 if [ "`_is_block_dev "$i"`" = "`_is_block_dev "$TEST_DEV"`" ]; then
2642                         _notrun "$i is part of TEST_DEV, this test requires unique disks"
2643                 fi
2644                 if _mount | grep -q $i; then
2645                         if ! $UMOUNT_PROG $i; then
2646                             echo "failed to unmount $i - aborting"
2647                             exit 1
2648                         fi
2649                 fi
2650                 # to help better debug when something fails, we remove
2651                 # traces of previous btrfs FS on the dev.
2652                 dd if=/dev/zero of=$i bs=4096 count=100 > /dev/null 2>&1
2653         done
2654 }
2655
2656 # ensure devices in SCRATCH_DEV_POOL are of the same size
2657 # must be called after _require_scratch_dev_pool
2658 _require_scratch_dev_pool_equal_size()
2659 {
2660         local _size
2661         local _newsize
2662         local _dev
2663
2664         # SCRATCH_DEV has been set to the first device in SCRATCH_DEV_POOL
2665         _size=`_get_device_size $SCRATCH_DEV`
2666         for _dev in $SCRATCH_DEV_POOL; do
2667                 _newsize=`_get_device_size $_dev`
2668                 if [ $_size -ne $_newsize ]; then
2669                         _notrun "This test requires devices in SCRATCH_DEV_POOL have the same size"
2670                 fi
2671         done
2672 }
2673
2674 # We will check if the device is deletable
2675 _require_deletable_scratch_dev_pool()
2676 {
2677         local i
2678         local x
2679         for i in $SCRATCH_DEV_POOL; do
2680                 x=`echo $i | cut -d"/" -f 3`
2681                 if [ ! -f /sys/class/block/${x}/device/delete ]; then
2682                         _notrun "$i is a device which is not deletable"
2683                 fi
2684         done
2685 }
2686
2687 # Check that fio is present, and it is able to execute given jobfile
2688 _require_fio()
2689 {
2690         job=$1
2691
2692         _require_command "$FIO_PROG" fio
2693         if [ -z "$1" ]; then
2694                 return 1;
2695         fi
2696
2697         $FIO_PROG --warnings-fatal --showcmd $job >> $seqres.full 2>&1
2698         [ $? -eq 0 ] || _notrun "$FIO_PROG too old, see $seqres.full"
2699 }
2700
2701 # Does freeze work on this fs?
2702 _require_freeze()
2703 {
2704         xfs_freeze -f "$TEST_DIR" >/dev/null 2>&1
2705         result=$? 
2706         xfs_freeze -u "$TEST_DIR" >/dev/null 2>&1
2707         [ $result -eq 0 ] || _notrun "$FSTYP does not support freezing"
2708 }
2709
2710 # Does shutdown work on this fs?
2711 _require_scratch_shutdown()
2712 {
2713         [ -x src/godown ] || _notrun "src/godown executable not found"
2714
2715         _scratch_mkfs > /dev/null 2>&1
2716         _scratch_mount
2717         src/godown -f $SCRATCH_MNT 2>&1 \
2718                 || _notrun "$FSTYP does not support shutdown"
2719         _scratch_unmount
2720 }
2721
2722 # Does dax mount option work on this dev/fs?
2723 _require_scratch_dax()
2724 {
2725         _require_scratch
2726         _scratch_mkfs > /dev/null 2>&1
2727         _scratch_mount -o dax
2728         # Check options to be sure. XFS ignores dax option
2729         # and goes on if dev underneath does not support dax.
2730         _fs_options $SCRATCH_DEV | grep -qw "dax" || \
2731                 _notrun "$SCRATCH_DEV $FSTYP does not support -o dax"
2732         _scratch_unmount
2733 }
2734
2735 # Does norecovery support by this fs?
2736 _require_norecovery()
2737 {
2738         _scratch_mount -o ro,norecovery || \
2739                 _notrun "$FSTYP does not support norecovery"
2740         _scratch_unmount
2741 }
2742
2743 # Does this filesystem support metadata journaling?
2744 # We exclude ones here that don't; otherwise we assume that it does, so the
2745 # test will run, fail, and motivate someone to update this test for a new
2746 # filesystem.
2747 #
2748 # It's possible that TEST_DEV and SCRATCH_DEV have different features (it'd be
2749 # odd, but possible) so check $TEST_DEV by default, but we can optionall pass
2750 # any dev we want.
2751 _require_metadata_journaling()
2752 {
2753         if [ -z $1 ]; then
2754                 DEV=$TEST_DEV
2755         else
2756                 DEV=$1
2757         fi
2758
2759         case "$FSTYP" in
2760         ext2|vfat|msdos)
2761                 _notrun "$FSTYP does not support metadata journaling"
2762                 ;;
2763         ext4)
2764                 # ext4 could be mkfs'd without a journal...
2765                 _require_dumpe2fs
2766                 $DUMPE2FS_PROG -h $DEV 2>&1 | grep -q has_journal || \
2767                         _notrun "$FSTYP on $DEV not configured with metadata journaling"
2768                 # ext4 might not load a journal
2769                 _exclude_scratch_mount_option "noload"
2770                 ;;
2771         *)
2772                 # by default we pass; if you need to, add your fs above!
2773                 ;;
2774         esac
2775 }
2776
2777 # Does fiemap support?
2778 _require_fiemap()
2779 {
2780         _require_xfs_io_command "fiemap"
2781 }
2782
2783 _count_extents()
2784 {
2785         $XFS_IO_PROG -c "fiemap" $1 | tail -n +2 | grep -v hole | wc -l
2786 }
2787
2788 _count_holes()
2789 {
2790         $XFS_IO_PROG -c "fiemap" $1 | tail -n +2 | grep hole | wc -l
2791 }
2792
2793 # arg 1 is dev to remove and is output of the below eg.
2794 # ls -l /sys/class/block/sdd | rev | cut -d "/" -f 3 | rev
2795 _devmgt_remove()
2796 {
2797         local lun=$1
2798         local disk=$2
2799
2800         echo 1 > /sys/class/scsi_device/${lun}/device/delete || _fail "Remove disk failed"
2801
2802         stat $disk > /dev/null 2>&1
2803         while [ $? -eq 0 ]; do
2804                 sleep 1
2805                 stat $disk > /dev/null 2>&1
2806         done
2807 }
2808
2809 # arg 1 is dev to add and is output of the below eg.
2810 # ls -l /sys/class/block/sdd | rev | cut -d "/" -f 3 | rev
2811 _devmgt_add()
2812 {
2813         local h
2814         local tdl
2815         # arg 1 will be in h:t:d:l format now in the h and "t d l" format
2816         h=`echo ${1} | cut -d":" -f 1`
2817         tdl=`echo ${1} | cut -d":" -f 2-|sed 's/:/ /g'`
2818
2819         echo ${tdl} >  /sys/class/scsi_host/host${h}/scan || _fail "Add disk failed"
2820
2821         # ensure the device comes online
2822         dev_back_oneline=0
2823         for i in `seq 1 10`; do
2824                 if [ -d /sys/class/scsi_device/${1}/device/block ]; then
2825                         dev=`ls /sys/class/scsi_device/${1}/device/block`
2826                         for j in `seq 1 10`;
2827                         do
2828                                 stat /dev/$dev > /dev/null 2>&1
2829                                 if [ $? -eq 0 ]; then
2830                                         dev_back_oneline=1
2831                                         break
2832                                 fi
2833                                 sleep 1
2834                         done
2835                         break
2836                 else
2837                         sleep 1
2838                 fi
2839         done
2840         if [ $dev_back_oneline -eq 0 ]; then
2841                 echo "/dev/$dev online failed" >> $seqres.full
2842         else
2843                 echo "/dev/$dev is back online" >> $seqres.full
2844         fi
2845 }
2846
2847 _require_fstrim()
2848 {
2849         if [ -z "$FSTRIM_PROG" ]; then
2850                 _notrun "This test requires fstrim utility."
2851         fi
2852 }
2853
2854 _require_batched_discard()
2855 {
2856         if [ $# -ne 1 ]; then
2857                 echo "Usage: _require_batched_discard mnt_point" 1>&2
2858                 exit 1
2859         fi
2860         _require_fstrim
2861         $FSTRIM_PROG $1 > /dev/null 2>&1 || _notrun "FITRIM not supported on $1"
2862 }
2863
2864 _require_dumpe2fs()
2865 {
2866         if [ -z "$DUMPE2FS_PROG" ]; then
2867                 _notrun "This test requires dumpe2fs utility."
2868         fi
2869 }
2870
2871 _require_ugid_map()
2872 {
2873         if [ ! -e /proc/self/uid_map ]; then
2874                 _notrun "This test requires procfs uid_map support."
2875         fi
2876         if [ ! -e /proc/self/gid_map ]; then
2877                 _notrun "This test requires procfs gid_map support."
2878         fi
2879 }
2880
2881 _require_fssum()
2882 {
2883         FSSUM_PROG=$here/src/fssum
2884         [ -x $FSSUM_PROG ] || _notrun "fssum not built"
2885 }
2886
2887 _require_cloner()
2888 {
2889         CLONER_PROG=$here/src/cloner
2890         [ -x $CLONER_PROG ] || \
2891                 _notrun "cloner binary not present at $CLONER_PROG"
2892 }
2893
2894 # Normalize mount options from global $MOUNT_OPTIONS
2895 # Convert options like "-o opt1,opt2 -oopt3" to
2896 # "opt1 opt2 opt3"
2897 _normalize_mount_options()
2898 {
2899         echo $MOUNT_OPTIONS | sed -n 's/-o\s*\(\S*\)/\1/gp'| sed 's/,/ /g'
2900 }
2901
2902 # skip test if MOUNT_OPTIONS contains the given strings
2903 _exclude_scratch_mount_option()
2904 {
2905         local mnt_opts=$(_normalize_mount_options)
2906
2907         while [ $# -gt 0 ]; do
2908                 if echo $mnt_opts | grep -qw "$1"; then
2909                         _notrun "mount option \"$1\" not allowed in this test"
2910                 fi
2911                 shift
2912         done
2913 }
2914
2915 _require_atime()
2916 {
2917         _exclude_scratch_mount_option "noatime"
2918         if [ "$FSTYP" == "nfs" ]; then
2919                 _notrun "atime related mount options have no effect on NFS"
2920         fi
2921 }
2922
2923 _require_relatime()
2924 {
2925         _scratch_mkfs > /dev/null 2>&1
2926         _scratch_mount -o relatime || \
2927                 _notrun "relatime not supported by the current kernel"
2928         _scratch_unmount
2929 }
2930
2931 _require_userns()
2932 {
2933         [ -x src/nsexec ] || _notrun "src/nsexec executable not found"
2934         src/nsexec -U true 2>/dev/null || _notrun "userns not supported by this kernel"
2935 }
2936
2937 _create_loop_device()
2938 {
2939         file=$1
2940         dev=`losetup -f --show $file` || _fail "Cannot assign $file to a loop device"
2941         echo $dev
2942 }
2943
2944 _destroy_loop_device()
2945 {
2946         dev=$1
2947         losetup -d $dev || _fail "Cannot destroy loop device $dev"
2948 }
2949
2950 _scale_fsstress_args()
2951 {
2952     args=""
2953     while [ $# -gt 0 ]; do
2954         case "$1" in
2955             -n) args="$args $1 $(($2 * $TIME_FACTOR))"; shift ;;
2956             -p) args="$args $1 $(($2 * $LOAD_FACTOR))"; shift ;;
2957             *) args="$args $1" ;;
2958         esac
2959         shift
2960     done
2961     echo $args
2962 }
2963
2964 #
2965 # Return the logical block size if running on a block device,
2966 # else substitute the page size.
2967 #
2968 _min_dio_alignment()
2969 {
2970     dev=$1
2971
2972     if [ -b "$dev" ]; then
2973         blockdev --getss $dev
2974     else
2975         $here/src/feature -s
2976     fi
2977 }
2978
2979 run_check()
2980 {
2981         echo "# $@" >> $seqres.full 2>&1
2982         "$@" >> $seqres.full 2>&1 || _fail "failed: '$@'"
2983 }
2984
2985 _require_test_symlinks()
2986 {
2987         # IRIX UDF does not support symlinks
2988         [ "$HOSTOS" = "IRIX" -a "$FSTYP" = 'udf' ] && \
2989                 _notrun "Require symlinks support"
2990         target=`mktemp -p $TEST_DIR`
2991         link=`mktemp -p $TEST_DIR -u`
2992         ln -s `basename $target` $link
2993         if [ "$?" -ne 0 ]; then
2994                 rm -f $target
2995                 _notrun "Require symlinks support"
2996         fi
2997         rm -f $target $link
2998 }
2999
3000 _require_test_fcntl_advisory_locks()
3001 {
3002         [ "$FSTYP" != "cifs" ] && return 0
3003         cat /proc/mounts | grep $TEST_DEV | grep cifs | grep -q "nobrl" && return 0
3004         cat /proc/mounts | grep $TEST_DEV | grep cifs | grep -qE "nounix|forcemand" && \
3005                 _notrun "Require fcntl advisory locks support"
3006 }
3007
3008 _require_test_lsattr()
3009 {
3010         testio=$(lsattr -d $TEST_DIR 2>&1)
3011         echo $testio | grep -q "Operation not supported" && \
3012                 _notrun "lsattr not supported by test filesystem type: $FSTYP"
3013         echo $testio | grep -q "Inappropriate ioctl for device" && \
3014                 _notrun "lsattr not supported by test filesystem type: $FSTYP"
3015 }
3016
3017 _require_chattr()
3018 {
3019     attribute=$1
3020
3021     touch $TEST_DIR/syscalltest
3022     chattr "+$attribute" $TEST_DIR/syscalltest > $TEST_DIR/syscalltest.out 2>&1
3023     status=$?
3024     chattr "-$attribute" $TEST_DIR/syscalltest > $TEST_DIR/syscalltest.out 2>&1
3025     if [ "$status" -ne 0 ]; then
3026       _notrun "file system doesn't support chattr +$attribute"
3027     fi
3028     cat $TEST_DIR/syscalltest.out >> $seqres.full
3029
3030     rm -f $TEST_DIR/syscalltest.out
3031 }
3032
3033 _get_total_inode()
3034 {
3035         if [ -z "$1" ]; then
3036                 echo "Usage: _get_total_inode <mnt>"
3037                 exit 1
3038         fi
3039         local nr_inode;
3040         nr_inode=`$DF_PROG -i $1 | tail -1 | awk '{print $3}'`
3041         echo $nr_inode
3042 }
3043
3044 _get_used_inode()
3045 {
3046         if [ -z "$1" ]; then
3047                 echo "Usage: _get_used_inode <mnt>"
3048                 exit 1
3049         fi
3050         local nr_inode;
3051         nr_inode=`$DF_PROG -i $1 | tail -1 | awk '{print $4}'`
3052         echo $nr_inode
3053 }
3054
3055 _get_used_inode_percent()
3056 {
3057         if [ -z "$1" ]; then
3058                 echo "Usage: _get_used_inode_percent <mnt>"
3059                 exit 1
3060         fi
3061         local pct_inode;
3062         pct_inode=`$DF_PROG -i $1 | tail -1 | awk '{ print $6 }' | \
3063                    sed -e 's/%//'`
3064         echo $pct_inode
3065 }
3066
3067 _get_free_inode()
3068 {
3069         if [ -z "$1" ]; then
3070                 echo "Usage: _get_free_inode <mnt>"
3071                 exit 1
3072         fi
3073         local nr_inode;
3074         nr_inode=`$DF_PROG -i $1 | tail -1 | awk '{print $5}'`
3075         echo $nr_inode
3076 }
3077
3078 # get the available space in bytes
3079 #
3080 _get_available_space()
3081 {
3082         if [ -z "$1" ]; then
3083                 echo "Usage: _get_available_space <mnt>"
3084                 exit 1
3085         fi
3086         local avail_kb;
3087         avail_kb=`$DF_PROG $1 | tail -n1 | awk '{ print $5 }'`
3088         echo $((avail_kb * 1024))
3089 }
3090
3091 # return device size in kb
3092 _get_device_size()
3093 {
3094         grep `_short_dev $1` /proc/partitions | awk '{print $3}'
3095 }
3096
3097 # check dmesg log for WARNING/Oops/etc.
3098 _check_dmesg()
3099 {
3100         if [ ! -f ${RESULT_DIR}/check_dmesg ]; then
3101                 return 0
3102         fi
3103         rm -f ${RESULT_DIR}/check_dmesg
3104
3105         # default filter is a simple cat command, caller could provide a
3106         # customized filter and pass the name through the first argument, to
3107         # filter out intentional WARNINGs or Oopses
3108         filter=${1:-cat}
3109
3110         # search the dmesg log of last run of $seqnum for possible failures
3111         # use sed \cregexpc address type, since $seqnum contains "/"
3112         dmesg | tac | sed -ne "0,\#run fstests $seqnum at $date_time#p" | \
3113                 tac | $filter >$seqres.dmesg
3114         grep -q -e "kernel BUG at" \
3115              -e "WARNING:" \
3116              -e "BUG:" \
3117              -e "Oops:" \
3118              -e "possible recursive locking detected" \
3119              -e "Internal error" \
3120              -e "INFO: suspicious RCU usage" \
3121              -e "INFO: possible circular locking dependency detected" \
3122              -e "general protection fault:" \
3123              $seqres.dmesg
3124         if [ $? -eq 0 ]; then
3125                 echo "_check_dmesg: something found in dmesg (see $seqres.dmesg)"
3126                 return 1
3127         else
3128                 rm -f $seqres.dmesg
3129                 return 0
3130         fi
3131 }
3132
3133 # don't check dmesg log after test
3134 _disable_dmesg_check()
3135 {
3136         rm -f ${RESULT_DIR}/check_dmesg
3137 }
3138
3139 init_rc()
3140 {
3141         if [ "$iam" == new ]
3142         then
3143                 return
3144         fi
3145         # make some further configuration checks here
3146         if [ "$TEST_DEV" = ""  ]
3147         then
3148                 echo "common/rc: Error: \$TEST_DEV is not set"
3149                 exit 1
3150         fi
3151
3152         # if $TEST_DEV is not mounted, mount it now as XFS
3153         if [ -z "`_fs_type $TEST_DEV`" ]
3154         then
3155                 # $TEST_DEV is not mounted
3156                 if ! _test_mount
3157                 then
3158                         echo "common/rc: retrying test device mount with external set"
3159                         [ "$USE_EXTERNAL" != "yes" ] && export USE_EXTERNAL=yes
3160                         if ! _test_mount
3161                         then
3162                                 echo "common/rc: could not mount $TEST_DEV on $TEST_DIR"
3163                                 exit 1
3164                         fi
3165                 fi
3166         fi
3167
3168         # Sanity check that TEST partition is not mounted at another mount point
3169         # or as another fs type
3170         _check_mounted_on TEST_DEV $TEST_DEV TEST_DIR $TEST_DIR $FSTYP || exit 1
3171         if [ -n "$SCRATCH_DEV" ]; then
3172                 # Sanity check that SCRATCH partition is not mounted at another
3173                 # mount point, because it is about to be unmounted and formatted.
3174                 # Another fs type for scratch is fine (bye bye old fs type).
3175                 _check_mounted_on SCRATCH_DEV $SCRATCH_DEV SCRATCH_MNT $SCRATCH_MNT
3176                 [ $? -le 1 ] || exit 1
3177         fi
3178
3179         # Figure out if we need to add -F ("foreign", deprecated) option to xfs_io
3180         $XFS_IO_PROG -c stat $TEST_DIR 2>&1 | grep -q "is not on an XFS filesystem" && \
3181                 export XFS_IO_PROG="$XFS_IO_PROG -F"
3182
3183         # xfs_io -i option starts an idle thread for xfs_io.
3184         # With single threaded process, the file table is not shared
3185         # and file structs are not reference counted.
3186         # Spawning an idle thread can help detecting file struct
3187         # reference leaks, so we want to enable the option whenever
3188         # it is supported.
3189         $XFS_IO_PROG -i -c quit 2>/dev/null && \
3190                 export XFS_IO_PROG="$XFS_IO_PROG -i"
3191
3192         # xfs_copy on v5 filesystems do not require the "-d" option if xfs_db
3193         # can change the UUID on v5 filesystems
3194         if [ "$FSTYP" == "xfs" ]; then
3195                 touch /tmp/$$.img
3196                 $MKFS_XFS_PROG -d file,name=/tmp/$$.img,size=512m >/dev/null 2>&1
3197                 # xfs_db will return 0 even if it can't generate a new uuid, so
3198                 # check the output to make sure if it can change UUID of V5 xfs
3199                 $XFS_DB_PROG -x -c "uuid generate" /tmp/$$.img \
3200                         | grep -q "invalid UUID\|supported on V5 fs" \
3201                         && export XFS_COPY_PROG="$XFS_COPY_PROG -d"
3202                 rm -f /tmp/$$.img
3203         fi
3204 }
3205
3206 # get real device path name by following link
3207 _real_dev()
3208 {
3209         local _dev=$1
3210         if [ -b "$_dev" ] && [ -L "$_dev" ]; then
3211                 _dev=`readlink -f "$_dev"`
3212         fi
3213         echo $_dev
3214 }
3215
3216 # basename of a device
3217 _short_dev()
3218 {
3219         echo `basename $(_real_dev $1)`
3220 }
3221
3222 _sysfs_dev()
3223 {
3224         local _dev=`_real_dev $1`
3225         local _maj=$(stat -c%t $_dev | tr [:lower:] [:upper:])
3226         local _min=$(stat -c%T $_dev | tr [:lower:] [:upper:])
3227         _maj=$(echo "ibase=16; $_maj" | bc)
3228         _min=$(echo "ibase=16; $_min" | bc)
3229         echo /sys/dev/block/$_maj:$_min
3230 }
3231
3232 # Get the minimum block size of a file.  Usually this is the
3233 # minimum fs block size, but some filesystems (ocfs2) do block
3234 # mappings in larger units.
3235 _get_file_block_size()
3236 {
3237         if [ -z $1 ] || [ ! -d $1 ]; then
3238                 echo "Missing mount point argument for _get_file_block_size"
3239                 exit 1
3240         fi
3241         if [ "$FSTYP" = "ocfs2" ]; then
3242                 stat -c '%o' $1
3243         else
3244                 _get_block_size $1
3245         fi
3246 }
3247
3248 # Get the minimum block size of an fs.
3249 _get_block_size()
3250 {
3251         if [ -z $1 ] || [ ! -d $1 ]; then
3252                 echo "Missing mount point argument for _get_block_size"
3253                 exit 1
3254         fi
3255         stat -f -c %S $1
3256 }
3257
3258 get_page_size()
3259 {
3260         echo $(getconf PAGE_SIZE)
3261 }
3262
3263
3264 run_fsx()
3265 {
3266         echo fsx $@
3267         args=`echo $@ | sed -e "s/ BSIZE / $bsize /g" -e "s/ PSIZE / $psize /g"`
3268         set -- $here/ltp/fsx $args $FSX_AVOID $TEST_DIR/junk
3269         echo "$@" >>$seqres.full
3270         rm -f $TEST_DIR/junk
3271         "$@" 2>&1 | tee -a $seqres.full >$tmp.fsx
3272         if [ ${PIPESTATUS[0]} -ne 0 ]; then
3273                 cat $tmp.fsx
3274                 exit 1
3275         fi
3276 }
3277
3278 # Test for the existence of a sysfs entry at /sys/fs/$FSTYP/DEV/$ATTR
3279 #
3280 # Only one argument is needed:
3281 #  - attr: path name under /sys/fs/$FSTYP/DEV
3282 #
3283 # Usage example:
3284 #   _require_fs_sysfs error/fail_at_unmount
3285 _require_fs_sysfs()
3286 {
3287         local attr=$1
3288         local dname=$(_short_dev $TEST_DEV)
3289
3290         if [ -z "$attr" -o -z "$dname" ];then
3291                 _fail "Usage: _require_fs_sysfs <sysfs_attr_path>"
3292         fi
3293
3294         if [ ! -e /sys/fs/${FSTYP}/${dname}/${attr} ];then
3295                 _notrun "This test requires /sys/fs/${FSTYP}/${dname}/${attr}"
3296         fi
3297 }
3298
3299 # Write "content" into /sys/fs/$FSTYP/$DEV/$ATTR
3300 #
3301 # All arguments are necessary, and in this order:
3302 #  - dev: device name, e.g. $SCRATCH_DEV
3303 #  - attr: path name under /sys/fs/$FSTYP/$dev
3304 #  - content: the content of $attr
3305 #
3306 # Usage example:
3307 #   _set_fs_sysfs_attr /dev/mapper/scratch-dev error/fail_at_unmount 0
3308 _set_fs_sysfs_attr()
3309 {
3310         local dev=$1
3311         shift
3312         local attr=$1
3313         shift
3314         local content="$*"
3315
3316         if [ ! -b "$dev" -o -z "$attr" -o -z "$content" ];then
3317                 _fail "Usage: _set_fs_sysfs_attr <mounted_device> <attr> <content>"
3318         fi
3319
3320         local dname=$(_short_dev $dev)
3321         echo "$content" > /sys/fs/${FSTYP}/${dname}/${attr}
3322 }
3323
3324 # Print the content of /sys/fs/$FSTYP/$DEV/$ATTR
3325 #
3326 # All arguments are necessary, and in this order:
3327 #  - dev: device name, e.g. $SCRATCH_DEV
3328 #  - attr: path name under /sys/fs/$FSTYP/$dev
3329 #
3330 # Usage example:
3331 #   _get_fs_sysfs_attr /dev/mapper/scratch-dev error/fail_at_unmount
3332 _get_fs_sysfs_attr()
3333 {
3334         local dev=$1
3335         local attr=$2
3336
3337         if [ ! -b "$dev" -o -z "$attr" ];then
3338                 _fail "Usage: _get_fs_sysfs_attr <mounted_device> <attr>"
3339         fi
3340
3341         local dname=$(_short_dev $dev)
3342         cat /sys/fs/${FSTYP}/${dname}/${attr}
3343 }
3344
3345
3346
3347 init_rc
3348
3349 ################################################################################
3350 # make sure this script returns success
3351 /bin/true