xref: /linux/tools/testing/selftests/net/setup_loopback.sh (revision 7d1575014a63caeebb13b000ee152ce711580119)
1#!/bin/bash
2# SPDX-License-Identifier: GPL-2.0
3netdev_check_for_carrier() {
4	local -r dev="$1"
5
6	for i in {1..5}; do
7		carrier="$(cat /sys/class/net/${dev}/carrier)"
8		if [[ "${carrier}" -ne 1 ]] ; then
9			echo "carrier not ready yet..." >&2
10			sleep 1
11		else
12			echo "carrier ready" >&2
13			break
14		fi
15	done
16	echo "${carrier}"
17}
18
19# Assumes that there is no existing ipvlan device on the physical device
20setup_loopback_environment() {
21    local dev="$1"
22
23	# Fail hard if cannot turn on loopback mode for current NIC
24	ethtool -K "${dev}" loopback on || exit 1
25	sleep 1
26
27	# Check for the carrier
28	carrier=$(netdev_check_for_carrier ${dev})
29	if [[ "${carrier}" -ne 1 ]] ; then
30		echo "setup_loopback_environment failed"
31		exit 1
32	fi
33}
34
35setup_macvlan_ns(){
36	local -r link_dev="$1"
37	local -r ns_name="$2"
38	local -r ns_dev="$3"
39	local -r ns_mac="$4"
40	local -r addr="$5"
41
42	ip link add link "${link_dev}" dev "${ns_dev}" \
43		address "${ns_mac}" type macvlan
44	exit_code=$?
45	if [[ "${exit_code}" -ne 0 ]]; then
46		echo "setup_macvlan_ns failed"
47		exit $exit_code
48	fi
49
50	[[ -e /var/run/netns/"${ns_name}" ]] || ip netns add "${ns_name}"
51	ip link set dev "${ns_dev}" netns "${ns_name}"
52	ip -netns "${ns_name}" link set dev "${ns_dev}" up
53	if [[ -n "${addr}" ]]; then
54		ip -netns "${ns_name}" addr add dev "${ns_dev}" "${addr}"
55	fi
56
57	sleep 1
58}
59
60cleanup_macvlan_ns(){
61	while (( $# >= 2 )); do
62		ns_name="$1"
63		ns_dev="$2"
64		ip -netns "${ns_name}" link del dev "${ns_dev}"
65		ip netns del "${ns_name}"
66		shift 2
67	done
68}
69
70cleanup_loopback(){
71	local -r dev="$1"
72
73	ethtool -K "${dev}" loopback off
74	sleep 1
75
76	# Check for the carrier
77	carrier=$(netdev_check_for_carrier ${dev})
78	if [[ "${carrier}" -ne 1 ]] ; then
79		echo "setup_loopback_environment failed"
80		exit 1
81	fi
82}
83