common: open files in ro mode for extent and hole count helpers
[xfstests-dev.git] / common / rc
index 6a91850c538833b751aa015316646312c867085c..238ffef9d959e5309abcb73724c687e62d7877b5 100644 (file)
--- a/common/rc
+++ b/common/rc
@@ -1,37 +1,10 @@
 ##/bin/bash
-#-----------------------------------------------------------------------
-#  Copyright (c) 2000-2006 Silicon Graphics, Inc.  All Rights Reserved.
-#  This program is free software; you can redistribute it and/or modify
-#  it under the terms of the GNU General Public License as published by
-#  the Free Software Foundation; either version 2 of the License, or
-#  (at your option) any later version.
-#
-#  This program is distributed in the hope that it will be useful,
-#  but WITHOUT ANY WARRANTY; without even the implied warranty of
-#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-#  GNU General Public License for more details.
-#
-#  You should have received a copy of the GNU General Public License
-#  along with this program; if not, write to the Free Software
-#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
-#  USA
-#
-#  Contact information: Silicon Graphics, Inc., 1500 Crittenden Lane,
-#  Mountain View, CA 94043, USA, or: http://www.sgi.com
-#-----------------------------------------------------------------------
+# SPDX-License-Identifier: GPL-2.0+
+# Copyright (c) 2000-2006 Silicon Graphics, Inc.  All Rights Reserved.
 
-BC=$(which bc 2> /dev/null) || BC=
+. common/config
 
-# Valid test names start with 3 digits "NNN":
-#  "[0-9]\{3\}"
-# followed by an optional "-":
-#  "-\?"
-# followed by an optional combination of alphanumeric and "-" chars:
-#  "[[:alnum:]-]*"
-# e.g. 999-the-mark-of-fstests
-#
-VALID_TEST_ID="[0-9]\{3\}"
-VALID_TEST_NAME="$VALID_TEST_ID-\?[[:alnum:]-]*"
+BC=$(which bc 2> /dev/null) || BC=
 
 # Some tests are not relevant or functional when testing XFS realtime
 # subvolumes along with the rtinherit=1 mkfs option.  In these cases,
@@ -53,12 +26,7 @@ _require_math()
 _math()
 {
        [ $# -le 0 ] && return
-       if [ "$BC" ]; then
-               result=$(LANG=C echo "scale=0; $@" | "$BC" -q 2> /dev/null)
-       else
-               _notrun "this test requires 'bc' tool for doing math operations"
-       fi
-       echo "$result"
+       LANG=C echo "scale=0; $@" | "$BC" -q 2> /dev/null
 }
 
 dd()
@@ -86,22 +54,22 @@ _md5_checksum()
 
 # Write a byte into a range of a file
 _pwrite_byte() {
-       pattern="$1"
-       offset="$2"
-       len="$3"
-       file="$4"
-       xfs_io_args="$5"
+       local pattern="$1"
+       local offset="$2"
+       local len="$3"
+       local file="$4"
+       local xfs_io_args="$5"
 
        $XFS_IO_PROG $xfs_io_args -f -c "pwrite -S $pattern $offset $len" "$file"
 }
 
 # mmap-write a byte into a range of a file
 _mwrite_byte() {
-       pattern="$1"
-       offset="$2"
-       len="$3"
-       mmap_len="$4"
-       file="$5"
+       local pattern="$1"
+       local offset="$2"
+       local len="$3"
+       local mmap_len="$4"
+       local file="$5"
 
        $XFS_IO_PROG -f -c "mmap -rw 0 $mmap_len" -c "mwrite -S $pattern $offset $len" "$file"
 }
@@ -115,32 +83,28 @@ _ls_l()
        ls -l $* | sed "s/\(^[-rwxdlbcpsStT]*\)\. /\1 /" | grep -v 'lost+found'
 }
 
-# we need common/config
-if [ "$iam" != "check" ]
-then
-    if ! . ./common/config
-        then
-        echo "$iam: failed to source common/config"
-        exit 1
-    fi
-fi
-
 _dump_err()
 {
-    err_msg="$*"
-    echo "$err_msg"
+    _err_msg="$*"
+    echo "$_err_msg"
+}
+
+_dump_err_cont()
+{
+    _err_msg="$*"
+    echo -n "$_err_msg"
 }
 
 _dump_err2()
 {
-    err_msg="$*"
-    >2& echo "$err_msg"
+    _err_msg="$*"
+    >&2 echo "$_err_msg"
 }
 
 _log_err()
 {
-    err_msg="$*"
-    echo "$err_msg" | tee -a $seqres.full
+    _err_msg="$*"
+    echo "$_err_msg" | tee -a $seqres.full
     echo "(see $seqres.full for details)"
 }
 
@@ -154,6 +118,7 @@ case "$FSTYP" in
         [ "$XFS_REPAIR_PROG" = "" ] && _fatal "xfs_repair not found"
         [ "$XFS_DB_PROG" = "" ] && _fatal "xfs_db not found"
         [ "$MKFS_XFS_PROG" = "" ] && _fatal "mkfs_xfs not found"
+        [ "$XFS_INFO_PROG" = "" ] && _fatal "xfs_info not found"
 
         . ./common/xfs
         ;;
@@ -200,6 +165,11 @@ if [ ! -z "$REPORT_LIST" ]; then
        _assert_report_list
 fi
 
+_get_filesize()
+{
+    stat -c %s "$1"
+}
+
 _mount()
 {
     $MOUNT_PROG `_mount_ops_filter $*`
@@ -249,6 +219,8 @@ _clear_mount_stack()
 _scratch_options()
 {
     local type=$1
+    local rt_opt=""
+    local log_opt=""
     SCRATCH_OPTIONS=""
 
     if [ "$FSTYP" != "xfs" ]; then
@@ -274,7 +246,9 @@ _scratch_options()
 
 _test_options()
 {
-    type=$1
+    local type=$1
+    local rt_opt=""
+    local log_opt=""
     TEST_OPTIONS=""
 
     if [ "$FSTYP" != "xfs" ]; then
@@ -299,15 +273,15 @@ _test_options()
 
 _mount_ops_filter()
 {
-    params="$*"
-    
+    local params="$*"
+    local last_index=$(( $# - 1 ))
+
     #get mount point to handle dmapi mtpt option correctly
-    let last_index=$#-1
     [ $last_index -gt 0 ] && shift $last_index
-    FS_ESCAPED=$1
-    
+    local fs_escaped=$1
+
     echo $params | sed -e 's/dmapi/dmi/' \
-        | $PERL_PROG -ne "s#mtpt=[^,|^\n|^\s]*#mtpt=$FS_ESCAPED\1\2#; print;"
+        | $PERL_PROG -ne "s#mtpt=[^,|^\n|^\s]*#mtpt=$fs_escaped\1\2#; print;"
 
 }
 
@@ -334,7 +308,7 @@ _supports_filetype()
        local fstyp=`$DF_PROG $dir | tail -1 | $AWK_PROG '{print $2}'`
        case "$fstyp" in
        xfs)
-               xfs_info $dir | grep -q "ftype=1"
+               $XFS_INFO_PROG $dir | grep -q "ftype=1"
                ;;
        ext2|ext3|ext4)
                local dev=`$DF_PROG $dir | tail -1 | $AWK_PROG '{print $1}'`
@@ -344,7 +318,7 @@ _supports_filetype()
                local testfile=$dir/$$.ftype
                touch $testfile
                # look for DT_UNKNOWN files
-               local unknowns=$(src/t_dir_type $dir u | wc -l)
+               local unknowns=$($here/src/t_dir_type $dir u | wc -l)
                rm $testfile
                # 0 unknowns is success
                return $unknowns
@@ -388,7 +362,7 @@ _scratch_remount()
     local opts="$1"
 
     if test -n "$opts"; then
-       mount -o "remount,$opts" $SCRATCH_MNT
+       _try_scratch_mount "-o remount,$opts"
     fi
 }
 
@@ -417,10 +391,21 @@ _scratch_shutdown()
                if [ -z $OVL_BASE_SCRATCH_DEV ]; then
                        _fail "_scratch_shutdown: call _require_scratch_shutdown first in test"
                else
-                       src/godown $* $OVL_BASE_SCRATCH_MNT
+                       $here/src/godown $* $OVL_BASE_SCRATCH_MNT
                fi
        else
-               src/godown $* $SCRATCH_MNT
+               $here/src/godown $* $SCRATCH_MNT
+       fi
+}
+
+# Return a file path that can be used to shut down the scratch filesystem.
+# Caller should _require_scratch_shutdown before using this.
+_scratch_shutdown_handle()
+{
+       if [ $FSTYP = "overlay" ]; then
+               echo $OVL_BASE_SCRATCH_MNT
+       else
+               echo $SCRATCH_MNT
        fi
 }
 
@@ -506,9 +491,9 @@ _scratch_do_mkfs()
 
 _scratch_metadump()
 {
-       dumpfile=$1
+       local dumpfile=$1
        shift
-       options=
+       local options=
 
        [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_LOGDEV" ] && \
                options="-l $SCRATCH_LOGDEV"
@@ -518,7 +503,7 @@ _scratch_metadump()
 
 _setup_large_ext4_fs()
 {
-       fs_size=$1
+       local fs_size=$1
        local tmp_dir=/tmp/
 
        [ "$LARGE_SCRATCH_DEV" != yes ] && return 0
@@ -527,7 +512,7 @@ _setup_large_ext4_fs()
 
        # Default free space in the FS is 50GB, but you can specify more via
        # SCRATCH_DEV_EMPTY_SPACE
-       space_to_consume=$(($fs_size - 50*1024*1024*1024 - $SCRATCH_DEV_EMPTY_SPACE))
+       local space_to_consume=$(($fs_size - 50*1024*1024*1024 - $SCRATCH_DEV_EMPTY_SPACE))
 
        # mount the filesystem and create 16TB - 4KB files until we consume
        # all the necessary space.
@@ -541,8 +526,8 @@ _setup_large_ext4_fs()
        fi
        rm -f $tmp_dir/mnt.err
 
-       file_size=$((16*1024*1024*1024*1024 - 4096))
-       nfiles=0
+       local file_size=$((16*1024*1024*1024*1024 - 4096))
+       local nfiles=0
        while [ $space_to_consume -gt $file_size ]; do
 
                xfs_io -F -f \
@@ -593,7 +578,7 @@ _scratch_mkfs_ext4()
 
        if [ $mkfs_status -eq 0 -a "$LARGE_SCRATCH_DEV" = yes ]; then
                # manually parse the mkfs output to get the fs size in bytes
-               fs_size=`cat $tmp.mkfsstd | awk ' \
+               local fs_size=`cat $tmp.mkfsstd | awk ' \
                        /^Block size/ { split($2, a, "="); bs = a[2] ; } \
                        / inodes, / { blks = $3 } \
                        /reserved for the super user/ { resv = $1 } \
@@ -623,6 +608,9 @@ _test_mkfs()
     9p)
        # do nothing for 9p
        ;;
+    virtiofs)
+       # do nothing for virtiofs
+       ;;
     ceph)
        # do nothing for ceph
        ;;
@@ -660,6 +648,9 @@ _mkfs_dev()
     9p)
        # do nothing for 9p
        ;;
