#!/bin/sh
# Copyright (c) 2015-2017 Oracle and/or its affiliates. All Rights Reserved.
# Copyright (c) International Business Machines  Corp., 2005
#
# 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 would 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, see <http://www.gnu.org/licenses/>.
#
# Author: Mitsuru Chinen <mitch@jp.ibm.com>

TST_TOTAL=2

TST_CLEANUP="do_cleanup"

. test_net_stress.sh

# The interval of the mtu change [second]
CHANGE_INTERVAL=${CHANGE_INTERVAL:-5}

# The array of the value which MTU is changed into sequentially
# 552 - net.ipv4.route.min_pmtu
CHANGE_VALUES="784 1142 552 1500 552 1500 552 748 552 1142 1500"
CHANGE6_VALUES="1280 1445 1335 1390 1500 1280 1500 1280 1335 1500"
[ "$TST_IPV6" ] && CHANGE_VALUES=$CHANGE6_VALUES
saved_mtu=

do_cleanup()
{
	netstress_cleanup
	if [ "$saved_mtu" ]; then
		ip li set $(tst_iface) mtu $saved_mtu
		tst_rhost_run -c "ip li set $(tst_iface rhost) mtu $saved_mtu"
	fi
	tst_restore_ipaddr
	tst_restore_ipaddr rhost
	tst_wait_ipv6_dad
}

test_body()
{
	local cmd_type=$1

	case $cmd_type in
	if_cmd) local cmd_name='ifconfig' ;;
	ip_cmd) local cmd_name='ip' ;;
	*) tst_brkm TBROK "Unknown test parameter '$cmd_type'"
	esac

	local iface=$(tst_iface)
	local iface_rmt=$(tst_iface rhost)
	[ "$TST_IPV6" ] && local netmask=64 || local netmask=16

	tst_resm TINFO "'$cmd_name changes MTU $MTU_CHANGE_TIMES times" \
	               "every $CHANGE_INTERVAL seconds"

	mtu_array_len=$(echo $CHANGE_VALUES | wc -w)
	local cnt=0
	while [ $cnt -lt $MTU_CHANGE_TIMES ]; do
		local nth=$(($cnt % $mtu_array_len))
		field=$(($nth + 1))
		cnt=$(($cnt + 1))
		mtu=$(echo $CHANGE_VALUES | cut -d ' ' -f $field)
		[ $cnt -eq $MTU_CHANGE_TIMES ] && mtu="$saved_mtu"

		make_background_tcp_traffic

		tst_resm TINFO "set MTU to $mtu $cnt/$MTU_CHANGE_TIMES"
		local ret=0
		case $cmd_type in
		if_cmd) ifconfig $iface mtu $mtu || ret=1
			tst_rhost_run -c "ifconfig $iface_rmt mtu $mtu"
		;;
		ip_cmd) ip link set $iface mtu $mtu || ret=1
			tst_rhost_run -c "ip link set $iface_rmt mtu $mtu"
		;;
		esac

		if [ $? -ne 0 -o $ret -ne 0 ]; then
			tst_resm TFAIL "Failed to change the mtu at $cnt time"
			return
		fi

		tst_sleep $CHANGE_INTERVAL

		tst_ping $(tst_ipaddr) $(tst_ipaddr rhost) "1 1000 65507"
	done
}

netstress_setup

tst_check_cmds ifconfig

saved_mtu="$(cat /sys/class/net/$(tst_iface)/mtu)"

test_body 'if_cmd'
test_body 'ip_cmd'

tst_exit