1#!/usr/bin/env python3 2# SPDX-License-Identifier: GPL-2.0 3 4"""A simple test for TSO.""" 5 6import fcntl 7import mmap 8import socket 9import struct 10import termios 11import time 12 13from lib.py import ksft_pr, ksft_run, ksft_exit, KsftSkipEx, KsftXfailEx 14from lib.py import ksft_eq, ksft_ge, ksft_lt 15from lib.py import EthtoolFamily, NetdevFamily, NetDrvEpEnv 16from lib.py import bkg, cmd, defer, ethtool, ip, rand_port, wait_port_listen 17 18 19MAP_HUGETLB = getattr(mmap, "MAP_HUGETLB", 0x40000) 20MSG_ZEROCOPY = getattr(socket, "MSG_ZEROCOPY", 0x4000000) 21SO_ZEROCOPY = getattr(socket, "SO_ZEROCOPY", 60) 22 23GSO_LEGACY_MAX_SIZE = 65536 24 25# Pool of the default hugepage size, the one /proc/meminfo reports on. 26NR_HUGEPAGES = "/proc/sys/vm/nr_hugepages" 27 28 29def default_huge_page_size(): 30 """Return the hugepage size in bytes""" 31 try: 32 with open("/proc/meminfo", encoding="utf-8") as meminfo: 33 for line in meminfo: 34 if line.startswith("Hugepagesize:"): 35 return int(line.split()[1]) * 1024 36 except OSError: 37 pass 38 39 return 2 * 1024 * 1024 40 41 42def hugepages_free(): 43 """Return the number of unused hugepages of the default size.""" 44 try: 45 with open("/proc/meminfo", encoding="utf-8") as meminfo: 46 for line in meminfo: 47 if line.startswith("HugePages_Free:"): 48 return int(line.split()[1]) 49 except OSError: 50 pass 51 return 0 52 53 54def set_nr_hugepages(count): 55 with open(NR_HUGEPAGES, "w", encoding="utf-8") as sysctl: 56 sysctl.write(f"{count}\n") 57 58 59def tx_dropped(ifname): 60 with open(f"/sys/class/net/{ifname}/statistics/tx_dropped", 61 encoding="utf-8") as counter: 62 return int(counter.read()) 63 64 65def setup_hugepage(): 66 """Reserve one hugepage, and put the pool back afterwards.""" 67 if hugepages_free() >= 1: 68 return 69 70 try: 71 with open(NR_HUGEPAGES, encoding="utf-8") as sysctl: 72 old_count = int(sysctl.read()) 73 set_nr_hugepages(old_count + 1) 74 except OSError as error: 75 raise KsftSkipEx(f"Unable to reserve a hugepage: {error}") from error 76 77 defer(set_nr_hugepages, old_count) 78 79 if hugepages_free() < 1: 80 raise KsftSkipEx("Unable to reserve a hugepage") 81 82 83def mmap_large_buffer(): 84 """Allocate a buffer backed by one huge page.""" 85 size = default_huge_page_size() 86 87 setup_hugepage() 88 89 try: 90 return mmap.mmap(-1, size, 91 flags=mmap.MAP_PRIVATE | 92 mmap.MAP_ANONYMOUS | 93 MAP_HUGETLB, 94 prot=mmap.PROT_READ) 95 except OSError as e: 96 raise KsftSkipEx(f"Unable to allocate a {size >> 20}MB hugepage " 97 f"buffer: {e}") from e 98 99 100def sock_wait_drain(sock, max_wait=1000): 101 """Wait for all pending write data on the socket to get ACKed.""" 102 for _ in range(max_wait): 103 one = b'\0' * 4 104 outq = fcntl.ioctl(sock.fileno(), termios.TIOCOUTQ, one) 105 outq = struct.unpack("I", outq)[0] 106 if outq == 0: 107 break 108 time.sleep(0.01) 109 ksft_eq(outq, 0) 110 111 112def tcp_sock_get_retrans(sock): 113 """Get the number of retransmissions for the TCP socket.""" 114 info = sock.getsockopt(socket.SOL_TCP, socket.TCP_INFO, 512) 115 return struct.unpack("I", info[100:104])[0] 116 117 118def setup_big_tcp(cfg): 119 """Lift the GSO ceiling to what the device advertises for TSO.""" 120 if cfg.dev["tso_max_size"] <= GSO_LEGACY_MAX_SIZE: 121 raise KsftSkipEx("Device does not support BIG TCP") 122 123 ip(f"link set dev {cfg.ifname} " 124 f"gso_max_size {cfg.dev['tso_max_size']} " 125 f"gso_ipv4_max_size {cfg.dev['tso_max_size']}") 126 127 defer(ip, f"link set dev {cfg.ifname} " 128 f"gso_max_size {cfg.dev['gso_max_size']} " 129 f"gso_ipv4_max_size {cfg.dev['gso_ipv4_max_size']}") 130 131 132def sock_send_zerocopy(sock): 133 """Send with MSG_ZEROCOPY, return the bytes queued.""" 134 try: 135 sock.setsockopt(socket.SOL_SOCKET, SO_ZEROCOPY, 1) 136 except OSError as e: 137 raise KsftSkipEx(f"SO_ZEROCOPY not supported: {e}") from e 138 139 with mmap_large_buffer() as tx_buf: 140 sock.sendall(tx_buf, MSG_ZEROCOPY) 141 return len(tx_buf) 142 143 144def run_one_stream(cfg, ipver, remote_v4, remote_v6, should_lso): 145 cfg.require_cmd("socat", local=False, remote=True) 146 147 # Set recv window clamp to avoid overwhelming receiver on debug kernels 148 # the 200k clamp should still let use reach > 15Gbps on real HW 149 port = rand_port() 150 listen_opts = f"{port},reuseport,tcp-window-clamp=200000" 151 listen_cmd = f"socat -{ipver} -t 2 -u TCP-LISTEN:{listen_opts} /dev/null,ignoreeof" 152 153 with bkg(listen_cmd, host=cfg.remote, exit_wait=True) as nc: 154 wait_port_listen(port, host=cfg.remote) 155 156 if ipver == "4": 157 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 158 sock.connect((remote_v4, port)) 159 else: 160 sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) 161 sock.connect((remote_v6, port)) 162 163 # Small send to make sure the connection is working. 164 sock.send("ping".encode()) 165 sock_wait_drain(sock) 166 167 # Send 4MB of data, record the LSO packet count. 168 qstat_old = cfg.netnl.qstats_get({"ifindex": cfg.ifindex}, dump=True)[0] 169 buf = b"0" * 1024 * 1024 * 4 170 sock.send(buf) 171 sock_wait_drain(sock) 172 qstat_new = cfg.netnl.qstats_get({"ifindex": cfg.ifindex}, dump=True)[0] 173 174 # Check that at least 90% of the data was sent as LSO packets. 175 # System noise may cause false negatives. Also header overheads 176 # will add up to 5% of extra packes... The check is best effort. 177 total_lso_wire = len(buf) * 0.90 // cfg.dev["mtu"] 178 total_lso_super = len(buf) * 0.90 // cfg.dev["tso_max_size"] 179 180 # Make sure we have order of magnitude more LSO packets than 181 # retransmits, in case TCP retransmitted all the LSO packets. 182 ksft_lt(tcp_sock_get_retrans(sock), total_lso_wire / 16) 183 sock.close() 184 185 if should_lso: 186 if cfg.have_stat_super_count: 187 ksft_ge(qstat_new['tx-hw-gso-packets'] - 188 qstat_old['tx-hw-gso-packets'], 189 total_lso_super, 190 comment="Number of LSO super-packets with LSO enabled") 191 if cfg.have_stat_wire_count: 192 ksft_ge(qstat_new['tx-hw-gso-wire-packets'] - 193 qstat_old['tx-hw-gso-wire-packets'], 194 total_lso_wire, 195 comment="Number of LSO wire-packets with LSO enabled") 196 else: 197 if cfg.have_stat_super_count: 198 ksft_lt(qstat_new['tx-hw-gso-packets'] - 199 qstat_old['tx-hw-gso-packets'], 200 15, comment="Number of LSO super-packets with LSO disabled") 201 if cfg.have_stat_wire_count: 202 ksft_lt(qstat_new['tx-hw-gso-wire-packets'] - 203 qstat_old['tx-hw-gso-wire-packets'], 204 500, comment="Number of LSO wire-packets with LSO disabled") 205 206 207def run_big_tcp_stream(cfg, ipver, remote_v4, remote_v6): 208 """Send with MSG_ZEROCOPY out of a huge page, so the frags exceed 64kB.""" 209 cfg.require_cmd("socat", local=False, remote=True) 210 211 # No clamping, as it would keep the frags under 64kB 212 port = rand_port() 213 listen_opts = f"{port},reuseport" 214 listen_cmd = f"socat -{ipver} -t 2 -u TCP-LISTEN:{listen_opts} /dev/null,ignoreeof" 215 216 with bkg(listen_cmd, host=cfg.remote, exit_wait=True): 217 wait_port_listen(port, host=cfg.remote) 218 219 if ipver == "4": 220 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 221 sock.connect((remote_v4, port)) 222 else: 223 sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) 224 sock.connect((remote_v6, port)) 225 226 # Small send to make sure the connection is working. 227 sock.send("ping".encode()) 228 sock_wait_drain(sock) 229 230 retrans_old = tcp_sock_get_retrans(sock) 231 drops_old = tx_dropped(cfg.ifname) 232 233 sent = sock_send_zerocopy(sock) 234 sock_wait_drain(sock) 235 236 drops = tx_dropped(cfg.ifname) - drops_old 237 retrans = tcp_sock_get_retrans(sock) - retrans_old 238 sock.close() 239 240 ksft_eq(drops, 0, comment="Driver TX drops during BIG TCP send") 241 242 # Same best effort bound as the plain stream. 243 total_lso_wire = sent * 0.90 // cfg.dev["mtu"] 244 ksft_lt(retrans, total_lso_wire / 16) 245 246 247def build_tunnel(cfg, outer_ipver, tun_info): 248 local_v4 = NetDrvEpEnv.nsim_v4_pfx + "1" 249 local_v6 = NetDrvEpEnv.nsim_v6_pfx + "1" 250 remote_v4 = NetDrvEpEnv.nsim_v4_pfx + "2" 251 remote_v6 = NetDrvEpEnv.nsim_v6_pfx + "2" 252 253 local_addr = cfg.addr_v[outer_ipver] 254 remote_addr = cfg.remote_addr_v[outer_ipver] 255 256 tun_type = tun_info[0] 257 tun_arg = tun_info[1] 258 ip(f"link add {tun_type}-ksft type {tun_type} {tun_arg} local {local_addr} remote {remote_addr} dev {cfg.ifname}") 259 defer(ip, f"link del {tun_type}-ksft") 260 ip(f"link set dev {tun_type}-ksft up") 261 ip(f"addr add {local_v4}/24 dev {tun_type}-ksft") 262 ip(f"addr add {local_v6}/64 dev {tun_type}-ksft") 263 264 ip(f"link add {tun_type}-ksft type {tun_type} {tun_arg} local {remote_addr} remote {local_addr} dev {cfg.remote_ifname}", 265 host=cfg.remote) 266 defer(ip, f"link del {tun_type}-ksft", host=cfg.remote) 267 ip(f"link set dev {tun_type}-ksft up", host=cfg.remote) 268 ip(f"addr add {remote_v4}/24 dev {tun_type}-ksft", host=cfg.remote) 269 ip(f"addr add {remote_v6}/64 dev {tun_type}-ksft", host=cfg.remote) 270 271 return remote_v4, remote_v6 272 273 274def restore_wanted_features(cfg): 275 features_cmd = "" 276 for feature in cfg.hw_features: 277 setting = "on" if feature in cfg.wanted_features else "off" 278 features_cmd += f" {feature} {setting}" 279 try: 280 ethtool(f"-K {cfg.ifname} {features_cmd}") 281 except Exception as e: 282 ksft_pr(f"WARNING: failure restoring wanted features: {e}") 283 284 285def test_builder(name, cfg, outer_ipver, feature, tun=None, inner_ipver=None): 286 """Construct specific tests from the common template.""" 287 def f(cfg): 288 cfg.require_ipver(outer_ipver) 289 defer(restore_wanted_features, cfg) 290 291 if not cfg.have_stat_super_count and \ 292 not cfg.have_stat_wire_count: 293 raise KsftSkipEx(f"Device does not support LSO queue stats") 294 295 if feature not in cfg.hw_features: 296 raise KsftSkipEx(f"Device does not support {feature}") 297 298 # Run non-tunnel test cases under the BIG TCP limits too. 299 big_tcp = "big_tcp" in name 300 if big_tcp: 301 setup_big_tcp(cfg) 302 303 ipver = outer_ipver 304 if tun: 305 remote_v4, remote_v6 = build_tunnel(cfg, ipver, tun) 306 ipver = inner_ipver 307 else: 308 remote_v4 = cfg.remote_addr_v["4"] 309 remote_v6 = cfg.remote_addr_v["6"] 310 311 # First test without the feature enabled. 312 ethtool(f"-K {cfg.ifname} {feature} off") 313 run_one_stream(cfg, ipver, remote_v4, remote_v6, should_lso=False) 314 315 if big_tcp: 316 run_big_tcp_stream(cfg, ipver, remote_v4, remote_v6) 317 318 ethtool(f"-K {cfg.ifname} tx-gso-partial off") 319 ethtool(f"-K {cfg.ifname} tx-tcp-mangleid-segmentation off") 320 if feature in cfg.partial_features: 321 ethtool(f"-K {cfg.ifname} tx-gso-partial on") 322 if ipver == "4": 323 ksft_pr("Testing with mangleid enabled") 324 ethtool(f"-K {cfg.ifname} tx-tcp-mangleid-segmentation on") 325 326 # Full feature enabled. 327 ethtool(f"-K {cfg.ifname} {feature} on") 328 run_one_stream(cfg, ipver, remote_v4, remote_v6, should_lso=True) 329 330 if big_tcp: 331 run_big_tcp_stream(cfg, ipver, remote_v4, remote_v6) 332 333 f.__name__ = name + ((outer_ipver + "_") if tun else "") + "ipv" + inner_ipver 334 return f 335 336 337def query_nic_features(cfg) -> None: 338 """Query and cache the NIC features.""" 339 cfg.have_stat_super_count = False 340 cfg.have_stat_wire_count = False 341 342 features = cfg.ethnl.features_get({"header": {"dev-index": cfg.ifindex}}) 343 344 cfg.wanted_features = set() 345 for f in features["wanted"]["bits"]["bit"]: 346 cfg.wanted_features.add(f["name"]) 347 348 cfg.hw_features = set() 349 for f in features["hw"]["bits"]["bit"]: 350 if f.get("value", False): 351 cfg.hw_features.add(f["name"]) 352 353 # Check which features are supported via GSO partial 354 cfg.partial_features = set() 355 if 'tx-gso-partial' in cfg.hw_features: 356 seg_features = {f for f in cfg.hw_features if "segmentation" in f} 357 ethtool(f"-K {cfg.ifname} " + 358 " ".join(f"{f} on" for f in seg_features)) 359 360 ethtool(f"-K {cfg.ifname} tx-gso-partial off") 361 362 no_partial = set() 363 features = cfg.ethnl.features_get({"header": {"dev-index": cfg.ifindex}}) 364 for f in features["active"]["bits"]["bit"]: 365 no_partial.add(f["name"]) 366 cfg.partial_features = seg_features - no_partial 367 ethtool(f"-K {cfg.ifname} tx-gso-partial on") 368 369 restore_wanted_features(cfg) 370 371 stats = cfg.netnl.qstats_get({"ifindex": cfg.ifindex}, dump=True) 372 if stats: 373 if 'tx-hw-gso-packets' in stats[0]: 374 ksft_pr("Detected qstat for LSO super-packets") 375 cfg.have_stat_super_count = True 376 if 'tx-hw-gso-wire-packets' in stats[0]: 377 ksft_pr("Detected qstat for LSO wire-packets") 378 cfg.have_stat_wire_count = True 379 380 381def main() -> None: 382 with NetDrvEpEnv(__file__, nsim_test=False) as cfg: 383 cfg.ethnl = EthtoolFamily() 384 cfg.netnl = NetdevFamily() 385 386 query_nic_features(cfg) 387 388 test_info = ( 389 # name, v4/v6 ethtool_feature tun:(type, args, inner ip versions) 390 ("", "4", "tx-tcp-segmentation", None), 391 ("", "6", "tx-tcp6-segmentation", None), 392 ("big_tcp_", "4", "tx-tcp-segmentation", None), 393 ("big_tcp_", "6", "tx-tcp6-segmentation", None), 394 ("vxlan", "4", "tx-udp_tnl-segmentation", ("vxlan", "id 100 dstport 4789 noudpcsum", ("4", "6"))), 395 ("vxlan", "6", "tx-udp_tnl-segmentation", ("vxlan", "id 100 dstport 4789 udp6zerocsumtx udp6zerocsumrx", ("4", "6"))), 396 ("vxlan_csum", "", "tx-udp_tnl-csum-segmentation", ("vxlan", "id 100 dstport 4789 udpcsum", ("4", "6"))), 397 ("gre", "4", "tx-gre-segmentation", ("gre", "", ("4", "6"))), 398 ("gre", "6", "tx-gre-segmentation", ("ip6gre","", ("4", "6"))), 399 ("ip", "6", "tx-ipxip6-segmentation", ("ip6tnl","mode any", ("4", "6"))), 400 ("ip", "4", "tx-ipxip4-segmentation", ("sit","", ("6", ))), 401 ("ip", "4", "tx-ipxip4-segmentation", ("ipip","", ("4", ))), 402 ) 403 404 cases = [] 405 for outer_ipver in ["4", "6"]: 406 for info in test_info: 407 # Skip if test which only works for a specific IP version 408 if info[1] and outer_ipver != info[1]: 409 continue 410 411 if info[3]: 412 cases += [ 413 test_builder(info[0], cfg, outer_ipver, info[2], info[3], inner_ipver) 414 for inner_ipver in info[3][2] 415 ] 416 else: 417 cases.append(test_builder(info[0], cfg, outer_ipver, info[2], None, outer_ipver)) 418 419 ksft_run(cases=cases, args=(cfg, )) 420 ksft_exit() 421 422 423if __name__ == "__main__": 424 main() 425