1#!/bin/bash
2# SPDX-License-Identifier: GPL-2.0
3# Copyright(c) 2020 Intel Corporation.
4
5ksft_pass=0
6ksft_fail=1
7ksft_xfail=2
8ksft_xpass=3
9ksft_skip=4
10
11GREEN='\033[0;92m'
12YELLOW='\033[0;93m'
13RED='\033[0;31m'
14NC='\033[0m'
15STACK_LIM=131072
16SPECFILE=veth.spec
17
18validate_root_exec()
19{
20	msg="skip all tests:"
21	if [ $UID != 0 ]; then
22		echo $msg must be run as root >&2
23		test_exit $ksft_fail 2
24	else
25		return $ksft_pass
26	fi
27}
28
29validate_veth_support()
30{
31	msg="skip all tests:"
32	if [ $(ip link add $1 type veth 2>/dev/null; echo $?;) != 0 ]; then
33		echo $msg veth kernel support not available >&2
34		test_exit $ksft_skip 1
35	else
36		ip link del $1
37		return $ksft_pass
38	fi
39}
40
41validate_veth_spec_file()
42{
43	if [ ! -f ${SPECFILE} ]; then
44		test_exit $ksft_skip 1
45	fi
46}
47
48test_status()
49{
50	statusval=$1
51	if [ -n "${colorconsole+set}" ]; then
52		if [ $statusval -eq 2 ]; then
53			echo -e "${YELLOW}$2${NC}: [ ${RED}FAIL${NC} ]"
54		elif [ $statusval -eq 1 ]; then
55			echo -e "${YELLOW}$2${NC}: [ ${RED}SKIPPED${NC} ]"
56		elif [ $statusval -eq 0 ]; then
57			echo -e "${YELLOW}$2${NC}: [ ${GREEN}PASS${NC} ]"
58		fi
59	else
60		if [ $statusval -eq 2 ]; then
61			echo -e "$2: [ FAIL ]"
62		elif [ $statusval -eq 1 ]; then
63			echo -e "$2: [ SKIPPED ]"
64		elif [ $statusval -eq 0 ]; then
65			echo -e "$2: [ PASS ]"
66		fi
67	fi
68}
69
70test_exit()
71{
72	retval=$1
73	if [ $2 -ne 0 ]; then
74		test_status $2 $(basename $0)
75	fi
76	exit $retval
77}
78
79clear_configs()
80{
81	if [ $(ip netns show | grep $3 &>/dev/null; echo $?;) == 0 ]; then
82		[ $(ip netns exec $3 ip link show $2 &>/dev/null; echo $?;) == 0 ] &&
83			{ echo "removing link $1:$2"; ip netns exec $3 ip link del $2; }
84		echo "removing ns $3"
85		ip netns del $3
86	fi
87	#Once we delete a veth pair node, the entire veth pair is removed,
88	#this is just to be cautious just incase the NS does not exist then
89	#veth node inside NS won't get removed so we explicitly remove it
90	[ $(ip link show $1 &>/dev/null; echo $?;) == 0 ] &&
91		{ echo "removing link $1"; ip link del $1; }
92	if [ -f ${SPECFILE} ]; then
93		echo "removing spec file:" ${SPECFILE}
94		rm -f ${SPECFILE}
95	fi
96}
97
98cleanup_exit()
99{
100	echo "cleaning up..."
101	clear_configs $1 $2 $3
102}
103
104validate_ip_utility()
105{
106	[ ! $(type -P ip) ] && { echo "'ip' not found. Skipping tests."; test_exit $ksft_skip 1; }
107}
108
109vethXDPgeneric()
110{
111	ip link set dev $1 xdpdrv off
112	ip netns exec $3 ip link set dev $2 xdpdrv off
113}
114
115vethXDPnative()
116{
117	ip link set dev $1 xdpgeneric off
118	ip netns exec $3 ip link set dev $2 xdpgeneric off
119}
120