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