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