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