xref: /linux/tools/testing/selftests/drivers/net/hw/devmem_lib.py (revision 24e4aff8983fe663a85b5b157476f87ae0819e2c)
1# SPDX-License-Identifier: GPL-2.0
2"""Shared helpers for devmem TCP selftests."""
3
4import re
5
6from lib.py import (bkg, cmd, defer, ethtool, rand_port, wait_port_listen,
7                    ksft_eq, KsftSkipEx, NetNSEnter, EthtoolFamily,
8                    NetdevFamily)
9
10
11def require_devmem(cfg):
12    """Probe ncdevmem on cfg.ifname and SKIP the test if devmem isn't supported."""
13    if not hasattr(cfg, "devmem_probed"):
14        probe_command = f"{cfg.bin_local} -f {cfg.ifname}"
15        cfg.devmem_supported = cmd(probe_command, fail=False, shell=True).ret == 0
16        cfg.devmem_probed = True
17
18    if not cfg.devmem_supported:
19        raise KsftSkipEx("Test requires devmem support")
20
21
22def configure_nic(cfg):
23    """Channels, rings, RSS, queue lease for netkit devmem."""
24    if not hasattr(cfg, 'netns'):
25        return
26
27    cfg.require_ipver('6')
28    ethnl = EthtoolFamily()
29
30    channels = ethnl.channels_get({'header': {'dev-index': cfg.ifindex}})
31    channels = channels['combined-count']
32    if channels < 2:
33        raise KsftSkipEx(
34            'Test requires NETIF with at least 2 combined channels'
35        )
36
37    rings = ethnl.rings_get({'header': {'dev-index': cfg.ifindex}})
38    orig_rx_rings = rings['rx']
39    orig_hds_thresh = rings.get('hds-thresh', 0)
40
41    ethnl.rings_set({'header': {'dev-index': cfg.ifindex},
42                     'tcp-data-split': 'enabled',
43                     'hds-thresh': 0,
44                     'rx': min(64, orig_rx_rings)})
45    defer(ethnl.rings_set, {'header': {'dev-index': cfg.ifindex},
46                            'tcp-data-split': 'unknown',
47                            'hds-thresh': orig_hds_thresh,
48                            'rx': orig_rx_rings})
49
50    cfg.src_queue = channels - 1
51    ethtool(f"-X {cfg.ifname} equal {cfg.src_queue}")
52    defer(ethtool, f"-X {cfg.ifname} default")
53
54    if not hasattr(cfg, 'nk_queue'):
55        with NetNSEnter(str(cfg.netns)):
56            netdevnl = NetdevFamily()
57            lease_result = netdevnl.queue_create({
58                "ifindex": cfg.nk_guest_ifindex,
59                "type": "rx",
60                "lease": {
61                    "ifindex": cfg.ifindex,
62                    "queue": {"id": cfg.src_queue, "type": "rx"},
63                    "netns-id": 0,
64                },
65            })
66            cfg.nk_queue = lease_result['id']
67
68
69def set_flow_rule(cfg, port):
70    """Install a flow rule steering to src_queue and return the flow rule ID."""
71    output = ethtool(
72        f"-N {cfg.ifname} flow-type tcp6 dst-port {port}"
73        f" action {cfg.src_queue}"
74    ).stdout
75    return int(re.search(r'ID (\d+)', output).group(1))
76
77
78def ncdevmem_rx(cfg, port, verify=True, fail_on_linear=False, flow_steer=False):
79    """Build the ncdevmem RX listener command."""
80    if hasattr(cfg, 'netns'):
81        flow_rule_id = set_flow_rule(cfg, port)
82        defer(ethtool, f"-N {cfg.ifname} delete {flow_rule_id}")
83
84        ifname = cfg.nk_guest_ifname
85        addr = cfg.nk_guest_ipv6
86        extras = [f"-t {cfg.nk_queue}", "-q 1", "-n"]
87    else:
88        ifname = cfg.ifname
89        addr = cfg.addr
90        extras = []
91        if flow_steer:
92            extras.append(f"-c {cfg.remote_addr}")
93
94    if verify:
95        extras.append("-v 7")
96    if fail_on_linear:
97        extras.append("-L")
98
99    parts = [cfg.bin_local, "-l", f"-f {ifname}", f"-s {addr}",
100             f"-p {port}", *extras]
101    return " ".join(parts)
102
103
104def ncdevmem_tx(cfg, port, chunk_size=0):
105    """Build the ncdevmem TX send command."""
106    if hasattr(cfg, 'netns'):
107        ifname = cfg.nk_guest_ifname
108        addr = cfg.remote_addr_v['6']
109        extras = ["-t 0", "-q 1", "-n"]
110    else:
111        ifname = cfg.ifname
112        addr = cfg.remote_addr
113        extras = []
114
115    if chunk_size:
116        extras.append(f"-z {chunk_size}")
117
118    parts = [cfg.bin_local, f"-f {ifname}", f"-s {addr}",
119             f"-p {port}", *extras]
120    return " ".join(parts)
121
122
123def socat_send(cfg, port, buf_size=0):
124    """Socat command for sending to the devmem listener.
125
126    When buf_size > 0, force one TCP segment per write of exactly that size by
127    setting socat's buffer (-b) and disabling Nagle (TCP_NODELAY).
128    """
129    proto = f"TCP{cfg.addr_ipver}"
130
131    if hasattr(cfg, 'netns'):
132        addr = f"[{cfg.nk_guest_ipv6}]"
133    else:
134        addr = cfg.baddr
135
136    suffix = f",bind={cfg.remote_baddr}:{port}"
137
138    buf = ""
139    if buf_size:
140        buf = f"-b {buf_size}"
141        suffix += ",nodelay"
142
143    return f"socat {buf} -u - {proto}:{addr}:{port}{suffix}"
144
145
146def socat_listen(cfg, port):
147    """Socat listen command for TX tests."""
148    return f"socat -U - TCP{cfg.addr_ipver}-LISTEN:{port}"
149
150
151def setup_test(cfg, bin_local):
152    """Stash the local ncdevmem path on cfg and deploy it to the remote."""
153    cfg.bin_local = bin_local
154    cfg.bin_remote = cfg.remote.deploy(cfg.bin_local)
155
156
157def run_rx(cfg):
158    """Run the devmem RX test."""
159    require_devmem(cfg)
160    configure_nic(cfg)
161    port = rand_port()
162    socat = socat_send(cfg, port)
163    data_pipe = (f"yes $(echo -e \x01\x02\x03\x04\x05\x06) | head -c 1K"
164                 f" | {socat}")
165    netns = getattr(cfg, "netns", None)
166
167    listen_cmd = ncdevmem_rx(cfg, port, flow_steer=not hasattr(cfg, 'netns'))
168    with bkg(listen_cmd, exit_wait=True, ns=netns) as ncdevmem:
169        wait_port_listen(port, proto="tcp", ns=netns)
170        cmd(data_pipe, host=cfg.remote, shell=True)
171    ksft_eq(ncdevmem.ret, 0)
172
173
174def run_tx(cfg):
175    """Run the devmem TX test."""
176    require_devmem(cfg)
177    configure_nic(cfg)
178    netns = getattr(cfg, "netns", None)
179    port = rand_port()
180    tx_cmd = ncdevmem_tx(cfg, port)
181    listen_cmd = socat_listen(cfg, port)
182
183    with bkg(listen_cmd, host=cfg.remote, exit_wait=True) as socat:
184        wait_port_listen(port, host=cfg.remote)
185        cmd(f"bash -c 'echo -e \"hello\\nworld\" | {tx_cmd}'", ns=netns, shell=True)
186    ksft_eq(socat.stdout.strip(), "hello\nworld")
187
188
189def run_tx_chunks(cfg):
190    """Run the devmem TX chunking test."""
191    require_devmem(cfg)
192    configure_nic(cfg)
193    netns = getattr(cfg, "netns", None)
194    port = rand_port()
195    tx_cmd = ncdevmem_tx(cfg, port, chunk_size=3)
196    listen_cmd = socat_listen(cfg, port)
197
198    with bkg(listen_cmd, host=cfg.remote, exit_wait=True) as socat:
199        wait_port_listen(port, host=cfg.remote)
200        cmd(f"bash -c 'echo -e \"hello\\nworld\" | {tx_cmd}'", ns=netns, shell=True)
201    ksft_eq(socat.stdout.strip(), "hello\nworld")
202
203
204def run_rx_hds(cfg):
205    """Run the HDS test by running devmem RX across a segment size sweep."""
206    require_devmem(cfg)
207    configure_nic(cfg)
208    netns = getattr(cfg, "netns", None)
209
210    for size in [1, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192]:
211        port = rand_port()
212
213        listen_cmd = ncdevmem_rx(cfg, port, verify=False,
214                                 fail_on_linear=True)
215        socat = socat_send(cfg, port, buf_size=size)
216
217        with bkg(listen_cmd, exit_wait=True, ns=netns) as ncdevmem:
218            wait_port_listen(port, proto="tcp", ns=netns)
219            cmd(f"dd if=/dev/zero bs={size} count=1 2>/dev/null | "
220                f"{socat}", host=cfg.remote, shell=True)
221        ksft_eq(ncdevmem.ret, 0, f"HDS failed for payload size {size}")
222