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