xfs: fix $XFS_DB_PROG usage
[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_db()
1110 {
1111         $XFS_DB_PROG "$@" $(_scratch_xfs_db_options)
1112 }
1113
1114 _scratch_xfs_logprint()
1115 {
1116     SCRATCH_OPTIONS=""
1117     [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_LOGDEV" ] && \
1118         SCRATCH_OPTIONS="-l$SCRATCH_LOGDEV"
1119     $XFS_LOGPRINT_PROG $SCRATCH_OPTIONS $* $SCRATCH_DEV
1120 }
1121
1122 _test_xfs_logprint()
1123 {
1124         TEST_OPTIONS=""
1125         [ "$USE_EXTERNAL" = yes -a ! -z "$TEST_LOGDEV" ] && \
1126                 TEST_OPTIONS="-l$TEST_LOGDEV"
1127         $XFS_LOGPRINT_PROG $TEST_OPTIONS $* $TEST_DEV
1128 }
1129
1130 _scratch_xfs_check()
1131 {
1132     SCRATCH_OPTIONS=""
1133     [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_LOGDEV" ] && \
1134         SCRATCH_OPTIONS="-l $SCRATCH_LOGDEV"
1135     [ "$LARGE_SCRATCH_DEV" = yes ] && \
1136         SCRATCH_OPTIONS=$SCRATCH_OPTIONS" -t"
1137     _xfs_check $SCRATCH_OPTIONS $* $SCRATCH_DEV
1138 }
1139
1140 _scratch_xfs_repair()
1141 {
1142     SCRATCH_OPTIONS=""
1143     [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_LOGDEV" ] && \
1144         SCRATCH_OPTIONS="-l$SCRATCH_LOGDEV"
1145     [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_RTDEV" ] && \
1146         SCRATCH_OPTIONS=$SCRATCH_OPTIONS" -r$SCRATCH_RTDEV"
1147     [ "$LARGE_SCRATCH_DEV" = yes ] && SCRATCH_OPTIONS=$SCRATCH_OPTIONS" -t"
1148     $XFS_REPAIR_PROG $SCRATCH_OPTIONS $* $SCRATCH_DEV
1149 }
1150
1151 # Repair scratch filesystem.  Returns 0 if the FS is good to go (either no
1152 # errors found or errors were fixed) and nonzero otherwise; also spits out
1153 # a complaint on stderr if fsck didn't tell us that the FS is good to go.
1154 _repair_scratch_fs()
1155 {
1156     case $FSTYP in
1157     xfs)
1158         _scratch_xfs_repair "$@" 2>&1
1159         res=$?
1160         if [ "$res" -ne 0 ]; then
1161                 echo "xfs_repair returns $res; replay log?"
1162                 _scratch_mount
1163                 res=$?
1164                 if [ "$res" -gt 0 ]; then
1165                         echo "mount returns $res; zap log?"
1166                         _scratch_xfs_repair -L 2>&1
1167                         echo "log zap returns $?"
1168                 else
1169                         umount "$SCRATCH_MNT"
1170                 fi
1171                 _scratch_xfs_repair "$@" 2>&1
1172                 res=$?
1173         fi
1174         test $res -ne 0 && >&2 echo "xfs_repair failed, err=$res"
1175         return $res
1176         ;;
1177     *)
1178         # Let's hope fsck -y suffices...
1179         fsck -t $FSTYP -y $SCRATCH_DEV 2>&1
1180         res=$?
1181         case $res in
1182         0|1|2)
1183                 res=0
1184                 ;;
1185         *)
1186                 >&2 echo "fsck.$FSTYP failed, err=$res"
1187                 ;;
1188         esac
1189         return $res
1190         ;;
1191     esac
1192 }
1193
1194 _get_pids_by_name()
1195 {
1196     if [ $# -ne 1 ]
1197     then
1198         echo "Usage: _get_pids_by_name process-name" 1>&2
1199         exit 1
1200     fi
1201
1202     # Algorithm ... all ps(1) variants have a time of the form MM:SS or
1203     # HH:MM:SS before the psargs field, use this as the search anchor.
1204     #
1205     # Matches with $1 (process-name) occur if the first psarg is $1
1206     # or ends in /$1 ... the matching uses sed's regular expressions,
1207     # so passing a regex into $1 will work.
1208
1209     ps $PS_ALL_FLAGS \
1210     | sed -n \
1211         -e 's/$/ /' \
1212         -e 's/[         ][      ]*/ /g' \
1213         -e 's/^ //' \
1214         -e 's/^[^ ]* //' \
1215         -e "/[0-9]:[0-9][0-9]  *[^ ]*\/$1 /s/ .*//p" \
1216         -e "/[0-9]:[0-9][0-9]  *$1 /s/ .*//p"
1217 }
1218
1219 # fix malloc libs output
1220 #
1221 _fix_malloc()
1222 {
1223     # filter out the Electric Fence notice
1224     $PERL_PROG -e '
1225         while (<>) {
1226             if (defined $o && /^\s+Electric Fence/) {
1227                 chomp($o);
1228                 print "$o";
1229                 undef $o;
1230                 next;
1231             }
1232             print $o if (defined $o);
1233
1234             $o=$_;
1235         }
1236         print $o if (defined $o);
1237     '
1238 }
1239
1240 #
1241 # _df_device : get an IRIX style df line for a given device
1242 #
1243 #       - returns "" if not mounted
1244 #       - returns fs type in field two (ala IRIX)
1245 #       - joins line together if split by fancy df formatting
1246 #       - strips header etc
1247 #
1248
1249 _df_device()
1250 {
1251     if [ $# -ne 1 ]
1252     then
1253         echo "Usage: _df_device device" 1>&2
1254         exit 1
1255     fi
1256
1257     # Note that we use "==" here so awk doesn't try to interpret an NFS over
1258     # IPv6 server as a regular expression.
1259     $DF_PROG 2>/dev/null | $AWK_PROG -v what=$1 '
1260         ($1==what) && (NF==1) {
1261             v=$1
1262             getline
1263             print v, $0
1264             exit
1265         }
1266         ($1==what) {
1267             print
1268             exit
1269         }
1270     '
1271 }
1272
1273 #
1274 # _df_dir : get an IRIX style df line for device where a directory resides
1275 #
1276 #       - returns fs type in field two (ala IRIX)
1277 #       - joins line together if split by fancy df formatting
1278 #       - strips header etc
1279 #
1280
1281 _df_dir()
1282 {
1283     if [ $# -ne 1 ]
1284     then
1285         echo "Usage: _df_dir device" 1>&2
1286         exit 1
1287     fi
1288
1289     $DF_PROG $1 2>/dev/null | $AWK_PROG -v what=$1 '
1290         NR == 2 && NF==1 {
1291             v=$1
1292             getline
1293             print v, $0;
1294             exit 0
1295         }
1296         NR == 2 {
1297             print;
1298             exit 0
1299         }
1300         {}
1301     '
1302     # otherwise, nada
1303 }
1304
1305 # return percentage used disk space for mounted device
1306
1307 _used()
1308 {
1309     if [ $# -ne 1 ]
1310     then
1311         echo "Usage: _used device" 1>&2
1312         exit 1
1313     fi
1314
1315     _df_device $1 | $AWK_PROG '{ sub("%", "") ; print $6 }'
1316 }
1317
1318 # return the FS type of a mounted device
1319 #
1320 _fs_type()
1321 {
1322     if [ $# -ne 1 ]
1323     then
1324         echo "Usage: _fs_type device" 1>&2
1325         exit 1
1326     fi
1327
1328     #
1329     # The Linux kernel shows NFSv4 filesystems in df output as
1330     # filesystem type nfs4, although we mounted it as nfs earlier.
1331     # Fix the filesystem type up here so that the callers don't
1332     # have to bother with this quirk.
1333     #
1334     _df_device $1 | $AWK_PROG '{ print $2 }' | sed -e 's/nfs4/nfs/'
1335 }
1336
1337 # return the FS mount options of a mounted device
1338 #
1339 # should write a version which just parses the output of mount for IRIX
1340 # compatibility, but since this isn't used at all, at the moment I'll leave
1341 # this for now
1342 #
1343 _fs_options()
1344 {
1345     if [ $# -ne 1 ]
1346     then
1347         echo "Usage: _fs_options device" 1>&2
1348         exit 1
1349     fi
1350
1351     $AWK_PROG -v dev=$1 '
1352         match($1,dev) { print $4 }
1353     ' </proc/mounts
1354 }
1355
1356 # returns device number if a file is a block device
1357 #
1358 _is_block_dev()
1359 {
1360     if [ $# -ne 1 ]
1361     then
1362         echo "Usage: _is_block_dev dev" 1>&2
1363         exit 1
1364     fi
1365
1366     _dev=$1
1367     if [ -L "${_dev}" ]; then
1368         _dev=`readlink -f "${_dev}"`
1369     fi
1370
1371     if [ -b "${_dev}" ]; then
1372         src/lstat64 "${_dev}" | $AWK_PROG '/Device type:/ { print $9 }'
1373     fi
1374 }
1375
1376 # Do a command, log it to $seqres.full, optionally test return status
1377 # and die if command fails. If called with one argument _do executes the
1378 # command, logs it, and returns its exit status. With two arguments _do
1379 # first prints the message passed in the first argument, and then "done"
1380 # or "fail" depending on the return status of the command passed in the
1381 # second argument. If the command fails and the variable _do_die_on_error
1382 # is set to "always" or the two argument form is used and _do_die_on_error
1383 # is set to "message_only" _do will print an error message to
1384 # $seqres.out and exit.
1385
1386 _do()
1387 {
1388     if [ $# -eq 1 ]; then
1389         _cmd=$1
1390     elif [ $# -eq 2 ]; then
1391         _note=$1
1392         _cmd=$2
1393         echo -n "$_note... "
1394     else
1395         echo "Usage: _do [note] cmd" 1>&2
1396         status=1; exit
1397     fi
1398
1399     (eval "echo '---' \"$_cmd\"") >>$seqres.full
1400     (eval "$_cmd") >$tmp._out 2>&1; ret=$?
1401     cat $tmp._out | _fix_malloc >>$seqres.full
1402     if [ $# -eq 2 ]; then
1403         if [ $ret -eq 0 ]; then
1404             echo "done"
1405         else
1406             echo "fail"
1407         fi
1408     fi
1409     if [ $ret -ne 0  ] \
1410         && [ "$_do_die_on_error" = "always" \
1411             -o \( $# -eq 2 -a "$_do_die_on_error" = "message_only" \) ]
1412     then
1413         [ $# -ne 2 ] && echo
1414         eval "echo \"$_cmd\" failed \(returned $ret\): see $seqres.full"
1415         status=1; exit
1416     fi
1417
1418     return $ret
1419 }
1420
1421 # bail out, setting up .notrun file. Need to kill the filesystem check files
1422 # here, otherwise they are set incorrectly for the next test.
1423 #
1424 _notrun()
1425 {
1426     echo "$*" > $seqres.notrun
1427     echo "$seq not run: $*"
1428     rm -f ${RESULT_DIR}/require_test
1429     rm -f ${RESULT_DIR}/require_scratch
1430     status=0
1431     exit
1432 }
1433
1434 # just plain bail out
1435 #
1436 _fail()
1437 {
1438     echo "$*" | tee -a $seqres.full
1439     echo "(see $seqres.full for details)"
1440     status=1
1441     exit 1
1442 }
1443
1444 # tests whether $FSTYP is one of the supported filesystems for a test
1445 #
1446 _supported_fs()
1447 {
1448     for f
1449     do
1450         if [ "$f" = "$FSTYP" -o "$f" = "generic" ]
1451         then
1452             return
1453         fi
1454     done
1455
1456     _notrun "not suitable for this filesystem type: $FSTYP"
1457 }
1458
1459
1460 # tests whether $FSTYP is one of the supported OSes for a test
1461 #
1462 _supported_os()
1463 {
1464     for h
1465     do
1466         if [ "$h" = "$HOSTOS" ]
1467         then
1468             return
1469         fi
1470     done
1471
1472     _notrun "not suitable for this OS: $HOSTOS"
1473 }
1474
1475 _require_btrfs_loadable()
1476 {
1477         modprobe -r btrfs || _notrun "btrfs unloadable"
1478         modprobe btrfs || _notrun "Can't load btrfs"
1479 }
1480
1481 _reload_btrfs_ko()
1482 {
1483         modprobe -r btrfs || _fail "btrfs unload failed"
1484         modprobe btrfs || _fail "btrfs load failed"
1485 }
1486
1487 # this test needs a scratch partition - check we're ok & unmount it
1488 # No post-test check of the device is required. e.g. the test intentionally
1489 # finishes the test with the filesystem in a corrupt state
1490 _require_scratch_nocheck()
1491 {
1492     case "$FSTYP" in
1493         nfs*)
1494                 echo $SCRATCH_DEV | grep -q ":/" > /dev/null 2>&1
1495                 if [ -z "$SCRATCH_DEV" -o "$?" != "0" ]; then
1496                         _notrun "this test requires a valid \$SCRATCH_DEV"
1497                 fi
1498                 if [ ! -d "$SCRATCH_MNT" ]; then
1499                         _notrun "this test requires a valid \$SCRATCH_MNT"
1500                 fi
1501                 ;;
1502         cifs)
1503                 echo $SCRATCH_DEV | grep -q "//" > /dev/null 2>&1
1504                 if [ -z "$SCRATCH_DEV" -o "$?" != "0" ]; then
1505                         _notrun "this test requires a valid \$SCRATCH_DEV"
1506                 fi
1507                 if [ ! -d "$SCRATCH_MNT" ]; then
1508                      _notrun "this test requires a valid \$SCRATCH_MNT"
1509                 fi
1510                 ;;
1511         overlay)
1512                 if [ -z "$SCRATCH_DEV" -o ! -d "$SCRATCH_DEV" ]; then
1513                         _notrun "this test requires a valid \$SCRATCH_DEV as ovl base dir"
1514                 fi
1515                 if [ ! -d "$SCRATCH_MNT" ]; then
1516                         _notrun "this test requires a valid \$SCRATCH_MNT"
1517                 fi
1518                 ;;
1519         tmpfs)
1520                 if [ -z "$SCRATCH_DEV" -o ! -d "$SCRATCH_MNT" ];
1521                 then
1522                     _notrun "this test requires a valid \$SCRATCH_MNT and unique $SCRATCH_DEV"
1523                 fi
1524                 ;;
1525         *)
1526                  if [ -z "$SCRATCH_DEV" -o "`_is_block_dev "$SCRATCH_DEV"`" = "" ]
1527                  then
1528                      _notrun "this test requires a valid \$SCRATCH_DEV"
1529                  fi
1530                  if [ "`_is_block_dev "$SCRATCH_DEV"`" = "`_is_block_dev "$TEST_DEV"`" ]
1531                  then
1532                      _notrun "this test requires a valid \$SCRATCH_DEV"
1533                  fi
1534                 if [ ! -d "$SCRATCH_MNT" ]
1535                 then
1536                      _notrun "this test requires a valid \$SCRATCH_MNT"
1537                 fi
1538                  ;;
1539     esac
1540
1541     # mounted?
1542     # Note that we use -F here so grep doesn't try to interpret an NFS over
1543     # IPv6 server as a regular expression.
1544     mount_rec=`_mount | grep -F $SCRATCH_DEV`
1545     if [ "$mount_rec" ]
1546     then
1547         # if it's mounted, make sure its on $SCRATCH_MNT
1548         if ! echo $mount_rec | grep -q $SCRATCH_MNT
1549         then
1550             echo "\$SCRATCH_DEV=$SCRATCH_DEV is mounted but not on \$SCRATCH_MNT=$SCRATCH_MNT - aborting"
1551             echo "Already mounted result:"
1552             echo $mount_rec
1553             exit 1
1554         fi
1555         # and then unmount it
1556         if ! _scratch_unmount
1557         then
1558             echo "failed to unmount $SCRATCH_DEV"
1559             exit 1
1560         fi
1561     fi
1562     rm -f ${RESULT_DIR}/require_scratch
1563 }
1564
1565 # we need the scratch device and it should be checked post test.
1566 _require_scratch()
1567 {
1568         _require_scratch_nocheck
1569         touch ${RESULT_DIR}/require_scratch
1570 }
1571
1572
1573 # this test needs a test partition - check we're ok & mount it
1574 #
1575 _require_test()
1576 {
1577     case "$FSTYP" in
1578         nfs*)
1579                 echo $TEST_DEV | grep -q ":/" > /dev/null 2>&1
1580                 if [ -z "$TEST_DEV" -o "$?" != "0" ]; then
1581                         _notrun "this test requires a valid \$TEST_DIR"
1582                 fi
1583                 if [ ! -d "$TEST_DIR" ]; then
1584                         _notrun "this test requires a valid \$TEST_DIR"
1585                 fi
1586                 ;;
1587         cifs)
1588                 echo $TEST_DEV | grep -q "//" > /dev/null 2>&1
1589                 if [ -z "$TEST_DEV" -o "$?" != "0" ]; then
1590                         _notrun "this test requires a valid \$TEST_DEV"
1591                 fi
1592                 if [ ! -d "$TEST_DIR" ]; then
1593                      _notrun "this test requires a valid \$TEST_DIR"
1594                 fi
1595                 ;;
1596         overlay)
1597                 if [ -z "$TEST_DEV" -o ! -d "$TEST_DEV" ]; then
1598                         _notrun "this test requires a valid \$TEST_DEV as ovl base dir"
1599                 fi
1600                 if [ ! -d "$TEST_DIR" ]; then
1601                         _notrun "this test requires a valid \$TEST_DIR"
1602                 fi
1603                 ;;
1604         tmpfs)
1605                 if [ -z "$TEST_DEV" -o ! -d "$TEST_DIR" ];
1606                 then
1607                     _notrun "this test requires a valid \$TEST_DIR and unique $TEST_DEV"
1608                 fi
1609                 ;;
1610         *)
1611                  if [ -z "$TEST_DEV" ] || [ "`_is_block_dev "$TEST_DEV"`" = "" ]
1612                  then
1613                      _notrun "this test requires a valid \$TEST_DEV"
1614                  fi
1615                  if [ "`_is_block_dev "$SCRATCH_DEV"`" = "`_is_block_dev "$TEST_DEV"`" ]
1616                  then
1617                      _notrun "this test requires a valid \$TEST_DEV"
1618                  fi
1619                 if [ ! -d "$TEST_DIR" ]
1620                 then
1621                      _notrun "this test requires a valid \$TEST_DIR"
1622                 fi
1623                  ;;
1624     esac
1625
1626     # mounted?
1627     # Note that we use -F here so grep doesn't try to interpret an NFS over
1628     # IPv6 server as a regular expression.
1629     mount_rec=`_mount | grep -F $TEST_DEV`
1630     if [ "$mount_rec" ]
1631     then
1632         # if it's mounted, make sure its on $TEST_DIR
1633         if ! echo $mount_rec | grep -q $TEST_DIR
1634         then
1635             echo "\$TEST_DEV=$TEST_DEV is mounted but not on \$TEST_DIR=$TEST_DIR - aborting"
1636             echo "Already mounted result:"
1637             echo $mount_rec
1638             exit 1
1639         fi
1640     else
1641         out=`_mount_or_remount_rw "$MOUNT_OPTIONS" $TEST_DEV $TEST_DIR`
1642         if [ $? -ne 1 ]; then
1643                 echo $out
1644                 exit 1
1645         fi
1646     fi
1647     touch ${RESULT_DIR}/require_test
1648 }
1649
1650 # this test needs a logdev
1651 #
1652 _require_logdev()
1653 {
1654     [ -z "$SCRATCH_LOGDEV" -o ! -b "$SCRATCH_LOGDEV" ] && \
1655         _notrun "This test requires a valid \$SCRATCH_LOGDEV"
1656     [ "$USE_EXTERNAL" != yes ] && \
1657         _notrun "This test requires USE_EXTERNAL to be enabled"
1658
1659     # ensure its not mounted
1660     $UMOUNT_PROG $SCRATCH_LOGDEV 2>/dev/null
1661 }
1662
1663 # this test requires loopback device support
1664 #
1665 _require_loop()
1666 {
1667     if [ "$HOSTOS" != "Linux" ]
1668     then
1669         _notrun "This test requires linux for loopback device support"
1670     fi
1671
1672     modprobe loop >/dev/null 2>&1
1673     if grep loop /proc/devices >/dev/null 2>&1
1674     then
1675         :
1676     else
1677         _notrun "This test requires loopback device support"
1678     fi
1679 }
1680
1681 # this test requires ext2 filesystem support
1682 #
1683 _require_ext2()
1684 {
1685     if [ "$HOSTOS" != "Linux" ]
1686     then
1687         _notrun "This test requires linux for ext2 filesystem support"
1688     fi
1689
1690     modprobe ext2 >/dev/null 2>&1
1691     if grep ext2 /proc/filesystems >/dev/null 2>&1
1692     then
1693         :
1694     else
1695         _notrun "This test requires ext2 filesystem support"
1696     fi
1697 }
1698
1699 # this test requires that (large) loopback device files are not in use
1700 #
1701 _require_no_large_scratch_dev()
1702 {
1703     [ "$LARGE_SCRATCH_DEV" = yes ] && \
1704         _notrun "Large filesystem testing in progress, skipped this test"
1705 }
1706
1707 # this test requires that a realtime subvolume is in use, and
1708 # that the kernel supports realtime as well.
1709 #
1710 _require_realtime()
1711 {
1712     [ "$USE_EXTERNAL" = yes ] || \
1713         _notrun "External volumes not in use, skipped this test"
1714     [ "$SCRATCH_RTDEV" = "" ] && \
1715         _notrun "Realtime device required, skipped this test"
1716 }
1717
1718 # this test requires that a specified command (executable) exists
1719 # $1 - command, $2 - name for error message
1720 #
1721 # Note: the command string might have parameters, so strip them before checking
1722 # whether it is executable.
1723 _require_command()
1724 {
1725         if [ $# -eq 2 ]; then
1726                 _name="$2"
1727         elif [ $# -eq 1 ]; then
1728                 _name="$1"
1729         else
1730                 _fail "usage: _require_command <command> [<name>]"
1731         fi
1732
1733         _command=`echo "$1" | awk '{ print $1 }'`
1734         if [ ! -x "$_command" ]; then
1735                 _notrun "$_name utility required, skipped this test"
1736         fi
1737 }
1738
1739 # this test requires the device to be valid block device
1740 # $1 - device
1741 _require_block_device()
1742 {
1743         if [ -z "$1" ]; then
1744                 echo "Usage: _require_block_device <dev>" 1>&2
1745                 exit 1
1746         fi
1747         if [ "`_is_block_dev "$1"`" == "" ]; then
1748                 _notrun "require $1 to be valid block disk"
1749         fi
1750 }
1751
1752 # brd based ram disks erase the device when they receive a flush command when no
1753 # active references are present. This causes problems for DM devices sitting on
1754 # top of brd devices as DM doesn't hold active references to the brd device.
1755 _require_sane_bdev_flush()
1756 {
1757         echo $1 | grep -q "^/dev/ram[0-9]\+$"
1758         if [ $? -eq 0 ]; then
1759                 _notrun "This test requires a sane block device flush"
1760         fi
1761 }
1762
1763 # this test requires a specific device mapper target
1764 _require_dm_target()
1765 {
1766         _target=$1
1767
1768         # require SCRATCH_DEV to be a valid block device with sane BLKFLSBUF
1769         # behaviour
1770         _require_block_device $SCRATCH_DEV
1771         _require_sane_bdev_flush $SCRATCH_DEV
1772         _require_command "$DMSETUP_PROG" dmsetup
1773
1774         modprobe dm-$_target >/dev/null 2>&1
1775
1776         $DMSETUP_PROG targets 2>&1 | grep -q ^$_target
1777         if [ $? -ne 0 ]; then
1778                 _notrun "This test requires dm $_target support"
1779         fi
1780 }
1781
1782 # this test requires the projid32bit feature to be available in mkfs.xfs.
1783 #
1784 _require_projid32bit()
1785 {
1786        _scratch_mkfs_xfs_supported -i projid32bit=1 >/dev/null 2>&1 \
1787            || _notrun "mkfs.xfs doesn't have projid32bit feature"
1788 }
1789
1790 _require_projid16bit()
1791 {
1792         _scratch_mkfs_xfs_supported -i projid32bit=0 >/dev/null 2>&1 \
1793            || _notrun "16 bit project IDs not supported on $SCRATCH_DEV"
1794 }
1795
1796 # this test requires the crc feature to be available in mkfs.xfs
1797 #
1798 _require_xfs_mkfs_crc()
1799 {
1800         _scratch_mkfs_xfs_supported -m crc=1 >/dev/null 2>&1 \
1801            || _notrun "mkfs.xfs doesn't have crc feature"
1802 }
1803
1804 # this test requires the xfs kernel support crc feature
1805 #
1806 _require_xfs_crc()
1807 {
1808         _scratch_mkfs_xfs -m crc=1 >/dev/null 2>&1
1809         _scratch_mount >/dev/null 2>&1 \
1810            || _notrun "Kernel doesn't support crc feature"
1811         _scratch_unmount
1812 }
1813
1814 # this test requires the ext4 kernel support crc feature on scratch device
1815 #
1816 _require_scratch_ext4_crc()
1817 {
1818         _scratch_mkfs_ext4 >/dev/null 2>&1
1819         dumpe2fs -h $SCRATCH_DEV 2> /dev/null | grep -q metadata_csum || _notrun "metadata_csum not supported by this filesystem"
1820         _scratch_mount >/dev/null 2>&1 \
1821            || _notrun "Kernel doesn't support metadata_csum feature"
1822         _scratch_unmount
1823 }
1824
1825 # this test requires the xfs kernel support crc feature on scratch device
1826 #
1827 _require_scratch_xfs_crc()
1828 {
1829         _scratch_mkfs_xfs >/dev/null 2>&1
1830         _scratch_mount >/dev/null 2>&1 \
1831            || _notrun "Kernel doesn't support crc feature"
1832         xfs_info $SCRATCH_MNT | grep -q 'crc=1' || _notrun "crc feature not supported by this filesystem"
1833         _scratch_unmount
1834 }
1835
1836 # this test requires the bigalloc feature to be available in mkfs.ext4
1837 #
1838 _require_ext4_mkfs_bigalloc()
1839 {
1840         $MKFS_EXT4_PROG -F -O bigalloc -n $SCRATCH_DEV 512m >/dev/null 2>&1 \
1841            || _notrun "mkfs.ext4 doesn't have bigalloc feature"
1842 }
1843
1844 # this test requires the ext4 kernel support bigalloc feature
1845 #
1846 _require_ext4_bigalloc()
1847 {
1848         $MKFS_EXT4_PROG -F -O bigalloc $SCRATCH_DEV 512m >/dev/null 2>&1
1849         _scratch_mount >/dev/null 2>&1 \
1850            || _notrun "Ext4 kernel doesn't support bigalloc feature"
1851         _scratch_unmount
1852 }
1853
1854 # this test requires the finobt feature to be available in mkfs.xfs
1855 #
1856 _require_xfs_mkfs_finobt()
1857 {
1858         _scratch_mkfs_xfs_supported -m crc=1,finobt=1 >/dev/null 2>&1 \
1859            || _notrun "mkfs.xfs doesn't have finobt feature"
1860 }
1861
1862 # this test requires the xfs kernel support finobt feature
1863 #
1864 _require_xfs_finobt()
1865 {
1866         _scratch_mkfs_xfs -m crc=1,finobt=1 >/dev/null 2>&1
1867         _scratch_mount >/dev/null 2>&1 \
1868            || _notrun "Kernel doesn't support finobt feature"
1869         _scratch_unmount
1870 }
1871
1872 # this test requires xfs sysfs attribute support
1873 #
1874 _require_xfs_sysfs()
1875 {
1876         attr=$1
1877         sysfsdir=/sys/fs/xfs
1878
1879         if [ ! -e $sysfsdir ]; then
1880                 _notrun "no kernel support for XFS sysfs attributes"
1881         fi
1882
1883         if [ ! -z $1 ] && [ ! -e $sysfsdir/$attr ]; then
1884                 _notrun "sysfs attribute '$attr' is not supported"
1885         fi
1886 }
1887
1888 # this test requires the xfs sparse inode feature
1889 #
1890 _require_xfs_sparse_inodes()
1891 {
1892         _scratch_mkfs_xfs_supported -m crc=1 -i sparse > /dev/null 2>&1 \
1893                 || _notrun "mkfs.xfs does not support sparse inodes"
1894         _scratch_mkfs_xfs -m crc=1 -i sparse > /dev/null 2>&1
1895         _scratch_mount >/dev/null 2>&1 \
1896                 || _notrun "kernel does not support sparse inodes"
1897         _scratch_unmount
1898 }
1899
1900 # this test requires that external log/realtime devices are not in use
1901 #
1902 _require_nonexternal()
1903 {
1904     [ "$USE_EXTERNAL" = yes ] && \
1905         _notrun "External device testing in progress, skipped this test"
1906 }
1907
1908 # this test requires that a (specified) aio-dio executable exists
1909 # $1 - command (optional)
1910 #
1911 _require_aiodio()
1912 {
1913     if [ -z "$1" ]
1914     then
1915         AIO_TEST=src/aio-dio-regress/aiodio_sparse2
1916         [ -x $AIO_TEST ] || _notrun "aio-dio utilities required"
1917     else
1918         AIO_TEST=src/aio-dio-regress/$1
1919         [ -x $AIO_TEST ] || _notrun "$AIO_TEST not built"
1920     fi
1921     _require_odirect
1922 }
1923
1924 # this test requires that a test program exists under src/
1925 # $1 - command (require)
1926 #
1927 _require_test_program()
1928 {
1929     SRC_TEST=src/$1
1930     [ -x $SRC_TEST ] || _notrun "$SRC_TEST not built"
1931 }
1932
1933 # run an aio-dio program
1934 # $1 - command
1935 _run_aiodio()
1936 {
1937     if [ -z "$1" ]
1938     then
1939         echo "usage: _run_aiodio command_name" 2>&1
1940         status=1; exit 1
1941     fi
1942
1943     _require_aiodio $1
1944
1945     local testtemp=$TEST_DIR/aio-testfile
1946     rm -f $testtemp
1947     $AIO_TEST $testtemp 2>&1
1948     status=$?
1949     rm -f $testtemp
1950
1951     return $status
1952 }
1953
1954 # indicate whether YP/NIS is active or not
1955 #
1956 _yp_active()
1957 {
1958         local dn
1959         dn=$(domainname 2>/dev/null)
1960         test -n "${dn}" -a "${dn}" != "(none)"
1961         echo $?
1962 }
1963
1964 # cat the password file
1965 #
1966 _cat_passwd()
1967 {
1968         [ $(_yp_active) -eq 0 ] && ypcat passwd
1969         cat /etc/passwd
1970 }
1971
1972 # cat the group file
1973 #
1974 _cat_group()
1975 {
1976         [ $(_yp_active) -eq 0 ] && ypcat group
1977         cat /etc/group
1978 }
1979
1980 # check for a user on the machine, fsgqa as default
1981 #
1982 _require_user()
1983 {
1984     qa_user=fsgqa
1985     if [ -n "$1" ];then
1986         qa_user=$1
1987     fi
1988     _cat_passwd | grep -q $qa_user
1989     [ "$?" == "0" ] || _notrun "$qa_user user not defined."
1990     echo /bin/true | su $qa_user
1991     [ "$?" == "0" ] || _notrun "$qa_user cannot execute commands."
1992 }
1993
1994 # check for a group on the machine, fsgqa as default
1995 #
1996 _require_group()
1997 {
1998     qa_group=fsgqa
1999     if [ -n "$1" ];then
2000         qa_group=$1
2001     fi
2002     _cat_group | grep -q $qa_group
2003     [ "$?" == "0" ] || _notrun "$qa_group user not defined."
2004 }
2005
2006 _filter_user_do()
2007 {
2008         perl -ne "
2009 s,.*Permission\sdenied.*,Permission denied,;
2010 s,.*no\saccess\sto\stty.*,,;
2011 s,.*no\sjob\scontrol\sin\sthis\sshell.*,,;
2012 s,^\s*$,,;
2013         print;"
2014 }
2015
2016 _user_do()
2017 {
2018     if [ "$HOSTOS" == "IRIX" ]
2019         then
2020         echo $1 | /bin/bash "su $qa_user 2>&1" | _filter_user_do
2021     else
2022         echo $1 | su $qa_user 2>&1 | _filter_user_do
2023     fi
2024 }
2025
2026 _require_xfs_io_command()
2027 {
2028         if [ -z "$1" ]
2029         then
2030                 echo "Usage: _require_xfs_io_command command [switch]" 1>&2
2031                 exit 1
2032         fi
2033         command=$1
2034         shift
2035         param="$*"
2036
2037         testfile=$TEST_DIR/$$.xfs_io
2038         case $command in
2039         "chproj")
2040                 testio=`$XFS_IO_PROG -F -f -c "chproj 0" $testfile 2>&1`
2041                 ;;
2042         "falloc" )
2043                 testio=`$XFS_IO_PROG -F -f -c "falloc 0 1m" $testfile 2>&1`
2044                 ;;
2045         "fpunch" | "fcollapse" | "zero" | "fzero" | "finsert" )
2046                 testio=`$XFS_IO_PROG -F -f -c "pwrite 0 20k" -c "fsync" \
2047                         -c "$command 4k 8k" $testfile 2>&1`
2048                 ;;
2049         "fiemap")
2050                 testio=`$XFS_IO_PROG -F -f -c "pwrite 0 20k" -c "fsync" \
2051                         -c "fiemap -v" $testfile 2>&1`
2052                 ;;
2053         "flink" )
2054                 testio=`$XFS_IO_PROG -T -F -c "flink $testfile" \
2055                         $TEST_DIR 2>&1`
2056                 echo $testio | egrep -q "invalid option|Is a directory" && \
2057                         _notrun "xfs_io $command support is missing"
2058                 ;;
2059         "fsmap" )
2060                 testio=`$XFS_IO_PROG -f -c "fsmap" $testfile 2>&1`
2061                 echo $testio | egrep -q "Inappropriate ioctl" && \
2062                         _notrun "xfs_io $command support is missing"
2063                 ;;
2064         *)
2065                 testio=`$XFS_IO_PROG -c "$command help" 2>&1`
2066         esac
2067
2068         rm -f $testfile 2>&1 > /dev/null
2069         echo $testio | grep -q "not found" && \
2070                 _notrun "xfs_io $command support is missing"
2071         echo $testio | grep -q "Operation not supported" && \
2072                 _notrun "xfs_io $command failed (old kernel/wrong fs?)"
2073         echo $testio | grep -q "foreign file active" && \
2074                 _notrun "xfs_io $command not supported on $FSTYP"
2075
2076         test -z "$param" && return
2077         $XFS_IO_PROG -c "help $command" | grep -q "^ $param --" || \
2078                 _notrun "xfs_io $command doesn't support $param"
2079 }
2080
2081 # check that xfs_db supports a specific command
2082 _require_xfs_db_command()
2083 {
2084         if [ $# -ne 1 ]
2085         then
2086                 echo "Usage: _require_xfs_db_command command" 1>&2
2087                 exit 1
2088         fi
2089         command=$1
2090
2091         _scratch_xfs_db -x -c "help" | grep $command > /dev/null || \
2092                 _notrun "xfs_db $command support is missing"
2093 }
2094
2095 # check that kernel and filesystem support direct I/O
2096 _require_odirect()
2097 {
2098         if [ $FSTYP = "ext4" ] ; then
2099                 if echo "$MOUNT_OPTIONS" | grep -q "test_dummy_encryption"; then
2100                         _notrun "ext4 encryption doesn't support O_DIRECT"
2101                 fi
2102         fi
2103         testfile=$TEST_DIR/$$.direct
2104         $XFS_IO_PROG -F -f -d -c "pwrite 0 20k" $testfile > /dev/null 2>&1
2105         if [ $? -ne 0 ]; then
2106                 _notrun "O_DIRECT is not supported"
2107         fi
2108         rm -f $testfile 2>&1 > /dev/null
2109 }
2110
2111 # Check that a fs has enough free space (in 1024b blocks)
2112 #
2113 _require_fs_space()
2114 {
2115         MNT=$1
2116         BLOCKS=$2       # in units of 1024
2117         let GB=$BLOCKS/1024/1024
2118
2119         FREE_BLOCKS=`df -kP $MNT | grep -v Filesystem | awk '{print $4}'`
2120         [ $FREE_BLOCKS -lt $BLOCKS ] && \
2121                 _notrun "This test requires at least ${GB}GB free on $MNT to run"
2122 }
2123
2124 #
2125 # Check if the filesystem supports sparse files.
2126 #
2127 # Unfortunately there is no better way to do this than a manual black list.
2128 #
2129 _require_sparse_files()
2130 {
2131     case $FSTYP in
2132     hfsplus)
2133         _notrun "Sparse files not supported by this filesystem type: $FSTYP"
2134         ;;
2135     *)
2136         ;;
2137     esac
2138 }
2139
2140 _require_debugfs()
2141 {
2142     #boot_params always present in debugfs
2143     [ -d "$DEBUGFS_MNT/boot_params" ] || _notrun "Debugfs not mounted"
2144 }
2145
2146 _require_fail_make_request()
2147 {
2148     [ -f "$DEBUGFS_MNT/fail_make_request/probability" ] \
2149         || _notrun "$DEBUGFS_MNT/fail_make_request \
2150  not found. Seems that CONFIG_FAIL_MAKE_REQUEST kernel config option not enabled"
2151 }
2152
2153 #
2154 # Check if the file system supports seek_data/hole
2155 #
2156 _require_seek_data_hole()
2157 {
2158     testfile=$TEST_DIR/$$.seek
2159     testseek=`$here/src/seek_sanity_test -t $testfile 2>&1`
2160     rm -f $testfile &>/dev/null
2161     echo $testseek | grep -q "Kernel does not support" && \
2162         _notrun "File system does not support llseek(2) SEEK_DATA/HOLE"
2163 }
2164
2165 _require_runas()
2166 {
2167         _require_test_program "runas"
2168 }
2169
2170 _runas()
2171 {
2172         "$here/src/runas" "$@"
2173 }
2174
2175 _require_richacl_prog()
2176 {
2177         _require_command "$GETRICHACL_PROG" getrichacl
2178         _require_command "$SETRICHACL_PROG" setrichacl
2179 }
2180
2181 _require_scratch_richacl_xfs()
2182 {
2183         _scratch_mkfs_xfs_supported -m richacl=1 >/dev/null 2>&1 \
2184                 || _notrun "mkfs.xfs doesn't have richacl feature"
2185         _scratch_mkfs_xfs -m richacl=1 >/dev/null 2>&1
2186         _scratch_mount >/dev/null 2>&1 \
2187                 || _notrun "kernel doesn't support richacl feature on $FSTYP"
2188         _scratch_unmount
2189 }
2190
2191 _require_scratch_richacl_ext4()
2192 {
2193         _scratch_mkfs -O richacl >/dev/null 2>&1 \
2194                 || _notrun "can't mkfs $FSTYP with option -O richacl"
2195         _scratch_mount >/dev/null 2>&1 \
2196                 || _notrun "kernel doesn't support richacl feature on $FSTYP"
2197         _scratch_unmount
2198 }
2199
2200 _require_scratch_richacl_support()
2201 {
2202         _scratch_mount
2203         $GETFATTR_PROG -n system.richacl >/dev/null 2>&1 \
2204                 || _notrun "this test requires richacl support on \$SCRATCH_DEV"
2205         _scratch_unmount
2206 }
2207
2208 _require_scratch_richacl()
2209 {
2210         case "$FSTYP" in
2211         xfs)    _require_scratch_richacl_xfs
2212                 ;;
2213         ext4)   _require_scratch_richacl_ext4
2214                 ;;
2215         nfs*|cifs|overlay)
2216                 _require_scratch_richacl_support
2217                 ;;
2218         *)      _notrun "this test requires richacl support on \$SCRATCH_DEV"
2219                 ;;
2220         esac
2221 }
2222
2223 _scratch_mkfs_richacl()
2224 {
2225         case "$FSTYP" in
2226         xfs)    _scratch_mkfs_xfs -m richacl=1
2227                 ;;
2228         ext4)   _scratch_mkfs -O richacl
2229                 ;;
2230         nfs*|cifs|overlay)
2231                 _scratch_mkfs
2232                 ;;
2233         esac
2234 }
2235
2236 # check that a FS on a device is mounted
2237 # if so, return mount point
2238 #
2239 _is_mounted()
2240 {
2241     if [ $# -ne 1 ]
2242     then
2243         echo "Usage: _is_mounted device" 1>&2
2244         exit 1
2245     fi
2246
2247     device=$1
2248
2249     if _mount | grep "$device " | $AWK_PROG -v pattern="type $FSTYP" '
2250         pattern        { print $3 ; exit 0 }
2251         END            { exit 1 }
2252     '
2253     then
2254         echo "_is_mounted: $device is not a mounted $FSTYP FS"
2255         exit 1
2256     fi
2257 }
2258
2259 # remount a FS to a new mode (ro or rw)
2260 #
2261 _remount()
2262 {
2263     if [ $# -ne 2 ]
2264     then
2265         echo "Usage: _remount device ro/rw" 1>&2
2266         exit 1
2267     fi
2268     device=$1
2269     mode=$2
2270
2271     if ! mount -o remount,$mode $device
2272     then
2273         echo "_remount: failed to remount filesystem on $device as $mode"
2274         exit 1
2275     fi
2276 }
2277
2278 # Run the appropriate repair/check on a filesystem
2279 #
2280 # if the filesystem is mounted, it's either remounted ro before being
2281 # checked or it's unmounted and then remounted
2282 #
2283
2284 # If set, we remount ro instead of unmounting for fsck
2285 USE_REMOUNT=0
2286
2287 _umount_or_remount_ro()
2288 {
2289     if [ $# -ne 1 ]
2290     then
2291         echo "Usage: _umount_or_remount_ro <device>" 1>&2
2292         exit 1
2293     fi
2294
2295     device=$1
2296     mountpoint=`_is_mounted $device`
2297
2298     if [ $USE_REMOUNT -eq 0 ]; then
2299         $UMOUNT_PROG $device
2300     else
2301         _remount $device ro
2302     fi
2303     echo "$mountpoint"
2304 }
2305
2306 _mount_or_remount_rw()
2307 {
2308         if [ $# -ne 3 ]; then
2309                 echo "Usage: _mount_or_remount_rw <opts> <dev> <mnt>" 1>&2
2310                 exit 1
2311         fi
2312         mount_opts=$1
2313         device=$2
2314         mountpoint=$3
2315
2316         if [ $USE_REMOUNT -eq 0 ]; then
2317                 if [ "$FSTYP" != "overlay" ]; then
2318                         _mount -t $FSTYP $mount_opts $device $mountpoint
2319                 else
2320                         _overlay_mount $device $mountpoint
2321                 fi
2322                 if [ $? -ne 0 ]; then
2323                         echo "!!! failed to remount $device on $mountpoint"
2324                         return 0 # ok=0
2325                 fi
2326         else
2327                 _remount $device rw
2328         fi
2329
2330         return 1 # ok=1
2331 }
2332
2333 # Check a generic filesystem in no-op mode; this assumes that the
2334 # underlying fsck program accepts "-n" for a no-op (check-only) run,
2335 # and that it will still return an errno for corruption in this mode.
2336 #
2337 # Filesystems which don't support this will need to define their
2338 # own check routine.
2339 #
2340 _check_generic_filesystem()
2341 {
2342     device=$1
2343
2344     # If type is set, we're mounted
2345     type=`_fs_type $device`
2346     ok=1
2347
2348     if [ "$type" = "$FSTYP" ]
2349     then
2350         # mounted ...
2351         mountpoint=`_umount_or_remount_ro $device`
2352     fi
2353
2354     fsck -t $FSTYP $FSCK_OPTIONS $device >$tmp.fsck 2>&1
2355     if [ $? -ne 0 ]
2356     then
2357         echo "_check_generic_filesystem: filesystem on $device is inconsistent (see $seqres.full)"
2358
2359         echo "_check_generic filesystem: filesystem on $device is inconsistent" >>$seqres.full
2360         echo "*** fsck.$FSTYP output ***"       >>$seqres.full
2361         cat $tmp.fsck                           >>$seqres.full
2362         echo "*** end fsck.$FSTYP output"       >>$seqres.full
2363
2364         ok=0
2365     fi
2366     rm -f $tmp.fsck
2367
2368     if [ $ok -eq 0 ]
2369     then
2370         echo "*** mount output ***"             >>$seqres.full
2371         _mount                                  >>$seqres.full
2372         echo "*** end mount output"             >>$seqres.full
2373     elif [ "$type" = "$FSTYP" ]
2374     then
2375         # was mounted ...
2376         _mount_or_remount_rw "$MOUNT_OPTIONS" $device $mountpoint
2377         ok=$?
2378     fi
2379
2380     if [ $ok -eq 0 ]; then
2381         status=1
2382         if [ "$iam" != "check" ]; then
2383                 exit 1
2384         fi
2385         return 1
2386     fi
2387
2388     return 0
2389 }
2390
2391 # run xfs_check and friends on a FS.
2392
2393 _check_xfs_filesystem()
2394 {
2395     if [ $# -ne 3 ]
2396     then
2397         echo "Usage: _check_xfs_filesystem device <logdev>|none <rtdev>|none" 1>&2
2398         exit 1
2399     fi
2400
2401     extra_mount_options=""
2402     extra_log_options=""
2403     extra_options=""
2404     device=$1
2405     if [ -f $device ];then
2406        extra_options="-f"
2407     fi
2408
2409     if [ "$2" != "none" ]; then
2410         extra_log_options="-l$2"
2411         extra_mount_options="-ologdev=$2"
2412     fi
2413
2414     if [ "$3" != "none" ]; then
2415         extra_rt_options="-r$3"
2416         extra_mount_options=$extra_mount_options" -ortdev=$3"
2417     fi
2418     extra_mount_options=$extra_mount_options" $MOUNT_OPTIONS"
2419
2420     [ "$FSTYP" != xfs ] && return 0
2421
2422     type=`_fs_type $device`
2423     ok=1
2424
2425     if [ "$type" = "xfs" ]
2426     then
2427         if [ -n "$TEST_XFS_SCRUB" ] && [ -x "$XFS_SCRUB_PROG" ]; then
2428             "$XFS_SCRUB_PROG" $scrubflag -vd $device >>$seqres.full
2429             if [ $? -ne 0 ]; then
2430                 echo "filesystem on $device failed scrub (see $seqres.full)"
2431                 ok=0
2432             fi
2433         fi
2434         # mounted ...
2435         mountpoint=`_umount_or_remount_ro $device`
2436     fi
2437
2438     $XFS_LOGPRINT_PROG -t $extra_log_options $device 2>&1 \
2439                 | tee $tmp.logprint | grep -q "<CLEAN>"
2440     if [ $? -ne 0 -a "$HOSTOS" = "Linux" ]
2441     then
2442         echo "_check_xfs_filesystem: filesystem on $device has dirty log (see $seqres.full)"
2443
2444         echo "_check_xfs_filesystem: filesystem on $device has dirty log"   >>$seqres.full
2445         echo "*** xfs_logprint -t output ***"   >>$seqres.full
2446         cat $tmp.logprint                       >>$seqres.full
2447         echo "*** end xfs_logprint output"      >>$seqres.full
2448
2449         ok=0
2450     fi
2451
2452     # xfs_check runs out of memory on large files, so even providing the test
2453     # option (-t) to avoid indexing the free space trees doesn't make it pass on
2454     # large filesystems. Avoid it.
2455     if [ "$LARGE_SCRATCH_DEV" != yes ]; then
2456             _xfs_check $extra_log_options $device 2>&1 |\
2457                  _fix_malloc >$tmp.fs_check
2458     fi
2459     if [ -s $tmp.fs_check ]
2460     then
2461         echo "_check_xfs_filesystem: filesystem on $device is inconsistent (c) (see $seqres.full)"
2462
2463         echo "_check_xfs_filesystem: filesystem on $device is inconsistent" >>$seqres.full
2464         echo "*** xfs_check output ***"         >>$seqres.full
2465         cat $tmp.fs_check                       >>$seqres.full
2466         echo "*** end xfs_check output"         >>$seqres.full
2467
2468         ok=0
2469     fi
2470
2471     $XFS_REPAIR_PROG -n $extra_options $extra_log_options $extra_rt_options $device >$tmp.repair 2>&1
2472     if [ $? -ne 0 ]
2473     then
2474         echo "_check_xfs_filesystem: filesystem on $device is inconsistent (r) (see $seqres.full)"
2475
2476         echo "_check_xfs_filesystem: filesystem on $device is inconsistent" >>$seqres.full
2477         echo "*** xfs_repair -n output ***"     >>$seqres.full
2478         cat $tmp.repair | _fix_malloc           >>$seqres.full
2479         echo "*** end xfs_repair output"        >>$seqres.full
2480
2481         ok=0
2482     fi
2483     rm -f $tmp.fs_check $tmp.logprint $tmp.repair
2484
2485     # Optionally test the index rebuilding behavior.
2486     if [ -n "$TEST_XFS_REPAIR_REBUILD" ]; then
2487         $XFS_REPAIR_PROG $extra_options $extra_log_options $extra_rt_options $device >$tmp.repair 2>&1
2488         if [ $? -ne 0 ]; then
2489             echo "_check_xfs_filesystem: filesystem on $device is inconsistent (rebuild) (see $seqres.full)"
2490
2491             echo "_check_xfs_filesystem: filesystem on $device is inconsistent (rebuild)" >>$seqres.full
2492             echo "*** xfs_repair output ***"    >>$seqres.full
2493             cat $tmp.repair | _fix_malloc               >>$seqres.full
2494             echo "*** end xfs_repair output"    >>$seqres.full
2495
2496             ok=0
2497         fi
2498         rm -f $tmp.repair
2499
2500         $XFS_REPAIR_PROG -n $extra_options $extra_log_options $extra_rt_options $device >$tmp.repair 2>&1
2501         if [ $? -ne 0 ]; then
2502             echo "_check_xfs_filesystem: filesystem on $device is inconsistent (rebuild-reverify) (see $seqres.full)"
2503
2504             echo "_check_xfs_filesystem: filesystem on $device is inconsistent (rebuild-reverify)" >>$seqres.full
2505             echo "*** xfs_repair -n output ***" >>$seqres.full
2506             cat $tmp.repair | _fix_malloc               >>$seqres.full
2507             echo "*** end xfs_repair output"    >>$seqres.full
2508
2509             ok=0
2510         fi
2511         rm -f $tmp.repair
2512     fi
2513
2514     if [ $ok -eq 0 ]
2515     then
2516         echo "*** mount output ***"             >>$seqres.full
2517         _mount                                  >>$seqres.full
2518         echo "*** end mount output"             >>$seqres.full
2519     elif [ "$type" = "xfs" ]
2520     then
2521         _mount_or_remount_rw "$extra_mount_options" $device $mountpoint
2522     fi
2523
2524     if [ $ok -eq 0 ]; then
2525         status=1
2526         if [ "$iam" != "check" ]; then
2527                 exit 1
2528         fi
2529         return 1
2530     fi
2531
2532     return 0
2533 }
2534
2535 # Filter the knowen errors the UDF Verifier reports.
2536 _udf_test_known_error_filter()
2537 {
2538         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."
2539
2540 }
2541
2542 _check_udf_filesystem()
2543 {
2544     [ "$DISABLE_UDF_TEST" == "1" ] && return
2545
2546     if [ $# -ne 1 -a $# -ne 2 ]
2547     then
2548         echo "Usage: _check_udf_filesystem device [last_block]" 1>&2
2549         exit 1
2550     fi
2551
2552     if [ ! -x $here/src/udf_test ]
2553     then
2554         echo "udf_test not installed, please download and build the Philips"
2555         echo "UDF Verification Software from http://www.extra.research.philips.com/udf/."
2556         echo "Then copy the udf_test binary to $here/src/."
2557         echo "If you do not wish to run udf_test then set environment variable DISABLE_UDF_TEST"
2558         echo "to 1."
2559         return
2560     fi
2561
2562     device=$1
2563     if [ $# -eq 2 ];
2564     then
2565         LAST_BLOCK=`expr \( $2 - 1 \)`
2566         OPT_ARG="-lastvalidblock $LAST_BLOCK"
2567     fi
2568
2569     rm -f $seqres.checkfs
2570     sleep 1 # Due to a problem with time stamps in udf_test
2571     $here/src/udf_test $OPT_ARG $device | tee $seqres.checkfs | egrep "Error|Warning" | \
2572         _udf_test_known_error_filter | \
2573         egrep -iv "Error count:.*[0-9]+.*total occurrences:.*[0-9]+|Warning count:.*[0-9]+.*total occurrences:.*[0-9]+" && \
2574         echo "Warning UDF Verifier reported errors see $seqres.checkfs." && return 1
2575     return 0
2576 }
2577
2578 _check_xfs_test_fs()
2579 {
2580     TEST_LOG="none"
2581     TEST_RT="none"
2582     [ "$USE_EXTERNAL" = yes -a ! -z "$TEST_LOGDEV" ] && \
2583         TEST_LOG="$TEST_LOGDEV"
2584
2585     [ "$USE_EXTERNAL" = yes -a ! -z "$TEST_RTDEV" ] && \
2586         TEST_RT="$TEST_RTDEV"
2587
2588     _check_xfs_filesystem $TEST_DEV $TEST_LOG $TEST_RT
2589
2590     # check for ipath consistency
2591     if $XFS_GROWFS_PROG -n $TEST_DIR | grep -q 'inode-paths=1'; then
2592         # errors go to stderr
2593         xfs_check_ipaths $TEST_DIR >/dev/null
2594         xfs_repair_ipaths -n $TEST_DIR >/dev/null
2595     fi
2596 }
2597
2598 _check_btrfs_filesystem()
2599 {
2600     device=$1
2601
2602     # If type is set, we're mounted
2603     type=`_fs_type $device`
2604     ok=1
2605
2606     if [ "$type" = "$FSTYP" ]
2607     then
2608         # mounted ...
2609         mountpoint=`_umount_or_remount_ro $device`
2610     fi
2611
2612     btrfsck $device >$tmp.fsck 2>&1
2613     if [ $? -ne 0 ]
2614     then
2615         echo "_check_btrfs_filesystem: filesystem on $device is inconsistent (see $seqres.full)"
2616
2617         echo "_check_btrfs_filesystem: filesystem on $device is inconsistent" >>$seqres.full
2618         echo "*** fsck.$FSTYP output ***"       >>$seqres.full
2619         cat $tmp.fsck                           >>$seqres.full
2620         echo "*** end fsck.$FSTYP output"       >>$seqres.full
2621
2622         ok=0
2623     fi
2624     rm -f $tmp.fsck
2625
2626     if [ $ok -eq 0 ]
2627     then
2628         echo "*** mount output ***"             >>$seqres.full
2629         _mount                                  >>$seqres.full
2630         echo "*** end mount output"             >>$seqres.full
2631     elif [ "$type" = "$FSTYP" ]
2632     then
2633         # was mounted ...
2634         _mount_or_remount_rw "$MOUNT_OPTIONS" $device $mountpoint
2635         ok=$?
2636     fi
2637
2638     if [ $ok -eq 0 ]; then
2639         status=1
2640         if [ "$iam" != "check" ]; then
2641                 exit 1
2642         fi
2643         return 1
2644     fi
2645
2646     return 0
2647 }
2648
2649 _check_test_fs()
2650 {
2651     case $FSTYP in
2652     xfs)
2653         _check_xfs_test_fs
2654         ;;
2655     nfs)
2656         # no way to check consistency for nfs
2657         ;;
2658     cifs)
2659         # no way to check consistency for cifs
2660         ;;
2661     overlay)
2662         # no way to check consistency for overlay
2663         ;;
2664     udf)
2665         # do nothing for now
2666         ;;
2667     btrfs)
2668         _check_btrfs_filesystem $TEST_DEV
2669         ;;
2670     tmpfs)
2671         # no way to check consistency for tmpfs
2672         ;;
2673     *)
2674         _check_generic_filesystem $TEST_DEV
2675         ;;
2676     esac
2677 }
2678
2679 _check_scratch_fs()
2680 {
2681     device=$SCRATCH_DEV
2682     [ $# -eq 1 ] && device=$1
2683
2684     case $FSTYP in
2685     xfs)
2686         SCRATCH_LOG="none"
2687         SCRATCH_RT="none"
2688         [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_LOGDEV" ] && \
2689             SCRATCH_LOG="$SCRATCH_LOGDEV"
2690
2691         [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_RTDEV" ] && \
2692             SCRATCH_RT="$SCRATCH_RTDEV"
2693
2694         _check_xfs_filesystem $device $SCRATCH_LOG $SCRATCH_RT
2695         ;;
2696     udf)
2697         _check_udf_filesystem $device $udf_fsize
2698         ;;
2699     nfs*)
2700         # Don't know how to check an NFS filesystem, yet.
2701         ;;
2702     cifs)
2703         # Don't know how to check a CIFS filesystem, yet.
2704         ;;
2705     overlay)
2706         # no way to check consistency for overlay
2707         ;;
2708     btrfs)
2709         _check_btrfs_filesystem $device
2710         ;;
2711     tmpfs)
2712         # no way to check consistency for tmpfs
2713         ;;
2714     *)
2715         _check_generic_filesystem $device
2716         ;;
2717     esac
2718 }
2719
2720 _full_fstyp_details()
2721 {
2722      [ -z "$FSTYP" ] && FSTYP=xfs
2723      if [ $FSTYP = xfs ]; then
2724         if [ -d /proc/fs/xfs ]; then
2725             if grep -q 'debug 0' /proc/fs/xfs/stat; then
2726                 FSTYP="$FSTYP (non-debug)"
2727             elif grep -q 'debug 1' /proc/fs/xfs/stat; then
2728                 FSTYP="$FSTYP (debug)"
2729             fi
2730         else
2731             if uname -a | grep -qi 'debug'; then
2732                 FSTYP="$FSTYP (debug)"
2733             else
2734                 FSTYP="$FSTYP (non-debug)"
2735             fi
2736         fi
2737      fi
2738      echo $FSTYP
2739 }
2740
2741 _full_platform_details()
2742 {
2743      os=`uname -s`
2744      host=`hostname -s`
2745      kernel=`uname -r`
2746      platform=`uname -m`
2747      echo "$os/$platform $host $kernel"
2748 }
2749
2750 _get_os_name()
2751 {
2752         if [ "`uname`" == "IRIX64" ] || [ "`uname`" == "IRIX" ]; then
2753                 echo 'irix'
2754         elif [ "`uname`" == "Linux" ]; then
2755                 echo 'linux'
2756         else
2757                 echo Unknown operating system: `uname`
2758                 exit
2759         fi
2760 }
2761
2762 _link_out_file_named()
2763 {
2764         export FEATURES=$2
2765         SUFFIX=$(perl -e '
2766                 my %feathash;
2767                 my $feature, $result, $suffix, $opts;
2768
2769                 foreach $feature (split(/,/, $ENV{"FEATURES"})) {
2770                         $feathash{$feature} = 1;
2771                 }
2772                 $result = "default";
2773                 while (<>) {
2774                         my $found = 1;
2775
2776                         chomp;
2777                         ($opts, $suffix) = split(/ *: */);
2778                         foreach my $opt (split(/,/, $opts)) {
2779                                 if (!exists($feathash{$opt})) {
2780                                         $found = 0;
2781                                         last;
2782                                 }
2783                         }
2784                         if ($found == 1) {
2785                                 $result = $suffix;
2786                                 last;
2787                         }
2788                 }
2789                 print $result
2790                 ' <$seqfull.cfg)
2791         rm -f $1
2792         SRC=$(basename $1)
2793         ln -fs $SRC.$SUFFIX $1
2794 }
2795
2796 _link_out_file()
2797 {
2798         if [ $# -eq 0 ]; then
2799                 FEATURES="$(_get_os_name)"
2800                 if [ -n "$MOUNT_OPTIONS" ]; then
2801                         FEATURES=$FEATURES,${MOUNT_OPTIONS##"-o "}
2802                 fi
2803         else
2804                 FEATURES=$1
2805         fi
2806
2807         _link_out_file_named $seqfull.out "$FEATURES"
2808 }
2809
2810 _die()
2811 {
2812         echo $@
2813         exit 1
2814 }
2815
2816 #takes files, randomdata
2817 _nfiles()
2818 {
2819         f=0
2820         while [ $f -lt $1 ]
2821         do
2822                 file=f$f
2823                 echo > $file
2824                 if [ $size -gt 0 ]; then
2825                     if [ "$2" == "false" ]; then
2826                         dd if=/dev/zero of=$file bs=1024 count=$size 2>&1 | _filter_dd
2827                     else
2828                         dd if=/dev/urandom of=$file bs=1024 count=$size 2>&1 | _filter_dd
2829                     fi
2830                 fi
2831                 let f=$f+1
2832         done
2833 }
2834
2835 # takes dirname, depth, randomdata
2836 _descend()
2837 {
2838         dirname=$1; depth=$2; randomdata=$3
2839         mkdir $dirname  || die "mkdir $dirname failed"
2840         cd $dirname
2841
2842         _nfiles $files $randomdata          # files for this dir and data type
2843
2844         [ $depth -eq 0 ] && return
2845         let deep=$depth-1 # go 1 down
2846
2847         [ $verbose = true ] && echo "descending, depth from leaves = $deep"
2848
2849         d=0
2850         while [ $d -lt $dirs ]
2851         do
2852                 _descend d$d $deep &
2853                 let d=$d+1
2854                 wait
2855         done
2856 }
2857
2858 # Populate a filesystem with inodes for performance experiments
2859 #
2860 # usage: populate [-v] [-n ndirs] [-f nfiles] [-d depth] [-r root] [-s size] [-x]
2861 #
2862 _populate_fs()
2863 {
2864     here=`pwd`
2865     dirs=5          # ndirs in each subdir till leaves
2866     size=0          # sizeof files in K
2867     files=100       # num files in _each_ subdir
2868     depth=2         # depth of tree from root to leaves
2869     verbose=false
2870     root=root       # path of initial root of directory tree
2871     randomdata=false # -x data type urandom or zero
2872
2873     OPTIND=1
2874     while getopts "d:f:n:r:s:v:x" c
2875     do
2876         case $c in
2877         d)      depth=$OPTARG;;
2878         n)      dirs=$OPTARG;;
2879         f)      files=$OPTARG;;
2880         s)      size=$OPTARG;;
2881         v)      verbose=true;;
2882         r)      root=$OPTARG;;
2883         x)      randomdata=true;;
2884         esac
2885     done
2886
2887     _descend $root $depth $randomdata
2888     wait
2889
2890     cd $here
2891
2892     [ $verbose = true ] && echo done
2893 }
2894
2895 # query whether the given file has the given inode flag set
2896 #
2897 _test_inode_flag()
2898 {
2899     flag=$1
2900     file=$2
2901
2902     if which $XFS_IO_PROG >/dev/null; then
2903         if $XFS_IO_PROG -r -c 'lsattr -v' "$file" | grep -q "$flag" ; then
2904             return 0
2905         fi
2906     fi
2907     return 1
2908 }
2909
2910 # query the given files extsize allocator hint in bytes (if any)
2911 #
2912 _test_inode_extsz()
2913 {
2914     file=$1
2915     blocks=""
2916
2917     if which $XFS_IO_PROG >/dev/null; then
2918         blocks=`$XFS_IO_PROG -r -c 'stat' "$file" | \
2919                 awk '/^xattr.extsize =/ { print $3 }'`
2920     fi
2921     [ -z "$blocks" ] && blocks="0"
2922     echo $blocks
2923 }
2924
2925 # scratch_dev_pool should contain the disks pool for the btrfs raid
2926 _require_scratch_dev_pool()
2927 {
2928         local i
2929         local ndevs
2930
2931         if [ -z "$SCRATCH_DEV_POOL" ]; then
2932                 _notrun "this test requires a valid \$SCRATCH_DEV_POOL"
2933         fi
2934
2935         if [ -z "$1" ]; then
2936                 ndevs=2
2937         else
2938                 ndevs=$1
2939         fi
2940
2941         # btrfs test case needs ndevs or more scratch_dev_pool; other FS not sure
2942         # so fail it
2943         case $FSTYP in
2944         btrfs)
2945                 if [ "`echo $SCRATCH_DEV_POOL|wc -w`" -lt $ndevs ]; then
2946                         _notrun "btrfs and this test needs $ndevs or more disks in SCRATCH_DEV_POOL"
2947                 fi
2948         ;;
2949         *)
2950                 _notrun "dev_pool is not supported by fstype \"$FSTYP\""
2951         ;;
2952         esac
2953
2954         for i in $SCRATCH_DEV_POOL; do
2955                 if [ "`_is_block_dev "$i"`" = "" ]; then
2956                         _notrun "this test requires valid block disk $i"
2957                 fi
2958                 if [ "`_is_block_dev "$i"`" = "`_is_block_dev "$TEST_DEV"`" ]; then
2959                         _notrun "$i is part of TEST_DEV, this test requires unique disks"
2960                 fi
2961                 if _mount | grep -q $i; then
2962                         if ! $UMOUNT_PROG $i; then
2963                             echo "failed to unmount $i - aborting"
2964                             exit 1
2965                         fi
2966                 fi
2967                 # to help better debug when something fails, we remove
2968                 # traces of previous btrfs FS on the dev.
2969                 dd if=/dev/zero of=$i bs=4096 count=100 > /dev/null 2>&1
2970         done
2971 }
2972
2973 # ensure devices in SCRATCH_DEV_POOL are of the same size
2974 # must be called after _require_scratch_dev_pool
2975 _require_scratch_dev_pool_equal_size()
2976 {
2977         local _size
2978         local _newsize
2979         local _dev
2980
2981         # SCRATCH_DEV has been set to the first device in SCRATCH_DEV_POOL
2982         _size=`_get_device_size $SCRATCH_DEV`
2983         for _dev in $SCRATCH_DEV_POOL; do
2984                 _newsize=`_get_device_size $_dev`
2985                 if [ $_size -ne $_newsize ]; then
2986                         _notrun "This test requires devices in SCRATCH_DEV_POOL have the same size"
2987                 fi
2988         done
2989 }
2990
2991 # We will check if the device is deletable
2992 _require_deletable_scratch_dev_pool()
2993 {
2994         local i
2995         local x
2996         for i in $SCRATCH_DEV_POOL; do
2997                 x=`echo $i | cut -d"/" -f 3`
2998                 if [ ! -f /sys/class/block/${x}/device/delete ]; then
2999                         _notrun "$i is a device which is not deletable"
3000                 fi
3001         done
3002 }
3003
3004 # We check for btrfs and (optionally) features of the btrfs command
3005 _require_btrfs()
3006 {
3007         cmd=$1
3008         _require_command "$BTRFS_UTIL_PROG" btrfs
3009         if [ -z "$1" ]; then
3010                 return 1;
3011         fi
3012         $BTRFS_UTIL_PROG $cmd --help >/dev/null 2>&1
3013         [ $? -eq 0 ] || _notrun "$BTRFS_UTIL_PROG too old (must support $cmd)"
3014 }
3015
3016 # Check that fio is present, and it is able to execute given jobfile
3017 _require_fio()
3018 {
3019         job=$1
3020
3021         _require_command "$FIO_PROG" fio
3022         if [ -z "$1" ]; then
3023                 return 1;
3024         fi
3025
3026         $FIO_PROG --warnings-fatal --showcmd $job >> $seqres.full 2>&1
3027         [ $? -eq 0 ] || _notrun "$FIO_PROG too old, see $seqres.full"
3028 }
3029
3030 # Does freeze work on this fs?
3031 _require_freeze()
3032 {
3033         xfs_freeze -f "$TEST_DIR" >/dev/null 2>&1
3034         result=$? 
3035         xfs_freeze -u "$TEST_DIR" >/dev/null 2>&1
3036         [ $result -eq 0 ] || _notrun "$FSTYP does not support freezing"
3037 }
3038
3039 # Does shutdown work on this fs?
3040 _require_scratch_shutdown()
3041 {
3042         [ -x src/godown ] || _notrun "src/godown executable not found"
3043
3044         _scratch_mkfs > /dev/null 2>&1
3045         _scratch_mount
3046         src/godown -f $SCRATCH_MNT 2>&1 \
3047                 || _notrun "$FSTYP does not support shutdown"
3048         _scratch_unmount
3049 }
3050
3051 # Does norecovery support by this fs?
3052 _require_norecovery()
3053 {
3054         _scratch_mount -o ro,norecovery || \
3055                 _notrun "$FSTYP does not support norecovery"
3056         _scratch_unmount
3057 }
3058
3059 # Does this filesystem support metadata journaling?
3060 # We exclude ones here that don't; otherwise we assume that it does, so the
3061 # test will run, fail, and motivate someone to update this test for a new
3062 # filesystem.
3063 #
3064 # It's possible that TEST_DEV and SCRATCH_DEV have different features (it'd be
3065 # odd, but possible) so check $TEST_DEV by default, but we can optionall pass
3066 # any dev we want.
3067 _require_metadata_journaling()
3068 {
3069         if [ -z $1 ]; then
3070                 DEV=$TEST_DEV
3071         else
3072                 DEV=$1
3073         fi
3074
3075         case "$FSTYP" in
3076         ext2|vfat|msdos)
3077                 _notrun "$FSTYP does not support metadata journaling"
3078                 ;;
3079         ext4)
3080                 # ext4 could be mkfs'd without a journal...
3081                 _require_dumpe2fs
3082                 $DUMPE2FS_PROG -h $DEV 2>&1 | grep -q has_journal || \
3083                         _notrun "$FSTYP on $DEV not configured with metadata journaling"
3084                 # ext4 might not load a journal
3085                 _exclude_scratch_mount_option "noload"
3086                 ;;
3087         *)
3088                 # by default we pass; if you need to, add your fs above!
3089                 ;;
3090         esac
3091 }
3092
3093 # Does fiemap support?
3094 _require_fiemap()
3095 {
3096         _require_xfs_io_command "fiemap"
3097 }
3098
3099 _count_extents()
3100 {
3101         $XFS_IO_PROG -c "fiemap" $1 | tail -n +2 | grep -v hole | wc -l
3102 }
3103
3104 _count_holes()
3105 {
3106         $XFS_IO_PROG -c "fiemap" $1 | tail -n +2 | grep hole | wc -l
3107 }
3108
3109 # arg 1 is dev to remove and is output of the below eg.
3110 # ls -l /sys/class/block/sdd | rev | cut -d "/" -f 3 | rev
3111 _devmgt_remove()
3112 {
3113         local lun=$1
3114         local disk=$2
3115
3116         echo 1 > /sys/class/scsi_device/${lun}/device/delete || _fail "Remove disk failed"
3117
3118         stat $disk > /dev/null 2>&1
3119         while [ $? -eq 0 ]; do
3120                 sleep 1
3121                 stat $disk > /dev/null 2>&1
3122         done
3123 }
3124
3125 # arg 1 is dev to add and is output of the below eg.
3126 # ls -l /sys/class/block/sdd | rev | cut -d "/" -f 3 | rev
3127 _devmgt_add()
3128 {
3129         local h
3130         local tdl
3131         # arg 1 will be in h:t:d:l format now in the h and "t d l" format
3132         h=`echo ${1} | cut -d":" -f 1`
3133         tdl=`echo ${1} | cut -d":" -f 2-|sed 's/:/ /g'`
3134
3135         echo ${tdl} >  /sys/class/scsi_host/host${h}/scan || _fail "Add disk failed"
3136
3137         # ensure the device comes online
3138         dev_back_oneline=0
3139         for i in `seq 1 10`; do
3140                 if [ -d /sys/class/scsi_device/${1}/device/block ]; then
3141                         dev=`ls /sys/class/scsi_device/${1}/device/block`
3142                         for j in `seq 1 10`;
3143                         do
3144                                 stat /dev/$dev > /dev/null 2>&1
3145                                 if [ $? -eq 0 ]; then
3146                                         dev_back_oneline=1
3147                                         break
3148                                 fi
3149                                 sleep 1
3150                         done
3151                         break
3152                 else
3153                         sleep 1
3154                 fi
3155         done
3156         if [ $dev_back_oneline -eq 0 ]; then
3157                 echo "/dev/$dev online failed" >> $seqres.full
3158         else
3159                 echo "/dev/$dev is back online" >> $seqres.full
3160         fi
3161 }
3162
3163 _require_fstrim()
3164 {
3165         if [ -z "$FSTRIM_PROG" ]; then
3166                 _notrun "This test requires fstrim utility."
3167         fi
3168 }
3169
3170 _require_batched_discard()
3171 {
3172         if [ $# -ne 1 ]; then
3173                 echo "Usage: _require_batched_discard mnt_point" 1>&2
3174                 exit 1
3175         fi
3176         _require_fstrim
3177         $FSTRIM_PROG $1 > /dev/null 2>&1 || _notrun "FITRIM not supported on $1"
3178 }
3179
3180 _require_dumpe2fs()
3181 {
3182         if [ -z "$DUMPE2FS_PROG" ]; then
3183                 _notrun "This test requires dumpe2fs utility."
3184         fi
3185 }
3186
3187 _require_ugid_map()
3188 {
3189         if [ ! -e /proc/self/uid_map ]; then
3190                 _notrun "This test requires procfs uid_map support."
3191         fi
3192         if [ ! -e /proc/self/gid_map ]; then
3193                 _notrun "This test requires procfs gid_map support."
3194         fi
3195 }
3196
3197 _require_fssum()
3198 {
3199         FSSUM_PROG=$here/src/fssum
3200         [ -x $FSSUM_PROG ] || _notrun "fssum not built"
3201 }
3202
3203 _require_cloner()
3204 {
3205         CLONER_PROG=$here/src/cloner
3206         [ -x $CLONER_PROG ] || \
3207                 _notrun "cloner binary not present at $CLONER_PROG"
3208 }
3209
3210 # Normalize mount options from global $MOUNT_OPTIONS
3211 # Convert options like "-o opt1,opt2 -oopt3" to
3212 # "opt1 opt2 opt3"
3213 _normalize_mount_options()
3214 {
3215         echo $MOUNT_OPTIONS | sed -n 's/-o\s*\(\S*\)/\1/gp'| sed 's/,/ /g'
3216 }
3217
3218 # skip test if MOUNT_OPTIONS contains the given strings
3219 _exclude_scratch_mount_option()
3220 {
3221         local mnt_opts=$(_normalize_mount_options)
3222
3223         while [ $# -gt 0 ]; do
3224                 if echo $mnt_opts | grep -qw "$1"; then
3225                         _notrun "mount option \"$1\" not allowed in this test"
3226                 fi
3227                 shift
3228         done
3229 }
3230
3231 _require_atime()
3232 {
3233         _exclude_scratch_mount_option "noatime"
3234         if [ "$FSTYP" == "nfs" ]; then
3235                 _notrun "atime related mount options have no effect on NFS"
3236         fi
3237 }
3238
3239 _require_relatime()
3240 {
3241         _scratch_mkfs > /dev/null 2>&1
3242         _scratch_mount -o relatime || \
3243                 _notrun "relatime not supported by the current kernel"
3244         _scratch_unmount
3245 }
3246
3247 _require_userns()
3248 {
3249         [ -x src/nsexec ] || _notrun "src/nsexec executable not found"
3250         src/nsexec -U true 2>/dev/null || _notrun "userns not supported by this kernel"
3251 }
3252
3253 _create_loop_device()
3254 {
3255         file=$1
3256         dev=`losetup -f --show $file` || _fail "Cannot assign $file to a loop device"
3257         echo $dev
3258 }
3259
3260 _destroy_loop_device()
3261 {
3262         dev=$1
3263         losetup -d $dev || _fail "Cannot destroy loop device $dev"
3264 }
3265
3266 _scale_fsstress_args()
3267 {
3268     args=""
3269     while [ $# -gt 0 ]; do
3270         case "$1" in
3271             -n) args="$args $1 $(($2 * $TIME_FACTOR))"; shift ;;
3272             -p) args="$args $1 $(($2 * $LOAD_FACTOR))"; shift ;;
3273             *) args="$args $1" ;;
3274         esac
3275         shift
3276     done
3277     echo $args
3278 }
3279
3280 #
3281 # Return the logical block size if running on a block device,
3282 # else substitute the page size.
3283 #
3284 _min_dio_alignment()
3285 {
3286     dev=$1
3287
3288     if [ -b "$dev" ]; then
3289         blockdev --getss $dev
3290     else
3291         $here/src/feature -s
3292     fi
3293 }
3294
3295 run_check()
3296 {
3297         echo "# $@" >> $seqres.full 2>&1
3298         "$@" >> $seqres.full 2>&1 || _fail "failed: '$@'"
3299 }
3300
3301 _run_btrfs_util_prog()
3302 {
3303         run_check $BTRFS_UTIL_PROG $*
3304 }
3305
3306 _require_btrfs_send_stream_version()
3307 {
3308         $BTRFS_UTIL_PROG send 2>&1 | \
3309                 grep '^[ \t]*\-\-stream\-version <version>' > /dev/null 2>&1
3310         if [ $? -ne 0 ]; then
3311                 _notrun "Missing btrfs-progs send --stream-version command line option, skipped this test"
3312         fi
3313
3314         # test if btrfs kernel supports send stream version 2
3315         if [ ! -f /sys/fs/btrfs/send/stream_version ]; then
3316                 _notrun "Missing btrfs kernel patch for send stream version 2, skipped this test"
3317         fi
3318 }
3319
3320 _require_btrfs_mkfs_feature()
3321 {
3322         if [ -z $1 ]; then
3323                 echo "Missing feature name argument for _require_btrfs_mkfs_feature"
3324                 exit 1
3325         fi
3326         feat=$1
3327         $MKFS_BTRFS_PROG -O list-all 2>&1 | \
3328                 grep '^[ \t]*'"$feat"'\b' > /dev/null 2>&1
3329         [ $? -eq 0 ] || \
3330                 _notrun "Feature $feat not supported in the available version of mkfs.btrfs"
3331 }
3332
3333 _require_btrfs_fs_feature()
3334 {
3335         if [ -z $1 ]; then
3336                 echo "Missing feature name argument for _require_btrfs_fs_feature"
3337                 exit 1
3338         fi
3339         feat=$1
3340         modprobe btrfs > /dev/null 2>&1
3341         [ -e /sys/fs/btrfs/features/$feat ] || \
3342                 _notrun "Feature $feat not supported by the available btrfs version"
3343 }
3344
3345 _require_test_symlinks()
3346 {
3347         # IRIX UDF does not support symlinks
3348         [ "$HOSTOS" = "IRIX" -a "$FSTYP" = 'udf' ] && \
3349                 _notrun "Require symlinks support"
3350         target=`mktemp -p $TEST_DIR`
3351         link=`mktemp -p $TEST_DIR -u`
3352         ln -s `basename $target` $link
3353         if [ "$?" -ne 0 ]; then
3354                 rm -f $target
3355                 _notrun "Require symlinks support"
3356         fi
3357         rm -f $target $link
3358 }
3359
3360 _require_test_fcntl_advisory_locks()
3361 {
3362         [ "$FSTYP" != "cifs" ] && return 0
3363         cat /proc/mounts | grep $TEST_DEV | grep cifs | grep -q "nobrl" && return 0
3364         cat /proc/mounts | grep $TEST_DEV | grep cifs | grep -qE "nounix|forcemand" && \
3365                 _notrun "Require fcntl advisory locks support"
3366 }
3367
3368 # XFS ability to change UUIDs on V5/CRC filesystems
3369 #
3370 _require_meta_uuid()
3371 {
3372         # This will create a crc fs on $SCRATCH_DEV
3373         _require_xfs_crc
3374
3375         _scratch_xfs_db -x -c "uuid restore" 2>&1 \
3376            | grep -q "invalid UUID\|supported on V5 fs" \
3377            && _notrun "Userspace doesn't support meta_uuid feature"
3378
3379         _scratch_xfs_db -x -c "uuid generate" >/dev/null 2>&1
3380
3381         _scratch_mount >/dev/null 2>&1 \
3382            || _notrun "Kernel doesn't support meta_uuid feature"
3383         _scratch_unmount
3384 }
3385
3386 _require_btrfs_dev_del_by_devid()
3387 {
3388         $BTRFS_UTIL_PROG device delete --help | egrep devid > /dev/null 2>&1
3389         [ $? -eq 0 ] || _notrun "$BTRFS_UTIL_PROG too old "\
3390                         "(must support 'btrfs device delete <devid> /<mnt>')"
3391 }
3392
3393 _require_test_lsattr()
3394 {
3395         testio=$(lsattr -d $TEST_DIR 2>&1)
3396         echo $testio | grep -q "Operation not supported" && \
3397                 _notrun "lsattr not supported by test filesystem type: $FSTYP"
3398         echo $testio | grep -q "Inappropriate ioctl for device" && \
3399                 _notrun "lsattr not supported by test filesystem type: $FSTYP"
3400 }
3401
3402 _require_xfs_test_rmapbt()
3403 {
3404         _require_test
3405
3406         if [ "$(xfs_info "$TEST_DIR" | grep -c "rmapbt=1")" -ne 1 ]; then
3407                 _notrun "rmapbt not supported by test filesystem type: $FSTYP"
3408         fi
3409 }
3410
3411 _require_xfs_scratch_rmapbt()
3412 {
3413         _require_scratch
3414
3415         _scratch_mkfs > /dev/null
3416         _scratch_mount
3417         if [ "$(xfs_info "$SCRATCH_MNT" | grep -c "rmapbt=1")" -ne 1 ]; then
3418                 _scratch_unmount
3419                 _notrun "rmapbt not supported by scratch filesystem type: $FSTYP"
3420         fi
3421         _scratch_unmount
3422 }
3423
3424 _xfs_bmapx_find() {
3425         case "$1" in
3426         "attr")
3427                 param="a"
3428                 ;;
3429         "cow")
3430                 param="c"
3431                 ;;
3432         *)
3433                 param="e"
3434                 ;;
3435         esac
3436         shift
3437         file="$1"
3438         shift
3439
3440         "$XFS_IO_PROG" -c "bmap -${param}lpv" "$file" | grep -c "$@"
3441 }
3442
3443 _require_chattr()
3444 {
3445     attribute=$1
3446
3447     touch $TEST_DIR/syscalltest
3448     chattr "+$attribute" $TEST_DIR/syscalltest > $TEST_DIR/syscalltest.out 2>&1
3449     status=$?
3450     chattr "-$attribute" $TEST_DIR/syscalltest > $TEST_DIR/syscalltest.out 2>&1
3451     if [ "$status" -ne 0 ]; then
3452       _notrun "file system doesn't support chattr +$attribute"
3453     fi
3454     cat $TEST_DIR/syscalltest.out >> $seqres.full
3455
3456     rm -f $TEST_DIR/syscalltest.out
3457 }
3458
3459 _get_total_inode()
3460 {
3461         if [ -z "$1" ]; then
3462                 echo "Usage: _get_total_inode <mnt>"
3463                 exit 1
3464         fi
3465         local nr_inode;
3466         nr_inode=`$DF_PROG -i $1 | tail -1 | awk '{print $3}'`
3467         echo $nr_inode
3468 }
3469
3470 _get_used_inode()
3471 {
3472         if [ -z "$1" ]; then
3473                 echo "Usage: _get_used_inode <mnt>"
3474                 exit 1
3475         fi
3476         local nr_inode;
3477         nr_inode=`$DF_PROG -i $1 | tail -1 | awk '{print $4}'`
3478         echo $nr_inode
3479 }
3480
3481 _get_used_inode_percent()
3482 {
3483         if [ -z "$1" ]; then
3484                 echo "Usage: _get_used_inode_percent <mnt>"
3485                 exit 1
3486         fi
3487         local pct_inode;
3488         pct_inode=`$DF_PROG -i $1 | tail -1 | awk '{ print $6 }' | \
3489                    sed -e 's/%//'`
3490         echo $pct_inode
3491 }
3492
3493 _get_free_inode()
3494 {
3495         if [ -z "$1" ]; then
3496                 echo "Usage: _get_free_inode <mnt>"
3497                 exit 1
3498         fi
3499         local nr_inode;
3500         nr_inode=`$DF_PROG -i $1 | tail -1 | awk '{print $5}'`
3501         echo $nr_inode
3502 }
3503
3504 # get the available space in bytes
3505 #
3506 _get_available_space()
3507 {
3508         if [ -z "$1" ]; then
3509                 echo "Usage: _get_available_space <mnt>"
3510                 exit 1
3511         fi
3512         local avail_kb;
3513         avail_kb=`$DF_PROG $1 | tail -n1 | awk '{ print $5 }'`
3514         echo $((avail_kb * 1024))
3515 }
3516
3517 # get btrfs profile configs being tested
3518 #
3519 # A set of pre-set profile configs are exported via _btrfs_profile_configs
3520 # array. Default configs can be overridden by setting BTRFS_PROFILE_CONFIGS
3521 # var in the format "metadata_profile:data_profile", multiple configs can be
3522 # seperated by space, e.g.
3523 # export BTRFS_PROFILE_CONFIGS="raid0:raid0 raid1:raid1 dup:single"
3524 _btrfs_get_profile_configs()
3525 {
3526         if [ "$FSTYP" != "btrfs" ]; then
3527                 return
3528         fi
3529
3530         if [ -z "$BTRFS_PROFILE_CONFIGS" ]; then
3531                 # Default configurations to test.
3532                 local configs=(
3533                         "single:single"
3534                         "dup:single"
3535                         "raid0:raid0"
3536                         "raid1:raid0"
3537                         "raid1:raid1"
3538                         "raid10:raid10"
3539                         "raid5:raid5"
3540                         "raid6:raid6"
3541                 )
3542         else
3543                 # User-provided configurations.
3544                 local configs=(${BTRFS_PROFILE_CONFIGS[@]})
3545         fi
3546
3547         _btrfs_profile_configs=()
3548         for cfg in "${configs[@]}"; do
3549                 local supported=true
3550                 local profiles=(${cfg/:/ })
3551                 if [ "$1" == "replace" ]; then
3552                         # We can't do replace with these profiles because they
3553                         # imply only one device ($SCRATCH_DEV), and we need to
3554                         # keep $SCRATCH_DEV around for _scratch_mount
3555                         # and _check_scratch_fs.
3556                         local unsupported=(
3557                                 "dup"
3558                         )
3559                 elif [ "$1" == "replace-missing" ]; then
3560                         # We can't replace missing devices with these profiles
3561                         # because there isn't enough redundancy.
3562                         local unsupported=(
3563                                 "single"
3564                                 "dup"
3565                                 "raid0"
3566                         )
3567                 else
3568                         local unsupported=()
3569                 fi
3570                 for unsupp in "${unsupported[@]}"; do
3571                         if [ "${profiles[0]}" == "$unsupp" -o "${profiles[1]}" == "$unsupp" ]; then
3572                              if [ -z "$BTRFS_PROFILE_CONFIGS" ]; then
3573                                      # For the default config, just omit it.
3574                                      supported=false
3575                              else
3576                                      # For user-provided config, don't run the test.
3577                                      _notrun "Profile $unsupp not supported for $1"
3578                              fi
3579                         fi
3580                 done
3581                 if "$supported"; then
3582                         _btrfs_profile_configs+=("-m ${profiles[0]} -d ${profiles[1]}")
3583                 fi
3584         done
3585         export _btrfs_profile_configs
3586 }
3587
3588 # stress btrfs by running balance operation in a loop
3589 _btrfs_stress_balance()
3590 {
3591         local options=$@
3592         while true; do
3593                 $BTRFS_UTIL_PROG balance start $options
3594         done
3595 }
3596
3597 # stress btrfs by creating/mounting/umounting/deleting subvolume in a loop
3598 _btrfs_stress_subvolume()
3599 {
3600         local btrfs_dev=$1
3601         local btrfs_mnt=$2
3602         local subvol_name=$3
3603         local subvol_mnt=$4
3604         local stop_file=$5
3605
3606         mkdir -p $subvol_mnt
3607         while [ ! -e $stop_file ]; do
3608                 $BTRFS_UTIL_PROG subvolume create $btrfs_mnt/$subvol_name
3609                 $MOUNT_PROG -o subvol=$subvol_name $btrfs_dev $subvol_mnt
3610                 $UMOUNT_PROG $subvol_mnt
3611                 $BTRFS_UTIL_PROG subvolume delete $btrfs_mnt/$subvol_name
3612         done
3613 }
3614
3615 # stress btrfs by running scrub in a loop
3616 _btrfs_stress_scrub()
3617 {
3618         local btrfs_mnt=$1
3619         while true; do
3620                 $BTRFS_UTIL_PROG scrub start -B $btrfs_mnt
3621         done
3622 }
3623
3624 # stress btrfs by defragmenting every file/dir in a loop and compress file
3625 # contents while defragmenting if second argument is not "nocompress"
3626 _btrfs_stress_defrag()
3627 {
3628         local btrfs_mnt=$1
3629         local compress=$2
3630
3631         while true; do
3632                 if [ "$compress" == "nocompress" ]; then
3633                         find $btrfs_mnt \( -type f -o -type d \) -exec \
3634                         $BTRFS_UTIL_PROG filesystem defrag {} \;
3635                 else
3636                         find $btrfs_mnt \( -type f -o -type d \) -exec \
3637                         $BTRFS_UTIL_PROG filesystem defrag -clzo {} \;
3638                         find $btrfs_mnt \( -type f -o -type d \) -exec \
3639                         $BTRFS_UTIL_PROG filesystem defrag -czlib {} \;
3640                 fi
3641         done
3642 }
3643
3644 # stress btrfs by remounting it with different compression algorithms in a loop
3645 # run this with fsstress running at background could exercise the compression
3646 # code path and ensure no race when switching compression algorithm with constant
3647 # I/O activity.
3648 _btrfs_stress_remount_compress()
3649 {
3650         local btrfs_mnt=$1
3651         while true; do
3652                 for algo in no zlib lzo; do
3653                         $MOUNT_PROG -o remount,compress=$algo $btrfs_mnt
3654                 done
3655         done
3656 }
3657
3658 # stress btrfs by replacing devices in a loop
3659 # Note that at least 3 devices are needed in SCRATCH_DEV_POOL and the last
3660 # device should be free(not used by btrfs)
3661 _btrfs_stress_replace()
3662 {
3663         local btrfs_mnt=$1
3664
3665         # The device number in SCRATCH_DEV_POOL should be at least 3,
3666         # one is SCRATCH_DEV, one is to be replaced, one is free device
3667         # we won't replace SCRATCH_DEV, see below for reason
3668         if [ "`echo $SCRATCH_DEV_POOL | wc -w`" -lt 3 ]; then
3669                 echo "_btrfs_stress_replace requires at least 3 devices in SCRATCH_DEV_POOL"
3670                 return
3671         fi
3672
3673         # take the last device as the first free_dev
3674         local free_dev="`echo $SCRATCH_DEV_POOL | $AWK_PROG '{print $NF}'`"
3675
3676         # free_dev should be really free
3677         if $BTRFS_UTIL_PROG filesystem show $btrfs_mnt | grep -q "$free_dev"; then
3678                 echo "_btrfs_stress_replace: $free_dev is used by btrfs"
3679                 return
3680         fi
3681
3682         # dev_pool is device list being currently used by btrfs (excluding SCRATCH_DEV)
3683         # and can be replaced. We don't replace SCRATCH_DEV because it will be used in
3684         # _scratch_mount and _check_scratch_fs etc.
3685         local dev_pool=`echo $SCRATCH_DEV_POOL | sed -e "s# *$SCRATCH_DEV *##" \
3686                         -e "s# *$free_dev *##"`
3687
3688         # set the first device in dev_pool as the first src_dev to be replaced
3689         local src_dev=`echo $dev_pool | $AWK_PROG '{print $1}'`
3690
3691         echo "dev_pool=$dev_pool"
3692         echo "free_dev=$free_dev, src_dev=$src_dev"
3693         while true; do
3694                 echo "Replacing $src_dev with $free_dev"
3695                 $BTRFS_UTIL_PROG replace start -fB $src_dev $free_dev $btrfs_mnt
3696                 if [ $? -ne 0 ]; then
3697                         # don't update src_dev and free_dev if replace failed
3698                         continue
3699                 fi
3700                 dev_pool="$dev_pool $free_dev"
3701                 dev_pool=`echo $dev_pool | sed -e "s# *$src_dev *##"`
3702                 free_dev=$src_dev
3703                 src_dev=`echo $dev_pool | $AWK_PROG '{print $1}'`
3704         done
3705 }
3706
3707 # find the right option to force output in bytes, older versions of btrfs-progs
3708 # print that by default, newer print human readable numbers with unit suffix
3709 _btrfs_qgroup_units()
3710 {
3711         $BTRFS_UTIL_PROG qgroup show --help 2>&1 | grep -q -- --raw && echo "--raw"
3712 }
3713
3714 # return device size in kb
3715 _get_device_size()
3716 {
3717         grep `_short_dev $1` /proc/partitions | awk '{print $3}'
3718 }
3719
3720 # check dmesg log for WARNING/Oops/etc.
3721 _check_dmesg()
3722 {
3723         if [ ! -f ${RESULT_DIR}/check_dmesg ]; then
3724                 return 0
3725         fi
3726         rm -f ${RESULT_DIR}/check_dmesg
3727
3728         # default filter is a simple cat command, caller could provide a
3729         # customized filter and pass the name through the first argument, to
3730         # filter out intentional WARNINGs or Oopses
3731         filter=${1:-cat}
3732
3733         # search the dmesg log of last run of $seqnum for possible failures
3734         # use sed \cregexpc address type, since $seqnum contains "/"
3735         dmesg | tac | sed -ne "0,\#run fstests $seqnum at $date_time#p" | \
3736                 tac | $filter >$seqres.dmesg
3737         grep -q -e "kernel BUG at" \
3738              -e "WARNING:" \
3739              -e "BUG:" \
3740              -e "Oops:" \
3741              -e "possible recursive locking detected" \
3742              -e "Internal error" \
3743              -e "INFO: suspicious RCU usage" \
3744              -e "INFO: possible circular locking dependency detected" \
3745              -e "general protection fault:" \
3746              $seqres.dmesg
3747         if [ $? -eq 0 ]; then
3748                 echo "_check_dmesg: something found in dmesg (see $seqres.dmesg)"
3749                 return 1
3750         else
3751                 rm -f $seqres.dmesg
3752                 return 0
3753         fi
3754 }
3755
3756 # don't check dmesg log after test
3757 _disable_dmesg_check()
3758 {
3759         rm -f ${RESULT_DIR}/check_dmesg
3760 }
3761
3762 init_rc()
3763 {
3764         if [ "$iam" == new ]
3765         then
3766                 return
3767         fi
3768         # make some further configuration checks here
3769         if [ "$TEST_DEV" = ""  ]
3770         then
3771                 echo "common/rc: Error: \$TEST_DEV is not set"
3772                 exit 1
3773         fi
3774
3775         # if $TEST_DEV is not mounted, mount it now as XFS
3776         if [ -z "`_fs_type $TEST_DEV`" ]
3777         then
3778                 # $TEST_DEV is not mounted
3779                 if ! _test_mount
3780                 then
3781                         echo "common/rc: retrying test device mount with external set"
3782                         [ "$USE_EXTERNAL" != "yes" ] && export USE_EXTERNAL=yes
3783                         if ! _test_mount
3784                         then
3785                                 echo "common/rc: could not mount $TEST_DEV on $TEST_DIR"
3786                                 exit 1
3787                         fi
3788                 fi
3789         fi
3790
3791         if [ "`_fs_type $TEST_DEV`" != "$FSTYP" ]
3792         then
3793                 echo "common/rc: Error: \$TEST_DEV ($TEST_DEV) is not a MOUNTED $FSTYP filesystem"
3794                 # raw $DF_PROG cannot handle NFS/CIFS/overlay correctly
3795                 _df_device $TEST_DEV
3796                 exit 1
3797         fi
3798         # Figure out if we need to add -F ("foreign", deprecated) option to xfs_io
3799         xfs_io -c stat $TEST_DIR 2>&1 | grep -q "is not on an XFS filesystem" && \
3800         export XFS_IO_PROG="$XFS_IO_PROG -F"
3801
3802         # xfs_copy doesn't work on v5 xfs yet without -d option
3803         if [ "$FSTYP" == "xfs" ] && [[ $MKFS_OPTIONS =~ crc=1 ]]; then
3804                 export XFS_COPY_PROG="$XFS_COPY_PROG -d"
3805         fi
3806 }
3807
3808 # get real device path name by following link
3809 _real_dev()
3810 {
3811         local _dev=$1
3812         if [ -b "$_dev" ] && [ -L "$_dev" ]; then
3813                 _dev=`readlink -f "$_dev"`
3814         fi
3815         echo $_dev
3816 }
3817
3818 # basename of a device
3819 _short_dev()
3820 {
3821         echo `basename $(_real_dev $1)`
3822 }
3823
3824 _sysfs_dev()
3825 {
3826         local _dev=$1
3827         local _maj=$(stat -c%t $_dev | tr [:lower:] [:upper:])
3828         local _min=$(stat -c%T $_dev | tr [:lower:] [:upper:])
3829         _maj=$(echo "ibase=16; $_maj" | bc)
3830         _min=$(echo "ibase=16; $_min" | bc)
3831         echo /sys/dev/block/$_maj:$_min
3832 }
3833
3834 get_block_size()
3835 {
3836         if [ -z $1 ] || [ ! -d $1 ]; then
3837                 echo "Missing mount point argument for get_block_size"
3838                 exit 1
3839         fi
3840         echo `stat -f -c %S $1`
3841 }
3842
3843 get_page_size()
3844 {
3845         echo $(getconf PAGE_SIZE)
3846 }
3847
3848
3849 run_fsx()
3850 {
3851         echo fsx $@
3852         args=`echo $@ | sed -e "s/ BSIZE / $bsize /g" -e "s/ PSIZE / $psize /g"`
3853         set -- $here/ltp/fsx $args $FSX_AVOID $TEST_DIR/junk
3854         echo "$@" >>$seqres.full
3855         rm -f $TEST_DIR/junk
3856         "$@" 2>&1 | tee -a $seqres.full >$tmp.fsx
3857         if [ ${PIPESTATUS[0]} -ne 0 ]; then
3858                 cat $tmp.fsx
3859                 exit 1
3860         fi
3861 }
3862
3863 # Test for the existence of a sysfs entry at /sys/fs/$FSTYP/DEV/$ATTR
3864 #
3865 # Only one argument is needed:
3866 #  - attr: path name under /sys/fs/$FSTYP/DEV
3867 #
3868 # Usage example:
3869 #   _require_fs_sysfs error/fail_at_unmount
3870 _require_fs_sysfs()
3871 {
3872         local attr=$1
3873         local dname=$(_short_dev $TEST_DEV)
3874
3875         if [ -z "$attr" -o -z "$dname" ];then
3876                 _fail "Usage: _require_fs_sysfs <sysfs_attr_path>"
3877         fi
3878
3879         if [ ! -e /sys/fs/${FSTYP}/${dname}/${attr} ];then
3880                 _notrun "This test requires /sys/fs/${FSTYP}/${dname}/${attr}"
3881         fi
3882 }
3883
3884 # Write "content" into /sys/fs/$FSTYP/$DEV/$ATTR
3885 #
3886 # All arguments are necessary, and in this order:
3887 #  - dev: device name, e.g. $SCRATCH_DEV
3888 #  - attr: path name under /sys/fs/$FSTYP/$dev
3889 #  - content: the content of $attr
3890 #
3891 # Usage example:
3892 #   _set_fs_sysfs_attr /dev/mapper/scratch-dev error/fail_at_unmount 0
3893 _set_fs_sysfs_attr()
3894 {
3895         local dev=$1
3896         shift
3897         local attr=$1
3898         shift
3899         local content="$*"
3900
3901         if [ ! -b "$dev" -o -z "$attr" -o -z "$content" ];then
3902                 _fail "Usage: _set_fs_sysfs_attr <mounted_device> <attr> <content>"
3903         fi
3904
3905         local dname=$(_short_dev $dev)
3906         echo "$content" > /sys/fs/${FSTYP}/${dname}/${attr}
3907 }
3908
3909 # Print the content of /sys/fs/$FSTYP/$DEV/$ATTR
3910 #
3911 # All arguments are necessary, and in this order:
3912 #  - dev: device name, e.g. $SCRATCH_DEV
3913 #  - attr: path name under /sys/fs/$FSTYP/$dev
3914 #
3915 # Usage example:
3916 #   _get_fs_sysfs_attr /dev/mapper/scratch-dev error/fail_at_unmount
3917 _get_fs_sysfs_attr()
3918 {
3919         local dev=$1
3920         local attr=$2
3921
3922         if [ ! -b "$dev" -o -z "$attr" ];then
3923                 _fail "Usage: _get_fs_sysfs_attr <mounted_device> <attr>"
3924         fi
3925
3926         local dname=$(_short_dev $dev)
3927         cat /sys/fs/${FSTYP}/${dname}/${attr}
3928 }
3929
3930
3931 # Reset all xfs error handling attributes, set them to original
3932 # status.
3933 #
3934 # Only one argument, and it's mandatory:
3935 #  - dev: device name, e.g. $SCRATCH_DEV
3936 #
3937 # Note: this function only works for XFS
3938 _reset_xfs_sysfs_error_handling()
3939 {
3940         local dev=$1
3941
3942         if [ ! -b "$dev" -o "$FSTYP" != "xfs" ];then
3943                 _fail "Usage: reset_xfs_sysfs_error_handling <device>"
3944         fi
3945
3946         _set_fs_sysfs_attr $dev error/fail_at_unmount 1
3947         echo -n "error/fail_at_unmount="
3948         _get_fs_sysfs_attr $dev error/fail_at_unmount
3949
3950         # Make sure all will be configured to retry forever by default, except
3951         # for ENODEV, which is an unrecoverable error, so it will be configured
3952         # to not retry on error by default.
3953         for e in default EIO ENOSPC; do
3954                 _set_fs_sysfs_attr $dev \
3955                                    error/metadata/${e}/max_retries -1
3956                 echo -n "error/metadata/${e}/max_retries="
3957                 _get_fs_sysfs_attr $dev error/metadata/${e}/max_retries
3958
3959                 _set_fs_sysfs_attr $dev \
3960                                    error/metadata/${e}/retry_timeout_seconds 0
3961                 echo -n "error/metadata/${e}/retry_timeout_seconds="
3962                 _get_fs_sysfs_attr $dev \
3963                                    error/metadata/${e}/retry_timeout_seconds
3964         done
3965 }
3966
3967 # Skip if we are running an older binary without the stricter input checks.
3968 # Make multiple checks to be sure that there is no regression on the one
3969 # selected feature check, which would skew the result.
3970 #
3971 # At first, make a common function that runs the tests and returns
3972 # number of failed cases.
3973 _xfs_mkfs_validation_check()
3974 {
3975         local tmpfile=`mktemp`
3976         local cmd="$MKFS_XFS_PROG -f -N -d file,name=$tmpfile,size=1g"
3977
3978         $cmd -s size=2s >/dev/null 2>&1
3979         local sum=$?
3980
3981         $cmd -l version=2,su=260k >/dev/null 2>&1
3982         sum=`expr $sum + $?`
3983
3984         rm -f $tmpfile
3985         return $sum
3986 }
3987
3988 # Skip the test if all calls passed - mkfs accepts invalid input
3989 _require_xfs_mkfs_validation()
3990 {
3991         _xfs_mkfs_validation_check
3992         if [ "$?" -eq 0 ]; then
3993                 _notrun "Requires newer mkfs with stricter input checks: the oldest supported version of xfsprogs is 4.7."
3994         fi
3995 }
3996
3997 # The oposite of _require_xfs_mkfs_validation.
3998 _require_xfs_mkfs_without_validation()
3999 {
4000         _xfs_mkfs_validation_check
4001         if [ "$?" -ne 0 ]; then
4002                 _notrun "Requires older mkfs without strict input checks: the last supported version of xfsprogs is 4.5."
4003         fi
4004 }
4005
4006 init_rc
4007
4008 ################################################################################
4009 # make sure this script returns success
4010 /bin/true