+    virtiofs)
+       # do nothing for virtiofs
+       ;;
     overlay)
        # do nothing for overlay
        ;;
@@ -724,7 +715,7 @@ _scratch_mkfs()
        local mkfs_status
 
        case $FSTYP in
-       nfs*|cifs|ceph|overlay|glusterfs|pvfs2|9p)
+       nfs*|cifs|ceph|overlay|glusterfs|pvfs2|9p|virtiofs)
                # unable to re-create this fstyp, just remove all files in
                # $SCRATCH_MNT to avoid EEXIST caused by the leftover files
                # created in previous runs
@@ -905,13 +896,7 @@ _scratch_pool_mkfs()
 {
     case $FSTYP in
     btrfs)
-        # if dup profile is in mkfs options call _scratch_mkfs instead
-        # because dup profile only works with single device
-        if [[ "$*" =~ dup ]]; then
-            _scratch_mkfs $*
-        else
-            $MKFS_BTRFS_PROG $MKFS_OPTIONS $* $SCRATCH_DEV_POOL > /dev/null
-        fi
+        $MKFS_BTRFS_PROG $MKFS_OPTIONS $* $SCRATCH_DEV_POOL > /dev/null
         ;;
     *)
         echo "_scratch_pool_mkfs is not implemented for $FSTYP" 1>&2
@@ -929,8 +914,9 @@ _free_memory_bytes()
 # _scratch_mkfs_sized <size in bytes> [optional blocksize]
 _scratch_mkfs_sized()
 {
-    fssize=$1
-    blocksize=$2
+    local fssize=$1
+    local blocksize=$2
+    local def_blksz
 
     case $FSTYP in
     xfs)
@@ -948,7 +934,7 @@ _scratch_mkfs_sized()
     [ -z "$blocksize" ] && blocksize=4096
 
 
-    re='^[0-9]+$'
+    local re='^[0-9]+$'
     if ! [[ $fssize =~ $re ]] ; then
         _notrun "error: _scratch_mkfs_sized: fs size \"$fssize\" not an integer."
     fi
@@ -956,10 +942,10 @@ _scratch_mkfs_sized()
         _notrun "error: _scratch_mkfs_sized: block size \"$blocksize\" not an integer."
     fi
 
-    blocks=`expr $fssize / $blocksize`
+    local blocks=`expr $fssize / $blocksize`
 
     if [ "$HOSTOS" == "Linux" -a -b "$SCRATCH_DEV" ]; then
-       devsize=`blockdev --getsize64 $SCRATCH_DEV`
+       local devsize=`blockdev --getsize64 $SCRATCH_DEV`
        [ "$fssize" -gt "$devsize" ] && _notrun "Scratch device too small"
     fi
 
@@ -982,12 +968,12 @@ _scratch_mkfs_sized()
        # filesystem, which will cause mkfs.gfs2 to fail.  Until that's fixed,
        # shrink the journal size to at most one eigth of the filesystem and at
        # least 8 MiB, the minimum size allowed.
-       MIN_JOURNAL_SIZE=8
-       DEFAULT_JOURNAL_SIZE=128
-       if (( fssize/8 / (1024*1024) < DEFAULT_JOURNAL_SIZE )); then
-           (( JOURNAL_SIZE = fssize/8 / (1024*1024) ))
-           (( JOURNAL_SIZE >= MIN_JOURNAL_SIZE )) || JOURNAL_SIZE=$MIN_JOURNAL_SIZE
-           MKFS_OPTIONS="-J $JOURNAL_SIZE $MKFS_OPTIONS"
+       local min_journal_size=8
+       local default_journal_size=128
+       if (( fssize/8 / (1024*1024) < default_journal_size )); then
+           local journal_size=$(( fssize/8 / (1024*1024) ))
+           (( journal_size >= min_journal_size )) || journal_size=$min_journal_size
+           MKFS_OPTIONS="-J $journal_size $MKFS_OPTIONS"
        fi
        ${MKFS_PROG}.$FSTYP $MKFS_OPTIONS -O -b $blocksize $SCRATCH_DEV $blocks
        ;;
@@ -999,7 +985,10 @@ _scratch_mkfs_sized()
        ;;
     btrfs)
        local mixed_opt=
-       (( fssize <= 100 * 1024 * 1024 )) && mixed_opt='--mixed'
+       # minimum size that's needed without the mixed option.
+       # Ref: btrfs-prog: btrfs_min_dev_size()
+       # Non mixed mode is also the default option.
+       (( fssize < $((256 * 1024 *1024)) )) && mixed_opt='--mixed'
        $MKFS_BTRFS_PROG $MKFS_OPTIONS $mixed_opt -b $fssize $SCRATCH_DEV
        ;;
     jfs)
@@ -1015,11 +1004,11 @@ _scratch_mkfs_sized()
        ;;
     f2fs)
        # mkfs.f2fs requires # of sectors as an input for the size
-       sector_size=`blockdev --getss $SCRATCH_DEV`
+       local sector_size=`blockdev --getss $SCRATCH_DEV`
        $MKFS_F2FS_PROG $MKFS_OPTIONS $SCRATCH_DEV `expr $fssize / $sector_size`
        ;;
     tmpfs)
-       free_mem=`_free_memory_bytes`
+       local free_mem=`_free_memory_bytes`
        if [ "$free_mem" -lt "$fssize" ] ; then
           _notrun "Not enough memory ($free_mem) for tmpfs with $fssize bytes"
        fi
@@ -1035,13 +1024,13 @@ _scratch_mkfs_sized()
 # _scratch_mkfs_geom <sunit bytes> <swidth multiplier> [optional blocksize]
 _scratch_mkfs_geom()
 {
-    sunit_bytes=$1
-    swidth_mult=$2
-    blocksize=$3
+    local sunit_bytes=$1
+    local swidth_mult=$2
+    local blocksize=$3
     [ -z "$blocksize" ] && blocksize=4096
 
-    let sunit_blocks=$sunit_bytes/$blocksize
-    let swidth_blocks=$sunit_blocks*$swidth_mult
+    local sunit_blocks=$(( sunit_bytes / blocksize ))
+    local swidth_blocks=$(( sunit_blocks * swidth_mult ))
 
     case $FSTYP in
     xfs)
@@ -1061,9 +1050,9 @@ _scratch_mkfs_geom()
 # _scratch_mkfs_blocksized blocksize
 _scratch_mkfs_blocksized()
 {
-    blocksize=$1
+    local blocksize=$1
 
-    re='^[0-9]+$'
+    local re='^[0-9]+$'
     if ! [[ $blocksize =~ $re ]] ; then
         _notrun "error: _scratch_mkfs_sized: block size \"$blocksize\" not an integer."
     fi
@@ -1107,7 +1096,7 @@ _repair_scratch_fs()
     case $FSTYP in
     xfs)
         _scratch_xfs_repair "$@" 2>&1
-       res=$?
+       local res=$?
        if [ "$res" -ne 0 ]; then
                echo "xfs_repair returns $res; replay log?"
                _try_scratch_mount
@@ -1128,11 +1117,20 @@ _repair_scratch_fs()
        return $res
         ;;
     *)
-        # Let's hope fsck -y suffices...
-        fsck -t $FSTYP -y $SCRATCH_DEV 2>&1
-       res=$?
+       local dev=$SCRATCH_DEV
+       local fstyp=$FSTYP
+       if [ $FSTYP = "overlay" -a -n "$OVL_BASE_SCRATCH_DEV" ]; then
+               _repair_overlay_scratch_fs
+               # Fall through to repair base fs
+               dev=$OVL_BASE_SCRATCH_DEV
+               fstyp=$OVL_BASE_FSTYP
+               $UMOUNT_PROG $OVL_BASE_SCRATCH_MNT
+       fi
+       # Let's hope fsck -y suffices...
+       fsck -t $fstyp -y $dev 2>&1
+       local res=$?
        case $res in
-       0|1|2)
+       $FSCK_OK|$FSCK_NONDESTRUCT|$FSCK_REBOOT)
                res=0
                ;;
        *)
@@ -1169,27 +1167,6 @@ _get_pids_by_name()
        -e "/[0-9]:[0-9][0-9]  *$1 /s/ .*//p"
 }
 
-# fix malloc libs output
-#
-_fix_malloc()
-{
-    # filter out the Electric Fence notice
-    $PERL_PROG -e '
-        while (<>) {
-            if (defined $o && /^\s+Electric Fence/) {
-                chomp($o);
-                print "$o";
-                undef $o;
-                next;
-            }
-            print $o if (defined $o);
-
-            $o=$_;
-        }
-        print $o if (defined $o);
-    '
-}
-
 #
 # _df_device : get an IRIX style df line for a given device
 #
@@ -1317,13 +1294,13 @@ _is_block_dev()
        exit 1
     fi
 
-    _dev=$1
-    if [ -L "${_dev}" ]; then
-        _dev=`readlink -f "${_dev}"`
+    local dev=$1
+    if [ -L "$dev" ]; then
+        dev=`readlink -f "$dev"`
     fi
 
-    if [ -b "${_dev}" ]; then
-        src/lstat64 "${_dev}" | $AWK_PROG '/Device type:/ { print $9 }'
+    if [ -b "$dev" ]; then
+        $here/src/lstat64 "$dev" | $AWK_PROG '/Device type:/ { print $9 }'
     fi
 }
 
@@ -1336,13 +1313,13 @@ _is_char_dev()
                exit 1
        fi
 
-       _dev=$1
-       if [ -L "${_dev}" ]; then
-               _dev=`readlink -f "${_dev}"`
+       local dev=$1
+       if [ -L "$dev" ]; then
+               dev=`readlink -f "$dev"`
        fi
 
-       if [ -c "${_dev}" ]; then
-               src/lstat64 "${_dev}" | $AWK_PROG '/Device type:/ { print $9 }'
+       if [ -c "$dev" ]; then
+               $here/src/lstat64 "$dev" | $AWK_PROG '/Device type:/ { print $9 }'
        fi
 }
 
@@ -1359,19 +1336,20 @@ _is_char_dev()
 _do()
 {
     if [ $# -eq 1 ]; then
-       _cmd=$1
+       local cmd=$1
     elif [ $# -eq 2 ]; then
-       _note=$1
-       _cmd=$2
-       echo -n "$_note... "
+       local note=$1
+       local cmd=$2
+       echo -n "$note... "
     else
        echo "Usage: _do [note] cmd" 1>&2
        status=1; exit
     fi
 
-    (eval "echo '---' \"$_cmd\"") >>$seqres.full
-    (eval "$_cmd") >$tmp._out 2>&1; ret=$?
-    cat $tmp._out | _fix_malloc >>$seqres.full
+    (eval "echo '---' \"$cmd\"") >>$seqres.full
+    (eval "$cmd") >$tmp._out 2>&1
+    local ret=$?
+    cat $tmp._out >>$seqres.full
     rm -f $tmp._out
     if [ $# -eq 2 ]; then
        if [ $ret -eq 0 ]; then
@@ -1385,7 +1363,7 @@ _do()
            -o \( $# -eq 2 -a "$_do_die_on_error" = "message_only" \) ]
     then
        [ $# -ne 2 ] && echo
-       eval "echo \"$_cmd\" failed \(returned $ret\): see $seqres.full"
+       eval "echo \"$cmd\" failed \(returned $ret\): see $seqres.full"
        status=1; exit
     fi
 
@@ -1420,6 +1398,8 @@ _fail()
 #
 _supported_fs()
 {
+    local f
+
     for f
     do
        if [ "$f" = "$FSTYP" -o "$f" = "generic" ]
@@ -1436,6 +1416,8 @@ _supported_fs()
 #
 _supported_os()
 {
+    local h
+
     for h
     do
        if [ "$h" = "$HOSTOS" ]
@@ -1496,7 +1478,7 @@ _require_scratch_nocheck()
                        _notrun "this test requires a valid \$SCRATCH_MNT"
                fi
                ;;
-       9p)
+       9p|virtiofs)
                if [ -z "$SCRATCH_DEV" ]; then
                        _notrun "this test requires a valid \$SCRATCH_DEV"
                fi
@@ -1595,6 +1577,16 @@ _require_scratch()
        touch ${RESULT_DIR}/require_scratch
 }
 
+# require a scratch dev of a minimum size (in kb)
+_require_scratch_size()
+{
+       [ $# -eq 1 ] || _fail "_require_scratch_size: expected size param"
+
+       _require_scratch
+       local devsize=`_get_device_size $SCRATCH_DEV`
+       [ $devsize -lt $1 ] && _notrun "scratch dev too small"
+}
+
 
 # this test needs a test partition - check we're ok & mount it
 #
@@ -1610,7 +1602,7 @@ _require_test()
                        _notrun "this test requires a valid \$TEST_DIR"
                fi
                ;;
-       9p)
+       9p|virtiofs)
                if [ -z "$TEST_DEV" ]; then
                        _notrun "this test requires a valid \$TEST_DEV"
                fi
@@ -1800,16 +1792,16 @@ _require_no_realtime()
 _require_command()
 {
        if [ $# -eq 2 ]; then
-               _name="$2"
+               local name="$2"
        elif [ $# -eq 1 ]; then
-               _name="$1"
+               local name="$1"
        else
                _fail "usage: _require_command <command> [<name>]"
        fi
 
-       _command=`echo "$1" | awk '{ print $1 }'`
-       if [ ! -x "$_command" ]; then
-               _notrun "$_name utility required, skipped this test"
+       local command=`echo "$1" | awk '{ print $1 }'`
+       if [ ! -x "$command" ]; then
+               _notrun "$name utility required, skipped this test"
        fi
 }
 
@@ -1857,7 +1849,7 @@ _require_sane_bdev_flush()
 # this test requires a specific device mapper target
 _require_dm_target()
 {
-       _target=$1
+       local target=$1
 
        # require SCRATCH_DEV to be a valid block device with sane BLKFLSBUF
        # behaviour
@@ -1865,11 +1857,11 @@ _require_dm_target()
        _require_sane_bdev_flush $SCRATCH_DEV
        _require_command "$DMSETUP_PROG" dmsetup
 
-       modprobe dm-$_target >/dev/null 2>&1
+       modprobe dm-$target >/dev/null 2>&1
 
-       $DMSETUP_PROG targets 2>&1 | grep -q ^$_target
+       $DMSETUP_PROG targets 2>&1 | grep -q ^$target
        if [ $? -ne 0 ]; then
-               _notrun "This test requires dm $_target support"
+               _notrun "This test requires dm $target support"
        fi
 }
 
@@ -1932,10 +1924,10 @@ _require_aiodio()
 {
     if [ -z "$1" ]
     then
-        AIO_TEST=src/aio-dio-regress/aiodio_sparse2
+        AIO_TEST=$here/src/aio-dio-regress/aiodio_sparse2
         [ -x $AIO_TEST ] || _notrun "aio-dio utilities required"
     else
-        AIO_TEST=src/aio-dio-regress/$1
+        AIO_TEST=$here/src/aio-dio-regress/$1
         [ -x $AIO_TEST ] || _notrun "$AIO_TEST not built"
     fi
     _require_aio
@@ -1947,8 +1939,8 @@ _require_aiodio()
 #
 _require_test_program()
 {
-    SRC_TEST=src/$1
-    [ -x $SRC_TEST ] || _notrun "$SRC_TEST not built"
+    local prog=$here/src/$1
+    [ -x $prog ] || _notrun "$prog not built"
 }
 
 # run an aio-dio program
@@ -1972,16 +1964,9 @@ _run_aiodio()
     return $status
 }
 
-# this test requires y2038 sysfs switch and filesystem
-# timestamp ranges support.
-_require_y2038()
+_require_timestamp_range()
 {
        local device=${1:-$TEST_DEV}
-       local sysfsdir=/proc/sys/fs/fs-timestamp-check-on
-
-       if [ ! -e $sysfsdir ]; then
-               _notrun "no kernel support for y2038 sysfs switch"
-       fi
 
        local tsmin tsmax
        read tsmin tsmax <<<$(_filesystem_timestamp_range $device)
@@ -1992,24 +1977,33 @@ _require_y2038()
 
 _filesystem_timestamp_range()
 {
-       device=${1:-$TEST_DEV}
+       local device=${1:-$TEST_DEV}
+       u32max=$(((1<<32)-1))
+       s32min=-$((1<<31))
+       s32max=$(((1<<31)-1))
+       s64max=$(((1<<63)-1))
+       s64min=$((1<<63))
+
        case $FSTYP in
-       ext4)
+       ext2)
+               echo "$s32min $s32max"
+               ;;
+       ext3|ext4)
                if [ $(dumpe2fs -h $device 2>/dev/null | grep "Inode size:" | cut -d: -f2) -gt 128 ]; then
-                       echo "-2147483648 15032385535"
+                       printf "%d %d\n" $s32min 0x37fffffff
                else
-                       echo "-2147483648 2147483647"
+                       echo "$s32min $s32max"
                fi
                ;;
 
-       xfs)
-               echo "-2147483648 2147483647"
-               ;;
        jfs)
-               echo "0 4294967295"
+               echo "0 $u32max"
                ;;
-       f2fs)
-               echo "-2147483648 2147483647"
+       xfs)
+               echo "$s32min $s32max"
+               ;;
+       btrfs)
+               echo "$s64min $s64max"
                ;;
        *)
                echo "-1 -1"
