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