#! /bin/bash
# SPDX-License-Identifier: GPL-2.0
# Copyright (c) 2024-2026 Oracle.  All Rights Reserved.
#
# FS QA Test No. 654
#
# Make sure that healthmon handles module refcount correctly.
#
. ./common/preamble
_begin_fstest auto selfhealing quick

. ./common/filter
. ./common/module

_cleanup()
{
	test -n "$healer_pid" && kill $healer_pid &>/dev/null
	wait
	cd /
	rm -r -f $tmp.*
}

_require_test
_require_xfs_io_command healthmon
_require_module_refcount xfs

# Capture mod refcount without the test fs mounted
_test_unmount
init_refcount="$(_module_refcount xfs)"

# Capture mod refcount with the test fs mounted
_test_mount
nomon_mount_refcount="$(_module_refcount xfs)"

# Capture mod refcount with test fs mounted and the healthmon fd open.
# Pause the xfs_io process so that it doesn't actually respond to events.
$XFS_IO_PROG -c 'healthmon -c -v' $TEST_DIR >> $seqres.full &
healer_pid=$!
sleep 0.5
kill -STOP $healer_pid
mon_mount_refcount="$(_module_refcount xfs)"

# Capture mod refcount with only the healthmon fd open.
_test_unmount
mon_nomount_refcount="$(_module_refcount xfs)"

# Capture mod refcount after continuing healthmon (which should exit due to the
# unmount) and killing it.
kill -CONT $healer_pid
kill $healer_pid
wait
unset healer_pid
nomon_nomount_refcount="$(_module_refcount xfs)"

_within_tolerance "mount refcount" "$nomon_mount_refcount" "$((init_refcount + 1))" 0 -v
_within_tolerance "mount + healthmon refcount" "$mon_mount_refcount" "$((init_refcount + 2))" 0 -v
_within_tolerance "healthmon refcount" "$mon_nomount_refcount" "$((init_refcount + 1))" 0 -v
_within_tolerance "end refcount" "$nomon_nomount_refcount" "$init_refcount" 0 -v

_exit 0
