From: Rishikesh Jethwani <rjethwani@purestorage.com>
To: netdev@vger.kernel.org
Cc: Rishikesh Jethwani <rjethwani@purestorage.com>,
Andrew Lunn <andrew+netdev@lunn.ch>,
"David S. Miller" <davem@davemloft.net>,
Eric Dumazet <edumazet@kernel.org>,
Jakub Kicinski <kuba@kernel.org>, Paolo Abeni <pabeni@redhat.com>,
Shuah Khan <shuah@kernel.org>,
John Fastabend <john.fastabend@gmail.com>,
Sabrina Dubroca <sd@queasysnail.net>,
linux-kselftest@vger.kernel.org
Subject: [PATCH net v3 7/9] selftests: net: add TLS offload over bond tests
Date: Fri, 4 Dec 2026 16:53:54 -0700 [thread overview]
Message-ID: <20261204235642.36653-8-rjethwani@purestorage.com> (raw)
In-Reply-To: <20261204235642.36653-1-rjethwani@purestorage.com>
Run the kTLS echo test over a single-slave balance-xor bond with
layer3+4 hashing. First verify that the slave offloads TLS. Then take
the slave down midway through an echo to exercise TX software fallback.
Cover two cases: bring the slave back before the client resumes, or
resume the client with the slave down and wait for a retransmission
timeout before bringing it back. Without the fix, the fallback
encrypts the same data at both the bond and the slave, and the echoed
data differs from what the client sent in both cases.
Skip configurations the test cannot safely restore. On cleanup,
restore the NIC's addresses and verify that its original routes are back
Both bounce cases fail without "tls: device: keep tls_sw_fallback()
from encrypting its own output".
Signed-off-by: Rishikesh Jethwani <rjethwani@purestorage.com>
---
tools/testing/selftests/drivers/net/hw/config | 1 +
.../selftests/drivers/net/hw/tls_hw_offload.c | 57 +-
.../drivers/net/hw/tls_hw_offload.py | 499 +++++++++++++++++-
3 files changed, 543 insertions(+), 14 deletions(-)
diff --git a/tools/testing/selftests/drivers/net/hw/config b/tools/testing/selftests/drivers/net/hw/config
index 081155bf7847..ee658188670a 100644
--- a/tools/testing/selftests/drivers/net/hw/config
+++ b/tools/testing/selftests/drivers/net/hw/config
@@ -1,3 +1,4 @@
+CONFIG_BONDING=y
CONFIG_BPF_SYSCALL=y
CONFIG_FAIL_FUNCTION=y
CONFIG_FAULT_INJECTION=y
diff --git a/tools/testing/selftests/drivers/net/hw/tls_hw_offload.c b/tools/testing/selftests/drivers/net/hw/tls_hw_offload.c
index 5b3887f32b68..9c1c546d36cf 100644
--- a/tools/testing/selftests/drivers/net/hw/tls_hw_offload.c
+++ b/tools/testing/selftests/drivers/net/hw/tls_hw_offload.c
@@ -24,6 +24,8 @@
#include <netdb.h>
#include <linux/tls.h>
+#include "../../../net/lib/ksft.h"
+
#ifndef SOL_TLS
#define SOL_TLS 282
#endif
@@ -82,13 +84,19 @@ static int random_size_max;
*/
static int verbose;
-/* Upper bound on a helper's lifetime, enforced by SIGALRM. The harness
- * waits for both helpers with the default 20s cmd()/bkg() timeout and
- * cannot signal the one on the remote, so each must exit on its own first.
- * A normal run takes a few seconds; the socket timeouts catch most stalls
- * sooner and with a better error.
+/* -P: pause the client halfway until the harness releases it. */
+static int pause_mid;
+
+/* Upper bound on a helper's lifetime, enforced by SIGALRM. On a timeout
+ * the harness can only kill the ssh client of the remote helper, not the
+ * helper itself, so each must exit on its own first. A normal run takes a
+ * few seconds; the socket timeouts catch most stalls sooner and with a
+ * better error. -T raises both, keeping the lifetime above the I/O timeout.
*/
#define HELPER_TIMEOUT_S 15
+#define IO_TIMEOUT_S 8
+static int io_timeout_s = IO_TIMEOUT_S;
+static int helper_timeout_s = HELPER_TIMEOUT_S;
static const char *cipher_name(int cipher)
{
@@ -152,7 +160,7 @@ static void configure_echo_socket(int fd, int payload)
*/
static void set_io_timeouts(int fd)
{
- struct timeval tv = { .tv_sec = 8, .tv_usec = 0 };
+ struct timeval tv = { .tv_sec = io_timeout_s, .tv_usec = 0 };
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
@@ -388,6 +396,13 @@ static int do_client(void)
printf("Sent %zd bytes (iteration %d)\n", n, i);
if (client_recv_echo(csk, buf, echo_buf, n) < 0)
goto out;
+
+ if (pause_mid && i == num_iterations / 2) {
+ printf("Pausing after iteration %d\n", i);
+ ksft_ready();
+ ksft_wait();
+ printf("Resumed\n");
+ }
}
test_result = 0;
@@ -751,6 +766,10 @@ static void print_usage(const char *prog)
printf(" -c <cipher> Cipher: 128 or 256 (default: 128)\n");
printf(" -n <N> Send/echo iterations (default: 100)\n");
printf(" -t <type> Record type test: 21=alert, 22=handshake\n");
+ printf(" -P Pause halfway (client): ksft_ready(), ksft_wait()\n");
+ printf(" -T <sec> Send/recv timeout (default: %d); lifetime bound\n"
+ " becomes 2 * <sec> + 15 (default: %d)\n",
+ IO_TIMEOUT_S, HELPER_TIMEOUT_S);
printf(" -V Verbose: log every iteration\n");
printf(" -h Show this help message\n");
printf("\nExample:\n");
@@ -779,7 +798,6 @@ int main(int argc, char *argv[])
* is not lost in the stdio buffer.
*/
setvbuf(stdout, NULL, _IOLBF, 0);
- alarm(HELPER_TIMEOUT_S);
if (argc < 2 ||
(strcmp(argv[1], "server") && strcmp(argv[1], "client"))) {
@@ -789,7 +807,7 @@ int main(int argc, char *argv[])
is_server = !strcmp(argv[1], "server");
optind = 2; /* skip subcommand */
- while ((opt = getopt(argc, argv, "s:p:b:r:c:v:n:t:V46h")) != -1) {
+ while ((opt = getopt(argc, argv, "s:p:b:r:c:v:n:t:T:PV46h")) != -1) {
switch (opt) {
case 's':
server_ip = optarg;
@@ -797,6 +815,17 @@ int main(int argc, char *argv[])
case 'V':
verbose = 1;
break;
+ case 'P':
+ pause_mid = 1;
+ break;
+ case 'T':
+ io_timeout_s = atoi(optarg);
+ if (io_timeout_s < 1 || io_timeout_s > 120) {
+ printf("ERROR: -T out of range 1..120\n");
+ return 1;
+ }
+ helper_timeout_s = 2 * io_timeout_s + 15;
+ break;
case '4':
if (force_family == AF_INET6) {
printf("ERROR: -4 and -6 are exclusive\n");
@@ -865,6 +894,11 @@ int main(int argc, char *argv[])
return 1;
}
+ if (pause_mid && (test_record_type || num_iterations < 2)) {
+ printf("ERROR: -P needs echo mode and -n >= 2\n");
+ return 1;
+ }
+
if (test_record_type && random_size_max) {
printf("ERROR: -t cannot be combined with -r\n");
return 1;
@@ -879,6 +913,10 @@ int main(int argc, char *argv[])
printf("warning: -r is ignored in server mode\n");
random_size_max = 0;
}
+ if (pause_mid) {
+ printf("warning: -P is ignored in server mode\n");
+ pause_mid = 0;
+ }
} else {
if (!server_ip) {
printf("ERROR: Client requires -s <ip> option\n");
@@ -886,6 +924,9 @@ int main(int argc, char *argv[])
}
}
+ /* After option parsing, so -T applies */
+ alarm(helper_timeout_s);
+
printf("TLS Version: %s\n", version_name(tls_version));
printf("Cipher: %s\n", cipher_name(cipher_type));
printf("Address family: %s\n",
diff --git a/tools/testing/selftests/drivers/net/hw/tls_hw_offload.py b/tools/testing/selftests/drivers/net/hw/tls_hw_offload.py
index e720ce654761..7d90f1c2024a 100755
--- a/tools/testing/selftests/drivers/net/hw/tls_hw_offload.py
+++ b/tools/testing/selftests/drivers/net/hw/tls_hw_offload.py
@@ -3,15 +3,27 @@
"""Test kTLS hardware offload using a C helper binary."""
+import ipaddress
+import json
+import os
+import socket
+import struct
+import sys
+import tempfile
+import time
from collections import defaultdict
from lib.py import (
CmdExitFailure,
+ KsftFailEx,
KsftNamedVariant,
KsftSkipEx,
NetDrvEpEnv,
bkg,
cmd,
+ defer,
+ ip,
+ ksft_disruptive,
ksft_eq,
ksft_exit,
ksft_ge,
@@ -19,9 +31,18 @@ from lib.py import (
ksft_run,
ksft_variants,
rand_port,
+ wait_file,
wait_port_listen,
)
+BOND_IFNAME = "tlsbond0"
+
+# -T for -P cases, long enough for a bounced NIC to retrain.
+PAUSE_IO_TIMEOUT_S = 45
+# bounce_inflight(): outage once the client has sent, and wait for that.
+INFLIGHT_OUTAGE_S = 2
+INFLIGHT_SEND_WAIT_S = 10
+
# `ethtool -S` counters on the DUT NIC, from the minimum set every TLS
# offload driver should report (Documentation/networking/tls-offload.rst,
# "Statistics"). Drivers expose varying subsets: mlx5 has all four, nfp
@@ -198,7 +219,7 @@ def verify_tls_counters(stats_before, stats_after, is_dut, hw_directions=()):
def run_tls_test(cfg, cipher="128", tls_version="1.2",
buffer_size=None, random_max=None, ipver="4",
- record_type=None):
+ record_type=None, pause=None):
"""Run the TLS offload test.
The DUT runs the TLS client and the remote runs the echo server.
@@ -213,6 +234,10 @@ def run_tls_test(cfg, cipher="128", tls_version="1.2",
kTLS because TLS is pairwise, but verify_tls_counters() requires HW
offload only in enabled DUT directions. The peer and the DUT's other
direction may use SW kTLS.
+
+ pause: if set, the client stops halfway, pause(cfg, port) runs, and
+ the client resumes once it returns. pause() may return a bkg()
+ handle for work that outlives it, reaped after the echo.
"""
require_tls_setup(cfg)
@@ -228,8 +253,13 @@ def run_tls_test(cfg, cipher="128", tls_version="1.2",
port = rand_port()
send_size = random_max or buffer_size
+ io_opt = f"-T {PAUSE_IO_TIMEOUT_S}"
+ budget = {"timeout": 2 * PAUSE_IO_TIMEOUT_S + 30} if pause else {}
+
server_parts = [f"{cfg.bin_remote} server -p {port} -c {cipher}",
f"-v {tls_version}", f"-{ipver}"]
+ if pause:
+ server_parts.append(io_opt)
if send_size:
server_parts.append(f"-b {send_size}")
if record_type:
@@ -244,26 +274,48 @@ def run_tls_test(cfg, cipher="128", tls_version="1.2",
client_parts.append(f"-b {buffer_size}")
if record_type:
client_parts.append(f"-t {record_type}")
+ if pause:
+ client_parts += ["-P", io_opt]
client_cmd = " ".join(client_parts)
stats_before_local = read_tls_stats()
stats_before_remote = read_tls_stats(host=cfg.remote)
nic_before = read_nic_stats(cfg)
+ nic_paused = None
# The remote server runs under bkg(), whose stdout pipe is only drained
# once it exits, so the helper keeps its per-connection output small
# (see the note on verbose in tls_hw_offload.c); do not pass -V.
#
- # Both helpers exit on their own within HELPER_TIMEOUT_S (see
+ # Both helpers exit on their own within their SIGALRM lifetime (see
# tls_hw_offload.c), so nothing outlives the variant even on failure.
- with bkg(server_cmd, host=cfg.remote, exit_wait=True):
+ with bkg(server_cmd, host=cfg.remote, exit_wait=True, **budget):
wait_port_listen(port, host=cfg.remote)
- cmd(client_cmd)
+ if pause:
+ # bkg() returns once the client pauses; leaving resumes it.
+ pending = None
+ reap_timeout = INFLIGHT_SEND_WAIT_S + INFLIGHT_OUTAGE_S + 10
+ try:
+ with bkg(client_cmd, ksft_wait=30, **budget):
+ # pause() may take the socket off the NIC.
+ cfg.wait_hw_stats_settle()
+ nic_paused = read_nic_stats(cfg)
+ pending = pause(cfg, port)
+ except BaseException:
+ if pending:
+ pending.process(terminate=True, fail=False,
+ timeout=reap_timeout)
+ raise
+ if pending:
+ pending.process(terminate=False, fail=True,
+ timeout=reap_timeout)
+ else:
+ cmd(client_cmd)
cfg.wait_hw_stats_settle()
stats_after_local = read_tls_stats()
stats_after_remote = read_tls_stats(host=cfg.remote)
- nic_after = read_nic_stats(cfg)
+ nic_after = nic_paused if pause else read_nic_stats(cfg)
verify_tls_counters(stats_before_local, stats_after_local, is_dut=True,
hw_directions=hw_directions)
@@ -305,6 +357,439 @@ def test_tls_offload_record_type(cfg, record_type):
run_tls_test(cfg, record_type=record_type)
+def wait_carrier(ifname, deadline=30):
+ """Wait for carrier, which can take a NIC well over wait_file()'s
+ default 5s after a flap.
+ """
+ wait_file(f"/sys/class/net/{ifname}/carrier",
+ lambda x: x.strip() == "1", deadline=deadline)
+
+
+def wait_reachable(ifname, peer, deadline=30):
+ """Wait until the peer answers through ifname.
+
+ The peer can lag carrier after a flap; fail here rather than with an
+ opaque connect() error in the helper.
+ """
+ family = "-6" if ":" in peer else "-4"
+ end = time.monotonic() + deadline
+ while cmd(f"ping {family} -c1 -W1 -I {ifname} {peer}",
+ fail=False).ret != 0:
+ if time.monotonic() > end:
+ raise KsftFailEx(f"{peer} unreachable through {ifname}")
+ time.sleep(0.5)
+
+
+def save_nic(ifname):
+ """Dump the NIC's global addresses and its routes in all tables.
+
+ Skip the IPv6 local table, which the restored addresses and addrconf
+ recreate: require_restorable() refuses NICs with other routes there,
+ and restore_nic() checks that they came back.
+ """
+ saved = tempfile.TemporaryDirectory()
+ cmd(f"ip addr save dev {ifname} scope global > {saved.name}/addr",
+ shell=True)
+ cmd(f"ip -4 route save dev {ifname} table all > {saved.name}/route4",
+ shell=True)
+ tables = {r.get("table", "main") for r in
+ ip(f"-6 route show dev {ifname} table all", json=True)}
+ for table in sorted(tables - {"local"}):
+ cmd(f"ip -6 route save dev {ifname} table {table} "
+ f"> {saved.name}/route6-{table}", shell=True)
+ return saved
+
+
+# Route attributes that change on their own: flags follow the carrier
+# (linkdown), and expires counts down.
+ROUTE_VOLATILE = ("flags", "expires")
+
+
+def route_keys(ifname):
+ """The NIC's routes as save_nic() dumps them, for comparison."""
+ keys = set()
+ for family in ("-4", "-6"):
+ for r in ip(f"{family} route show dev {ifname} table all",
+ json=True):
+ if family == "-6" and r.get("table") == "local":
+ continue
+ attrs = {k: v for k, v in r.items() if k not in ROUTE_VOLATILE}
+ keys.add((family, json.dumps(attrs, sort_keys=True)))
+ return keys
+
+
+def local6_routes(ifname):
+ """The NIC's IPv6 local table routes, with the attributes that identify
+ them: all but empty flags. Unlike in route_keys(), an expiry or a flag
+ counts: addrconf's routes have neither, so such a route would not come
+ back as it was. -d, as iproute2 omits "proto boot" otherwise.
+ """
+ return [{k: v for k, v in r.items() if k != "flags" or v}
+ for r in ip(f"-d -6 route show dev {ifname} table local",
+ json=True)]
+
+
+def local6_keys(ifname):
+ """local6_routes() in comparable form."""
+ return {json.dumps(r, sort_keys=True) for r in local6_routes(ifname)}
+
+
+def wait_local6(ifname, local6, deadline=10):
+ """Fail unless the IPv6 local routes saved by setup_bond() come back.
+
+ addrconf adds an address's route only once its DAD completes.
+ """
+ end = time.monotonic() + deadline
+ while True:
+ missing = local6 - local6_keys(ifname)
+ if not missing:
+ return
+ if time.monotonic() > end:
+ raise KsftFailEx(f"{len(missing)} IPv6 local routes of {ifname} "
+ f"missing after restore: "
+ + "; ".join(sorted(missing)))
+ time.sleep(0.5)
+
+
+def check_routes(ifname, routes, when):
+ """Fail if any of the routes saved by setup_bond() is missing."""
+ missing = routes - route_keys(ifname)
+ if missing:
+ link = ip(f"link show dev {ifname}", json=True)[0]
+ raise KsftFailEx(f"{len(missing)} routes of {ifname} missing "
+ f"{when} (flags {link['flags']}, operstate "
+ f"{link['operstate']}): "
+ + "; ".join(f"{family} {attrs}"
+ for family, attrs in sorted(missing)))
+
+
+def count_routes(ifname):
+ """Number of IPv4 and IPv6 routes on ifname, in all tables."""
+ return sum(len(ip(f"{family} route show dev {ifname} table all",
+ json=True))
+ for family in ("-4", "-6"))
+
+
+def restore_routes(ifname, dumps):
+ """Replay route dumps until all of them apply.
+
+ "ip route restore" stops at the first failing route, e.g. one whose
+ gateway's route comes later, so replay while each round adds routes.
+ """
+ routes = count_routes(ifname)
+ while True:
+ failed = [dump for dump in dumps
+ if cmd(f"ip route restore < {dump}", shell=True,
+ fail=False).ret]
+ if not failed:
+ return
+ prev, routes = routes, count_routes(ifname)
+ if routes == prev:
+ raise KsftFailEx(f"Could not restore the routes of {ifname} "
+ f"from {failed}")
+
+
+def restore_nic(cfg, saved, routes, local6):
+ """Bring the NIC back up as a standalone link with its configuration.
+
+ Check the routes after the replay and again after carrier, to tell a
+ failed replay from routes the kernel removed later, and the IPv6
+ local routes, which addrconf recreates, once there is carrier.
+ """
+ try:
+ ip(f"link set dev {cfg.ifname} up")
+ cmd(f"ip addr restore < {saved.name}/addr", shell=True)
+ restore_routes(cfg.ifname,
+ [f"{saved.name}/{dump}"
+ for dump in sorted(os.listdir(saved.name))
+ if dump.startswith("route")])
+ finally:
+ saved.cleanup()
+ check_routes(cfg.ifname, routes, "after the replay")
+ # Best effort: the next case waits for carrier itself.
+ try:
+ wait_carrier(cfg.ifname, deadline=10)
+ except TimeoutError:
+ ksft_pr(f"NOTE: {cfg.ifname} still without carrier, "
+ f"leaving it to the next case to wait for, and not "
+ f"checking its IPv6 local routes, which need DAD")
+ else:
+ wait_local6(cfg.ifname, local6)
+ check_routes(cfg.ifname, routes, "after waiting for carrier")
+
+
+def eui64_link_local(mac):
+ """The link-local address addrconf derives from mac (addr_gen_mode 0)."""
+ b = bytes.fromhex(mac.replace(":", ""))
+ iid = bytes([b[0] ^ 2]) + b[1:3] + b"\xff\xfe" + b[3:6]
+ return ipaddress.IPv6Address(b"\xfe\x80" + bytes(6) + iid)
+
+
+def normalize_local6(route):
+ """route with its destination as an IPv6 network, so that a host
+ address printed without /128 compares equal. Anything else, such as
+ "default", is left as printed.
+ """
+ try:
+ dst = str(ipaddress.IPv6Network(route["dst"]))
+ except ValueError:
+ return route
+ return {**route, "dst": dst}
+
+
+def require_ipv6_recreated(ifname):
+ """Skip unless the NIC's IPv6 addresses and local routes come back.
+
+ Taking the NIC down removes its IPv6 addresses and its IPv6 local
+ table, which save_nic() leaves out. Only the global addresses are
+ restored; addrconf adds the EUI-64 link-local address again in
+ addr_gen_mode 0, as the MAC is unchanged. Of the local table, allow
+ only the routes those recreate, as wait_local6() expects them back,
+ compared whole: any other route, or one of those with an attribute
+ addrconf does not set (another metric, a metrics entry, ...), would
+ be lost, so skip. This includes anycast routes and NICs without IPv6
+ addresses, whose local table can still hold routes.
+ """
+ link = ip(f"addr show dev {ifname}", json=True)[0]
+ v6 = [a for a in link["addr_info"] if a["family"] == "inet6"]
+ auto_ll = None
+ mode = f"/proc/sys/net/ipv6/conf/{ifname}/addr_gen_mode"
+ if os.path.exists(mode):
+ with open(mode, encoding="ascii") as f:
+ if f.read().strip() == "0":
+ auto_ll = eui64_link_local(link["address"])
+ kept = set()
+ for a in v6:
+ addr = ipaddress.IPv6Address(a["local"])
+ if a.get("scope") != "global" and addr != auto_ll:
+ raise KsftSkipEx(f"IPv6 address {addr} on {ifname} would be "
+ f"lost: taking {ifname} down removes it, and "
+ f"only global addresses are restored")
+ kept.add(addr)
+ # The routes addrconf adds, as local6_routes() shows them.
+ common = {"protocol": "kernel", "scope": "global", "pref": "medium"}
+ allowed = [{**common, "type": "local", "dst": f"{addr}/128",
+ "metric": 0} for addr in kept]
+ allowed.append({**common, "type": "multicast", "dst": "ff00::/8",
+ "metric": 256})
+ for r in local6_routes(ifname):
+ if normalize_local6(r) in allowed:
+ continue
+ raise KsftSkipEx(f"IPv6 local table route of {ifname} would not "
+ f"come back after taking {ifname} down: "
+ f"{json.dumps(r, sort_keys=True)}")
+
+
+def require_restorable(ifname, addrs):
+ """Skip if moving the NIC into the bond would lose state that
+ restore_nic() does not put back.
+
+ Flushing the addresses deletes IPv4 routes, and strips the source of
+ IPv6 routes, that prefer one of them as source, also through other
+ devices. Taking the NIC down deletes multipath routes through it,
+ which save_nic()'s per-device dumps miss, flushes its permanent and
+ proxy neighbour entries, and removes its IPv6 addresses (see
+ require_ipv6_recreated()).
+ """
+ locals_ = {a["local"] for a in addrs}
+ for family in ("-4", "-6"):
+ # Unfiltered: "dev" filtering can leave out multipath routes.
+ for r in ip(f"{family} route show table all", json=True):
+ hops = [h.get("dev") for h in r.get("nexthops", [])]
+ if ifname in hops:
+ raise KsftSkipEx(f"Multipath route {r['dst']} has a "
+ f"nexthop through {ifname}, which taking "
+ f"it down would delete")
+ # A multipath route has no "dev".
+ if r.get("prefsrc") in locals_ and r.get("dev") != ifname:
+ raise KsftSkipEx(f"Route {r['dst']} via "
+ f"{r.get('dev', 'multipath')} prefers "
+ f"{r['prefsrc']} as source, which moving "
+ f"{ifname}'s addresses would remove")
+ require_ipv6_recreated(ifname)
+ if ip(f"neigh show dev {ifname} nud permanent", json=True) or \
+ ip(f"neigh show proxy dev {ifname}", json=True):
+ raise KsftSkipEx(f"{ifname} has permanent or proxy neighbour "
+ f"entries, which taking it down would delete")
+
+
+def require_connected_peers(cfg, addrs):
+ """Skip unless every peer is on-link through a prefix of addrs.
+
+ Only the addresses move to the bond, bringing their prefix routes
+ with them: a peer reached through a gateway, or through any route
+ other than those, would be unreachable through the bond.
+ """
+ nets = [ipaddress.ip_network(f"{a['local']}/{a['prefixlen']}",
+ strict=False) for a in addrs]
+ for peer in filter(None, cfg.remote_addr_v.values()):
+ family = "-6" if ":" in peer else "-4"
+ route = ip(f"{family} route get {peer}", json=True)[0]
+ if (route.get("dev") != cfg.ifname or "gateway" in route or
+ not any(ipaddress.ip_address(peer) in net for net in nets)):
+ raise KsftSkipEx(f"{peer} is not on-link through a prefix of "
+ f"{cfg.ifname}'s global addresses, so it would "
+ f"be unreachable through {BOND_IFNAME}")
+
+
+def setup_bond(cfg):
+ """Enslave the DUT NIC to a single-slave bond for the rest of the case.
+
+ kTLS offload over a bond needs layer3+4 hashing (bond_sk_get_lower_dev());
+ balance-xor needs no LACP partner. The NIC's global addresses move to
+ the bond and cleanup restores them and its routes.
+ """
+ # Reuse the NIC's MAC so the peer's neighbour entries stay valid.
+ link = ip(f"link show dev {cfg.ifname}", json=True)[0]
+ if "master" in link:
+ raise KsftSkipEx(f"{cfg.ifname} is already enslaved to "
+ f"{link['master']}")
+ if ip(f"nexthop show dev {cfg.ifname}", json=True):
+ raise KsftSkipEx(f"{cfg.ifname} has nexthop objects, which taking "
+ f"it down would delete")
+ mtu, mac = link["mtu"], link["address"]
+ addrs = [a for a in
+ ip(f"addr show dev {cfg.ifname}", json=True)[0]["addr_info"]
+ if a.get("scope") == "global"]
+ if not addrs:
+ raise KsftSkipEx(f"No global address on {cfg.ifname} to move to "
+ f"{BOND_IFNAME}")
+ require_restorable(cfg.ifname, addrs)
+ require_connected_peers(cfg, addrs)
+
+ routes = route_keys(cfg.ifname)
+ local6 = local6_keys(cfg.ifname)
+ saved = save_nic(cfg.ifname)
+ ip(f"link add {BOND_IFNAME} address {mac} mtu {mtu} type bond "
+ "mode balance-xor xmit_hash_policy layer3+4 miimon 100")
+ # defer() runs LIFO: delete the bond (releasing the NIC) first.
+ defer(restore_nic, cfg, saved, routes, local6)
+ defer(ip, f"link del {BOND_IFNAME}")
+
+ # Deleting a primary IPv4 address can take its secondaries with it.
+ ip(f"addr flush dev {cfg.ifname} scope global")
+ ip(f"link set dev {cfg.ifname} down")
+ ip(f"link set dev {cfg.ifname} master {BOND_IFNAME}")
+ ip(f"link set dev {BOND_IFNAME} up")
+ for addr in addrs:
+ nodad = " nodad" if addr["family"] == "inet6" else ""
+ ip(f"addr replace {addr['local']}/{addr['prefixlen']} "
+ f"dev {BOND_IFNAME}{nodad}")
+ wait_bond_ready(cfg)
+
+
+def wait_bond_ready(cfg):
+ """Wait until the bond carries traffic through its slave again.
+
+ The bond's carrier lags the slave's by a miimon round: check both.
+ """
+ wait_carrier(cfg.ifname)
+ wait_carrier(BOND_IFNAME)
+
+ for peer in filter(None, cfg.remote_addr_v.values()):
+ wait_reachable(BOND_IFNAME, peer)
+
+
+@ksft_disruptive
+def test_tls_offload_bond(cfg):
+ """kTLS offload to the slave NIC through a bond, with no bounce."""
+ require_tls_setup(cfg)
+ cfg.require_ipver("4")
+ setup_bond(cfg)
+ run_tls_test(cfg)
+
+
+def bounce_idle(cfg, _port):
+ """Bounce the slave while the socket is idle, then resume the echo."""
+ ip(f"link set dev {cfg.ifname} down")
+ ip(f"link set dev {cfg.ifname} up")
+ wait_bond_ready(cfg)
+
+
+# Background link-up for bounce_inflight(). Reads icsk_retransmits from
+# /proc/net/tcp, as ss needs CONFIG_INET_DIAG for it.
+INFLIGHT_LINK_UP = """
+import subprocess, sys, time
+proc_rem, base, ifname, wait_s, outage_s = sys.argv[1:]
+
+def client_retransmits():
+ with open("/proc/net/tcp") as f:
+ return [int(c[6], 16) for c in (l.split() for l in f.readlines()[1:])
+ if c[2] == proc_rem and c[3] == "01"]
+
+found = []
+# Bring the slave back however polling ends.
+try:
+ end = time.monotonic() + float(wait_s)
+ while time.monotonic() < end:
+ found = client_retransmits()
+ if len(found) == 1 and found[0] > int(base):
+ time.sleep(float(outage_s))
+ break
+ time.sleep(0.1)
+finally:
+ up = subprocess.run(["ip", "link", "set", "dev", ifname, "up"])
+if up.returncode:
+ sys.exit(up.returncode)
+if len(found) != 1 or found[0] <= int(base):
+ sys.exit(f"no client retransmission timeout during the outage "
+ f"(client sockets' retransmits: {found}, was {base})")
+"""
+
+
+def client_proc_rem(cfg, port):
+ """The test client's remote address as /proc/net/tcp prints it."""
+ addr = struct.unpack("=I", socket.inet_aton(cfg.remote_addr_v["4"]))[0]
+ return f"{addr:08X}:{port:04X}"
+
+
+def client_retransmits(cfg, port):
+ """The test client's icsk_retransmits."""
+ rem = client_proc_rem(cfg, port)
+ with open("/proc/net/tcp", encoding="ascii") as f:
+ found = [int(c[6], 16) for c in (l.split() for l in f.readlines()[1:])
+ if c[2] == rem and c[3] == "01"]
+ if len(found) != 1:
+ raise KsftFailEx(f"Expected one client socket to port {port}, "
+ f"found {len(found)}")
+ return found[0]
+
+
+def bounce_inflight(cfg, port):
+ """Send the resumed echo into a bond that has no usable slave.
+
+ The client resumes only after this returns, so the link-up runs in the
+ background, once the client's socket has had a retransmission timeout.
+ Returns it for run_tls_test() to reap; it fails if there was none.
+ """
+ base = client_retransmits(cfg, port)
+ ip(f"link set dev {cfg.ifname} down")
+ return bkg([sys.executable, "-c", INFLIGHT_LINK_UP,
+ client_proc_rem(cfg, port), str(base), cfg.ifname,
+ str(INFLIGHT_SEND_WAIT_S), str(INFLIGHT_OUTAGE_S)],
+ exit_wait=True)
+
+
+@ksft_variants([
+ KsftNamedVariant("idle", bounce_idle),
+ KsftNamedVariant("inflight", bounce_inflight),
+])
+@ksft_disruptive
+def test_tls_offload_bond_bounce(cfg, bounce):
+ """Bounce the bond slave under an open offloaded socket.
+
+ NETDEV_DOWN moves the socket to the TX SW fallback, which then runs
+ at both bond master and slave and must encrypt only once; encrypting
+ twice puts plaintext on the wire and the echo mismatches.
+ """
+ require_tls_setup(cfg)
+ if 'Tx' not in cfg.tls_hw_directions:
+ raise KsftSkipEx("Bond bounce requires DUT TLS TX offload")
+ cfg.require_ipver("4")
+ setup_bond(cfg)
+ run_tls_test(cfg, pause=bounce)
+
+
def main() -> None:
"""Set up the DUT/peer environment and run the offload test suites."""
with NetDrvEpEnv(__file__, nsim_test=False) as cfg:
@@ -312,8 +797,10 @@ def main() -> None:
cfg.bin_remote = None
cfg.tls_skip_reason = None
+ # Flap the NIC last, so a slow retrain cannot fail later cases.
ksft_run([test_tls_offload, test_tls_offload_sizes,
- test_tls_offload_record_type], args=(cfg, ))
+ test_tls_offload_record_type, test_tls_offload_bond,
+ test_tls_offload_bond_bounce], args=(cfg, ))
ksft_exit()
--
2.50.1
next prev parent reply other threads:[~2026-12-04 23:56 UTC|newest]
Thread overview: 10+ messages / expand[flat|nested] mbox.gz Atom feed top
2026-12-04 23:53 [PATCH net v3 0/9] tls: device: don't put offload plaintext on the wire Rishikesh Jethwani
2026-12-04 23:53 ` [PATCH net v3 1/9] net: don't fragment skbs that still need device crypto Rishikesh Jethwani
2026-12-04 23:53 ` [PATCH net v3 2/9] tls: device: keep tls_sw_fallback() from encrypting its own output Rishikesh Jethwani
2026-12-04 23:53 ` [PATCH net v3 3/9] tls: device: don't let the NIC encrypt fallback output again Rishikesh Jethwani
2026-12-04 23:53 ` [PATCH net v3 4/9] tls: device: remove the dead start marker bypass in TX fallback Rishikesh Jethwani
2026-12-04 23:53 ` [PATCH net v3 5/9] selftests: net: py: reap commands that fail to report ready Rishikesh Jethwani
2026-12-04 23:53 ` [PATCH net v3 6/9] selftests: net: py: add a timeout argument to bkg() Rishikesh Jethwani
2026-12-04 23:53 ` Rishikesh Jethwani [this message]
2026-12-04 23:53 ` [PATCH net v3 8/9] selftests: net: test TLS fallback after rerouting to an upper device Rishikesh Jethwani
2026-12-04 23:53 ` [PATCH net v3 9/9] selftests: net: verify that IP refuses to fragment TLS offload data Rishikesh Jethwani
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=20261204235642.36653-8-rjethwani@purestorage.com \
--to=rjethwani@purestorage.com \
--cc=andrew+netdev@lunn.ch \
--cc=davem@davemloft.net \
--cc=edumazet@kernel.org \
--cc=john.fastabend@gmail.com \
--cc=kuba@kernel.org \
--cc=linux-kselftest@vger.kernel.org \
--cc=netdev@vger.kernel.org \
--cc=pabeni@redhat.com \
--cc=sd@queasysnail.net \
--cc=shuah@kernel.org \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox