#! /bin/bash
# SPDX-License-Identifier: GPL-2.0+
# Copyright (c) 2019, Oracle and/or its affiliates.  All Rights Reserved.
#
# FS QA Test No. 537
#
# Ensure that we can't call fstrim on filesystems mounted norecovery, because
# FSTRIM implementations use free space metadata to drive the discard requests
# and we told the filesystem not to make sure the metadata are up to date.
#
# The following patches fixed the bug on ext4, xfs and btrfs
# ext4: prohibit fstrim in norecovery mode
# xfs: prohibit fstrim in norecovery mode
# Btrfs: do not allow trimming when a fs is mounted with the nologreplay option

. ./common/preamble
_begin_fstest auto quick trim

# Import common functions.
. ./common/filter
. ./common/quota

_require_scratch
_require_fstrim

_scratch_mkfs > $seqres.full 2>&1
_require_metadata_journaling $SCRATCH_DEV

echo "fstrim on regular mount"
_scratch_mount >> $seqres.full 2>&1
$FSTRIM_PROG -v $SCRATCH_MNT >> $seqres.full 2>&1 || \
	_notrun "FSTRIM not supported"
_scratch_unmount

echo "fstrim on ro mount"
_scratch_mount -o ro >> $seqres.full 2>&1
$FSTRIM_PROG -v $SCRATCH_MNT >> $seqres.full 2>&1
_scratch_unmount

# As of kernel commit 9f0902091c332b ("xfs: Do not allow norecovery mount with
# quotacheck"), it is no longer possible to mount with "norecovery" and any
# quota mount option if the quota mount options would require a metadata update
# such as quotacheck.  For a pre-metadir XFS filesystem with a realtime volume
# and quota-enabling options, the first two mount attempts will have succeeded
# but with quotas disabled.  The mount option parsing for this next mount
# attempt will see the same quota-enabling options and a lack of qflags in the
# ondisk metadata and reject the mount because it thinks that will require
# quotacheck.  Edit out the quota mount options for this specific
# configuration.
if [ "$FSTYP" = "xfs" ]; then
	if [ "$USE_EXTERNAL" = "yes" ] && [ -n "$SCRATCH_RTDEV" ]; then
		_qmount_option ""
	fi
fi

echo "fstrim on ro mount with no log replay"
norecovery="norecovery"
_scratch_mount -o ro,$norecovery >> $seqres.full 2>&1
$FSTRIM_PROG -v $SCRATCH_MNT >> $seqres.full 2>&1 && \
	echo "fstrim with unrecovered metadata just ate your filesystem"
_scratch_unmount

# success, all done
status=0
exit
