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