xref: /qemu/scripts/rdma-migration-helper.sh (revision c6e1f60cc73c787317316bb2956f9a95a5daee15)
1#!/bin/bash
2
3# Copied from blktests
4get_ipv4_addr()
5{
6    ip -4 -o addr show dev "$1" |
7        sed -n 's/.*[[:blank:]]inet[[:blank:]]*\([^[:blank:]/]*\).*/\1/p' |
8        head -1 | tr -d '\n'
9}
10
11get_ipv6_addr() {
12    ipv6=$(ip -6 -o addr show dev "$1" |
13        sed -n 's/.*[[:blank:]]inet6[[:blank:]]*\([^[:blank:]/]*\).*/\1/p' |
14        head -1 | tr -d '\n')
15
16    [ $? -eq 0 ] || return
17
18    if [[ "$ipv6" =~ ^fe80: ]]; then
19        echo -n "[$ipv6%$1]"
20    else
21        echo -n "[$ipv6]"
22    fi
23}
24
25# existing rdma interfaces
26rdma_interfaces()
27{
28    rdma link show | sed -nE 's/^link .* netdev ([^ ]+).*$/\1 /p' |
29    grep -Ev '^(lo|tun|tap)'
30}
31
32# existing valid ipv4 interfaces
33ipv4_interfaces()
34{
35    ip -o addr show | awk '/inet / {print $2}' | grep -Ev '^(lo|tun|tap)'
36}
37
38ipv6_interfaces()
39{
40    ip -o addr show | awk '/inet6 / {print $2}' | grep -Ev '^(lo|tun|tap)'
41}
42
43rdma_rxe_detect()
44{
45    family=$1
46    for r in $(rdma_interfaces)
47    do
48        "$family"_interfaces | grep -qw $r && get_"$family"_addr $r && return
49    done
50
51    return 1
52}
53
54rdma_rxe_setup()
55{
56    family=$1
57    for i in $("$family"_interfaces)
58    do
59        if rdma_interfaces | grep -qw $i; then
60            echo "$family: Reuse the existing rdma/rxe ${i}_rxe" \
61                 "for $i with $(get_"$family"_addr $i)"
62            return
63        fi
64
65        rdma link add "${i}_rxe" type rxe netdev "$i" && {
66            echo "$family: Setup new rdma/rxe ${i}_rxe" \
67                 "for $i with $(get_"$family"_addr $i)"
68            return
69        }
70    done
71
72    echo "$family: Failed to setup any new rdma/rxe link" >&2
73    return 1
74}
75
76rdma_rxe_clean()
77{
78    modprobe -r rdma_rxe
79}
80
81IP_FAMILY=${IP_FAMILY:-ipv4}
82if [ "$IP_FAMILY" != "ipv6" ] && [ "$IP_FAMILY" != "ipv4" ]; then
83    echo "Unknown ip family '$IP_FAMILY', only ipv4 or ipv6 is supported." >&2
84    exit 1
85fi
86
87operation=${1:-detect}
88
89command -v rdma >/dev/null || {
90    echo "Command 'rdma' is not available, please install it first." >&2
91    exit 1
92}
93
94if [ "$operation" == "setup" ] || [ "$operation" == "clean" ]; then
95    [ "$UID" == 0 ] || {
96        echo "Root privilege is required to setup/clean a rdma/rxe link" >&2
97        exit 1
98    }
99    if [ "$operation" == "setup" ]; then
100        rdma_rxe_setup ipv4
101        rdma_rxe_setup ipv6
102    else
103        rdma_rxe_clean
104    fi
105elif [ "$operation" == "detect" ]; then
106    rdma_rxe_detect "$IP_FAMILY"
107else
108    echo "Usage: $0 [setup | detect | clean]"
109fi
110