#! /bin/bash
# SPDX-License-Identifier: GPL-2.0
# Copyright (C) 2017 CTERA Networks. All Rights Reserved.
#
# FS QA Test 033
#
# Test nlink accounting of overlay hardlinks.
#
# nlink of overlay inode should account for the union of lower and upper
# hardlinks.
#
. ./common/preamble
_begin_fstest auto quick copyup hardlink

# Import common functions.
. ./common/filter

_require_scratch
_require_scratch_feature index

report_nlink()
{
	when=$1

	[ $DCACHETEMP != cold ] || echo 2 > /proc/sys/vm/drop_caches

	# check nlink with warm dcache after overlay modification
	# List <nlink> <name>
	echo "== $when - $DCACHETEMP dcache =="
	for f in $HARDLINKS; do
		_ls_l $SCRATCH_MNT/$f | awk '{ print $2, $9 }' | _filter_scratch
	done
}

# Create lower hardlinks
create_hardlinks()
{
	mkdir -p $lowerdir
	touch $lowerdir/0
	ln $lowerdir/0 $lowerdir/1
	ln $lowerdir/0 $lowerdir/2
	ln $lowerdir/0 $lowerdir/3
}

test_hardlinks()
{
	HARDLINKS=`seq 0 3`
	report_nlink "all lower"

	# Unlink lower hardlink
	rm $SCRATCH_MNT/0
	HARDLINKS=`seq 1 3`
	report_nlink "unlink lower"

	# Link to lower hardlink
	ln $SCRATCH_MNT/3 $SCRATCH_MNT/4
	HARDLINKS=`seq 1 4`
	report_nlink "link lower"

	# Link to upper hardlink
	ln $SCRATCH_MNT/4 $SCRATCH_MNT/5
	HARDLINKS=`seq 1 5`
	report_nlink "link upper"

	# Rename over lower hardlink
	touch $SCRATCH_MNT/new
	mv $SCRATCH_MNT/new $SCRATCH_MNT/1
	HARDLINKS=`seq 2 5`
	report_nlink "cover lower"

	# Unlink upper hardlink
	rm $SCRATCH_MNT/5
	HARDLINKS=`seq 2 4`
	report_nlink "unlink upper"

	# Rename over upper hardlink
	touch $SCRATCH_MNT/new
	mv $SCRATCH_MNT/new $SCRATCH_MNT/4
	HARDLINKS=`seq 2 3`
	report_nlink "cover upper"

	# Unlink last upper (union still has one lower)
	rm $SCRATCH_MNT/3
	HARDLINKS=2
	report_nlink "unlink last upper"

	# Unlink last lower and drop union nlink to zero (and hopefully not below)
	rm $SCRATCH_MNT/2

	# Verify that orphan index is cleaned when dropping nlink to zero
	# With nfs_export=on index will contain a whiteout index entry, so allow
	# chardev entries in index dir.
	find $workdir/index -mindepth 1 -type c -o -print
}

lowerdir=$OVL_BASE_SCRATCH_MNT/$OVL_LOWER
workdir=$OVL_BASE_SCRATCH_MNT/$OVL_WORK

# Remove all files from previous tests
_scratch_mkfs

# Create lower hardlinks
create_hardlinks

# Enable overlay index feature to prevent breaking hardlinks on copy up
_scratch_mount -o index=on
# Test hardlinks with warm dcache
DCACHETEMP=warm
test_hardlinks

# Reset to lower hardlinks
_scratch_unmount
_scratch_mkfs
create_hardlinks
_scratch_mount -o index=on

# Test hardlinks with cold dcache
DCACHETEMP=cold
test_hardlinks

status=0
exit
