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