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