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