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