1#!/bin/bash
2# SPDX-License-Identifier: GPL-2.0
3
4speeds_arr_get()
5{
6	cmd='/ETHTOOL_LINK_MODE_[^[:space:]]*_BIT[[:space:]]+=[[:space:]]+/ \
7		{sub(/,$/, "") \
8		sub(/ETHTOOL_LINK_MODE_/,"") \
9		sub(/_BIT/,"") \
10		sub(/_Full/,"/Full") \
11		sub(/_Half/,"/Half");\
12		print "["$1"]="$3}'
13
14	awk "${cmd}" /usr/include/linux/ethtool.h
15}
16
17ethtool_set()
18{
19	local cmd="$@"
20	local out=$(ethtool -s $cmd 2>&1 | wc -l)
21
22	check_err $out "error in configuration. $cmd"
23}
24
25dev_speeds_get()
26{
27	local dev=$1; shift
28	local with_mode=$1; shift
29	local adver=$1; shift
30	local speeds_str
31
32	if (($adver)); then
33		mode="Advertised link modes"
34	else
35		mode="Supported link modes"
36	fi
37
38	speeds_str=$(ethtool "$dev" | \
39		# Snip everything before the link modes section.
40		sed -n '/'"$mode"':/,$p' | \
41		# Quit processing the rest at the start of the next section.
42		# When checking, skip the header of this section (hence the 2,).
43		sed -n '2,${/^[\t][^ \t]/q};p' | \
44		# Drop the section header of the current section.
45		cut -d':' -f2)
46
47	local -a speeds_arr=($speeds_str)
48	if [[ $with_mode -eq 0 ]]; then
49		for ((i=0; i<${#speeds_arr[@]}; i++)); do
50			speeds_arr[$i]=${speeds_arr[$i]%base*}
51		done
52	fi
53	echo ${speeds_arr[@]}
54}
55
56common_speeds_get()
57{
58	dev1=$1; shift
59	dev2=$1; shift
60	with_mode=$1; shift
61	adver=$1; shift
62
63	local -a dev1_speeds=($(dev_speeds_get $dev1 $with_mode $adver))
64	local -a dev2_speeds=($(dev_speeds_get $dev2 $with_mode $adver))
65
66	comm -12 \
67		<(printf '%s\n' "${dev1_speeds[@]}" | sort -u) \
68		<(printf '%s\n' "${dev2_speeds[@]}" | sort -u)
69}
70
71different_speeds_get()
72{
73	local dev1=$1; shift
74	local dev2=$1; shift
75	local with_mode=$1; shift
76	local adver=$1; shift
77
78	local -a speeds_arr
79
80	speeds_arr=($(common_speeds_get $dev1 $dev2 $with_mode $adver))
81	if [[ ${#speeds_arr[@]} < 2 ]]; then
82		check_err 1 "cannot check different speeds. There are not enough speeds"
83	fi
84
85	echo ${speeds_arr[0]} ${speeds_arr[1]}
86}
87