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