@@ -2023,7 +2017,10 @@ _yp_active()
 {
        local dn
        dn=$(domainname 2>/dev/null)
-       test -n "${dn}" -a "${dn}" != "(none)" -a "${dn}" != "localdomain"
+       local ypcat=$(type -P ypcat)
+       local rpcinfo=$(type -P rpcinfo)
+       test -n "${dn}" -a "${dn}" != "(none)" -a "${dn}" != "localdomain" -a -n "${ypcat}" -a -n "${rpcinfo}" && \
+               "${rpcinfo}" -p localhost 2>/dev/null | grep -q ypbind
        echo $?
 }
 
@@ -2094,23 +2091,41 @@ _require_xfs_io_command()
        local command=$1
        shift
        local param="$*"
-       local param_checked=0
+       local param_checked=""
        local opts=""
 
-       testfile=$TEST_DIR/$$.xfs_io
+       local testfile=$TEST_DIR/$$.xfs_io
+       local testio
        case $command in
+       "chattr")
+               if [ -z "$param" ]; then
+                       param=s
+               fi
+               # Test xfs_io chattr support AND
+               # filesystem FS_IOC_FSSETXATTR support
+               testio=`$XFS_IO_PROG -F -f -c "chattr +$param" $testfile 2>&1`
+               $XFS_IO_PROG -F -f -r -c "chattr -$param" $testfile 2>&1
+               param_checked="+$param"
+               ;;
        "chproj")
                testio=`$XFS_IO_PROG -F -f -c "chproj 0" $testfile 2>&1`
                ;;
        "copy_range")
-               testcopy=$TEST_DIR/$$.copy.xfs_io
+               local testcopy=$TEST_DIR/$$.copy.xfs_io
+               local copy_opts=$testfile
+               if [ "$param" == "-f" ]; then
+                       # source file is the open destination file
+                       testcopy=$testfile
+                       copy_opts="0 -d 4k -l 4k"
+               fi
                $XFS_IO_PROG -F -f -c "pwrite 0 4k" $testfile > /dev/null 2>&1
-               testio=`$XFS_IO_PROG -F -f -c "copy_range $testfile" $testcopy 2>&1`
+               testio=`$XFS_IO_PROG -F -f -c "copy_range $param $copy_opts" $testcopy 2>&1`
                rm -f $testcopy > /dev/null 2>&1
+               param_checked="$param"
                ;;
        "falloc" )
                testio=`$XFS_IO_PROG -F -f -c "falloc $param 0 1m" $testfile 2>&1`
-               param_checked=1
+               param_checked="$param"
                ;;
        "fpunch" | "fcollapse" | "zero" | "fzero" | "finsert" | "funshare")
                local blocksize=$(_get_block_size $TEST_DIR)
@@ -2128,19 +2143,29 @@ _require_xfs_io_command()
                fi
                testio=`$XFS_IO_PROG -F -f -c "pwrite 0 20k" -c "fsync" \
                        -c "fiemap -v $param" $testfile 2>&1`
-               param_checked=1
+               param_checked="$param"
+               ;;
+       "flink")
+               local testlink=$TEST_DIR/$$.link.xfs_io
+               testio=`$XFS_IO_PROG -F -f -c "flink $testlink" $testfile 2>&1`
+               rm -f $testlink > /dev/null 2>&1
                ;;
-       "flink" )
-               testio=`$XFS_IO_PROG -T -F -c "flink $testfile" \
-                       $TEST_DIR 2>&1`
+       "-T")
+               # Check O_TMPFILE support in xfs_io, kernel and fs
+               testio=`$XFS_IO_PROG -T -c quit $TEST_DIR 2>&1`
                echo $testio | egrep -q "invalid option|Is a directory" && \
                        _notrun "xfs_io $command support is missing"
+               echo $testio | grep -q "Operation not supported" && \
+                       _notrun "O_TMPFILE is not supported"
                ;;
-       "fsmap" )
+       "fsmap")
                testio=`$XFS_IO_PROG -f -c "fsmap" $testfile 2>&1`
                echo $testio | grep -q "Inappropriate ioctl" && \
                        _notrun "xfs_io $command support is missing"
                ;;
+       "label")
+               testio=`$XFS_IO_PROG -c "label" $TEST_DIR 2>&1`
+               ;;
        "open")
                # -c "open $f" is broken in xfs_io <= 4.8. Along with the fix,
                # a new -C flag was introduced to execute one shot commands.
@@ -2158,15 +2183,15 @@ _require_xfs_io_command()
                fi
                testio=`$XFS_IO_PROG -f $opts -c \
                        "pwrite $pwrite_opts $param 0 4k" $testfile 2>&1`
-               param_checked=1
+               param_checked="$pwrite_opts $param"
                ;;
        "scrub"|"repair")
-               testio=`$XFS_IO_PROG -x -c "$command probe 0" $TEST_DIR 2>&1`
+               testio=`$XFS_IO_PROG -x -c "$command probe" $TEST_DIR 2>&1`
                echo $testio | grep -q "Inappropriate ioctl" && \
                        _notrun "xfs_io $command support is missing"
                ;;
        "utimes" )
-               testio=`$XFS_IO_PROG -f -c "utimes" 0 0 0 0 $testfile 2>&1`
+               testio=`$XFS_IO_PROG -f -c "utimes 0 0 0 0" $testfile 2>&1`
                ;;
        "syncfs")
                touch $testfile
@@ -2178,19 +2203,19 @@ _require_xfs_io_command()
 
        rm -f $testfile 2>&1 > /dev/null
        echo $testio | grep -q "not found" && \
-               _notrun "xfs_io $command support is missing"
-       echo $testio | grep -q "Operation not supported" && \
-               _notrun "xfs_io $command failed (old kernel/wrong fs?)"
+               _notrun "xfs_io $command $param_checked support is missing"
+       echo $testio | grep -q "Operation not supported\|Inappropriate ioctl" && \
+               _notrun "xfs_io $command $param_checked failed (old kernel/wrong fs?)"
        echo $testio | grep -q "Invalid" && \
-               _notrun "xfs_io $command failed (old kernel/wrong fs/bad args?)"
+               _notrun "xfs_io $command $param_checked failed (old kernel/wrong fs/bad args?)"
        echo $testio | grep -q "foreign file active" && \
-               _notrun "xfs_io $command not supported on $FSTYP"
+               _notrun "xfs_io $command $param_checked not supported on $FSTYP"
        echo $testio | grep -q "Function not implemented" && \
-               _notrun "xfs_io $command support is missing (missing syscall?)"
+               _notrun "xfs_io $command $param_checked support is missing (missing syscall?)"
 
        [ -n "$param" ] || return
 
-       if [ $param_checked -eq 0 ]; then
+       if [ -z "$param_checked" ]; then
                $XFS_IO_PROG -c "help $command" | grep -q "^ $param --" || \
                        _notrun "xfs_io $command doesn't support $param"
        else
@@ -2204,14 +2229,17 @@ _require_xfs_io_command()
 # check that kernel and filesystem support direct I/O
 _require_odirect()
 {
-       if [ $FSTYP = "ext4" ] ; then
+       if [ $FSTYP = "ext4" ] || [ $FSTYP = "f2fs" ] ; then
                if echo "$MOUNT_OPTIONS" | grep -q "test_dummy_encryption"; then
-                       _notrun "ext4 encryption doesn't support O_DIRECT"
-               elif echo "$MOUNT_OPTIONS" | grep -q "data=journal"; then
+                       _notrun "$FSTYP encryption doesn't support O_DIRECT"
+               fi
+       fi
+       if [ $FSTYP = "ext4" ] ; then
+               if echo "$MOUNT_OPTIONS" | grep -q "data=journal"; then
                        _notrun "ext4 data journaling doesn't support O_DIRECT"
                fi
        fi
-       testfile=$TEST_DIR/$$.direct
+       local testfile=$TEST_DIR/$$.direct
        $XFS_IO_PROG -F -f -d -c "pwrite 0 20k" $testfile > /dev/null 2>&1
        if [ $? -ne 0 ]; then
                _notrun "O_DIRECT is not supported"
@@ -2219,19 +2247,43 @@ _require_odirect()
        rm -f $testfile 2>&1 > /dev/null
 }
 
