1#!/usr/bin/env python3
2# SPDX-License-Identifier: GPL-2.0
3
4import multiprocessing
5import socket
6from lib.py import ksft_run, ksft_exit, ksft_eq, ksft_ge, cmd, fd_read_timeout
7from lib.py import NetDrvEpEnv
8from lib.py import EthtoolFamily, NetdevFamily
9from lib.py import KsftSkipEx, KsftFailEx
10from lib.py import rand_port
11
12
13def traffic(cfg, local_port, remote_port, ipver):
14    af_inet = socket.AF_INET if ipver == "4" else socket.AF_INET6
15    sock = socket.socket(af_inet, socket.SOCK_DGRAM)
16    sock.bind(("", local_port))
17    sock.connect((cfg.remote_addr_v[ipver], remote_port))
18    tgt = f"{ipver}:[{cfg.addr_v[ipver]}]:{local_port},sourceport={remote_port}"
19    cmd("echo a | socat - UDP" + tgt, host=cfg.remote)
20    fd_read_timeout(sock.fileno(), 5)
21    return sock.getsockopt(socket.SOL_SOCKET, socket.SO_INCOMING_CPU)
22
23
24def test_rss_input_xfrm(cfg, ipver):
25    """
26    Test symmetric input_xfrm.
27    If symmetric RSS hash is configured, send traffic twice, swapping the
28    src/dst UDP ports, and verify that the same queue is receiving the traffic
29    in both cases (IPs are constant).
30    """
31
32    if multiprocessing.cpu_count() < 2:
33        raise KsftSkipEx("Need at least two CPUs to test symmetric RSS hash")
34
35    input_xfrm = cfg.ethnl.rss_get(
36        {'header': {'dev-name': cfg.ifname}}).get('input_xfrm')
37
38    # Check for symmetric xor/or-xor
39    if not input_xfrm or (input_xfrm != 1 and input_xfrm != 2):
40        raise KsftSkipEx("Symmetric RSS hash not requested")
41
42    cpus = set()
43    successful = 0
44    for _ in range(100):
45        try:
46            port1 = rand_port(socket.SOCK_DGRAM)
47            port2 = rand_port(socket.SOCK_DGRAM)
48            cpu1 = traffic(cfg, port1, port2, ipver)
49            cpu2 = traffic(cfg, port2, port1, ipver)
50            cpus.update([cpu1, cpu2])
51            ksft_eq(
52                cpu1, cpu2, comment=f"Received traffic on different cpus with ports ({port1 = }, {port2 = }) while symmetric hash is configured")
53
54            successful += 1
55            if successful == 10:
56                break
57        except:
58            continue
59    else:
60        raise KsftFailEx("Failed to run traffic")
61
62    ksft_ge(len(cpus), 2,
63            comment=f"Received traffic on less than two cpus {cpus = }")
64
65
66def test_rss_input_xfrm_ipv4(cfg):
67    cfg.require_ipver("4")
68    test_rss_input_xfrm(cfg, "4")
69
70
71def test_rss_input_xfrm_ipv6(cfg):
72    cfg.require_ipver("6")
73    test_rss_input_xfrm(cfg, "6")
74
75
76def main() -> None:
77    with NetDrvEpEnv(__file__, nsim_test=False) as cfg:
78        cfg.ethnl = EthtoolFamily()
79        cfg.netdevnl = NetdevFamily()
80
81        ksft_run([test_rss_input_xfrm_ipv4, test_rss_input_xfrm_ipv6],
82                 args=(cfg, ))
83    ksft_exit()
84
85
86if __name__ == "__main__":
87    main()
88