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