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