#!/bin/bash
#
# Udev script to rename SF netdevice
# SF netdevices that aren't used by HBN renamed to conventional name, eg. enp3s0f0s88

SFNUM=$1
IFINDEX=$2

# Names for special SFs on ECPF0 (function 0)
declare -A SFMAP=(
    [2]="p0_sf"
    [3]="p1_sf"
    [1]="pf0dpu0_sf"
    [1513]="pf0dpu1_sf"
    [1514]="pf0hpf_sf"
    [1515]="pf1hpf_sf"
)

# SF numbers 1001 to 1001+126 on ECPF0 (function 0) are mapped to ECPF0 VFs and follow pattern pf0vfx_sf
start=1001
end=$((start+126))
for i in $(seq ${start} ${end});  do
	vf_idx=$((i-${start}))
	SFMAP[$i]="pf0vf${vf_idx}_sf"
done

# SF numbers 1257 to 1257+126 on ECPF0 (function 0) are mapped to ECPF1 VFs and follow pattern pf1vfx_sf
start=1257
end=$((start+126))
for i in $(seq ${start} ${end});  do
	vf_idx=$((i-${start}))
	SFMAP[$i]="pf1vf${vf_idx}_sf"
done


for sf_ndev in `ls /sys/class/net/`; do
	_ifindex=`cat /sys/class/net/$sf_ndev/ifindex | head -1 2>/dev/null`
	if [ "$_ifindex" != "$IFINDEX" ]; then continue; fi

	_sfnum=`cat /sys/class/net/$sf_ndev/device/sfnum | head -1 2>/dev/null`
	if [ "$_sfnum" != "$SFNUM" ];then continue; fi

	devpath=`udevadm info /sys/class/net/$sf_ndev | grep "DEVPATH="`
	pcipath=`echo $devpath | awk -F "/mlx5_core.sf" '{print $1}'`
	array=($(echo "$pcipath" | sed 's/\// /g'))
	len=${#array[@]}
	# last element in array is pci parent device
	parent_pdev=${array[$len-1]}
	#pdev is : 0000:03:00.0, so extract them by their index
	b=`echo ${parent_pdev:5:2} | sed 's/^0//'`
	d=`echo ${parent_pdev:8:2} | sed 's/^0//'`
	f=${parent_pdev: -1}

	if (( $f == 0 )); then
		sf_name="${SFMAP[${SFNUM}]}"
	elif (( $f != 1 )) ; then
		echo "Unexpected PCI function: got $f, expected 0 or 1" > /dev/kmsg
	fi

	# non-HBN SF netdevice, use conventional name
	[ -z "$sf_name" ] && sf_name="enp${b}s${d}f${f}s${SFNUM}"

	echo "${sf_name}" >> /tmp/sf_devices
	echo "SF_NETDEV_NAME=${sf_name}"
	exit
done
