xref: /linux/tools/testing/selftests/drivers/net/hw/toeplitz.py (revision 348ea4642f56ab3dc93621c8e3ab0ccd0e5f1782)
1#!/usr/bin/env python3
2# SPDX-License-Identifier: GPL-2.0
3
4"""
5Toeplitz Rx hashing test:
6 - rxhash (the hash value calculation itself);
7 - RSS mapping from rxhash to rx queue;
8 - RPS mapping from rxhash to cpu.
9"""
10
11import glob
12import os
13import socket
14from lib.py import ksft_run, ksft_exit, ksft_pr
15from lib.py import NetDrvEpEnv, EthtoolFamily, NetdevFamily
16from lib.py import cmd, bkg, ctl_file_write, rand_port, defer
17from lib.py import ksft_in
18from lib.py import ksft_variants, KsftNamedVariant, KsftSkipEx, KsftFailEx
19
20# "define" for the ID of the Toeplitz hash function
21ETH_RSS_HASH_TOP = 1
22# Must match RPS_MAX_CPUS in toeplitz.c
23RPS_MAX_CPUS = 16
24# Cap Rx queues so IRQ pinning leaves free CPUs in the RPS_MAX_CPUS range
25QUEUE_CAP = 8
26
27
28def _check_rps_and_rfs_not_configured(cfg):
29    """Verify that RPS is not already configured."""
30
31    for rps_file in glob.glob(f"/sys/class/net/{cfg.ifname}/queues/rx-*/rps_cpus"):
32        with open(rps_file, "r", encoding="utf-8") as fp:
33            val = fp.read().strip()
34            if set(val) - {"0", ","}:
35                raise KsftSkipEx(f"RPS already configured on {rps_file}: {val}")
36
37    rfs_file = "/proc/sys/net/core/rps_sock_flow_entries"
38    with open(rfs_file, "r", encoding="utf-8") as fp:
39        val = fp.read().strip()
40        if val != "0":
41            raise KsftSkipEx(f"RFS already configured {rfs_file}: {val}")
42
43
44def _get_cpu_for_irq(irq):
45    with open(f"/proc/irq/{irq}/smp_affinity_list", "r",
46              encoding="utf-8") as fp:
47        data = fp.read().strip()
48        if "," in data or "-" in data:
49            raise KsftFailEx(f"IRQ{irq} is not mapped to a single core: {data}")
50        return int(data)
51
52
53def _cap_queue_count(cfg):
54    ehdr = {"header": {"dev-index": cfg.ifindex}}
55    chans = cfg.ethnl.channels_get(ehdr)
56
57    config = {}
58    restore = {}
59    for key in ("combined-count", "rx-count"):
60        cur = chans.get(key, 0)
61        if cur > QUEUE_CAP:
62            config[key] = QUEUE_CAP
63            restore[key] = cur
64
65    if not config:
66        return
67
68    cfg.ethnl.channels_set(ehdr | config)
69    defer(cfg.ethnl.channels_set, ehdr | restore)
70
71
72def _get_irq_cpus(cfg):
73    """
74    Read the list of IRQs for the device Rx queues.
75    """
76    queues = cfg.netnl.queue_get({"ifindex": cfg.ifindex}, dump=True)
77    napis = cfg.netnl.napi_get({"ifindex": cfg.ifindex}, dump=True)
78
79    # Remap into ID-based dicts
80    napis = {n["id"]: n for n in napis}
81    queues = {f"{q['type']}{q['id']}": q for q in queues}
82
83    cpus = []
84    for rx in range(9999):
85        name = f"rx{rx}"
86        if name not in queues:
87            break
88        cpus.append(_get_cpu_for_irq(napis[queues[name]["napi-id"]]["irq"]))
89
90    return cpus
91
92
93def _get_unused_rps_cpus(cfg, count=2):
94    """
95    Get CPUs that are not used by Rx queues for RPS.
96    Returns a list of at least 'count' CPU numbers within
97    the RPS_MAX_CPUS supported range.
98    """
99
100    # Get CPUs used by Rx queues
101    rx_cpus = set(_get_irq_cpus(cfg))
102
103    # Get total number of CPUs, capped by RPS_MAX_CPUS
104    num_cpus = min(os.cpu_count(), RPS_MAX_CPUS)
105
106    # Find unused CPUs
107    unused_cpus = [cpu for cpu in range(num_cpus) if cpu not in rx_cpus]
108
109    if len(unused_cpus) < count:
110        raise KsftSkipEx(f"Need at least {count} CPUs in range 0..{num_cpus - 1} not used by Rx queues, found {len(unused_cpus)}")
111
112    return unused_cpus[:count]
113
114
115def _configure_rps(cfg, rps_cpus):
116    """Configure RPS for all Rx queues, restored at the end of the test."""
117
118    mask = 0
119    for cpu in rps_cpus:
120        mask |= (1 << cpu)
121
122    mask = hex(mask)
123
124    # Set RPS bitmap for all rx queues
125    for rps_file in glob.glob(f"/sys/class/net/{cfg.ifname}/queues/rx-*/rps_cpus"):
126        # sysfs expects hex without '0x' prefix, toeplitz.c needs the prefix
127        ctl_file_write(rps_file, mask[2:])
128
129    return mask
130
131
132def _send_traffic(cfg, proto_flag, ipver, port):
133    """Send 20 packets of requested type."""
134
135    # Determine protocol and IP version for socat
136    if proto_flag == "-u":
137        proto = "UDP"
138    else:
139        proto = "TCP"
140
141    baddr = f"[{cfg.addr_v['6']}]" if ipver == "6" else cfg.addr_v["4"]
142
143    # Run socat in a loop to send traffic periodically
144    # Use sh -c with a loop similar to toeplitz_client.sh
145    socat_cmd = f"""
146    for i in `seq 20`; do
147        echo "msg $i" | socat -{ipver} -t 0.1 - {proto}:{baddr}:{port};
148        sleep 0.001;
149    done
150    """
151
152    cmd(socat_cmd, shell=True, host=cfg.remote)
153
154
155def _test_variants():
156    for grp in ["", "rss", "rps"]:
157        for l4 in ["tcp", "udp"]:
158            for l3 in ["4", "6"]:
159                name = f"{l4}_ipv{l3}"
160                if grp:
161                    name = f"{grp}_{name}"
162                yield KsftNamedVariant(name, "-" + l4[0], l3, grp)
163
164
165@ksft_variants(_test_variants())
166def test(cfg, proto_flag, ipver, grp):
167    """Run a single toeplitz test."""
168
169    cfg.require_ipver(ipver)
170
171    # Check that rxhash is enabled
172    ksft_in("receive-hashing: on", cmd(f"ethtool -k {cfg.ifname}").stdout)
173
174    rss = cfg.ethnl.rss_get({"header": {"dev-index": cfg.ifindex}})
175    # Make sure NIC is configured to use Toeplitz hash, and no key xfrm.
176    if rss.get('hfunc') != ETH_RSS_HASH_TOP or rss.get('input-xfrm'):
177        cfg.ethnl.rss_set({"header": {"dev-index": cfg.ifindex},
178                           "hfunc": ETH_RSS_HASH_TOP,
179                           "input-xfrm": {}})
180        defer(cfg.ethnl.rss_set, {"header": {"dev-index": cfg.ifindex},
181                                  "hfunc": rss.get('hfunc'),
182                                  "input-xfrm": rss.get('input-xfrm', {})
183                                  })
184
185    port = rand_port(socket.SOCK_DGRAM)
186
187    toeplitz_path = cfg.test_dir / "toeplitz"
188    rx_cmd = [
189        str(toeplitz_path),
190        "-" + ipver,
191        proto_flag,
192        "-d", str(port),
193        "-i", cfg.ifname,
194        "-T", "4000",
195        "-s",
196        "-v"
197    ]
198
199    if grp:
200        _cap_queue_count(cfg)
201        _check_rps_and_rfs_not_configured(cfg)
202    if grp == "rss":
203        irq_cpus = ",".join([str(x) for x in _get_irq_cpus(cfg)])
204        rx_cmd += ["-C", irq_cpus]
205        ksft_pr(f"RSS using CPUs: {irq_cpus}")
206    elif grp == "rps":
207        # Get CPUs not used by Rx queues and configure them for RPS
208        rps_cpus = _get_unused_rps_cpus(cfg, count=2)
209        rps_mask = _configure_rps(cfg, rps_cpus)
210        rx_cmd += ["-r", rps_mask]
211        ksft_pr(f"RPS using CPUs: {rps_cpus}, mask: {rps_mask}")
212
213    # Run rx in background, it will exit once it has seen enough packets
214    with bkg(" ".join(rx_cmd), ksft_ready=True, exit_wait=True) as rx_proc:
215        while rx_proc.proc.poll() is None:
216            _send_traffic(cfg, proto_flag, ipver, port)
217
218    # Check rx result
219    ksft_pr("Receiver output:")
220    ksft_pr(rx_proc.stdout.strip().replace('\n', '\n# '))
221    if rx_proc.stderr:
222        ksft_pr(rx_proc.stderr.strip().replace('\n', '\n# '))
223
224
225def main() -> None:
226    """Ksft boilerplate main."""
227
228    with NetDrvEpEnv(__file__) as cfg:
229        cfg.ethnl = EthtoolFamily()
230        cfg.netnl = NetdevFamily()
231        ksft_run(cases=[test], args=(cfg,))
232    ksft_exit()
233
234
235if __name__ == "__main__":
236    main()
237