common: fix "utility required warning" with empty utility name
[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 _require_math()
26 {
27         if [ -z "$BC" ]; then
28                 _notrun "this test requires 'bc' tool for doing math operations"
29         fi
30 }
31
32 _math()
33 {
34         [ $# -le 0 ] && return
35         if [ "$BC" ]; then
36                 result=$(LANG=C echo "scale=0; $@" | "$BC" -q 2> /dev/null)
37         else
38                 _notrun "this test requires 'bc' tool for doing math operations"
39         fi
40         echo "$result"
41 }
42
43 dd()
44 {
45    if [ "$HOSTOS" == "Linux" ]
46    then 
47         command dd --help 2>&1 | grep noxfer >/dev/null
48         
49         if [ "$?" -eq 0 ]
50             then
51                 command dd status=noxfer $@
52             else
53                 command dd $@
54         fi
55    else
56         command dd $@
57    fi
58 }
59
60 _btrfs_get_subvolid()
61 {
62         mnt=$1
63         name=$2
64
65         $BTRFS_UTIL_PROG sub list $mnt | grep $name | awk '{ print $2 }'
66 }
67
68 # Prints the md5 checksum of a given file
69 _md5_checksum()
70 {
71         md5sum $1 | cut -d ' ' -f1
72 }
73
74
75 # ls -l w/ selinux sometimes puts a dot at the end:
76 # -rwxrw-r--. id1 id2 file1
77 # Also filter out lost+found directory on extN file system if present
78
79 _ls_l()
80 {
81         ls -l $* | sed "s/\(^[-rwxdlbcpsStT]*\)\. /\1 /" | grep -v 'lost+found'
82 }
83
84 # we need common/config
85 if [ "$iam" != "check" ]
86 then
87     if ! . ./common/config
88         then
89         echo "$iam: failed to source common/config"
90         exit 1
91     fi
92 fi
93
94 # check for correct setup
95 case "$FSTYP" in
96     xfs)
97          [ "$XFS_LOGPRINT_PROG" = "" ] && _fatal "xfs_logprint not found"
98          [ "$XFS_REPAIR_PROG" = "" ] && _fatal "xfs_repair not found"
99          [ "$XFS_DB_PROG" = "" ] && _fatal "xfs_db not found"
100          [ "$MKFS_XFS_PROG" = "" ] && _fatal "mkfs_xfs not found"
101          ;;
102     udf)
103          [ "$MKFS_UDF_PROG" = "" ] && _fatal "mkfs_udf/mkudffs not found"
104          ;;
105     btrfs)
106          [ "$MKFS_BTRFS_PROG" = "" ] && _fatal "mkfs.btrfs not found"
107          ;;
108     ext4)
109          [ "$MKFS_EXT4_PROG" = "" ] && _fatal "mkfs.ext4 not found"
110          ;;
111     f2fs)
112          [ "$MKFS_F2FS_PROG" = "" ] && _fatal "mkfs.f2fs not found"
113          ;;
114     nfs)
115          ;;
116     cifs)
117          ;;
118     reiser4)
119          [ "$MKFS_REISER4_PROG" = "" ] && _fatal "mkfs.reiser4 not found"
120          ;;
121 esac
122
123 # make sure we have a standard umask
124 umask 022
125
126 _mount()
127 {
128     $MOUNT_PROG `_mount_ops_filter $*`
129 }
130
131 _scratch_options()
132 {
133     type=$1
134     SCRATCH_OPTIONS=""
135
136     if [ "$FSTYP" != "xfs" ]; then
137         return
138     fi
139
140     case $type in
141     mkfs)
142         [ "$HOSTOS" != "IRIX" ] && SCRATCH_OPTIONS="$SCRATCH_OPTIONS -f"
143         rt_opt="-r"
144         log_opt="-l"
145         ;;
146     mount)
147         rt_opt="-o"
148         log_opt="-o"
149         ;;
150     esac
151     [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_RTDEV" ] && \
152         SCRATCH_OPTIONS="$SCRATCH_OPTIONS ${rt_opt}rtdev=$SCRATCH_RTDEV"
153     [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_LOGDEV" ] && \
154         SCRATCH_OPTIONS="$SCRATCH_OPTIONS ${log_opt}logdev=$SCRATCH_LOGDEV"
155 }
156
157 _test_options()
158 {
159     type=$1
160     TEST_OPTIONS=""
161
162     if [ "$FSTYP" != "xfs" ]; then
163         return
164     fi
165
166     case $type in
167     mkfs)
168         rt_opt="-r"
169         log_opt="-l"
170         ;;
171     mount)
172         rt_opt="-o"
173         log_opt="-o"
174         ;;
175     esac
176     [ "$USE_EXTERNAL" = yes -a ! -z "$TEST_RTDEV" ] && \
177         TEST_OPTIONS="$TEST_OPTIONS ${rt_opt}rtdev=$TEST_RTDEV"
178     [ "$USE_EXTERNAL" = yes -a ! -z "$TEST_LOGDEV" ] && \
179         TEST_OPTIONS="$TEST_OPTIONS ${log_opt}logdev=$TEST_LOGDEV"
180 }
181
182 _mount_ops_filter()
183 {
184     params="$*"
185     
186     #get mount point to handle dmapi mtpt option correctly
187     let last_index=$#-1
188     [ $last_index -gt 0 ] && shift $last_index
189     FS_ESCAPED=$1
190     
191     # irix is fussy about how it is fed its mount options
192     # - multiple -o's are not allowed
193     # - no spaces between comma delimitered options
194     # the sed script replaces all -o's (except the first) with a comma
195     # not required for linux, but won't hurt
196     
197     echo $params | sed -e 's/[[:space:]]\+-o[[:space:]]*/UnIqUe/1; s/[[:space:]]\+-o[[:space:]]*/,/g; s/UnIqUe/ -o /1' \
198         | sed -e 's/dmapi/dmi/' \
199         | $PERL_PROG -ne "s#mtpt=[^,|^\n|^\s]*#mtpt=$FS_ESCAPED\1\2#; print;"
200
201 }
202
203 _scratch_mount_options()
204 {
205     _scratch_options mount
206
207     echo $SCRATCH_OPTIONS $MOUNT_OPTIONS $SELINUX_MOUNT_OPTIONS $* $SCRATCH_DEV $SCRATCH_MNT
208 }
209
210 _scratch_mount()
211 {
212     _mount -t $FSTYP `_scratch_mount_options $*`
213 }
214
215 _scratch_unmount()
216 {
217     $UMOUNT_PROG $SCRATCH_DEV
218 }
219
220 _scratch_remount()
221 {
222     _scratch_unmount
223     _scratch_mount
224 }
225
226 _test_mount()
227 {
228     _test_options mount
229     _mount -t $FSTYP $TEST_OPTIONS $TEST_FS_MOUNT_OPTS $SELINUX_MOUNT_OPTIONS $* $TEST_DEV $TEST_DIR
230 }
231
232 _test_remount()
233 {
234     $UMOUNT_PROG $TEST_DEV
235     _test_mount
236 }
237
238 _scratch_mkfs_options()
239 {
240     _scratch_options mkfs
241     echo $SCRATCH_OPTIONS $MKFS_OPTIONS $* $SCRATCH_DEV
242 }
243
244 _scratch_metadump()
245 {
246         dumpfile=$1
247         options=
248
249         [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_LOGDEV" ] && \
250                 options="-l $SCRATCH_LOGDEV"
251
252         xfs_metadump $options $SCRATCH_DEV $dumpfile
253 }
254
255 _setup_large_xfs_fs()
256 {
257         fs_size=$1
258         local tmp_dir=/tmp/
259
260         [ "$LARGE_SCRATCH_DEV" != yes ] && return 0
261         [ -z "$SCRATCH_DEV_EMPTY_SPACE" ] && SCRATCH_DEV_EMPTY_SPACE=0
262         [ $SCRATCH_DEV_EMPTY_SPACE -ge $fs_size ] && return 0
263
264         # calculate the size of the file we need to allocate.
265         # Default free space in the FS is 50GB, but you can specify more via
266         # SCRATCH_DEV_EMPTY_SPACE
267         file_size=$(($fs_size - 50*1024*1024*1024))
268         file_size=$(($file_size - $SCRATCH_DEV_EMPTY_SPACE))
269
270         # mount the filesystem, create the file, unmount it
271         _scratch_mount 2>&1 >$tmp_dir/mnt.err
272         local status=$?
273         if [ $status -ne 0 ]; then
274                 echo "mount failed"
275                 cat $tmp_dir/mnt.err >&2
276                 rm -f $tmp_dir/mnt.err
277                 return $status
278         fi
279         rm -f $tmp_dir/mnt.err
280
281         xfs_io -F -f \
282                 -c "truncate $file_size" \
283                 -c "falloc -k 0 $file_size" \
284                 -c "chattr +d" \
285                 $SCRATCH_MNT/.use_space 2>&1 > /dev/null
286         export NUM_SPACE_FILES=1
287         status=$?
288         umount $SCRATCH_MNT
289         if [ $status -ne 0 ]; then
290                 echo "large file prealloc failed"
291                 cat $tmp_dir/mnt.err >&2
292                 return $status
293         fi
294         return 0
295 }
296
297 _scratch_mkfs_xfs_opts()
298 {
299         mkfs_opts=$*
300
301         _scratch_options mkfs
302
303         $MKFS_XFS_PROG $SCRATCH_OPTIONS $mkfs_opts $SCRATCH_DEV
304 }
305
306
307 _scratch_mkfs_xfs_supported()
308 {
309         mkfs_opts=$*
310
311         _scratch_options mkfs
312
313         $MKFS_XFS_PROG -N $MKFS_OPTIONS $SCRATCH_OPTIONS $mkfs_opts $SCRATCH_DEV
314 }
315
316 _scratch_mkfs_xfs()
317 {
318         # extra mkfs options can be added by tests
319         local extra_mkfs_options=$*
320
321         local tmp_dir=/tmp/
322
323         # save mkfs output in case conflict means we need to run again.
324         # only the output for the mkfs that applies should be shown
325         _scratch_mkfs_xfs_opts $MKFS_OPTIONS $extra_mkfs_options \
326                 2>$tmp_dir.mkfserr 1>$tmp_dir.mkfsstd
327         local mkfs_status=$?
328
329
330         # a mkfs failure may be caused by conflicts between
331         # $MKFS_OPTIONS and $extra_mkfs_options
332         if [ $mkfs_status -ne 0 -a ! -z "$extra_mkfs_options" ]; then
333                 (
334                 echo -n "** mkfs failed with extra mkfs options "
335                 echo "added to \"$MKFS_OPTIONS\" by test $seq **"
336                 echo -n "** attempting to mkfs using only test $seq "
337                 echo "options: $extra_mkfs_options **"
338                 ) >> $seqres.full
339
340                 # running mkfs again. overwrite previous mkfs output files
341                 _scratch_mkfs_xfs_opts $extra_mkfs_options \
342                         2>$tmp_dir.mkfserr 1>$tmp_dir.mkfsstd
343                 local mkfs_status=$?
344         fi
345
346         if [ $mkfs_status -eq 0 -a "$LARGE_SCRATCH_DEV" = yes ]; then
347                 # manually parse the mkfs output to get the fs size in bytes
348                 local fs_size
349                 fs_size=`cat $tmp_dir.mkfsstd | perl -ne '
350                         if (/^data\s+=\s+bsize=(\d+)\s+blocks=(\d+)/) {
351                                 my $size = $1 * $2;
352                                 print STDOUT "$size\n";
353                         }'`
354                 _setup_large_xfs_fs $fs_size
355                 mkfs_status=$?
356         fi
357
358         # output stored mkfs output
359         cat $tmp_dir.mkfserr >&2
360         cat $tmp_dir.mkfsstd
361         rm -f $tmp_dir.mkfserr $tmp_dir.mkfsstd
362
363         return $mkfs_status
364 }
365
366 # xfs_check script is planned to be deprecated. But, we want to
367 # be able to invoke "xfs_check" behavior in xfstests in order to
368 # maintain the current verification levels.
369 _xfs_check()
370 {
371     OPTS=" "
372     DBOPTS=" "
373     USAGE="Usage: xfs_check [-fsvV] [-l logdev] [-i ino]... [-b bno]... special"
374
375     while getopts "b:fi:l:stvV" c
376     do
377         case $c in
378             s) OPTS=$OPTS"-s ";;
379             t) OPTS=$OPTS"-t ";;
380             v) OPTS=$OPTS"-v ";;
381             i) OPTS=$OPTS"-i "$OPTARG" ";;
382             b) OPTS=$OPTS"-b "$OPTARG" ";;
383             f) DBOPTS=$DBOPTS" -f";;
384             l) DBOPTS=$DBOPTS" -l "$OPTARG" ";;
385             V) $XFS_DB_PROG -p xfs_check -V
386                 return $?
387                 ;;
388         esac
389     done
390     set -- extra $@
391     shift $OPTIND
392     case $# in
393         1)    ${XFS_DB_PROG}${DBOPTS} -F -i -p xfs_check -c "check$OPTS" $1
394                status=$?
395                ;;
396         2)    echo $USAGE 1>&1
397               status=2
398               ;;
399     esac
400     return $status
401 }
402
403 _setup_large_ext4_fs()
404 {
405         fs_size=$1
406         local tmp_dir=/tmp/
407
408         [ "$LARGE_SCRATCH_DEV" != yes ] && return 0
409         [ -z "$SCRATCH_DEV_EMPTY_SPACE" ] && SCRATCH_DEV_EMPTY_SPACE=0
410         [ $SCRATCH_DEV_EMPTY_SPACE -ge $fs_size ] && return 0
411
412         # Default free space in the FS is 50GB, but you can specify more via
413         # SCRATCH_DEV_EMPTY_SPACE
414         space_to_consume=$(($fs_size - 50*1024*1024*1024 - $SCRATCH_DEV_EMPTY_SPACE))
415
416         # mount the filesystem and create 16TB - 4KB files until we consume
417         # all the necessary space.
418         _scratch_mount 2>&1 >$tmp_dir/mnt.err
419         local status=$?
420         if [ $status -ne 0 ]; then
421                 echo "mount failed"
422                 cat $tmp_dir/mnt.err >&2
423                 rm -f $tmp_dir/mnt.err
424                 return $status
425         fi
426         rm -f $tmp_dir/mnt.err
427
428         file_size=$((16*1024*1024*1024*1024 - 4096))
429         nfiles=0
430         while [ $space_to_consume -gt $file_size ]; do
431
432                 xfs_io -F -f \
433                         -c "truncate $file_size" \
434                         -c "falloc -k 0 $file_size" \
435                         $SCRATCH_MNT/.use_space.$nfiles 2>&1
436                 status=$?
437                 if [ $status -ne 0 ]; then
438                         break;
439                 fi
440
441                 space_to_consume=$(( $space_to_consume - $file_size ))
442                 nfiles=$(($nfiles + 1))
443         done
444
445         # consume the remaining space.
446         if [ $space_to_consume -gt 0 ]; then
447                 xfs_io -F -f \
448                         -c "truncate $space_to_consume" \
449                         -c "falloc -k 0 $space_to_consume" \
450                         $SCRATCH_MNT/.use_space.$nfiles 2>&1
451                 status=$?
452         fi
453         export NUM_SPACE_FILES=$nfiles
454
455         umount $SCRATCH_MNT
456         if [ $status -ne 0 ]; then
457                 echo "large file prealloc failed"
458                 cat $tmp_dir/mnt.err >&2
459                 return $status
460         fi
461         return 0
462 }
463
464 _scratch_mkfs_ext4()
465 {
466         # extra mkfs options can be added by tests
467         local extra_mkfs_options=$*
468
469         local tmp_dir=/tmp/
470
471         $MKFS_EXT4_PROG -F $MKFS_OPTIONS $extra_mkfs_options $SCRATCH_DEV \
472                         2>$tmp_dir.mkfserr 1>$tmp_dir.mkfsstd
473         local mkfs_status=$?
474
475         # a mkfs failure may be caused by conflicts between
476         # $MKFS_OPTIONS and $extra_mkfs_options
477         if [ $mkfs_status -ne 0 -a ! -z "$extra_mkfs_options" ]; then
478                 (
479                 echo -n "** mkfs failed with extra mkfs options "
480                 echo "added to \"$MKFS_OPTIONS\" by test $seq **"
481                 echo -n "** attempting to mkfs using only test $seq "
482                 echo "options: $extra_mkfs_options **"
483                 ) >> $seqres.full
484
485                 # running mkfs again. overwrite previous mkfs output files
486                 $MKFS_EXT4_PROG -F $extra_mkfs_options $SCRATCH_DEV \
487                                 2>$tmp_dir.mkfserr 1>$tmp_dir.mkfsstd
488                 local mkfs_status=$?
489         fi
490
491         if [ $mkfs_status -eq 0 -a "$LARGE_SCRATCH_DEV" = yes ]; then
492                 # manually parse the mkfs output to get the fs size in bytes
493                 fs_size=`cat $tmp_dir.mkfsstd | awk ' \
494                         /^Block size/ { split($2, a, "="); bs = a[2] ; } \
495                         / inodes, / { blks = $3 } \
496                         /reserved for the super user/ { resv = $1 } \
497                         END { fssize = bs * blks - resv; print fssize }'`
498
499                 _setup_large_ext4_fs $fs_size
500                 mkfs_status=$?
501         fi
502
503         # output stored mkfs output
504         cat $tmp_dir.mkfserr >&2
505         cat $tmp_dir.mkfsstd
506         rm -f $tmp_dir.mkfserr $tmp_dir.mkfsstd
507
508         return $mkfs_status
509 }
510
511 _test_mkfs()
512 {
513     case $FSTYP in
514     nfs*)
515         # do nothing for nfs
516         ;;
517     cifs)
518         # do nothing for cifs
519         ;;
520     udf)
521         $MKFS_UDF_PROG $MKFS_OPTIONS $* $TEST_DEV > /dev/null
522         ;;
523     btrfs)
524         $MKFS_BTRFS_PROG $MKFS_OPTIONS $* $TEST_DEV > /dev/null
525         ;;
526     ext2|ext3|ext4)
527         $MKFS_PROG -t $FSTYP -- -F $MKFS_OPTIONS $* $TEST_DEV
528         ;;
529     *)
530         yes | $MKFS_PROG -t $FSTYP -- $MKFS_OPTIONS $* $TEST_DEV
531         ;;
532     esac
533 }
534
535 _mkfs_dev()
536 {
537     case $FSTYP in
538     nfs*)
539         # do nothing for nfs
540         ;;
541     udf)
542         $MKFS_UDF_PROG $MKFS_OPTIONS $* 2>$tmp_dir.mkfserr 1>$tmp_dir.mkfsstd
543         ;;
544     btrfs)
545         $MKFS_BTRFS_PROG $MKFS_OPTIONS $* 2>$tmp_dir.mkfserr 1>$tmp_dir.mkfsstd
546         ;;
547     ext2|ext3|ext4)
548         $MKFS_PROG -t $FSTYP -- -F $MKFS_OPTIONS $* \
549                 2>$tmp_dir.mkfserr 1>$tmp_dir.mkfsstd
550         ;;
551
552     *)
553         yes | $MKFS_PROG -t $FSTYP -- $MKFS_OPTIONS $* \
554                 2>$tmp_dir.mkfserr 1>$tmp_dir.mkfsstd
555         ;;
556     esac
557
558     if [ $? -ne 0 ]; then
559         # output stored mkfs output
560         cat $tmp_dir.mkfserr >&2
561         cat $tmp_dir.mkfsstd
562         status=1
563         exit 1
564     fi
565     rm -f $tmp_dir.mkfserr $tmp_dir.mkfsstd
566 }
567
568 # remove all files in $SCRATCH_MNT, useful when testing on NFS/CIFS
569 _scratch_cleanup_files()
570 {
571         _scratch_mount
572         rm -rf $SCRATCH_MNT/*
573         _scratch_unmount
574 }
575
576 _scratch_mkfs()
577 {
578     case $FSTYP in
579     xfs)
580         _scratch_mkfs_xfs $*
581         ;;
582     nfs*)
583         # unable to re-create NFS, just remove all files in $SCRATCH_MNT to
584         # avoid EEXIST caused by the leftover files created in previous runs
585         _scratch_cleanup_files
586         ;;
587     cifs)
588         # unable to re-create CIFS, just remove all files in $SCRATCH_MNT to
589         # avoid EEXIST caused by the leftover files created in previous runs
590         _scratch_cleanup_files
591         ;;
592     udf)
593         $MKFS_UDF_PROG $MKFS_OPTIONS $* $SCRATCH_DEV > /dev/null
594         ;;
595     btrfs)
596         $MKFS_BTRFS_PROG $MKFS_OPTIONS $* $SCRATCH_DEV > /dev/null
597         ;;
598     ext2|ext3)
599         $MKFS_PROG -t $FSTYP -- -F $MKFS_OPTIONS $* $SCRATCH_DEV
600         ;;
601     ext4)
602         _scratch_mkfs_ext4 $*
603         ;;
604     tmpfs)
605         # do nothing for tmpfs
606         ;;
607     f2fs)
608         $MKFS_F2FS_PROG $MKFS_OPTIONS $* $SCRATCH_DEV > /dev/null
609         ;;
610     *)
611         yes | $MKFS_PROG -t $FSTYP -- $MKFS_OPTIONS $* $SCRATCH_DEV
612         ;;
613     esac
614 }
615
616 _scratch_pool_mkfs()
617 {
618     case $FSTYP in
619     btrfs)
620         # if dup profile is in mkfs options call _scratch_mkfs instead
621         # because dup profile only works with single device
622         if [[ "$*" =~ dup ]]; then
623             _scratch_mkfs $*
624         else
625             $MKFS_BTRFS_PROG $MKFS_OPTIONS $* $SCRATCH_DEV_POOL > /dev/null
626         fi
627         ;;
628     *)
629         echo "_scratch_pool_mkfs is not implemented for $FSTYP" 1>&2
630         ;;
631     esac
632 }
633
634 # Create fs of certain size on scratch device
635 # _scratch_mkfs_sized <size in bytes> [optional blocksize]
636 _scratch_mkfs_sized()
637 {
638     fssize=$1
639     blocksize=$2
640
641     case $FSTYP in
642     xfs)
643         def_blksz=`echo $MKFS_OPTIONS|sed -rn 's/.*-b ?size= ?+([0-9]+).*/\1/p'`
644         ;;
645     ext2|ext3|ext4|ext4dev|udf|btrfs|reiser4)
646         def_blksz=`echo $MKFS_OPTIONS| sed -rn 's/.*-b ?+([0-9]+).*/\1/p'`
647         ;;
648     esac
649
650     [ -n "$def_blksz" ] && blocksize=$def_blksz
651     [ -z "$blocksize" ] && blocksize=4096
652
653
654     re='^[0-9]+$'
655     if ! [[ $fssize =~ $re ]] ; then
656         _notrun "error: _scratch_mkfs_sized: fs size \"$fssize\" not an integer."
657     fi
658     if ! [[ $blocksize =~ $re ]] ; then
659         _notrun "error: _scratch_mkfs_sized: block size \"$blocksize\" not an integer."
660     fi
661
662     blocks=`expr $fssize / $blocksize`
663
664     if [ "$HOSTOS" == "Linux" ]; then
665         devsize=`blockdev --getsize64 $SCRATCH_DEV`
666         [ "$fssize" -gt "$devsize" ] && _notrun "Scratch device too small"
667     fi
668
669     case $FSTYP in
670     xfs)
671         # don't override MKFS_OPTIONS that set a block size.
672         echo $MKFS_OPTIONS |egrep -q "b?size="
673         if [ $? -eq 0 ]; then
674                 _scratch_mkfs_xfs -d size=$fssize
675         else
676                 _scratch_mkfs_xfs -d size=$fssize -b size=$blocksize
677         fi
678         ;;
679     ext2|ext3|ext4|ext4dev)
680         ${MKFS_PROG}.$FSTYP -F $MKFS_OPTIONS -b $blocksize $SCRATCH_DEV $blocks
681         ;;
682     udf)
683         $MKFS_UDF_PROG $MKFS_OPTIONS -b $blocksize $SCRATCH_DEV $blocks
684         ;;
685     btrfs)
686         $MKFS_BTRFS_PROG $MKFS_OPTIONS -b $fssize $SCRATCH_DEV
687         ;;
688     reiser4)
689         # mkfs.resier4 requires size in KB as input for creating filesystem
690         $MKFS_REISER4_PROG $MKFS_OPTIONS -y -b $blocksize $SCRATCH_DEV \
691                            `expr $fssize / 1024`
692         ;;
693     *)
694         _notrun "Filesystem $FSTYP not supported in _scratch_mkfs_sized"
695         ;;
696     esac
697 }
698
699 # Emulate an N-data-disk stripe w/ various stripe units
700 # _scratch_mkfs_geom <sunit bytes> <swidth multiplier> [optional blocksize]
701 _scratch_mkfs_geom()
702 {
703     sunit_bytes=$1
704     swidth_mult=$2
705     blocksize=$3
706     [ -z "$blocksize" ] && blocksize=4096
707
708     let sunit_blocks=$sunit_bytes/$blocksize
709     let swidth_blocks=$sunit_blocks*$swidth_mult
710
711     case $FSTYP in
712     xfs)
713         MKFS_OPTIONS+=" -b size=$blocksize, -d su=$sunit_bytes,sw=$swidth_mult"
714         ;;
715     ext4|ext4dev)
716         MKFS_OPTIONS+=" -b $blocksize -E stride=$sunit_blocks,stripe_width=$swidth_blocks"
717         ;;
718     *)
719         _notrun "can't mkfs $FSTYP with geometry"
720         ;;
721     esac
722     _scratch_mkfs
723 }
724
725 _scratch_resvblks()
726 {
727         case $FSTYP in
728         xfs)
729                 xfs_io -x -c "resblks $1" $SCRATCH_MNT
730                 ;;
731         *)
732                 ;;
733         esac
734 }
735
736 _scratch_xfs_db_options()
737 {
738     SCRATCH_OPTIONS=""
739     [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_LOGDEV" ] && \
740         SCRATCH_OPTIONS="-l$SCRATCH_LOGDEV"
741     echo $SCRATCH_OPTIONS $* $SCRATCH_DEV
742 }
743
744 _scratch_xfs_logprint()
745 {
746     SCRATCH_OPTIONS=""
747     [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_LOGDEV" ] && \
748         SCRATCH_OPTIONS="-l$SCRATCH_LOGDEV"
749     $XFS_LOGPRINT_PROG $SCRATCH_OPTIONS $* $SCRATCH_DEV
750 }
751
752 _scratch_xfs_check()
753 {
754     SCRATCH_OPTIONS=""
755     [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_LOGDEV" ] && \
756         SCRATCH_OPTIONS="-l $SCRATCH_LOGDEV"
757     [ "$LARGE_SCRATCH_DEV" = yes ] && \
758         SCRATCH_OPTIONS=$SCRATCH_OPTIONS" -t"
759     _xfs_check $SCRATCH_OPTIONS $* $SCRATCH_DEV
760 }
761
762 _scratch_xfs_repair()
763 {
764     SCRATCH_OPTIONS=""
765     [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_LOGDEV" ] && \
766         SCRATCH_OPTIONS="-l$SCRATCH_LOGDEV"
767     [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_RTDEV" ] && \
768         SCRATCH_OPTIONS=$SCRATCH_OPTIONS" -r$SCRATCH_RTDEV"
769     [ "$LARGE_SCRATCH_DEV" = yes ] && SCRATCH_OPTIONS=$SCRATCH_OPTIONS" -t"
770     $XFS_REPAIR_PROG $SCRATCH_OPTIONS $* $SCRATCH_DEV
771 }
772
773 _get_pids_by_name()
774 {
775     if [ $# -ne 1 ]
776     then
777         echo "Usage: _get_pids_by_name process-name" 1>&2
778         exit 1
779     fi
780
781     # Algorithm ... all ps(1) variants have a time of the form MM:SS or
782     # HH:MM:SS before the psargs field, use this as the search anchor.
783     #
784     # Matches with $1 (process-name) occur if the first psarg is $1
785     # or ends in /$1 ... the matching uses sed's regular expressions,
786     # so passing a regex into $1 will work.
787
788     ps $PS_ALL_FLAGS \
789     | sed -n \
790         -e 's/$/ /' \
791         -e 's/[         ][      ]*/ /g' \
792         -e 's/^ //' \
793         -e 's/^[^ ]* //' \
794         -e "/[0-9]:[0-9][0-9]  *[^ ]*\/$1 /s/ .*//p" \
795         -e "/[0-9]:[0-9][0-9]  *$1 /s/ .*//p"
796 }
797
798 # fix malloc libs output
799 #
800 _fix_malloc()
801 {
802     # filter out the Electric Fence notice
803     $PERL_PROG -e '
804         while (<>) {
805             if (defined $o && /^\s+Electric Fence/) {
806                 chomp($o);
807                 print "$o";
808                 undef $o;
809                 next;
810             }
811             print $o if (defined $o);
812
813             $o=$_;
814         }
815         print $o if (defined $o);
816     '
817 }
818
819 # check if run as root
820 #
821 _need_to_be_root()
822 {
823     id=`id | $SED_PROG -e 's/(.*//' -e 's/.*=//'`
824     if [ "$id" -ne 0 ]
825     then
826         echo "Arrgh ... you need to be root (not uid=$id) to run this test"
827         exit 1
828     fi
829 }
830
831
832 #
833 # _df_device : get an IRIX style df line for a given device
834 #
835 #       - returns "" if not mounted
836 #       - returns fs type in field two (ala IRIX)
837 #       - joins line together if split by fancy df formatting
838 #       - strips header etc
839 #
840
841 _df_device()
842 {
843     if [ $# -ne 1 ]
844     then
845         echo "Usage: _df_device device" 1>&2
846         exit 1
847     fi
848
849     # Note that we use "==" here so awk doesn't try to interpret an NFS over
850     # IPv6 server as a regular expression.
851     $DF_PROG 2>/dev/null | $AWK_PROG -v what=$1 '
852         ($1==what) && (NF==1) {
853             v=$1
854             getline
855             print v, $0
856             exit
857         }
858         ($1==what) {
859             print
860             exit
861         }
862     '
863 }
864
865 #
866 # _df_dir : get an IRIX style df line for device where a directory resides
867 #
868 #       - returns fs type in field two (ala IRIX)
869 #       - joins line together if split by fancy df formatting
870 #       - strips header etc
871 #
872
873 _df_dir()
874 {
875     if [ $# -ne 1 ]
876     then
877         echo "Usage: _df_dir device" 1>&2
878         exit 1
879     fi
880
881     $DF_PROG $1 2>/dev/null | $AWK_PROG -v what=$1 '
882         NR == 2 && NF==1 {
883             v=$1
884             getline
885             print v, $0;
886             exit 0
887         }
888         NR == 2 {
889             print;
890             exit 0
891         }
892         {}
893     '
894     # otherwise, nada
895 }
896
897 # return percentage used disk space for mounted device
898
899 _used()
900 {
901     if [ $# -ne 1 ]
902     then
903         echo "Usage: _used device" 1>&2
904         exit 1
905     fi
906
907     _df_device $1 | $AWK_PROG '{ sub("%", "") ; print $6 }'
908 }
909
910 # return the FS type of a mounted device
911 #
912 _fs_type()
913 {
914     if [ $# -ne 1 ]
915     then
916         echo "Usage: _fs_type device" 1>&2
917         exit 1
918     fi
919
920     #
921     # The Linux kernel shows NFSv4 filesystems in df output as
922     # filesystem type nfs4, although we mounted it as nfs earlier.
923     # Fix the filesystem type up here so that the callers don't
924     # have to bother with this quirk.
925     #
926     _df_device $1 | $AWK_PROG '{ print $2 }' | sed -e 's/nfs4/nfs/'
927 }
928
929 # return the FS mount options of a mounted device
930 #
931 # should write a version which just parses the output of mount for IRIX
932 # compatibility, but since this isn't used at all, at the moment I'll leave
933 # this for now
934 #
935 _fs_options()
936 {
937     if [ $# -ne 1 ]
938     then
939         echo "Usage: _fs_options device" 1>&2
940         exit 1
941     fi
942
943     $AWK_PROG -v dev=$1 '
944         match($1,dev) { print $4 }
945     ' </proc/mounts
946 }
947
948 # returns device number if a file is a block device
949 #
950 _is_block_dev()
951 {
952     if [ $# -ne 1 ]
953     then
954         echo "Usage: _is_block_dev dev" 1>&2
955         exit 1
956     fi
957
958     _dev=$1
959     if [ -L "${_dev}" ]; then
960         _dev=`readlink -f ${_dev}`
961     fi
962
963     if [ -b "${_dev}" ]; then
964         src/lstat64 ${_dev} | $AWK_PROG '/Device type:/ { print $9 }'
965     fi
966 }
967
968 # Do a command, log it to $seqres.full, optionally test return status
969 # and die if command fails. If called with one argument _do executes the
970 # command, logs it, and returns its exit status. With two arguments _do
971 # first prints the message passed in the first argument, and then "done"
972 # or "fail" depending on the return status of the command passed in the
973 # second argument. If the command fails and the variable _do_die_on_error
974 # is set to "always" or the two argument form is used and _do_die_on_error
975 # is set to "message_only" _do will print an error message to
976 # $seqres.out and exit.
977
978 _do()
979 {
980     if [ $# -eq 1 ]; then
981         _cmd=$1
982     elif [ $# -eq 2 ]; then
983         _note=$1
984         _cmd=$2
985         echo -n "$_note... "
986     else
987         echo "Usage: _do [note] cmd" 1>&2
988         status=1; exit
989     fi
990
991     (eval "echo '---' \"$_cmd\"") >>$seqres.full
992     (eval "$_cmd") >$tmp._out 2>&1; ret=$?
993     cat $tmp._out | _fix_malloc >>$seqres.full
994     if [ $# -eq 2 ]; then
995         if [ $ret -eq 0 ]; then
996             echo "done"
997         else
998             echo "fail"
999         fi
1000     fi
1001     if [ $ret -ne 0  ] \
1002         && [ "$_do_die_on_error" = "always" \
1003             -o \( $# -eq 2 -a "$_do_die_on_error" = "message_only" \) ]
1004     then
1005         [ $# -ne 2 ] && echo
1006         eval "echo \"$_cmd\" failed \(returned $ret\): see $seqres.full"
1007         status=1; exit
1008     fi
1009
1010     return $ret
1011 }
1012
1013 # bail out, setting up .notrun file. Need to kill the filesystem check files
1014 # here, otherwise they are set incorrectly for the next test.
1015 #
1016 _notrun()
1017 {
1018     echo "$*" > $seqres.notrun
1019     echo "$seq not run: $*"
1020     rm -f ${RESULT_DIR}/require_test
1021     rm -f ${RESULT_DIR}/require_scratch
1022     status=0
1023     exit
1024 }
1025
1026 # just plain bail out
1027 #
1028 _fail()
1029 {
1030     echo "$*" | tee -a $seqres.full
1031     echo "(see $seqres.full for details)"
1032     status=1
1033     exit 1
1034 }
1035
1036 # tests whether $FSTYP is one of the supported filesystems for a test
1037 #
1038 _supported_fs()
1039 {
1040     for f
1041     do
1042         if [ "$f" = "$FSTYP" -o "$f" = "generic" ]
1043         then
1044             return
1045         fi
1046     done
1047
1048     _notrun "not suitable for this filesystem type: $FSTYP"
1049 }
1050
1051
1052 # tests whether $FSTYP is one of the supported OSes for a test
1053 #
1054 _supported_os()
1055 {
1056     for h
1057     do
1058         if [ "$h" = "$HOSTOS" ]
1059         then
1060             return
1061         fi
1062     done
1063
1064     _notrun "not suitable for this OS: $HOSTOS"
1065 }
1066
1067 # this test needs a scratch partition - check we're ok & unmount it
1068 # No post-test check of the device is required. e.g. the test intentionally
1069 # finishes the test with the filesystem in a corrupt state
1070 _require_scratch_nocheck()
1071 {
1072     case "$FSTYP" in
1073         nfs*)
1074                 echo $SCRATCH_DEV | grep -q ":/" > /dev/null 2>&1
1075                 if [ -z "$SCRATCH_DEV" -o "$?" != "0" ]; then
1076                         _notrun "this test requires a valid \$SCRATCH_DEV"
1077                 fi
1078                 if [ ! -d "$SCRATCH_MNT" ]; then
1079                         _notrun "this test requires a valid \$SCRATCH_MNT"
1080                 fi
1081                 ;;
1082         cifs)
1083                 echo $SCRATCH_DEV | grep -q "//" > /dev/null 2>&1
1084                 if [ -z "$SCRATCH_DEV" -o "$?" != "0" ]; then
1085                         _notrun "this test requires a valid \$SCRATCH_DEV"
1086                 fi
1087                 if [ ! -d "$SCRATCH_MNT" ]; then
1088                      _notrun "this test requires a valid \$SCRATCH_MNT"
1089                 fi
1090                 ;;
1091         tmpfs)
1092                 if [ -z "$SCRATCH_DEV" -o ! -d "$SCRATCH_MNT" ];
1093                 then
1094                     _notrun "this test requires a valid \$SCRATCH_MNT and unique $SCRATCH_DEV"
1095                 fi
1096                 ;;
1097         *)
1098                  if [ -z "$SCRATCH_DEV" -o "`_is_block_dev $SCRATCH_DEV`" = "" ]
1099                  then
1100                      _notrun "this test requires a valid \$SCRATCH_DEV"
1101                  fi
1102                  if [ "`_is_block_dev $SCRATCH_DEV`" = "`_is_block_dev $TEST_DEV`" ]
1103                  then
1104                      _notrun "this test requires a valid \$SCRATCH_DEV"
1105                  fi
1106                 if [ ! -d "$SCRATCH_MNT" ]
1107                 then
1108                      _notrun "this test requires a valid \$SCRATCH_MNT"
1109                 fi
1110                  ;;
1111     esac
1112
1113     # mounted?
1114     if _mount | grep -q $SCRATCH_DEV
1115     then
1116         # if it's mounted, make sure its on $SCRATCH_MNT
1117         if ! _mount | grep $SCRATCH_DEV | grep -q $SCRATCH_MNT
1118         then
1119             echo "\$SCRATCH_DEV is mounted but not on \$SCRATCH_MNT - aborting"
1120             exit 1
1121         fi
1122         # and then unmount it
1123         if ! $UMOUNT_PROG $SCRATCH_DEV
1124         then
1125             echo "failed to unmount $SCRATCH_DEV"
1126             exit 1
1127         fi
1128     fi
1129     rm -f ${RESULT_DIR}/require_scratch
1130 }
1131
1132 # we need the scratch device and it should be checked post test.
1133 _require_scratch()
1134 {
1135         _require_scratch_nocheck
1136         touch ${RESULT_DIR}/require_scratch
1137 }
1138
1139
1140 # this test needs a test partition - check we're ok & mount it
1141 #
1142 _require_test()
1143 {
1144     case "$FSTYP" in
1145         nfs*)
1146                 echo $TEST_DEV | grep -q ":/" > /dev/null 2>&1
1147                 if [ -z "$TEST_DEV" -o "$?" != "0" ]; then
1148                         _notrun "this test requires a valid \$TEST_DIR"
1149                 fi
1150                 if [ ! -d "$TEST_DIR" ]; then
1151                         _notrun "this test requires a valid \$TEST_DIR"
1152                 fi
1153                 ;;
1154         cifs)
1155                 echo $TEST_DEV | grep -q "//" > /dev/null 2>&1
1156                 if [ -z "$TEST_DEV" -o "$?" != "0" ]; then
1157                         _notrun "this test requires a valid \$TEST_DEV"
1158                 fi
1159                 if [ ! -d "$TEST_DIR" ]; then
1160                      _notrun "this test requires a valid \$TEST_DIR"
1161                 fi
1162                 ;;
1163         tmpfs)
1164                 if [ -z "$TEST_DEV" -o ! -d "$TEST_DIR" ];
1165                 then
1166                     _notrun "this test requires a valid \$TEST_DIR and unique $TEST_DEV"
1167                 fi
1168                 ;;
1169         *)
1170                  if [ -z "$TEST_DEV" -o "`_is_block_dev $TEST_DEV`" = "" ]
1171                  then
1172                      _notrun "this test requires a valid \$TEST_DEV"
1173                  fi
1174                  if [ "`_is_block_dev $SCRATCH_DEV`" = "`_is_block_dev $TEST_DEV`" ]
1175                  then
1176                      _notrun "this test requires a valid \$TEST_DEV"
1177                  fi
1178                 if [ ! -d "$TEST_DIR" ]
1179                 then
1180                      _notrun "this test requires a valid \$TEST_DIR"
1181                 fi
1182                  ;;
1183     esac
1184
1185     # mounted?
1186     # Note that we use -F here so grep doesn't try to interpret an NFS over
1187     # IPv6 server as a regular expression.
1188     if _mount | grep -F -q $TEST_DEV
1189     then
1190         # if it's mounted, make sure its on $TEST_DIR
1191         if ! _mount | grep -F $TEST_DEV | grep -q $TEST_DIR
1192         then
1193             echo "\$TEST_DEV is mounted but not on \$TEST_DIR - aborting"
1194             exit 1
1195         fi
1196     else
1197         out=`_mount_or_remount_rw "$MOUNT_OPTIONS" $TEST_DEV $TEST_DIR`
1198         if [ $? -ne 1 ]; then
1199                 echo $out
1200                 exit 1
1201         fi
1202     fi
1203     touch ${RESULT_DIR}/require_test
1204 }
1205
1206 # this test needs a logdev
1207 #
1208 _require_logdev()
1209 {
1210     [ -z "$SCRATCH_LOGDEV" -o ! -b "$SCRATCH_LOGDEV" ] && \
1211         _notrun "This test requires a valid \$SCRATCH_LOGDEV"
1212     [ "$USE_EXTERNAL" != yes ] && \
1213         _notrun "This test requires USE_EXTERNAL to be enabled"
1214
1215     # ensure its not mounted
1216     $UMOUNT_PROG $SCRATCH_LOGDEV 2>/dev/null
1217 }
1218
1219 # this test requires loopback device support
1220 #
1221 _require_loop()
1222 {
1223     if [ "$HOSTOS" != "Linux" ]
1224     then
1225         _notrun "This test requires linux for loopback device support"
1226     fi
1227
1228     modprobe loop >/dev/null 2>&1
1229     if grep loop /proc/devices >/dev/null 2>&1
1230     then
1231         :
1232     else
1233         _notrun "This test requires loopback device support"
1234     fi
1235 }
1236
1237 # this test requires ext2 filesystem support
1238 #
1239 _require_ext2()
1240 {
1241     if [ "$HOSTOS" != "Linux" ]
1242     then
1243         _notrun "This test requires linux for ext2 filesystem support"
1244     fi
1245
1246     modprobe ext2 >/dev/null 2>&1
1247     if grep ext2 /proc/filesystems >/dev/null 2>&1
1248     then
1249         :
1250     else
1251         _notrun "This test requires ext2 filesystem support"
1252     fi
1253 }
1254
1255 # this test requires that (large) loopback device files are not in use
1256 #
1257 _require_no_large_scratch_dev()
1258 {
1259     [ "$LARGE_SCRATCH_DEV" = yes ] && \
1260         _notrun "Large filesystem testing in progress, skipped this test"
1261 }
1262
1263 # this test requires that a realtime subvolume is in use, and
1264 # that the kernel supports realtime as well.
1265 #
1266 _require_realtime()
1267 {
1268     [ "$USE_EXTERNAL" = yes ] || \
1269         _notrun "External volumes not in use, skipped this test"
1270     [ "$SCRATCH_RTDEV" = "" ] && \
1271         _notrun "Realtime device required, skipped this test"
1272 }
1273
1274 # this test requires that a specified command (executable) exists
1275 # $1 - command, $2 - name for error message
1276 #
1277 _require_command()
1278 {
1279     [ -n "$1" ] && _cmd="$1" || _cmd="$2"
1280     [ -n "$1" -a -x "$1" ] || _notrun "$_cmd utility required, skipped this test"
1281 }
1282
1283 # this test requires the device to be valid block device
1284 # $1 - device
1285 _require_block_device()
1286 {
1287         if [ -z "$1" ]; then
1288                 echo "Usage: _require_block_device <dev>" 1>&2
1289                 exit 1
1290         fi
1291         if [ "`_is_block_dev "$1"`" == "" ]; then
1292                 _notrun "require $1 to be valid block disk"
1293         fi
1294 }
1295
1296 # this test requires the device mapper flakey target
1297 #
1298 _require_dm_flakey()
1299 {
1300     # require SCRATCH_DEV to be a valid block device
1301     _require_block_device $SCRATCH_DEV
1302     _require_command "$DMSETUP_PROG" dmsetup
1303
1304     modprobe dm-flakey >/dev/null 2>&1
1305     $DMSETUP_PROG targets | grep flakey >/dev/null 2>&1
1306     if [ $? -eq 0 ]
1307     then
1308         :
1309     else
1310         _notrun "This test requires dm flakey support"
1311     fi
1312 }
1313
1314 # this test requires the projid32bit feature to be available in mkfs.xfs.
1315 #
1316 _require_projid32bit()
1317 {
1318        _scratch_mkfs_xfs_supported -i projid32bit=1 >/dev/null 2>&1 \
1319            || _notrun "mkfs.xfs doesn't have projid32bit feature"
1320 }
1321
1322 _require_projid16bit()
1323 {
1324         _scratch_mkfs_xfs_supported -i projid32bit=0 >/dev/null 2>&1 \
1325            || _notrun "16 bit project IDs not supported on $SCRATCH_DEV"
1326 }
1327
1328 # this test requires the crc feature to be available in mkfs.xfs
1329 #
1330 _require_xfs_mkfs_crc()
1331 {
1332         _scratch_mkfs_xfs_supported -m crc=1 >/dev/null 2>&1 \
1333            || _notrun "mkfs.xfs doesn't have crc feature"
1334 }
1335
1336 # this test requires the xfs kernel support crc feature
1337 #
1338 _require_xfs_crc()
1339 {
1340         _scratch_mkfs_xfs -m crc=1 >/dev/null 2>&1
1341         _scratch_mount >/dev/null 2>&1 \
1342            || _notrun "Kernel doesn't support crc feature"
1343         umount $SCRATCH_MNT
1344 }
1345
1346 # this test requires the bigalloc feature to be available in mkfs.ext4
1347 #
1348 _require_ext4_mkfs_bigalloc()
1349 {
1350         $MKFS_EXT4_PROG -F -O bigalloc -n $SCRATCH_DEV 512m >/dev/null 2>&1 \
1351            || _notrun "mkfs.ext4 doesn't have bigalloc feature"
1352 }
1353
1354 # this test requires the ext4 kernel support bigalloc feature
1355 #
1356 _require_ext4_bigalloc()
1357 {
1358         $MKFS_EXT4_PROG -F -O bigalloc $SCRATCH_DEV 512m >/dev/null 2>&1
1359         _scratch_mount >/dev/null 2>&1 \
1360            || _notrun "Ext4 kernel doesn't support bigalloc feature"
1361         umount $SCRATCH_MNT
1362 }
1363
1364 # this test requires the finobt feature to be available in mkfs.xfs
1365 #
1366 _require_xfs_mkfs_finobt()
1367 {
1368         _scratch_mkfs_xfs_supported -m crc=1,finobt=1 >/dev/null 2>&1 \
1369            || _notrun "mkfs.xfs doesn't have finobt feature"
1370 }
1371
1372 # this test requires the xfs kernel support finobt feature
1373 #
1374 _require_xfs_finobt()
1375 {
1376         _scratch_mkfs_xfs -m crc=1,finobt=1 >/dev/null 2>&1
1377         _scratch_mount >/dev/null 2>&1 \
1378            || _notrun "Kernel doesn't support finobt feature"
1379         umount $SCRATCH_MNT
1380 }
1381
1382 # this test requires xfs sysfs attribute support
1383 #
1384 _require_xfs_sysfs()
1385 {
1386         attr=$1
1387         sysfsdir=/sys/fs/xfs
1388
1389         if [ ! -e $sysfsdir ]; then
1390                 _notrun "no kernel support for XFS sysfs attributes"
1391         fi
1392
1393         if [ ! -z $1 ] && [ ! -e $sysfsdir/$attr ]; then
1394                 _notrun "sysfs attribute '$attr' is not supported"
1395         fi
1396 }
1397
1398 # this test requires that external log/realtime devices are not in use
1399 #
1400 _require_nonexternal()
1401 {
1402     [ "$USE_EXTERNAL" = yes ] && \
1403         _notrun "External device testing in progress, skipped this test"
1404 }
1405
1406 # this test requires that a (specified) aio-dio executable exists
1407 # $1 - command (optional)
1408 #
1409 _require_aiodio()
1410 {
1411     if [ -z "$1" ]
1412     then
1413         AIO_TEST=src/aio-dio-regress/aiodio_sparse2
1414         [ -x $AIO_TEST ] || _notrun "aio-dio utilities required"
1415     else
1416         AIO_TEST=src/aio-dio-regress/$1
1417         [ -x $AIO_TEST ] || _notrun "$AIO_TEST not built"
1418     fi
1419     _require_odirect
1420 }
1421
1422 # run an aio-dio program
1423 # $1 - command
1424 _run_aiodio()
1425 {
1426     if [ -z "$1" ]
1427     then
1428         echo "usage: _run_aiodio command_name" 2>&1
1429         status=1; exit 1
1430     fi
1431
1432     _require_aiodio $1
1433
1434     local testtemp=$TEST_DIR/aio-testfile
1435     rm -f $testtemp
1436     $AIO_TEST $testtemp 2>&1
1437     status=$?
1438     rm -f $testtemp
1439
1440     return $status
1441 }
1442
1443 # indicate whether YP/NIS is active or not
1444 #
1445 _yp_active()
1446 {
1447         local dn
1448         dn=$(domainname 2>/dev/null)
1449         test -n "${dn}" -a "${dn}" != "(none)"
1450         echo $?
1451 }
1452
1453 # cat the password file
1454 #
1455 _cat_passwd()
1456 {
1457         [ $(_yp_active) -eq 0 ] && ypcat passwd
1458         cat /etc/passwd
1459 }
1460
1461 # cat the group file
1462 #
1463 _cat_group()
1464 {
1465         [ $(_yp_active) -eq 0 ] && ypcat group
1466         cat /etc/group
1467 }
1468
1469 # check for the fsgqa user on the machine
1470 #
1471 _require_user()
1472 {
1473     qa_user=fsgqa
1474     _cat_passwd | grep -q $qa_user
1475     [ "$?" == "0" ] || _notrun "$qa_user user not defined."
1476     echo /bin/true | su $qa_user
1477     [ "$?" == "0" ] || _notrun "$qa_user cannot execute commands."
1478 }
1479
1480 # check for the fsgqa group on the machine
1481 #
1482 _require_group()
1483 {
1484     qa_group=fsgqa
1485     _cat_group | grep -q $qa_group
1486     [ "$?" == "0" ] || _notrun "$qa_group user not defined."
1487 }
1488
1489 _filter_user_do()
1490 {
1491         perl -ne "
1492 s,.*Permission\sdenied.*,Permission denied,;
1493 s,.*no\saccess\sto\stty.*,,;
1494 s,.*no\sjob\scontrol\sin\sthis\sshell.*,,;
1495 s,^\s*$,,;
1496         print;"
1497 }
1498
1499 _user_do()
1500 {
1501     if [ "$HOSTOS" == "IRIX" ]
1502         then
1503         echo $1 | /bin/bash "su $qa_user 2>&1" | _filter_user_do
1504     else
1505         echo $1 | su $qa_user 2>&1 | _filter_user_do
1506     fi
1507 }
1508
1509 _require_xfs_io_command()
1510 {
1511         if [ $# -ne 1 ]
1512         then
1513                 echo "Usage: _require_xfs_io_command command" 1>&2
1514                 exit 1
1515         fi
1516         command=$1
1517
1518         testfile=$TEST_DIR/$$.xfs_io
1519         case $command in
1520         "falloc" )
1521                 testio=`$XFS_IO_PROG -F -f -c "falloc 0 1m" $testfile 2>&1`
1522                 ;;
1523         "fpunch" | "fcollapse" | "zero" | "fzero" | "finsert" )
1524                 testio=`$XFS_IO_PROG -F -f -c "pwrite 0 20k" -c "fsync" \
1525                         -c "$command 4k 8k" $testfile 2>&1`
1526                 ;;
1527         "fiemap")
1528                 testio=`$XFS_IO_PROG -F -f -c "pwrite 0 20k" -c "fsync" \
1529                         -c "fiemap -v" $testfile 2>&1`
1530                 ;;
1531         "flink" )
1532                 testio=`$XFS_IO_PROG -T -F -c "flink $testfile" \
1533                         $TEST_DIR 2>&1`
1534                 echo $testio | egrep -q "invalid option|Is a directory" && \
1535                         _notrun "xfs_io $command support is missing"
1536                 ;;
1537         *)
1538                 testio=`$XFS_IO_PROG -c "$command help" 2>&1`
1539         esac
1540
1541         rm -f $testfile 2>&1 > /dev/null
1542         echo $testio | grep -q "not found" && \
1543                 _notrun "xfs_io $command support is missing"
1544         echo $testio | grep -q "Operation not supported" && \
1545                 _notrun "xfs_io $command failed (old kernel/wrong fs?)"
1546 }
1547
1548 # check that kernel and filesystem support direct I/O
1549 _require_odirect()
1550 {
1551        testfile=$TEST_DIR/$$.direct
1552        $XFS_IO_PROG -F -f -d -c "pwrite 0 20k" $testfile > /dev/null 2>&1
1553        if [ $? -ne 0 ]; then
1554                _notrun "O_DIRECT is not supported"
1555        fi
1556        rm -f $testfile 2>&1 > /dev/null
1557 }
1558
1559 # Check that a fs has enough free space (in 1024b blocks)
1560 #
1561 _require_fs_space()
1562 {
1563         MNT=$1
1564         BLOCKS=$2       # in units of 1024
1565         let GB=$BLOCKS/1024/1024
1566
1567         FREE_BLOCKS=`df -klP $MNT | grep -v Filesystem | awk '{print $4}'`
1568         [ $FREE_BLOCKS -lt $BLOCKS ] && \
1569                 _notrun "This test requires at least ${GB}GB free on $MNT to run"
1570 }
1571
1572 #
1573 # Check if the filesystem supports sparse files.
1574 #
1575 # Unfortunately there is no better way to do this than a manual black list.
1576 #
1577 _require_sparse_files()
1578 {
1579     case $FSTYP in
1580     hfsplus)
1581         _notrun "Sparse files not supported by this filesystem type: $FSTYP"
1582         ;;
1583     *)
1584         ;;
1585     esac
1586 }
1587
1588 _require_debugfs()
1589 {
1590     #boot_params always present in debugfs
1591     [ -d "$DEBUGFS_MNT/boot_params" ] || _notrun "Debugfs not mounted"
1592 }
1593
1594 _require_fail_make_request()
1595 {
1596     [ -f "$DEBUGFS_MNT/fail_make_request/probability" ] \
1597         || _notrun "$DEBUGFS_MNT/fail_make_request \
1598  not found. Seems that CONFIG_FAIL_MAKE_REQUEST kernel config option not enabled"
1599 }
1600
1601 #
1602 # Check if the file system supports seek_data/hole
1603 #
1604 _require_seek_data_hole()
1605 {
1606     testfile=$TEST_DIR/$$.seek
1607     testseek=`$here/src/seek_sanity_test -t $testfile 2>&1`
1608     rm -f $testfile &>/dev/null
1609     echo $testseek | grep -q "Kernel does not support" && \
1610         _notrun "File system does not support llseek(2) SEEK_DATA/HOLE"
1611 }
1612
1613 # check that a FS on a device is mounted
1614 # if so, return mount point
1615 #
1616 _is_mounted()
1617 {
1618     if [ $# -ne 1 ]
1619     then
1620         echo "Usage: _is_mounted device" 1>&2
1621         exit 1
1622     fi
1623
1624     device=$1
1625
1626     if _mount | grep "$device " | $AWK_PROG -v pattern="type $FSTYP" '
1627         pattern        { print $3 ; exit 0 }
1628         END            { exit 1 }
1629     '
1630     then
1631         echo "_is_mounted: $device is not a mounted $FSTYP FS"
1632         exit 1
1633     fi
1634 }
1635
1636 # remount a FS to a new mode (ro or rw)
1637 #
1638 _remount()
1639 {
1640     if [ $# -ne 2 ]
1641     then
1642         echo "Usage: _remount device ro/rw" 1>&2
1643         exit 1
1644     fi
1645     device=$1
1646     mode=$2
1647
1648     if ! mount -o remount,$mode $device
1649     then
1650         echo "_remount: failed to remount filesystem on $device as $mode"
1651         exit 1
1652     fi
1653 }
1654
1655 # Run the appropriate repair/check on a filesystem
1656 #
1657 # if the filesystem is mounted, it's either remounted ro before being
1658 # checked or it's unmounted and then remounted
1659 #
1660
1661 # If set, we remount ro instead of unmounting for fsck
1662 USE_REMOUNT=0
1663
1664 _umount_or_remount_ro()
1665 {
1666     if [ $# -ne 1 ]
1667     then
1668         echo "Usage: _umount_or_remount_ro <device>" 1>&2
1669         exit 1
1670     fi
1671
1672     device=$1
1673     mountpoint=`_is_mounted $device`
1674
1675     if [ $USE_REMOUNT -eq 0 ]; then
1676         $UMOUNT_PROG $device
1677     else
1678         _remount $device ro
1679     fi
1680     echo "$mountpoint"
1681 }
1682
1683 _mount_or_remount_rw()
1684 {
1685     if [ $# -ne 3 ]
1686     then
1687         echo "Usage: _mount_or_remount_rw <opts> <device> <mountpoint>" 1>&2
1688         exit 1
1689     fi
1690     mount_opts=$1
1691     device=$2
1692     mountpoint=$3
1693
1694     if [ $USE_REMOUNT -eq 0 ]
1695     then
1696         if ! _mount -t $FSTYP $mount_opts $device $mountpoint
1697         then
1698             echo "!!! failed to remount $device on $mountpoint"
1699             return 0 # ok=0
1700         fi
1701     else
1702         _remount $device rw
1703     fi
1704
1705     return 1 # ok=1
1706 }
1707
1708 # Check a generic filesystem in no-op mode; this assumes that the
1709 # underlying fsck program accepts "-n" for a no-op (check-only) run,
1710 # and that it will still return an errno for corruption in this mode.
1711 #
1712 # Filesystems which don't support this will need to define their
1713 # own check routine.
1714 #
1715 _check_generic_filesystem()
1716 {
1717     device=$1
1718
1719     # If type is set, we're mounted
1720     type=`_fs_type $device`
1721     ok=1
1722
1723     if [ "$type" = "$FSTYP" ]
1724     then
1725         # mounted ...
1726         mountpoint=`_umount_or_remount_ro $device`
1727     fi
1728
1729     fsck -t $FSTYP $FSCK_OPTIONS $device >$tmp.fsck 2>&1
1730     if [ $? -ne 0 ]
1731     then
1732         echo "_check_generic_filesystem: filesystem on $device is inconsistent (see $seqres.full)"
1733
1734         echo "_check_generic filesystem: filesystem on $device is inconsistent" >>$seqres.full
1735         echo "*** fsck.$FSTYP output ***"       >>$seqres.full
1736         cat $tmp.fsck                           >>$seqres.full
1737         echo "*** end fsck.$FSTYP output"       >>$seqres.full
1738
1739         ok=0
1740     fi
1741     rm -f $tmp.fsck
1742
1743     if [ $ok -eq 0 ]
1744     then
1745         echo "*** mount output ***"             >>$seqres.full
1746         _mount                                  >>$seqres.full
1747         echo "*** end mount output"             >>$seqres.full
1748     elif [ "$type" = "$FSTYP" ]
1749     then
1750         # was mounted ...
1751         _mount_or_remount_rw "$MOUNT_OPTIONS" $device $mountpoint
1752         ok=$?
1753     fi
1754
1755     if [ $ok -eq 0 ]; then
1756         status=1
1757         if [ "$iam" != "check" ]; then
1758                 exit 1
1759         fi
1760         return 1
1761     fi
1762
1763     return 0
1764 }
1765
1766 # run xfs_check and friends on a FS.
1767
1768 _check_xfs_filesystem()
1769 {
1770     if [ $# -ne 3 ]
1771     then
1772         echo "Usage: _check_xfs_filesystem device <logdev>|none <rtdev>|none" 1>&2
1773         exit 1
1774     fi
1775
1776     extra_mount_options=""
1777     device=$1
1778     if [ "$2" != "none" ]; then
1779         extra_log_options="-l$2"
1780         extra_mount_options="-ologdev=$2"
1781     fi
1782
1783     if [ "$3" != "none" ]; then
1784         extra_rt_options="-r$3"
1785         extra_mount_options=$extra_mount_options" -ortdev=$3"
1786     fi
1787     extra_mount_options=$extra_mount_options" $MOUNT_OPTIONS"
1788
1789     [ "$FSTYP" != xfs ] && return 0
1790
1791     type=`_fs_type $device`
1792     ok=1
1793
1794     if [ "$type" = "xfs" ]
1795     then
1796         # mounted ...
1797         mountpoint=`_umount_or_remount_ro $device`
1798     fi
1799
1800     $XFS_LOGPRINT_PROG -t $extra_log_options $device 2>&1 \
1801                 | tee $tmp.logprint | grep -q "<CLEAN>"
1802     if [ $? -ne 0 -a "$HOSTOS" = "Linux" ]
1803     then
1804         echo "_check_xfs_filesystem: filesystem on $device has dirty log (see $seqres.full)"
1805
1806         echo "_check_xfs_filesystem: filesystem on $device has dirty log"   >>$seqres.full
1807         echo "*** xfs_logprint -t output ***"   >>$seqres.full
1808         cat $tmp.logprint                       >>$seqres.full
1809         echo "*** end xfs_logprint output"      >>$seqres.full
1810
1811         ok=0
1812     fi
1813
1814     # xfs_check runs out of memory on large files, so even providing the test
1815     # option (-t) to avoid indexing the free space trees doesn't make it pass on
1816     # large filesystems. Avoid it.
1817     if [ "$LARGE_SCRATCH_DEV" != yes ]; then
1818             _xfs_check $extra_log_options $device 2>&1 |\
1819                  _fix_malloc >$tmp.fs_check
1820     fi
1821     if [ -s $tmp.fs_check ]
1822     then
1823         echo "_check_xfs_filesystem: filesystem on $device is inconsistent (c) (see $seqres.full)"
1824
1825         echo "_check_xfs_filesystem: filesystem on $device is inconsistent" >>$seqres.full
1826         echo "*** xfs_check output ***"         >>$seqres.full
1827         cat $tmp.fs_check                       >>$seqres.full
1828         echo "*** end xfs_check output"         >>$seqres.full
1829
1830         ok=0
1831     fi
1832
1833     $XFS_REPAIR_PROG -n $extra_log_options $extra_rt_options $device >$tmp.repair 2>&1
1834     if [ $? -ne 0 ]
1835     then
1836         echo "_check_xfs_filesystem: filesystem on $device is inconsistent (r) (see $seqres.full)"
1837
1838         echo "_check_xfs_filesystem: filesystem on $device is inconsistent" >>$seqres.full
1839         echo "*** xfs_repair -n output ***"     >>$seqres.full
1840         cat $tmp.repair | _fix_malloc           >>$seqres.full
1841         echo "*** end xfs_repair output"        >>$seqres.full
1842
1843         ok=0
1844     fi
1845     rm -f $tmp.fs_check $tmp.logprint $tmp.repair
1846
1847     if [ $ok -eq 0 ]
1848     then
1849         echo "*** mount output ***"             >>$seqres.full
1850         _mount                                  >>$seqres.full
1851         echo "*** end mount output"             >>$seqres.full
1852     elif [ "$type" = "xfs" ]
1853     then
1854         _mount_or_remount_rw "$extra_mount_options" $device $mountpoint
1855     fi
1856
1857     if [ $ok -eq 0 ]; then
1858         status=1
1859         if [ "$iam" != "check" ]; then
1860                 exit 1
1861         fi
1862         return 1
1863     fi
1864
1865     return 0
1866 }
1867
1868 # Filter the knowen errors the UDF Verifier reports.
1869 _udf_test_known_error_filter()
1870 {
1871         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."
1872
1873 }
1874
1875 _check_udf_filesystem()
1876 {
1877     [ "$DISABLE_UDF_TEST" == "1" ] && return
1878
1879     if [ $# -ne 1 -a $# -ne 2 ]
1880     then
1881         echo "Usage: _check_udf_filesystem device [last_block]" 1>&2
1882         exit 1
1883     fi
1884
1885     if [ ! -x $here/src/udf_test ]
1886     then
1887         echo "udf_test not installed, please download and build the Philips"
1888         echo "UDF Verification Software from http://www.extra.research.philips.com/udf/."
1889         echo "Then copy the udf_test binary to $here/src/."
1890         echo "If you do not wish to run udf_test then set environment variable DISABLE_UDF_TEST"
1891         echo "to 1."
1892         return
1893     fi
1894
1895     device=$1
1896     if [ $# -eq 2 ];
1897     then
1898         LAST_BLOCK=`expr \( $2 - 1 \)`
1899         OPT_ARG="-lastvalidblock $LAST_BLOCK"
1900     fi
1901
1902     rm -f $seqres.checkfs
1903     sleep 1 # Due to a problem with time stamps in udf_test
1904     $here/src/udf_test $OPT_ARG $device | tee $seqres.checkfs | egrep "Error|Warning" | \
1905         _udf_test_known_error_filter | \
1906         egrep -iv "Error count:.*[0-9]+.*total occurrences:.*[0-9]+|Warning count:.*[0-9]+.*total occurrences:.*[0-9]+" && \
1907         echo "Warning UDF Verifier reported errors see $seqres.checkfs." && return 1
1908     return 0
1909 }
1910
1911 _check_xfs_test_fs()
1912 {
1913     TEST_LOG="none"
1914     TEST_RT="none"
1915     [ "$USE_EXTERNAL" = yes -a ! -z "$TEST_LOGDEV" ] && \
1916         TEST_LOG="$TEST_LOGDEV"
1917
1918     [ "$USE_EXTERNAL" = yes -a ! -z "$TEST_RTDEV" ] && \
1919         TEST_RT="$TEST_RTDEV"
1920
1921     _check_xfs_filesystem $TEST_DEV $TEST_LOG $TEST_RT
1922
1923     # check for ipath consistency
1924     if $XFS_GROWFS_PROG -n $TEST_DIR | grep -q 'inode-paths=1'; then
1925         # errors go to stderr
1926         xfs_check_ipaths $TEST_DIR >/dev/null
1927         xfs_repair_ipaths -n $TEST_DIR >/dev/null
1928     fi
1929 }
1930
1931 _check_btrfs_filesystem()
1932 {
1933     device=$1
1934
1935     # If type is set, we're mounted
1936     type=`_fs_type $device`
1937     ok=1
1938
1939     if [ "$type" = "$FSTYP" ]
1940     then
1941         # mounted ...
1942         mountpoint=`_umount_or_remount_ro $device`
1943     fi
1944
1945     btrfsck $device >$tmp.fsck 2>&1
1946     if [ $? -ne 0 ]
1947     then
1948         echo "_check_btrfs_filesystem: filesystem on $device is inconsistent (see $seqres.full)"
1949
1950         echo "_check_btrfs_filesystem: filesystem on $device is inconsistent" >>$seqres.full
1951         echo "*** fsck.$FSTYP output ***"       >>$seqres.full
1952         cat $tmp.fsck                           >>$seqres.full
1953         echo "*** end fsck.$FSTYP output"       >>$seqres.full
1954
1955         ok=0
1956     fi
1957     rm -f $tmp.fsck
1958
1959     if [ $ok -eq 0 ]
1960     then
1961         echo "*** mount output ***"             >>$seqres.full
1962         _mount                                  >>$seqres.full
1963         echo "*** end mount output"             >>$seqres.full
1964     elif [ "$type" = "$FSTYP" ]
1965     then
1966         # was mounted ...
1967         _mount_or_remount_rw "$MOUNT_OPTIONS" $device $mountpoint
1968         ok=$?
1969     fi
1970
1971     if [ $ok -eq 0 ]; then
1972         status=1
1973         if [ "$iam" != "check" ]; then
1974                 exit 1
1975         fi
1976         return 1
1977     fi
1978
1979     return 0
1980 }
1981
1982 _check_test_fs()
1983 {
1984     case $FSTYP in
1985     xfs)
1986         _check_xfs_test_fs
1987         ;;
1988     nfs)
1989         # no way to check consistency for nfs
1990         ;;
1991     cifs)
1992         # no way to check consistency for cifs
1993         ;;
1994     udf)
1995         # do nothing for now
1996         ;;
1997     btrfs)
1998         _check_btrfs_filesystem $TEST_DEV
1999         ;;
2000     tmpfs)
2001         # no way to check consistency for tmpfs
2002         ;;
2003     *)
2004         _check_generic_filesystem $TEST_DEV
2005         ;;
2006     esac
2007 }
2008
2009 _check_scratch_fs()
2010 {
2011     device=$SCRATCH_DEV
2012     [ $# -eq 1 ] && device=$1
2013
2014     case $FSTYP in
2015     xfs)
2016         SCRATCH_LOG="none"
2017         SCRATCH_RT="none"
2018         [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_LOGDEV" ] && \
2019             SCRATCH_LOG="$SCRATCH_LOGDEV"
2020
2021         [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_RTDEV" ] && \
2022             SCRATCH_RT="$SCRATCH_RTDEV"
2023
2024         _check_xfs_filesystem $device $SCRATCH_LOG $SCRATCH_RT
2025         ;;
2026     udf)
2027         _check_udf_filesystem $device $udf_fsize
2028         ;;
2029     nfs*)
2030         # Don't know how to check an NFS filesystem, yet.
2031         ;;
2032     cifs)
2033         # Don't know how to check a CIFS filesystem, yet.
2034         ;;
2035     btrfs)
2036         _check_btrfs_filesystem $device
2037         ;;
2038     tmpfs)
2039         # no way to check consistency for tmpfs
2040         ;;
2041     *)
2042         _check_generic_filesystem $device
2043         ;;
2044     esac
2045 }
2046
2047 _full_fstyp_details()
2048 {
2049      [ -z "$FSTYP" ] && FSTYP=xfs
2050      if [ $FSTYP = xfs ]; then
2051         if [ -d /proc/fs/xfs ]; then
2052             if grep -q 'debug 0' /proc/fs/xfs/stat; then
2053                 FSTYP="$FSTYP (non-debug)"
2054             elif grep -q 'debug 1' /proc/fs/xfs/stat; then
2055                 FSTYP="$FSTYP (debug)"
2056             fi
2057         else
2058             if uname -a | grep -qi 'debug'; then
2059                 FSTYP="$FSTYP (debug)"
2060             else
2061                 FSTYP="$FSTYP (non-debug)"
2062             fi
2063         fi
2064      fi
2065      echo $FSTYP
2066 }
2067
2068 _full_platform_details()
2069 {
2070      os=`uname -s`
2071      host=`hostname -s`
2072      kernel=`uname -r`
2073      platform=`uname -m`
2074      echo "$os/$platform $host $kernel"
2075 }
2076
2077 _link_out_file()
2078 {
2079         if [ -z "$1" -o -z "$2" ]; then
2080                 echo Error must pass src and dst.
2081                 exit
2082         fi
2083         rm -f $2
2084         if [ "`uname`" == "IRIX64" ] || [ "`uname`" == "IRIX" ]; then
2085                 ln -s $1.irix $2
2086         elif [ "`uname`" == "Linux" ]; then
2087                 ln -s $1.linux $2
2088         else
2089                 echo Error test $seq does not run on the operating system: `uname`
2090                 exit
2091         fi
2092 }
2093
2094 _die()
2095 {
2096         echo $@
2097         exit 1
2098 }
2099
2100 #takes files, randomdata
2101 _nfiles()
2102 {
2103         f=0
2104         while [ $f -lt $1 ]
2105         do
2106                 file=f$f
2107                 echo > $file
2108                 if [ $size -gt 0 ]; then
2109                     if [ "$2" == "false" ]; then
2110                         dd if=/dev/zero of=$file bs=1024 count=$size 2>&1 | _filter_dd
2111                     else
2112                         dd if=/dev/urandom of=$file bs=1024 count=$size 2>&1 | _filter_dd
2113                     fi
2114                 fi
2115                 let f=$f+1
2116         done
2117 }
2118
2119 # takes dirname, depth, randomdata
2120 _descend()
2121 {
2122         dirname=$1; depth=$2; randomdata=$3
2123         mkdir $dirname  || die "mkdir $dirname failed"
2124         cd $dirname
2125
2126         _nfiles $files $randomdata          # files for this dir and data type
2127
2128         [ $depth -eq 0 ] && return
2129         let deep=$depth-1 # go 1 down
2130
2131         [ $verbose = true ] && echo "descending, depth from leaves = $deep"
2132
2133         d=0
2134         while [ $d -lt $dirs ]
2135         do
2136                 _descend d$d $deep &
2137                 let d=$d+1
2138                 wait
2139         done
2140 }
2141
2142 # Populate a filesystem with inodes for performance experiments
2143 #
2144 # usage: populate [-v] [-n ndirs] [-f nfiles] [-d depth] [-r root] [-s size] [-x]
2145 #
2146 _populate_fs()
2147 {
2148     here=`pwd`
2149     dirs=5          # ndirs in each subdir till leaves
2150     size=0          # sizeof files in K
2151     files=100       # num files in _each_ subdir
2152     depth=2         # depth of tree from root to leaves
2153     verbose=false
2154     root=root       # path of initial root of directory tree
2155     randomdata=false # -x data type urandom or zero
2156
2157     OPTIND=1
2158     while getopts "d:f:n:r:s:v:x" c
2159     do
2160         case $c in
2161         d)      depth=$OPTARG;;
2162         n)      dirs=$OPTARG;;
2163         f)      files=$OPTARG;;
2164         s)      size=$OPTARG;;
2165         v)      verbose=true;;
2166         r)      root=$OPTARG;;
2167         x)      randomdata=true;;
2168         esac
2169     done
2170
2171     _descend $root $depth $randomdata
2172     wait
2173
2174     cd $here
2175
2176     [ $verbose = true ] && echo done
2177 }
2178
2179 # query whether the given file has the given inode flag set
2180 #
2181 _test_inode_flag()
2182 {
2183     flag=$1
2184     file=$2
2185
2186     if which $XFS_IO_PROG >/dev/null; then
2187         if $XFS_IO_PROG -r -c 'lsattr -v' "$file" | grep -q "$flag" ; then
2188             return 0
2189         fi
2190     fi
2191     return 1
2192 }
2193
2194 # query the given files extsize allocator hint in bytes (if any)
2195 #
2196 _test_inode_extsz()
2197 {
2198     file=$1
2199     blocks=""
2200
2201     if which $XFS_IO_PROG >/dev/null; then
2202         blocks=`$XFS_IO_PROG -r -c 'stat' "$file" | \
2203                 awk '/^xattr.extsize =/ { print $3 }'`
2204     fi
2205     [ -z "$blocks" ] && blocks="0"
2206     echo $blocks
2207 }
2208
2209 # scratch_dev_pool should contain the disks pool for the btrfs raid
2210 _require_scratch_dev_pool()
2211 {
2212         local i
2213         local ndevs
2214
2215         if [ -z "$SCRATCH_DEV_POOL" ]; then
2216                 _notrun "this test requires a valid \$SCRATCH_DEV_POOL"
2217         fi
2218
2219         if [ -z "$1" ]; then
2220                 ndevs=2
2221         else
2222                 ndevs=$1
2223         fi
2224
2225         # btrfs test case needs ndevs or more scratch_dev_pool; other FS not sure
2226         # so fail it
2227         case $FSTYP in
2228         btrfs)
2229                 if [ "`echo $SCRATCH_DEV_POOL|wc -w`" -lt $ndevs ]; then
2230                         _notrun "btrfs and this test needs $ndevs or more disks in SCRATCH_DEV_POOL"
2231                 fi
2232         ;;
2233         *)
2234                 _notrun "dev_pool is not supported by fstype \"$FSTYP\""
2235         ;;
2236         esac
2237
2238         for i in $SCRATCH_DEV_POOL; do
2239                 if [ "`_is_block_dev $i`" = "" ]; then
2240                         _notrun "this test requires valid block disk $i"
2241                 fi
2242                 if [ "`_is_block_dev $i`" = "`_is_block_dev $TEST_DEV`" ]; then
2243                         _notrun "$i is part of TEST_DEV, this test requires unique disks"
2244                 fi
2245                 if _mount | grep -q $i; then
2246                         if ! $UMOUNT_PROG $i; then
2247                             echo "failed to unmount $i - aborting"
2248                             exit 1
2249                         fi
2250                 fi
2251                 # to help better debug when something fails, we remove
2252                 # traces of previous btrfs FS on the dev.
2253                 dd if=/dev/zero of=$i bs=4096 count=100 > /dev/null 2>&1
2254         done
2255 }
2256
2257 # ensure devices in SCRATCH_DEV_POOL are of the same size
2258 # must be called after _require_scratch_dev_pool
2259 _require_scratch_dev_pool_equal_size()
2260 {
2261         local _size
2262         local _newsize
2263         local _dev
2264
2265         # SCRATCH_DEV has been set to the first device in SCRATCH_DEV_POOL
2266         _size=`_get_device_size $SCRATCH_DEV`
2267         for _dev in $SCRATCH_DEV_POOL; do
2268                 _newsize=`_get_device_size $_dev`
2269                 if [ $_size -ne $_newsize ]; then
2270                         _notrun "This test requires devices in SCRATCH_DEV_POOL have the same size"
2271                 fi
2272         done
2273 }
2274
2275 # We will check if the device is deletable
2276 _require_deletable_scratch_dev_pool()
2277 {
2278         local i
2279         local x
2280         for i in $SCRATCH_DEV_POOL; do
2281                 x=`echo $i | cut -d"/" -f 3`
2282                 if [ ! -f /sys/class/block/${x}/device/delete ]; then
2283                         _notrun "$i is a device which is not deletable"
2284                 fi
2285         done
2286 }
2287
2288 # We check for btrfs and (optionally) features of the btrfs command
2289 _require_btrfs()
2290 {
2291         cmd=$1
2292         _require_command "$BTRFS_UTIL_PROG" btrfs
2293         if [ -z "$1" ]; then
2294                 return 1;
2295         fi
2296         $BTRFS_UTIL_PROG $cmd --help >/dev/null 2>&1
2297         [ $? -eq 0 ] || _notrun "$BTRFS_UTIL_PROG too old (must support $cmd)"
2298 }
2299
2300 # Check that fio is present, and it is able to execute given jobfile
2301 _require_fio()
2302 {
2303         job=$1
2304
2305         _require_command "$FIO_PROG" fio
2306         if [ -z "$1" ]; then
2307                 return 1;
2308         fi
2309
2310         $FIO_PROG --warnings-fatal --showcmd $job >> $seqres.full 2>&1
2311         [ $? -eq 0 ] || _notrun "$FIO_PROG too old, see $seqres.full"
2312 }
2313
2314 # Does freeze work on this fs?
2315 _require_freeze()
2316 {
2317         xfs_freeze -f "$TEST_DIR" >/dev/null 2>&1
2318         result=$? 
2319         xfs_freeze -u "$TEST_DIR" >/dev/null 2>&1
2320         [ $result -eq 0 ] || _notrun "$FSTYP does not support freezing"
2321 }
2322
2323 # Does shutdown work on this fs?
2324 _require_scratch_shutdown()
2325 {
2326         [ -x src/godown ] || _notrun "src/godown executable not found"
2327
2328         _scratch_mkfs > /dev/null 2>&1
2329         _scratch_mount
2330         src/godown -f $SCRATCH_MNT 2>&1 \
2331                 || _notrun "$FSTYP does not support shutdown"
2332         _scratch_unmount
2333 }
2334
2335 # Does norecovery support by this fs?
2336 _require_norecovery()
2337 {
2338         _scratch_mount -o ro,norecovery || \
2339                 _notrun "$FSTYP does not support norecovery"
2340         _scratch_unmount
2341 }
2342
2343 # Does this filesystem support metadata journaling?
2344 # We exclude ones here that don't; otherwise we assume that it does, so the
2345 # test will run, fail, and motivate someone to update this test for a new
2346 # filesystem.
2347 #
2348 # It's possible that TEST_DEV and SCRATCH_DEV have different features (it'd be
2349 # odd, but possible) so check $TEST_DEV by default, but we can optionall pass
2350 # any dev we want.
2351 _require_metadata_journaling()
2352 {
2353         if [ -z $1 ]; then
2354                 DEV=$TEST_DEV
2355         else
2356                 DEV=$1
2357         fi
2358
2359         case "$FSTYP" in
2360         ext2|vfat|msdos)
2361                 _notrun "$FSTYP does not support metadata journaling"
2362                 ;;
2363         ext4)
2364                 # ext4 could be mkfs'd without a journal...
2365                 _require_dumpe2fs
2366                 $DUMPE2FS_PROG -h $DEV 2>&1 | grep -q has_journal || \
2367                         _notrun "$FSTYP on $DEV not configured with metadata journaling"
2368                 ;;
2369         *)
2370                 # by default we pass; if you need to, add your fs above!
2371                 ;;
2372         esac
2373 }
2374
2375 # Does fiemap support?
2376 _require_fiemap()
2377 {
2378         _require_xfs_io_command "fiemap"
2379 }
2380
2381 _count_extents()
2382 {
2383         res=`$XFS_IO_PROG -c "fiemap" $1 | tail -n +2`
2384         echo $res | grep -v hole | wc -l | $AWK_PROG '{print $1}'
2385 }
2386
2387 _count_holes()
2388 {
2389         res=`$XFS_IO_PROG -c "fiemap" $1 | tail -n +2`
2390         echo $res | grep hole | wc -l | $AWK_PROG '{print $1}'
2391 }
2392
2393 # arg 1 is dev to remove and is output of the below eg.
2394 # ls -l /sys/class/block/sdd | rev | cut -d "/" -f 3 | rev
2395 _devmgt_remove()
2396 {
2397         local lun=$1
2398         local disk=$2
2399
2400         echo 1 > /sys/class/scsi_device/${lun}/device/delete || _fail "Remove disk failed"
2401
2402         stat $disk > /dev/null 2>&1
2403         while [ $? -eq 0 ]; do
2404                 sleep 1
2405                 stat $disk > /dev/null 2>&1
2406         done
2407 }
2408
2409 # arg 1 is dev to add and is output of the below eg.
2410 # ls -l /sys/class/block/sdd | rev | cut -d "/" -f 3 | rev
2411 _devmgt_add()
2412 {
2413         local h
2414         local tdl
2415         # arg 1 will be in h:t:d:l format now in the h and "t d l" format
2416         h=`echo ${1} | cut -d":" -f 1`
2417         tdl=`echo ${1} | cut -d":" -f 2-|sed 's/:/ /g'`
2418
2419         echo ${tdl} >  /sys/class/scsi_host/host${h}/scan || _fail "Add disk failed"
2420
2421         # ensure the device comes online
2422         dev_back_oneline=0
2423         for i in `seq 1 10`; do
2424                 if [ -d /sys/class/scsi_device/${1}/device/block ]; then
2425                         dev=`ls /sys/class/scsi_device/${1}/device/block`
2426                         for j in `seq 1 10`;
2427                         do
2428                                 stat /dev/$dev > /dev/null 2>&1
2429                                 if [ $? -eq 0 ]; then
2430                                         dev_back_oneline=1
2431                                         break
2432                                 fi
2433                                 sleep 1
2434                         done
2435                         break
2436                 else
2437                         sleep 1
2438                 fi
2439         done
2440         if [ $dev_back_oneline -eq 0 ]; then
2441                 echo "/dev/$dev online failed" >> $seqres.full
2442         else
2443                 echo "/dev/$dev is back online" >> $seqres.full
2444         fi
2445 }
2446
2447 _require_fstrim()
2448 {
2449         if [ -z "$FSTRIM_PROG" ]; then
2450                 _notrun "This test requires fstrim utility."
2451         fi
2452 }
2453
2454 _require_batched_discard()
2455 {
2456         if [ $# -ne 1 ]; then
2457                 echo "Usage: _require_batched_discard mnt_point" 1>&2
2458                 exit 1
2459         fi
2460         _require_fstrim
2461         $FSTRIM_PROG $1 > /dev/null 2>&1 || _notrun "FITRIM not supported on $1"
2462 }
2463
2464 _require_dumpe2fs()
2465 {
2466         if [ -z "$DUMPE2FS_PROG" ]; then
2467                 _notrun "This test requires dumpe2fs utility."
2468         fi
2469 }
2470
2471 _require_ugid_map()
2472 {
2473         if [ ! -e /proc/self/uid_map ]; then
2474                 _notrun "This test requires procfs uid_map support."
2475         fi
2476         if [ ! -e /proc/self/gid_map ]; then
2477                 _notrun "This test requires procfs gid_map support."
2478         fi
2479 }
2480
2481 _require_cp_reflink()
2482 {
2483        cp --help | grep -q reflink || \
2484                _notrun "This test requires a cp with --reflink support."
2485 }
2486
2487 _require_fssum()
2488 {
2489         FSSUM_PROG=$here/src/fssum
2490         [ -x $FSSUM_PROG ] || _notrun "fssum not built"
2491 }
2492
2493 _require_cloner()
2494 {
2495         CLONER_PROG=$here/src/cloner
2496         [ -x $CLONER_PROG ] || \
2497                 _notrun "cloner binary not present at $CLONER_PROG"
2498 }
2499
2500 # Given 2 files, verify that they have the same mapping but different
2501 # inodes - i.e. an undisturbed reflink
2502 # Silent if so, make noise if not
2503 _verify_reflink()
2504 {
2505        # not a hard link or symlink?
2506        cmp -s  <(stat -c '%i' $1) <(stat -c '%i' $2) \
2507                && echo "$1 and $2 are not reflinks: same inode number"
2508
2509        # same mapping?
2510        diff -u <($XFS_IO_PROG -c "fiemap" $1 | grep -v $1) \
2511                <($XFS_IO_PROG -c "fiemap" $2 | grep -v $2) \
2512                || echo "$1 and $2 are not reflinks: different extents"
2513 }
2514
2515 _require_atime()
2516 {
2517         if [ "$FSTYP" == "nfs" ]; then
2518                 _notrun "atime related mount options have no effect on NFS"
2519         fi
2520 }
2521
2522 _require_relatime()
2523 {
2524         _scratch_mkfs > /dev/null 2>&1
2525         _scratch_mount -o relatime || \
2526                 _notrun "relatime not supported by the current kernel"
2527         _scratch_unmount
2528 }
2529
2530 _require_userns()
2531 {
2532         [ -x src/nsexec ] || _notrun "src/nsexec executable not found"
2533         src/nsexec -U true 2>/dev/null || _notrun "userns not supported by this kernel"
2534 }
2535
2536 _create_loop_device()
2537 {
2538         file=$1
2539         dev=`losetup -f --show $file` || _fail "Cannot assign $file to a loop device"
2540         echo $dev
2541 }
2542
2543 _destroy_loop_device()
2544 {
2545         dev=$1
2546         losetup -d $dev || _fail "Cannot destroy loop device $dev"
2547 }
2548
2549 _scale_fsstress_args()
2550 {
2551     args=""
2552     while [ $# -gt 0 ]; do
2553         case "$1" in
2554             -n) args="$args $1 $(($2 * $TIME_FACTOR))"; shift ;;
2555             -p) args="$args $1 $(($2 * $LOAD_FACTOR))"; shift ;;
2556             *) args="$args $1" ;;
2557         esac
2558         shift
2559     done
2560     echo $args
2561 }
2562
2563 #
2564 # Return the logical block size if running on a block device,
2565 # else substitute the page size.
2566 #
2567 _min_dio_alignment()
2568 {
2569     dev=$1
2570
2571     if [ -b "$dev" ]; then
2572         blockdev --getss $dev
2573     else
2574         $here/src/feature -s
2575     fi
2576 }
2577
2578 run_check()
2579 {
2580         echo "# $@" >> $seqres.full 2>&1
2581         "$@" >> $seqres.full 2>&1 || _fail "failed: '$@'"
2582 }
2583
2584 _run_btrfs_util_prog()
2585 {
2586         run_check $BTRFS_UTIL_PROG $*
2587 }
2588
2589 _require_btrfs_send_stream_version()
2590 {
2591         $BTRFS_UTIL_PROG send 2>&1 | \
2592                 grep '^[ \t]*\-\-stream\-version <version>' > /dev/null 2>&1
2593         if [ $? -ne 0 ]; then
2594                 _notrun "Missing btrfs-progs send --stream-version command line option, skipped this test"
2595         fi
2596
2597         # test if btrfs kernel supports send stream version 2
2598         if [ ! -f /sys/fs/btrfs/send/stream_version ]; then
2599                 _notrun "Missing btrfs kernel patch for send stream version 2, skipped this test"
2600         fi
2601 }
2602
2603 _require_btrfs_mkfs_feature()
2604 {
2605         if [ -z $1 ]; then
2606                 echo "Missing feature name argument for _require_btrfs_mkfs_feature"
2607                 exit 1
2608         fi
2609         feat=$1
2610         $MKFS_BTRFS_PROG -O list-all 2>&1 | \
2611                 grep '^[ \t]*'"$feat"'\b' > /dev/null 2>&1
2612         [ $? -eq 0 ] || \
2613                 _notrun "Feature $feat not supported in the available version of mkfs.btrfs"
2614 }
2615
2616 _require_btrfs_fs_feature()
2617 {
2618         if [ -z $1 ]; then
2619                 echo "Missing feature name argument for _require_btrfs_fs_feature"
2620                 exit 1
2621         fi
2622         feat=$1
2623         modprobe btrfs > /dev/null 2>&1
2624         [ -e /sys/fs/btrfs/features/$feat ] || \
2625                 _notrun "Feature $feat not supported by the available btrfs version"
2626 }
2627
2628 _require_test_symlinks()
2629 {
2630         # IRIX UDF does not support symlinks
2631         [ "$HOSTOS" = "IRIX" -a "$FSTYP" = 'udf' ] && \
2632                 _notrun "Require symlinks support"
2633         target=`mktemp -p $TEST_DIR`
2634         link=`mktemp -p $TEST_DIR -u`
2635         ln -s `basename $target` $link
2636         if [ "$?" -ne 0 ]; then
2637                 rm -f $target
2638                 _notrun "Require symlinks support"
2639         fi
2640         rm -f $target $link
2641 }
2642
2643 _require_test_fcntl_advisory_locks()
2644 {
2645         [ "$FSTYP" != "cifs" ] && return 0
2646         cat /proc/mounts | grep $TEST_DEV | grep cifs | grep -q "nobrl" && return 0
2647         cat /proc/mounts | grep $TEST_DEV | grep cifs | grep -qE "nounix|forcemand" && \
2648                 _notrun "Require fcntl advisory locks support"
2649 }
2650
2651 _get_total_inode()
2652 {
2653         if [ -z "$1" ]; then
2654                 echo "Usage: _get_total_inode <mnt>"
2655                 exit 1
2656         fi
2657         local nr_inode;
2658         nr_inode=`$DF_PROG -i $1 | tail -1 | awk '{print $3}'`
2659         echo $nr_inode
2660 }
2661
2662 _get_used_inode()
2663 {
2664         if [ -z "$1" ]; then
2665                 echo "Usage: _get_used_inode <mnt>"
2666                 exit 1
2667         fi
2668         local nr_inode;
2669         nr_inode=`$DF_PROG -i $1 | tail -1 | awk '{print $4}'`
2670         echo $nr_inode
2671 }
2672
2673 _get_free_inode()
2674 {
2675         if [ -z "$1" ]; then
2676                 echo "Usage: _get_free_inode <mnt>"
2677                 exit 1
2678         fi
2679         local nr_inode;
2680         nr_inode=`$DF_PROG -i $1 | tail -1 | awk '{print $5}'`
2681         echo $nr_inode
2682 }
2683
2684 # get btrfs profile configs being tested
2685 #
2686 # A set of pre-set profile configs are exported via _btrfs_profile_configs
2687 # array. Default configs can be overridden by setting BTRFS_PROFILE_CONFIGS
2688 # var in the format "metadata_profile:data_profile", multiple configs can be
2689 # seperated by space, e.g.
2690 # export BTRFS_PROFILE_CONFIGS="raid0:raid0 raid1:raid1 dup:single"
2691 _btrfs_get_profile_configs()
2692 {
2693         if [ "$FSTYP" != "btrfs" ]; then
2694                 return
2695         fi
2696
2697         # no user specified btrfs profile configs, export the default configs
2698         if [ -z "$BTRFS_PROFILE_CONFIGS" ]; then
2699                 # default configs
2700                 _btrfs_profile_configs=(
2701                         "-m single -d single"
2702                         "-m dup -d single"
2703                         "-m raid0 -d raid0"
2704                         "-m raid1 -d raid0"
2705                         "-m raid1 -d raid1"
2706                         "-m raid10 -d raid10"
2707                         "-m raid5 -d raid5"
2708                         "-m raid6 -d raid6"
2709                 )
2710
2711                 # remove dup/raid5/raid6 profiles if we're doing device replace
2712                 # dup profile indicates only one device being used (SCRATCH_DEV),
2713                 # but we don't want to replace SCRATCH_DEV, which will be used in
2714                 # _scratch_mount/_check_scratch_fs etc.
2715                 # and raid5/raid6 doesn't support replace yet
2716                 if [ "$1" == "replace" ]; then
2717                         _btrfs_profile_configs=(
2718                                 "-m single -d single"
2719                                 "-m raid0 -d raid0"
2720                                 "-m raid1 -d raid0"
2721                                 "-m raid1 -d raid1"
2722                                 "-m raid10 -d raid10"
2723                                 # add these back when raid5/6 is working with replace
2724                                 #"-m raid5 -d raid5"
2725                                 #"-m raid6 -d raid6"
2726                         )
2727                 fi
2728                 export _btrfs_profile_configs
2729                 return
2730         fi
2731
2732         # parse user specified btrfs profile configs
2733         local i=0
2734         local cfg=""
2735         for cfg in $BTRFS_PROFILE_CONFIGS; do
2736                 # turn "metadata:data" format to "-m metadata -d data"
2737                 # and assign it to _btrfs_profile_configs array
2738                 cfg=`echo "$cfg" | sed -e 's/^/-m /' -e 's/:/ -d /'`
2739                 _btrfs_profile_configs[$i]="$cfg"
2740                 let i=i+1
2741         done
2742
2743         if [ "$1" == "replace" ]; then
2744                 if echo ${_btrfs_profile_configs[*]} | grep -q raid[56]; then
2745                         _notrun "RAID5/6 doesn't support btrfs device replace yet"
2746                 fi
2747                 if echo ${_btrfs_profile_configs[*]} | grep -q dup; then
2748                         _notrun "Do not set dup profile in btrfs device replace test"
2749                 fi
2750         fi
2751         export _btrfs_profile_configs
2752 }
2753
2754 # stress btrfs by running balance operation in a loop
2755 _btrfs_stress_balance()
2756 {
2757         local btrfs_mnt=$1
2758         while true; do
2759                 $BTRFS_UTIL_PROG balance start $btrfs_mnt
2760         done
2761 }
2762
2763 # stress btrfs by creating/mounting/umounting/deleting subvolume in a loop
2764 _btrfs_stress_subvolume()
2765 {
2766         local btrfs_dev=$1
2767         local btrfs_mnt=$2
2768         local subvol_name=$3
2769         local subvol_mnt=$4
2770
2771         mkdir -p $subvol_mnt
2772         while true; do
2773                 $BTRFS_UTIL_PROG subvolume create $btrfs_mnt/$subvol_name
2774                 $MOUNT_PROG -o subvol=$subvol_name $btrfs_dev $subvol_mnt
2775                 $UMOUNT_PROG $subvol_mnt
2776                 $BTRFS_UTIL_PROG subvolume delete $btrfs_mnt/$subvol_name
2777         done
2778 }
2779
2780 # stress btrfs by running scrub in a loop
2781 _btrfs_stress_scrub()
2782 {
2783         local btrfs_mnt=$1
2784         while true; do
2785                 $BTRFS_UTIL_PROG scrub start -B $btrfs_mnt
2786         done
2787 }
2788
2789 # stress btrfs by defragmenting every file/dir in a loop and compress file
2790 # contents while defragmenting if second argument is not "nocompress"
2791 _btrfs_stress_defrag()
2792 {
2793         local btrfs_mnt=$1
2794         local compress=$2
2795
2796         while true; do
2797                 if [ "$compress" == "nocompress" ]; then
2798                         find $btrfs_mnt \( -type f -o -type d \) -exec \
2799                         $BTRFS_UTIL_PROG filesystem defrag {} \;
2800                 else
2801                         find $btrfs_mnt \( -type f -o -type d \) -exec \
2802                         $BTRFS_UTIL_PROG filesystem defrag -clzo {} \;
2803                         find $btrfs_mnt \( -type f -o -type d \) -exec \
2804                         $BTRFS_UTIL_PROG filesystem defrag -czlib {} \;
2805                 fi
2806         done
2807 }
2808
2809 # stress btrfs by remounting it with different compression algorithms in a loop
2810 # run this with fsstress running at background could exercise the compression
2811 # code path and ensure no race when switching compression algorithm with constant
2812 # I/O activity.
2813 _btrfs_stress_remount_compress()
2814 {
2815         local btrfs_mnt=$1
2816         while true; do
2817                 for algo in no zlib lzo; do
2818                         $MOUNT_PROG -o remount,compress=$algo $btrfs_mnt
2819                 done
2820         done
2821 }
2822
2823 # stress btrfs by replacing devices in a loop
2824 # Note that at least 3 devices are needed in SCRATCH_DEV_POOL and the last
2825 # device should be free(not used by btrfs)
2826 _btrfs_stress_replace()
2827 {
2828         local btrfs_mnt=$1
2829
2830         # The device number in SCRATCH_DEV_POOL should be at least 3,
2831         # one is SCRATCH_DEV, one is to be replaced, one is free device
2832         # we won't replace SCRATCH_DEV, see below for reason
2833         if [ "`echo $SCRATCH_DEV_POOL | wc -w`" -lt 3 ]; then
2834                 echo "_btrfs_stress_replace requires at least 3 devices in SCRATCH_DEV_POOL"
2835                 return
2836         fi
2837
2838         # take the last device as the first free_dev
2839         local free_dev="`echo $SCRATCH_DEV_POOL | $AWK_PROG '{print $NF}'`"
2840
2841         # free_dev should be really free
2842         if $BTRFS_UTIL_PROG filesystem show $btrfs_mnt | grep -q "$free_dev"; then
2843                 echo "_btrfs_stress_replace: $free_dev is used by btrfs"
2844                 return
2845         fi
2846
2847         # dev_pool is device list being currently used by btrfs (excluding SCRATCH_DEV)
2848         # and can be replaced. We don't replace SCRATCH_DEV because it will be used in
2849         # _scratch_mount and _check_scratch_fs etc.
2850         local dev_pool=`echo $SCRATCH_DEV_POOL | sed -e "s# *$SCRATCH_DEV *##" \
2851                         -e "s# *$free_dev *##"`
2852
2853         # set the first device in dev_pool as the first src_dev to be replaced
2854         local src_dev=`echo $dev_pool | $AWK_PROG '{print $1}'`
2855
2856         echo "dev_pool=$dev_pool"
2857         echo "free_dev=$free_dev, src_dev=$src_dev"
2858         while true; do
2859                 echo "Replacing $src_dev with $free_dev"
2860                 $BTRFS_UTIL_PROG replace start -fB $src_dev $free_dev $btrfs_mnt
2861                 if [ $? -ne 0 ]; then
2862                         # don't update src_dev and free_dev if replace failed
2863                         continue
2864                 fi
2865                 dev_pool="$dev_pool $free_dev"
2866                 dev_pool=`echo $dev_pool | sed -e "s# *$src_dev *##"`
2867                 free_dev=$src_dev
2868                 src_dev=`echo $dev_pool | $AWK_PROG '{print $1}'`
2869         done
2870 }
2871
2872 # find the right option to force output in bytes, older versions of btrfs-progs
2873 # print that by default, newer print human readable numbers with unit suffix
2874 _btrfs_qgroup_units()
2875 {
2876         $BTRFS_UTIL_PROG qgroup show --help 2>&1 | grep -q -- --raw && echo "--raw"
2877 }
2878
2879 # return device size in kb
2880 _get_device_size()
2881 {
2882         grep `_short_dev $1` /proc/partitions | awk '{print $3}'
2883 }
2884
2885 # don't check dmesg log after test
2886 _disable_dmesg_check()
2887 {
2888         rm -f ${RESULT_DIR}/check_dmesg
2889 }
2890
2891 init_rc()
2892 {
2893         if [ "$iam" == new ]
2894         then
2895                 return
2896         fi
2897         # make some further configuration checks here
2898         if [ "$TEST_DEV" = ""  ]
2899         then
2900                 echo "common/rc: Error: \$TEST_DEV is not set"
2901                 exit 1
2902         fi
2903
2904         # if $TEST_DEV is not mounted, mount it now as XFS
2905         if [ -z "`_fs_type $TEST_DEV`" ]
2906         then
2907                 # $TEST_DEV is not mounted
2908                 if ! _test_mount
2909                 then
2910                         echo "common/rc: retrying test device mount with external set"
2911                         [ "$USE_EXTERNAL" != "yes" ] && export USE_EXTERNAL=yes
2912                         if ! _test_mount
2913                         then
2914                                 echo "common/rc: could not mount $TEST_DEV on $TEST_DIR"
2915                                 exit 1
2916                         fi
2917                 fi
2918         fi
2919
2920         if [ "`_fs_type $TEST_DEV`" != "$FSTYP" ]
2921         then
2922                 echo "common/rc: Error: \$TEST_DEV ($TEST_DEV) is not a MOUNTED $FSTYP filesystem"
2923                 $DF_PROG $TEST_DEV
2924                 exit 1
2925         fi
2926         # Figure out if we need to add -F ("foreign", deprecated) option to xfs_io
2927         xfs_io -c stat $TEST_DIR 2>&1 | grep -q "is not on an XFS filesystem" && \
2928         export XFS_IO_PROG="$XFS_IO_PROG -F"
2929
2930         # xfs_copy doesn't work on v5 xfs yet without -d option
2931         if [ "$FSTYP" == "xfs" ] && [[ $MKFS_OPTIONS =~ crc=1 ]]; then
2932                 export XFS_COPY_PROG="$XFS_COPY_PROG -d"
2933         fi
2934 }
2935
2936 # get real device path name by following link
2937 _real_dev()
2938 {
2939         local _dev=$1
2940         if [ -b "$_dev" ] && [ -L "$_dev" ]; then
2941                 _dev=`readlink -f "$_dev"`
2942         fi
2943         echo $_dev
2944 }
2945
2946 # basename of a device
2947 _short_dev()
2948 {
2949         echo `basename $(_real_dev $1)`
2950 }
2951
2952 get_block_size()
2953 {
2954         if [ -z $1 ] || [ ! -d $1 ]; then
2955                 echo "Missing mount point argument for get_block_size"
2956                 exit 1
2957         fi
2958         echo `stat -f -c %S $1`
2959 }
2960
2961 init_rc
2962
2963 ################################################################################
2964 # make sure this script returns success
2965 /bin/true