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