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