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