+_format_swapfile() {
+       local fname="$1"
+       local sz="$2"
+
+       rm -f "$fname"
+       touch "$fname"
+       chmod 0600 "$fname"
+       # Swap files must be nocow on Btrfs.
+       $CHATTR_PROG +C "$fname" > /dev/null 2>&1
+       _pwrite_byte 0x61 0 "$sz" "$fname" >> $seqres.full
+       $MKSWAP_PROG "$fname" >> $seqres.full
+}
+
 # Check that the filesystem supports swapfiles
 _require_scratch_swapfile()
 {
        _require_scratch
+       _require_command "$MKSWAP_PROG" "mkswap"
 
        _scratch_mkfs >/dev/null
+
+       # With mounting SELinux context(e.g. system_u:object_r:root_t:s0),
+       # standard mkswap tried to reset the type of default context to
+       # swapfile_t if it's not swapfile_t, and then it failed and returned
+       # ENOTSUP expectedly as we don't want to create any SELinux attr on
+       # purpose.  standard mkswap ignored this relabel error by commit
+       # d97dc0e of util-linux, but it still reported the error before
+       # commit d97dc0e.  We mount swapfile context directly to skip the
+       # reset step.
+       [ -n "$SELINUX_MOUNT_OPTIONS" ] && export \
+               SELINUX_MOUNT_OPTIONS="-o context=system_u:object_r:swapfile_t:s0"
+
        _scratch_mount
 
        # Minimum size for mkswap is 10 pages
-       local size=$(($(get_page_size) * 10))
+       _format_swapfile "$SCRATCH_MNT/swap" $(($(get_page_size) * 10))
 
-       _pwrite_byte 0x61 0 "$size" "$SCRATCH_MNT/swap" >/dev/null 2>&1
-       mkswap "$SCRATCH_MNT/swap" >/dev/null 2>&1
        if ! swapon "$SCRATCH_MNT/swap" >/dev/null 2>&1; then
                _scratch_unmount
                _notrun "swapfiles are not supported"
@@ -2245,13 +2297,13 @@ _require_scratch_swapfile()
 #
 _require_fs_space()
 {
-       MNT=$1
-       BLOCKS=$2       # in units of 1024
-       let GB=$BLOCKS/1024/1024
+       local mnt=$1
+       local blocks=$2 # in units of 1024
+       local gb=$(( blocks / 1024 / 1024 ))
 
-       FREE_BLOCKS=`df -kP $MNT | grep -v Filesystem | awk '{print $4}'`
-       [ $FREE_BLOCKS -lt $BLOCKS ] && \
-               _notrun "This test requires at least ${GB}GB free on $MNT to run"
+       local free_blocks=`df -kP $mnt | grep -v Filesystem | awk '{print $4}'`
+       [ $free_blocks -lt $blocks ] && \
+               _notrun "This test requires at least ${gb}GB free on $mnt to run"
 }
 
 #
@@ -2293,6 +2345,60 @@ _ext4_disable_extent_zeroout()
                echo 0 >/sys/fs/ext4/$sdev/extent_max_zeroout_kb
 }
 
+# The default behavior of SEEK_HOLE is to always return EOF.
+# Filesystems that implement non-default behavior return the offset
+# of holes with SEEK_HOLE. There is no way to query the filesystem
+# of which behavior it is implementing.
+# We use this whitelist FSTYP, to set expectation and avoid silent
+# regression of filesystem seek hole behavior.
+#
+# Return 0 for true
+_fstyp_has_non_default_seek_data_hole()
+{
+       if [ -z $1 ]; then
+               local fstyp=$FSTYP
+       else
+               local fstyp=$1
+       fi
+
+       case "$fstyp" in
+       btrfs|ext4|xfs|cifs|f2fs|gfs2|ocfs2|tmpfs)
+               return 0
+               ;;
+       nfs*)
+               # NFSv2 and NFSv3 only support default behavior of SEEK_HOLE,
+               # while NFSv4 supports non-default behavior
+               local nfsvers=`_df_device $TEST_DEV | $AWK_PROG '{ print $2 }'`
+               [ "$nfsvers" = "nfs4" ]
+               return $?
+               ;;
+       overlay)
+               if [ ! -z $OVL_BASE_FSTYP -a $OVL_BASE_FSTYP != "overlay" ]; then
+                       _fstyp_has_non_default_seek_data_hole $OVL_BASE_FSTYP
+                       return $?
+               else
+                       # Assume that base fs has default behavior
+                       return 1
+               fi
+               ;;
+       *)
+               # by default fstyp has default SEEK_HOLE behavior;
+               # if your fs has non-default behavior, add it to whitelist above!
+               return 1
+               ;;
+       esac
+}
+
+# Run seek sanity test with predefined expectation for SEEK_DATA/HOLE behavior
+_run_seek_sanity_test()
+{
+       local testseekargs
+       if _fstyp_has_non_default_seek_data_hole; then
+               testseekargs+="-f"
+       fi
+       $here/src/seek_sanity_test $testseekargs $*
+}
+
 # Check if the file system supports seek_data/hole
 _require_seek_data_hole()
 {
@@ -2418,8 +2524,8 @@ _remount()
        echo "Usage: _remount device ro/rw" 1>&2
        exit 1
     fi
-    device=$1
-    mode=$2
+    local device=$1
+    local mode=$2
 
     if ! mount -o remount,$mode $device
     then
@@ -2445,8 +2551,8 @@ _umount_or_remount_ro()
        exit 1
     fi
 
-    device=$1
-    mountpoint=`_is_dev_mounted $device`
+    local device=$1
+    local mountpoint=`_is_dev_mounted $device`
 
     if [ $USE_REMOUNT -eq 0 ]; then
         $UMOUNT_PROG $device
@@ -2462,9 +2568,9 @@ _mount_or_remount_rw()
                echo "Usage: _mount_or_remount_rw <opts> <dev> <mnt>" 1>&2
                exit 1
        fi
-       mount_opts=$1
-       device=$2
-       mountpoint=$3
+       local mount_opts=$1
+       local device=$2
+       local mountpoint=$3
 
        if [ $USE_REMOUNT -eq 0 ]; then
                if [ "$FSTYP" != "overlay" ]; then
@@ -2492,16 +2598,16 @@ _mount_or_remount_rw()
 #
 _check_generic_filesystem()
 {
-    device=$1
+    local device=$1
 
     # If type is set, we're mounted
-    type=`_fs_type $device`
-    ok=1
+    local type=`_fs_type $device`
+    local ok=1
 
     if [ "$type" = "$FSTYP" ]
     then
         # mounted ...
-        mountpoint=`_umount_or_remount_ro $device`
+        local mountpoint=`_umount_or_remount_ro $device`
     fi
 
     fsck -t $FSTYP $FSCK_OPTIONS $device >$tmp.fsck 2>&1
@@ -2566,16 +2672,15 @@ _check_udf_filesystem()
        return
     fi
 
-    device=$1
-    if [ $# -eq 2 ];
-    then
-        LAST_BLOCK=`expr \( $2 - 1 \)`
-        OPT_ARG="-lastvalidblock $LAST_BLOCK"
+    local device=$1
+    local opt_arg=""
+    if [ $# -eq 2 ]; then
+       opt_arg="-lastvalidblock $(( $2 - 1 ))"
     fi
 
     rm -f $seqres.checkfs
     sleep 1 # Due to a problem with time stamps in udf_test
-    $here/src/udf_test $OPT_ARG $device | tee $seqres.checkfs | egrep "Error|Warning" | \
+    $here/src/udf_test $opt_arg $device | tee $seqres.checkfs | egrep "Error|Warning" | \
        _udf_test_known_error_filter | \
        egrep -iv "Error count:.*[0-9]+.*total occurrences:.*[0-9]+|Warning count:.*[0-9]+.*total occurrences:.*[0-9]+" && \
         echo "Warning UDF Verifier reported errors see $seqres.checkfs." && return 1
@@ -2597,6 +2702,9 @@ _check_test_fs()
     9p)
        # no way to check consistency for 9p
        ;;
+    virtiofs)
+       # no way to check consistency for virtiofs
+       ;;
     ceph)
        # no way to check consistency for CephFS
        ;;
@@ -2628,20 +2736,20 @@ _check_test_fs()
 
 _check_scratch_fs()
 {
-    device=$SCRATCH_DEV
+    local device=$SCRATCH_DEV
     [ $# -eq 1 ] && device=$1
 
     case $FSTYP in
     xfs)
-       SCRATCH_LOG="none"
-       SCRATCH_RT="none"
+       local scratch_log="none"
+       local scratch_rt="none"
        [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_LOGDEV" ] && \
-           SCRATCH_LOG="$SCRATCH_LOGDEV"
+           scratch_log="$SCRATCH_LOGDEV"
 
        [ "$USE_EXTERNAL" = yes -a ! -z "$SCRATCH_RTDEV" ] && \
-           SCRATCH_RT="$SCRATCH_RTDEV"
+           scratch_rt="$SCRATCH_RTDEV"
 
-       _check_xfs_filesystem $device $SCRATCH_LOG $SCRATCH_RT
+       _check_xfs_filesystem $device $scratch_log $scratch_rt
        ;;
     udf)
        _check_udf_filesystem $device $udf_fsize
@@ -2655,6 +2763,9 @@ _check_scratch_fs()
     9p)
        # no way to check consistency for 9p
        ;;
+    virtiofs)
+       # no way to check consistency for virtiofs
+       ;;
     ceph)
        # no way to check consistency for CephFS
        ;;
