common/rc: fix fsmap check
[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     overlay)
151          ;;
152     reiser4)
153          [ "$MKFS_REISER4_PROG" = "" ] && _fatal "mkfs.reiser4 not found"
154          ;;
155 esac
156
157 # make sure we have a standard umask
158 umask 022
159
160 _mount()
161 {
162     $MOUNT_PROG `_mount_ops_filter $*`
163 }
164
165 _scratch_options()
166 {
167     type=$1
168     SCRATCH_OPTIONS=""
169
170     if [ "$FSTYP" != "xfs" ]; then
171         return
172     fi
173
174     case $type in
175     mkfs)
176         [ "$HOSTOS" != "IRIX" ] && SCRATCH_OPTIONS="$SCRATCH_OPTIONS -f"
177         rt_opt="-r"
178         log_opt="-l"
179         ;;
180     mount)
181         rt_opt="-o"
182         log_opt="-o"
183         ;;
184     esac
185     [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_RTDEV" ] && \
186         SCRATCH_OPTIONS="$SCRATCH_OPTIONS ${rt_opt}rtdev=$SCRATCH_RTDEV"
187     [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_LOGDEV" ] && \
188         SCRATCH_OPTIONS="$SCRATCH_OPTIONS ${log_opt}logdev=$SCRATCH_LOGDEV"
189 }
190
191 _test_options()
192 {
193     type=$1
194     TEST_OPTIONS=""
195
196     if [ "$FSTYP" != "xfs" ]; then
197         return
198     fi
199
200     case $type in
201     mkfs)
202         rt_opt="-r"
203         log_opt="-l"
204         ;;
205     mount)
206         rt_opt="-o"
207         log_opt="-o"
208         ;;
209     esac
210     [ "$USE_EXTERNAL" = yes -a ! -z "$TEST_RTDEV" ] && \
211         TEST_OPTIONS="$TEST_OPTIONS ${rt_opt}rtdev=$TEST_RTDEV"
212     [ "$USE_EXTERNAL" = yes -a ! -z "$TEST_LOGDEV" ] && \
213         TEST_OPTIONS="$TEST_OPTIONS ${log_opt}logdev=$TEST_LOGDEV"
214 }
215
216 _mount_ops_filter()
217 {
218     params="$*"
219     
220     #get mount point to handle dmapi mtpt option correctly
221     let last_index=$#-1
222     [ $last_index -gt 0 ] && shift $last_index
223     FS_ESCAPED=$1
224     
225     # irix is fussy about how it is fed its mount options
226     # - multiple -o's are not allowed
227     # - no spaces between comma delimitered options
228     # the sed script replaces all -o's (except the first) with a comma
229     # not required for linux, but won't hurt
230     
231     echo $params | sed -e 's/[[:space:]]\+-o[[:space:]]*/UnIqUe/1; s/[[:space:]]\+-o[[:space:]]*/,/g; s/UnIqUe/ -o /1' \
232         | sed -e 's/dmapi/dmi/' \
233         | $PERL_PROG -ne "s#mtpt=[^,|^\n|^\s]*#mtpt=$FS_ESCAPED\1\2#; print;"
234
235 }
236
237 # Used for mounting non-scratch devices (e.g. loop, dm constructs)
238 # with the safe set of scratch mount options (e.g. loop image may be
239 # hosted on $SCRATCH_DEV, so can't use external scratch devices).
240 _common_dev_mount_options()
241 {
242         echo $MOUNT_OPTIONS $SELINUX_MOUNT_OPTIONS $*
243 }
244
245 _overlay_basic_mount_options()
246 {
247         echo "-o lowerdir=$1/$OVERLAY_LOWER_DIR,upperdir=$1/$OVERLAY_UPPER_DIR,workdir=$1/$OVERLAY_WORK_DIR"
248 }
249
250 _overlay_mount_options()
251 {
252         echo `_common_dev_mount_options` \
253              `_overlay_basic_mount_options $1` \
254              $OVERLAY_MOUNT_OPTIONS
255 }
256
257 _scratch_mount_options()
258 {
259         _scratch_options mount
260
261         if [ "$FSTYP" == "overlay" ]; then
262                 echo `_overlay_mount_options $SCRATCH_DEV`
263                 return 0
264         fi
265         echo `_common_dev_mount_options $*` $SCRATCH_OPTIONS \
266                                         $SCRATCH_DEV $SCRATCH_MNT
267 }
268
269 # helper function to do the actual overlayfs mount operation
270 _overlay_mount_dirs()
271 {
272         local lowerdir=$1
273         local upperdir=$2
274         local workdir=$3
275         shift 3
276
277         $MOUNT_PROG -t overlay -o lowerdir=$lowerdir -o upperdir=$upperdir \
278                     -o workdir=$workdir $*
279 }
280
281 # Given a dir, set up 3 subdirectories and mount on the given mnt.
282 # The dir is used as the mount device so it can be seen from df or mount
283 _overlay_mount()
284 {
285         local dir=$1
286         local mnt=$2
287         shift 2
288
289         local upper_fst=$(df --output=fstype $dir | tail -1)
290         case "$upper_fst" in
291         xfs)
292                 if ! xfs_info $dir | grep -q "ftype=1" ; then
293                         _notrun "upper fs needs to support d_type"
294                 fi
295                 ;;
296         ext2|ext3|ext4)
297                 if ! tune2fs -l $(df --output=source $dir | tail -1) | \
298                    grep -q filetype ; then
299                         _notrun "upper fs needs to support d_type"
300                 fi
301                 ;;
302         esac
303
304         mkdir -p $dir/$OVERLAY_UPPER_DIR
305         mkdir -p $dir/$OVERLAY_LOWER_DIR
306         mkdir -p $dir/$OVERLAY_WORK_DIR
307
308         _overlay_mount_dirs $dir/$OVERLAY_LOWER_DIR $dir/$OVERLAY_UPPER_DIR \
309                             $dir/$OVERLAY_WORK_DIR $OVERLAY_MOUNT_OPTIONS \
310                             $SELINUX_MOUNT_OPTIONS $* $dir $mnt
311 }
312
313 _overlay_test_mount()
314 {
315         _overlay_mount $TEST_DEV $TEST_DIR $*
316 }
317
318 _overlay_scratch_mount()
319 {
320         _overlay_mount $SCRATCH_DEV $SCRATCH_MNT $*
321 }
322
323 _overlay_test_unmount()
324 {
325         $UMOUNT_PROG $TEST_DIR
326 }
327
328 _overlay_scratch_unmount()
329 {
330         $UMOUNT_PROG $SCRATCH_MNT
331 }
332
333 _scratch_mount()
334 {
335     if [ "$FSTYP" == "overlay" ]; then
336         _overlay_scratch_mount $*
337         return $?
338     fi
339     _mount -t $FSTYP `_scratch_mount_options $*`
340 }
341
342 _scratch_unmount()
343 {
344         case "$FSTYP" in
345         overlay)
346                 _overlay_scratch_unmount
347                 ;;
348         btrfs)
349                 $UMOUNT_PROG $SCRATCH_MNT
350                 ;;
351         *)
352                 $UMOUNT_PROG $SCRATCH_DEV
353                 ;;
354         esac
355 }
356
357 _scratch_remount()
358 {
359     local opts="$1"
360
361     if test -n "$opts"; then
362         mount -o "remount,$opts" $SCRATCH_MNT
363     fi
364 }
365
366 _scratch_cycle_mount()
367 {
368     local opts="$1"
369
370     if [ "$FSTYP" = tmpfs ]; then
371         _scratch_remount "$opts"
372         return
373     fi
374     if test -n "$opts"; then
375         opts="-o $opts"
376     fi
377     _scratch_unmount
378     _scratch_mount "$opts"
379 }
380
381 _test_mount()
382 {
383     if [ "$FSTYP" == "overlay" ]; then
384         _overlay_test_mount $*
385         return $?
386     fi
387     _test_options mount
388     _mount -t $FSTYP $TEST_OPTIONS $TEST_FS_MOUNT_OPTS $SELINUX_MOUNT_OPTIONS $* $TEST_DEV $TEST_DIR
389 }
390
391 _test_unmount()
392 {
393         if [ "$FSTYP" == "overlay" ]; then
394                 _overlay_test_unmount
395         else
396                 $UMOUNT_PROG $TEST_DEV
397         fi
398 }
399
400 _test_cycle_mount()
401 {
402     if [ "$FSTYP" = tmpfs ]; then
403         return
404     fi
405     _test_unmount
406     _test_mount
407 }
408
409 _scratch_mkfs_options()
410 {
411     _scratch_options mkfs
412     echo $SCRATCH_OPTIONS $MKFS_OPTIONS $* $SCRATCH_DEV
413 }
414
415 _scratch_metadump()
416 {
417         dumpfile=$1
418         options=
419
420         [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_LOGDEV" ] && \
421                 options="-l $SCRATCH_LOGDEV"
422
423         xfs_metadump $options $SCRATCH_DEV $dumpfile
424 }
425
426 _setup_large_xfs_fs()
427 {
428         fs_size=$1
429         local tmp_dir=/tmp/
430
431         [ "$LARGE_SCRATCH_DEV" != yes ] && return 0
432         [ -z "$SCRATCH_DEV_EMPTY_SPACE" ] && SCRATCH_DEV_EMPTY_SPACE=0
433         [ $SCRATCH_DEV_EMPTY_SPACE -ge $fs_size ] && return 0
434
435         # calculate the size of the file we need to allocate.
436         # Default free space in the FS is 50GB, but you can specify more via
437         # SCRATCH_DEV_EMPTY_SPACE
438         file_size=$(($fs_size - 50*1024*1024*1024))
439         file_size=$(($file_size - $SCRATCH_DEV_EMPTY_SPACE))
440
441         # mount the filesystem, create the file, unmount it
442         _scratch_mount 2>&1 >$tmp_dir/mnt.err
443         local status=$?
444         if [ $status -ne 0 ]; then
445                 echo "mount failed"
446                 cat $tmp_dir/mnt.err >&2
447                 rm -f $tmp_dir/mnt.err
448                 return $status
449         fi
450         rm -f $tmp_dir/mnt.err
451
452         xfs_io -F -f \
453                 -c "truncate $file_size" \
454                 -c "falloc -k 0 $file_size" \
455                 -c "chattr +d" \
456                 $SCRATCH_MNT/.use_space 2>&1 > /dev/null
457         export NUM_SPACE_FILES=1
458         status=$?
459         _scratch_unmount
460         if [ $status -ne 0 ]; then
461                 echo "large file prealloc failed"
462                 cat $tmp_dir/mnt.err >&2
463                 return $status
464         fi
465         return 0
466 }
467
468 _scratch_mkfs_xfs_opts()
469 {
470         mkfs_opts=$*
471
472         # remove metadata related mkfs options if mkfs.xfs doesn't them
473         if [ -n "$XFS_MKFS_HAS_NO_META_SUPPORT" ]; then
474                 mkfs_opts=`echo $mkfs_opts | sed "s/-m\s\+\S\+//g"`
475         fi
476
477         _scratch_options mkfs
478
479         $MKFS_XFS_PROG $SCRATCH_OPTIONS $mkfs_opts $SCRATCH_DEV
480 }
481
482
483 _scratch_mkfs_xfs_supported()
484 {
485         local mkfs_opts=$*
486
487         _scratch_options mkfs
488
489         $MKFS_XFS_PROG -N $MKFS_OPTIONS $SCRATCH_OPTIONS $mkfs_opts $SCRATCH_DEV
490         local mkfs_status=$?
491
492         # a mkfs failure may be caused by conflicts between $MKFS_OPTIONS and
493         # $mkfs_opts, try again without $MKFS_OPTIONS
494         if [ $mkfs_status -ne 0 -a -n "$mkfs_opts" ]; then
495                 $MKFS_XFS_PROG -N $SCRATCH_OPTIONS $mkfs_opts $SCRATCH_DEV
496                 mkfs_status=$?
497         fi
498         return $mkfs_status
499 }
500
501 _scratch_mkfs_xfs()
502 {
503         # extra mkfs options can be added by tests
504         local extra_mkfs_options=$*
505
506         local tmp_dir=/tmp/
507
508         # save mkfs output in case conflict means we need to run again.
509         # only the output for the mkfs that applies should be shown
510         _scratch_mkfs_xfs_opts $MKFS_OPTIONS $extra_mkfs_options \
511                 2>$tmp_dir.mkfserr 1>$tmp_dir.mkfsstd
512         local mkfs_status=$?
513
514
515         # a mkfs failure may be caused by conflicts between
516         # $MKFS_OPTIONS and $extra_mkfs_options
517         if [ $mkfs_status -ne 0 -a ! -z "$extra_mkfs_options" ]; then
518                 (
519                 echo -n "** mkfs failed with extra mkfs options "
520                 echo "added to \"$MKFS_OPTIONS\" by test $seq **"
521                 echo -n "** attempting to mkfs using only test $seq "
522                 echo "options: $extra_mkfs_options **"
523                 ) >> $seqres.full
524
525                 # running mkfs again. overwrite previous mkfs output files
526                 _scratch_mkfs_xfs_opts $extra_mkfs_options \
527                         2>$tmp_dir.mkfserr 1>$tmp_dir.mkfsstd
528                 local mkfs_status=$?
529         fi
530
531         if [ $mkfs_status -eq 0 -a "$LARGE_SCRATCH_DEV" = yes ]; then
532                 # manually parse the mkfs output to get the fs size in bytes
533                 local fs_size
534                 fs_size=`cat $tmp_dir.mkfsstd | perl -ne '
535                         if (/^data\s+=\s+bsize=(\d+)\s+blocks=(\d+)/) {
536                                 my $size = $1 * $2;
537                                 print STDOUT "$size\n";
538                         }'`
539                 _setup_large_xfs_fs $fs_size
540                 mkfs_status=$?
541         fi
542
543         # output stored mkfs output, filtering unnecessary warnings from stderr
544         cat $tmp_dir.mkfsstd
545         cat $tmp_dir.mkfserr | sed \
546                 -e '/less than device physical sector/d' \
547                 -e '/switching to logical sector/d' \
548                 >&2
549         rm -f $tmp_dir.mkfserr $tmp_dir.mkfsstd
550
551         return $mkfs_status
552 }
553
554 # xfs_check script is planned to be deprecated. But, we want to
555 # be able to invoke "xfs_check" behavior in xfstests in order to
556 # maintain the current verification levels.
557 _xfs_check()
558 {
559     OPTS=" "
560     DBOPTS=" "
561     USAGE="Usage: xfs_check [-fsvV] [-l logdev] [-i ino]... [-b bno]... special"
562
563     while getopts "b:fi:l:stvV" c
564     do
565         case $c in
566             s) OPTS=$OPTS"-s ";;
567             t) OPTS=$OPTS"-t ";;
568             v) OPTS=$OPTS"-v ";;
569             i) OPTS=$OPTS"-i "$OPTARG" ";;
570             b) OPTS=$OPTS"-b "$OPTARG" ";;
571             f) DBOPTS=$DBOPTS" -f";;
572             l) DBOPTS=$DBOPTS" -l "$OPTARG" ";;
573             V) $XFS_DB_PROG -p xfs_check -V
574                 return $?
575                 ;;
576         esac
577     done
578     set -- extra $@
579     shift $OPTIND
580     case $# in
581         1)    ${XFS_DB_PROG}${DBOPTS} -F -i -p xfs_check -c "check$OPTS" $1
582                status=$?
583                ;;
584         2)    echo $USAGE 1>&1
585               status=2
586               ;;
587     esac
588     return $status
589 }
590
591 _setup_large_ext4_fs()
592 {
593         fs_size=$1
594         local tmp_dir=/tmp/
595
596         [ "$LARGE_SCRATCH_DEV" != yes ] && return 0
597         [ -z "$SCRATCH_DEV_EMPTY_SPACE" ] && SCRATCH_DEV_EMPTY_SPACE=0
598         [ $SCRATCH_DEV_EMPTY_SPACE -ge $fs_size ] && return 0
599
600         # Default free space in the FS is 50GB, but you can specify more via
601         # SCRATCH_DEV_EMPTY_SPACE
602         space_to_consume=$(($fs_size - 50*1024*1024*1024 - $SCRATCH_DEV_EMPTY_SPACE))
603
604         # mount the filesystem and create 16TB - 4KB files until we consume
605         # all the necessary space.
606         _scratch_mount 2>&1 >$tmp_dir/mnt.err
607         local status=$?
608         if [ $status -ne 0 ]; then
609                 echo "mount failed"
610                 cat $tmp_dir/mnt.err >&2
611                 rm -f $tmp_dir/mnt.err
612                 return $status
613         fi
614         rm -f $tmp_dir/mnt.err
615
616         file_size=$((16*1024*1024*1024*1024 - 4096))
617         nfiles=0
618         while [ $space_to_consume -gt $file_size ]; do
619
620                 xfs_io -F -f \
621                         -c "truncate $file_size" \
622                         -c "falloc -k 0 $file_size" \
623                         $SCRATCH_MNT/.use_space.$nfiles 2>&1
624                 status=$?
625                 if [ $status -ne 0 ]; then
626                         break;
627                 fi
628
629                 space_to_consume=$(( $space_to_consume - $file_size ))
630                 nfiles=$(($nfiles + 1))
631         done
632
633         # consume the remaining space.
634         if [ $space_to_consume -gt 0 ]; then
635                 xfs_io -F -f \
636                         -c "truncate $space_to_consume" \
637                         -c "falloc -k 0 $space_to_consume" \
638                         $SCRATCH_MNT/.use_space.$nfiles 2>&1
639                 status=$?
640         fi
641         export NUM_SPACE_FILES=$nfiles
642
643         _scratch_unmount
644         if [ $status -ne 0 ]; then
645                 echo "large file prealloc failed"
646                 cat $tmp_dir/mnt.err >&2
647                 return $status
648         fi
649         return 0
650 }
651
652 _scratch_mkfs_ext4()
653 {
654         # extra mkfs options can be added by tests
655         local extra_mkfs_options=$*
656
657         local tmp_dir=/tmp/
658
659         $MKFS_EXT4_PROG -F $MKFS_OPTIONS $extra_mkfs_options $SCRATCH_DEV \
660                         2>$tmp_dir.mkfserr 1>$tmp_dir.mkfsstd
661         local mkfs_status=$?
662
663         # a mkfs failure may be caused by conflicts between
664         # $MKFS_OPTIONS and $extra_mkfs_options
665         if [ $mkfs_status -ne 0 -a ! -z "$extra_mkfs_options" ]; then
666                 (
667                 echo -n "** mkfs failed with extra mkfs options "
668                 echo "added to \"$MKFS_OPTIONS\" by test $seq **"
669                 echo -n "** attempting to mkfs using only test $seq "
670                 echo "options: $extra_mkfs_options **"
671                 ) >> $seqres.full
672
673                 # running mkfs again. overwrite previous mkfs output files
674                 $MKFS_EXT4_PROG -F $extra_mkfs_options $SCRATCH_DEV \
675                                 2>$tmp_dir.mkfserr 1>$tmp_dir.mkfsstd
676                 local mkfs_status=$?
677         fi
678
679         if [ $mkfs_status -eq 0 -a "$LARGE_SCRATCH_DEV" = yes ]; then
680                 # manually parse the mkfs output to get the fs size in bytes
681                 fs_size=`cat $tmp_dir.mkfsstd | awk ' \
682                         /^Block size/ { split($2, a, "="); bs = a[2] ; } \
683                         / inodes, / { blks = $3 } \
684                         /reserved for the super user/ { resv = $1 } \
685                         END { fssize = bs * blks - resv; print fssize }'`
686
687                 _setup_large_ext4_fs $fs_size
688                 mkfs_status=$?
689         fi
690
691         # output stored mkfs output
692         grep -v -e ^Warning: -e "^mke2fs " $tmp_dir.mkfserr >&2
693         cat $tmp_dir.mkfsstd
694         rm -f $tmp_dir.mkfserr $tmp_dir.mkfsstd
695
696         return $mkfs_status
697 }
698
699 _test_mkfs()
700 {
701     case $FSTYP in
702     nfs*)
703         # do nothing for nfs
704         ;;
705     cifs)
706         # do nothing for cifs
707         ;;
708     overlay)
709         # do nothing for overlay
710         ;;
711     udf)
712         $MKFS_UDF_PROG $MKFS_OPTIONS $* $TEST_DEV > /dev/null
713         ;;
714     btrfs)
715         $MKFS_BTRFS_PROG $MKFS_OPTIONS $* $TEST_DEV > /dev/null
716         ;;
717     ext2|ext3|ext4)
718         $MKFS_PROG -t $FSTYP -- -F $MKFS_OPTIONS $* $TEST_DEV
719         ;;
720     *)
721         yes | $MKFS_PROG -t $FSTYP -- $MKFS_OPTIONS $* $TEST_DEV
722         ;;
723     esac
724 }
725
726 _mkfs_dev()
727 {
728     case $FSTYP in
729     nfs*)
730         # do nothing for nfs
731         ;;
732     overlay)
733         # do nothing for overlay
734         ;;
735     udf)
736         $MKFS_UDF_PROG $MKFS_OPTIONS $* 2>$tmp_dir.mkfserr 1>$tmp_dir.mkfsstd
737         ;;
738     btrfs)
739         $MKFS_BTRFS_PROG $MKFS_OPTIONS $* 2>$tmp_dir.mkfserr 1>$tmp_dir.mkfsstd
740         ;;
741     ext2|ext3|ext4)
742         $MKFS_PROG -t $FSTYP -- -F $MKFS_OPTIONS $* \
743                 2>$tmp_dir.mkfserr 1>$tmp_dir.mkfsstd
744         ;;
745
746     *)
747         yes | $MKFS_PROG -t $FSTYP -- $MKFS_OPTIONS $* \
748                 2>$tmp_dir.mkfserr 1>$tmp_dir.mkfsstd
749         ;;
750     esac
751
752     if [ $? -ne 0 ]; then
753         # output stored mkfs output
754         cat $tmp_dir.mkfserr >&2
755         cat $tmp_dir.mkfsstd
756         status=1
757         exit 1
758     fi
759     rm -f $tmp_dir.mkfserr $tmp_dir.mkfsstd
760 }
761
762 # remove all files in $SCRATCH_MNT, useful when testing on NFS/CIFS
763 _scratch_cleanup_files()
764 {
765         case $FSTYP in
766         overlay)
767                 # $SCRATCH_DEV is a valid directory in overlay case
768                 rm -rf $SCRATCH_DEV/*
769                 ;;
770         *)
771                 _scratch_mount
772                 rm -rf $SCRATCH_MNT/*
773                 _scratch_unmount
774                 ;;
775         esac
776 }
777
778 _scratch_mkfs()
779 {
780     case $FSTYP in
781     xfs)
782         _scratch_mkfs_xfs $*
783         ;;
784     nfs*)
785         # unable to re-create NFS, just remove all files in $SCRATCH_MNT to
786         # avoid EEXIST caused by the leftover files created in previous runs
787         _scratch_cleanup_files
788         ;;
789     cifs)
790         # unable to re-create CIFS, just remove all files in $SCRATCH_MNT to
791         # avoid EEXIST caused by the leftover files created in previous runs
792         _scratch_cleanup_files
793         ;;
794     overlay)
795         # unable to re-create overlay, remove all files in $SCRATCH_MNT to
796         # avoid EEXIST caused by the leftover files created in previous runs
797         _scratch_cleanup_files
798         ;;
799     udf)
800         $MKFS_UDF_PROG $MKFS_OPTIONS $* $SCRATCH_DEV > /dev/null
801         ;;
802     btrfs)
803         $MKFS_BTRFS_PROG $MKFS_OPTIONS $* $SCRATCH_DEV > /dev/null
804         ;;
805     ext2|ext3)
806         $MKFS_PROG -t $FSTYP -- -F $MKFS_OPTIONS $* $SCRATCH_DEV
807         ;;
808     ext4)
809         _scratch_mkfs_ext4 $*
810         ;;
811     tmpfs)
812         # do nothing for tmpfs
813         ;;
814     f2fs)
815         $MKFS_F2FS_PROG $MKFS_OPTIONS $* $SCRATCH_DEV > /dev/null
816         ;;
817     *)
818         yes | $MKFS_PROG -t $FSTYP -- $MKFS_OPTIONS $* $SCRATCH_DEV
819         ;;
820     esac
821 }
822
823 # Helper function to get a spare or replace-target device from
824 # configured SCRATCH_DEV_POLL, must call _scratch_dev_pool_get()
825 # before _spare_dev_get(). Replace-target-device/Spare-device will
826 # be assigned to SPARE_DEV.
827 # As of now only one replace-target-device/spare-device can be
828 # assigned.
829 #
830 # Usage:
831 #  _scratch_dev_pool_get() <ndevs>
832 #     _spare_dev_get()
833 #     :: do stuff
834 #     _spare_dev_put()
835 #  _scratch_dev_pool_put()
836 #
837 _spare_dev_get()
838 {
839         typeset -p SCRATCH_DEV_POOL_SAVED >/dev/null 2>&1
840         if [ $? -ne 0 ]; then
841                 _fail "Bug: unset val, must call _scratch_dev_pool_get before _spare_dev_get"
842         fi
843
844         if [ -z "$SCRATCH_DEV_POOL_SAVED" ]; then
845                 _fail "Bug: str empty, must call _scratch_dev_pool_get before _spare_dev_get"
846         fi
847
848         # Check if the spare is already assigned
849         typeset -p SPARE_DEV >/dev/null 2>&1
850         if [ $? -eq 0 ]; then
851                 if [ ! -z "$SPARE_DEV" ]; then
852                         _fail "Bug: SPARE_DEV = $SPARE_DEV already assigned"
853                 fi
854         fi
855
856         local ndevs=`echo $SCRATCH_DEV_POOL| wc -w`
857         local config_ndevs=`echo $SCRATCH_DEV_POOL_SAVED| wc -w`
858
859         if [ $ndevs -eq $config_ndevs ]; then
860                 _notrun "All devs used no spare"
861         fi
862         # Get a dev that is not used
863         local devs[]="( $SCRATCH_DEV_POOL_SAVED )"
864         SPARE_DEV=${devs[@]:$ndevs:1}
865         export SPARE_DEV
866 }
867
868 _spare_dev_put()
869 {
870         typeset -p SPARE_DEV >/dev/null 2>&1
871         if [ $? -ne 0 ]; then
872                 _fail "Bug: unset val, must call _spare_dev_get before its put"
873         fi
874
875         if [ -z "$SPARE_DEV" ]; then
876                 _fail "Bug: str empty, must call _spare_dev_get before its put"
877         fi
878
879         export SPARE_DEV=""
880 }
881
882 #
883 # Generally test cases will have..
884 #   _require_scratch_dev_pool X
885 # to make sure it has the enough scratch devices including
886 # replace-target and spare device. Now arg1 here is the
887 # required number of scratch devices by a-test-case excluding
888 # the replace-target and spare device. So this function will
889 # set SCRATCH_DEV_POOL to the specified number of devices.
890 #
891 # Usage:
892 #  _scratch_dev_pool_get() <ndevs>
893 #     :: do stuff
894 #
895 #  _scratch_dev_pool_put()
896 #
897 _scratch_dev_pool_get()
898 {
899         if [ $# -ne 1 ]; then
900                 _fail "Usage: _scratch_dev_pool_get ndevs"
901         fi
902
903         local test_ndevs=$1
904         local config_ndevs=`echo $SCRATCH_DEV_POOL| wc -w`
905         local devs[]="( $SCRATCH_DEV_POOL )"
906
907         typeset -p config_ndevs >/dev/null 2>&1
908         if [ $? -ne 0 ]; then
909                 _fail "Bug: cant find SCRATCH_DEV_POOL ndevs"
910         fi
911
912         if [ $config_ndevs -lt $test_ndevs ]; then
913                 _notrun "Need at least test requested number of ndevs $test_ndevs"
914         fi
915
916         SCRATCH_DEV_POOL_SAVED=${SCRATCH_DEV_POOL}
917         export SCRATCH_DEV_POOL_SAVED
918         SCRATCH_DEV_POOL=${devs[@]:0:$test_ndevs}
919         export SCRATCH_DEV_POOL
920 }
921
922 _scratch_dev_pool_put()
923 {
924         typeset -p SCRATCH_DEV_POOL_SAVED >/dev/null 2>&1
925         if [ $? -ne 0 ]; then
926                 _fail "Bug: unset val, must call _scratch_dev_pool_get before _scratch_dev_pool_put"
927         fi
928
929         if [ -z "$SCRATCH_DEV_POOL_SAVED" ]; then
930                 _fail "Bug: str empty, must call _scratch_dev_pool_get before _scratch_dev_pool_put"
931         fi
932
933         export SCRATCH_DEV_POOL=$SCRATCH_DEV_POOL_SAVED
934         export SCRATCH_DEV_POOL_SAVED=""
935 }
936
937 _scratch_pool_mkfs()
938 {
939     case $FSTYP in
940     btrfs)
941         # if dup profile is in mkfs options call _scratch_mkfs instead
942         # because dup profile only works with single device
943         if [[ "$*" =~ dup ]]; then
944             _scratch_mkfs $*
945         else
946             $MKFS_BTRFS_PROG $MKFS_OPTIONS $* $SCRATCH_DEV_POOL > /dev/null
947         fi
948         ;;
949     *)
950         echo "_scratch_pool_mkfs is not implemented for $FSTYP" 1>&2
951         ;;
952     esac
953 }
954
955 # Return the amount of free memory available on the system
956 _free_memory_bytes()
957 {
958     free -b | grep ^Mem | awk '{print $4}'
959 }
960
961 # Create fs of certain size on scratch device
962 # _scratch_mkfs_sized <size in bytes> [optional blocksize]
963 _scratch_mkfs_sized()
964 {
965     fssize=$1
966     blocksize=$2
967
968     case $FSTYP in
969     xfs)
970         def_blksz=`echo $MKFS_OPTIONS|sed -rn 's/.*-b ?size= ?+([0-9]+).*/\1/p'`
971         ;;
972     ext2|ext3|ext4|ext4dev|udf|btrfs|reiser4)
973         def_blksz=`echo $MKFS_OPTIONS| sed -rn 's/.*-b ?+([0-9]+).*/\1/p'`
974         ;;
975     esac
976
977     [ -n "$def_blksz" ] && blocksize=$def_blksz
978     [ -z "$blocksize" ] && blocksize=4096
979
980
981     re='^[0-9]+$'
982     if ! [[ $fssize =~ $re ]] ; then
983         _notrun "error: _scratch_mkfs_sized: fs size \"$fssize\" not an integer."
984     fi
985     if ! [[ $blocksize =~ $re ]] ; then
986         _notrun "error: _scratch_mkfs_sized: block size \"$blocksize\" not an integer."
987     fi
988
989     blocks=`expr $fssize / $blocksize`
990
991     if [ "$HOSTOS" == "Linux" -a -b "$SCRATCH_DEV" ]; then
992         devsize=`blockdev --getsize64 $SCRATCH_DEV`
993         [ "$fssize" -gt "$devsize" ] && _notrun "Scratch device too small"
994     fi
995
996     case $FSTYP in
997     xfs)
998         # don't override MKFS_OPTIONS that set a block size.
999         echo $MKFS_OPTIONS |egrep -q "b?size="
1000         if [ $? -eq 0 ]; then
1001                 _scratch_mkfs_xfs -d size=$fssize
1002         else
1003                 _scratch_mkfs_xfs -d size=$fssize -b size=$blocksize
1004         fi
1005         ;;
1006     ext2|ext3|ext4|ext4dev)
1007         ${MKFS_PROG}.$FSTYP -F $MKFS_OPTIONS -b $blocksize $SCRATCH_DEV $blocks
1008         ;;
1009     udf)
1010         $MKFS_UDF_PROG $MKFS_OPTIONS -b $blocksize $SCRATCH_DEV $blocks
1011         ;;
1012     btrfs)
1013         local mixed_opt=
1014         (( fssize <= 100 * 1024 * 1024 )) && mixed_opt='--mixed'
1015         $MKFS_BTRFS_PROG $MKFS_OPTIONS $mixed_opt -b $fssize $SCRATCH_DEV
1016         ;;
1017     reiser4)
1018         # mkfs.resier4 requires size in KB as input for creating filesystem
1019         $MKFS_REISER4_PROG $MKFS_OPTIONS -y -b $blocksize $SCRATCH_DEV \
1020                            `expr $fssize / 1024`
1021         ;;
1022     f2fs)
1023         # mkfs.f2fs requires # of sectors as an input for the size
1024         sector_size=`blockdev --getss $SCRATCH_DEV`
1025         $MKFS_F2FS_PROG $MKFS_OPTIONS $SCRATCH_DEV `expr $fssize / $sector_size`
1026         ;;
1027     tmpfs)
1028         free_mem=`_free_memory_bytes`
1029         if [ "$free_mem" -lt "$fssize" ] ; then
1030            _notrun "Not enough memory ($free_mem) for tmpfs with $fssize bytes"
1031         fi
1032         export MOUNT_OPTIONS="-o size=$fssize $TMPFS_MOUNT_OPTIONS"
1033         ;;
1034     *)
1035         _notrun "Filesystem $FSTYP not supported in _scratch_mkfs_sized"
1036         ;;
1037     esac
1038 }
1039
1040 # Emulate an N-data-disk stripe w/ various stripe units
1041 # _scratch_mkfs_geom <sunit bytes> <swidth multiplier> [optional blocksize]
1042 _scratch_mkfs_geom()
1043 {
1044     sunit_bytes=$1
1045     swidth_mult=$2
1046     blocksize=$3
1047     [ -z "$blocksize" ] && blocksize=4096
1048
1049     let sunit_blocks=$sunit_bytes/$blocksize
1050     let swidth_blocks=$sunit_blocks*$swidth_mult
1051
1052     case $FSTYP in
1053     xfs)
1054         MKFS_OPTIONS+=" -b size=$blocksize, -d su=$sunit_bytes,sw=$swidth_mult"
1055         ;;
1056     ext4|ext4dev)
1057         MKFS_OPTIONS+=" -b $blocksize -E stride=$sunit_blocks,stripe_width=$swidth_blocks"
1058         ;;
1059     *)
1060         _notrun "can't mkfs $FSTYP with geometry"
1061         ;;
1062     esac
1063     _scratch_mkfs
1064 }
1065
1066 # Create fs of certain blocksize on scratch device
1067 # _scratch_mkfs_blocksized blocksize
1068 _scratch_mkfs_blocksized()
1069 {
1070     blocksize=$1
1071
1072     re='^[0-9]+$'
1073     if ! [[ $blocksize =~ $re ]] ; then
1074         _notrun "error: _scratch_mkfs_sized: block size \"$blocksize\" not an integer."
1075     fi
1076
1077     case $FSTYP in
1078     xfs)
1079         _scratch_mkfs_xfs $MKFS_OPTIONS -b size=$blocksize
1080         ;;
1081     ext2|ext3|ext4|ocfs2)
1082         ${MKFS_PROG}.$FSTYP -F $MKFS_OPTIONS -b $blocksize $SCRATCH_DEV
1083         ;;
1084     *)
1085         _notrun "Filesystem $FSTYP not supported in _scratch_mkfs_blocksized"
1086         ;;
1087     esac
1088 }
1089
1090 _scratch_resvblks()
1091 {
1092         case $FSTYP in
1093         xfs)
1094                 xfs_io -x -c "resblks $1" $SCRATCH_MNT
1095                 ;;
1096         *)
1097                 ;;
1098         esac
1099 }
1100
1101 _scratch_xfs_db_options()
1102 {
1103     SCRATCH_OPTIONS=""
1104     [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_LOGDEV" ] && \
1105         SCRATCH_OPTIONS="-l$SCRATCH_LOGDEV"
1106     echo $SCRATCH_OPTIONS $* $SCRATCH_DEV
1107 }
1108
1109 _scratch_xfs_logprint()
1110 {
1111     SCRATCH_OPTIONS=""
1112     [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_LOGDEV" ] && \
1113         SCRATCH_OPTIONS="-l$SCRATCH_LOGDEV"
1114     $XFS_LOGPRINT_PROG $SCRATCH_OPTIONS $* $SCRATCH_DEV
1115 }
1116
1117 _test_xfs_logprint()
1118 {
1119         TEST_OPTIONS=""
1120         [ "$USE_EXTERNAL" = yes -a ! -z "$TEST_LOGDEV" ] && \
1121                 TEST_OPTIONS="-l$TEST_LOGDEV"
1122         $XFS_LOGPRINT_PROG $TEST_OPTIONS $* $TEST_DEV
1123 }
1124
1125 _scratch_xfs_check()
1126 {
1127     SCRATCH_OPTIONS=""
1128     [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_LOGDEV" ] && \
1129         SCRATCH_OPTIONS="-l $SCRATCH_LOGDEV"
1130     [ "$LARGE_SCRATCH_DEV" = yes ] && \
1131         SCRATCH_OPTIONS=$SCRATCH_OPTIONS" -t"
1132     _xfs_check $SCRATCH_OPTIONS $* $SCRATCH_DEV
1133 }
1134
1135 _scratch_xfs_repair()
1136 {
1137     SCRATCH_OPTIONS=""
1138     [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_LOGDEV" ] && \
1139         SCRATCH_OPTIONS="-l$SCRATCH_LOGDEV"
1140     [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_RTDEV" ] && \
1141         SCRATCH_OPTIONS=$SCRATCH_OPTIONS" -r$SCRATCH_RTDEV"
1142     [ "$LARGE_SCRATCH_DEV" = yes ] && SCRATCH_OPTIONS=$SCRATCH_OPTIONS" -t"
1143     $XFS_REPAIR_PROG $SCRATCH_OPTIONS $* $SCRATCH_DEV
1144 }
1145
1146 # Repair scratch filesystem.  Returns 0 if the FS is good to go (either no
1147 # errors found or errors were fixed) and nonzero otherwise; also spits out
1148 # a complaint on stderr if fsck didn't tell us that the FS is good to go.
1149 _repair_scratch_fs()
1150 {
1151     case $FSTYP in
1152     xfs)
1153         _scratch_xfs_repair "$@" 2>&1
1154         res=$?
1155         if [ "$res" -ne 0 ]; then
1156                 echo "xfs_repair returns $res; replay log?"
1157                 _scratch_mount
1158                 res=$?
1159                 if [ "$res" -gt 0 ]; then
1160                         echo "mount returns $res; zap log?"
1161                         _scratch_xfs_repair -L 2>&1
1162                         echo "log zap returns $?"
1163                 else
1164                         umount "$SCRATCH_MNT"
1165                 fi
1166                 _scratch_xfs_repair "$@" 2>&1
1167                 res=$?
1168         fi
1169         test $res -ne 0 && >&2 echo "xfs_repair failed, err=$res"
1170         return $res
1171         ;;
1172     *)
1173         # Let's hope fsck -y suffices...
1174         fsck -t $FSTYP -y $SCRATCH_DEV 2>&1
1175         res=$?
1176         case $res in
1177         0|1|2)
1178                 res=0
1179                 ;;
1180         *)
1181                 >&2 echo "fsck.$FSTYP failed, err=$res"
1182                 ;;
1183         esac
1184         return $res
1185         ;;
1186     esac
1187 }
1188
1189 _get_pids_by_name()
1190 {
1191     if [ $# -ne 1 ]
1192     then
1193         echo "Usage: _get_pids_by_name process-name" 1>&2
1194         exit 1
1195     fi
1196
1197     # Algorithm ... all ps(1) variants have a time of the form MM:SS or
1198     # HH:MM:SS before the psargs field, use this as the search anchor.
1199     #
1200     # Matches with $1 (process-name) occur if the first psarg is $1
1201     # or ends in /$1 ... the matching uses sed's regular expressions,
1202     # so passing a regex into $1 will work.
1203
1204     ps $PS_ALL_FLAGS \
1205     | sed -n \
1206         -e 's/$/ /' \
1207         -e 's/[         ][      ]*/ /g' \
1208         -e 's/^ //' \
1209         -e 's/^[^ ]* //' \
1210         -e "/[0-9]:[0-9][0-9]  *[^ ]*\/$1 /s/ .*//p" \
1211         -e "/[0-9]:[0-9][0-9]  *$1 /s/ .*//p"
1212 }
1213
1214 # fix malloc libs output
1215 #
1216 _fix_malloc()
1217 {
1218     # filter out the Electric Fence notice
1219     $PERL_PROG -e '
1220         while (<>) {
1221             if (defined $o && /^\s+Electric Fence/) {
1222                 chomp($o);
1223                 print "$o";
1224                 undef $o;
1225                 next;
1226             }
1227             print $o if (defined $o);
1228
1229             $o=$_;
1230         }
1231         print $o if (defined $o);
1232     '
1233 }
1234
1235 #
1236 # _df_device : get an IRIX style df line for a given device
1237 #
1238 #       - returns "" if not mounted
1239 #       - returns fs type in field two (ala IRIX)
1240 #       - joins line together if split by fancy df formatting
1241 #       - strips header etc
1242 #
1243
1244 _df_device()
1245 {
1246     if [ $# -ne 1 ]
1247     then
1248         echo "Usage: _df_device device" 1>&2
1249         exit 1
1250     fi
1251
1252     # Note that we use "==" here so awk doesn't try to interpret an NFS over
1253     # IPv6 server as a regular expression.
1254     $DF_PROG 2>/dev/null | $AWK_PROG -v what=$1 '
1255         ($1==what) && (NF==1) {
1256             v=$1
1257             getline
1258             print v, $0
1259             exit
1260         }
1261         ($1==what) {
1262             print
1263             exit
1264         }
1265     '
1266 }
1267
1268 #
1269 # _df_dir : get an IRIX style df line for device where a directory resides
1270 #
1271 #       - returns fs type in field two (ala IRIX)
1272 #       - joins line together if split by fancy df formatting
1273 #       - strips header etc
1274 #
1275
1276 _df_dir()
1277 {
1278     if [ $# -ne 1 ]
1279     then
1280         echo "Usage: _df_dir device" 1>&2
1281         exit 1
1282     fi
1283
1284     $DF_PROG $1 2>/dev/null | $AWK_PROG -v what=$1 '
1285         NR == 2 && NF==1 {
1286             v=$1
1287             getline
1288             print v, $0;
1289             exit 0
1290         }
1291         NR == 2 {
1292             print;
1293             exit 0
1294         }
1295         {}
1296     '
1297     # otherwise, nada
1298 }
1299
1300 # return percentage used disk space for mounted device
1301
1302 _used()
1303 {
1304     if [ $# -ne 1 ]
1305     then
1306         echo "Usage: _used device" 1>&2
1307         exit 1
1308     fi
1309
1310     _df_device $1 | $AWK_PROG '{ sub("%", "") ; print $6 }'
1311 }
1312
1313 # return the FS type of a mounted device
1314 #
1315 _fs_type()
1316 {
1317     if [ $# -ne 1 ]
1318     then
1319         echo "Usage: _fs_type device" 1>&2
1320         exit 1
1321     fi
1322
1323     #
1324     # The Linux kernel shows NFSv4 filesystems in df output as
1325     # filesystem type nfs4, although we mounted it as nfs earlier.
1326     # Fix the filesystem type up here so that the callers don't
1327     # have to bother with this quirk.
1328     #
1329     _df_device $1 | $AWK_PROG '{ print $2 }' | sed -e 's/nfs4/nfs/'
1330 }
1331
1332 # return the FS mount options of a mounted device
1333 #
1334 # should write a version which just parses the output of mount for IRIX
1335 # compatibility, but since this isn't used at all, at the moment I'll leave
1336 # this for now
1337 #
1338 _fs_options()
1339 {
1340     if [ $# -ne 1 ]
1341     then
1342         echo "Usage: _fs_options device" 1>&2
1343         exit 1
1344     fi
1345
1346     $AWK_PROG -v dev=$1 '
1347         match($1,dev) { print $4 }
1348     ' </proc/mounts
1349 }
1350
1351 # returns device number if a file is a block device
1352 #
1353 _is_block_dev()
1354 {
1355     if [ $# -ne 1 ]
1356     then
1357         echo "Usage: _is_block_dev dev" 1>&2
1358         exit 1
1359     fi
1360
1361     _dev=$1
1362     if [ -L "${_dev}" ]; then
1363         _dev=`readlink -f "${_dev}"`
1364     fi
1365
1366     if [ -b "${_dev}" ]; then
1367         src/lstat64 "${_dev}" | $AWK_PROG '/Device type:/ { print $9 }'
1368     fi
1369 }
1370
1371 # Do a command, log it to $seqres.full, optionally test return status
1372 # and die if command fails. If called with one argument _do executes the
1373 # command, logs it, and returns its exit status. With two arguments _do
1374 # first prints the message passed in the first argument, and then "done"
1375 # or "fail" depending on the return status of the command passed in the
1376 # second argument. If the command fails and the variable _do_die_on_error
1377 # is set to "always" or the two argument form is used and _do_die_on_error
1378 # is set to "message_only" _do will print an error message to
1379 # $seqres.out and exit.
1380
1381 _do()
1382 {
1383     if [ $# -eq 1 ]; then
1384         _cmd=$1
1385     elif [ $# -eq 2 ]; then
1386         _note=$1
1387         _cmd=$2
1388         echo -n "$_note... "
1389     else
1390         echo "Usage: _do [note] cmd" 1>&2
1391         status=1; exit
1392     fi
1393
1394     (eval "echo '---' \"$_cmd\"") >>$seqres.full
1395     (eval "$_cmd") >$tmp._out 2>&1; ret=$?
1396     cat $tmp._out | _fix_malloc >>$seqres.full
1397     if [ $# -eq 2 ]; then
1398         if [ $ret -eq 0 ]; then
1399             echo "done"
1400         else
1401             echo "fail"
1402         fi
1403     fi
1404     if [ $ret -ne 0  ] \
1405         && [ "$_do_die_on_error" = "always" \
1406             -o \( $# -eq 2 -a "$_do_die_on_error" = "message_only" \) ]
1407     then
1408         [ $# -ne 2 ] && echo
1409         eval "echo \"$_cmd\" failed \(returned $ret\): see $seqres.full"
1410         status=1; exit
1411     fi
1412
1413     return $ret
1414 }
1415
1416 # bail out, setting up .notrun file. Need to kill the filesystem check files
1417 # here, otherwise they are set incorrectly for the next test.
1418 #
1419 _notrun()
1420 {
1421     echo "$*" > $seqres.notrun
1422     echo "$seq not run: $*"
1423     rm -f ${RESULT_DIR}/require_test
1424     rm -f ${RESULT_DIR}/require_scratch
1425     status=0
1426     exit
1427 }
1428
1429 # just plain bail out
1430 #
1431 _fail()
1432 {
1433     echo "$*" | tee -a $seqres.full
1434     echo "(see $seqres.full for details)"
1435     status=1
1436     exit 1
1437 }
1438
1439 # tests whether $FSTYP is one of the supported filesystems for a test
1440 #
1441 _supported_fs()
1442 {
1443     for f
1444     do
1445         if [ "$f" = "$FSTYP" -o "$f" = "generic" ]
1446         then
1447             return
1448         fi
1449     done
1450
1451     _notrun "not suitable for this filesystem type: $FSTYP"
1452 }
1453
1454
1455 # tests whether $FSTYP is one of the supported OSes for a test
1456 #
1457 _supported_os()
1458 {
1459     for h
1460     do
1461         if [ "$h" = "$HOSTOS" ]
1462         then
1463             return
1464         fi
1465     done
1466
1467     _notrun "not suitable for this OS: $HOSTOS"
1468 }
1469
1470 _require_btrfs_loadable()
1471 {
1472         modprobe -r btrfs || _notrun "btrfs unloadable"
1473         modprobe btrfs || _notrun "Can't load btrfs"
1474 }
1475
1476 _reload_btrfs_ko()
1477 {
1478         modprobe -r btrfs || _fail "btrfs unload failed"
1479         modprobe btrfs || _fail "btrfs load failed"
1480 }
1481
1482 # this test needs a scratch partition - check we're ok & unmount it
1483 # No post-test check of the device is required. e.g. the test intentionally
1484 # finishes the test with the filesystem in a corrupt state
1485 _require_scratch_nocheck()
1486 {
1487     case "$FSTYP" in
1488         nfs*)
1489                 echo $SCRATCH_DEV | grep -q ":/" > /dev/null 2>&1
1490                 if [ -z "$SCRATCH_DEV" -o "$?" != "0" ]; then
1491                         _notrun "this test requires a valid \$SCRATCH_DEV"
1492                 fi
1493                 if [ ! -d "$SCRATCH_MNT" ]; then
1494                         _notrun "this test requires a valid \$SCRATCH_MNT"
1495                 fi
1496                 ;;
1497         cifs)
1498                 echo $SCRATCH_DEV | grep -q "//" > /dev/null 2>&1
1499                 if [ -z "$SCRATCH_DEV" -o "$?" != "0" ]; then
1500                         _notrun "this test requires a valid \$SCRATCH_DEV"
1501                 fi
1502                 if [ ! -d "$SCRATCH_MNT" ]; then
1503                      _notrun "this test requires a valid \$SCRATCH_MNT"
1504                 fi
1505                 ;;
1506         overlay)
1507                 if [ -z "$SCRATCH_DEV" -o ! -d "$SCRATCH_DEV" ]; then
1508                         _notrun "this test requires a valid \$SCRATCH_DEV as ovl base dir"
1509                 fi
1510                 if [ ! -d "$SCRATCH_MNT" ]; then
1511                         _notrun "this test requires a valid \$SCRATCH_MNT"
1512                 fi
1513                 ;;
1514         tmpfs)
1515                 if [ -z "$SCRATCH_DEV" -o ! -d "$SCRATCH_MNT" ];
1516                 then
1517                     _notrun "this test requires a valid \$SCRATCH_MNT and unique $SCRATCH_DEV"
1518                 fi
1519                 ;;
1520         *)
1521                  if [ -z "$SCRATCH_DEV" -o "`_is_block_dev "$SCRATCH_DEV"`" = "" ]
1522                  then
1523                      _notrun "this test requires a valid \$SCRATCH_DEV"
1524                  fi
1525                  if [ "`_is_block_dev "$SCRATCH_DEV"`" = "`_is_block_dev "$TEST_DEV"`" ]
1526                  then
1527                      _notrun "this test requires a valid \$SCRATCH_DEV"
1528                  fi
1529                 if [ ! -d "$SCRATCH_MNT" ]
1530                 then
1531                      _notrun "this test requires a valid \$SCRATCH_MNT"
1532                 fi
1533                  ;;
1534     esac
1535
1536     # mounted?
1537     # Note that we use -F here so grep doesn't try to interpret an NFS over
1538     # IPv6 server as a regular expression.
1539     mount_rec=`_mount | grep -F $SCRATCH_DEV`
1540     if [ "$mount_rec" ]
1541     then
1542         # if it's mounted, make sure its on $SCRATCH_MNT
1543         if ! echo $mount_rec | grep -q $SCRATCH_MNT
1544         then
1545             echo "\$SCRATCH_DEV=$SCRATCH_DEV is mounted but not on \$SCRATCH_MNT=$SCRATCH_MNT - aborting"
1546             echo "Already mounted result:"
1547             echo $mount_rec
1548             exit 1
1549         fi
1550         # and then unmount it
1551         if ! _scratch_unmount
1552         then
1553             echo "failed to unmount $SCRATCH_DEV"
1554             exit 1
1555         fi
1556     fi
1557     rm -f ${RESULT_DIR}/require_scratch
1558 }
1559
1560 # we need the scratch device and it should be checked post test.
1561 _require_scratch()
1562 {
1563         _require_scratch_nocheck
1564         touch ${RESULT_DIR}/require_scratch
1565 }
1566
1567
1568 # this test needs a test partition - check we're ok & mount it
1569 #
1570 _require_test()
1571 {
1572     case "$FSTYP" in
1573         nfs*)
1574                 echo $TEST_DEV | grep -q ":/" > /dev/null 2>&1
1575                 if [ -z "$TEST_DEV" -o "$?" != "0" ]; then
1576                         _notrun "this test requires a valid \$TEST_DIR"
1577                 fi
1578                 if [ ! -d "$TEST_DIR" ]; then
1579                         _notrun "this test requires a valid \$TEST_DIR"
1580                 fi
1581                 ;;
1582         cifs)
1583                 echo $TEST_DEV | grep -q "//" > /dev/null 2>&1
1584                 if [ -z "$TEST_DEV" -o "$?" != "0" ]; then
1585                         _notrun "this test requires a valid \$TEST_DEV"
1586                 fi
1587                 if [ ! -d "$TEST_DIR" ]; then
1588                      _notrun "this test requires a valid \$TEST_DIR"
1589                 fi
1590                 ;;
1591         overlay)
1592                 if [ -z "$TEST_DEV" -o ! -d "$TEST_DEV" ]; then
1593                         _notrun "this test requires a valid \$TEST_DEV as ovl base dir"
1594                 fi
1595                 if [ ! -d "$TEST_DIR" ]; then
1596                         _notrun "this test requires a valid \$TEST_DIR"
1597                 fi
1598                 ;;
1599         tmpfs)
1600                 if [ -z "$TEST_DEV" -o ! -d "$TEST_DIR" ];
1601                 then
1602                     _notrun "this test requires a valid \$TEST_DIR and unique $TEST_DEV"
1603                 fi
1604                 ;;
1605         *)
1606                  if [ -z "$TEST_DEV" ] || [ "`_is_block_dev "$TEST_DEV"`" = "" ]
1607                  then
1608                      _notrun "this test requires a valid \$TEST_DEV"
1609                  fi
1610                  if [ "`_is_block_dev "$SCRATCH_DEV"`" = "`_is_block_dev "$TEST_DEV"`" ]
1611                  then
1612                      _notrun "this test requires a valid \$TEST_DEV"
1613                  fi
1614                 if [ ! -d "$TEST_DIR" ]
1615                 then
1616                      _notrun "this test requires a valid \$TEST_DIR"
1617                 fi
1618                  ;;
1619     esac
1620
1621     # mounted?
1622     # Note that we use -F here so grep doesn't try to interpret an NFS over
1623     # IPv6 server as a regular expression.
1624     mount_rec=`_mount | grep -F $TEST_DEV`
1625     if [ "$mount_rec" ]
1626     then
1627         # if it's mounted, make sure its on $TEST_DIR
1628         if ! echo $mount_rec | grep -q $TEST_DIR
1629         then
1630             echo "\$TEST_DEV=$TEST_DEV is mounted but not on \$TEST_DIR=$TEST_DIR - aborting"
1631             echo "Already mounted result:"
1632             echo $mount_rec
1633             exit 1
1634         fi
1635     else
1636         out=`_mount_or_remount_rw "$MOUNT_OPTIONS" $TEST_DEV $TEST_DIR`
1637         if [ $? -ne 1 ]; then
1638                 echo $out
1639                 exit 1
1640         fi
1641     fi
1642     touch ${RESULT_DIR}/require_test
1643 }
1644
1645 # this test needs a logdev
1646 #
1647 _require_logdev()
1648 {
1649     [ -z "$SCRATCH_LOGDEV" -o ! -b "$SCRATCH_LOGDEV" ] && \
1650         _notrun "This test requires a valid \$SCRATCH_LOGDEV"
1651     [ "$USE_EXTERNAL" != yes ] && \
1652         _notrun "This test requires USE_EXTERNAL to be enabled"
1653
1654     # ensure its not mounted
1655     $UMOUNT_PROG $SCRATCH_LOGDEV 2>/dev/null
1656 }
1657
1658 # this test requires loopback device support
1659 #
1660 _require_loop()
1661 {
1662     if [ "$HOSTOS" != "Linux" ]
1663     then
1664         _notrun "This test requires linux for loopback device support"
1665     fi
1666
1667     modprobe loop >/dev/null 2>&1
1668     if grep loop /proc/devices >/dev/null 2>&1
1669     then
1670         :
1671     else
1672         _notrun "This test requires loopback device support"
1673     fi
1674 }
1675
1676 # this test requires ext2 filesystem support
1677 #
1678 _require_ext2()
1679 {
1680     if [ "$HOSTOS" != "Linux" ]
1681     then
1682         _notrun "This test requires linux for ext2 filesystem support"
1683     fi
1684
1685     modprobe ext2 >/dev/null 2>&1
1686     if grep ext2 /proc/filesystems >/dev/null 2>&1
1687     then
1688         :
1689     else
1690         _notrun "This test requires ext2 filesystem support"
1691     fi
1692 }
1693
1694 # this test requires that (large) loopback device files are not in use
1695 #
1696 _require_no_large_scratch_dev()
1697 {
1698     [ "$LARGE_SCRATCH_DEV" = yes ] && \
1699         _notrun "Large filesystem testing in progress, skipped this test"
1700 }
1701
1702 # this test requires that a realtime subvolume is in use, and
1703 # that the kernel supports realtime as well.
1704 #
1705 _require_realtime()
1706 {
1707     [ "$USE_EXTERNAL" = yes ] || \
1708         _notrun "External volumes not in use, skipped this test"
1709     [ "$SCRATCH_RTDEV" = "" ] && \
1710         _notrun "Realtime device required, skipped this test"
1711 }
1712
1713 # this test requires that a specified command (executable) exists
1714 # $1 - command, $2 - name for error message
1715 #
1716 # Note: the command string might have parameters, so strip them before checking
1717 # whether it is executable.
1718 _require_command()
1719 {
1720         if [ $# -eq 2 ]; then
1721                 _name="$2"
1722         elif [ $# -eq 1 ]; then
1723                 _name="$1"
1724         else
1725                 _fail "usage: _require_command <command> [<name>]"
1726         fi
1727
1728         _command=`echo "$1" | awk '{ print $1 }'`
1729         if [ ! -x "$_command" ]; then
1730                 _notrun "$_name utility required, skipped this test"
1731         fi
1732 }
1733
1734 # this test requires the device to be valid block device
1735 # $1 - device
1736 _require_block_device()
1737 {
1738         if [ -z "$1" ]; then
1739                 echo "Usage: _require_block_device <dev>" 1>&2
1740                 exit 1
1741         fi
1742         if [ "`_is_block_dev "$1"`" == "" ]; then
1743                 _notrun "require $1 to be valid block disk"
1744         fi
1745 }
1746
1747 # brd based ram disks erase the device when they receive a flush command when no
1748 # active references are present. This causes problems for DM devices sitting on
1749 # top of brd devices as DM doesn't hold active references to the brd device.
1750 _require_sane_bdev_flush()
1751 {
1752         echo $1 | grep -q "^/dev/ram[0-9]\+$"
1753         if [ $? -eq 0 ]; then
1754                 _notrun "This test requires a sane block device flush"
1755         fi
1756 }
1757
1758 # this test requires a specific device mapper target
1759 _require_dm_target()
1760 {
1761         _target=$1
1762
1763         # require SCRATCH_DEV to be a valid block device with sane BLKFLSBUF
1764         # behaviour
1765         _require_block_device $SCRATCH_DEV
1766         _require_sane_bdev_flush $SCRATCH_DEV
1767         _require_command "$DMSETUP_PROG" dmsetup
1768
1769         modprobe dm-$_target >/dev/null 2>&1
1770
1771         $DMSETUP_PROG targets 2>&1 | grep -q ^$_target
1772         if [ $? -ne 0 ]; then
1773                 _notrun "This test requires dm $_target support"
1774         fi
1775 }
1776
1777 # this test requires the projid32bit feature to be available in mkfs.xfs.
1778 #
1779 _require_projid32bit()
1780 {
1781        _scratch_mkfs_xfs_supported -i projid32bit=1 >/dev/null 2>&1 \
1782            || _notrun "mkfs.xfs doesn't have projid32bit feature"
1783 }
1784
1785 _require_projid16bit()
1786 {
1787         _scratch_mkfs_xfs_supported -i projid32bit=0 >/dev/null 2>&1 \
1788            || _notrun "16 bit project IDs not supported on $SCRATCH_DEV"
1789 }
1790
1791 # this test requires the crc feature to be available in mkfs.xfs
1792 #
1793 _require_xfs_mkfs_crc()
1794 {
1795         _scratch_mkfs_xfs_supported -m crc=1 >/dev/null 2>&1 \
1796            || _notrun "mkfs.xfs doesn't have crc feature"
1797 }
1798
1799 # this test requires the xfs kernel support crc feature
1800 #
1801 _require_xfs_crc()
1802 {
1803         _scratch_mkfs_xfs -m crc=1 >/dev/null 2>&1
1804         _scratch_mount >/dev/null 2>&1 \
1805            || _notrun "Kernel doesn't support crc feature"
1806         _scratch_unmount
1807 }
1808
1809 # this test requires the ext4 kernel support crc feature on scratch device
1810 #
1811 _require_scratch_ext4_crc()
1812 {
1813         _scratch_mkfs_ext4 >/dev/null 2>&1
1814         dumpe2fs -h $SCRATCH_DEV 2> /dev/null | grep -q metadata_csum || _notrun "metadata_csum not supported by this filesystem"
1815         _scratch_mount >/dev/null 2>&1 \
1816            || _notrun "Kernel doesn't support metadata_csum feature"
1817         _scratch_unmount
1818 }
1819
1820 # this test requires the xfs kernel support crc feature on scratch device
1821 #
1822 _require_scratch_xfs_crc()
1823 {
1824         _scratch_mkfs_xfs >/dev/null 2>&1
1825         _scratch_mount >/dev/null 2>&1 \
1826            || _notrun "Kernel doesn't support crc feature"
1827         xfs_info $SCRATCH_MNT | grep -q 'crc=1' || _notrun "crc feature not supported by this filesystem"
1828         _scratch_unmount
1829 }
1830
1831 # this test requires the bigalloc feature to be available in mkfs.ext4
1832 #
1833 _require_ext4_mkfs_bigalloc()
1834 {
1835         $MKFS_EXT4_PROG -F -O bigalloc -n $SCRATCH_DEV 512m >/dev/null 2>&1 \
1836            || _notrun "mkfs.ext4 doesn't have bigalloc feature"
1837 }
1838
1839 # this test requires the ext4 kernel support bigalloc feature
1840 #
1841 _require_ext4_bigalloc()
1842 {
1843         $MKFS_EXT4_PROG -F -O bigalloc $SCRATCH_DEV 512m >/dev/null 2>&1
1844         _scratch_mount >/dev/null 2>&1 \
1845            || _notrun "Ext4 kernel doesn't support bigalloc feature"
1846         _scratch_unmount
1847 }
1848
1849 # this test requires the finobt feature to be available in mkfs.xfs
1850 #
1851 _require_xfs_mkfs_finobt()
1852 {
1853         _scratch_mkfs_xfs_supported -m crc=1,finobt=1 >/dev/null 2>&1 \
1854            || _notrun "mkfs.xfs doesn't have finobt feature"
1855 }
1856
1857 # this test requires the xfs kernel support finobt feature
1858 #
1859 _require_xfs_finobt()
1860 {
1861         _scratch_mkfs_xfs -m crc=1,finobt=1 >/dev/null 2>&1
1862         _scratch_mount >/dev/null 2>&1 \
1863            || _notrun "Kernel doesn't support finobt feature"
1864         _scratch_unmount
1865 }
1866
1867 # this test requires xfs sysfs attribute support
1868 #
1869 _require_xfs_sysfs()
1870 {
1871         attr=$1
1872         sysfsdir=/sys/fs/xfs
1873
1874         if [ ! -e $sysfsdir ]; then
1875                 _notrun "no kernel support for XFS sysfs attributes"
1876         fi
1877
1878         if [ ! -z $1 ] && [ ! -e $sysfsdir/$attr ]; then
1879                 _notrun "sysfs attribute '$attr' is not supported"
1880         fi
1881 }
1882
1883 # this test requires the xfs sparse inode feature
1884 #
1885 _require_xfs_sparse_inodes()
1886 {
1887         _scratch_mkfs_xfs_supported -m crc=1 -i sparse > /dev/null 2>&1 \
1888                 || _notrun "mkfs.xfs does not support sparse inodes"
1889         _scratch_mkfs_xfs -m crc=1 -i sparse > /dev/null 2>&1
1890         _scratch_mount >/dev/null 2>&1 \
1891                 || _notrun "kernel does not support sparse inodes"
1892         _scratch_unmount
1893 }
1894
1895 # this test requires that external log/realtime devices are not in use
1896 #
1897 _require_nonexternal()
1898 {
1899     [ "$USE_EXTERNAL" = yes ] && \
1900         _notrun "External device testing in progress, skipped this test"
1901 }
1902
1903 # this test requires that a (specified) aio-dio executable exists
1904 # $1 - command (optional)
1905 #
1906 _require_aiodio()
1907 {
1908     if [ -z "$1" ]
1909     then
1910         AIO_TEST=src/aio-dio-regress/aiodio_sparse2
1911         [ -x $AIO_TEST ] || _notrun "aio-dio utilities required"
1912     else
1913         AIO_TEST=src/aio-dio-regress/$1
1914         [ -x $AIO_TEST ] || _notrun "$AIO_TEST not built"
1915     fi
1916     _require_odirect
1917 }
1918
1919 # this test requires that a test program exists under src/
1920 # $1 - command (require)
1921 #
1922 _require_test_program()
1923 {
1924     SRC_TEST=src/$1
1925     [ -x $SRC_TEST ] || _notrun "$SRC_TEST not built"
1926 }
1927
1928 # run an aio-dio program
1929 # $1 - command
1930 _run_aiodio()
1931 {
1932     if [ -z "$1" ]
1933     then
1934         echo "usage: _run_aiodio command_name" 2>&1
1935         status=1; exit 1
1936     fi
1937
1938     _require_aiodio $1
1939
1940     local testtemp=$TEST_DIR/aio-testfile
1941     rm -f $testtemp
1942     $AIO_TEST $testtemp 2>&1
1943     status=$?
1944     rm -f $testtemp
1945
1946     return $status
1947 }
1948
1949 # indicate whether YP/NIS is active or not
1950 #
1951 _yp_active()
1952 {
1953         local dn
1954         dn=$(domainname 2>/dev/null)
1955         test -n "${dn}" -a "${dn}" != "(none)"
1956         echo $?
1957 }
1958
1959 # cat the password file
1960 #
1961 _cat_passwd()
1962 {
1963         [ $(_yp_active) -eq 0 ] && ypcat passwd
1964         cat /etc/passwd
1965 }
1966
1967 # cat the group file
1968 #
1969 _cat_group()
1970 {
1971         [ $(_yp_active) -eq 0 ] && ypcat group
1972         cat /etc/group
1973 }
1974
1975 # check for a user on the machine, fsgqa as default
1976 #
1977 _require_user()
1978 {
1979     qa_user=fsgqa
1980     if [ -n "$1" ];then
1981         qa_user=$1
1982     fi
1983     _cat_passwd | grep -q $qa_user
1984     [ "$?" == "0" ] || _notrun "$qa_user user not defined."
1985     echo /bin/true | su $qa_user
1986     [ "$?" == "0" ] || _notrun "$qa_user cannot execute commands."
1987 }
1988
1989 # check for a group on the machine, fsgqa as default
1990 #
1991 _require_group()
1992 {
1993     qa_group=fsgqa
1994     if [ -n "$1" ];then
1995         qa_group=$1
1996     fi
1997     _cat_group | grep -q $qa_group
1998     [ "$?" == "0" ] || _notrun "$qa_group user not defined."
1999 }
2000
2001 _filter_user_do()
2002 {
2003         perl -ne "
2004 s,.*Permission\sdenied.*,Permission denied,;
2005 s,.*no\saccess\sto\stty.*,,;
2006 s,.*no\sjob\scontrol\sin\sthis\sshell.*,,;
2007 s,^\s*$,,;
2008         print;"
2009 }
2010
2011 _user_do()
2012 {
2013     if [ "$HOSTOS" == "IRIX" ]
2014         then
2015         echo $1 | /bin/bash "su $qa_user 2>&1" | _filter_user_do
2016     else
2017         echo $1 | su $qa_user 2>&1 | _filter_user_do
2018     fi
2019 }
2020
2021 _require_xfs_io_command()
2022 {
2023         if [ -z "$1" ]
2024         then
2025                 echo "Usage: _require_xfs_io_command command [switch]" 1>&2
2026                 exit 1
2027         fi
2028         command=$1
2029         shift
2030         param="$*"
2031
2032         testfile=$TEST_DIR/$$.xfs_io
2033         case $command in
2034         "falloc" )
2035                 testio=`$XFS_IO_PROG -F -f -c "falloc 0 1m" $testfile 2>&1`
2036                 ;;
2037         "fpunch" | "fcollapse" | "zero" | "fzero" | "finsert" )
2038                 testio=`$XFS_IO_PROG -F -f -c "pwrite 0 20k" -c "fsync" \
2039                         -c "$command 4k 8k" $testfile 2>&1`
2040                 ;;
2041         "fiemap")
2042                 testio=`$XFS_IO_PROG -F -f -c "pwrite 0 20k" -c "fsync" \
2043                         -c "fiemap -v" $testfile 2>&1`
2044                 ;;
2045         "flink" )
2046                 testio=`$XFS_IO_PROG -T -F -c "flink $testfile" \
2047                         $TEST_DIR 2>&1`
2048                 echo $testio | egrep -q "invalid option|Is a directory" && \
2049                         _notrun "xfs_io $command support is missing"
2050                 ;;
2051         "fsmap" )
2052                 testio=`$XFS_IO_PROG -f -c "fsmap" $testfile 2>&1`
2053                 echo $testio | egrep -q "Inappropriate ioctl" && \
2054                         _notrun "xfs_io $command support is missing"
2055                 ;;
2056         *)
2057                 testio=`$XFS_IO_PROG -c "$command help" 2>&1`
2058         esac
2059
2060         rm -f $testfile 2>&1 > /dev/null
2061         echo $testio | grep -q "not found" && \
2062                 _notrun "xfs_io $command support is missing"
2063         echo $testio | grep -q "Operation not supported" && \
2064                 _notrun "xfs_io $command failed (old kernel/wrong fs?)"
2065
2066         test -z "$param" && return
2067         $XFS_IO_PROG -c "help $command" | grep -q "^ $param --" || \
2068                 _notrun "xfs_io $command doesn't support $param"
2069 }
2070
2071 # check that xfs_db supports a specific command
2072 _require_xfs_db_command()
2073 {
2074         if [ $# -ne 1 ]
2075         then
2076                 echo "Usage: _require_xfs_db_command command" 1>&2
2077                 exit 1
2078         fi
2079         command=$1
2080
2081         $XFS_DB_PROG -x -c "help" $SCRATCH_DEV | grep $command > /dev/null || \
2082                 _notrun "xfs_db $command support is missing"
2083 }
2084
2085 # check that kernel and filesystem support direct I/O
2086 _require_odirect()
2087 {
2088         if [ $FSTYP = "ext4" ] ; then
2089                 if echo "$MOUNT_OPTIONS" | grep -q "test_dummy_encryption"; then
2090                         _notrun "ext4 encryption doesn't support O_DIRECT"
2091                 fi
2092         fi
2093         testfile=$TEST_DIR/$$.direct
2094         $XFS_IO_PROG -F -f -d -c "pwrite 0 20k" $testfile > /dev/null 2>&1
2095         if [ $? -ne 0 ]; then
2096                 _notrun "O_DIRECT is not supported"
2097         fi
2098         rm -f $testfile 2>&1 > /dev/null
2099 }
2100
2101 # Check that a fs has enough free space (in 1024b blocks)
2102 #
2103 _require_fs_space()
2104 {
2105         MNT=$1
2106         BLOCKS=$2       # in units of 1024
2107         let GB=$BLOCKS/1024/1024
2108
2109         FREE_BLOCKS=`df -kP $MNT | grep -v Filesystem | awk '{print $4}'`
2110         [ $FREE_BLOCKS -lt $BLOCKS ] && \
2111                 _notrun "This test requires at least ${GB}GB free on $MNT to run"
2112 }
2113
2114 #
2115 # Check if the filesystem supports sparse files.
2116 #
2117 # Unfortunately there is no better way to do this than a manual black list.
2118 #
2119 _require_sparse_files()
2120 {
2121     case $FSTYP in
2122     hfsplus)
2123         _notrun "Sparse files not supported by this filesystem type: $FSTYP"
2124         ;;
2125     *)
2126         ;;
2127     esac
2128 }
2129
2130 _require_debugfs()
2131 {
2132     #boot_params always present in debugfs
2133     [ -d "$DEBUGFS_MNT/boot_params" ] || _notrun "Debugfs not mounted"
2134 }
2135
2136 _require_fail_make_request()
2137 {
2138     [ -f "$DEBUGFS_MNT/fail_make_request/probability" ] \
2139         || _notrun "$DEBUGFS_MNT/fail_make_request \
2140  not found. Seems that CONFIG_FAIL_MAKE_REQUEST kernel config option not enabled"
2141 }
2142
2143 #
2144 # Check if the file system supports seek_data/hole
2145 #
2146 _require_seek_data_hole()
2147 {
2148     testfile=$TEST_DIR/$$.seek
2149     testseek=`$here/src/seek_sanity_test -t $testfile 2>&1`
2150     rm -f $testfile &>/dev/null
2151     echo $testseek | grep -q "Kernel does not support" && \
2152         _notrun "File system does not support llseek(2) SEEK_DATA/HOLE"
2153 }
2154
2155 _require_runas()
2156 {
2157         _require_test_program "runas"
2158 }
2159
2160 _runas()
2161 {
2162         "$here/src/runas" "$@"
2163 }
2164
2165 _require_richacl_prog()
2166 {
2167         _require_command "$GETRICHACL_PROG" getrichacl
2168         _require_command "$SETRICHACL_PROG" setrichacl
2169 }
2170
2171 _require_scratch_richacl_xfs()
2172 {
2173         _scratch_mkfs_xfs_supported -m richacl=1 >/dev/null 2>&1 \
2174                 || _notrun "mkfs.xfs doesn't have richacl feature"
2175         _scratch_mkfs_xfs -m richacl=1 >/dev/null 2>&1
2176         _scratch_mount >/dev/null 2>&1 \
2177                 || _notrun "kernel doesn't support richacl feature on $FSTYP"
2178         _scratch_unmount
2179 }
2180
2181 _require_scratch_richacl_ext4()
2182 {
2183         _scratch_mkfs -O richacl >/dev/null 2>&1 \
2184                 || _notrun "can't mkfs $FSTYP with option -O richacl"
2185         _scratch_mount >/dev/null 2>&1 \
2186                 || _notrun "kernel doesn't support richacl feature on $FSTYP"
2187         _scratch_unmount
2188 }
2189
2190 _require_scratch_richacl_support()
2191 {
2192         _scratch_mount
2193         $GETFATTR_PROG -n system.richacl >/dev/null 2>&1 \
2194                 || _notrun "this test requires richacl support on \$SCRATCH_DEV"
2195         _scratch_unmount
2196 }
2197
2198 _require_scratch_richacl()
2199 {
2200         case "$FSTYP" in
2201         xfs)    _require_scratch_richacl_xfs
2202                 ;;
2203         ext4)   _require_scratch_richacl_ext4
2204                 ;;
2205         nfs*|cifs|overlay)
2206                 _require_scratch_richacl_support
2207                 ;;
2208         *)      _notrun "this test requires richacl support on \$SCRATCH_DEV"
2209                 ;;
2210         esac
2211 }
2212
2213 _scratch_mkfs_richacl()
2214 {
2215         case "$FSTYP" in
2216         xfs)    _scratch_mkfs_xfs -m richacl=1
2217                 ;;
2218         ext4)   _scratch_mkfs -O richacl
2219                 ;;
2220         nfs*|cifs|overlay)
2221                 _scratch_mkfs
2222                 ;;
2223         esac
2224 }
2225
2226 # check that a FS on a device is mounted
2227 # if so, return mount point
2228 #
2229 _is_mounted()
2230 {
2231     if [ $# -ne 1 ]
2232     then
2233         echo "Usage: _is_mounted device" 1>&2
2234         exit 1
2235     fi
2236
2237     device=$1
2238
2239     if _mount | grep "$device " | $AWK_PROG -v pattern="type $FSTYP" '
2240         pattern        { print $3 ; exit 0 }
2241         END            { exit 1 }
2242     '
2243     then
2244         echo "_is_mounted: $device is not a mounted $FSTYP FS"
2245         exit 1
2246     fi
2247 }
2248
2249 # remount a FS to a new mode (ro or rw)
2250 #
2251 _remount()
2252 {
2253     if [ $# -ne 2 ]
2254     then
2255         echo "Usage: _remount device ro/rw" 1>&2
2256         exit 1
2257     fi
2258     device=$1
2259     mode=$2
2260
2261     if ! mount -o remount,$mode $device
2262     then
2263         echo "_remount: failed to remount filesystem on $device as $mode"
2264         exit 1
2265     fi
2266 }
2267
2268 # Run the appropriate repair/check on a filesystem
2269 #
2270 # if the filesystem is mounted, it's either remounted ro before being
2271 # checked or it's unmounted and then remounted
2272 #
2273
2274 # If set, we remount ro instead of unmounting for fsck
2275 USE_REMOUNT=0
2276
2277 _umount_or_remount_ro()
2278 {
2279     if [ $# -ne 1 ]
2280     then
2281         echo "Usage: _umount_or_remount_ro <device>" 1>&2
2282         exit 1
2283     fi
2284
2285     device=$1
2286     mountpoint=`_is_mounted $device`
2287
2288     if [ $USE_REMOUNT -eq 0 ]; then
2289         $UMOUNT_PROG $device
2290     else
2291         _remount $device ro
2292     fi
2293     echo "$mountpoint"
2294 }
2295
2296 _mount_or_remount_rw()
2297 {
2298         if [ $# -ne 3 ]; then
2299                 echo "Usage: _mount_or_remount_rw <opts> <dev> <mnt>" 1>&2
2300                 exit 1
2301         fi
2302         mount_opts=$1
2303         device=$2
2304         mountpoint=$3
2305
2306         if [ $USE_REMOUNT -eq 0 ]; then
2307                 if [ "$FSTYP" != "overlay" ]; then
2308                         _mount -t $FSTYP $mount_opts $device $mountpoint
2309                 else
2310                         _overlay_mount $device $mountpoint
2311                 fi
2312                 if [ $? -ne 0 ]; then
2313                         echo "!!! failed to remount $device on $mountpoint"
2314                         return 0 # ok=0
2315                 fi
2316         else
2317                 _remount $device rw
2318         fi
2319
2320         return 1 # ok=1
2321 }
2322
2323 # Check a generic filesystem in no-op mode; this assumes that the
2324 # underlying fsck program accepts "-n" for a no-op (check-only) run,
2325 # and that it will still return an errno for corruption in this mode.
2326 #
2327 # Filesystems which don't support this will need to define their
2328 # own check routine.
2329 #
2330 _check_generic_filesystem()
2331 {
2332     device=$1
2333
2334     # If type is set, we're mounted
2335     type=`_fs_type $device`
2336     ok=1
2337
2338     if [ "$type" = "$FSTYP" ]
2339     then
2340         # mounted ...
2341         mountpoint=`_umount_or_remount_ro $device`
2342     fi
2343
2344     fsck -t $FSTYP $FSCK_OPTIONS $device >$tmp.fsck 2>&1
2345     if [ $? -ne 0 ]
2346     then
2347         echo "_check_generic_filesystem: filesystem on $device is inconsistent (see $seqres.full)"
2348
2349         echo "_check_generic filesystem: filesystem on $device is inconsistent" >>$seqres.full
2350         echo "*** fsck.$FSTYP output ***"       >>$seqres.full
2351         cat $tmp.fsck                           >>$seqres.full
2352         echo "*** end fsck.$FSTYP output"       >>$seqres.full
2353
2354         ok=0
2355     fi
2356     rm -f $tmp.fsck
2357
2358     if [ $ok -eq 0 ]
2359     then
2360         echo "*** mount output ***"             >>$seqres.full
2361         _mount                                  >>$seqres.full
2362         echo "*** end mount output"             >>$seqres.full
2363     elif [ "$type" = "$FSTYP" ]
2364     then
2365         # was mounted ...
2366         _mount_or_remount_rw "$MOUNT_OPTIONS" $device $mountpoint
2367         ok=$?
2368     fi
2369
2370     if [ $ok -eq 0 ]; then
2371         status=1
2372         if [ "$iam" != "check" ]; then
2373                 exit 1
2374         fi
2375         return 1
2376     fi
2377
2378     return 0
2379 }
2380
2381 # run xfs_check and friends on a FS.
2382
2383 _check_xfs_filesystem()
2384 {
2385     if [ $# -ne 3 ]
2386     then
2387         echo "Usage: _check_xfs_filesystem device <logdev>|none <rtdev>|none" 1>&2
2388         exit 1
2389     fi
2390
2391     extra_mount_options=""
2392     extra_log_options=""
2393     extra_options=""
2394     device=$1
2395     if [ -f $device ];then
2396        extra_options="-f"
2397     fi
2398
2399     if [ "$2" != "none" ]; then
2400         extra_log_options="-l$2"
2401         extra_mount_options="-ologdev=$2"
2402     fi
2403
2404     if [ "$3" != "none" ]; then
2405         extra_rt_options="-r$3"
2406         extra_mount_options=$extra_mount_options" -ortdev=$3"
2407     fi
2408     extra_mount_options=$extra_mount_options" $MOUNT_OPTIONS"
2409
2410     [ "$FSTYP" != xfs ] && return 0
2411
2412     type=`_fs_type $device`
2413     ok=1
2414
2415     if [ "$type" = "xfs" ]
2416     then
2417         if [ -n "$TEST_XFS_SCRUB" ] && [ -x "$XFS_SCRUB_PROG" ]; then
2418             "$XFS_SCRUB_PROG" $scrubflag -vd $device >>$seqres.full
2419             if [ $? -ne 0 ]; then
2420                 echo "filesystem on $device failed scrub (see $seqres.full)"
2421                 ok=0
2422             fi
2423         fi
2424         # mounted ...
2425         mountpoint=`_umount_or_remount_ro $device`
2426     fi
2427
2428     $XFS_LOGPRINT_PROG -t $extra_log_options $device 2>&1 \
2429                 | tee $tmp.logprint | grep -q "<CLEAN>"
2430     if [ $? -ne 0 -a "$HOSTOS" = "Linux" ]
2431     then
2432         echo "_check_xfs_filesystem: filesystem on $device has dirty log (see $seqres.full)"
2433
2434         echo "_check_xfs_filesystem: filesystem on $device has dirty log"   >>$seqres.full
2435         echo "*** xfs_logprint -t output ***"   >>$seqres.full
2436         cat $tmp.logprint                       >>$seqres.full
2437         echo "*** end xfs_logprint output"      >>$seqres.full
2438
2439         ok=0
2440     fi
2441
2442     # xfs_check runs out of memory on large files, so even providing the test
2443     # option (-t) to avoid indexing the free space trees doesn't make it pass on
2444     # large filesystems. Avoid it.
2445     if [ "$LARGE_SCRATCH_DEV" != yes ]; then
2446             _xfs_check $extra_log_options $device 2>&1 |\
2447                  _fix_malloc >$tmp.fs_check
2448     fi
2449     if [ -s $tmp.fs_check ]
2450     then
2451         echo "_check_xfs_filesystem: filesystem on $device is inconsistent (c) (see $seqres.full)"
2452
2453         echo "_check_xfs_filesystem: filesystem on $device is inconsistent" >>$seqres.full
2454         echo "*** xfs_check output ***"         >>$seqres.full
2455         cat $tmp.fs_check                       >>$seqres.full
2456         echo "*** end xfs_check output"         >>$seqres.full
2457
2458         ok=0
2459     fi
2460
2461     $XFS_REPAIR_PROG -n $extra_options $extra_log_options $extra_rt_options $device >$tmp.repair 2>&1
2462     if [ $? -ne 0 ]
2463     then
2464         echo "_check_xfs_filesystem: filesystem on $device is inconsistent (r) (see $seqres.full)"
2465
2466         echo "_check_xfs_filesystem: filesystem on $device is inconsistent" >>$seqres.full
2467         echo "*** xfs_repair -n output ***"     >>$seqres.full
2468         cat $tmp.repair | _fix_malloc           >>$seqres.full
2469         echo "*** end xfs_repair output"        >>$seqres.full
2470
2471         ok=0
2472     fi
2473     rm -f $tmp.fs_check $tmp.logprint $tmp.repair
2474
2475     # Optionally test the index rebuilding behavior.
2476     if [ -n "$TEST_XFS_REPAIR_REBUILD" ]; then
2477         $XFS_REPAIR_PROG $extra_options $extra_log_options $extra_rt_options $device >$tmp.repair 2>&1
2478         if [ $? -ne 0 ]; then
2479             echo "_check_xfs_filesystem: filesystem on $device is inconsistent (rebuild) (see $seqres.full)"
2480
2481             echo "_check_xfs_filesystem: filesystem on $device is inconsistent (rebuild)" >>$seqres.full
2482             echo "*** xfs_repair output ***"    >>$seqres.full
2483             cat $tmp.repair | _fix_malloc               >>$seqres.full
2484             echo "*** end xfs_repair output"    >>$seqres.full
2485
2486             ok=0
2487         fi
2488         rm -f $tmp.repair
2489
2490         $XFS_REPAIR_PROG -n $extra_options $extra_log_options $extra_rt_options $device >$tmp.repair 2>&1
2491         if [ $? -ne 0 ]; then
2492             echo "_check_xfs_filesystem: filesystem on $device is inconsistent (rebuild-reverify) (see $seqres.full)"
2493
2494             echo "_check_xfs_filesystem: filesystem on $device is inconsistent (rebuild-reverify)" >>$seqres.full
2495             echo "*** xfs_repair -n output ***" >>$seqres.full
2496             cat $tmp.repair | _fix_malloc               >>$seqres.full
2497             echo "*** end xfs_repair output"    >>$seqres.full
2498
2499             ok=0
2500         fi
2501         rm -f $tmp.repair
2502     fi
2503
2504     if [ $ok -eq 0 ]
2505     then
2506         echo "*** mount output ***"             >>$seqres.full
2507         _mount                                  >>$seqres.full
2508         echo "*** end mount output"             >>$seqres.full
2509     elif [ "$type" = "xfs" ]
2510     then
2511         _mount_or_remount_rw "$extra_mount_options" $device $mountpoint
2512     fi
2513
2514     if [ $ok -eq 0 ]; then
2515         status=1
2516         if [ "$iam" != "check" ]; then
2517                 exit 1
2518         fi
2519         return 1
2520     fi
2521
2522     return 0
2523 }
2524
2525 # Filter the knowen errors the UDF Verifier reports.
2526 _udf_test_known_error_filter()
2527 {
2528         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."
2529
2530 }
2531
2532 _check_udf_filesystem()
2533 {
2534     [ "$DISABLE_UDF_TEST" == "1" ] && return
2535
2536     if [ $# -ne 1 -a $# -ne 2 ]
2537     then
2538         echo "Usage: _check_udf_filesystem device [last_block]" 1>&2
2539         exit 1
2540     fi
2541
2542     if [ ! -x $here/src/udf_test ]
2543     then
2544         echo "udf_test not installed, please download and build the Philips"
2545         echo "UDF Verification Software from http://www.extra.research.philips.com/udf/."
2546         echo "Then copy the udf_test binary to $here/src/."
2547         echo "If you do not wish to run udf_test then set environment variable DISABLE_UDF_TEST"
2548         echo "to 1."
2549         return
2550     fi
2551
2552     device=$1
2553     if [ $# -eq 2 ];
2554     then
2555         LAST_BLOCK=`expr \( $2 - 1 \)`
2556         OPT_ARG="-lastvalidblock $LAST_BLOCK"
2557     fi
2558
2559     rm -f $seqres.checkfs
2560     sleep 1 # Due to a problem with time stamps in udf_test
2561     $here/src/udf_test $OPT_ARG $device | tee $seqres.checkfs | egrep "Error|Warning" | \
2562         _udf_test_known_error_filter | \
2563         egrep -iv "Error count:.*[0-9]+.*total occurrences:.*[0-9]+|Warning count:.*[0-9]+.*total occurrences:.*[0-9]+" && \
2564         echo "Warning UDF Verifier reported errors see $seqres.checkfs." && return 1
2565     return 0
2566 }
2567
2568 _check_xfs_test_fs()
2569 {
2570     TEST_LOG="none"
2571     TEST_RT="none"
2572     [ "$USE_EXTERNAL" = yes -a ! -z "$TEST_LOGDEV" ] && \
2573         TEST_LOG="$TEST_LOGDEV"
2574
2575     [ "$USE_EXTERNAL" = yes -a ! -z "$TEST_RTDEV" ] && \
2576         TEST_RT="$TEST_RTDEV"
2577
2578     _check_xfs_filesystem $TEST_DEV $TEST_LOG $TEST_RT
2579
2580     # check for ipath consistency
2581     if $XFS_GROWFS_PROG -n $TEST_DIR | grep -q 'inode-paths=1'; then
2582         # errors go to stderr
2583         xfs_check_ipaths $TEST_DIR >/dev/null
2584         xfs_repair_ipaths -n $TEST_DIR >/dev/null
2585     fi
2586 }
2587
2588 _check_btrfs_filesystem()
2589 {
2590     device=$1
2591
2592     # If type is set, we're mounted
2593     type=`_fs_type $device`
2594     ok=1
2595
2596     if [ "$type" = "$FSTYP" ]
2597     then
2598         # mounted ...
2599         mountpoint=`_umount_or_remount_ro $device`
2600     fi
2601
2602     btrfsck $device >$tmp.fsck 2>&1
2603     if [ $? -ne 0 ]
2604     then
2605         echo "_check_btrfs_filesystem: filesystem on $device is inconsistent (see $seqres.full)"
2606
2607         echo "_check_btrfs_filesystem: filesystem on $device is inconsistent" >>$seqres.full
2608         echo "*** fsck.$FSTYP output ***"       >>$seqres.full
2609         cat $tmp.fsck                           >>$seqres.full
2610         echo "*** end fsck.$FSTYP output"       >>$seqres.full
2611
2612         ok=0
2613     fi
2614     rm -f $tmp.fsck
2615
2616     if [ $ok -eq 0 ]
2617     then
2618         echo "*** mount output ***"             >>$seqres.full
2619         _mount                                  >>$seqres.full
2620         echo "*** end mount output"             >>$seqres.full
2621     elif [ "$type" = "$FSTYP" ]
2622     then
2623         # was mounted ...
2624         _mount_or_remount_rw "$MOUNT_OPTIONS" $device $mountpoint
2625         ok=$?
2626     fi
2627
2628     if [ $ok -eq 0 ]; then
2629         status=1
2630         if [ "$iam" != "check" ]; then
2631                 exit 1
2632         fi
2633         return 1
2634     fi
2635
2636     return 0
2637 }
2638
2639 _check_test_fs()
2640 {
2641     case $FSTYP in
2642     xfs)
2643         _check_xfs_test_fs
2644         ;;
2645     nfs)
2646         # no way to check consistency for nfs
2647         ;;
2648     cifs)
2649         # no way to check consistency for cifs
2650         ;;
2651     overlay)
2652         # no way to check consistency for overlay
2653         ;;
2654     udf)
2655         # do nothing for now
2656         ;;
2657     btrfs)
2658         _check_btrfs_filesystem $TEST_DEV
2659         ;;
2660     tmpfs)
2661         # no way to check consistency for tmpfs
2662         ;;
2663     *)
2664         _check_generic_filesystem $TEST_DEV
2665         ;;
2666     esac
2667 }
2668
2669 _check_scratch_fs()
2670 {
2671     device=$SCRATCH_DEV
2672     [ $# -eq 1 ] && device=$1
2673
2674     case $FSTYP in
2675     xfs)
2676         SCRATCH_LOG="none"
2677         SCRATCH_RT="none"
2678         [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_LOGDEV" ] && \
2679             SCRATCH_LOG="$SCRATCH_LOGDEV"
2680
2681         [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_RTDEV" ] && \
2682             SCRATCH_RT="$SCRATCH_RTDEV"
2683
2684         _check_xfs_filesystem $device $SCRATCH_LOG $SCRATCH_RT
2685         ;;
2686     udf)
2687         _check_udf_filesystem $device $udf_fsize
2688         ;;
2689     nfs*)
2690         # Don't know how to check an NFS filesystem, yet.
2691         ;;
2692     cifs)
2693         # Don't know how to check a CIFS filesystem, yet.
2694         ;;
2695     overlay)
2696         # no way to check consistency for overlay
2697         ;;
2698     btrfs)
2699         _check_btrfs_filesystem $device
2700         ;;
2701     tmpfs)
2702         # no way to check consistency for tmpfs
2703         ;;
2704     *)
2705         _check_generic_filesystem $device
2706         ;;
2707     esac
2708 }
2709
2710 _full_fstyp_details()
2711 {
2712      [ -z "$FSTYP" ] && FSTYP=xfs
2713      if [ $FSTYP = xfs ]; then
2714         if [ -d /proc/fs/xfs ]; then
2715             if grep -q 'debug 0' /proc/fs/xfs/stat; then
2716                 FSTYP="$FSTYP (non-debug)"
2717             elif grep -q 'debug 1' /proc/fs/xfs/stat; then
2718                 FSTYP="$FSTYP (debug)"
2719             fi
2720         else
2721             if uname -a | grep -qi 'debug'; then
2722                 FSTYP="$FSTYP (debug)"
2723             else
2724                 FSTYP="$FSTYP (non-debug)"
2725             fi
2726         fi
2727      fi
2728      echo $FSTYP
2729 }
2730
2731 _full_platform_details()
2732 {
2733      os=`uname -s`
2734      host=`hostname -s`
2735      kernel=`uname -r`
2736      platform=`uname -m`
2737      echo "$os/$platform $host $kernel"
2738 }
2739
2740 _get_os_name()
2741 {
2742         if [ "`uname`" == "IRIX64" ] || [ "`uname`" == "IRIX" ]; then
2743                 echo 'irix'
2744         elif [ "`uname`" == "Linux" ]; then
2745                 echo 'linux'
2746         else
2747                 echo Unknown operating system: `uname`
2748                 exit
2749         fi
2750 }
2751
2752 _link_out_file_named()
2753 {
2754         export FEATURES=$2
2755         SUFFIX=$(perl -e '
2756                 my %feathash;
2757                 my $feature, $result, $suffix, $opts;
2758
2759                 foreach $feature (split(/,/, $ENV{"FEATURES"})) {
2760                         $feathash{$feature} = 1;
2761                 }
2762                 $result = "default";
2763                 while (<>) {
2764                         my $found = 1;
2765
2766                         chomp;
2767                         ($opts, $suffix) = split(/ *: */);
2768                         foreach my $opt (split(/,/, $opts)) {
2769                                 if (!exists($feathash{$opt})) {
2770                                         $found = 0;
2771                                         last;
2772                                 }
2773                         }
2774                         if ($found == 1) {
2775                                 $result = $suffix;
2776                                 last;
2777                         }
2778                 }
2779                 print $result
2780                 ' <$seqfull.cfg)
2781         rm -f $1
2782         SRC=$(basename $1)
2783         ln -fs $SRC.$SUFFIX $1
2784 }
2785
2786 _link_out_file()
2787 {
2788         if [ $# -eq 0 ]; then
2789                 FEATURES="$(_get_os_name)"
2790                 if [ -n "$MOUNT_OPTIONS" ]; then
2791                         FEATURES=$FEATURES,${MOUNT_OPTIONS##"-o "}
2792                 fi
2793         else
2794                 FEATURES=$1
2795         fi
2796
2797         _link_out_file_named $seqfull.out "$FEATURES"
2798 }
2799
2800 _die()
2801 {
2802         echo $@
2803         exit 1
2804 }
2805
2806 #takes files, randomdata
2807 _nfiles()
2808 {
2809         f=0
2810         while [ $f -lt $1 ]
2811         do
2812                 file=f$f
2813                 echo > $file
2814                 if [ $size -gt 0 ]; then
2815                     if [ "$2" == "false" ]; then
2816                         dd if=/dev/zero of=$file bs=1024 count=$size 2>&1 | _filter_dd
2817                     else
2818                         dd if=/dev/urandom of=$file bs=1024 count=$size 2>&1 | _filter_dd
2819                     fi
2820                 fi
2821                 let f=$f+1
2822         done
2823 }
2824
2825 # takes dirname, depth, randomdata
2826 _descend()
2827 {
2828         dirname=$1; depth=$2; randomdata=$3
2829         mkdir $dirname  || die "mkdir $dirname failed"
2830         cd $dirname
2831
2832         _nfiles $files $randomdata          # files for this dir and data type
2833
2834         [ $depth -eq 0 ] && return
2835         let deep=$depth-1 # go 1 down
2836
2837         [ $verbose = true ] && echo "descending, depth from leaves = $deep"
2838
2839         d=0
2840         while [ $d -lt $dirs ]
2841         do
2842                 _descend d$d $deep &
2843                 let d=$d+1
2844                 wait
2845         done
2846 }
2847
2848 # Populate a filesystem with inodes for performance experiments
2849 #
2850 # usage: populate [-v] [-n ndirs] [-f nfiles] [-d depth] [-r root] [-s size] [-x]
2851 #
2852 _populate_fs()
2853 {
2854     here=`pwd`
2855     dirs=5          # ndirs in each subdir till leaves
2856     size=0          # sizeof files in K
2857     files=100       # num files in _each_ subdir
2858     depth=2         # depth of tree from root to leaves
2859     verbose=false
2860     root=root       # path of initial root of directory tree
2861     randomdata=false # -x data type urandom or zero
2862
2863     OPTIND=1
2864     while getopts "d:f:n:r:s:v:x" c
2865     do
2866         case $c in
2867         d)      depth=$OPTARG;;
2868         n)      dirs=$OPTARG;;
2869         f)      files=$OPTARG;;
2870         s)      size=$OPTARG;;
2871         v)      verbose=true;;
2872         r)      root=$OPTARG;;
2873         x)      randomdata=true;;
2874         esac
2875     done
2876
2877     _descend $root $depth $randomdata
2878     wait
2879
2880     cd $here
2881
2882     [ $verbose = true ] && echo done
2883 }
2884
2885 # query whether the given file has the given inode flag set
2886 #
2887 _test_inode_flag()
2888 {
2889     flag=$1
2890     file=$2
2891
2892     if which $XFS_IO_PROG >/dev/null; then
2893         if $XFS_IO_PROG -r -c 'lsattr -v' "$file" | grep -q "$flag" ; then
2894             return 0
2895         fi
2896     fi
2897     return 1
2898 }
2899
2900 # query the given files extsize allocator hint in bytes (if any)
2901 #
2902 _test_inode_extsz()
2903 {
2904     file=$1
2905     blocks=""
2906
2907     if which $XFS_IO_PROG >/dev/null; then
2908         blocks=`$XFS_IO_PROG -r -c 'stat' "$file" | \
2909                 awk '/^xattr.extsize =/ { print $3 }'`
2910     fi
2911     [ -z "$blocks" ] && blocks="0"
2912     echo $blocks
2913 }
2914
2915 # scratch_dev_pool should contain the disks pool for the btrfs raid
2916 _require_scratch_dev_pool()
2917 {
2918         local i
2919         local ndevs
2920
2921         if [ -z "$SCRATCH_DEV_POOL" ]; then
2922                 _notrun "this test requires a valid \$SCRATCH_DEV_POOL"
2923         fi
2924
2925         if [ -z "$1" ]; then
2926                 ndevs=2
2927         else
2928                 ndevs=$1
2929         fi
2930
2931         # btrfs test case needs ndevs or more scratch_dev_pool; other FS not sure
2932         # so fail it
2933         case $FSTYP in
2934         btrfs)
2935                 if [ "`echo $SCRATCH_DEV_POOL|wc -w`" -lt $ndevs ]; then
2936                         _notrun "btrfs and this test needs $ndevs or more disks in SCRATCH_DEV_POOL"
2937                 fi
2938         ;;
2939         *)
2940                 _notrun "dev_pool is not supported by fstype \"$FSTYP\""
2941         ;;
2942         esac
2943
2944         for i in $SCRATCH_DEV_POOL; do
2945                 if [ "`_is_block_dev "$i"`" = "" ]; then
2946                         _notrun "this test requires valid block disk $i"
2947                 fi
2948                 if [ "`_is_block_dev "$i"`" = "`_is_block_dev "$TEST_DEV"`" ]; then
2949                         _notrun "$i is part of TEST_DEV, this test requires unique disks"
2950                 fi
2951                 if _mount | grep -q $i; then
2952                         if ! $UMOUNT_PROG $i; then
2953                             echo "failed to unmount $i - aborting"
2954                             exit 1
2955                         fi
2956                 fi
2957                 # to help better debug when something fails, we remove
2958                 # traces of previous btrfs FS on the dev.
2959                 dd if=/dev/zero of=$i bs=4096 count=100 > /dev/null 2>&1
2960         done
2961 }
2962
2963 # ensure devices in SCRATCH_DEV_POOL are of the same size
2964 # must be called after _require_scratch_dev_pool
2965 _require_scratch_dev_pool_equal_size()
2966 {
2967         local _size
2968         local _newsize
2969         local _dev
2970
2971         # SCRATCH_DEV has been set to the first device in SCRATCH_DEV_POOL
2972         _size=`_get_device_size $SCRATCH_DEV`
2973         for _dev in $SCRATCH_DEV_POOL; do
2974                 _newsize=`_get_device_size $_dev`
2975                 if [ $_size -ne $_newsize ]; then
2976                         _notrun "This test requires devices in SCRATCH_DEV_POOL have the same size"
2977                 fi
2978         done
2979 }
2980
2981 # We will check if the device is deletable
2982 _require_deletable_scratch_dev_pool()
2983 {
2984         local i
2985         local x
2986         for i in $SCRATCH_DEV_POOL; do
2987                 x=`echo $i | cut -d"/" -f 3`
2988                 if [ ! -f /sys/class/block/${x}/device/delete ]; then
2989                         _notrun "$i is a device which is not deletable"
2990                 fi
2991         done
2992 }
2993
2994 # We check for btrfs and (optionally) features of the btrfs command
2995 _require_btrfs()
2996 {
2997         cmd=$1
2998         _require_command "$BTRFS_UTIL_PROG" btrfs
2999         if [ -z "$1" ]; then
3000                 return 1;
3001         fi
3002         $BTRFS_UTIL_PROG $cmd --help >/dev/null 2>&1
3003         [ $? -eq 0 ] || _notrun "$BTRFS_UTIL_PROG too old (must support $cmd)"
3004 }
3005
3006 # Check that fio is present, and it is able to execute given jobfile
3007 _require_fio()
3008 {
3009         job=$1
3010
3011         _require_command "$FIO_PROG" fio
3012         if [ -z "$1" ]; then
3013                 return 1;
3014         fi
3015
3016         $FIO_PROG --warnings-fatal --showcmd $job >> $seqres.full 2>&1
3017         [ $? -eq 0 ] || _notrun "$FIO_PROG too old, see $seqres.full"
3018 }
3019
3020 # Does freeze work on this fs?
3021 _require_freeze()
3022 {
3023         xfs_freeze -f "$TEST_DIR" >/dev/null 2>&1
3024         result=$? 
3025         xfs_freeze -u "$TEST_DIR" >/dev/null 2>&1
3026         [ $result -eq 0 ] || _notrun "$FSTYP does not support freezing"
3027 }
3028
3029 # Does shutdown work on this fs?
3030 _require_scratch_shutdown()
3031 {
3032         [ -x src/godown ] || _notrun "src/godown executable not found"
3033
3034         _scratch_mkfs > /dev/null 2>&1
3035         _scratch_mount
3036         src/godown -f $SCRATCH_MNT 2>&1 \
3037                 || _notrun "$FSTYP does not support shutdown"
3038         _scratch_unmount
3039 }
3040
3041 # Does norecovery support by this fs?
3042 _require_norecovery()
3043 {
3044         _scratch_mount -o ro,norecovery || \
3045                 _notrun "$FSTYP does not support norecovery"
3046         _scratch_unmount
3047 }
3048
3049 # Does this filesystem support metadata journaling?
3050 # We exclude ones here that don't; otherwise we assume that it does, so the
3051 # test will run, fail, and motivate someone to update this test for a new
3052 # filesystem.
3053 #
3054 # It's possible that TEST_DEV and SCRATCH_DEV have different features (it'd be
3055 # odd, but possible) so check $TEST_DEV by default, but we can optionall pass
3056 # any dev we want.
3057 _require_metadata_journaling()
3058 {
3059         if [ -z $1 ]; then
3060                 DEV=$TEST_DEV
3061         else
3062                 DEV=$1
3063         fi
3064
3065         case "$FSTYP" in
3066         ext2|vfat|msdos)
3067                 _notrun "$FSTYP does not support metadata journaling"
3068                 ;;
3069         ext4)
3070                 # ext4 could be mkfs'd without a journal...
3071                 _require_dumpe2fs
3072                 $DUMPE2FS_PROG -h $DEV 2>&1 | grep -q has_journal || \
3073                         _notrun "$FSTYP on $DEV not configured with metadata journaling"
3074                 # ext4 might not load a journal
3075                 _exclude_scratch_mount_option "noload"
3076                 ;;
3077         *)
3078                 # by default we pass; if you need to, add your fs above!
3079                 ;;
3080         esac
3081 }
3082
3083 # Does fiemap support?
3084 _require_fiemap()
3085 {
3086         _require_xfs_io_command "fiemap"
3087 }
3088
3089 _count_extents()
3090 {
3091         $XFS_IO_PROG -c "fiemap" $1 | tail -n +2 | grep -v hole | wc -l
3092 }
3093
3094 _count_holes()
3095 {
3096         $XFS_IO_PROG -c "fiemap" $1 | tail -n +2 | grep hole | wc -l
3097 }
3098
3099 # arg 1 is dev to remove and is output of the below eg.
3100 # ls -l /sys/class/block/sdd | rev | cut -d "/" -f 3 | rev
3101 _devmgt_remove()
3102 {
3103         local lun=$1
3104         local disk=$2
3105
3106         echo 1 > /sys/class/scsi_device/${lun}/device/delete || _fail "Remove disk failed"
3107
3108         stat $disk > /dev/null 2>&1
3109         while [ $? -eq 0 ]; do
3110                 sleep 1
3111                 stat $disk > /dev/null 2>&1
3112         done
3113 }
3114
3115 # arg 1 is dev to add and is output of the below eg.
3116 # ls -l /sys/class/block/sdd | rev | cut -d "/" -f 3 | rev
3117 _devmgt_add()
3118 {
3119         local h
3120         local tdl
3121         # arg 1 will be in h:t:d:l format now in the h and "t d l" format
3122         h=`echo ${1} | cut -d":" -f 1`
3123         tdl=`echo ${1} | cut -d":" -f 2-|sed 's/:/ /g'`
3124
3125         echo ${tdl} >  /sys/class/scsi_host/host${h}/scan || _fail "Add disk failed"
3126
3127         # ensure the device comes online
3128         dev_back_oneline=0
3129         for i in `seq 1 10`; do
3130                 if [ -d /sys/class/scsi_device/${1}/device/block ]; then
3131                         dev=`ls /sys/class/scsi_device/${1}/device/block`
3132                         for j in `seq 1 10`;
3133                         do
3134                                 stat /dev/$dev > /dev/null 2>&1
3135                                 if [ $? -eq 0 ]; then
3136                                         dev_back_oneline=1
3137                                         break
3138                                 fi
3139                                 sleep 1
3140                         done
3141                         break
3142                 else
3143                         sleep 1
3144                 fi
3145         done
3146         if [ $dev_back_oneline -eq 0 ]; then
3147                 echo "/dev/$dev online failed" >> $seqres.full
3148         else
3149                 echo "/dev/$dev is back online" >> $seqres.full
3150         fi
3151 }
3152
3153 _require_fstrim()
3154 {
3155         if [ -z "$FSTRIM_PROG" ]; then
3156                 _notrun "This test requires fstrim utility."
3157         fi
3158 }
3159
3160 _require_batched_discard()
3161 {
3162         if [ $# -ne 1 ]; then
3163                 echo "Usage: _require_batched_discard mnt_point" 1>&2
3164                 exit 1
3165         fi
3166         _require_fstrim
3167         $FSTRIM_PROG $1 > /dev/null 2>&1 || _notrun "FITRIM not supported on $1"
3168 }
3169
3170 _require_dumpe2fs()
3171 {
3172         if [ -z "$DUMPE2FS_PROG" ]; then
3173                 _notrun "This test requires dumpe2fs utility."
3174         fi
3175 }
3176
3177 _require_ugid_map()
3178 {
3179         if [ ! -e /proc/self/uid_map ]; then
3180                 _notrun "This test requires procfs uid_map support."
3181         fi
3182         if [ ! -e /proc/self/gid_map ]; then
3183                 _notrun "This test requires procfs gid_map support."
3184         fi
3185 }
3186
3187 _require_fssum()
3188 {
3189         FSSUM_PROG=$here/src/fssum
3190         [ -x $FSSUM_PROG ] || _notrun "fssum not built"
3191 }
3192
3193 _require_cloner()
3194 {
3195         CLONER_PROG=$here/src/cloner
3196         [ -x $CLONER_PROG ] || \
3197                 _notrun "cloner binary not present at $CLONER_PROG"
3198 }
3199
3200 # Normalize mount options from global $MOUNT_OPTIONS
3201 # Convert options like "-o opt1,opt2 -oopt3" to
3202 # "opt1 opt2 opt3"
3203 _normalize_mount_options()
3204 {
3205         echo $MOUNT_OPTIONS | sed -n 's/-o\s*\(\S*\)/\1/gp'| sed 's/,/ /g'
3206 }
3207
3208 # skip test if MOUNT_OPTIONS contains the given strings
3209 _exclude_scratch_mount_option()
3210 {
3211         local mnt_opts=$(_normalize_mount_options)
3212
3213         while [ $# -gt 0 ]; do
3214                 if echo $mnt_opts | grep -qw "$1"; then
3215                         _notrun "mount option \"$1\" not allowed in this test"
3216                 fi
3217                 shift
3218         done
3219 }
3220
3221 _require_atime()
3222 {
3223         _exclude_scratch_mount_option "noatime"
3224         if [ "$FSTYP" == "nfs" ]; then
3225                 _notrun "atime related mount options have no effect on NFS"
3226         fi
3227 }
3228
3229 _require_relatime()
3230 {
3231         _scratch_mkfs > /dev/null 2>&1
3232         _scratch_mount -o relatime || \
3233                 _notrun "relatime not supported by the current kernel"
3234         _scratch_unmount
3235 }
3236
3237 _require_userns()
3238 {
3239         [ -x src/nsexec ] || _notrun "src/nsexec executable not found"
3240         src/nsexec -U true 2>/dev/null || _notrun "userns not supported by this kernel"
3241 }
3242
3243 _create_loop_device()
3244 {
3245         file=$1
3246         dev=`losetup -f --show $file` || _fail "Cannot assign $file to a loop device"
3247         echo $dev
3248 }
3249
3250 _destroy_loop_device()
3251 {
3252         dev=$1
3253         losetup -d $dev || _fail "Cannot destroy loop device $dev"
3254 }
3255
3256 _scale_fsstress_args()
3257 {
3258     args=""
3259     while [ $# -gt 0 ]; do
3260         case "$1" in
3261             -n) args="$args $1 $(($2 * $TIME_FACTOR))"; shift ;;
3262             -p) args="$args $1 $(($2 * $LOAD_FACTOR))"; shift ;;
3263             *) args="$args $1" ;;
3264         esac
3265         shift
3266     done
3267     echo $args
3268 }
3269
3270 #
3271 # Return the logical block size if running on a block device,
3272 # else substitute the page size.
3273 #
3274 _min_dio_alignment()
3275 {
3276     dev=$1
3277
3278     if [ -b "$dev" ]; then
3279         blockdev --getss $dev
3280     else
3281         $here/src/feature -s
3282     fi
3283 }
3284
3285 run_check()
3286 {
3287         echo "# $@" >> $seqres.full 2>&1
3288         "$@" >> $seqres.full 2>&1 || _fail "failed: '$@'"
3289 }
3290
3291 _run_btrfs_util_prog()
3292 {
3293         run_check $BTRFS_UTIL_PROG $*
3294 }
3295
3296 _require_btrfs_send_stream_version()
3297 {
3298         $BTRFS_UTIL_PROG send 2>&1 | \
3299                 grep '^[ \t]*\-\-stream\-version <version>' > /dev/null 2>&1
3300         if [ $? -ne 0 ]; then
3301                 _notrun "Missing btrfs-progs send --stream-version command line option, skipped this test"
3302         fi
3303
3304         # test if btrfs kernel supports send stream version 2
3305         if [ ! -f /sys/fs/btrfs/send/stream_version ]; then
3306                 _notrun "Missing btrfs kernel patch for send stream version 2, skipped this test"
3307         fi
3308 }
3309
3310 _require_btrfs_mkfs_feature()
3311 {
3312         if [ -z $1 ]; then
3313                 echo "Missing feature name argument for _require_btrfs_mkfs_feature"
3314                 exit 1
3315         fi
3316         feat=$1
3317         $MKFS_BTRFS_PROG -O list-all 2>&1 | \
3318                 grep '^[ \t]*'"$feat"'\b' > /dev/null 2>&1
3319         [ $? -eq 0 ] || \
3320                 _notrun "Feature $feat not supported in the available version of mkfs.btrfs"
3321 }
3322
3323 _require_btrfs_fs_feature()
3324 {
3325         if [ -z $1 ]; then
3326                 echo "Missing feature name argument for _require_btrfs_fs_feature"
3327                 exit 1
3328         fi
3329         feat=$1
3330         modprobe btrfs > /dev/null 2>&1
3331         [ -e /sys/fs/btrfs/features/$feat ] || \
3332                 _notrun "Feature $feat not supported by the available btrfs version"
3333 }
3334
3335 _require_test_symlinks()
3336 {
3337         # IRIX UDF does not support symlinks
3338         [ "$HOSTOS" = "IRIX" -a "$FSTYP" = 'udf' ] && \
3339                 _notrun "Require symlinks support"
3340         target=`mktemp -p $TEST_DIR`
3341         link=`mktemp -p $TEST_DIR -u`
3342         ln -s `basename $target` $link
3343         if [ "$?" -ne 0 ]; then
3344                 rm -f $target
3345                 _notrun "Require symlinks support"
3346         fi
3347         rm -f $target $link
3348 }
3349
3350 _require_test_fcntl_advisory_locks()
3351 {
3352         [ "$FSTYP" != "cifs" ] && return 0
3353         cat /proc/mounts | grep $TEST_DEV | grep cifs | grep -q "nobrl" && return 0
3354         cat /proc/mounts | grep $TEST_DEV | grep cifs | grep -qE "nounix|forcemand" && \
3355                 _notrun "Require fcntl advisory locks support"
3356 }
3357
3358 # XFS ability to change UUIDs on V5/CRC filesystems
3359 #
3360 _require_meta_uuid()
3361 {
3362         # This will create a crc fs on $SCRATCH_DEV
3363         _require_xfs_crc
3364
3365         $XFS_DB_PROG -x -c "uuid restore" $SCRATCH_DEV 2>&1 \
3366            | grep -q "invalid UUID\|supported on V5 fs" \
3367            && _notrun "Userspace doesn't support meta_uuid feature"
3368
3369         $XFS_DB_PROG -x -c "uuid generate" $SCRATCH_DEV >/dev/null 2>&1
3370
3371         _scratch_mount >/dev/null 2>&1 \
3372            || _notrun "Kernel doesn't support meta_uuid feature"
3373         _scratch_unmount
3374 }
3375
3376 _require_btrfs_dev_del_by_devid()
3377 {
3378         $BTRFS_UTIL_PROG device delete --help | egrep devid > /dev/null 2>&1
3379         [ $? -eq 0 ] || _notrun "$BTRFS_UTIL_PROG too old "\
3380                         "(must support 'btrfs device delete <devid> /<mnt>')"
3381 }
3382
3383 _require_test_lsattr()
3384 {
3385         testio=$(lsattr -d $TEST_DIR 2>&1)
3386         echo $testio | grep -q "Operation not supported" && \
3387                 _notrun "lsattr not supported by test filesystem type: $FSTYP"
3388         echo $testio | grep -q "Inappropriate ioctl for device" && \
3389                 _notrun "lsattr not supported by test filesystem type: $FSTYP"
3390 }
3391
3392 _require_xfs_test_rmapbt()
3393 {
3394         _require_test
3395
3396         if [ "$(xfs_info "$TEST_DIR" | grep -c "rmapbt=1")" -ne 1 ]; then
3397                 _notrun "rmapbt not supported by test filesystem type: $FSTYP"
3398         fi
3399 }
3400
3401 _require_xfs_scratch_rmapbt()
3402 {
3403         _require_scratch
3404
3405         _scratch_mkfs > /dev/null
3406         _scratch_mount
3407         if [ "$(xfs_info "$SCRATCH_MNT" | grep -c "rmapbt=1")" -ne 1 ]; then
3408                 _scratch_unmount
3409                 _notrun "rmapbt not supported by scratch filesystem type: $FSTYP"
3410         fi
3411         _scratch_unmount
3412 }
3413
3414 _xfs_bmapx_find() {
3415         case "$1" in
3416         "attr")
3417                 param="a"
3418                 ;;
3419         "cow")
3420                 param="c"
3421                 ;;
3422         *)
3423                 param="e"
3424                 ;;
3425         esac
3426         shift
3427         file="$1"
3428         shift
3429
3430         "$XFS_IO_PROG" -c "bmap -${param}lpv" "$file" | grep -c "$@"
3431 }
3432
3433 _require_chattr()
3434 {
3435     attribute=$1
3436
3437     touch $TEST_DIR/syscalltest
3438     chattr "+$attribute" $TEST_DIR/syscalltest > $TEST_DIR/syscalltest.out 2>&1
3439     status=$?
3440     chattr "-$attribute" $TEST_DIR/syscalltest > $TEST_DIR/syscalltest.out 2>&1
3441     if [ "$status" -ne 0 ]; then
3442       _notrun "file system doesn't support chattr +$attribute"
3443     fi
3444     cat $TEST_DIR/syscalltest.out >> $seqres.full
3445
3446     rm -f $TEST_DIR/syscalltest.out
3447 }
3448
3449 _get_total_inode()
3450 {
3451         if [ -z "$1" ]; then
3452                 echo "Usage: _get_total_inode <mnt>"
3453                 exit 1
3454         fi
3455         local nr_inode;
3456         nr_inode=`$DF_PROG -i $1 | tail -1 | awk '{print $3}'`
3457         echo $nr_inode
3458 }
3459
3460 _get_used_inode()
3461 {
3462         if [ -z "$1" ]; then
3463                 echo "Usage: _get_used_inode <mnt>"
3464                 exit 1
3465         fi
3466         local nr_inode;
3467         nr_inode=`$DF_PROG -i $1 | tail -1 | awk '{print $4}'`
3468         echo $nr_inode
3469 }
3470
3471 _get_used_inode_percent()
3472 {
3473         if [ -z "$1" ]; then
3474                 echo "Usage: _get_used_inode_percent <mnt>"
3475                 exit 1
3476         fi
3477         local pct_inode;
3478         pct_inode=`$DF_PROG -i $1 | tail -1 | awk '{ print $6 }' | \
3479                    sed -e 's/%//'`
3480         echo $pct_inode
3481 }
3482
3483 _get_free_inode()
3484 {
3485         if [ -z "$1" ]; then
3486                 echo "Usage: _get_free_inode <mnt>"
3487                 exit 1
3488         fi
3489         local nr_inode;
3490         nr_inode=`$DF_PROG -i $1 | tail -1 | awk '{print $5}'`
3491         echo $nr_inode
3492 }
3493
3494 # get the available space in bytes
3495 #
3496 _get_available_space()
3497 {
3498         if [ -z "$1" ]; then
3499                 echo "Usage: _get_available_space <mnt>"
3500                 exit 1
3501         fi
3502         local avail_kb;
3503         avail_kb=`$DF_PROG $1 | tail -n1 | awk '{ print $5 }'`
3504         echo $((avail_kb * 1024))
3505 }
3506
3507 # get btrfs profile configs being tested
3508 #
3509 # A set of pre-set profile configs are exported via _btrfs_profile_configs
3510 # array. Default configs can be overridden by setting BTRFS_PROFILE_CONFIGS
3511 # var in the format "metadata_profile:data_profile", multiple configs can be
3512 # seperated by space, e.g.
3513 # export BTRFS_PROFILE_CONFIGS="raid0:raid0 raid1:raid1 dup:single"
3514 _btrfs_get_profile_configs()
3515 {
3516         if [ "$FSTYP" != "btrfs" ]; then
3517                 return
3518         fi
3519
3520         if [ -z "$BTRFS_PROFILE_CONFIGS" ]; then
3521                 # Default configurations to test.
3522                 local configs=(
3523                         "single:single"
3524                         "dup:single"
3525                         "raid0:raid0"
3526                         "raid1:raid0"
3527                         "raid1:raid1"
3528                         "raid10:raid10"
3529                         "raid5:raid5"
3530                         "raid6:raid6"
3531                 )
3532         else
3533                 # User-provided configurations.
3534                 local configs=(${BTRFS_PROFILE_CONFIGS[@]})
3535         fi
3536
3537         _btrfs_profile_configs=()
3538         for cfg in "${configs[@]}"; do
3539                 local supported=true
3540                 local profiles=(${cfg/:/ })
3541                 if [ "$1" == "replace" ]; then
3542                         # We can't do replace with these profiles because they
3543                         # imply only one device ($SCRATCH_DEV), and we need to
3544                         # keep $SCRATCH_DEV around for _scratch_mount
3545                         # and _check_scratch_fs.
3546                         local unsupported=(
3547                                 "dup"
3548                         )
3549                 elif [ "$1" == "replace-missing" ]; then
3550                         # We can't replace missing devices with these profiles
3551                         # because there isn't enough redundancy.
3552                         local unsupported=(
3553                                 "single"
3554                                 "dup"
3555                                 "raid0"
3556                         )
3557                 else
3558                         local unsupported=()
3559                 fi
3560                 for unsupp in "${unsupported[@]}"; do
3561                         if [ "${profiles[0]}" == "$unsupp" -o "${profiles[1]}" == "$unsupp" ]; then
3562                              if [ -z "$BTRFS_PROFILE_CONFIGS" ]; then
3563                                      # For the default config, just omit it.
3564                                      supported=false
3565                              else
3566                                      # For user-provided config, don't run the test.
3567                                      _notrun "Profile $unsupp not supported for $1"
3568                              fi
3569                         fi
3570                 done
3571                 if "$supported"; then
3572                         _btrfs_profile_configs+=("-m ${profiles[0]} -d ${profiles[1]}")
3573                 fi
3574         done
3575         export _btrfs_profile_configs
3576 }
3577
3578 # stress btrfs by running balance operation in a loop
3579 _btrfs_stress_balance()
3580 {
3581         local options=$@
3582         while true; do
3583                 $BTRFS_UTIL_PROG balance start $options
3584         done
3585 }
3586
3587 # stress btrfs by creating/mounting/umounting/deleting subvolume in a loop
3588 _btrfs_stress_subvolume()
3589 {
3590         local btrfs_dev=$1
3591         local btrfs_mnt=$2
3592         local subvol_name=$3
3593         local subvol_mnt=$4
3594         local stop_file=$5
3595
3596         mkdir -p $subvol_mnt
3597         while [ ! -e $stop_file ]; do
3598                 $BTRFS_UTIL_PROG subvolume create $btrfs_mnt/$subvol_name
3599                 $MOUNT_PROG -o subvol=$subvol_name $btrfs_dev $subvol_mnt
3600                 $UMOUNT_PROG $subvol_mnt
3601                 $BTRFS_UTIL_PROG subvolume delete $btrfs_mnt/$subvol_name
3602         done
3603 }
3604
3605 # stress btrfs by running scrub in a loop
3606 _btrfs_stress_scrub()
3607 {
3608         local btrfs_mnt=$1
3609         while true; do
3610                 $BTRFS_UTIL_PROG scrub start -B $btrfs_mnt
3611         done
3612 }
3613
3614 # stress btrfs by defragmenting every file/dir in a loop and compress file
3615 # contents while defragmenting if second argument is not "nocompress"
3616 _btrfs_stress_defrag()
3617 {
3618         local btrfs_mnt=$1
3619         local compress=$2
3620
3621         while true; do
3622                 if [ "$compress" == "nocompress" ]; then
3623                         find $btrfs_mnt \( -type f -o -type d \) -exec \
3624                         $BTRFS_UTIL_PROG filesystem defrag {} \;
3625                 else
3626                         find $btrfs_mnt \( -type f -o -type d \) -exec \
3627                         $BTRFS_UTIL_PROG filesystem defrag -clzo {} \;
3628                         find $btrfs_mnt \( -type f -o -type d \) -exec \
3629                         $BTRFS_UTIL_PROG filesystem defrag -czlib {} \;
3630                 fi
3631         done
3632 }
3633
3634 # stress btrfs by remounting it with different compression algorithms in a loop
3635 # run this with fsstress running at background could exercise the compression
3636 # code path and ensure no race when switching compression algorithm with constant
3637 # I/O activity.
3638 _btrfs_stress_remount_compress()
3639 {
3640         local btrfs_mnt=$1
3641         while true; do
3642                 for algo in no zlib lzo; do
3643                         $MOUNT_PROG -o remount,compress=$algo $btrfs_mnt
3644                 done
3645         done
3646 }
3647
3648 # stress btrfs by replacing devices in a loop
3649 # Note that at least 3 devices are needed in SCRATCH_DEV_POOL and the last
3650 # device should be free(not used by btrfs)
3651 _btrfs_stress_replace()
3652 {
3653         local btrfs_mnt=$1
3654
3655         # The device number in SCRATCH_DEV_POOL should be at least 3,
3656         # one is SCRATCH_DEV, one is to be replaced, one is free device
3657         # we won't replace SCRATCH_DEV, see below for reason
3658         if [ "`echo $SCRATCH_DEV_POOL | wc -w`" -lt 3 ]; then
3659                 echo "_btrfs_stress_replace requires at least 3 devices in SCRATCH_DEV_POOL"
3660                 return
3661         fi
3662
3663         # take the last device as the first free_dev
3664         local free_dev="`echo $SCRATCH_DEV_POOL | $AWK_PROG '{print $NF}'`"
3665
3666         # free_dev should be really free
3667         if $BTRFS_UTIL_PROG filesystem show $btrfs_mnt | grep -q "$free_dev"; then
3668                 echo "_btrfs_stress_replace: $free_dev is used by btrfs"
3669                 return
3670         fi
3671
3672         # dev_pool is device list being currently used by btrfs (excluding SCRATCH_DEV)
3673         # and can be replaced. We don't replace SCRATCH_DEV because it will be used in
3674         # _scratch_mount and _check_scratch_fs etc.
3675         local dev_pool=`echo $SCRATCH_DEV_POOL | sed -e "s# *$SCRATCH_DEV *##" \
3676                         -e "s# *$free_dev *##"`
3677
3678         # set the first device in dev_pool as the first src_dev to be replaced
3679         local src_dev=`echo $dev_pool | $AWK_PROG '{print $1}'`
3680
3681         echo "dev_pool=$dev_pool"
3682         echo "free_dev=$free_dev, src_dev=$src_dev"
3683         while true; do
3684                 echo "Replacing $src_dev with $free_dev"
3685                 $BTRFS_UTIL_PROG replace start -fB $src_dev $free_dev $btrfs_mnt
3686                 if [ $? -ne 0 ]; then
3687                         # don't update src_dev and free_dev if replace failed
3688                         continue
3689                 fi
3690                 dev_pool="$dev_pool $free_dev"
3691                 dev_pool=`echo $dev_pool | sed -e "s# *$src_dev *##"`
3692                 free_dev=$src_dev
3693                 src_dev=`echo $dev_pool | $AWK_PROG '{print $1}'`
3694         done
3695 }
3696
3697 # find the right option to force output in bytes, older versions of btrfs-progs
3698 # print that by default, newer print human readable numbers with unit suffix
3699 _btrfs_qgroup_units()
3700 {
3701         $BTRFS_UTIL_PROG qgroup show --help 2>&1 | grep -q -- --raw && echo "--raw"
3702 }
3703
3704 # return device size in kb
3705 _get_device_size()
3706 {
3707         grep `_short_dev $1` /proc/partitions | awk '{print $3}'
3708 }
3709
3710 # check dmesg log for WARNING/Oops/etc.
3711 _check_dmesg()
3712 {
3713         if [ ! -f ${RESULT_DIR}/check_dmesg ]; then
3714                 return 0
3715         fi
3716         rm -f ${RESULT_DIR}/check_dmesg
3717
3718         # default filter is a simple cat command, caller could provide a
3719         # customized filter and pass the name through the first argument, to
3720         # filter out intentional WARNINGs or Oopses
3721         filter=${1:-cat}
3722
3723         # search the dmesg log of last run of $seqnum for possible failures
3724         # use sed \cregexpc address type, since $seqnum contains "/"
3725         dmesg | tac | sed -ne "0,\#run fstests $seqnum at $date_time#p" | \
3726                 tac | $filter >$seqres.dmesg
3727         grep -q -e "kernel BUG at" \
3728              -e "WARNING:" \
3729              -e "BUG:" \
3730              -e "Oops:" \
3731              -e "possible recursive locking detected" \
3732              -e "Internal error" \
3733              -e "INFO: suspicious RCU usage" \
3734              -e "INFO: possible circular locking dependency detected" \
3735              -e "general protection fault:" \
3736              $seqres.dmesg
3737         if [ $? -eq 0 ]; then
3738                 echo "_check_dmesg: something found in dmesg (see $seqres.dmesg)"
3739                 return 1
3740         else
3741                 rm -f $seqres.dmesg
3742                 return 0
3743         fi
3744 }
3745
3746 # don't check dmesg log after test
3747 _disable_dmesg_check()
3748 {
3749         rm -f ${RESULT_DIR}/check_dmesg
3750 }
3751
3752 init_rc()
3753 {
3754         if [ "$iam" == new ]
3755         then
3756                 return
3757         fi
3758         # make some further configuration checks here
3759         if [ "$TEST_DEV" = ""  ]
3760         then
3761                 echo "common/rc: Error: \$TEST_DEV is not set"
3762                 exit 1
3763         fi
3764
3765         # if $TEST_DEV is not mounted, mount it now as XFS
3766         if [ -z "`_fs_type $TEST_DEV`" ]
3767         then
3768                 # $TEST_DEV is not mounted
3769                 if ! _test_mount
3770                 then
3771                         echo "common/rc: retrying test device mount with external set"
3772                         [ "$USE_EXTERNAL" != "yes" ] && export USE_EXTERNAL=yes
3773                         if ! _test_mount
3774                         then
3775                                 echo "common/rc: could not mount $TEST_DEV on $TEST_DIR"
3776                                 exit 1
3777                         fi
3778                 fi
3779         fi
3780
3781         if [ "`_fs_type $TEST_DEV`" != "$FSTYP" ]
3782         then
3783                 echo "common/rc: Error: \$TEST_DEV ($TEST_DEV) is not a MOUNTED $FSTYP filesystem"
3784                 # raw $DF_PROG cannot handle NFS/CIFS/overlay correctly
3785                 _df_device $TEST_DEV
3786                 exit 1
3787         fi
3788         # Figure out if we need to add -F ("foreign", deprecated) option to xfs_io
3789         xfs_io -c stat $TEST_DIR 2>&1 | grep -q "is not on an XFS filesystem" && \
3790         export XFS_IO_PROG="$XFS_IO_PROG -F"
3791
3792         # xfs_copy doesn't work on v5 xfs yet without -d option
3793         if [ "$FSTYP" == "xfs" ] && [[ $MKFS_OPTIONS =~ crc=1 ]]; then
3794                 export XFS_COPY_PROG="$XFS_COPY_PROG -d"
3795         fi
3796 }
3797
3798 # get real device path name by following link
3799 _real_dev()
3800 {
3801         local _dev=$1
3802         if [ -b "$_dev" ] && [ -L "$_dev" ]; then
3803                 _dev=`readlink -f "$_dev"`
3804         fi
3805         echo $_dev
3806 }
3807
3808 # basename of a device
3809 _short_dev()
3810 {
3811         echo `basename $(_real_dev $1)`
3812 }
3813
3814 _sysfs_dev()
3815 {
3816         local _dev=$1
3817         local _maj=$(stat -c%t $_dev | tr [:lower:] [:upper:])
3818         local _min=$(stat -c%T $_dev | tr [:lower:] [:upper:])
3819         _maj=$(echo "ibase=16; $_maj" | bc)
3820         _min=$(echo "ibase=16; $_min" | bc)
3821         echo /sys/dev/block/$_maj:$_min
3822 }
3823
3824 get_block_size()
3825 {
3826         if [ -z $1 ] || [ ! -d $1 ]; then
3827                 echo "Missing mount point argument for get_block_size"
3828                 exit 1
3829         fi
3830         echo `stat -f -c %S $1`
3831 }
3832
3833 get_page_size()
3834 {
3835         echo $(getconf PAGE_SIZE)
3836 }
3837
3838
3839 run_fsx()
3840 {
3841         echo fsx $@
3842         args=`echo $@ | sed -e "s/ BSIZE / $bsize /g" -e "s/ PSIZE / $psize /g"`
3843         set -- $here/ltp/fsx $args $FSX_AVOID $TEST_DIR/junk
3844         echo "$@" >>$seqres.full
3845         rm -f $TEST_DIR/junk
3846         "$@" 2>&1 | tee -a $seqres.full >$tmp.fsx
3847         if [ ${PIPESTATUS[0]} -ne 0 ]; then
3848                 cat $tmp.fsx
3849                 exit 1
3850         fi
3851 }
3852
3853 # Test for the existence of a sysfs entry at /sys/fs/$FSTYP/DEV/$ATTR
3854 #
3855 # Only one argument is needed:
3856 #  - attr: path name under /sys/fs/$FSTYP/DEV
3857 #
3858 # Usage example:
3859 #   _require_fs_sysfs error/fail_at_unmount
3860 _require_fs_sysfs()
3861 {
3862         local attr=$1
3863         local dname=$(_short_dev $TEST_DEV)
3864
3865         if [ -z "$attr" -o -z "$dname" ];then
3866                 _fail "Usage: _require_fs_sysfs <sysfs_attr_path>"
3867         fi
3868
3869         if [ ! -e /sys/fs/${FSTYP}/${dname}/${attr} ];then
3870                 _notrun "This test requires /sys/fs/${FSTYP}/${dname}/${attr}"
3871         fi
3872 }
3873
3874 # Write "content" into /sys/fs/$FSTYP/$DEV/$ATTR
3875 #
3876 # All arguments are necessary, and in this order:
3877 #  - dev: device name, e.g. $SCRATCH_DEV
3878 #  - attr: path name under /sys/fs/$FSTYP/$dev
3879 #  - content: the content of $attr
3880 #
3881 # Usage example:
3882 #   _set_fs_sysfs_attr /dev/mapper/scratch-dev error/fail_at_unmount 0
3883 _set_fs_sysfs_attr()
3884 {
3885         local dev=$1
3886         shift
3887         local attr=$1
3888         shift
3889         local content="$*"
3890
3891         if [ ! -b "$dev" -o -z "$attr" -o -z "$content" ];then
3892                 _fail "Usage: _set_fs_sysfs_attr <mounted_device> <attr> <content>"
3893         fi
3894
3895         local dname=$(_short_dev $dev)
3896         echo "$content" > /sys/fs/${FSTYP}/${dname}/${attr}
3897 }
3898
3899 # Print the content of /sys/fs/$FSTYP/$DEV/$ATTR
3900 #
3901 # All arguments are necessary, and in this order:
3902 #  - dev: device name, e.g. $SCRATCH_DEV
3903 #  - attr: path name under /sys/fs/$FSTYP/$dev
3904 #
3905 # Usage example:
3906 #   _get_fs_sysfs_attr /dev/mapper/scratch-dev error/fail_at_unmount
3907 _get_fs_sysfs_attr()
3908 {
3909         local dev=$1
3910         local attr=$2
3911
3912         if [ ! -b "$dev" -o -z "$attr" ];then
3913                 _fail "Usage: _get_fs_sysfs_attr <mounted_device> <attr>"
3914         fi
3915
3916         local dname=$(_short_dev $dev)
3917         cat /sys/fs/${FSTYP}/${dname}/${attr}
3918 }
3919
3920
3921 # Reset all xfs error handling attributes, set them to original
3922 # status.
3923 #
3924 # Only one argument, and it's mandatory:
3925 #  - dev: device name, e.g. $SCRATCH_DEV
3926 #
3927 # Note: this function only works for XFS
3928 _reset_xfs_sysfs_error_handling()
3929 {
3930         local dev=$1
3931
3932         if [ ! -b "$dev" -o "$FSTYP" != "xfs" ];then
3933                 _fail "Usage: reset_xfs_sysfs_error_handling <device>"
3934         fi
3935
3936         _set_fs_sysfs_attr $dev error/fail_at_unmount 1
3937         echo -n "error/fail_at_unmount="
3938         _get_fs_sysfs_attr $dev error/fail_at_unmount
3939
3940         # Make sure all will be configured to retry forever by default, except
3941         # for ENODEV, which is an unrecoverable error, so it will be configured
3942         # to not retry on error by default.
3943         for e in default EIO ENOSPC; do
3944                 _set_fs_sysfs_attr $dev \
3945                                    error/metadata/${e}/max_retries -1
3946                 echo -n "error/metadata/${e}/max_retries="
3947                 _get_fs_sysfs_attr $dev error/metadata/${e}/max_retries
3948
3949                 _set_fs_sysfs_attr $dev \
3950                                    error/metadata/${e}/retry_timeout_seconds 0
3951                 echo -n "error/metadata/${e}/retry_timeout_seconds="
3952                 _get_fs_sysfs_attr $dev \
3953                                    error/metadata/${e}/retry_timeout_seconds
3954         done
3955 }
3956
3957 # Skip if we are running an older binary without the stricter input checks.
3958 # Make multiple checks to be sure that there is no regression on the one
3959 # selected feature check, which would skew the result.
3960 #
3961 # At first, make a common function that runs the tests and returns
3962 # number of failed cases.
3963 _xfs_mkfs_validation_check()
3964 {
3965         local tmpfile=`mktemp`
3966         local cmd="$MKFS_XFS_PROG -f -N -d file,name=$tmpfile,size=1g"
3967
3968         $cmd -s size=2s >/dev/null 2>&1
3969         local sum=$?
3970
3971         $cmd -l version=2,su=260k >/dev/null 2>&1
3972         sum=`expr $sum + $?`
3973
3974         rm -f $tmpfile
3975         return $sum
3976 }
3977
3978 # Skip the test if all calls passed - mkfs accepts invalid input
3979 _require_xfs_mkfs_validation()
3980 {
3981         _xfs_mkfs_validation_check
3982         if [ "$?" -eq 0 ]; then
3983                 _notrun "Requires newer mkfs with stricter input checks: the oldest supported version of xfsprogs is 4.7."
3984         fi
3985 }
3986
3987 # The oposite of _require_xfs_mkfs_validation.
3988 _require_xfs_mkfs_without_validation()
3989 {
3990         _xfs_mkfs_validation_check
3991         if [ "$?" -ne 0 ]; then
3992                 _notrun "Requires older mkfs without strict input checks: the last supported version of xfsprogs is 4.5."
3993         fi
3994 }
3995
3996 init_rc
3997
3998 ################################################################################
3999 # make sure this script returns success
4000 /bin/true