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