@@ -2704,10 +2815,10 @@ _full_fstyp_details()
 
 _full_platform_details()
 {
-     os=`uname -s`
-     host=`hostname -s`
-     kernel=`uname -r`
-     platform=`uname -m`
+     local os=`uname -s`
+     local host=`hostname -s`
+     local kernel=`uname -rv`
+     local platform=`uname -m`
      echo "$os/$platform $host $kernel"
 }
 
@@ -2723,8 +2834,8 @@ _get_os_name()
 
 _link_out_file_named()
 {
-       export FEATURES=$2
-       SUFFIX=$(perl -e '
+       local features=$2
+       local suffix=$(FEATURES="$features" perl -e '
                my %feathash;
                my $feature, $result, $suffix, $opts;
 
@@ -2751,22 +2862,23 @@ _link_out_file_named()
                print $result
                ' <$seqfull.cfg)
        rm -f $1
-       SRC=$(basename $1)
-       ln -fs $SRC.$SUFFIX $1
+       ln -fs $(basename $1).$suffix $1
 }
 
 _link_out_file()
 {
+       local features
+
        if [ $# -eq 0 ]; then
-               FEATURES="$(_get_os_name)"
+               features="$(_get_os_name),$FSTYP"
                if [ -n "$MOUNT_OPTIONS" ]; then
-                       FEATURES=$FEATURES,${MOUNT_OPTIONS##"-o "}
+                       features=$features,${MOUNT_OPTIONS##"-o "}
                fi
        else
-               FEATURES=$1
+               features=$1
        fi
 
-       _link_out_file_named $seqfull.out "$FEATURES"
+       _link_out_file_named $seqfull.out "$features"
 }
 
 _die()
@@ -2784,10 +2896,10 @@ _ddt()
 #takes files, randomdata
 _nfiles()
 {
-        f=0
+        local f=0
         while [ $f -lt $1 ]
         do
-                file=f$f
+                local file=f$f
                 echo > $file
                 if [ $size -gt 0 ]; then
                     if [ "$2" == "false" ]; then
@@ -2805,18 +2917,18 @@ _nfiles()
 # takes dirname, depth, randomdata
 _descend()
 {
-        dirname=$1; depth=$2; randomdata=$3
+        local dirname=$1 depth=$2 randomdata=$3
         mkdir $dirname  || die "mkdir $dirname failed"
         cd $dirname
 
         _nfiles $files $randomdata          # files for this dir and data type
 
         [ $depth -eq 0 ] && return
-       let deep=$depth-1 # go 1 down
+        local deep=$(( depth - 1 )) # go 1 down
 
         [ $verbose = true ] && echo "descending, depth from leaves = $deep"
 
-        d=0
+        local d=0
         while [ $d -lt $dirs ]
         do
                 _descend d$d $deep &
@@ -2831,14 +2943,15 @@ _descend()
 #
 _populate_fs()
 {
-    here=`pwd`
-    dirs=5          # ndirs in each subdir till leaves
-    size=0          # sizeof files in K
-    files=100       # num files in _each_ subdir
-    depth=2         # depth of tree from root to leaves
-    verbose=false
-    root=root       # path of initial root of directory tree
-    randomdata=false # -x data type urandom, zero or compressible
+    local here=`pwd`
+    local dirs=5          # ndirs in each subdir till leaves
+    local size=0          # sizeof files in K
+    local files=100       # num files in _each_ subdir
+    local depth=2         # depth of tree from root to leaves
+    local verbose=false
+    local root=root       # path of initial root of directory tree
+    local randomdata=false # -x data type urandom, zero or compressible
+    local c
 
     OPTIND=1
     while getopts "d:f:n:r:s:v:x:c" c
@@ -2867,8 +2980,8 @@ _populate_fs()
 #
 _test_inode_flag()
 {
-       flag=$1
-       file=$2
+       local flag=$1
+       local file=$2
 
        if $XFS_IO_PROG -r -c 'lsattr -v' "$file" | grep -q "$flag" ; then
                return 0
@@ -2880,8 +2993,8 @@ _test_inode_flag()
 #
 _test_inode_extsz()
 {
-       file=$1
-       blocks=""
+       local file=$1
+       local blocks=""
 
        blocks=`$XFS_IO_PROG -r -c 'stat' "$file" | \
                awk '/^xattr.extsize =/ { print $3 }'`
@@ -2941,37 +3054,25 @@ _require_scratch_dev_pool()
 # must be called after _require_scratch_dev_pool
 _require_scratch_dev_pool_equal_size()
 {
-       local _size
-       local _newsize
-       local _dev
+       local size
+       local newsize
+       local dev
 
        # SCRATCH_DEV has been set to the first device in SCRATCH_DEV_POOL
-       _size=`_get_device_size $SCRATCH_DEV`
-       for _dev in $SCRATCH_DEV_POOL; do
-               _newsize=`_get_device_size $_dev`
-               if [ $_size -ne $_newsize ]; then
+       size=`_get_device_size $SCRATCH_DEV`
+       for dev in $SCRATCH_DEV_POOL; do
+               newsize=`_get_device_size $dev`
+               if [ $size -ne $newsize ]; then
                        _notrun "This test requires devices in SCRATCH_DEV_POOL have the same size"
                fi
        done
 }
 
-# We will check if the device is deletable
-_require_deletable_scratch_dev_pool()
-{
-       local i
-       local x
-       for i in $SCRATCH_DEV_POOL; do
-               x=`echo $i | cut -d"/" -f 3`
-               if [ ! -f /sys/class/block/${x}/device/delete ]; then
-                       _notrun "$i is a device which is not deletable"
-               fi
-       done
-}
 
 # Check that fio is present, and it is able to execute given jobfile
 _require_fio()
 {
-       job=$1
+       local job=$1
 
        _require_command "$FIO_PROG" fio
        if [ -z "$1" ]; then
@@ -2986,7 +3087,7 @@ _require_fio()
 _require_freeze()
 {
        xfs_freeze -f "$TEST_DIR" >/dev/null 2>&1
-       result=$? 
+       local result=$?
        xfs_freeze -u "$TEST_DIR" >/dev/null 2>&1
        [ $result -eq 0 ] || _notrun "$FSTYP does not support freezing"
 }
@@ -3004,7 +3105,7 @@ _require_exportfs()
 # Does shutdown work on this fs?
 _require_scratch_shutdown()
 {
-       [ -x src/godown ] || _notrun "src/godown executable not found"
+       [ -x $here/src/godown ] || _notrun "src/godown executable not found"
 
        _scratch_mkfs > /dev/null 2>&1 || _notrun "_scratch_mkfs failed on $SCRATCH_DEV"
        _scratch_mount
@@ -3015,13 +3116,13 @@ _require_scratch_shutdown()
                        # SCRATCH_DEV, in this case OVL_BASE_SCRATCH_DEV
                        # will be null, so check OVL_BASE_SCRATCH_DEV before
                        # running shutdown to avoid shutting down base fs accidently.
-                       _notrun "$SCRATCH_DEV is not a block device"
+                       _notrun "This test requires a valid $OVL_BASE_SCRATCH_DEV as ovl base fs"
                else
-                       src/godown -f $OVL_BASE_SCRATCH_MNT 2>&1 \
+                       $here/src/godown -f $OVL_BASE_SCRATCH_MNT 2>&1 \
                        || _notrun "Underlying filesystem does not support shutdown"
                fi
        else
-               src/godown -f $SCRATCH_MNT 2>&1 \
+               $here/src/godown -f $SCRATCH_MNT 2>&1 \
                        || _notrun "$FSTYP does not support shutdown"
        fi
 
@@ -3061,9 +3162,9 @@ _require_norecovery()
 _require_metadata_journaling()
 {
        if [ -z $1 ]; then
-               DEV=$TEST_DEV
+               local dev=$TEST_DEV
        else
-               DEV=$1
+               local dev=$1
        fi
 
        case "$FSTYP" in
@@ -3073,8 +3174,8 @@ _require_metadata_journaling()
        ext4)
                # ext4 could be mkfs'd without a journal...
                _require_dumpe2fs
-               $DUMPE2FS_PROG -h $DEV 2>&1 | grep -q has_journal || \
-                       _notrun "$FSTYP on $DEV not configured with metadata journaling"
+               $DUMPE2FS_PROG -h $dev 2>&1 | grep -q has_journal || \
+                       _notrun "$FSTYP on $dev not configured with metadata journaling"
                # ext4 might not load a journal
                _exclude_scratch_mount_option "noload"
                ;;
@@ -3098,12 +3199,12 @@ _require_metadata_journaling()
 
 _count_extents()
 {
-       $XFS_IO_PROG -c "fiemap" $1 | tail -n +2 | grep -v hole | wc -l
+       $XFS_IO_PROG -r -c "fiemap" $1 | tail -n +2 | grep -v hole | wc -l
 }
 
 _count_holes()
 {
-       $XFS_IO_PROG -c "fiemap" $1 | tail -n +2 | grep hole | wc -l
+       $XFS_IO_PROG -r -c "fiemap" $1 | tail -n +2 | grep hole | wc -l
 }
 
 _count_attr_extents()
@@ -3140,10 +3241,12 @@ _devmgt_add()
        echo ${tdl} >  /sys/class/scsi_host/host${h}/scan || _fail "Add disk failed"
 
        # ensure the device comes online
-       dev_back_oneline=0
+       local dev_back_oneline=0
+       local i
        for i in `seq 1 10`; do
                if [ -d /sys/class/scsi_device/${1}/device/block ]; then
-                       dev=`ls /sys/class/scsi_device/${1}/device/block`
+                       local dev=`ls /sys/class/scsi_device/${1}/device/block`
+                       local j
                        for j in `seq 1 10`;
                        do
                                stat /dev/$dev > /dev/null 2>&1
@@ -3236,9 +3339,12 @@ _exclude_scratch_mount_option()
 _require_atime()
 {
        _exclude_scratch_mount_option "noatime"
-       if [ "$FSTYP" == "nfs" ]; then
-               _notrun "atime related mount options have no effect on NFS"
-       fi
+       case $FSTYP in
+       nfs|cifs)
+               _notrun "atime related mount options have no effect on $FSTYP"
+               ;;
+       esac
+
 }
 
 _require_relatime()
@@ -3251,26 +3357,26 @@ _require_relatime()
 
 _require_userns()
 {
-       [ -x src/nsexec ] || _notrun "src/nsexec executable not found"
-       src/nsexec -U true 2>/dev/null || _notrun "userns not supported by this kernel"
+       [ -x $here/src/nsexec ] || _notrun "src/nsexec executable not found"
+       $here/src/nsexec -U true 2>/dev/null || _notrun "userns not supported by this kernel"
 }
 
 _create_loop_device()
 {
-       file=$1
+       local file=$1 dev
        dev=`losetup -f --show $file` || _fail "Cannot assign $file to a loop device"
        echo $dev
 }
 
 _destroy_loop_device()
 {
-       dev=$1
+       local dev=$1
        losetup -d $dev || _fail "Cannot destroy loop device $dev"
 }
 
 _scale_fsstress_args()
 {
-    args=""
+    local args=""
     while [ $# -gt 0 ]; do
         case "$1" in
             -n) args="$args $1 $(($2 * $TIME_FACTOR))"; shift ;;
@@ -3288,7 +3394,7 @@ _scale_fsstress_args()
 #
 _min_dio_alignment()
 {
-    dev=$1
+    local dev=$1
 
     if [ -b "$dev" ]; then
         blockdev --getss $dev
@@ -3305,8 +3411,8 @@ run_check()
 
 _require_test_symlinks()
 {
-       target=`mktemp -p $TEST_DIR`
-       link=`mktemp -p $TEST_DIR -u`
+       local target=`mktemp -p $TEST_DIR`
+       local link=`mktemp -p $TEST_DIR -u`
        ln -s `basename $target` $link
        if [ "$?" -ne 0 ]; then
                rm -f $target
@@ -3330,13 +3436,13 @@ _require_ofd_locks()
        # EINVAL will be returned.
        _require_test_program "t_ofd_locks"
        touch $TEST_DIR/ofd_testfile
-       src/t_ofd_locks -t $TEST_DIR/ofd_testfile > /dev/null 2>&1
+       $here/src/t_ofd_locks -t $TEST_DIR/ofd_testfile > /dev/null 2>&1
        [ $? -eq 22 ] && _notrun "Require OFD locks support"
 }
 
 _require_test_lsattr()
 {
-       testio=$(lsattr -d $TEST_DIR 2>&1)
+       local testio=$(lsattr -d $TEST_DIR 2>&1)
        echo $testio | grep -q "Operation not supported" && \
                _notrun "lsattr not supported by test filesystem type: $FSTYP"
        echo $testio | grep -q "Inappropriate ioctl for device" && \
@@ -3353,9 +3459,9 @@ _require_chattr()
 
        touch $TEST_DIR/syscalltest
        chattr "+$attribute" $TEST_DIR/syscalltest > $TEST_DIR/syscalltest.out 2>&1
-       status=$?
+       local ret=$?
        chattr "-$attribute" $TEST_DIR/syscalltest > $TEST_DIR/syscalltest.out 2>&1
-       if [ "$status" -ne 0 ]; then
+       if [ "$ret" -ne 0 ]; then
                _notrun "file system doesn't support chattr +$attribute"
        fi
        cat $TEST_DIR/syscalltest.out >> $seqres.full
@@ -3451,6 +3557,16 @@ _check_dmesg_for()
        _dmesg_since_test_start | egrep -q "$1"
 }
 
+# Default filter for dmesg scanning.
+# Ignore lockdep complaining about its own bugginess when scanning dmesg
+# output, because we shouldn't be failing filesystem tests on account of
+# lockdep.
+_check_dmesg_filter()
+{
+       egrep -v -e "BUG: MAX_LOCKDEP_CHAIN_HLOCKS too low" \
+               -e "BUG: MAX_STACK_TRACE_ENTRIES too low"
+}
+
 # check dmesg log for WARNING/Oops/etc.
 _check_dmesg()
 {
@@ -3462,12 +3578,12 @@ _check_dmesg()
        # default filter is a simple cat command, caller could provide a
        # customized filter and pass the name through the first argument, to
        # filter out intentional WARNINGs or Oopses
-       filter=${1:-cat}
+       local filter=${1:-_check_dmesg_filter}
 
        _dmesg_since_test_start | $filter >$seqres.dmesg
        egrep -q -e "kernel BUG at" \
             -e "WARNING:" \
-            -e "BUG:" \
+            -e "\bBUG:" \
             -e "Oops:" \
             -e "possible recursive locking detected" \
             -e "Internal error" \
@@ -3489,59 +3605,80 @@ _check_dmesg()
 # capture the kmemleak report
 _capture_kmemleak()
 {
-       local _kern_knob="${DEBUGFS_MNT}/kmemleak"
-       local _leak_file="$1"
+       local kern_knob="$DEBUGFS_MNT/kmemleak"
+       local leak_file="$1"
 
        # Tell the kernel to scan for memory leaks.  Apparently the write
        # returns before the scan is complete, so do it twice in the hopes
        # that twice is enough to capture all the leaks.
-       echo "scan" > "${_kern_knob}"
-       cat "${_kern_knob}" > /dev/null
-       echo "scan" > "${_kern_knob}"
-       cat "${_kern_knob}" > "${_leak_file}.tmp"
-       if [ -s "${_leak_file}.tmp" ]; then
-               cat > "${_leak_file}" << ENDL
+       echo "scan" > "$kern_knob"
+       cat "$kern_knob" > /dev/null
+       echo "scan" > "$kern_knob"
+       cat "$kern_knob" > "$leak_file.tmp"
+       if [ -s "$leak_file.tmp" ]; then
+               cat > "$leak_file" << ENDL
 EXPERIMENTAL kmemleak reported some memory leaks!  Due to the way kmemleak
 works, the leak might be from an earlier test, or something totally unrelated.
 ENDL
-               cat "${_leak_file}.tmp" >> "${_leak_file}"
-               rm -rf "${_leak_file}.tmp"
+               cat "$leak_file.tmp" >> "$leak_file"
        fi
-       echo "clear" > "${_kern_knob}"
+       rm -rf "$leak_file.tmp"
+       echo "clear" > "$kern_knob"
 }
 
-# set up kmemleak
-_init_kmemleak()
+# Figure out if the running kernel supports kmemleak; if it does, clear out
+# anything that leaked before we even started testing.  The leak checker only
+# needs to be primed like this once per ./check invocation.
+_detect_kmemleak()
 {
-       local _kern_knob="${DEBUGFS_MNT}/kmemleak"
+       local kern_knob="$DEBUGFS_MNT/kmemleak"
+       KMEMLEAK_CHECK_FILE="/tmp/check_kmemleak"
 
-       if [ ! -w "${_kern_knob}" ]; then
+       # Since kernel v4.19-rc3, the kmemleak knob exists even if kmemleak is
+       # disabled, but returns EBUSY on write. So instead of relying on
+       # existance of writable knob file, we use a test file to indicate that
+       # _check_kmemleak() is enabled only if we actually managed to write to
+       # the knob file.
+       rm -f "$KMEMLEAK_CHECK_FILE"
+
+       if [ ! -w "$kern_knob" ]; then
                return 0
        fi
 
        # Disable the automatic scan so that we can control it completely,
        # then dump all the leaks recorded so far.
-       echo "scan=off" > "${_kern_knob}"
-       _capture_kmemleak /dev/null
+       if echo "scan=off" > "$kern_knob" 2>/dev/null; then
+               _capture_kmemleak /dev/null
+               touch "$KMEMLEAK_CHECK_FILE"
+       fi
 }
 
-# check kmemleak log
+# Kick the kmemleak checker to scan for leaks.  Background leak scan mode is
+# not enabled, so we must call the kernel to ask for a scan and deal with the
+# results appropriately.  This we do after every test completes, whether or not
+# it was successful.
 _check_kmemleak()
 {
-       local _kern_knob="${DEBUGFS_MNT}/kmemleak"
-       local _leak_file="${seqres}.kmemleak"
+       local kern_knob="$DEBUGFS_MNT/kmemleak"
+       local leak_file="$seqres.kmemleak"
 
-       if [ ! -w "${_kern_knob}" ]; then
+       if [ ! -f "$KMEMLEAK_CHECK_FILE" ]; then
+               return 0
+       fi
+
+       # Not enabled, so discard any report of leaks found.
+       if [ "$USE_KMEMLEAK" != "yes" ]; then
+               _capture_kmemleak /dev/null
                return 0
        fi
 
        # Capture and report any leaks
-       _capture_kmemleak "${_leak_file}"
-       if [ -s "${_leak_file}" ]; then
-               _dump_err "_check_kmemleak: something found in kmemleak (see ${_leak_file})"
+       _capture_kmemleak "$leak_file"
+       if [ -s "$leak_file" ]; then
+               _dump_err "_check_kmemleak: something found in kmemleak (see $leak_file)"
                return 1
        else
-               rm -f "${_leak_file}"
+               rm -f "$leak_file"
                return 0
        fi
 }
@@ -3554,10 +3691,6 @@ _disable_dmesg_check()
 
 init_rc()
 {
-       if [ "$iam" == new ]
-       then
-               return
-       fi
        # make some further configuration checks here
        if [ "$TEST_DEV" = ""  ]
        then
@@ -3622,11 +3755,11 @@ init_rc()
 # get real device path name by following link
 _real_dev()
 {
-       local _dev=$1
-       if [ -b "$_dev" ] && [ -L "$_dev" ]; then
-               _dev=`readlink -f "$_dev"`
+       local dev=$1
+       if [ -b "$dev" ] && [ -L "$dev" ]; then
+               dev=`readlink -f "$dev"`
        fi
-       echo $_dev
+       echo $dev
 }
 
 # basename of a device
@@ -3637,12 +3770,12 @@ _short_dev()
 
 _sysfs_dev()
 {
-       local _dev=`_real_dev $1`
-       local _maj=$(stat -c%t $_dev | tr [:lower:] [:upper:])
-       local _min=$(stat -c%T $_dev | tr [:lower:] [:upper:])
-       _maj=$(echo "ibase=16; $_maj" | bc)
-       _min=$(echo "ibase=16; $_min" | bc)
-       echo /sys/dev/block/$_maj:$_min
+       local dev=`_real_dev $1`
+       local maj=$(stat -c%t $dev | tr [:lower:] [:upper:])
+       local min=$(stat -c%T $dev | tr [:lower:] [:upper:])
+       maj=$(echo "ibase=16; $maj" | bc)
+       min=$(echo "ibase=16; $min" | bc)
+       echo /sys/dev/block/$maj:$min
 }
 
 # Get the minimum block size of a file.  Usually this is the
@@ -3680,7 +3813,7 @@ get_page_size()
 run_fsx()
 {
        echo fsx $@
-       args=`echo $@ | sed -e "s/ BSIZE / $bsize /g" -e "s/ PSIZE / $psize /g"`
+       local args=`echo $@ | sed -e "s/ BSIZE / $bsize /g" -e "s/ PSIZE / $psize /g"`
        set -- $here/ltp/fsx $args $FSX_AVOID $TEST_DIR/junk
        echo "$@" >>$seqres.full
        rm -f $TEST_DIR/junk
@@ -3782,6 +3915,183 @@ _require_scratch_feature()
        esac
 }
 
+# Get the maximum size of a file in $TEST_DIR (s_maxbytes).  On ext4 this will
+# be UINT32_MAX * block_size, but other filesystems may allow up to LLONG_MAX.
+_get_max_file_size()
+{
+       local testfile=$TEST_DIR/maxfilesize.$seq
+       local l=0
+       local r=9223372036854775807 # LLONG_MAX
+
+       rm -f $testfile
+       while (( l < r )); do
+               # Use _math() to avoid signed integer overflow.
+               local m=$(_math "($l + $r + 1) / 2")
+               if $XFS_IO_PROG -f -c "truncate $m" $testfile \
+                       |& grep -q 'File too large'
+               then
+                       r=$(( m - 1 ))
+               else
+                       l=$m
+               fi
+       done
+       echo $l
+}
+
+# get MAX_LFS_FILESIZE
+_get_max_lfs_filesize()
+{
+       case "$(getconf LONG_BIT)" in
+       "32")
+               echo $(( ($(getconf PAGE_SIZE) << ($(getconf LONG_BIT) - 1) ) - 1))
+               ;;
+       "64")
+               echo 9223372036854775807
+               ;;
+       *)
+               _fail "sizeof(long) == $(getconf LONG_BIT)?"
+               ;;
+       esac
+}
+
+# The maximum filesystem label length, /not/ including terminating NULL
+_label_get_max()
+{
+       case $FSTYP in
+       xfs)
+               echo 12
+               ;;
+       btrfs)
+               echo 255
+               ;;
+       f2fs)
+               echo 255
+               ;;
+       *)
+               _notrun "$FSTYP does not define maximum label length"
+               ;;
+       esac
+}
+
+# Helper to check above early in a script
+_require_label_get_max()
+{
+       # Just call _label_get_max which will notrun if appropriate
+       dummy=$(_label_get_max)
+}
+
+_dmsetup_remove()
+{
+       $UDEV_SETTLE_PROG >/dev/null 2>&1
+       $DMSETUP_PROG remove "$@" >>$seqres.full 2>&1
+       $DMSETUP_PROG mknodes >/dev/null 2>&1
+}
+
+_dmsetup_create()
+{
+       $DMSETUP_PROG create "$@" >>$seqres.full 2>&1 || return 1
+       $DMSETUP_PROG mknodes >/dev/null 2>&1
+       $UDEV_SETTLE_PROG >/dev/null 2>&1
+}
+
+_require_btime()
+{
+       # Note: filesystems are not required to report btime (creation time)
+       # if the caller doesn't ask for it, so we define STATX_BTIME here and
+       # pass it in to the statx command.
+       export STATX_BTIME=0x800
+       $XFS_IO_PROG -f $TEST_DIR/test_creation_time -c "statx -m $STATX_BTIME -v" \
+               | grep btime >>$seqres.full 2>&1 || \
+               _notrun "inode creation time not supported by this filesystem"
+       rm -f $TEST_DIR/test_creation_time
+}
+
+_require_scratch_btime()
+{
+       _require_scratch
+       _scratch_mkfs > /dev/null 2>&1
+       _scratch_mount
+
+       # Note: filesystems are not required to report btime (creation time)
+       # if the caller doesn't ask for it, so we define STATX_BTIME here and
+       # pass it in to the statx command.
+       export STATX_BTIME=0x800
+       $XFS_IO_PROG -f $SCRATCH_MNT/test_creation_time -c "statx -m $STATX_BTIME -v" \
+               | grep btime >>$seqres.full 2>&1 || \
+               _notrun "inode creation time not supported by this filesystem"
+
+       _scratch_unmount
+}
+
+_require_inode_limits()
+{
+       if [ $(_get_free_inode $TEST_DIR) -eq 0 ]; then
+               _notrun "$FSTYP does not have a fixed number of inodes available"
+       fi
+}
+
+_require_filefrag_options()
+{
+       _require_command "$FILEFRAG_PROG" filefrag
+
+       local options=$1
+       local file="$TEST_DIR/options_testfile"
+
+       echo "XX" > $file
+       ${FILEFRAG_PROG} -$options $file 2>&1 | grep -q "invalid option" && \
+               _notrun "filefrag doesn't support $options option"
+       rm -f $file
+}
+
+_require_fibmap()
+{
+       _require_filefrag_options "B"
+
+       local file="$TEST_DIR/fibmap_testfile"
+
+       echo "XX" > $file
+       ${FILEFRAG_PROG} -B $file 2>&1 | grep -q "FIBMAP[[:space:]]*unsupported"
+       if [ $? -eq 0 ]; then
+               _notrun "FIBMAP not supported by this filesystem"
+       fi
+       rm -f $file
+}
+
+_try_wipe_scratch_devs()
+{
+       test -x "$WIPEFS_PROG" || return 0
+
+       # Do specified filesystem wipe at first
+       case "$FSTYP" in
+       "xfs")
+               _try_wipe_scratch_xfs
+               ;;
+       esac
+
+       # Then do wipefs on all scratch devices
+       for dev in $SCRATCH_DEV_POOL $SCRATCH_DEV $SCRATCH_LOGDEV $SCRATCH_RTDEV; do
+               test -b $dev && $WIPEFS_PROG -a $dev
+       done
+}
+
+# Only run this on xfs if xfs_scrub is available and has the unicode checker
+_check_xfs_scrub_does_unicode() {
+       [ "${FSTYP}" == "xfs" ] || return 1
+
+       local mount="$1"
+       local dev="$2"
+
+       _supports_xfs_scrub "${mount}" "${dev}" || return 1
+
+       # We only care if xfs_scrub has unicode string support...
+       if ! type ldd > /dev/null 2>&1 || \
+          ! ldd "${XFS_SCRUB_PROG}" | grep -q libicui18n; then
+               return 1
+       fi
+
+       return 0
+}
+
 init_rc
 
 ################################################################################