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