AI Trajectory


Trajectory: (Expand/Collapse All)
Seq Timestamp Type Name Duration
0/0 2026/10/21 04:12 flow patch-triage
3m Args:
null

Results:
{
  "EnableConfigs": [
    "TLS",
    "TLS_DEVICE"
  ],
  "FocusSymbols": [
    "tls_set_sw_offload",
    "tls_sw_push_pending_record",
    "tls_process_cmsg"
  ],
  "KMSANReasoning": "The patch modifies `tls_set_sw_offload()` in `net/tls/tls_sw.c` so that `ctx-\u003epush_pending_record` is only set when configuring the TX path (`if (tx)`). Previously, configuring RX offload on a socket that had hardware TX offload would overwrite `ctx-\u003epush_pending_record` with `tls_sw_push_pending_record`. The remainder of the patch adds a self-test and documentation.\n\n`struct tls_context` is allocated via `kzalloc_obj()` in `tls_ctx_create()`, ensuring all fields are zero-initialized from the start. The change merely guards the assignment of a function pointer based on the function argument `tx`. It does not introduce or expose any uninitialized memory reads, uninitialized branching conditions, or information leaks to userspace. Therefore, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false,
  "Reasoning": "The patch modifies net/tls/tls_sw.c in the core networking kTLS subsystem so that ctx-\u003epush_pending_record is only assigned to tls_sw_push_pending_record when configuring TX offload (if (tx)), avoiding overwriting the TX push_pending_record callback when configuring RX. This affects reachable socket configuration and record handling in kTLS, which is exercised through standard TCP setsockopt and sendmsg operations.",
  "WorthFuzzing": true
}

1/1 2026/10/21 04:12 action read-patch-diff
0m Args:
null

Results:
{
  "PatchDiff": "commit 2449cc829c24f2d986b3e924a1bd5f0afa3905ad\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate:   Wed Oct 21 04:12:00 2026 +0000\n\n    syz-cluster: applied patch under review\n\ndiff --git a/MAINTAINERS b/MAINTAINERS\nindex 00b440be0d46c..771cd3161a05f 100644\n--- a/MAINTAINERS\n+++ b/MAINTAINERS\n@@ -19269,6 +19269,8 @@ F:\tDocumentation/networking/tls*\n F:\tinclude/net/tls.h\n F:\tinclude/uapi/linux/tls.h\n F:\tnet/tls/\n+F:\ttools/testing/selftests/drivers/net/hw/tls_hw_offload.c\n+F:\ttools/testing/selftests/drivers/net/hw/tls_hw_offload.py\n F:\ttools/testing/selftests/net/tls.c\n \n NETWORKING [SOCKETS]\ndiff --git a/net/tls/tls_sw.c b/net/tls/tls_sw.c\nindex d1ad31986cf2c..235b868facfa9 100644\n--- a/net/tls/tls_sw.c\n+++ b/net/tls/tls_sw.c\n@@ -2591,7 +2591,8 @@ int tls_set_sw_offload(struct sock *sk, int tx,\n \t\t}\n \t}\n \n-\tctx-\u003epush_pending_record = tls_sw_push_pending_record;\n+\tif (tx)\n+\t\tctx-\u003epush_pending_record = tls_sw_push_pending_record;\n \n \t/* setkey is the last operation that could fail during a\n \t * rekey. if it succeeds, we can start modifying the\ndiff --git a/tools/testing/selftests/drivers/net/README.rst b/tools/testing/selftests/drivers/net/README.rst\nindex c6bed9a985bc7..94c6aeecfe2ff 100644\n--- a/tools/testing/selftests/drivers/net/README.rst\n+++ b/tools/testing/selftests/drivers/net/README.rst\n@@ -188,6 +188,28 @@ The tests have a handful of dependencies. For Fedora / CentOS::\n \n   dnf -y install netsniff-ng python-yaml socat iperf3\n \n+TLS hardware offload\n+~~~~~~~~~~~~~~~~~~~~\n+\n+``hw/tls_hw_offload.py`` tests TLS 1.2 with AES-GCM-128/256 using a C\n+helper on both endpoints. Configure the endpoints using the variables above\n+and enable at least one of ``tls-hw-tx-offload`` or ``tls-hw-rx-offload`` on\n+the DUT. The peer can use software kTLS. The test checks every enabled DUT\n+direction; unexpected software fallback fails. Known AES-GCM-128-only\n+drivers skip the AES-GCM-256 case.\n+\n+The record-type cases require DUT TX offload. They install TLS_RX after\n+TLS_TX, buffer application data with MSG_MORE, then send a handshake or\n+alert record. The peer verifies both record types and payloads. Running\n+with RX offload enabled covers hardware RX setup; running with it disabled\n+also covers software RX setup on a socket with hardware TX offload.\n+\n+Run without other kTLS workloads in either endpoint's network namespace:\n+the tests compare shared TLS MIB and NIC counter snapshots. Build the helper\n+with ``make -C tools/testing/selftests/drivers/net/hw tls_hw_offload`` and\n+run ``tools/testing/selftests/drivers/net/hw/tls_hw_offload.py`` with the\n+endpoint configuration. The harness deploys the helper to the peer.\n+\n Guidance for test authors\n =========================\n \ndiff --git a/tools/testing/selftests/drivers/net/hw/.gitignore b/tools/testing/selftests/drivers/net/hw/.gitignore\nindex 46540468a7753..911a9bfeaf41e 100644\n--- a/tools/testing/selftests/drivers/net/hw/.gitignore\n+++ b/tools/testing/selftests/drivers/net/hw/.gitignore\n@@ -1,4 +1,5 @@\n # SPDX-License-Identifier: GPL-2.0-only\n iou-zcrx\n ncdevmem\n+tls_hw_offload\n toeplitz\ndiff --git a/tools/testing/selftests/drivers/net/hw/Makefile b/tools/testing/selftests/drivers/net/hw/Makefile\nindex 78bb0169350b2..ee412ec930231 100644\n--- a/tools/testing/selftests/drivers/net/hw/Makefile\n+++ b/tools/testing/selftests/drivers/net/hw/Makefile\n@@ -45,6 +45,7 @@ TEST_PROGS = \\\n \trss_drv.py \\\n \trss_flow_label.py \\\n \trss_input_xfrm.py \\\n+\ttls_hw_offload.py \\\n \ttoeplitz.py \\\n \ttso.py \\\n \tuserns_devmem.py \\\n@@ -77,6 +78,7 @@ YNL_GEN_FILES := \\\n # end of YNL_GEN_FILES\n TEST_GEN_FILES += $(YNL_GEN_FILES)\n TEST_GEN_FILES += $(patsubst %.c,%.o,$(wildcard *.bpf.c))\n+TEST_GEN_FILES += tls_hw_offload\n \n include ../../../lib.mk\n \n@@ -90,6 +92,8 @@ include ../../../net/ynl.mk\n \n include ../../../net/bpf.mk\n \n+$(OUTPUT)/tls_hw_offload: CFLAGS += $(KHDR_INCLUDES)\n+\n ifeq ($(HAS_IOURING_ZCRX),y)\n $(OUTPUT)/iou-zcrx: LDLIBS += -luring\n endif\ndiff --git a/tools/testing/selftests/drivers/net/hw/config b/tools/testing/selftests/drivers/net/hw/config\nindex d89a9ba176558..169e608516bd5 100644\n--- a/tools/testing/selftests/drivers/net/hw/config\n+++ b/tools/testing/selftests/drivers/net/hw/config\n@@ -22,6 +22,8 @@ CONFIG_NET_IPIP=y\n CONFIG_NETKIT=y\n CONFIG_NET_SCH_INGRESS=y\n CONFIG_SYNC_FILE=y\n+CONFIG_TLS=y\n+CONFIG_TLS_DEVICE=y\n CONFIG_UDMABUF=y\n CONFIG_USER_NS=y\n CONFIG_VXLAN=y\ndiff --git a/tools/testing/selftests/drivers/net/hw/tls_hw_offload.c b/tools/testing/selftests/drivers/net/hw/tls_hw_offload.c\nnew file mode 100644\nindex 0000000000000..4e9f8a2be8a8f\n--- /dev/null\n+++ b/tools/testing/selftests/drivers/net/hw/tls_hw_offload.c\n@@ -0,0 +1,886 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/*\n+ * TLS Hardware Offload Two-Node Test\n+ *\n+ * Tests kTLS hardware offload between two physical nodes using\n+ * hardcoded keys. Supports TLS 1.2 and AES-GCM-128/256.\n+ *\n+ * Both ends must run this helper: there is no handshake.\n+ */\n+\n+#include \u003cstdio.h\u003e\n+#include \u003cstdlib.h\u003e\n+#include \u003cstring.h\u003e\n+#include \u003cunistd.h\u003e\n+#include \u003cerrno.h\u003e\n+#include \u003climits.h\u003e\n+#include \u003ctime.h\u003e\n+#include \u003csys/time.h\u003e\n+#include \u003csignal.h\u003e\n+#include \u003csys/types.h\u003e\n+#include \u003csys/socket.h\u003e\n+#include \u003cnetinet/in.h\u003e\n+#include \u003cnetinet/tcp.h\u003e\n+#include \u003cnetdb.h\u003e\n+#include \u003clinux/tls.h\u003e\n+\n+#ifndef SOL_TLS\n+#define SOL_TLS 282\n+#endif\n+\n+#define TLS_RECORD_TYPE_HANDSHAKE\t\t22\n+#define TLS_RECORD_TYPE_ALERT\t\t\t21\n+#define TLS_RECORD_TYPE_DATA\t\t\t23\n+\n+#define MIN_BUF_SIZE   16\n+\n+/* Initial key material */\n+static struct tls12_crypto_info_aes_gcm_128 tls_info_key0_128 = {\n+\t.info = {\n+\t\t.version = TLS_1_2_VERSION,\n+\t\t.cipher_type = TLS_CIPHER_AES_GCM_128,\n+\t},\n+\t.iv = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 },\n+\t.key = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,\n+\t\t 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10 },\n+\t.salt = { 0x01, 0x02, 0x03, 0x04 },\n+\t.rec_seq = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },\n+};\n+\n+static struct tls12_crypto_info_aes_gcm_256 tls_info_key0_256 = {\n+\t.info = {\n+\t\t.version = TLS_1_2_VERSION,\n+\t\t.cipher_type = TLS_CIPHER_AES_GCM_256,\n+\t},\n+\t.iv = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 },\n+\t.key = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,\n+\t\t 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,\n+\t\t 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,\n+\t\t 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20 },\n+\t.salt = { 0x01, 0x02, 0x03, 0x04 },\n+\t.rec_seq = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },\n+};\n+\n+static int test_record_type;\n+static int num_iterations = 100;\n+static int cipher_type = TLS_CIPHER_AES_GCM_128;\n+static int tls_version = TLS_1_2_VERSION;\n+static int server_port = 4433;\n+static char *server_ip;\n+/* Address family to force: AF_UNSPEC (any), AF_INET (-4), AF_INET6 (-6). */\n+static int force_family = AF_UNSPEC;\n+\n+static int send_size = 16384;\n+static int random_size_max;\n+/* Per-iteration progress output (-V). Off by default: the\n+ * harness captures stdout in a pipe that is not drained until the helper\n+ * exits, so unbounded per-record chatter (thousands of lines for the large\n+ * echo variants) would fill the pipe, block printf(), stall the echo loop\n+ * and surface as a bogus recv timeout on the peer. With -V off a run prints\n+ * fixed setup/summary lines, comfortably inside a 64 KiB pipe.\n+ */\n+static int verbose;\n+\n+static const char *cipher_name(int cipher)\n+{\n+\tswitch (cipher) {\n+\tcase TLS_CIPHER_AES_GCM_128: return \"AES-GCM-128\";\n+\tcase TLS_CIPHER_AES_GCM_256: return \"AES-GCM-256\";\n+\tdefault: return \"unknown\";\n+\t}\n+}\n+\n+static const char *version_name(int version)\n+{\n+\tswitch (version) {\n+\tcase TLS_1_2_VERSION: return \"TLS 1.2\";\n+\tdefault: return \"unknown\";\n+\t}\n+}\n+\n+static int setup_tls_ulp(int fd)\n+{\n+\tint ret;\n+\n+\tret = setsockopt(fd, IPPROTO_TCP, TCP_ULP, \"tls\", sizeof(\"tls\"));\n+\tif (ret \u003c 0) {\n+\t\tprintf(\"SETUP ERROR: TCP_ULP failed: %s\\n\", strerror(errno));\n+\t\treturn -1;\n+\t}\n+\treturn 0;\n+}\n+\n+/* Echo mode drives both directions from a single thread: the\n+ * client pushes a whole payload with one blocking send() and only reads the\n+ * echo afterwards, while the server blocks in send() mid-echo. If a payload\n+ * exceeds the peer's receive window the two sides deadlock - client stuck in\n+ * send(), server stuck echoing, neither draining the other. Size the socket\n+ * buffers so a full payload always fits in the peer's window (the forward\n+ * send() then completes without needing the peer to read concurrently); the\n+ * send/recv timeouts armed by set_io_timeouts() turn any residual stall into a\n+ * loud EAGAIN instead of a hang.\n+ */\n+static void configure_echo_socket(int fd, int payload)\n+{\n+\tint want = payload;\n+\n+\tif (want \u003c MIN_BUF_SIZE)\n+\t\twant = MIN_BUF_SIZE;\n+\n+\t/* SO_*BUFFORCE bypasses the rmem_max/wmem_max sysctl caps (needs\n+\t * CAP_NET_ADMIN); fall back to the best-effort, cap-limited option\n+\t * when unprivileged - the timeouts below still turn any resulting\n+\t * stall into a loud failure rather than a hang.\n+\t */\n+\tif (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, \u0026want, sizeof(want)) \u003c 0)\n+\t\tsetsockopt(fd, SOL_SOCKET, SO_RCVBUF, \u0026want, sizeof(want));\n+\tif (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, \u0026want, sizeof(want)) \u003c 0)\n+\t\tsetsockopt(fd, SOL_SOCKET, SO_SNDBUF, \u0026want, sizeof(want));\n+}\n+\n+/* Arm send/recv timeouts so any unexpected stall fails loudly with EAGAIN\n+ * instead of hanging until the harness SIGKILLs us.\n+ */\n+static void set_io_timeouts(int fd)\n+{\n+\tstruct timeval tv = { .tv_sec = 8, .tv_usec = 0 };\n+\n+\tsetsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, \u0026tv, sizeof(tv));\n+\tsetsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, \u0026tv, sizeof(tv));\n+}\n+\n+/* Send the whole buffer, looping over short counts. A blocking SOCK_STREAM\n+ * send() may return fewer bytes than requested (e.g. when SO_SNDTIMEO fires\n+ * after partial progress) without setting errno, so a short count is not an\n+ * error - only a negative return is.\n+ */\n+static int send_all(int fd, const char *buf, ssize_t len)\n+{\n+\tssize_t sent = 0;\n+\tssize_t ret;\n+\n+\twhile (sent \u003c len) {\n+\t\tret = send(fd, buf + sent, len - sent, 0);\n+\t\tif (ret \u003c= 0) {\n+\t\t\t/* 0 for a non-empty request would spin forever. */\n+\t\t\tprintf(\"FAIL: send failed: %s\\n\",\n+\t\t\t       ret ? strerror(errno) : \"no progress\");\n+\t\t\treturn -1;\n+\t\t}\n+\t\tsent += ret;\n+\t}\n+\treturn 0;\n+}\n+\n+static int recv_tls_message(int fd, char *buf, size_t buflen, int *record_type,\n+\t\t\t    int flags)\n+{\n+\tchar cmsg_buf[CMSG_SPACE(sizeof(unsigned char))];\n+\tstruct msghdr msg = {0};\n+\tstruct cmsghdr *cmsg;\n+\tstruct iovec iov;\n+\tint ret;\n+\n+\tiov.iov_base = buf;\n+\tiov.iov_len = buflen;\n+\n+\tmsg.msg_iov = \u0026iov;\n+\tmsg.msg_iovlen = 1;\n+\tmsg.msg_control = cmsg_buf;\n+\tmsg.msg_controllen = sizeof(cmsg_buf);\n+\n+\tret = recvmsg(fd, \u0026msg, flags);\n+\tif (ret \u003c= 0)\n+\t\treturn ret;\n+\n+\tcmsg = CMSG_FIRSTHDR(\u0026msg);\n+\tif (cmsg \u0026\u0026 cmsg-\u003ecmsg_level == SOL_TLS \u0026\u0026\n+\t    cmsg-\u003ecmsg_type == TLS_GET_RECORD_TYPE)\n+\t\t*record_type = *((unsigned char *)CMSG_DATA(cmsg));\n+\n+\treturn ret;\n+}\n+\n+static int install_tls_key(int fd, int direction, int cipher)\n+{\n+\tconst char *dir = direction == TLS_TX ? \"TX\" : \"RX\";\n+\tint ret;\n+\n+\tif (verbose)\n+\t\tprintf(\"Installing TLS_%s %s...\\n\", dir, cipher_name(cipher));\n+\n+\tif (cipher == TLS_CIPHER_AES_GCM_256) {\n+\t\tstruct tls12_crypto_info_aes_gcm_256 key;\n+\n+\t\tmemcpy(\u0026key, \u0026tls_info_key0_256, sizeof(key));\n+\t\tkey.info.version = tls_version;\n+\t\tret = setsockopt(fd, SOL_TLS, direction, \u0026key, sizeof(key));\n+\t} else {\n+\t\tstruct tls12_crypto_info_aes_gcm_128 key;\n+\n+\t\tmemcpy(\u0026key, \u0026tls_info_key0_128, sizeof(key));\n+\t\tkey.info.version = tls_version;\n+\t\tret = setsockopt(fd, SOL_TLS, direction, \u0026key, sizeof(key));\n+\t}\n+\n+\tif (ret \u003c 0) {\n+\t\tprintf(\"SETUP ERROR: TLS_%s %s failed: %s\\n\",\n+\t\t       dir, cipher_name(cipher), strerror(errno));\n+\t\treturn -1;\n+\t}\n+\tprintf(\"TLS_%s %s installed\\n\", dir, cipher_name(cipher));\n+\treturn 0;\n+}\n+\n+/* Open a TCP connection to server_ip:server_port, switch to the TLS\n+ * ULP, and install initial TX/RX keys. Works over IPv4 or\n+ * IPv6: getaddrinfo() resolves server_ip (honouring any -4/-6 forced\n+ * family and %zone scope IDs in link-local addresses). Returns the fd on\n+ * success, -1 on error (with the fd already closed).\n+ */\n+static int client_connect_tls(void)\n+{\n+\tstruct addrinfo hints = {0}, *res, *rp;\n+\tchar port_str[16];\n+\tint csk = -1;\n+\tint ret;\n+\n+\thints.ai_family = force_family;\n+\thints.ai_socktype = SOCK_STREAM;\n+\thints.ai_protocol = IPPROTO_TCP;\n+\tsnprintf(port_str, sizeof(port_str), \"%d\", server_port);\n+\n+\tret = getaddrinfo(server_ip, port_str, \u0026hints, \u0026res);\n+\tif (ret) {\n+\t\tprintf(\"SETUP ERROR: getaddrinfo(%s): %s\\n\", server_ip,\n+\t\t       gai_strerror(ret));\n+\t\treturn -1;\n+\t}\n+\n+\tprintf(\"Connecting to %s:%d...\\n\", server_ip, server_port);\n+\tfor (rp = res; rp; rp = rp-\u003eai_next) {\n+\t\tcsk = socket(rp-\u003eai_family, rp-\u003eai_socktype, rp-\u003eai_protocol);\n+\t\tif (csk \u003c 0)\n+\t\t\tcontinue;\n+\t\tif (connect(csk, rp-\u003eai_addr, rp-\u003eai_addrlen) == 0)\n+\t\t\tbreak;\n+\t\tclose(csk);\n+\t\tcsk = -1;\n+\t}\n+\tfreeaddrinfo(res);\n+\n+\tif (csk \u003c 0) {\n+\t\tprintf(\"SETUP ERROR: connect to %s:%d failed: %s\\n\",\n+\t\t       server_ip, server_port, strerror(errno));\n+\t\treturn -1;\n+\t}\n+\tprintf(\"Connected!\\n\");\n+\n+\tif (setup_tls_ulp(csk) \u003c 0)\n+\t\tgoto err;\n+\n+\tif (install_tls_key(csk, TLS_TX, cipher_type) \u003c 0 ||\n+\t    install_tls_key(csk, TLS_RX, cipher_type) \u003c 0)\n+\t\tgoto err;\n+\n+\tset_io_timeouts(csk);\n+\tconfigure_echo_socket(csk, random_size_max \u003e 0 ?\n+\t\t\t\t    random_size_max : send_size);\n+\n+\treturn csk;\n+err:\n+\tclose(csk);\n+\treturn -1;\n+}\n+\n+/* Drain `len` echoed bytes from the server and verify they match the\n+ * payload we just sent.\n+ */\n+static int client_recv_echo(int fd, const char *sent, char *echo_buf,\n+\t\t\t    ssize_t len)\n+{\n+\tssize_t total = 0;\n+\tssize_t n;\n+\n+\twhile (total \u003c len) {\n+\t\tn = recv(fd, echo_buf + total, len - total, 0);\n+\t\tif (n \u003c 0) {\n+\t\t\tprintf(\"FAIL: Echo recv failed: %s\\n\", strerror(errno));\n+\t\t\treturn -1;\n+\t\t}\n+\t\tif (n == 0) {\n+\t\t\tprintf(\"FAIL: Connection closed during echo\\n\");\n+\t\t\treturn -1;\n+\t\t}\n+\t\ttotal += n;\n+\t}\n+\n+\tif (memcmp(sent, echo_buf, len) != 0) {\n+\t\tprintf(\"FAIL: Echo data mismatch!\\n\");\n+\t\treturn -1;\n+\t}\n+\tif (verbose)\n+\t\tprintf(\"Received echo %zd bytes (ok)\\n\", total);\n+\treturn 0;\n+}\n+\n+static int do_client(void)\n+{\n+\tchar *buf = NULL, *echo_buf = NULL;\n+\tint max_size;\n+\tint csk = -1, i = 1;\n+\tint test_result = -1;\n+\tssize_t n, total = 0;\n+\n+\tmax_size = random_size_max \u003e 0 ? random_size_max : send_size;\n+\tif (max_size \u003c MIN_BUF_SIZE)\n+\t\tmax_size = MIN_BUF_SIZE;\n+\tbuf = malloc(max_size);\n+\techo_buf = malloc(max_size);\n+\tif (!buf || !echo_buf) {\n+\t\tprintf(\"SETUP ERROR: failed to allocate buffers\\n\");\n+\t\tgoto out;\n+\t}\n+\n+\tcsk = client_connect_tls();\n+\tif (csk \u003c 0)\n+\t\tgoto out;\n+\n+\tprintf(\"TLS setup complete.\\n\");\n+\n+\tif (random_size_max \u003e 0)\n+\t\tprintf(\"Sending %d messages of random size (1..%d bytes)...\\n\",\n+\t\t       num_iterations, random_size_max);\n+\telse\n+\t\tprintf(\"Sending %d messages of %d bytes...\\n\",\n+\t\t       num_iterations, send_size);\n+\n+\tfor (i = 1; i \u003c= num_iterations; i++) {\n+\t\tint this_size;\n+\t\tint j;\n+\n+\t\tif (random_size_max \u003e 0)\n+\t\t\tthis_size = (rand() % random_size_max) + 1;\n+\t\telse\n+\t\t\tthis_size = send_size;\n+\n+\t\tfor (j = 0; j \u003c this_size; j++)\n+\t\t\tbuf[j] = rand() \u0026 0xFF;\n+\n+\t\tif (send_all(csk, buf, this_size) \u003c 0)\n+\t\t\tgoto out;\n+\t\tn = this_size;\n+\t\ttotal += n;\n+\n+\t\tif (verbose)\n+\t\t\tprintf(\"Sent %zd bytes (iteration %d)\\n\", n, i);\n+\t\tif (client_recv_echo(csk, buf, echo_buf, n) \u003c 0)\n+\t\t\tgoto out;\n+\t}\n+\n+\ttest_result = 0;\n+out:\n+\tprintf(\"Sent %d/%d iterations, %zd bytes\\n\", i - 1, num_iterations,\n+\t       total);\n+\tif (csk \u003e= 0)\n+\t\tclose(csk);\n+\tfree(buf);\n+\tfree(echo_buf);\n+\treturn test_result;\n+}\n+\n+/* Bind/listen on server_port, accept one client, switch to the TLS ULP\n+ * and install initial keys.\n+ * Returns the connected fd on success and writes the listener fd to\n+ * *lsk_out so the caller can close it. Returns -1 on error, with all\n+ * intermediate fds already closed and *lsk_out left at -1.\n+ */\n+static int server_accept_tls(int *lsk_out)\n+{\n+\tstruct addrinfo hints = {0}, *res, *rp;\n+\tint lsk = -1, csk, one = 1;\n+\tchar port_str[16];\n+\tint ret;\n+\n+\t*lsk_out = -1;\n+\n+\t/* AI_PASSIVE gives a wildcard bind address for the chosen family\n+\t * (0.0.0.0 / ::). The family is forced by -4/-6; when unspecified,\n+\t * bind the first entry that works.\n+\t */\n+\thints.ai_family = force_family;\n+\thints.ai_socktype = SOCK_STREAM;\n+\thints.ai_protocol = IPPROTO_TCP;\n+\thints.ai_flags = AI_PASSIVE;\n+\tsnprintf(port_str, sizeof(port_str), \"%d\", server_port);\n+\n+\tret = getaddrinfo(NULL, port_str, \u0026hints, \u0026res);\n+\tif (ret) {\n+\t\tprintf(\"SETUP ERROR: getaddrinfo(port %d): %s\\n\", server_port,\n+\t\t       gai_strerror(ret));\n+\t\treturn -1;\n+\t}\n+\n+\tfor (rp = res; rp; rp = rp-\u003eai_next) {\n+\t\tlsk = socket(rp-\u003eai_family, rp-\u003eai_socktype, rp-\u003eai_protocol);\n+\t\tif (lsk \u003c 0)\n+\t\t\tcontinue;\n+\t\tsetsockopt(lsk, SOL_SOCKET, SO_REUSEADDR, \u0026one, sizeof(one));\n+\t\tif (bind(lsk, rp-\u003eai_addr, rp-\u003eai_addrlen) == 0)\n+\t\t\tbreak;\n+\t\tclose(lsk);\n+\t\tlsk = -1;\n+\t}\n+\tfreeaddrinfo(res);\n+\n+\tif (lsk \u003c 0) {\n+\t\tprintf(\"SETUP ERROR: failed to bind port %d: %s\\n\",\n+\t\t       server_port, strerror(errno));\n+\t\treturn -1;\n+\t}\n+\n+\tif (listen(lsk, 1) \u003c 0) {\n+\t\tprintf(\"SETUP ERROR: listen failed: %s\\n\", strerror(errno));\n+\t\tclose(lsk);\n+\t\treturn -1;\n+\t}\n+\n+\tprintf(\"Server listening on port %d\\n\", server_port);\n+\tprintf(\"Waiting for client connection...\\n\");\n+\n+\t/* Bound accept() so a client that never connects (a deploy or connect\n+\t * failure on the peer) does not block the server forever. accept()\n+\t * honours SO_RCVTIMEO on the listening socket; the client connects\n+\t * right after wait_port_listen(), so 10s is generous, and it is well\n+\t * inside the 20s the harness waits for the server to exit (the default\n+\t * cmd.process() timeout) so the server is gone, and its listening port\n+\t * released, before the next variant starts.\n+\t */\n+\t{\n+\t\tstruct timeval tv = { .tv_sec = 10, .tv_usec = 0 };\n+\n+\t\tsetsockopt(lsk, SOL_SOCKET, SO_RCVTIMEO, \u0026tv, sizeof(tv));\n+\t}\n+\n+\tcsk = accept(lsk, NULL, NULL);\n+\tif (csk \u003c 0) {\n+\t\tif (errno == EAGAIN || errno == EWOULDBLOCK)\n+\t\t\tprintf(\"SETUP ERROR: accept timed out; client never connected\\n\");\n+\t\telse\n+\t\t\tprintf(\"SETUP ERROR: accept failed: %s\\n\", strerror(errno));\n+\t\tclose(lsk);\n+\t\treturn -1;\n+\t}\n+\tprintf(\"Client connected!\\n\");\n+\n+\tif (setup_tls_ulp(csk) \u003c 0)\n+\t\tgoto err;\n+\n+\tif (install_tls_key(csk, TLS_TX, cipher_type) \u003c 0 ||\n+\t    install_tls_key(csk, TLS_RX, cipher_type) \u003c 0)\n+\t\tgoto err;\n+\n+\tset_io_timeouts(csk);\n+\tconfigure_echo_socket(csk, random_size_max \u003e 0 ?\n+\t\t\t\t    random_size_max : send_size);\n+\n+\t*lsk_out = lsk;\n+\treturn csk;\n+err:\n+\tclose(csk);\n+\tclose(lsk);\n+\treturn -1;\n+}\n+\n+static int do_server(void)\n+{\n+\tint lsk = -1, csk = -1;\n+\tssize_t n, total = 0;\n+\tint test_result = -1;\n+\tint recv_count = 0;\n+\tchar *buf = NULL;\n+\tint record_type = 0;\n+\tint buf_size;\n+\n+\tbuf_size = send_size;\n+\tif (buf_size \u003c MIN_BUF_SIZE)\n+\t\tbuf_size = MIN_BUF_SIZE;\n+\tbuf = malloc(buf_size);\n+\tif (!buf) {\n+\t\tprintf(\"SETUP ERROR: failed to allocate buffer\\n\");\n+\t\tgoto out;\n+\t}\n+\n+\tcsk = server_accept_tls(\u0026lsk);\n+\tif (csk \u003c 0)\n+\t\tgoto out;\n+\n+\tprintf(\"TLS %s setup complete. Receiving...\\n\",\n+\t       cipher_name(cipher_type));\n+\n+\t/* Echo everything back; the client verifies each echo. */\n+\twhile (1) {\n+\t\tn = recv_tls_message(csk, buf, buf_size, \u0026record_type, 0);\n+\t\tif (n == 0) {\n+\t\t\tprintf(\"Connection closed by client\\n\");\n+\t\t\tbreak;\n+\t\t}\n+\t\tif (n \u003c 0) {\n+\t\t\tprintf(\"FAIL: recv failed: %s\\n\", strerror(errno));\n+\t\t\tgoto out;\n+\t\t}\n+\n+\t\ttotal += n;\n+\t\trecv_count++;\n+\t\tif (verbose)\n+\t\t\tprintf(\"Received %zd bytes (total: %zd, count: %d)\\n\",\n+\t\t\t       n, total, recv_count);\n+\n+\t\tif (send_all(csk, buf, n) \u003c 0)\n+\t\t\tgoto out;\n+\t\tif (verbose)\n+\t\t\tprintf(\"Echoed %zd bytes back to client\\n\", n);\n+\t}\n+\n+\ttest_result = 0;\n+out:\n+\tprintf(\"Connection closed. Total received: %zd bytes in %d reads\\n\",\n+\t       total, recv_count);\n+\n+\tif (csk \u003e= 0)\n+\t\tclose(csk);\n+\tif (lsk \u003e= 0)\n+\t\tclose(lsk);\n+\tfree(buf);\n+\treturn test_result;\n+}\n+\n+static int send_record_type(int fd)\n+{\n+\tchar control[CMSG_SPACE(sizeof(unsigned char))] = {};\n+\tstruct iovec iov = { .iov_base = \"BBBB\", .iov_len = 4 };\n+\tstruct msghdr msg = {\n+\t\t.msg_iov = \u0026iov,\n+\t\t.msg_iovlen = 1,\n+\t\t.msg_control = control,\n+\t\t.msg_controllen = sizeof(control),\n+\t};\n+\tstruct cmsghdr *cmsg = CMSG_FIRSTHDR(\u0026msg);\n+\tchar ack[2];\n+\n+\tif (send(fd, \"AAAA\", 4, MSG_MORE) != 4) {\n+\t\tprintf(\"FAIL: send MSG_MORE failed: %s\\n\", strerror(errno));\n+\t\treturn -1;\n+\t}\n+\tcmsg-\u003ecmsg_level = SOL_TLS;\n+\tcmsg-\u003ecmsg_type = TLS_SET_RECORD_TYPE;\n+\tcmsg-\u003ecmsg_len = CMSG_LEN(sizeof(unsigned char));\n+\t*CMSG_DATA(cmsg) = test_record_type;\n+\tif (sendmsg(fd, \u0026msg, 0) != 4) {\n+\t\tprintf(\"FAIL: sendmsg record type failed: %s\\n\",\n+\t\t       strerror(errno));\n+\t\treturn -1;\n+\t}\n+\treturn client_recv_echo(fd, \"OK\", ack, sizeof(ack));\n+}\n+\n+static int expect_record(int fd, const char *data, unsigned char type)\n+{\n+\tchar control[CMSG_SPACE(sizeof(unsigned char))] = {};\n+\tchar buf[16];\n+\tstruct iovec iov = { .iov_base = buf, .iov_len = sizeof(buf) };\n+\tstruct msghdr msg = {\n+\t\t.msg_iov = \u0026iov,\n+\t\t.msg_iovlen = 1,\n+\t\t.msg_control = control,\n+\t\t.msg_controllen = sizeof(control),\n+\t};\n+\tstruct cmsghdr *cmsg;\n+\tint ret;\n+\n+\tret = recvmsg(fd, \u0026msg, 0);\n+\tif (ret != 4 || memcmp(buf, data, 4) ||\n+\t    (msg.msg_flags \u0026 (MSG_CTRUNC | MSG_TRUNC)) ||\n+\t    !(msg.msg_flags \u0026 MSG_EOR)) {\n+\t\tprintf(\"FAIL: expected record '%s', got %d bytes, flags %#x\\n\",\n+\t\t       data, ret, msg.msg_flags);\n+\t\treturn -1;\n+\t}\n+\tcmsg = CMSG_FIRSTHDR(\u0026msg);\n+\tif (!cmsg || cmsg-\u003ecmsg_level != SOL_TLS ||\n+\t    cmsg-\u003ecmsg_type != TLS_GET_RECORD_TYPE ||\n+\t    cmsg-\u003ecmsg_len != CMSG_LEN(sizeof(unsigned char)) ||\n+\t    *CMSG_DATA(cmsg) != type) {\n+\t\tprintf(\"FAIL: expected record type %u\\n\", type);\n+\t\treturn -1;\n+\t}\n+\treturn 0;\n+}\n+\n+static int recv_record_type(int fd)\n+{\n+\tchar buf[16];\n+\tint ret;\n+\n+\tif (expect_record(fd, \"AAAA\", TLS_RECORD_TYPE_DATA) ||\n+\t    expect_record(fd, \"BBBB\", test_record_type) ||\n+\t    send_all(fd, \"OK\", 2))\n+\t\treturn -1;\n+\tret = recv(fd, buf, sizeof(buf), 0);\n+\tif (ret) {\n+\t\tprintf(\"FAIL: expected EOF after records, got %d\\n\", ret);\n+\t\treturn -1;\n+\t}\n+\treturn 0;\n+}\n+\n+static int test_pending_record(int is_server)\n+{\n+\tchar *buf = NULL, *echo_buf = NULL;\n+\tint lsk = -1, csk = -1;\n+\tint test_result = -1;\n+\tint i;\n+\n+\tbuf = malloc(send_size);\n+\techo_buf = malloc(send_size);\n+\tif (!buf || !echo_buf) {\n+\t\tprintf(\"SETUP ERROR: failed to allocate buffers\\n\");\n+\t\tgoto out;\n+\t}\n+\tmemset(buf, 0xa5, send_size);\n+\n+\tcsk = is_server ? server_accept_tls(\u0026lsk) : client_connect_tls();\n+\tif (csk \u003c 0)\n+\t\tgoto out;\n+\n+\t/* Exercise hardware crypto before testing the record-type transition. */\n+\tfor (i = 0; i \u003c num_iterations; i++) {\n+\t\tif (!is_server \u0026\u0026 send_all(csk, buf, send_size) \u003c 0)\n+\t\t\tgoto out;\n+\t\tif (client_recv_echo(csk, buf, echo_buf, send_size) \u003c 0)\n+\t\t\tgoto out;\n+\t\tif (is_server \u0026\u0026 send_all(csk, buf, send_size) \u003c 0)\n+\t\t\tgoto out;\n+\t}\n+\n+\ttest_result = is_server ? recv_record_type(csk) : send_record_type(csk);\n+out:\n+\tif (csk \u003e= 0)\n+\t\tclose(csk);\n+\tif (lsk \u003e= 0)\n+\t\tclose(lsk);\n+\tfree(buf);\n+\tfree(echo_buf);\n+\treturn test_result;\n+}\n+\n+static int parse_int_arg(const char *arg, int min, int max,\n+\t\t\t const char *name, int *out)\n+{\n+\tchar *endp;\n+\tlong val;\n+\n+\terrno = 0;\n+\tval = strtol(arg, \u0026endp, 10);\n+\tif (errno || endp == arg || *endp != '\\0' || val \u003c min || val \u003e max) {\n+\t\tif (max == INT_MAX)\n+\t\t\tprintf(\"ERROR: Invalid %s '%s'. Must be \u003e= %d.\\n\",\n+\t\t\t       name, arg, min);\n+\t\telse\n+\t\t\tprintf(\"ERROR: Invalid %s '%s'. Must be %d..%d.\\n\",\n+\t\t\t       name, arg, min, max);\n+\t\treturn -1;\n+\t}\n+\t*out = (int)val;\n+\treturn 0;\n+}\n+\n+static int parse_cipher_option(const char *arg)\n+{\n+\tif (strcmp(arg, \"128\") == 0) {\n+\t\tcipher_type = TLS_CIPHER_AES_GCM_128;\n+\t\treturn 0;\n+\t} else if (strcmp(arg, \"256\") == 0) {\n+\t\tcipher_type = TLS_CIPHER_AES_GCM_256;\n+\t\treturn 0;\n+\t}\n+\tprintf(\"ERROR: Invalid cipher '%s'. Must be 128 or 256.\\n\", arg);\n+\treturn -1;\n+}\n+\n+static int parse_version_option(const char *arg)\n+{\n+\tif (strcmp(arg, \"1.2\") == 0) {\n+\t\ttls_version = TLS_1_2_VERSION;\n+\t\treturn 0;\n+\t}\n+\tprintf(\"ERROR: Invalid TLS version '%s'. Must be 1.2.\\n\", arg);\n+\treturn -1;\n+}\n+\n+static void print_usage(const char *prog)\n+{\n+\tprintf(\"TLS Hardware Offload Two-Node Test\\n\\n\");\n+\tprintf(\"Usage:\\n\");\n+\tprintf(\"  %s server [OPTIONS]\\n\", prog);\n+\tprintf(\"  %s client -s \u003cip\u003e [OPTIONS]\\n\", prog);\n+\tprintf(\"\\nOptions:\\n\");\n+\tprintf(\"  -s \u003cip\u003e       Server IP address, v4 or v6 (client, required)\\n\");\n+\tprintf(\"  -p \u003cport\u003e     Server port (default: 4433)\\n\");\n+\tprintf(\"  -4            Force IPv4 (default: auto/either)\\n\");\n+\tprintf(\"  -6            Force IPv6 (default: auto/either)\\n\");\n+\tprintf(\"  -b \u003csize\u003e     Send buffer size in bytes (default: 16384)\\n\");\n+\tprintf(\"  -r \u003cmax\u003e      Use random send buffer sizes (1..\u003cmax\u003e)\\n\");\n+\tprintf(\"  -v \u003cversion\u003e  TLS version: 1.2 (default: 1.2)\\n\");\n+\tprintf(\"  -c \u003ccipher\u003e   Cipher: 128 or 256 (default: 128)\\n\");\n+\tprintf(\"  -n \u003cN\u003e        Number of send/echo iterations (default: 100)\\n\");\n+\tprintf(\"  -t \u003ctype\u003e     Test MSG_MORE followed by alert (21) or handshake (22)\\n\");\n+\tprintf(\"  -V            Verbose: log every iteration\\n\");\n+\tprintf(\"  -h            Show this help message\\n\");\n+\tprintf(\"\\nExample:\\n\");\n+\tprintf(\"  Node A: %s server\\n\", prog);\n+\tprintf(\"  Node B: %s client -s 192.168.20.2\\n\", prog);\n+\tprintf(\"\\nIPv6 Example:\\n\");\n+\tprintf(\"  Node A: %s server -6\\n\", prog);\n+\tprintf(\"  Node B: %s client -6 -s fd00::2\\n\", prog);\n+}\n+\n+int main(int argc, char *argv[])\n+{\n+\tint send_size_set = 0;\n+\tint is_server;\n+\tint opt;\n+\n+\t/* When the peer aborts a TLS connection (e.g. tls_err_abort() on a\n+\t * failed decrypt), a send() here would raise SIGPIPE and kill us by\n+\t * signal, so the harness sees only a bare non-zero exit with no\n+\t * \"FAIL:\" line. Ignore it and let send()/sendmsg() return EPIPE, which\n+\t * send_all()/send_record_type() report.\n+\t */\n+\tsignal(SIGPIPE, SIG_IGN);\n+\n+\tif (argc \u003c 2 ||\n+\t    (strcmp(argv[1], \"server\") \u0026\u0026 strcmp(argv[1], \"client\"))) {\n+\t\tprint_usage(argv[0]);\n+\t\treturn 1;\n+\t}\n+\tis_server = !strcmp(argv[1], \"server\");\n+\n+\toptind = 2; /* skip subcommand */\n+\twhile ((opt = getopt(argc, argv, \"s:p:b:r:c:v:n:t:V46h\")) != -1) {\n+\t\tswitch (opt) {\n+\t\tcase 's':\n+\t\t\tserver_ip = optarg;\n+\t\t\tbreak;\n+\t\tcase 'V':\n+\t\t\tverbose = 1;\n+\t\t\tbreak;\n+\t\tcase '4':\n+\t\t\tif (force_family == AF_INET6) {\n+\t\t\t\tprintf(\"ERROR: -4 and -6 are mutually exclusive\\n\");\n+\t\t\t\treturn 1;\n+\t\t\t}\n+\t\t\tforce_family = AF_INET;\n+\t\t\tbreak;\n+\t\tcase '6':\n+\t\t\tif (force_family == AF_INET) {\n+\t\t\t\tprintf(\"ERROR: -4 and -6 are mutually exclusive\\n\");\n+\t\t\t\treturn 1;\n+\t\t\t}\n+\t\t\tforce_family = AF_INET6;\n+\t\t\tbreak;\n+\t\tcase 'p':\n+\t\t\tif (parse_int_arg(optarg, 1, 65535, \"port\",\n+\t\t\t\t\t  \u0026server_port) \u003c 0)\n+\t\t\t\treturn 1;\n+\t\t\tbreak;\n+\t\tcase 'b':\n+\t\t\tif (parse_int_arg(optarg, 1, INT_MAX, \"buffer size\",\n+\t\t\t\t\t  \u0026send_size) \u003c 0)\n+\t\t\t\treturn 1;\n+\t\t\tsend_size_set = 1;\n+\t\t\tbreak;\n+\t\tcase 'r':\n+\t\t\tif (parse_int_arg(optarg, 1, INT_MAX, \"random size\",\n+\t\t\t\t\t  \u0026random_size_max) \u003c 0)\n+\t\t\t\treturn 1;\n+\t\t\tbreak;\n+\t\tcase 'c':\n+\t\t\tif (parse_cipher_option(optarg) \u003c 0)\n+\t\t\t\treturn 1;\n+\t\t\tbreak;\n+\t\tcase 'v':\n+\t\t\tif (parse_version_option(optarg) \u003c 0)\n+\t\t\t\treturn 1;\n+\t\t\tbreak;\n+\t\tcase 't':\n+\t\t\tif (parse_int_arg(optarg, TLS_RECORD_TYPE_ALERT,\n+\t\t\t\t\t  TLS_RECORD_TYPE_HANDSHAKE, \"record type\",\n+\t\t\t\t\t  \u0026test_record_type) \u003c 0)\n+\t\t\t\treturn 1;\n+\t\t\tbreak;\n+\t\tcase 'n':\n+\t\t\t/* The iteration loops use an inclusive int bound\n+\t\t\t * (i \u003c= num_iterations), so INT_MAX itself would\n+\t\t\t * overflow the counter instead of terminating.\n+\t\t\t */\n+\t\t\tif (parse_int_arg(optarg, 1, INT_MAX - 1,\n+\t\t\t\t\t  \"iteration count\",\n+\t\t\t\t\t  \u0026num_iterations) \u003c 0)\n+\t\t\t\treturn 1;\n+\t\t\tbreak;\n+\t\tcase 'h':\n+\t\t\tprint_usage(argv[0]);\n+\t\t\treturn 0;\n+\t\tdefault:\n+\t\t\tprint_usage(argv[0]);\n+\t\t\treturn 1;\n+\t\t}\n+\t}\n+\n+\tif (send_size_set \u0026\u0026 random_size_max \u003e 0) {\n+\t\tprintf(\"ERROR: -b and -r are mutually exclusive\\n\");\n+\t\treturn 1;\n+\t}\n+\n+\tif (test_record_type \u0026\u0026 random_size_max) {\n+\t\tprintf(\"ERROR: -t cannot be combined with -r\\n\");\n+\t\treturn 1;\n+\t}\n+\n+\tif (is_server) {\n+\t\tif (server_ip) {\n+\t\t\tprintf(\"warning: -s is ignored in server mode\\n\");\n+\t\t\tserver_ip = NULL;\n+\t\t}\n+\t\tif (random_size_max \u003e 0) {\n+\t\t\tprintf(\"warning: -r is ignored in server mode\\n\");\n+\t\t\trandom_size_max = 0;\n+\t\t}\n+\t} else {\n+\t\tif (!server_ip) {\n+\t\t\tprintf(\"ERROR: Client requires -s \u003cip\u003e option\\n\");\n+\t\t\treturn 1;\n+\t\t}\n+\t}\n+\n+\tprintf(\"TLS Version: %s\\n\", version_name(tls_version));\n+\tprintf(\"Cipher: %s\\n\", cipher_name(cipher_type));\n+\tprintf(\"Address family: %s\\n\",\n+\t       force_family == AF_INET ? \"IPv4\" :\n+\t       force_family == AF_INET6 ? \"IPv6\" : \"auto\");\n+\tif (random_size_max \u003e 0)\n+\t\tprintf(\"Buffer size: random (1..%d)\\n\", random_size_max);\n+\telse\n+\t\tprintf(\"Buffer size: %d\\n\", send_size);\n+\n+\tsrand(time(NULL));\n+\n+\tif (test_record_type)\n+\t\treturn test_pending_record(is_server) ? 1 : 0;\n+\n+\tif (is_server)\n+\t\treturn do_server() ? 1 : 0;\n+\n+\treturn do_client() ? 1 : 0;\n+}\ndiff --git a/tools/testing/selftests/drivers/net/hw/tls_hw_offload.py b/tools/testing/selftests/drivers/net/hw/tls_hw_offload.py\nnew file mode 100755\nindex 0000000000000..37f26e21a7b78\n--- /dev/null\n+++ b/tools/testing/selftests/drivers/net/hw/tls_hw_offload.py\n@@ -0,0 +1,402 @@\n+#!/usr/bin/env python3\n+# SPDX-License-Identifier: GPL-2.0\n+\n+\"\"\"Test kTLS hardware offload using a C helper binary.\"\"\"\n+\n+import re\n+import shlex\n+import subprocess\n+from collections import defaultdict\n+\n+from lib.py import ksft_run, ksft_exit, ksft_pr, KsftSkipEx\n+from lib.py import ksft_ge, ksft_eq\n+from lib.py import ksft_variants, KsftNamedVariant\n+from lib.py import NetDrvEpEnv\n+from lib.py import cmd, bkg, wait_port_listen, rand_port\n+from lib.py import CmdExitFailure\n+\n+# Reading /proc/net/tls_stat is trivial locally, but on the remote it runs\n+# over ssh, where connection setup can occasionally spike past the short\n+# default cmd() timeout. Give these tiny reads plenty of headroom so a slow\n+# ssh round-trip doesn't fail an otherwise-good variant.\n+STATS_TIMEOUT_S = 30\n+\n+# `ethtool -S` counters on the DUT NIC, from the minimum set every TLS\n+# offload driver should report (Documentation/networking/tls-offload.rst,\n+# \"Statistics\"); mlx5, nfp, cxgb4 and funeth use exactly these names.\n+# TlsTxDevice/TlsRxDevice in /proc/net/tls_stat only prove tls_dev_add()\n+# accepted the offload:\n+#  - *_packets increment once per packet the NIC actually encrypted or\n+#    decrypted (mlx5 counts gso_segs, not records), so they prove the HW\n+#    crypto path was exercised.\n+#  - *_ctx increment once per tls_dev_add().\n+# Missing NIC crypto counters remain optional.\n+HW_NIC_COUNTERS = {\n+    'Tx': {'crypto': 'tx_tls_encrypted_packets', 'ctx': 'tx_tls_ctx'},\n+    'Rx': {'crypto': 'rx_tls_decrypted_packets', 'ctx': 'rx_tls_ctx'},\n+}\n+\n+\n+def check_tls_support(cfg):\n+    \"\"\"Require kTLS on both hosts and at least one DUT HW direction.\"\"\"\n+    # The tls module is autoloaded lazily on the first TCP_ULP=\"tls\"\n+    # setsockopt, so /proc/net/tls_stat (created from the module's pernet\n+    # init) may not exist yet on a freshly booted host. Load the module\n+    # explicitly before probing for it. Best effort only: with CONFIG_TLS=y\n+    # (what the config fragment asks for) there is nothing to load, and\n+    # modprobe may fail for reasons unrelated to kTLS (no modules.dep for a\n+    # locally built kernel, no modprobe on a minimal rootfs). The\n+    # /proc/net/tls_stat probe below is the authoritative check. Locally,\n+    # cmd() runs without a shell, so a missing modprobe raises\n+    # FileNotFoundError rather than returning a failed exit status.\n+    try:\n+        cmd(\"modprobe tls\", fail=False)\n+    except FileNotFoundError:\n+        pass\n+    cmd(\"modprobe tls\", host=cfg.remote, fail=False)\n+    try:\n+        cmd(\"test -f /proc/net/tls_stat\")\n+        cmd(\"test -f /proc/net/tls_stat\", host=cfg.remote)\n+    except CmdExitFailure as e:\n+        raise KsftSkipEx(f\"kTLS not supported: {e}\") from e\n+\n+    try:\n+        features = cmd(f\"ethtool -k {cfg.ifname}\").stdout\n+    except CmdExitFailure as e:\n+        raise KsftSkipEx(f\"Cannot determine TLS HW offload support: {e}\") from e\n+    cfg.tls_hw_directions = {\n+        direction for direction in ('Tx', 'Rx')\n+        if f'tls-hw-{direction.lower()}-offload: on' in features\n+    }\n+    if not cfg.tls_hw_directions:\n+        raise KsftSkipEx(\"Device has no enabled TLS HW offload direction\")\n+\n+\n+def read_tls_stats(host=None):\n+    \"\"\"Snapshot the per-netns TLS MIB from /proc/net/tls_stat as a dict.\"\"\"\n+    # /proc/net/tls_stat exposes the per-netns TLS MIB (TLS_INC_STATS on\n+    # sock_net(sk)). The test runs on a real NIC in the host namespace, so\n+    # these counters are shared with anything else doing kTLS there. The\n+    # strict before/after delta checks (zero error counters) assume no other\n+    # kTLS activity in this namespace during a\n+    # variant's window; concurrent kTLS users would perturb the deltas and\n+    # cause spurious failures. Don't run other kTLS workloads alongside this\n+    # test.\n+    stats = defaultdict(int)\n+    output = cmd(\"cat /proc/net/tls_stat\", host=host, timeout=STATS_TIMEOUT_S)\n+    for line in output.stdout.strip().split('\\n'):\n+        parts = line.split()\n+        if len(parts) == 2:\n+            stats[parts[0]] = int(parts[1])\n+    return stats\n+\n+\n+def read_nic_stats(cfg):\n+    \"\"\"Snapshot the DUT NIC's `ethtool -S` counters as a dict.\"\"\"\n+    # Driver per-record TLS counters from `ethtool -S` on the DUT NIC. Same\n+    # before/after-delta caveat as read_tls_stats(): these are device-wide,\n+    # so concurrent kTLS traffic on this NIC would perturb the deltas.\n+    stats = defaultdict(int)\n+    output = cmd(f\"ethtool -S {cfg.ifname}\").stdout\n+    for line in output.strip().split('\\n'):\n+        key, sep, val = line.partition(':')\n+        if sep and val.strip().isdigit():\n+            stats[key.strip()] = int(val.strip())\n+    return stats\n+\n+\n+def stat_diff(before, after, key):\n+    \"\"\"Return the delta of counter `key` between two stat snapshots.\"\"\"\n+    return after[key] - before[key]\n+\n+\n+def check_hw_crypto(cfg, nic_before, nic_after, hw_directions):\n+    \"\"\"Check DUT hardware crypto and initial key installs.\"\"\"\n+    for direction in hw_directions:\n+        names = HW_NIC_COUNTERS[direction]\n+\n+        key = names['crypto']\n+        if key in nic_after:\n+            got = stat_diff(nic_before, nic_after, key)\n+            ksft_ge(got, 1,\n+                    comment=f\"DUT {direction}: NIC reported no HW crypto \"\n+                            f\"({key}={got})\")\n+        else:\n+            ksft_pr(f\"NOTE: DUT {direction}: '{key}' not exposed by \"\n+                    f\"{cfg.ifname}, skipping HW crypto check\")\n+\n+        key = names['ctx']\n+        if key not in nic_after:\n+            ksft_pr(f\"NOTE: DUT {direction}: '{key}' not exposed by \"\n+                    f\"{cfg.ifname}, skipping NIC context count check\")\n+            continue\n+        ctx = stat_diff(nic_before, nic_after, key)\n+        ksft_ge(ctx, 1,\n+                comment=f\"DUT {direction}: no HW context installed \"\n+                        f\"({key}={ctx})\")\n+\n+\n+def check_path(before, after, direction, role, require_hw):\n+    \"\"\"Require HW for enabled DUT directions; otherwise HW or SW is fine.\"\"\"\n+    dev = stat_diff(before, after, f'Tls{direction}Device')\n+    sw = stat_diff(before, after, f'Tls{direction}Sw')\n+    if require_hw:\n+        ksft_ge(dev, 1,\n+                comment=f\"{role} {direction}: HW offload not engaged \"\n+                        f\"(Device={dev}, Sw={sw})\")\n+    else:\n+        ksft_ge(dev + sw, 1,\n+                comment=f\"{role} {direction}: no TLS activity \"\n+                        f\"(Device={dev}, Sw={sw})\")\n+\n+\n+def verify_tls_counters(stats_before, stats_after, is_dut, hw_directions=()):\n+    \"\"\"Verify TLS counters on one side of the connection.\n+\n+    is_dut: True for the local DUT.\n+    hw_directions: DUT directions with enabled HW offload; other directions\n+           may use SW kTLS but still undergo activity and error checks.\n+    \"\"\"\n+    role = 'DUT' if is_dut else 'Peer'\n+\n+    # Echo mode drives both directions on both sides.\n+    for direction in ('Tx', 'Rx'):\n+        check_path(stats_before, stats_after, direction, role,\n+                   require_hw=is_dut and direction in hw_directions)\n+\n+    ksft_eq(stat_diff(stats_before, stats_after, 'TlsDecryptError'), 0,\n+            comment=f\"{role}: TlsDecryptError expected 0\")\n+\n+\n+def stop_helper(helper):\n+    \"\"\"Reap a helper that is still running: SIGTERM, then SIGKILL.\n+\n+    cmd.process(terminate=True) sends SIGTERM and waits; if the process\n+    ignores it there is no fallback and communicate() raises again from the\n+    cleanup path, leaving the child alive. Escalate to SIGKILL instead.\n+    \"\"\"\n+    try:\n+        helper.process(terminate=True, fail=False, timeout=5)\n+    except subprocess.TimeoutExpired:\n+        helper.proc.kill()\n+        helper.process(terminate=False, fail=False, timeout=5)\n+\n+\n+def kill_remote_helper(cfg, helper_cmd):\n+    \"\"\"Stop this variant's remote helper and confirm that it has exited.\n+\n+    Signalling cmd.proc only reaches the local process, which for the ssh\n+    backend is the ssh client, not the helper on the peer. Losing its stdout\n+    does not stop the helper either: it ignores SIGPIPE so that a peer abort\n+    is reported as EPIPE instead of a bare signal death. Left alone it keeps\n+    driving kTLS (bumping the peer's TLS MIBs) into the next variant's\n+    measurement window, or sits in accept() for the rest of its own timeout.\n+    Match the complete command, including this variant's port, since the\n+    netns backend uses the same binary path for both endpoints and other\n+    runs. The anchors also exclude the shell executing the cleanup. Failure\n+    to confirm exit must prevent later variants from taking counter\n+    snapshots.\n+    \"\"\"\n+    pattern = shlex.quote('^' + re.escape(helper_cmd) + '$')\n+    cmd(f\"\"\"\n+command -v pkill \u003e/dev/null \u0026\u0026 command -v pgrep \u003e/dev/null || exit 2\n+for tls_signal in TERM KILL; do\n+    pkill -\"$tls_signal\" -f -- {pattern}\n+    tls_status=$?\n+    [ \"$tls_status\" -le 1 ] || exit \"$tls_status\"\n+    tls_attempt=0\n+    while [ \"$tls_attempt\" -lt 50 ]; do\n+        pgrep -f -- {pattern} \u003e/dev/null\n+        tls_status=$?\n+        case \"$tls_status\" in\n+            1) exit 0 ;;\n+            0) ;;\n+            *) exit \"$tls_status\" ;;\n+        esac\n+        sleep 0.1\n+        tls_attempt=$((tls_attempt + 1))\n+    done\n+done\n+echo 'TLS helper still running after SIGKILL' \u003e\u00262\n+exit 1\n+\"\"\", host=cfg.remote, timeout=STATS_TIMEOUT_S)\n+\n+\n+def run_tls_test(cfg, cipher=\"128\", tls_version=\"1.2\",\n+                 buffer_size=None, random_max=None, ipver=\"4\",\n+                 record_type=None):\n+    \"\"\"Run the TLS offload test.\n+\n+    The DUT runs the TLS client and the remote runs the echo server.\n+\n+    ipver: '4' or '6' - IP version to run over. The C helper is forced to the\n+           matching family with -4/-6 and connects to the peer's v4/v6 address.\n+           Variants requesting '6' skip cleanly when the environment lacks IPv6\n+           connectivity (require_ipver()).\n+\n+    The DUT (local) is the kernel under test; the remote is just a traffic\n+    source/sink and may run any kernel without HW offload. Both sides run\n+    kTLS because TLS is pairwise, but verify_tls_counters() requires HW\n+    offload only in enabled DUT directions. The peer and the DUT's other\n+    direction may use SW kTLS.\n+    \"\"\"\n+    if cfg.cleanup_failed:\n+        raise KsftSkipEx(\"Previous helper cleanup could not be confirmed\")\n+\n+    cfg.require_ipver(ipver)\n+\n+    # Echo exercises both directions, allowing SW in a direction without\n+    # HW support.\n+    hw_directions = tuple(d for d in ('Tx', 'Rx') if d in cfg.tls_hw_directions)\n+\n+    if record_type and 'Tx' not in hw_directions:\n+        raise KsftSkipEx(\"Record-type regression requires DUT TLS TX offload\")\n+\n+    port = rand_port()\n+    send_size = random_max or buffer_size\n+\n+    server_parts = [f\"{cfg.bin_remote} server -p {port} -c {cipher}\",\n+                    f\"-v {tls_version}\", f\"-{ipver}\"]\n+    if send_size:\n+        server_parts.append(f\"-b {send_size}\")\n+    if record_type:\n+        server_parts.append(f\"-t {record_type}\")\n+    server_cmd = \" \".join(server_parts)\n+\n+    client_parts = [f\"{cfg.bin_local} client -s {cfg.remote_addr_v[ipver]}\",\n+                    f\"-p {port} -c {cipher} -v {tls_version} -{ipver}\"]\n+    if random_max:\n+        client_parts.append(f\"-r {random_max}\")\n+    elif buffer_size:\n+        client_parts.append(f\"-b {buffer_size}\")\n+    if record_type:\n+        client_parts.append(f\"-t {record_type}\")\n+    client_cmd = \" \".join(client_parts)\n+\n+    stats_before_local = read_tls_stats()\n+    stats_before_remote = read_tls_stats(host=cfg.remote)\n+    nic_before = read_nic_stats(cfg)\n+\n+    # Both helpers run with their stdout captured in a pipe that is only\n+    # drained once they exit, so the helper keeps its per-connection output\n+    # small (see the note on verbose in tls_hw_offload.c); do not pass -V.\n+    #\n+    # On the failure path make sure nothing outlives the variant: a leaked\n+    # helper keeps bumping the per-netns TLS counters (TlsDecryptError, ...)\n+    # and would corrupt the before/after measurement\n+    # window of a later variant. The local client is a direct child; the\n+    # server on the peer needs kill_remote_helper().\n+    server = None\n+    client = None\n+    try:\n+        server = bkg(server_cmd, host=cfg.remote, exit_wait=True)\n+        with server:\n+            wait_port_listen(port, host=cfg.remote)\n+            # Start the client in the background so we keep a handle to it.\n+            # A foreground cmd() raises TimeoutExpired from inside its\n+            # constructor if the client hangs, and since the child is not\n+            # killed on timeout it would be left running with no handle to\n+            # reap it.\n+            client = cmd(client_cmd, background=True)\n+            try:\n+                client.process(terminate=False, fail=True, timeout=20)\n+            finally:\n+                if client.proc.poll() is None:\n+                    stop_helper(client)\n+    except BaseException:\n+        # bkg.__exit__ reaps the server with a plain 20 s communicate()\n+        # (SIGTERM first only on an exception). A server that hangs or\n+        # ignores SIGTERM makes it raise TimeoutExpired with the process\n+        # still alive; escalate to SIGKILL as for the client.\n+        cfg.cleanup_failed = True\n+        try:\n+            try:\n+                if client is not None and client.proc.poll() is None:\n+                    stop_helper(client)\n+            finally:\n+                if server is not None and server.proc.poll() is None:\n+                    stop_helper(server)\n+        finally:\n+            kill_remote_helper(cfg, server_cmd)\n+        cfg.cleanup_failed = False\n+        raise\n+\n+    cfg.wait_hw_stats_settle()\n+    stats_after_local = read_tls_stats()\n+    stats_after_remote = read_tls_stats(host=cfg.remote)\n+    nic_after = read_nic_stats(cfg)\n+\n+    verify_tls_counters(stats_before_local, stats_after_local, is_dut=True,\n+                        hw_directions=hw_directions)\n+    check_hw_crypto(cfg, nic_before, nic_after, hw_directions)\n+    verify_tls_counters(stats_before_remote, stats_after_remote, is_dut=False)\n+\n+\n+# Drivers whose tls_dev_add() accepts only AES-GCM-128: nfp\n+# (nfp_net_cipher_supported()), cxgb4 (chcr_ktls), funeth.\n+GCM128_ONLY_DRIVERS = {\"nfp\", \"nfp_netvf\", \"cxgb4\", \"funeth\"}\n+\n+\n+# The cipher/version matrix runs over IPv4; the socket setup is the only\n+# IP-version-specific code path, so a single representative variant over\n+# IPv6 is enough to cover it (it skips cleanly without v6 connectivity).\n+# The suites below likewise stay on IPv4 to bound runtime.\n+@ksft_variants([\n+    KsftNamedVariant(\"tls12_aes128\", \"128\", \"1.2\", \"4\"),\n+    KsftNamedVariant(\"tls12_aes256\", \"256\", \"1.2\", \"4\"),\n+    KsftNamedVariant(\"tls12_aes128_ip6\", \"128\", \"1.2\", \"6\"),\n+])\n+def test_tls_offload(cfg, cipher, tls_version, ipver):\n+    \"\"\"Cipher/version matrix over the HW offload data path.\"\"\"\n+    # The tls-hw-{tx,rx}-offload feature bits do not advertise cipher\n+    # support, and there is no uAPI to query it. Skip AES-GCM-256 on drivers\n+    # whose tls_dev_add() accepts only AES-GCM-128; keep the HW assertions\n+    # for every other driver/cipher pair.\n+    if tls_version == \"1.2\" and cipher == \"256\":\n+        info = cmd(f\"ethtool -i {cfg.ifname}\", fail=False).stdout\n+        for line in info.splitlines():\n+            name, _, value = line.partition(':')\n+            driver = value.strip()\n+            if name.strip() == 'driver' and driver in GCM128_ONLY_DRIVERS:\n+                raise KsftSkipEx(f\"{driver} TLS offload supports only AES-GCM-128\")\n+\n+    run_tls_test(cfg, cipher=cipher, tls_version=tls_version, ipver=ipver)\n+\n+\n+@ksft_variants([\n+    KsftNamedVariant(\"small_buf\", 512),\n+    KsftNamedVariant(\"large_buf\", 2097152),\n+    KsftNamedVariant(\"random_buf\", None, 8192),\n+])\n+def test_tls_offload_sizes(cfg, buffer_size=None, random_max=None):\n+    \"\"\"Echo-mode TLS 1.2 across a range of buffer sizes.\"\"\"\n+    run_tls_test(cfg, cipher=\"128\", tls_version=\"1.2\",\n+                 buffer_size=buffer_size, random_max=random_max)\n+\n+\n+@ksft_variants([\n+    KsftNamedVariant(\"handshake\", 22),\n+    KsftNamedVariant(\"alert\", 21),\n+])\n+def test_tls_offload_record_type(cfg, record_type):\n+    \"\"\"RX setup must preserve the HW TX hook which flushes an open record.\"\"\"\n+    run_tls_test(cfg, record_type=record_type)\n+\n+\n+def main() -\u003e None:\n+    \"\"\"Set up the DUT/peer environment and run the offload test suites.\"\"\"\n+    with NetDrvEpEnv(__file__, nsim_test=False) as cfg:\n+        cfg.bin_local = cfg.test_dir / \"tls_hw_offload\"\n+        if not cfg.bin_local.exists():\n+            raise KsftSkipEx(f\"tls_hw_offload binary not found at {cfg.bin_local}\")\n+        cfg.bin_remote = cfg.remote.deploy(cfg.bin_local)\n+        check_tls_support(cfg)\n+        cfg.cleanup_failed = False\n+\n+        ksft_run([test_tls_offload, test_tls_offload_sizes,\n+                  test_tls_offload_record_type], args=(cfg, ))\n+    ksft_exit()\n+\n+\n+if __name__ == \"__main__\":\n+    main()\n"
}

2/1 2026/10/21 04:12 agent patch-evaluator
2m Model:
core

Args:
null

Results:
{
  "EnableConfigs": [
    "TLS",
    "TLS_DEVICE"
  ],
  "FocusSymbols": [
    "tls_set_sw_offload",
    "tls_sw_push_pending_record",
    "tls_process_cmsg"
  ],
  "Reasoning": "The patch modifies net/tls/tls_sw.c in the core networking kTLS subsystem so that ctx-\u003epush_pending_record is only assigned to tls_sw_push_pending_record when configuring TX offload (if (tx)), avoiding overwriting the TX push_pending_record callback when configuring RX. This affects reachable socket configuration and record handling in kTLS, which is exercised through standard TCP setsockopt and sendmsg operations.",
  "WorthFuzzing": true
}

Instruction:
You are an expert Linux kernel maintainer and security engineer.
Your job is to review a provided patch series and evaluate whether it warrants fuzzing with syzkaller.

IMPORTANT: The changes have ALREADY been applied and committed as the HEAD commit in
your workspace. Do NOT rely on internal assumptions. You must actively use your code access
tools to inspect the actual source code, callers, and surrounding context.

================================================================================
1. CORE TRIAGE PHILOSOPHY
================================================================================
The goal of patch fuzzing is to discover crashes, regressions, exposed latent bugs,
and newly triggered assertions introduced by the patch series.

- REACHABILITY IS THE PRIMARY GATE:
  Fuzzing can only discover bugs in code that can actually execute in standard virtualized
  environments (GCE or QEMU, utilizing software-emulated devices like USB gadgets, netdev, tun/tap).
  If the modified code is structurally unreachable (see Section 2), it MUST NOT be fuzzed,
  regardless of whether it adds assertions or complex logic.

- DO NOT BLINDLY TRUST "NO FUNCTIONAL CHANGE" (NFCI) OR "REFACTORING" CLAIMS:
  Patch authors routinely label changes as "cleanups", "refactorings", or state
  "No functional change intended". Do NOT take these claims at face value.
  Code refactorings that rearrange logic, introduce helper functions, or alter state management
  in core subsystems frequently introduce subtle semantic shifts or uncover latent kernel bugs.
  If reachable executable code is modified or refactored, it MUST be fuzzed.

- NEW OR MODIFIED ASSERTIONS IN REACHABLE CODE MUST BE FUZZED:
  When a patch introduces or modifies runtime checks or assertions (e.g., WARN_ON*, VM_WARN_ON*,
  BUG_ON*, lockdep_assert*) in reachable code paths, it enforces new or stricter invariants.
  Even if the author believes the invariant always holds, fuzzing is essential to verify whether
  an unusual sequence of operations can violate it.

================================================================================
2. WHEN TO RETURN WorthFuzzing=false (NEGATIVE CRITERIA)
================================================================================
Return WorthFuzzing=false ONLY IF all modified code falls strictly into one or more of these categories:

- Non-kernel and non-executable changes:
  * Modifications to Documentation/, comments, or spelling fixes.
  * User-space directories, self-tests, samples, or scripts (e.g., tools/, samples/, scripts/, usr/)
    that do not affect the compiled kernel image (vmlinux) or kernel modules.
  * Purely decorative logging (e.g., message strings in pr_err, printk, dev_info) or tracepoints
    that do not alter control flow or data structures.
  * Build system or Kconfig changes that do not alter compiled C logic.
- Structurally unreachable hardware:
  * Vendor-specific PCIe switches, SmartNICs, or GPU drivers (e.g., mlxsw, pds_core, qed,
    ionic, amdgpu) requiring physical ASIC/PCIe cards not emulated in standard QEMU.
- Unreachable execution paths:
  * Driver teardown callbacks (.remove, .shutdown, pci_unregister_driver) executed only during
    physical PCI hot-unplug or manual sysfs driver unbinding.
  * Code paths exclusive to architectures other than the target architecture.

================================================================================
3. WHEN TO RETURN WorthFuzzing=true (POSITIVE CRITERIA)
================================================================================
Return WorthFuzzing=true whenever the patch touches reachable executable code, including:
- Core Subsystems:
  * Any logic modifications in memory management (mm/), synchronization/locking (kernel/locking/),
    BPF, scheduler, core networking, VFS, or syscall handling.
- Refactorings and Code Cleanups:
  * Any restructuring of reachable data structures, helper abstractions, or algorithm flows.
- Runtime Assertions and Defensive Checks:
  * Any introduction or alteration of assertions (WARN_ON*, VM_WARN_ON*, BUG_ON*, etc.) in reachable paths.
- Reachable Drivers and Protocols:
  * Drivers accessible via virtual buses (virtio, USB gadget, loopback, netlink, binder, sockets, etc.).

================================================================================
4. EXTRACTING FocusSymbols (PREVENTING DILUTION)
================================================================================
When WorthFuzzing=true, you must extract specific kernel functions into FocusSymbols to guide the fuzzer:

- AVOID UBIQUITOUS LIFECYCLE HOT-PATHS:
  Do NOT list generic, ubiquitous functions called by almost every program in the corpus
  (including, but not limited to: general memory allocators and deallocators, page fault
  and trap handlers, or core synchronization primitives; this is not an exhaustive list).
  Listing ubiquitous functions causes the fuzzer to classify thousands of unrelated tests as "focused",
  which severely dilutes fuzzing effort away from the actual changes.

- TARGET SPECIFIC FEATURE LOGIC AND ENTRYPOINTS:
  List functions that specifically implement the logic being added or altered, or direct API entrypoints
  for the subsystem feature under review.

- HANDLING STATIC INLINE FUNCTIONS IN HEADERS (.h):
  Compiler-inlined static functions (such as static inlines in mm/*.h or include/linux/*.h) lack
  distinct symbol addresses in vmlinux and cannot be targeted directly by symbol coverage filters.
  If the changes are primarily in static inline helpers, identify non-static, feature-specific caller
  functions in .c files that exercise them (avoiding ubiquitous lifecycle wrappers).

================================================================================
5. IDENTIFYING EnableConfigs
================================================================================
Identify any specific CONFIG_ options required to properly compile and reach the modified code:
- Inspect Kconfig files and #ifdef guards; do not make assumptions.
- Check "depends on" lines in Kconfig to include any non-standard parent subsystem configs needed.
- Strip any 'CONFIG_' prefix (e.g., return "NET_IPV4" instead of "CONFIG_NET_IPV4").
Prefer calling several tools at the same time to save round-trips.


Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit 2449cc829c24f2d986b3e924a1bd5f0afa3905ad
Author: syz-cluster <triage@syzkaller.com>
Date:   Wed Oct 21 04:12:00 2026 +0000

    syz-cluster: applied patch under review

diff --git a/MAINTAINERS b/MAINTAINERS
index 00b440be0d46c..771cd3161a05f 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -19269,6 +19269,8 @@ F:	Documentation/networking/tls*
 F:	include/net/tls.h
 F:	include/uapi/linux/tls.h
 F:	net/tls/
+F:	tools/testing/selftests/drivers/net/hw/tls_hw_offload.c
+F:	tools/testing/selftests/drivers/net/hw/tls_hw_offload.py
 F:	tools/testing/selftests/net/tls.c
 
 NETWORKING [SOCKETS]
diff --git a/net/tls/tls_sw.c b/net/tls/tls_sw.c
index d1ad31986cf2c..235b868facfa9 100644
--- a/net/tls/tls_sw.c
+++ b/net/tls/tls_sw.c
@@ -2591,7 +2591,8 @@ int tls_set_sw_offload(struct sock *sk, int tx,
 		}
 	}
 
-	ctx->push_pending_record = tls_sw_push_pending_record;
+	if (tx)
+		ctx->push_pending_record = tls_sw_push_pending_record;
 
 	/* setkey is the last operation that could fail during a
 	 * rekey. if it succeeds, we can start modifying the
diff --git a/tools/testing/selftests/drivers/net/README.rst b/tools/testing/selftests/drivers/net/README.rst
index c6bed9a985bc7..94c6aeecfe2ff 100644
--- a/tools/testing/selftests/drivers/net/README.rst
+++ b/tools/testing/selftests/drivers/net/README.rst
@@ -188,6 +188,28 @@ The tests have a handful of dependencies. For Fedora / CentOS::
 
   dnf -y install netsniff-ng python-yaml socat iperf3
 
+TLS hardware offload
+~~~~~~~~~~~~~~~~~~~~
+
+``hw/tls_hw_offload.py`` tests TLS 1.2 with AES-GCM-128/256 using a C
+helper on both endpoints. Configure the endpoints using the variables above
+and enable at least one of ``tls-hw-tx-offload`` or ``tls-hw-rx-offload`` on
+the DUT. The peer can use software kTLS. The test checks every enabled DUT
+direction; unexpected software fallback fails. Known AES-GCM-128-only
+drivers skip the AES-GCM-256 case.
+
+The record-type cases require DUT TX offload. They install TLS_RX after
+TLS_TX, buffer application data with MSG_MORE, then send a handshake or
+alert record. The peer verifies both record types and payloads. Running
+with RX offload enabled covers hardware RX setup; running with it disabled
+also covers software RX setup on a socket with hardware TX offload.
+
+Run without other kTLS workloads in either endpoint's network namespace:
+the tests compare shared TLS MIB and NIC counter snapshots. Build the helper
+with ``make -C tools/testing/selftests/drivers/net/hw tls_hw_offload`` and
+run ``tools/testing/selftests/drivers/net/hw/tls_hw_offload.py`` with the
+endpoint configuration. The harness deploys the helper to the peer.
+
 Guidance for test authors
 =========================
 
diff --git a/tools/testing/selftests/drivers/net/hw/.gitignore b/tools/testing/selftests/drivers/net/hw/.gitignore
index 46540468a7753..911a9bfeaf41e 100644
--- a/tools/testing/selftests/drivers/net/hw/.gitignore
+++ b/tools/testing/selftests/drivers/net/hw/.gitignore
@@ -1,4 +1,5 @@
 # SPDX-License-Identifier: GPL-2.0-only
 iou-zcrx
 ncdevmem
+tls_hw_offload
 toeplitz
diff --git a/tools/testing/selftests/drivers/net/hw/Makefile b/tools/testing/selftests/drivers/net/hw/Makefile
index 78bb0169350b2..ee412ec930231 100644
--- a/tools/testing/selftests/drivers/net/hw/Makefile
+++ b/tools/testing/selftests/drivers/net/hw/Makefile
@@ -45,6 +45,7 @@ TEST_PROGS = \
 	rss_drv.py \
 	rss_flow_label.py \
 	rss_input_xfrm.py \
+	tls_hw_offload.py \
 	toeplitz.py \
 	tso.py \
 	userns_devmem.py \
@@ -77,6 +78,7 @@ YNL_GEN_FILES := \
 # end of YNL_GEN_FILES
 TEST_GEN_FILES += $(YNL_GEN_FILES)
 TEST_GEN_FILES += $(patsubst %.c,%.o,$(wildcard *.bpf.c))
+TEST_GEN_FILES += tls_hw_offload
 
 include ../../../lib.mk
 
@@ -90,6 +92,8 @@ include ../../../net/ynl.mk
 
 include ../../../net/bpf.mk
 
+$(OUTPUT)/tls_hw_offload: CFLAGS += $(KHDR_INCLUDES)
+
 ifeq ($(HAS_IOURING_ZCRX),y)
 $(OUTPUT)/iou-zcrx: LDLIBS += -luring
 endif
diff --git a/tools/testing/selftests/drivers/net/hw/config b/tools/testing/selftests/drivers/net/hw/config
index d89a9ba176558..169e608516bd5 100644
--- a/tools/testing/selftests/drivers/net/hw/config
+++ b/tools/testing/selftests/drivers/net/hw/config
@@ -22,6 +22,8 @@ CONFIG_NET_IPIP=y
 CONFIG_NETKIT=y
 CONFIG_NET_SCH_INGRESS=y
 CONFIG_SYNC_FILE=y
+CONFIG_TLS=y
+CONFIG_TLS_DEVICE=y
 CONFIG_UDMABUF=y
 CONFIG_USER_NS=y
 CONFIG_VXLAN=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
new file mode 100644
index 0000000000000..4e9f8a2be8a8f
--- /dev/null
+++ b/tools/testing/selftests/drivers/net/hw/tls_hw_offload.c
@@ -0,0 +1,886 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * TLS Hardware Offload Two-Node Test
+ *
+ * Tests kTLS hardware offload between two physical nodes using
+ * hardcoded keys. Supports TLS 1.2 and AES-GCM-128/256.
+ *
+ * Both ends must run this helper: there is no handshake.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#include <limits.h>
+#include <time.h>
+#include <sys/time.h>
+#include <signal.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <netinet/tcp.h>
+#include <netdb.h>
+#include <linux/tls.h>
+
+#ifndef SOL_TLS
+#define SOL_TLS 282
+#endif
+
+#define TLS_RECORD_TYPE_HANDSHAKE		22
+#define TLS_RECORD_TYPE_ALERT			21
+#define TLS_RECORD_TYPE_DATA			23
+
+#define MIN_BUF_SIZE   16
+
+/* Initial key material */
+static struct tls12_crypto_info_aes_gcm_128 tls_info_key0_128 = {
+	.info = {
+		.version = TLS_1_2_VERSION,
+		.cipher_type = TLS_CIPHER_AES_GCM_128,
+	},
+	.iv = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 },
+	.key = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
+		 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10 },
+	.salt = { 0x01, 0x02, 0x03, 0x04 },
+	.rec_seq = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
+};
+
+static struct tls12_crypto_info_aes_gcm_256 tls_info_key0_256 = {
+	.info = {
+		.version = TLS_1_2_VERSION,
+		.cipher_type = TLS_CIPHER_AES_GCM_256,
+	},
+	.iv = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 },
+	.key = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
+		 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
+		 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
+		 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20 },
+	.salt = { 0x01, 0x02, 0x03, 0x04 },
+	.rec_seq = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
+};
+
+static int test_record_type;
+static int num_iterations = 100;
+static int cipher_type = TLS_CIPHER_AES_GCM_128;
+static int tls_version = TLS_1_2_VERSION;
+static int server_port = 4433;
+static char *server_ip;
+/* Address family to force: AF_UNSPEC (any), AF_INET (-4), AF_INET6 (-6). */
+static int force_family = AF_UNSPEC;
+
+static int send_size = 16384;
+static int random_size_max;
+/* Per-iteration progress output (-V). Off by default: the
+ * harness captures stdout in a pipe that is not drained until the helper
+ * exits, so unbounded per-record chatter (thousands of lines for the large
+ * echo variants) would fill the pipe, block printf(), stall the echo loop
+ * and surface as a bogus recv timeout on the peer. With -V off a run prints
+ * fixed setup/summary lines, comfortably inside a 64 KiB pipe.
+ */
+static int verbose;
+
+static const char *cipher_name(int cipher)
+{
+	switch (cipher) {
+	case TLS_CIPHER_AES_GCM_128: return "AES-GCM-128";
+	case TLS_CIPHER_AES_GCM_256: return "AES-GCM-256";
+	default: return "unknown";
+	}
+}
+
+static const char *version_name(int version)
+{
+	switch (version) {
+	case TLS_1_2_VERSION: return "TLS 1.2";
+	default: return "unknown";
+	}
+}
+
+static int setup_tls_ulp(int fd)
+{
+	int ret;
+
+	ret = setsockopt(fd, IPPROTO_TCP, TCP_ULP, "tls", sizeof("tls"));
+	if (ret < 0) {
+		printf("SETUP ERROR: TCP_ULP failed: %s\n", strerror(errno));
+		return -1;
+	}
+	return 0;
+}
+
+/* Echo mode drives both directions from a single thread: the
+ * client pushes a whole payload with one blocking send() and only reads the
+ * echo afterwards, while the server blocks in send() mid-echo. If a payload
+ * exceeds the peer's receive window the two sides deadlock - client stuck in
+ * send(), server stuck echoing, neither draining the other. Size the socket
+ * buffers so a full payload always fits in the peer's window (the forward
+ * send() then completes without needing the peer to read concurrently); the
+ * send/recv timeouts armed by set_io_timeouts() turn any residual stall into a
+ * loud EAGAIN instead of a hang.
+ */
+static void configure_echo_socket(int fd, int payload)
+{
+	int want = payload;
+
+	if (want < MIN_BUF_SIZE)
+		want = MIN_BUF_SIZE;
+
+	/* SO_*BUFFORCE bypasses the rmem_max/wmem_max sysctl caps (needs
+	 * CAP_NET_ADMIN); fall back to the best-effort, cap-limited option
+	 * when unprivileged - the timeouts below still turn any resulting
+	 * stall into a loud failure rather than a hang.
+	 */
+	if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &want, sizeof(want)) < 0)
+		setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &want, sizeof(want));
+	if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &want, sizeof(want)) < 0)
+		setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &want, sizeof(want));
+}
+
+/* Arm send/recv timeouts so any unexpected stall fails loudly with EAGAIN
+ * instead of hanging until the harness SIGKILLs us.
+ */
+static void set_io_timeouts(int fd)
+{
+	struct timeval tv = { .tv_sec = 8, .tv_usec = 0 };
+
+	setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
+	setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
+}
+
+/* Send the whole buffer, looping over short counts. A blocking SOCK_STREAM
+ * send() may return fewer bytes than requested (e.g. when SO_SNDTIMEO fires
+ * after partial progress) without setting errno, so a short count is not an
+ * error - only a negative return is.
+ */
+static int send_all(int fd, const char *buf, ssize_t len)
+{
+	ssize_t sent = 0;
+	ssize_t ret;
+
+	while (sent < len) {
+		ret = send(fd, buf + sent, len - sent, 0);
+		if (ret <= 0) {
+			/* 0 for a non-empty request would spin forever. */
+			printf("FAIL: send failed: %s\n",
+			       ret ? strerror(errno) : "no progress");
+			return -1;
+		}
+		sent += ret;
+	}
+	return 0;
+}
+
+static int recv_tls_message(int fd, char *buf, size_t buflen, int *record_type,
+			    int flags)
+{
+	char cmsg_buf[CMSG_SPACE(sizeof(unsigned char))];
+	struct msghdr msg = {0};
+	struct cmsghdr *cmsg;
+	struct iovec iov;
+	int ret;
+
+	iov.iov_base = buf;
+	iov.iov_len = buflen;
+
+	msg.msg_iov = &iov;
+	msg.msg_iovlen = 1;
+	msg.msg_control = cmsg_buf;
+	msg.msg_controllen = sizeof(cmsg_buf);
+
+	ret = recvmsg(fd, &msg, flags);
+	if (ret <= 0)
+		return ret;
+
+	cmsg = CMSG_FIRSTHDR(&msg);
+	if (cmsg && cmsg->cmsg_level == SOL_TLS &&
+	    cmsg->cmsg_type == TLS_GET_RECORD_TYPE)
+		*record_type = *((unsigned char *)CMSG_DATA(cmsg));
+
+	return ret;
+}
+
+static int install_tls_key(int fd, int direction, int cipher)
+{
+	const char *dir = direction == TLS_TX ? "TX" : "RX";
+	int ret;
+
+	if (verbose)
+		printf("Installing TLS_%s %s...\n", dir, cipher_name(cipher));
+
+	if (cipher == TLS_CIPHER_AES_GCM_256) {
+		struct tls12_crypto_info_aes_gcm_256 key;
+
+		memcpy(&key, &tls_info_key0_256, sizeof(key));
+		key.info.version = tls_version;
+		ret = setsockopt(fd, SOL_TLS, direction, &key, sizeof(key));
+	} else {
+		struct tls12_crypto_info_aes_gcm_128 key;
+
+		memcpy(&key, &tls_info_key0_128, sizeof(key));
+		key.info.version = tls_version;
+		ret = setsockopt(fd, SOL_TLS, direction, &key, sizeof(key));
+	}
+
+	if (ret < 0) {
+		printf("SETUP ERROR: TLS_%s %s failed: %s\n",
+		       dir, cipher_name(cipher), strerror(errno));
+		return -1;
+	}
+	printf("TLS_%s %s installed\n", dir, cipher_name(cipher));
+	return 0;
+}
+
+/* Open a TCP connection to server_ip:server_port, switch to the TLS
+ * ULP, and install initial TX/RX keys. Works over IPv4 or
+ * IPv6: getaddrinfo() resolves server_ip (honouring any -4/-6 forced
+ * family and %zone scope IDs in link-local addresses). Returns the fd on
+ * success, -1 on error (with the fd already closed).
+ */
+static int client_connect_tls(void)
+{
+	struct addrinfo hints = {0}, *res, *rp;
+	char port_str[16];
+	int csk = -1;
+	int ret;
+
+	hints.ai_family = force_family;
+	hints.ai_socktype = SOCK_STREAM;
+	hints.ai_protocol = IPPROTO_TCP;
+	snprintf(port_str, sizeof(port_str), "%d", server_port);
+
+	ret = getaddrinfo(server_ip, port_str, &hints, &res);
+	if (ret) {
+		printf("SETUP ERROR: getaddrinfo(%s): %s\n", server_ip,
+		       gai_strerror(ret));
+		return -1;
+	}
+
+	printf("Connecting to %s:%d...\n", server_ip, server_port);
+	for (rp = res; rp; rp = rp->ai_next) {
+		csk = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
+		if (csk < 0)
+			continue;
+		if (connect(csk, rp->ai_addr, rp->ai_addrlen) == 0)
+			break;
+		close(csk);
+		csk = -1;
+	}
+	freeaddrinfo(res);
+
+	if (csk < 0) {
+		printf("SETUP ERROR: connect to %s:%d failed: %s\n",
+		       server_ip, server_port, strerror(errno));
+		return -1;
+	}
+	printf("Connected!\n");
+
+	if (setup_tls_ulp(csk) < 0)
+		goto err;
+
+	if (install_tls_key(csk, TLS_TX, cipher_type) < 0 ||
+	    install_tls_key(csk, TLS_RX, cipher_type) < 0)
+		goto err;
+
+	set_io_timeouts(csk);
+	configure_echo_socket(csk, random_size_max > 0 ?
+				    random_size_max : send_size);
+
+	return csk;
+err:
+	close(csk);
+	return -1;
+}
+
+/* Drain `len` echoed bytes from the server and verify they match the
+ * payload we just sent.
+ */
+static int client_recv_echo(int fd, const char *sent, char *echo_buf,
+			    ssize_t len)
+{
+	ssize_t total = 0;
+	ssize_t n;
+
+	while (total < len) {
+		n = recv(fd, echo_buf + total, len - total, 0);
+		if (n < 0) {
+			printf("FAIL: Echo recv failed: %s\n", strerror(errno));
+			return -1;
+		}
+		if (n == 0) {
+			printf("FAIL: Connection closed during echo\n");
+			return -1;
+		}
+		total += n;
+	}
+
+	if (memcmp(sent, echo_buf, len) != 0) {
+		printf("FAIL: Echo data mismatch!\n");
+		return -1;
+	}
+	if (verbose)
+		printf("Received echo %zd bytes (ok)\n", total);
+	return 0;
+}
+
+static int do_client(void)
+{
+	char *buf = NULL, *echo_buf = NULL;
+	int max_size;
+	int csk = -1, i = 1;
+	int test_result = -1;
+	ssize_t n, total = 0;
+
+	max_size = random_size_max > 0 ? random_size_max : send_size;
+	if (max_size < MIN_BUF_SIZE)
+		max_size = MIN_BUF_SIZE;
+	buf = malloc(max_size);
+	echo_buf = malloc(max_size);
+	if (!buf || !echo_buf) {
+		printf("SETUP ERROR: failed to allocate buffers\n");
+		goto out;
+	}
+
+	csk = client_connect_tls();
+	if (csk < 0)
+		goto out;
+
+	printf("TLS setup complete.\n");
+
+	if (random_size_max > 0)
+		printf("Sending %d messages of random size (1..%d bytes)...\n",
+		       num_iterations, random_size_max);
+	else
+		printf("Sending %d messages of %d bytes...\n",
+		       num_iterations, send_size);
+
+	for (i = 1; i <= num_iterations; i++) {
+		int this_size;
+		int j;
+
+		if (random_size_max > 0)
+			this_size = (rand() % random_size_max) + 1;
+		else
+			this_size = send_size;
+
+		for (j = 0; j < this_size; j++)
+			buf[j] = rand() & 0xFF;
+
+		if (send_all(csk, buf, this_size) < 0)
+			goto out;
+		n = this_size;
+		total += n;
+
+		if (verbose)
+			printf("Sent %zd bytes (iteration %d)\n", n, i);
+		if (client_recv_echo(csk, buf, echo_buf, n) < 0)
+			goto out;
+	}
+
+	test_result = 0;
+out:
+	printf("Sent %d/%d iterations, %zd bytes\n", i - 1, num_iterations,
+	       total);
+	if (csk >= 0)
+		close(csk);
+	free(buf);
+	free(echo_buf);
+	return test_result;
+}
+
+/* Bind/listen on server_port, accept one client, switch to the TLS ULP
+ * and install initial keys.
+ * Returns the connected fd on success and writes the listener fd to
+ * *lsk_out so the caller can close it. Returns -1 on error, with all
+ * intermediate fds already closed and *lsk_out left at -1.
+ */
+static int server_accept_tls(int *lsk_out)
+{
+	struct addrinfo hints = {0}, *res, *rp;
+	int lsk = -1, csk, one = 1;
+	char port_str[16];
+	int ret;
+
+	*lsk_out = -1;
+
+	/* AI_PASSIVE gives a wildcard bind address for the chosen family
+	 * (0.0.0.0 / ::). The family is forced by -4/-6; when unspecified,
+	 * bind the first entry that works.
+	 */
+	hints.ai_family = force_family;
+	hints.ai_socktype = SOCK_STREAM;
+	hints.ai_protocol = IPPROTO_TCP;
+	hints.ai_flags = AI_PASSIVE;
+	snprintf(port_str, sizeof(port_str), "%d", server_port);
+
+	ret = getaddrinfo(NULL, port_str, &hints, &res);
+	if (ret) {
+		printf("SETUP ERROR: getaddrinfo(port %d): %s\n", server_port,
+		       gai_strerror(ret));
+		return -1;
+	}
+
+	for (rp = res; rp; rp = rp->ai_next) {
+		lsk = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
+		if (lsk < 0)
+			continue;
+		setsockopt(lsk, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
+		if (bind(lsk, rp->ai_addr, rp->ai_addrlen) == 0)
+			break;
+		close(lsk);
+		lsk = -1;
+	}
+	freeaddrinfo(res);
+
+	if (lsk < 0) {
+		printf("SETUP ERROR: failed to bind port %d: %s\n",
+		       server_port, strerror(errno));
+		return -1;
+	}
+
+	if (listen(lsk, 1) < 0) {
+		printf("SETUP ERROR: listen failed: %s\n", strerror(errno));
+		close(lsk);
+		return -1;
+	}
+
+	printf("Server listening on port %d\n", server_port);
+	printf("Waiting for client connection...\n");
+
+	/* Bound accept() so a client that never connects (a deploy or connect
+	 * failure on the peer) does not block the server forever. accept()
+	 * honours SO_RCVTIMEO on the listening socket; the client connects
+	 * right after wait_port_listen(), so 10s is generous, and it is well
+	 * inside the 20s the harness waits for the server to exit (the default
+	 * cmd.process() timeout) so the server is gone, and its listening port
+	 * released, before the next variant starts.
+	 */
+	{
+		struct timeval tv = { .tv_sec = 10, .tv_usec = 0 };
+
+		setsockopt(lsk, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
+	}
+
+	csk = accept(lsk, NULL, NULL);
+	if (csk < 0) {
+		if (errno == EAGAIN || errno == EWOULDBLOCK)
+			printf("SETUP ERROR: accept timed out; client never connected\n");
+		else
+			printf("SETUP ERROR: accept failed: %s\n", strerror(errno));
+		close(lsk);
+		return -1;
+	}
+	printf("Client connected!\n");
+
+	if (setup_tls_ulp(csk) < 0)
+		goto err;
+
+	if (install_tls_key(csk, TLS_TX, cipher_type) < 0 ||
+	    install_tls_key(csk, TLS_RX, cipher_type) < 0)
+		goto err;
+
+	set_io_timeouts(csk);
+	configure_echo_socket(csk, random_size_max > 0 ?
+				    random_size_max : send_size);
+
+	*lsk_out = lsk;
+	return csk;
+err:
+	close(csk);
+	close(lsk);
+	return -1;
+}
+
+static int do_server(void)
+{
+	int lsk = -1, csk = -1;
+	ssize_t n, total = 0;
+	int test_result = -1;
+	int recv_count = 0;
+	char *buf = NULL;
+	int record_type = 0;
+	int buf_size;
+
+	buf_size = send_size;
+	if (buf_size < MIN_BUF_SIZE)
+		buf_size = MIN_BUF_SIZE;
+	buf = malloc(buf_size);
+	if (!buf) {
+		printf("SETUP ERROR: failed to allocate buffer\n");
+		goto out;
+	}
+
+	csk = server_accept_tls(&lsk);
+	if (csk < 0)
+		goto out;
+
+	printf("TLS %s setup complete. Receiving...\n",
+	       cipher_name(cipher_type));
+
+	/* Echo everything back; the client verifies each echo. */
+	while (1) {
+		n = recv_tls_message(csk, buf, buf_size, &record_type, 0);
+		if (n == 0) {
+			printf("Connection closed by client\n");
+			break;
+		}
+		if (n < 0) {
+			printf("FAIL: recv failed: %s\n", strerror(errno));
+			goto out;
+		}
+
+		total += n;
+		recv_count++;
+		if (verbose)
+			printf("Received %zd bytes (total: %zd, count: %d)\n",
+			       n, total, recv_count);
+
+		if (send_all(csk, buf, n) < 0)
+			goto out;
+		if (verbose)
+			printf("Echoed %zd bytes back to client\n", n);
+	}
+
+	test_result = 0;
+out:
+	printf("Connection closed. Total received: %zd bytes in %d reads\n",
+	       total, recv_count);
+
+	if (csk >= 0)
+		close(csk);
+	if (lsk >= 0)
+		close(lsk);
+	free(buf);
+	return test_result;
+}
+
+static int send_record_type(int fd)
+{
+	char control[CMSG_SPACE(sizeof(unsigned char))] = {};
+	struct iovec iov = { .iov_base = "BBBB", .iov_len = 4 };
+	struct msghdr msg = {
+		.msg_iov = &iov,
+		.msg_iovlen = 1,
+		.msg_control = control,
+		.msg_controllen = sizeof(control),
+	};
+	struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
+	char ack[2];
+
+	if (send(fd, "AAAA", 4, MSG_MORE) != 4) {
+		printf("FAIL: send MSG_MORE failed: %s\n", strerror(errno));
+		return -1;
+	}
+	cmsg->cmsg_level = SOL_TLS;
+	cmsg->cmsg_type = TLS_SET_RECORD_TYPE;
+	cmsg->cmsg_len = CMSG_LEN(sizeof(unsigned char));
+	*CMSG_DATA(cmsg) = test_record_type;
+	if (sendmsg(fd, &msg, 0) != 4) {
+		printf("FAIL: sendmsg record type failed: %s\n",
+		       strerror(errno));
+		return -1;
+	}
+	return client_recv_echo(fd, "OK", ack, sizeof(ack));
+}
+
+static int expect_record(int fd, const char *data, unsigned char type)
+{
+	char control[CMSG_SPACE(sizeof(unsigned char))] = {};
+	char buf[16];
+	struct iovec iov = { .iov_base = buf, .iov_len = sizeof(buf) };
+	struct msghdr msg = {
+		.msg_iov = &iov,
+		.msg_iovlen = 1,
+		.msg_control = control,
+		.msg_controllen = sizeof(control),
+	};
+	struct cmsghdr *cmsg;
+	int ret;
+
+	ret = recvmsg(fd, &msg, 0);
+	if (ret != 4 || memcmp(buf, data, 4) ||
+	    (msg.msg_flags & (MSG_CTRUNC | MSG_TRUNC)) ||
+	    !(msg.msg_flags & MSG_EOR)) {
+		printf("FAIL: expected record '%s', got %d bytes, flags %#x\n",
+		       data, ret, msg.msg_flags);
+		return -1;
+	}
+	cmsg = CMSG_FIRSTHDR(&msg);
+	if (!cmsg || cmsg->cmsg_level != SOL_TLS ||
+	    cmsg->cmsg_type != TLS_GET_RECORD_TYPE ||
+	    cmsg->cmsg_len != CMSG_LEN(sizeof(unsigned char)) ||
+	    *CMSG_DATA(cmsg) != type) {
+		printf("FAIL: expected record type %u\n", type);
+		return -1;
+	}
+	return 0;
+}
+
+static int recv_record_type(int fd)
+{
+	char buf[16];
+	int ret;
+
+	if (expect_record(fd, "AAAA", TLS_RECORD_TYPE_DATA) ||
+	    expect_record(fd, "BBBB", test_record_type) ||
+	    send_all(fd, "OK", 2))
+		return -1;
+	ret = recv(fd, buf, sizeof(buf), 0);
+	if (ret) {
+		printf("FAIL: expected EOF after records, got %d\n", ret);
+		return -1;
+	}
+	return 0;
+}
+
+static int test_pending_record(int is_server)
+{
+	char *buf = NULL, *echo_buf = NULL;
+	int lsk = -1, csk = -1;
+	int test_result = -1;
+	int i;
+
+	buf = malloc(send_size);
+	echo_buf = malloc(send_size);
+	if (!buf || !echo_buf) {
+		printf("SETUP ERROR: failed to allocate buffers\n");
+		goto out;
+	}
+	memset(buf, 0xa5, send_size);
+
+	csk = is_server ? server_accept_tls(&lsk) : client_connect_tls();
+	if (csk < 0)
+		goto out;
+
+	/* Exercise hardware crypto before testing the record-type transition. */
+	for (i = 0; i < num_iterations; i++) {
+		if (!is_server && send_all(csk, buf, send_size) < 0)
+			goto out;
+		if (client_recv_echo(csk, buf, echo_buf, send_size) < 0)
+			goto out;
+		if (is_server && send_all(csk, buf, send_size) < 0)
+			goto out;
+	}
+
+	test_result = is_server ? recv_record_type(csk) : send_record_type(csk);
+out:
+	if (csk >= 0)
+		close(csk);
+	if (lsk >= 0)
+		close(lsk);
+	free(buf);
+	free(echo_buf);
+	return test_result;
+}
+
+static int parse_int_arg(const char *arg, int min, int max,
+			 const char *name, int *out)
+{
+	char *endp;
+	long val;
+
+	errno = 0;
+	val = strtol(arg, &endp, 10);
+	if (errno || endp == arg || *endp != '\0' || val < min || val > max) {
+		if (max == INT_MAX)
+			printf("ERROR: Invalid %s '%s'. Must be >= %d.\n",
+			       name, arg, min);
+		else
+			printf("ERROR: Invalid %s '%s'. Must be %d..%d.\n",
+			       name, arg, min, max);
+		return -1;
+	}
+	*out = (int)val;
+	return 0;
+}
+
+static int parse_cipher_option(const char *arg)
+{
+	if (strcmp(arg, "128") == 0) {
+		cipher_type = TLS_CIPHER_AES_GCM_128;
+		return 0;
+	} else if (strcmp(arg, "256") == 0) {
+		cipher_type = TLS_CIPHER_AES_GCM_256;
+		return 0;
+	}
+	printf("ERROR: Invalid cipher '%s'. Must be 128 or 256.\n", arg);
+	return -1;
+}
+
+static int parse_version_option(const char *arg)
+{
+	if (strcmp(arg, "1.2") == 0) {
+		tls_version = TLS_1_2_VERSION;
+		return 0;
+	}
+	printf("ERROR: Invalid TLS version '%s'. Must be 1.2.\n", arg);
+	return -1;
+}
+
+static void print_usage(const char *prog)
+{
+	printf("TLS Hardware Offload Two-Node Test\n\n");
+	printf("Usage:\n");
+	printf("  %s server [OPTIONS]\n", prog);
+	printf("  %s client -s <ip> [OPTIONS]\n", prog);
+	printf("\nOptions:\n");
+	printf("  -s <ip>       Server IP address, v4 or v6 (client, required)\n");
+	printf("  -p <port>     Server port (default: 4433)\n");
+	printf("  -4            Force IPv4 (default: auto/either)\n");
+	printf("  -6            Force IPv6 (default: auto/either)\n");
+	printf("  -b <size>     Send buffer size in bytes (default: 16384)\n");
+	printf("  -r <max>      Use random send buffer sizes (1..<max>)\n");
+	printf("  -v <version>  TLS version: 1.2 (default: 1.2)\n");
+	printf("  -c <cipher>   Cipher: 128 or 256 (default: 128)\n");
+	printf("  -n <N>        Number of send/echo iterations (default: 100)\n");
+	printf("  -t <type>     Test MSG_MORE followed by alert (21) or handshake (22)\n");
+	printf("  -V            Verbose: log every iteration\n");
+	printf("  -h            Show this help message\n");
+	printf("\nExample:\n");
+	printf("  Node A: %s server\n", prog);
+	printf("  Node B: %s client -s 192.168.20.2\n", prog);
+	printf("\nIPv6 Example:\n");
+	printf("  Node A: %s server -6\n", prog);
+	printf("  Node B: %s client -6 -s fd00::2\n", prog);
+}
+
+int main(int argc, char *argv[])
+{
+	int send_size_set = 0;
+	int is_server;
+	int opt;
+
+	/* When the peer aborts a TLS connection (e.g. tls_err_abort() on a
+	 * failed decrypt), a send() here would raise SIGPIPE and kill us by
+	 * signal, so the harness sees only a bare non-zero exit with no
+	 * "FAIL:" line. Ignore it and let send()/sendmsg() return EPIPE, which
+	 * send_all()/send_record_type() report.
+	 */
+	signal(SIGPIPE, SIG_IGN);
+
+	if (argc < 2 ||
+	    (strcmp(argv[1], "server") && strcmp(argv[1], "client"))) {
+		print_usage(argv[0]);
+		return 1;
+	}
+	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) {
+		switch (opt) {
+		case 's':
+			server_ip = optarg;
+			break;
+		case 'V':
+			verbose = 1;
+			break;
+		case '4':
+			if (force_family == AF_INET6) {
+				printf("ERROR: -4 and -6 are mutually exclusive\n");
+				return 1;
+			}
+			force_family = AF_INET;
+			break;
+		case '6':
+			if (force_family == AF_INET) {
+				printf("ERROR: -4 and -6 are mutually exclusive\n");
+				return 1;
+			}
+			force_family = AF_INET6;
+			break;
+		case 'p':
+			if (parse_int_arg(optarg, 1, 65535, "port",
+					  &server_port) < 0)
+				return 1;
+			break;
+		case 'b':
+			if (parse_int_arg(optarg, 1, INT_MAX, "buffer size",
+					  &send_size) < 0)
+				return 1;
+			send_size_set = 1;
+			break;
+		case 'r':
+			if (parse_int_arg(optarg, 1, INT_MAX, "random size",
+					  &random_size_max) < 0)
+				return 1;
+			break;
+		case 'c':
+			if (parse_cipher_option(optarg) < 0)
+				return 1;
+			break;
+		case 'v':
+			if (parse_version_option(optarg) < 0)
+				return 1;
+			break;
+		case 't':
+			if (parse_int_arg(optarg, TLS_RECORD_TYPE_ALERT,
+					  TLS_RECORD_TYPE_HANDSHAKE, "record type",
+					  &test_record_type) < 0)
+				return 1;
+			break;
+		case 'n':
+			/* The iteration loops use an inclusive int bound
+			 * (i <= num_iterations), so INT_MAX itself would
+			 * overflow the counter instead of terminating.
+			 */
+			if (parse_int_arg(optarg, 1, INT_MAX - 1,
+					  "iteration count",
+					  &num_iterations) < 0)
+				return 1;
+			break;
+		case 'h':
+			print_usage(argv[0]);
+			return 0;
+		default:
+			print_usage(argv[0]);
+			return 1;
+		}
+	}
+
+	if (send_size_set && random_size_max > 0) {
+		printf("ERROR: -b and -r are mutually exclusive\n");
+		return 1;
+	}
+
+	if (test_record_type && random_size_max) {
+		printf("ERROR: -t cannot be combined with -r\n");
+		return 1;
+	}
+
+	if (is_server) {
+		if (server_ip) {
+			printf("warning: -s is ignored in server mode\n");
+			server_ip = NULL;
+		}
+		if (random_size_max > 0) {
+			printf("warning: -r is ignored in server mode\n");
+			random_size_max = 0;
+		}
+	} else {
+		if (!server_ip) {
+			printf("ERROR: Client requires -s <ip> option\n");
+			return 1;
+		}
+	}
+
+	printf("TLS Version: %s\n", version_name(tls_version));
+	printf("Cipher: %s\n", cipher_name(cipher_type));
+	printf("Address family: %s\n",
+	       force_family == AF_INET ? "IPv4" :
+	       force_family == AF_INET6 ? "IPv6" : "auto");
+	if (random_size_max > 0)
+		printf("Buffer size: random (1..%d)\n", random_size_max);
+	else
+		printf("Buffer size: %d\n", send_size);
+
+	srand(time(NULL));
+
+	if (test_record_type)
+		return test_pending_record(is_server) ? 1 : 0;
+
+	if (is_server)
+		return do_server() ? 1 : 0;
+
+	return do_client() ? 1 : 0;
+}
diff --git a/tools/testing/selftests/drivers/net/hw/tls_hw_offload.py b/tools/testing/selftests/drivers/net/hw/tls_hw_offload.py
new file mode 100755
index 0000000000000..37f26e21a7b78
--- /dev/null
+++ b/tools/testing/selftests/drivers/net/hw/tls_hw_offload.py
@@ -0,0 +1,402 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-2.0
+
+"""Test kTLS hardware offload using a C helper binary."""
+
+import re
+import shlex
+import subprocess
+from collections import defaultdict
+
+from lib.py import ksft_run, ksft_exit, ksft_pr, KsftSkipEx
+from lib.py import ksft_ge, ksft_eq
+from lib.py import ksft_variants, KsftNamedVariant
+from lib.py import NetDrvEpEnv
+from lib.py import cmd, bkg, wait_port_listen, rand_port
+from lib.py import CmdExitFailure
+
+# Reading /proc/net/tls_stat is trivial locally, but on the remote it runs
+# over ssh, where connection setup can occasionally spike past the short
+# default cmd() timeout. Give these tiny reads plenty of headroom so a slow
+# ssh round-trip doesn't fail an otherwise-good variant.
+STATS_TIMEOUT_S = 30
+
+# `ethtool -S` counters on the DUT NIC, from the minimum set every TLS
+# offload driver should report (Documentation/networking/tls-offload.rst,
+# "Statistics"); mlx5, nfp, cxgb4 and funeth use exactly these names.
+# TlsTxDevice/TlsRxDevice in /proc/net/tls_stat only prove tls_dev_add()
+# accepted the offload:
+#  - *_packets increment once per packet the NIC actually encrypted or
+#    decrypted (mlx5 counts gso_segs, not records), so they prove the HW
+#    crypto path was exercised.
+#  - *_ctx increment once per tls_dev_add().
+# Missing NIC crypto counters remain optional.
+HW_NIC_COUNTERS = {
+    'Tx': {'crypto': 'tx_tls_encrypted_packets', 'ctx': 'tx_tls_ctx'},
+    'Rx': {'crypto': 'rx_tls_decrypted_packets', 'ctx': 'rx_tls_ctx'},
+}
+
+
+def check_tls_support(cfg):
+    """Require kTLS on both hosts and at least one DUT HW direction."""
+    # The tls module is autoloaded lazily on the first TCP_ULP="tls"
+    # setsockopt, so /proc/net/tls_stat (created from the module's pernet
+    # init) may not exist yet on a freshly booted host. Load the module
+    # explicitly before probing for it. Best effort only: with CONFIG_TLS=y
+    # (what the config fragment asks for) there is nothing to load, and
+    # modprobe may fail for reasons unrelated to kTLS (no modules.dep for a
+    # locally built kernel, no modprobe on a minimal rootfs). The
+    # /proc/net/tls_stat probe below is the authoritative check. Locally,
+    # cmd() runs without a shell, so a missing modprobe raises
+    # FileNotFoundError rather than returning a failed exit status.
+    try:
+        cmd("modprobe tls", fail=False)
+    except FileNotFoundError:
+        pass
+    cmd("modprobe tls", host=cfg.remote, fail=False)
+    try:
+        cmd("test -f /proc/net/tls_stat")
+        cmd("test -f /proc/net/tls_stat", host=cfg.remote)
+    except CmdExitFailure as e:
+        raise KsftSkipEx(f"kTLS not supported: {e}") from e
+
+    try:
+        features = cmd(f"ethtool -k {cfg.ifname}").stdout
+    except CmdExitFailure as e:
+        raise KsftSkipEx(f"Cannot determine TLS HW offload support: {e}") from e
+    cfg.tls_hw_directions = {
+        direction for direction in ('Tx', 'Rx')
+        if f'tls-hw-{direction.lower()}-offload: on' in features
+    }
+    if not cfg.tls_hw_directions:
+        raise KsftSkipEx("Device has no enabled TLS HW offload direction")
+
+
+def read_tls_stats(host=None):
+    """Snapshot the per-netns TLS MIB from /proc/net/tls_stat as a dict."""
+    # /proc/net/tls_stat exposes the per-netns TLS MIB (TLS_INC_STATS on
+    # sock_net(sk)). The test runs on a real NIC in the host namespace, so
+    # these counters are shared with anything else doing kTLS there. The
+    # strict before/after delta checks (zero error counters) assume no other
+    # kTLS activity in this namespace during a
+    # variant's window; concurrent kTLS users would perturb the deltas and
+    # cause spurious failures. Don't run other kTLS workloads alongside this
+    # test.
+    stats = defaultdict(int)
+    output = cmd("cat /proc/net/tls_stat", host=host, timeout=STATS_TIMEOUT_S)
+    for line in output.stdout.strip().split('\n'):
+        parts = line.split()
+        if len(parts) == 2:
+            stats[parts[0]] = int(parts[1])
+    return stats
+
+
+def read_nic_stats(cfg):
+    """Snapshot the DUT NIC's `ethtool -S` counters as a dict."""
+    # Driver per-record TLS counters from `ethtool -S` on the DUT NIC. Same
+    # before/after-delta caveat as read_tls_stats(): these are device-wide,
+    # so concurrent kTLS traffic on this NIC would perturb the deltas.
+    stats = defaultdict(int)
+    output = cmd(f"ethtool -S {cfg.ifname}").stdout
+    for line in output.strip().split('\n'):
+        key, sep, val = line.partition(':')
+        if sep and val.strip().isdigit():
+            stats[key.strip()] = int(val.strip())
+    return stats
+
+
+def stat_diff(before, after, key):
+    """Return the delta of counter `key` between two stat snapshots."""
+    return after[key] - before[key]
+
+
+def check_hw_crypto(cfg, nic_before, nic_after, hw_directions):
+    """Check DUT hardware crypto and initial key installs."""
+    for direction in hw_directions:
+        names = HW_NIC_COUNTERS[direction]
+
+        key = names['crypto']
+        if key in nic_after:
+            got = stat_diff(nic_before, nic_after, key)
+            ksft_ge(got, 1,
+                    comment=f"DUT {direction}: NIC reported no HW crypto "
+                            f"({key}={got})")
+        else:
+            ksft_pr(f"NOTE: DUT {direction}: '{key}' not exposed by "
+                    f"{cfg.ifname}, skipping HW crypto check")
+
+        key = names['ctx']
+        if key not in nic_after:
+            ksft_pr(f"NOTE: DUT {direction}: '{key}' not exposed by "
+                    f"{cfg.ifname}, skipping NIC context count check")
+            continue
+        ctx = stat_diff(nic_before, nic_after, key)
+        ksft_ge(ctx, 1,
+                comment=f"DUT {direction}: no HW context installed "
+                        f"({key}={ctx})")
+
+
+def check_path(before, after, direction, role, require_hw):
+    """Require HW for enabled DUT directions; otherwise HW or SW is fine."""
+    dev = stat_diff(before, after, f'Tls{direction}Device')
+    sw = stat_diff(before, after, f'Tls{direction}Sw')
+    if require_hw:
+        ksft_ge(dev, 1,
+                comment=f"{role} {direction}: HW offload not engaged "
+                        f"(Device={dev}, Sw={sw})")
+    else:
+        ksft_ge(dev + sw, 1,
+                comment=f"{role} {direction}: no TLS activity "
+                        f"(Device={dev}, Sw={sw})")
+
+
+def verify_tls_counters(stats_before, stats_after, is_dut, hw_directions=()):
+    """Verify TLS counters on one side of the connection.
+
+    is_dut: True for the local DUT.
+    hw_directions: DUT directions with enabled HW offload; other directions
+           may use SW kTLS but still undergo activity and error checks.
+    """
+    role = 'DUT' if is_dut else 'Peer'
+
+    # Echo mode drives both directions on both sides.
+    for direction in ('Tx', 'Rx'):
+        check_path(stats_before, stats_after, direction, role,
+                   require_hw=is_dut and direction in hw_directions)
+
+    ksft_eq(stat_diff(stats_before, stats_after, 'TlsDecryptError'), 0,
+            comment=f"{role}: TlsDecryptError expected 0")
+
+
+def stop_helper(helper):
+    """Reap a helper that is still running: SIGTERM, then SIGKILL.
+
+    cmd.process(terminate=True) sends SIGTERM and waits; if the process
+    ignores it there is no fallback and communicate() raises again from the
+    cleanup path, leaving the child alive. Escalate to SIGKILL instead.
+    """
+    try:
+        helper.process(terminate=True, fail=False, timeout=5)
+    except subprocess.TimeoutExpired:
+        helper.proc.kill()
+        helper.process(terminate=False, fail=False, timeout=5)
+
+
+def kill_remote_helper(cfg, helper_cmd):
+    """Stop this variant's remote helper and confirm that it has exited.
+
+    Signalling cmd.proc only reaches the local process, which for the ssh
+    backend is the ssh client, not the helper on the peer. Losing its stdout
+    does not stop the helper either: it ignores SIGPIPE so that a peer abort
+    is reported as EPIPE instead of a bare signal death. Left alone it keeps
+    driving kTLS (bumping the peer's TLS MIBs) into the next variant's
+    measurement window, or sits in accept() for the rest of its own timeout.
+    Match the complete command, including this variant's port, since the
+    netns backend uses the same binary path for both endpoints and other
+    runs. The anchors also exclude the shell executing the cleanup. Failure
+    to confirm exit must prevent later variants from taking counter
+    snapshots.
+    """
+    pattern = shlex.quote('^' + re.escape(helper_cmd) + '$')
+    cmd(f"""
+command -v pkill >/dev/null && command -v pgrep >/dev/null || exit 2
+for tls_signal in TERM KILL; do
+    pkill -"$tls_signal" -f -- {pattern}
+    tls_status=$?
+    [ "$tls_status" -le 1 ] || exit "$tls_status"
+    tls_attempt=0
+    while [ "$tls_attempt" -lt 50 ]; do
+        pgrep -f -- {pattern} >/dev/null
+        tls_status=$?
+        case "$tls_status" in
+            1) exit 0 ;;
+            0) ;;
+            *) exit "$tls_status" ;;
+        esac
+        sleep 0.1
+        tls_attempt=$((tls_attempt + 1))
+    done
+done
+echo 'TLS helper still running after SIGKILL' >&2
+exit 1
+""", host=cfg.remote, timeout=STATS_TIMEOUT_S)
+
+
+def run_tls_test(cfg, cipher="128", tls_version="1.2",
+                 buffer_size=None, random_max=None, ipver="4",
+                 record_type=None):
+    """Run the TLS offload test.
+
+    The DUT runs the TLS client and the remote runs the echo server.
+
+    ipver: '4' or '6' - IP version to run over. The C helper is forced to the
+           matching family with -4/-6 and connects to the peer's v4/v6 address.
+           Variants requesting '6' skip cleanly when the environment lacks IPv6
+           connectivity (require_ipver()).
+
+    The DUT (local) is the kernel under test; the remote is just a traffic
+    source/sink and may run any kernel without HW offload. Both sides run
+    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.
+    """
+    if cfg.cleanup_failed:
+        raise KsftSkipEx("Previous helper cleanup could not be confirmed")
+
+    cfg.require_ipver(ipver)
+
+    # Echo exercises both directions, allowing SW in a direction without
+    # HW support.
+    hw_directions = tuple(d for d in ('Tx', 'Rx') if d in cfg.tls_hw_directions)
+
+    if record_type and 'Tx' not in hw_directions:
+        raise KsftSkipEx("Record-type regression requires DUT TLS TX offload")
+
+    port = rand_port()
+    send_size = random_max or buffer_size
+
+    server_parts = [f"{cfg.bin_remote} server -p {port} -c {cipher}",
+                    f"-v {tls_version}", f"-{ipver}"]
+    if send_size:
+        server_parts.append(f"-b {send_size}")
+    if record_type:
+        server_parts.append(f"-t {record_type}")
+    server_cmd = " ".join(server_parts)
+
+    client_parts = [f"{cfg.bin_local} client -s {cfg.remote_addr_v[ipver]}",
+                    f"-p {port} -c {cipher} -v {tls_version} -{ipver}"]
+    if random_max:
+        client_parts.append(f"-r {random_max}")
+    elif buffer_size:
+        client_parts.append(f"-b {buffer_size}")
+    if record_type:
+        client_parts.append(f"-t {record_type}")
+    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)
+
+    # Both helpers run with their stdout captured in a pipe that is only
+    # drained once they exit, so the helper keeps its per-connection output
+    # small (see the note on verbose in tls_hw_offload.c); do not pass -V.
+    #
+    # On the failure path make sure nothing outlives the variant: a leaked
+    # helper keeps bumping the per-netns TLS counters (TlsDecryptError, ...)
+    # and would corrupt the before/after measurement
+    # window of a later variant. The local client is a direct child; the
+    # server on the peer needs kill_remote_helper().
+    server = None
+    client = None
+    try:
+        server = bkg(server_cmd, host=cfg.remote, exit_wait=True)
+        with server:
+            wait_port_listen(port, host=cfg.remote)
+            # Start the client in the background so we keep a handle to it.
+            # A foreground cmd() raises TimeoutExpired from inside its
+            # constructor if the client hangs, and since the child is not
+            # killed on timeout it would be left running with no handle to
+            # reap it.
+            client = cmd(client_cmd, background=True)
+            try:
+                client.process(terminate=False, fail=True, timeout=20)
+            finally:
+                if client.proc.poll() is None:
+                    stop_helper(client)
+    except BaseException:
+        # bkg.__exit__ reaps the server with a plain 20 s communicate()
+        # (SIGTERM first only on an exception). A server that hangs or
+        # ignores SIGTERM makes it raise TimeoutExpired with the process
+        # still alive; escalate to SIGKILL as for the client.
+        cfg.cleanup_failed = True
+        try:
+            try:
+                if client is not None and client.proc.poll() is None:
+                    stop_helper(client)
+            finally:
+                if server is not None and server.proc.poll() is None:
+                    stop_helper(server)
+        finally:
+            kill_remote_helper(cfg, server_cmd)
+        cfg.cleanup_failed = False
+        raise
+
+    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)
+
+    verify_tls_counters(stats_before_local, stats_after_local, is_dut=True,
+                        hw_directions=hw_directions)
+    check_hw_crypto(cfg, nic_before, nic_after, hw_directions)
+    verify_tls_counters(stats_before_remote, stats_after_remote, is_dut=False)
+
+
+# Drivers whose tls_dev_add() accepts only AES-GCM-128: nfp
+# (nfp_net_cipher_supported()), cxgb4 (chcr_ktls), funeth.
+GCM128_ONLY_DRIVERS = {"nfp", "nfp_netvf", "cxgb4", "funeth"}
+
+
+# The cipher/version matrix runs over IPv4; the socket setup is the only
+# IP-version-specific code path, so a single representative variant over
+# IPv6 is enough to cover it (it skips cleanly without v6 connectivity).
+# The suites below likewise stay on IPv4 to bound runtime.
+@ksft_variants([
+    KsftNamedVariant("tls12_aes128", "128", "1.2", "4"),
+    KsftNamedVariant("tls12_aes256", "256", "1.2", "4"),
+    KsftNamedVariant("tls12_aes128_ip6", "128", "1.2", "6"),
+])
+def test_tls_offload(cfg, cipher, tls_version, ipver):
+    """Cipher/version matrix over the HW offload data path."""
+    # The tls-hw-{tx,rx}-offload feature bits do not advertise cipher
+    # support, and there is no uAPI to query it. Skip AES-GCM-256 on drivers
+    # whose tls_dev_add() accepts only AES-GCM-128; keep the HW assertions
+    # for every other driver/cipher pair.
+    if tls_version == "1.2" and cipher == "256":
+        info = cmd(f"ethtool -i {cfg.ifname}", fail=False).stdout
+        for line in info.splitlines():
+            name, _, value = line.partition(':')
+            driver = value.strip()
+            if name.strip() == 'driver' and driver in GCM128_ONLY_DRIVERS:
+                raise KsftSkipEx(f"{driver} TLS offload supports only AES-GCM-128")
+
+    run_tls_test(cfg, cipher=cipher, tls_version=tls_version, ipver=ipver)
+
+
+@ksft_variants([
+    KsftNamedVariant("small_buf", 512),
+    KsftNamedVariant("large_buf", 2097152),
+    KsftNamedVariant("random_buf", None, 8192),
+])
+def test_tls_offload_sizes(cfg, buffer_size=None, random_max=None):
+    """Echo-mode TLS 1.2 across a range of buffer sizes."""
+    run_tls_test(cfg, cipher="128", tls_version="1.2",
+                 buffer_size=buffer_size, random_max=random_max)
+
+
+@ksft_variants([
+    KsftNamedVariant("handshake", 22),
+    KsftNamedVariant("alert", 21),
+])
+def test_tls_offload_record_type(cfg, record_type):
+    """RX setup must preserve the HW TX hook which flushes an open record."""
+    run_tls_test(cfg, record_type=record_type)
+
+
+def main() -> None:
+    """Set up the DUT/peer environment and run the offload test suites."""
+    with NetDrvEpEnv(__file__, nsim_test=False) as cfg:
+        cfg.bin_local = cfg.test_dir / "tls_hw_offload"
+        if not cfg.bin_local.exists():
+            raise KsftSkipEx(f"tls_hw_offload binary not found at {cfg.bin_local}")
+        cfg.bin_remote = cfg.remote.deploy(cfg.bin_local)
+        check_tls_support(cfg)
+        cfg.cleanup_failed = False
+
+        ksft_run([test_tls_offload, test_tls_offload_sizes,
+                  test_tls_offload_record_type], args=(cfg, ))
+    ksft_exit()
+
+
+if __name__ == "__main__":
+    main()

3/2 2026/10/21 04:12 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 20443
							output: 38
							thoughts: 483
						

Thoughts:
**Evaluating the Commit for Fuzzing Potential**

Okay, so I need to decide if this commit warrants a syzkaller fuzzing campaign. My initial thought process involves a file-by-file inspection. First, `MAINTAINERS` is documentation; likely not interesting from a fuzzing perspective, so I'll ignore that. Then, I see `net/tls/tls_sw.c`, which is kernel code, so *that* is certainly worth a deeper look. The diff shows a conditional assignment of `ctx->push_pending_record`. Interesting. This looks like it's guarding the assignment of `tls_sw_push_pending_record` based on the `tx` flag.  I'll want to understand the context of that function call, how `tx` is derived, and what implications the conditional assignment has on the control flow. The commit summary looks like:

```diff
--- a/net/tls/tls_sw.c
+++ b/net/tls/tls_sw.c
@@ -2591,7 +2591,8 @@ int tls_set_sw_offload(struct sock *sk, int tx,
 		}
 	}
 
-	ctx->push_pending_record = tls_sw_push_pending_record;
+	if (tx)
+		ctx->push_pending_record = tls_sw_push_pending_record;
 
 	/* setkey is the last operation that could fail during a
 	 * rekey. if it succeeds, we can start modifying the
```

The rest of the file list seems to be related to selftests, specifically hardware offload tests for TLS: `tools/testing/selftests/drivers/net/README.rst`, `tools/testing/selftests/drivers/net/hw/.gitignore`, `tools/testing/selftests/drivers/net/hw/Makefile`, `tools/testing/selftests/drivers/net/hw/config`, `tools/testing/selftests/drivers/net/hw/tls_hw_offload.c`, and `tools/testing/selftests/drivers/net/hw/tls_hw_offload.py`. The presence of these tests *could* be a good sign, implying that this code path is actively being tested, but the tests themselves might also be useful for generating new fuzzing targets.

To proceed, I need to understand the function `tls_set_sw_offload` and how the `tx` parameter is used and what is affected by the conditional assignment.  I'm going to quickly use a `read-file` command to see the surrounding code in `net/tls/tls_sw.c` around line 2591. This will give me some context to the change.



4/2 2026/10/21 04:12 tool read-file
0m Args:
{
  "File": "net/tls/tls_sw.c",
  "FirstLine": 2560,
  "LineCount": 60
}

Results:
{
  "Contents": "2560:\t\t\taead = \u0026sw_ctx_tx-\u003eaead_send;\n2561:\t\t} else {\n2562:\t\t\tsw_ctx_rx = ctx-\u003epriv_ctx_rx;\n2563:\t\t\tcrypto_info = \u0026ctx-\u003ecrypto_recv.info;\n2564:\t\t\tcctx = \u0026ctx-\u003erx;\n2565:\t\t\taead = \u0026sw_ctx_rx-\u003eaead_recv;\n2566:\t\t}\n2567:\t\n2568:\t\tsrc_crypto_info = new_crypto_info ?: crypto_info;\n2569:\t\n2570:\t\tcipher_desc = get_cipher_desc(src_crypto_info-\u003ecipher_type);\n2571:\t\tif (!cipher_desc) {\n2572:\t\t\trc = -EINVAL;\n2573:\t\t\tgoto free_priv;\n2574:\t\t}\n2575:\t\n2576:\t\trc = init_prot_info(prot, src_crypto_info, cipher_desc);\n2577:\t\tif (rc)\n2578:\t\t\tgoto free_priv;\n2579:\t\n2580:\t\tiv = crypto_info_iv(src_crypto_info, cipher_desc);\n2581:\t\tkey = crypto_info_key(src_crypto_info, cipher_desc);\n2582:\t\tsalt = crypto_info_salt(src_crypto_info, cipher_desc);\n2583:\t\trec_seq = crypto_info_rec_seq(src_crypto_info, cipher_desc);\n2584:\t\n2585:\t\tif (!*aead) {\n2586:\t\t\t*aead = crypto_alloc_aead(cipher_desc-\u003ecipher_name, 0, 0);\n2587:\t\t\tif (IS_ERR(*aead)) {\n2588:\t\t\t\trc = PTR_ERR(*aead);\n2589:\t\t\t\t*aead = NULL;\n2590:\t\t\t\tgoto free_priv;\n2591:\t\t\t}\n2592:\t\t}\n2593:\t\n2594:\t\tif (tx)\n2595:\t\t\tctx-\u003epush_pending_record = tls_sw_push_pending_record;\n2596:\t\n2597:\t\t/* setkey is the last operation that could fail during a\n2598:\t\t * rekey. if it succeeds, we can start modifying the\n2599:\t\t * context.\n2600:\t\t */\n2601:\t\trc = crypto_aead_setkey(*aead, key, cipher_desc-\u003ekey);\n2602:\t\tif (rc) {\n2603:\t\t\tif (new_crypto_info)\n2604:\t\t\t\tgoto out;\n2605:\t\t\telse\n2606:\t\t\t\tgoto free_aead;\n2607:\t\t}\n2608:\t\n2609:\t\tif (!new_crypto_info) {\n2610:\t\t\trc = crypto_aead_setauthsize(*aead, prot-\u003etag_size);\n2611:\t\t\tif (rc)\n2612:\t\t\t\tgoto free_aead;\n2613:\t\t}\n2614:\t\n2615:\t\tif (!tx \u0026\u0026 !new_crypto_info) {\n2616:\t\t\ttfm = crypto_aead_tfm(sw_ctx_rx-\u003eaead_recv);\n2617:\t\n2618:\t\t\ttls_update_rx_zc_capable(ctx);\n2619:\t\t\tsw_ctx_rx-\u003easync_capable =\n"
}

5/2 2026/10/21 04:12 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 22495
							output: 19
							thoughts: 135
						

Thoughts:
**Analyzing a Subtle TLS Optimization**

Okay, so I'm looking at this `tls_set_sw_offload` function, specifically this line: `tls_set_sw_offload(struct sock *sk, int tx, ...)` That's interesting. I immediately notice a change. Before this patch, the code unconditionally set `ctx->push_pending_record = tls_sw_push_pending_record;`. Now, it's conditional: `if (tx) ctx->push_pending_record = tls_sw_push_pending_record;`

My mind immediately starts ticking. Why the change? This means something significant had to be happening in the original logic. We've got a conditional now! The fact that `tx` is the deciding variable is a clue. This must affect how TLS records are handled. The original code was likely always setting the software TLS function. Now it's probably been optimized to only set the software method only in the tx case.

To really understand the implications, I need to know where `ctx->push_pending_record` is actually *used* and set. I'm going to quickly grep for that symbol to see all its call sites, how it is set, and where it is being used in the codebase.



6/2 2026/10/21 04:12 tool grepper
0m Args:
{
  "Expression": "push_pending_record"
}

Results:
{
  "Output": "include/net/tls.h=227=struct tls_context {\n--\ninclude/net/tls.h-236-\ninclude/net/tls.h:237:\tint (*push_pending_record)(struct sock *sk, int flags);\ninclude/net/tls.h-238-\tvoid (*sk_write_space)(struct sock *sk);\n--\nnet/tls/tls_device.c=674=EXPORT_SYMBOL(tls_get_record);\nnet/tls/tls_device.c-675-\nnet/tls/tls_device.c:676:static int tls_device_push_pending_record(struct sock *sk, int flags)\nnet/tls/tls_device.c-677-{\n--\nnet/tls/tls_device.c=1065=int tls_set_device_offload(struct sock *sk)\n--\nnet/tls/tls_device.c-1137-\tclean_acked_data_enable(tcp_sk(sk), \u0026tls_tcp_clean_acked);\nnet/tls/tls_device.c:1138:\tctx-\u003epush_pending_record = tls_device_push_pending_record;\nnet/tls/tls_device.c-1139-\n--\nnet/tls/tls_main.c=226=static int tls_handle_open_record(struct sock *sk, int flags)\n--\nnet/tls/tls_main.c-230-\tif (tls_is_pending_open_record(ctx))\nnet/tls/tls_main.c:231:\t\treturn ctx-\u003epush_pending_record(sk, flags);\nnet/tls/tls_main.c-232-\n--\nnet/tls/tls_sw.c=701=static int bpf_exec_tx_verdict(struct sk_msg *msg, struct sock *sk,\n--\nnet/tls/tls_sw.c-714-\nnet/tls/tls_sw.c:715:static int tls_sw_push_pending_record(struct sock *sk, int flags)\nnet/tls/tls_sw.c-716-{\n--\nnet/tls/tls_sw.c=1031=void tls_sw_splice_eof(struct socket *sock)\n--\nnet/tls/tls_sw.c-1048-retry:\nnet/tls/tls_sw.c:1049:\t/* same checks as in tls_sw_push_pending_record() */\nnet/tls/tls_sw.c-1050-\trec = ctx-\u003eopen_rec;\n--\nnet/tls/tls_sw.c=2525=int tls_set_sw_offload(struct sock *sk, int tx,\n--\nnet/tls/tls_sw.c-2594-\tif (tx)\nnet/tls/tls_sw.c:2595:\t\tctx-\u003epush_pending_record = tls_sw_push_pending_record;\nnet/tls/tls_sw.c-2596-\n"
}

7/2 2026/10/21 04:12 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 23679
							output: 40
							thoughts: 792
						

Thoughts:
**Analyzing a kTLS Offload Issue**

Okay, let's break this down. First, I wanted to understand the commit, so I initially thought about reaching for `git log`, but I realized I don't have that tool directly available in this context. No worries, I can find the information another way; perhaps a search or by examining commit messages and the relevant code.

My first thought was to check `tools/testing/selftests/drivers/net/README.rst` as a starting point. And yes, it describes record-type cases that require DUT TX offload. It highlights the use of `TLS_RX` after `TLS_TX` and the buffering of application data with `MSG_MORE`. It touches on testing both record types and payloads. The description mentions RX offload and TX offload and how to cover hardware RX and software RX.

Then, I shifted my attention to `tls_hw_offload.py`. There's a `test_tls_offload_record_type` function, which implies something related to RX setup needing to preserve the HW TX hook. I found `run_tls_test` and it looks like record types might play a key role.

Aha! Now I see what's happening. The core issue is with how `ctx->push_pending_record` gets managed during hardware TX offload. Specifically, when hardware TX offload is enabled (`tls_set_device_offload`), it sets `ctx->push_pending_record` to `tls_device_push_pending_record`. However, when `tls_set_sw_offload` is later called with `tx = 0` (for installing TLS_RX with software offload on the *same* socket), it used to unconditionally overwrite `ctx->push_pending_record` with the software version, `tls_sw_push_pending_record`. This is where the potential corruption lies.

Basically, if TX was hardware offload, and RX set SW offload, the `push_pending_record` function that would get called was the *software* version! This means that setting up software RX could corrupt the hardware TX. Conversely, if TX was software and RX was software, when TX was 1, it sets the `ctx->push_pending_record` to the software version, and when RX is set (tx == 0), it doesn't set it.

Now, let's carefully evaluate the reachability and fuzzability of this potential bug. This is kTLS (net/tls)! I am confident that kTLS is reachable in standard syzkaller environments. Any user can create a TCP socket, set the `TCP_ULP` sockopt to "tls", and set `SOL_TLS` options like `TLS_TX` and `TLS_RX`. Fantastic!

I know syzkaller heavily fuzzes kTLS. It has descriptions for TLS, and it can configure TLS TX and TLS RX via `setsockopt$inet_tcp_TLS_TX` / `TLS_RX`, etc. Great!

Okay, is this hardware specific? No. `net/tls/tls_sw.c` is the *software* kTLS implementation.

Finally, regarding hardware offload, does syzkaller test netdevsim? Can netdevsim emulate TLS device offload? Let me see… I should probably check for any mentions of `tls_dev_add` or netdevsim in `drivers/net/netdevsim`.



8/2 2026/10/21 04:12 tool grepper
0m Error:
no matches

Args:
{
  "Expression": "tls_dev_add|tls_dev_ops",
  "PathPrefixes": [
    "drivers/net/netdevsim/"
  ]
}

Results:
{
  "error": "no matches"
}

9/2 2026/10/21 04:12 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 25265
							output: 30
							thoughts: 14
						

Thoughts:
Okay, here's my take on those thoughts, tailored for an expert audience:

**Grasping for Context: `netdevsim` and `tls`**

Alright, my brain's kicking into gear. My initial thought process is this: I'm presented with "netdevsim" and "tls". Both terms are pretty specialized, but familiar. First, let's establish some basic context and then quickly define the scope of the problem.

My immediate instinct is to think about how these two might intersect. Are we talking about simulated network devices and secure transport layers? Is this some kind of performance testing, network debugging scenario, or perhaps emulation for a specific research project? I need a deeper understanding of the relationships. The "grep" suggests a search within some configuration file or a body of text, which should provide this missing context. I'm imagining searching for a configuration file that would define the behavior of `netdevsim` and possibly the use of `tls` for the traffic passing through the simulated network device. Is `tls` being used to encrypt traffic on a virtual interface, or perhaps to secure the control channel for the `netdevsim` device? Let's assume we are testing a setup where traffic is supposed to be encrypted, and one way to do it is to check for TLS. That is, if `netdevsim` is involved, and we want to do security testing, TLS is an obvious indicator that would be present.

The "grep" itself is a tool to pinpoint relevant code segments, configuration snippets, or log entries. I'm using this as a starting point to rapidly zoom in on specific areas to better understand the role these components play in the larger picture. I want to see if they're used in a shared code base, or in any configuration files. My experience tells me that such a quick and direct approach is a common and efficient initial step to gain insight into the problem. In this case, `grep` is a great way to map out the connections between `netdevsim` and `tls`. Let's see what's in there.



10/2 2026/10/21 04:12 tool grepper
0m Error:
no matches

Args:
{
  "Expression": "tls",
  "PathPrefixes": [
    "drivers/net/netdevsim/"
  ]
}

Results:
{
  "error": "no matches"
}

11/2 2026/10/21 04:12 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 25759
							output: 40
							thoughts: 186
						

Thoughts:
**Investigating a Potential TLS Vulnerability**

Okay, here's what's going through my head. I'm looking at this patch and my initial thought was, "Netdevsim doesn't deal with TLS, so what's the deal?". Then I stopped and thought, is it only hardware offload the patch is changing? Nope! It's touching `net/tls/tls_sw.c`. And I saw this code:

```c
	if (tx)
		ctx->push_pending_record = tls_sw_push_pending_record;
```

That's when the alarm bells went off! What happens if someone configures TLS_RX *before* TLS_TX, or even if they only configure TLS_RX? We might have a serious initialization issue on our hands, and I need to figure it out.

So, the next thing I need to do is trace `tls_set_sw_offload`. I have to understand what happens in the case where a socket is created, TLS is enabled, and then ONLY TLS_RX is set (or set before TLS_TX). I'm going to track how `push_pending_record` is initialized and where it's called.

I'm diving deep into `tls_main.c` and `tls_sw.c`, because I need the complete picture. This feels like it has the potential to expose a serious vulnerability if not handled right. I need to understand this whole initialization process and how these offload flags affect the final configuration.



12/2 2026/10/21 04:12 tool grepper
0m Args:
{
  "Expression": "push_pending_record",
  "PathPrefixes": [
    "net/tls/",
    "include/net/tls.h"
  ]
}

Results:
{
  "Output": "include/net/tls.h=227=struct tls_context {\n--\ninclude/net/tls.h-236-\ninclude/net/tls.h:237:\tint (*push_pending_record)(struct sock *sk, int flags);\ninclude/net/tls.h-238-\tvoid (*sk_write_space)(struct sock *sk);\n--\nnet/tls/tls_device.c=674=EXPORT_SYMBOL(tls_get_record);\nnet/tls/tls_device.c-675-\nnet/tls/tls_device.c:676:static int tls_device_push_pending_record(struct sock *sk, int flags)\nnet/tls/tls_device.c-677-{\n--\nnet/tls/tls_device.c=1065=int tls_set_device_offload(struct sock *sk)\n--\nnet/tls/tls_device.c-1137-\tclean_acked_data_enable(tcp_sk(sk), \u0026tls_tcp_clean_acked);\nnet/tls/tls_device.c:1138:\tctx-\u003epush_pending_record = tls_device_push_pending_record;\nnet/tls/tls_device.c-1139-\n--\nnet/tls/tls_main.c=226=static int tls_handle_open_record(struct sock *sk, int flags)\n--\nnet/tls/tls_main.c-230-\tif (tls_is_pending_open_record(ctx))\nnet/tls/tls_main.c:231:\t\treturn ctx-\u003epush_pending_record(sk, flags);\nnet/tls/tls_main.c-232-\n--\nnet/tls/tls_sw.c=701=static int bpf_exec_tx_verdict(struct sk_msg *msg, struct sock *sk,\n--\nnet/tls/tls_sw.c-714-\nnet/tls/tls_sw.c:715:static int tls_sw_push_pending_record(struct sock *sk, int flags)\nnet/tls/tls_sw.c-716-{\n--\nnet/tls/tls_sw.c=1031=void tls_sw_splice_eof(struct socket *sock)\n--\nnet/tls/tls_sw.c-1048-retry:\nnet/tls/tls_sw.c:1049:\t/* same checks as in tls_sw_push_pending_record() */\nnet/tls/tls_sw.c-1050-\trec = ctx-\u003eopen_rec;\n--\nnet/tls/tls_sw.c=2525=int tls_set_sw_offload(struct sock *sk, int tx,\n--\nnet/tls/tls_sw.c-2594-\tif (tx)\nnet/tls/tls_sw.c:2595:\t\tctx-\u003epush_pending_record = tls_sw_push_pending_record;\nnet/tls/tls_sw.c-2596-\n"
}

13/2 2026/10/21 04:12 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 27071
							output: 37
							thoughts: 26
						

Thoughts:
Okay, let's dive into this. Here's my thought process laid out:

**Checking `tls_handle_open_record` in `net/tls/tls_main.c`**

Alright, I need to get my bearings on how this TLS setup is functioning. The core of my interest right now lies in the function `tls_handle_open_record`. To really understand the flow and potential vulnerabilities, I need to trace this function. It sounds like this is the starting point for incoming TLS connections. Given the file path provided, `net/tls/tls_main.c`, I'm expecting this function to be a key element in handling the initial handshake or deciphering the first data records. I’ll be paying close attention to any error handling, buffer management, and cryptographic operations within this function. I'm looking for where and how the incoming TLS records are parsed. Is this function responsible for deciphering the records? Handling all different record types? Or delegating those functions? Knowing the overall architecture is important before I dive in too deep. Understanding this function's exact responsibilities in the larger context will clarify the role it plays in the system.



14/2 2026/10/21 04:12 tool read-file
0m Args:
{
  "File": "net/tls/tls_main.c",
  "FirstLine": 220,
  "LineCount": 40
}

Results:
{
  "Contents": " 220:\t\n 221:\t\tctx-\u003esplicing_pages = false;\n 222:\t\n 223:\t\treturn 0;\n 224:\t}\n 225:\t\n 226:\tstatic int tls_handle_open_record(struct sock *sk, int flags)\n 227:\t{\n 228:\t\tstruct tls_context *ctx = tls_get_ctx(sk);\n 229:\t\n 230:\t\tif (tls_is_pending_open_record(ctx))\n 231:\t\t\treturn ctx-\u003epush_pending_record(sk, flags);\n 232:\t\n 233:\t\treturn 0;\n 234:\t}\n 235:\t\n 236:\tint tls_process_cmsg(struct sock *sk, struct msghdr *msg,\n 237:\t\t\t     unsigned char *record_type)\n 238:\t{\n 239:\t\tstruct cmsghdr *cmsg;\n 240:\t\tint rc = -EINVAL;\n 241:\t\n 242:\t\tfor_each_cmsghdr(cmsg, msg) {\n 243:\t\t\tif (!CMSG_OK(msg, cmsg))\n 244:\t\t\t\treturn -EINVAL;\n 245:\t\t\tif (cmsg-\u003ecmsg_level != SOL_TLS)\n 246:\t\t\t\tcontinue;\n 247:\t\n 248:\t\t\tswitch (cmsg-\u003ecmsg_type) {\n 249:\t\t\tcase TLS_SET_RECORD_TYPE:\n 250:\t\t\t\tif (cmsg-\u003ecmsg_len \u003c CMSG_LEN(sizeof(*record_type)))\n 251:\t\t\t\t\treturn -EINVAL;\n 252:\t\n 253:\t\t\t\tif (msg-\u003emsg_flags \u0026 MSG_MORE)\n 254:\t\t\t\t\treturn -EINVAL;\n 255:\t\n 256:\t\t\t\t*record_type = *(unsigned char *)CMSG_DATA(cmsg);\n 257:\t\n 258:\t\t\t\trc = tls_handle_open_record(sk, msg-\u003emsg_flags);\n 259:\t\t\t\tbreak;\n"
}

15/2 2026/10/21 04:12 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 27944
							output: 23
							thoughts: 122
						

Thoughts:
Okay, here's my take on those code snippets.

**Deep Dive into TLS Record Handling**

Alright, let's see what we've got here. Interesting... it looks like whenever the `TLS_SET_RECORD_TYPE` action is triggered, the code calls `tls_handle_open_record(sk, msg->msg_flags)`. That makes sense; it's the point where we're going to start processing a TLS record.

Now, let's zoom in on `tls_handle_open_record`. I see an `if` statement right away: `if (tls_is_pending_open_record(ctx))`. So, if a condition related to a "pending open record" is true, the code calls `ctx->push_pending_record(sk, flags)`. A clever way to handle buffered records.

Hmm, this `tls_is_pending_open_record(ctx)` function is the key here. It seems like it must tell us something about the state of the connection or incoming data. I need to understand that logic. Let's dig into the definition of `tls_is_pending_open_record`. What's the context and how is it used to determine whether there's a record to open?



16/2 2026/10/21 04:12 tool grepper
0m Args:
{
  "Expression": "tls_is_pending_open_record"
}

Results:
{
  "Output": "net/tls/tls.h=275=static inline bool tls_is_partially_sent_record(struct tls_context *ctx)\n--\nnet/tls/tls.h-279-\nnet/tls/tls.h:280:static inline bool tls_is_pending_open_record(struct tls_context *tls_ctx)\nnet/tls/tls.h-281-{\n--\nnet/tls/tls_device.c=593=void tls_device_splice_eof(struct socket *sock)\n--\nnet/tls/tls_device.c-599-\tif (!tls_is_partially_sent_record(tls_ctx) \u0026\u0026\nnet/tls/tls_device.c:600:\t    !tls_is_pending_open_record(tls_ctx))\nnet/tls/tls_device.c-601-\t\treturn;\n--\nnet/tls/tls_device.c-606-\tif (tls_is_partially_sent_record(tls_ctx) ||\nnet/tls/tls_device.c:607:\t    tls_is_pending_open_record(tls_ctx)) {\nnet/tls/tls_device.c-608-\t\tiov_iter_bvec(\u0026iter, ITER_SOURCE, NULL, 0, 0);\n--\nnet/tls/tls_main.c=226=static int tls_handle_open_record(struct sock *sk, int flags)\n--\nnet/tls/tls_main.c-229-\nnet/tls/tls_main.c:230:\tif (tls_is_pending_open_record(ctx))\nnet/tls/tls_main.c-231-\t\treturn ctx-\u003epush_pending_record(sk, flags);\n"
}

17/2 2026/10/21 04:12 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 28802
							output: 35
							thoughts: 20
						

Thoughts:
Okay, here's my summary, tailored for an expert audience, as if I'm thinking these thoughts:

**Analyzing `net/tls/tls.h` - Line 275**

Alright, let's dive into this. The request came in to examine `net/tls/tls.h` at line 275. Given the context, my initial hunch is that we're dealing with either a fundamental data structure related to TLS negotiation, potentially a key exchange parameter, or maybe a definition related to certificate handling. Line 275 could be a field within a struct or union that's critical for security operations. I'm immediately thinking about:

*   **Key Exchange Parameters:** Is this related to Diffie-Hellman parameters, elliptic curve points, or something more modern like X25519/X448? The `net/` directory and `tls.h` suggest we're looking at low-level networking components, so this is high on my list.
*   **Certificate Structures:** Could it define a specific ASN.1 type or a field within a certificate request/response? I'm anticipating possibly seeing things like `CertificateRequest`, `ServerHello`, or a similar struct that's a cornerstone to secure connection establishment.
*   **Protocol Versioning:** It's conceivable that line 275 defines a macro or an enum value related to a specific TLS version or a feature flag for protocol extensions. Given that we're looking in the `tls.h` file and at such a specific location, I would suspect that the header would contain protocol related constants or structures.

I'm ready to find out if this is part of the implementation of the protocol or even a user's implementation. Let's get to the line and see what it is.



18/2 2026/10/21 04:12 tool read-file
0m Args:
{
  "File": "net/tls/tls.h",
  "FirstLine": 275,
  "LineCount": 20
}

Results:
{
  "Contents": " 275:\tstatic inline bool tls_is_partially_sent_record(struct tls_context *ctx)\n 276:\t{\n 277:\t\treturn !!ctx-\u003epartially_sent_record;\n 278:\t}\n 279:\t\n 280:\tstatic inline bool tls_is_pending_open_record(struct tls_context *tls_ctx)\n 281:\t{\n 282:\t\treturn tls_ctx-\u003epending_open_record_frags;\n 283:\t}\n 284:\t\n 285:\tstatic inline bool tls_bigint_increment(unsigned char *seq, int len)\n 286:\t{\n 287:\t\tint i;\n 288:\t\n 289:\t\tfor (i = len - 1; i \u003e= 0; i--) {\n 290:\t\t\t++seq[i];\n 291:\t\t\tif (seq[i] != 0)\n 292:\t\t\t\tbreak;\n 293:\t\t}\n 294:\t\n"
}

19/2 2026/10/21 04:12 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 29523
							output: 37
							thoughts: 353
						

Thoughts:
**Analyzing Potential Offload Configuration Conflicts**

Okay, so I'm thinking about how the `pending_open_record_frags` flag is used when we're sending records. My immediate thought is, where is `ctx->push_pending_record` even *called*? Ah, right, it's only in `tls_handle_open_record`. And what does that function even do? Let's trace it. It seems to be pushing a pending record, but the *type* of record depends. In `tls_device_push_pending_record`, we're pushing a device record, and in `tls_sw_push_pending_record`, it's a software record.

Now, here's where it gets interesting, and concerning. What if someone has configured device offload for *TX*? `tls_set_device_offload(sk)` would set `ctx->push_pending_record` to `tls_device_push_pending_record`. But, what if they then configure software offload for *RX*? `tls_set_sw_offload(sk, 0, ...)` is called. And, it used to overwrite the TX setting.

Before this patch, `tls_set_sw_offload` calls `ctx->push_pending_record = tls_sw_push_pending_record;`, effectively *overwriting* the previous setting! This is a problem! We're replacing a device offload function with a software one, even though the device offload might still be active for TX! If a pending record *was* pushed after this overwrite, it would call `tls_sw_push_pending_record(sk, flags)`. This function is expecting `sw_ctx_tx = ctx->priv_ctx_tx` to be a `struct tls_sw_context_tx`... but if the original configuration was device offload, this isn't necessarily true! This would introduce a major bug. I'll need to double check `tls_sw_push_pending_record` in `net/tls/tls_sw.c`, specifically line 715. I need to make sure I'm seeing this correctly.



20/2 2026/10/21 04:13 tool read-file
0m Args:
{
  "File": "net/tls/tls_sw.c",
  "FirstLine": 715,
  "LineCount": 35
}

Results:
{
  "Contents": " 715:\tstatic int tls_sw_push_pending_record(struct sock *sk, int flags)\n 716:\t{\n 717:\t\tstruct tls_context *tls_ctx = tls_get_ctx(sk);\n 718:\t\tstruct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);\n 719:\t\tstruct tls_rec *rec = ctx-\u003eopen_rec;\n 720:\t\tstruct sk_msg *msg_pl;\n 721:\t\tsize_t copied;\n 722:\t\n 723:\t\tif (!rec)\n 724:\t\t\treturn 0;\n 725:\t\n 726:\t\tmsg_pl = \u0026rec-\u003emsg_plaintext;\n 727:\t\tcopied = msg_pl-\u003esg.size;\n 728:\t\tif (!copied)\n 729:\t\t\treturn 0;\n 730:\t\n 731:\t\treturn bpf_exec_tx_verdict(msg_pl, sk, TLS_RECORD_TYPE_DATA,\n 732:\t\t\t\t\t   \u0026copied, flags);\n 733:\t}\n 734:\t\n 735:\tstatic int tls_sw_sendmsg_splice(struct sock *sk, struct msghdr *msg,\n 736:\t\t\t\t\t struct sk_msg *msg_pl, size_t try_to_copy,\n 737:\t\t\t\t\t ssize_t *copied)\n 738:\t{\n 739:\t\tstruct page *page = NULL, **pages = \u0026page;\n 740:\t\n 741:\t\tdo {\n 742:\t\t\tssize_t part;\n 743:\t\t\tsize_t off;\n 744:\t\n 745:\t\t\tpart = iov_iter_extract_pages(\u0026msg-\u003emsg_iter, \u0026pages,\n 746:\t\t\t\t\t\t      try_to_copy, 1, 0, \u0026off);\n 747:\t\t\tif (part \u003c= 0)\n 748:\t\t\t\treturn part ?: -EIO;\n 749:\t\n"
}

21/2 2026/10/21 04:13 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 30924
							output: 22
							thoughts: 339
						

Thoughts:
**Analyzing a Potential Vulnerability in TLS Software Offload**

Okay, let's dive into this `tls_sw_push_pending_record` function. The code starts by retrieving the TLS context and then casts a portion of it, `priv_ctx_tx`, to a `tls_sw_context_tx` struct. Now, the potential problem is immediately apparent. If we're dealing with a hardware offload scenario (and `tx` is false), `priv_ctx_tx` won't actually *be* a `tls_sw_context_tx`. Accessing `ctx->open_rec` would be a classic type confusion, or even a null pointer dereference, which is just begging for a crash.

The fix, setting `ctx->push_pending_record = tls_sw_push_pending_record` only when `tx` is true, makes perfect sense in preventing that condition. Only enabling the software TX path when software TX offload is configured.

Now, the important question: Can a fuzzer actually trigger this vulnerability? That's what I need to verify. Hold on... first things first: Can `tls_set_sw_offload` even be reached? Aha! Yes, it's called when setting `SOL_TLS` socket options, specifically `TLS_TX` or `TLS_RX` with software crypto!

Now, to solidify this, let's verify precisely how `tls_set_sw_offload` is called in the broader codebase. A quick grep should do the trick. That will give me the evidence needed to determine the overall reachability of this potential vulnerability during fuzzing.



22/2 2026/10/21 04:13 tool grepper
0m Args:
{
  "Expression": "tls_set_sw_offload"
}

Results:
{
  "Output": "net/tls/tls.h=147=int init_prot_info(struct tls_prot_info *prot,\n--\nnet/tls/tls.h-149-\t\t   const struct tls_cipher_desc *cipher_desc);\nnet/tls/tls.h:150:int tls_set_sw_offload(struct sock *sk, int tx,\nnet/tls/tls.h-151-\t\t       struct tls_crypto_info *new_crypto_info);\n--\nnet/tls/tls_device.c=1195=int tls_set_device_offload_rx(struct sock *sk, struct tls_context *ctx)\n--\nnet/tls/tls_device.c-1237-\tctx-\u003epriv_ctx_rx = context;\nnet/tls/tls_device.c:1238:\trc = tls_set_sw_offload(sk, 0, NULL);\nnet/tls/tls_device.c-1239-\tif (rc)\n--\nnet/tls/tls_main.c=623=static int do_tls_setsockopt_conf(struct sock *sk, sockptr_t optval,\n--\nnet/tls/tls_main.c-718-\t\t} else {\nnet/tls/tls_main.c:719:\t\t\trc = tls_set_sw_offload(sk, 1,\nnet/tls/tls_main.c-720-\t\t\t\t\t\tupdate ? crypto_info : NULL);\n--\nnet/tls/tls_main.c-738-\t\t} else {\nnet/tls/tls_main.c:739:\t\t\trc = tls_set_sw_offload(sk, 0,\nnet/tls/tls_main.c-740-\t\t\t\t\t\tupdate ? crypto_info : NULL);\n--\nnet/tls/tls_sw.c=2516=static void tls_finish_key_update(struct sock *sk, struct tls_context *tls_ctx)\n--\nnet/tls/tls_sw.c-2524-\nnet/tls/tls_sw.c:2525:int tls_set_sw_offload(struct sock *sk, int tx,\nnet/tls/tls_sw.c-2526-\t\t       struct tls_crypto_info *new_crypto_info)\n"
}

23/2 2026/10/21 04:13 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 32211
							output: 37
							thoughts: 200
						

Thoughts:
**Investigating the `tls_set_sw_offload` and Potential Hardware Offload Paths**

Okay, so I'm diving into the `net/tls/tls_main.c` code. My initial thought is to trace the execution of `tls_set_sw_offload` for both transmit (TX) and receive (RX) operations. It looks like it's reached directly via `setsockopt` with `SOL_TLS` and either `TLS_TX` or `TLS_RX`, which makes sense. But here's where it gets interesting: does syzkaller specifically need to target hardware offload to actually *call* `tls_set_sw_offload`? No, that's not right. It doesn't. Syzkaller can, and likely does, execute that function even without any hardware TLS acceleration.

That raises another question. Can `tls_set_device_offload` be reached even *without* that special hardware? That needs to be investigated, because I can’t immediately remember the control flow. Let’s figure out how that's reached. I need to check `tls_set_device_offload`. Okay, let’s dig into the `do_tls_setsockopt_conf` function within `net/tls/tls_main.c`! I should be able to trace it from there.



24/2 2026/10/21 04:13 tool read-file
0m Args:
{
  "File": "net/tls/tls_main.c",
  "FirstLine": 690,
  "LineCount": 60
}

Results:
{
  "Contents": " 690:\t\tif (rc)\n 691:\t\t\tgoto err_crypto_info;\n 692:\t\n 693:\t\tcipher_desc = get_cipher_desc(crypto_info-\u003ecipher_type);\n 694:\t\tif (!cipher_desc) {\n 695:\t\t\trc = -EINVAL;\n 696:\t\t\tgoto err_crypto_info;\n 697:\t\t}\n 698:\t\n 699:\t\tif (optlen != cipher_desc-\u003ecrypto_info) {\n 700:\t\t\trc = -EINVAL;\n 701:\t\t\tgoto err_crypto_info;\n 702:\t\t}\n 703:\t\n 704:\t\trc = copy_from_sockptr_offset(crypto_info + 1, optval,\n 705:\t\t\t\t\t      sizeof(*crypto_info),\n 706:\t\t\t\t\t      optlen - sizeof(*crypto_info));\n 707:\t\tif (rc) {\n 708:\t\t\trc = -EFAULT;\n 709:\t\t\tgoto err_crypto_info;\n 710:\t\t}\n 711:\t\n 712:\t\tif (tx) {\n 713:\t\t\trc = tls_set_device_offload(sk);\n 714:\t\t\tconf = TLS_HW;\n 715:\t\t\tif (!rc) {\n 716:\t\t\t\tTLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSTXDEVICE);\n 717:\t\t\t\tTLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSCURRTXDEVICE);\n 718:\t\t\t} else {\n 719:\t\t\t\trc = tls_set_sw_offload(sk, 1,\n 720:\t\t\t\t\t\t\tupdate ? crypto_info : NULL);\n 721:\t\t\t\tif (rc)\n 722:\t\t\t\t\tgoto err_crypto_info;\n 723:\t\n 724:\t\t\t\tif (update) {\n 725:\t\t\t\t\tTLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSTXREKEYOK);\n 726:\t\t\t\t} else {\n 727:\t\t\t\t\tTLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSTXSW);\n 728:\t\t\t\t\tTLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSCURRTXSW);\n 729:\t\t\t\t}\n 730:\t\t\t\tconf = TLS_SW;\n 731:\t\t\t}\n 732:\t\t} else {\n 733:\t\t\trc = tls_set_device_offload_rx(sk, ctx);\n 734:\t\t\tconf = TLS_HW;\n 735:\t\t\tif (!rc) {\n 736:\t\t\t\tTLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSRXDEVICE);\n 737:\t\t\t\tTLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSCURRRXDEVICE);\n 738:\t\t\t} else {\n 739:\t\t\t\trc = tls_set_sw_offload(sk, 0,\n 740:\t\t\t\t\t\t\tupdate ? crypto_info : NULL);\n 741:\t\t\t\tif (rc)\n 742:\t\t\t\t\tgoto err_crypto_info;\n 743:\t\n 744:\t\t\t\tif (update) {\n 745:\t\t\t\t\tTLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSRXREKEYOK);\n 746:\t\t\t\t} else {\n 747:\t\t\t\t\tTLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSRXSW);\n 748:\t\t\t\t\tTLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSCURRRXSW);\n 749:\t\t\t\t}\n"
}

25/2 2026/10/21 04:13 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 33703
							output: 20
							thoughts: 720
						

Thoughts:
**Analyzing the ktls Patch and its Potential Impact**

Okay, let's break this down. I'm focusing on lines 712-731 and the implications of this patch. The key here seems to be how the system handles TLS offload and what happens in fallback scenarios.

First, I see the typical flow: when `tx` (transmit) is enabled, the code *tries* to use hardware TLS offload (`tls_set_device_offload(sk)`). If that fails, as is often the case with the devices I'm working with or during testing, it falls back to software TLS (`tls_set_sw_offload(sk, 1, ...)`). For receive (`tx` is false), it's the same principle, but with `tls_set_device_offload_rx(sk, ctx)` and a software fallback.

The interesting bit, the thing that raises a red flag, is that even when device RX offload *is* used, `tls_set_sw_offload(sk, 0, NULL)` is still invoked!  Furthermore, in standard software TLS (the most relevant scenario in a lot of what I do), both `tls_set_sw_offload(sk, 1, ...)` (TX) and `tls_set_sw_offload(sk, 0, ...)` (RX) are consistently called for *every* TLS connection. This isn't necessarily abnormal, but it's a good baseline to remember.

Now, what changed with this patch in `net/tls/tls_sw.c`?  I see this: the code now only sets `ctx->push_pending_record = tls_sw_push_pending_record;` *if* `tx` is true.  If `tx` is *false*, `ctx->push_pending_record` remains NULL or is initialized to zero.

The problem, as I see it, is what happens with sockets that *only* set `TLS_RX` and not `TLS_TX`. Before the patch, `ctx->push_pending_record` *would* have been set. Now, it *won't* be. This is a critical change.

My immediate question: What happens if I attempt to send data or call `tls_handle_open_record` on a socket configured only for `TLS_RX`? Does this have a crash-like effect? Can `tls_handle_open_record` even *be* called in such a scenario? This needs a more comprehensive investigation.

I'm going to track down the call to `tls_handle_open_record`. Let's see what's calling it, and under what conditions. It's called from `tls_process_cmsg` in `net/tls/tls_main.c` (line 258). From there, I need to look at who calls `tls_process_cmsg` to get the full picture.



26/2 2026/10/21 04:13 tool grepper
0m Args:
{
  "Expression": "tls_process_cmsg"
}

Results:
{
  "Output": "net/tls/tls.h=177=void tls_device_write_space(struct sock *sk, struct tls_context *ctx);\nnet/tls/tls.h-178-\nnet/tls/tls.h:179:int tls_process_cmsg(struct sock *sk, struct msghdr *msg,\nnet/tls/tls.h-180-\t\t     unsigned char *record_type);\n--\nnet/tls/tls_device.c=566=int tls_device_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)\n--\nnet/tls/tls_device.c-578-\tif (unlikely(msg-\u003emsg_controllen)) {\nnet/tls/tls_device.c:579:\t\trc = tls_process_cmsg(sk, msg, \u0026record_type);\nnet/tls/tls_device.c-580-\t\tif (rc)\n--\nnet/tls/tls_main.c=226=static int tls_handle_open_record(struct sock *sk, int flags)\n--\nnet/tls/tls_main.c-235-\nnet/tls/tls_main.c:236:int tls_process_cmsg(struct sock *sk, struct msghdr *msg,\nnet/tls/tls_main.c-237-\t\t     unsigned char *record_type)\n--\nnet/tls/tls_sw.c=766=static int tls_sw_sendmsg_locked(struct sock *sk, struct msghdr *msg,\n--\nnet/tls/tls_sw.c-792-\tif (unlikely(msg-\u003emsg_controllen)) {\nnet/tls/tls_sw.c:793:\t\tret = tls_process_cmsg(sk, msg, \u0026record_type);\nnet/tls/tls_sw.c-794-\t\tif (ret) {\n"
}

27/2 2026/10/21 04:13 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 35562
							output: 36
							thoughts: 2024
						

Thoughts:
**Analysis of kTLS Offload Patch for Fuzzing Suitability**

Okay, let's break this down. My initial thought is to analyze this kTLS offload patch for fuzzing suitability. The core of the issue revolves around how `ctx->push_pending_record` gets set in `tls_set_sw_offload` and `tls_set_device_offload`, specifically in `net/tls/tls_sw.c`. The potential bug centers on a state mismatch: if HW offload on TX is enabled, then SW offload on RX is enabled, `ctx->push_pending_record` might be incorrectly overwritten.

The core question is, does this path exist in syzkaller's reach and ability? Is this a reachable path? Looking back at the rules, I need to check against the criteria for determining if fuzzing is warranted. My knowledge says:

*   The code modifies `net/tls/tls_sw.c`. This isn't just documentation or a sample; it's *executable core networking code* (`net/tls/`) directly in the kernel.
*   This code path is reachable. Anyone can configure TLS on a TCP socket using `setsockopt`. It's a standard interface. Therefore, the modified code is not structurally unreachable, not non-kernel, and not an unreachable execution path.
*   The modification changes the logic. Before, the value was always unconditionally set, now it is conditionally set based on `tx`. If `tx` is false, it is not set. The patch could introduce a situation where `ctx->push_pending_record` is null when it shouldn't be. This isn't just a refactoring or harmless comment; it directly alters the behavior of a critical data structure. The patch, specifically the condition, introduces a change in control flow.

Given this, I have to conclude that Section 3 applies: it touches *reachable executable code* within a core subsystem (`net/tls/`, which is core networking). Also, this can expose latent bugs in unusual operation sequence! If I think, could this introduce a null pointer dereference?

The `tls_handle_open_record` function doesn't check for a NULL `ctx->push_pending_record` *before* calling it. If `tls_is_pending_open_record` is true and `push_pending_record` is null, there's a clear vulnerability here.

Therefore, `WorthFuzzing = true`. This is a clear case for fuzzing. It's a logic modification that could introduce a NULL pointer dereference. The potential bug is related to a race or a combination of operations, exactly the type of thing fuzzing is designed to catch.

Now, for `FocusSymbols` and `EnableConfigs`, I need to identify the exact functions to target and the necessary kernel configurations to enable TLS and relevant network features. I need to make sure that the fuzzing environment includes `net/tls/` and anything related.



28/2 2026/10/21 04:14 tool grepper
0m Args:
{
  "Expression": "TLS",
  "PathPrefixes": [
    "net/tls/Makefile",
    "net/tls/Kconfig"
  ]
}

Results:
{
  "Output": "net/tls/Kconfig-2-#\nnet/tls/Kconfig:3:# TLS configuration\nnet/tls/Kconfig-4-#\nnet/tls/Kconfig:5:config TLS\nnet/tls/Kconfig-6-\ttristate \"Transport Layer Security support\"\n--\nnet/tls/Kconfig-13-\thelp\nnet/tls/Kconfig:14:\tEnable kernel support for TLS protocol. This allows symmetric\nnet/tls/Kconfig:15:\tencryption handling of the TLS protocol to be done in-kernel.\nnet/tls/Kconfig-16-\n--\nnet/tls/Kconfig-18-\nnet/tls/Kconfig:19:config TLS_DEVICE\nnet/tls/Kconfig-20-\tbool \"Transport Layer Security HW offload\"\nnet/tls/Kconfig:21:\tdepends on TLS\nnet/tls/Kconfig-22-\tselect SKB_DECRYPTED\n--\nnet/tls/Kconfig-26-\thelp\nnet/tls/Kconfig:27:\tEnable kernel support for HW offload of the TLS protocol.\nnet/tls/Kconfig-28-\n--\nnet/tls/Makefile-2-#\nnet/tls/Makefile:3:# Makefile for the TLS subsystem.\nnet/tls/Makefile-4-#\n--\nnet/tls/Makefile=6=CFLAGS_trace.o := -I$(src)\nnet/tls/Makefile-7-\nnet/tls/Makefile:8:obj-$(CONFIG_TLS) += tls.o\nnet/tls/Makefile-9-\nnet/tls/Makefile=10=tls-y := tls_main.o tls_sw.o tls_proc.o trace.o tls_strp.o\nnet/tls/Makefile-11-\nnet/tls/Makefile:12:tls-$(CONFIG_TLS_DEVICE) += tls_device.o tls_device_fallback.o\n"
}

29/2 2026/10/21 04:14 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 38714
							output: 32
							thoughts: 25
						

Thoughts:
Okay, let's dive into this. Here's my thought process laid out:

**Examining the TLS Configuration Dependencies**

Alright, I need to understand the dependencies related to `CONFIG_TLS` in this kernel configuration. My instinct, based on experience, is that I should check the `net/tls/Kconfig` file. That's typically where these low-level networking and security configurations are managed. To get a clear picture of what's going on, I'm going to jump straight to around line 5, assuming that's where the initial definition and potentially associated dependencies will be. I need to figure out what other configurations might be required or are affected by `CONFIG_TLS`. Understanding these dependencies is key for debugging, enabling, and disabling TLS support in this specific kernel build.



30/2 2026/10/21 04:14 tool read-file
0m Args:
{
  "File": "net/tls/Kconfig",
  "FirstLine": 1,
  "LineCount": 40
}

Results:
{
  "Contents": "   1:\t# SPDX-License-Identifier: GPL-2.0-only\n   2:\t#\n   3:\t# TLS configuration\n   4:\t#\n   5:\tconfig TLS\n   6:\t\ttristate \"Transport Layer Security support\"\n   7:\t\tdepends on INET\n   8:\t\tselect CRYPTO\n   9:\t\tselect CRYPTO_AES\n  10:\t\tselect CRYPTO_GCM\n  11:\t\tselect NET_SOCK_MSG\n  12:\t\tdefault n\n  13:\t\thelp\n  14:\t\tEnable kernel support for TLS protocol. This allows symmetric\n  15:\t\tencryption handling of the TLS protocol to be done in-kernel.\n  16:\t\n  17:\t\tIf unsure, say N.\n  18:\t\n  19:\tconfig TLS_DEVICE\n  20:\t\tbool \"Transport Layer Security HW offload\"\n  21:\t\tdepends on TLS\n  22:\t\tselect SKB_DECRYPTED\n  23:\t\tselect SOCK_VALIDATE_XMIT\n  24:\t\tselect SOCK_RX_QUEUE_MAPPING\n  25:\t\tdefault n\n  26:\t\thelp\n  27:\t\tEnable kernel support for HW offload of the TLS protocol.\n  28:\t\n  29:\t\tIf unsure, say N.\n"
}

31/2 2026/10/21 04:14 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 39264
							output: 20
							thoughts: 849
						

Thoughts:
**Focusing on the TLS HW Offload Fix**

Okay, so this fix is about the interaction between hardware and software offload in the TLS subsystem. Let me break down my understanding. First, I need to make sure I'm targeting the right configuration. `CONFIG_TLS` depends on `INET`, which is expected. Then, `CONFIG_TLS_DEVICE` enables `tls_device.o`, and that's the key - it's specifically for hardware offload. I remember seeing `CONFIG_TLS=y` and `CONFIG_TLS_DEVICE=y` in the selftest config fragment. I also just confirmed that standard syzkaller kernel configs also have those enabled. So, `INET`, `TLS`, and `TLS_DEVICE` seem to be the important configs I need to keep in mind.

Now, let's think about how to use FocusSymbols effectively. The guidance is clear: avoid ubiquitous functions like memory allocators and synchronization primitives. Instead, I need to target functions that *specifically* implement the logic being modified or entry points to the feature. Also, if there are static inline functions, I should identify non-static callers that exercise them.

Given the commit, here are the functions I'm focusing on:

1.  `tls_set_sw_offload`: This is where the core change is made, assigning `ctx->push_pending_record = tls_sw_push_pending_record;` based on the `tx` flag. This is definitely a candidate.
2.  `tls_sw_push_pending_record`: This is the function whose assignment is being controlled. I need to understand its role.
3.  `tls_handle_open_record`: This function is critical because it's where `ctx->push_pending_record(sk, flags)` is actually called. Wait... is it static? Let me check `net/tls/tls_main.c`. Yes, it's declared `static`. So, it might be inlined. But what are the callers of it? Let me check `net/tls/tls_main.c` again. Aha! It's called from `tls_process_cmsg(sk, msg, &record_type)`. `tls_process_cmsg` looks to be exported because it is a non-static function with the signature `int tls_process_cmsg(struct sock *sk, struct msghdr *msg, unsigned char *record_type)`. What about `do_tls_setsockopt_conf`? It is static in `tls_main.c`. Ok, so that probably isn't the best candidate. And, finally, let me check `tls_setsockopt`, which is the main setsockopt handler for TLS. I need to understand how the set sock opt interacts with the hw / sw switch. So, `tls_process_cmsg` and `tls_setsockopt` are definitely the functions I need to target.



32/2 2026/10/21 04:14 tool grepper
0m Args:
{
  "Expression": "int tls_setsockopt"
}

Results:
{
  "Output": "net/tls/tls_main.c=862=static int do_tls_setsockopt(struct sock *sk, int optname, sockptr_t optval,\n--\nnet/tls/tls_main.c-894-\nnet/tls/tls_main.c:895:static int tls_setsockopt(struct sock *sk, int level, int optname,\nnet/tls/tls_main.c-896-\t\t\t  sockptr_t optval, unsigned int optlen)\n"
}

33/2 2026/10/21 04:14 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 40901
							output: 20
							thoughts: 478
						

Thoughts:
**Analyzing TLS Offload Functionality**

Okay, let's dive into this TLS implementation. First, I need to confirm the visibility of `tls_set_sw_offload`. It's defined in `net/tls/tls_sw.c` and declared in `net/tls/tls.h`. I see it's non-static, which means it's exported and linked into the kernel's `vmlinux` image. I can see it's called from `tls_main.c` (specifically within `do_tls_setsockopt_conf`) and also from `tls_device.c` (`tls_set_device_offload_rx`). So, I'm confident that this is a real, accessible symbol.

Next, I need to clarify the potential inlining issues with some other functions. Looking at `tls_sw_push_pending_record`, it's defined as `static` in `net/tls/tls_sw.c`. However, its address is being taken and stored in a function pointer, which means the compiler *cannot* completely inline it. The linker needs the function's address to resolve the pointer. This is important to remember. The same applies to `tls_device_push_pending_record` – it also has its address taken.

Now, let's consider `tls_process_cmsg` in `net/tls/tls_main.c`. It's non-static, which is expected for functions involved in message handling.

Finally, I need to check the potential visibility of `tls_sw_sendmsg`. While `tls_sw_sendmsg_locked` is static, `tls_sw_sendmsg` is either non-static, or within `tls_sw_proto_ops`. I will check its definition in `net/tls/tls_sw.c`. This is where the core logic will lie.



34/2 2026/10/21 04:14 tool grepper
0m Args:
{
  "Expression": "tls_sw_sendmsg"
}

Results:
{
  "Output": "net/tls/tls.h=154=void tls_sw_strparser_done(struct tls_context *tls_ctx);\nnet/tls/tls.h:155:int tls_sw_sendmsg(struct sock *sk, struct msghdr *msg, size_t size);\nnet/tls/tls.h-156-void tls_sw_splice_eof(struct socket *sock);\n--\nnet/tls/tls_main.c=998=static void build_protos(struct proto prot[TLS_NUM_CONFIG][TLS_NUM_CONFIG],\n--\nnet/tls/tls_main.c-1007-\tprot[TLS_SW][TLS_BASE] = prot[TLS_BASE][TLS_BASE];\nnet/tls/tls_main.c:1008:\tprot[TLS_SW][TLS_BASE].sendmsg\t\t= tls_sw_sendmsg;\nnet/tls/tls_main.c-1009-\tprot[TLS_SW][TLS_BASE].splice_eof\t= tls_sw_splice_eof;\n--\nnet/tls/tls_sw.c=715=static int tls_sw_push_pending_record(struct sock *sk, int flags)\n--\nnet/tls/tls_sw.c-734-\nnet/tls/tls_sw.c:735:static int tls_sw_sendmsg_splice(struct sock *sk, struct msghdr *msg,\nnet/tls/tls_sw.c-736-\t\t\t\t struct sk_msg *msg_pl, size_t try_to_copy,\n--\nnet/tls/tls_sw.c-765-\nnet/tls/tls_sw.c:766:static int tls_sw_sendmsg_locked(struct sock *sk, struct msghdr *msg,\nnet/tls/tls_sw.c-767-\t\t\t\t size_t size)\n--\nnet/tls/tls_sw.c-857-\t\tif (try_to_copy \u0026\u0026 (msg-\u003emsg_flags \u0026 MSG_SPLICE_PAGES)) {\nnet/tls/tls_sw.c:858:\t\t\tret = tls_sw_sendmsg_splice(sk, msg, msg_pl,\nnet/tls/tls_sw.c-859-\t\t\t\t\t\t    try_to_copy, \u0026copied);\n--\nnet/tls/tls_sw.c-1007-\nnet/tls/tls_sw.c:1008:int tls_sw_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)\nnet/tls/tls_sw.c-1009-{\n--\nnet/tls/tls_sw.c-1021-\tlock_sock(sk);\nnet/tls/tls_sw.c:1022:\tret = tls_sw_sendmsg_locked(sk, msg, size);\nnet/tls/tls_sw.c-1023-\trelease_sock(sk);\n"
}

35/2 2026/10/21 04:14 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 42535
							output: 163
							thoughts: 764
						

Thoughts:
**Analysis of kTLS Offload Behavior and Fuzzing Strategy**

Okay, let's break this down. I'm looking at these kTLS functions: `tls_set_sw_offload`, `tls_sw_push_pending_record`, `tls_process_cmsg`, `tls_sw_sendmsg`, and `tls_device_push_pending_record`. The first four are definitely worth a closer look, especially since they're the subject of the change. `tls_device_push_pending_record` seems related, but let's see how.

`tls_set_sw_offload`, `tls_sw_push_pending_record`, `tls_process_cmsg` are not ubiquitous; the first two are involved when configuring TLS crypto on sockets and pushing pending TLS records, and the third for processing control messages. `tls_sw_sendmsg`, of course, is specific to sending data over TLS sockets. These are all good entry points for fuzzing.

My next thought is to investigate the relationship between the `push_pending_record` family of functions. `tls_device_push_pending_record` is in `net/tls/tls_device.c`, alongside `tls_set_device_offload`. Let's see if the latter is even reachable in a standard QEMU environment.

Aha, `tls_set_device_offload` is called within `do_tls_setsockopt_conf`, which is triggered by `setsockopt` with `SOL_TLS`. It checks for device support (`sk->sk_dst_cache`, `dst->dev->tlsdev_ops`, etc.), and if the device doesn't support offload, it falls back to `tls_set_sw_offload`.

So, in a default QEMU setup, both `tls_set_sw_offload` can be executed on `tx = 1` or `tx = 0`. The patch looks important: previously, the `ctx->push_pending_record` was unconditionally set to `tls_sw_push_pending_record` during RX configuration. Now, it's only set if TX offload is enabled (`if (tx)`). This introduces a change in behavior, particularly if an application only configures RX or sets record types or pushes pending records. This change is absolutely reachable in our standard virtualized environments.

This change warrants fuzzing. The key symbols are `tls_set_sw_offload`, `tls_sw_push_pending_record`, and `tls_process_cmsg`. The fuzzing should focus on configurations that enable both `TLS` and `TLS_DEVICE`.

The patch modifies `tls_set_sw_offload` to only set `ctx->push_pending_record` when configuring TX offload, which prevents software RX configuration from overwriting a device TX offload callback or leaving/changing the hook on RX-only configurations. This directly alters executable logic in the reachable core kTLS subsystem accessible via `setsockopt` and `sendmsg()` control messages.

Okay, that's the gist of it. This all looks good, so let's call `set-results`.



36/2 2026/10/21 04:14 tool set-results
0m Args:
{
  "EnableConfigs": [
    "TLS",
    "TLS_DEVICE"
  ],
  "FocusSymbols": [
    "tls_set_sw_offload",
    "tls_sw_push_pending_record",
    "tls_process_cmsg"
  ],
  "Reasoning": "The patch modifies net/tls/tls_sw.c in the core networking kTLS subsystem so that ctx-\u003epush_pending_record is only assigned to tls_sw_push_pending_record when configuring TX offload (if (tx)), avoiding overwriting the TX push_pending_record callback when configuring RX. This affects reachable socket configuration and record handling in kTLS, which is exercised through standard TCP setsockopt and sendmsg operations.",
  "WorthFuzzing": true
}

Results:
{
  "EnableConfigs": [
    "TLS",
    "TLS_DEVICE"
  ],
  "FocusSymbols": [
    "tls_set_sw_offload",
    "tls_sw_push_pending_record",
    "tls_process_cmsg"
  ],
  "Reasoning": "The patch modifies net/tls/tls_sw.c in the core networking kTLS subsystem so that ctx-\u003epush_pending_record is only assigned to tls_sw_push_pending_record when configuring TX offload (if (tx)), avoiding overwriting the TX push_pending_record callback when configuring RX. This affects reachable socket configuration and record handling in kTLS, which is exercised through standard TCP setsockopt and sendmsg operations.",
  "WorthFuzzing": true
}

37/1 2026/10/21 04:14 action If
0m Args:
{
  "WorthFuzzing": true
}

Results:
null

38/2 2026/10/21 04:14 agent kmsan-evaluator
0m Model:
core

Args:
null

Results:
{
  "KMSANReasoning": "The patch modifies `tls_set_sw_offload()` in `net/tls/tls_sw.c` so that `ctx-\u003epush_pending_record` is only set when configuring the TX path (`if (tx)`). Previously, configuring RX offload on a socket that had hardware TX offload would overwrite `ctx-\u003epush_pending_record` with `tls_sw_push_pending_record`. The remainder of the patch adds a self-test and documentation.\n\n`struct tls_context` is allocated via `kzalloc_obj()` in `tls_ctx_create()`, ensuring all fields are zero-initialized from the start. The change merely guards the assignment of a function pointer based on the function argument `tx`. It does not introduce or expose any uninitialized memory reads, uninitialized branching conditions, or information leaks to userspace. Therefore, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false
}

Instruction:
You are an expert Linux kernel security engineer specializing in kernel memory
error detectors (KASAN and KMSAN). Your job is to review the provided patch series and
determine if the code changes justify spawning a dedicated KMSAN (KernelMemorySanitizer)
fuzzing session in addition to standard KASAN fuzzing.

CRITICAL DISTINCTION BETWEEN KASAN AND KMSAN:
- Standard KASAN kernel builds (upstream-apparmor-kasan.config) already enable
  a comprehensive suite of debugging tools and sanitizers, including KASAN
  (out-of-bounds accesses, use-after-free, double free, invalid free), LOCKDEP
  (locking bugs and deadlocks), UB-sanitizers, and memory corruption checks.
- KMSAN (KernelMemorySanitizer) detects reads of UNINITIALIZED memory (stack, heap,
  or page allocations) and kernel-to-user memory info-leaks.

Rule: THERE IS NO SENSE IN RUNNING A KMSAN SESSION IF A BUG CAN BE CAUGHT BY KASAN,
LOCKDEP, OR OTHER STANDARD BUG DETECTORS.
A dedicated KMSAN fuzzing session incurs significant resource costs. You must ONLY
set NeedsKMSAN=true if the code changes introduce or expose UNINITIALIZED MEMORY risks
that are detected ONLY by KMSAN.

Look holistically at the patch series and surrounding code. Even if no direct
uninitialized field accesses or new buffer allocations are added in the diff itself,
a patch may alter control flow, bounds checking, or data length calculations in ways
that change how the rest of the code operates on existing buffers (e.g. allowing
uninitialized stack/heap memory to be read, copied to user space, or used in control
flow). Do not hesitate to use your code access tools to inspect the surrounding code,
called functions, and callers.

Set NeedsKMSAN=true ONLY IF the patch introduces or modifies:
1. Kernel structures sent to user space (via copy_to_user, put_user, netlink skb
   attributes, ioctl output arguments, socket options, or BPF buffers) where fields
   or structure padding might not be fully initialized/zeroed.
2. Conditional logic or branching that depends on potentially uninitialized variables
   or struct fields.
3. Allocation or initialization of complex data structures where uninitialized fields
   could be read later in reachable code paths.
4. Bounds checks, lengths, or logic in a way that allows surrounding code to access
   uninitialized bytes of existing buffers.

Set NeedsKMSAN=false IF:
- The code changes primarily risk out-of-bounds access, array overflows, NULL pointer
  dereferences, locking deadlocks, or use-after-free bugs (these are already caught
  by KASAN, LOCKDEP, or standard bug detectors).
- All stack/heap structures touched or introduced by the patch are fully zeroed
  or initialized (e.g. using = {0}, memset, kzalloc) before being read or copied.
- The patch does not introduce any risk of uninitialized memory usage or info-leaks.

Use your code access tools to inspect the surrounding code if necessary, then provide
detailed KMSANReasoning contrasting KASAN vs KMSAN applicability for this patch.
Prefer calling several tools at the same time to save round-trips.


Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit 2449cc829c24f2d986b3e924a1bd5f0afa3905ad
Author: syz-cluster <triage@syzkaller.com>
Date:   Wed Oct 21 04:12:00 2026 +0000

    syz-cluster: applied patch under review

diff --git a/MAINTAINERS b/MAINTAINERS
index 00b440be0d46c..771cd3161a05f 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -19269,6 +19269,8 @@ F:	Documentation/networking/tls*
 F:	include/net/tls.h
 F:	include/uapi/linux/tls.h
 F:	net/tls/
+F:	tools/testing/selftests/drivers/net/hw/tls_hw_offload.c
+F:	tools/testing/selftests/drivers/net/hw/tls_hw_offload.py
 F:	tools/testing/selftests/net/tls.c
 
 NETWORKING [SOCKETS]
diff --git a/net/tls/tls_sw.c b/net/tls/tls_sw.c
index d1ad31986cf2c..235b868facfa9 100644
--- a/net/tls/tls_sw.c
+++ b/net/tls/tls_sw.c
@@ -2591,7 +2591,8 @@ int tls_set_sw_offload(struct sock *sk, int tx,
 		}
 	}
 
-	ctx->push_pending_record = tls_sw_push_pending_record;
+	if (tx)
+		ctx->push_pending_record = tls_sw_push_pending_record;
 
 	/* setkey is the last operation that could fail during a
 	 * rekey. if it succeeds, we can start modifying the
diff --git a/tools/testing/selftests/drivers/net/README.rst b/tools/testing/selftests/drivers/net/README.rst
index c6bed9a985bc7..94c6aeecfe2ff 100644
--- a/tools/testing/selftests/drivers/net/README.rst
+++ b/tools/testing/selftests/drivers/net/README.rst
@@ -188,6 +188,28 @@ The tests have a handful of dependencies. For Fedora / CentOS::
 
   dnf -y install netsniff-ng python-yaml socat iperf3
 
+TLS hardware offload
+~~~~~~~~~~~~~~~~~~~~
+
+``hw/tls_hw_offload.py`` tests TLS 1.2 with AES-GCM-128/256 using a C
+helper on both endpoints. Configure the endpoints using the variables above
+and enable at least one of ``tls-hw-tx-offload`` or ``tls-hw-rx-offload`` on
+the DUT. The peer can use software kTLS. The test checks every enabled DUT
+direction; unexpected software fallback fails. Known AES-GCM-128-only
+drivers skip the AES-GCM-256 case.
+
+The record-type cases require DUT TX offload. They install TLS_RX after
+TLS_TX, buffer application data with MSG_MORE, then send a handshake or
+alert record. The peer verifies both record types and payloads. Running
+with RX offload enabled covers hardware RX setup; running with it disabled
+also covers software RX setup on a socket with hardware TX offload.
+
+Run without other kTLS workloads in either endpoint's network namespace:
+the tests compare shared TLS MIB and NIC counter snapshots. Build the helper
+with ``make -C tools/testing/selftests/drivers/net/hw tls_hw_offload`` and
+run ``tools/testing/selftests/drivers/net/hw/tls_hw_offload.py`` with the
+endpoint configuration. The harness deploys the helper to the peer.
+
 Guidance for test authors
 =========================
 
diff --git a/tools/testing/selftests/drivers/net/hw/.gitignore b/tools/testing/selftests/drivers/net/hw/.gitignore
index 46540468a7753..911a9bfeaf41e 100644
--- a/tools/testing/selftests/drivers/net/hw/.gitignore
+++ b/tools/testing/selftests/drivers/net/hw/.gitignore
@@ -1,4 +1,5 @@
 # SPDX-License-Identifier: GPL-2.0-only
 iou-zcrx
 ncdevmem
+tls_hw_offload
 toeplitz
diff --git a/tools/testing/selftests/drivers/net/hw/Makefile b/tools/testing/selftests/drivers/net/hw/Makefile
index 78bb0169350b2..ee412ec930231 100644
--- a/tools/testing/selftests/drivers/net/hw/Makefile
+++ b/tools/testing/selftests/drivers/net/hw/Makefile
@@ -45,6 +45,7 @@ TEST_PROGS = \
 	rss_drv.py \
 	rss_flow_label.py \
 	rss_input_xfrm.py \
+	tls_hw_offload.py \
 	toeplitz.py \
 	tso.py \
 	userns_devmem.py \
@@ -77,6 +78,7 @@ YNL_GEN_FILES := \
 # end of YNL_GEN_FILES
 TEST_GEN_FILES += $(YNL_GEN_FILES)
 TEST_GEN_FILES += $(patsubst %.c,%.o,$(wildcard *.bpf.c))
+TEST_GEN_FILES += tls_hw_offload
 
 include ../../../lib.mk
 
@@ -90,6 +92,8 @@ include ../../../net/ynl.mk
 
 include ../../../net/bpf.mk
 
+$(OUTPUT)/tls_hw_offload: CFLAGS += $(KHDR_INCLUDES)
+
 ifeq ($(HAS_IOURING_ZCRX),y)
 $(OUTPUT)/iou-zcrx: LDLIBS += -luring
 endif
diff --git a/tools/testing/selftests/drivers/net/hw/config b/tools/testing/selftests/drivers/net/hw/config
index d89a9ba176558..169e608516bd5 100644
--- a/tools/testing/selftests/drivers/net/hw/config
+++ b/tools/testing/selftests/drivers/net/hw/config
@@ -22,6 +22,8 @@ CONFIG_NET_IPIP=y
 CONFIG_NETKIT=y
 CONFIG_NET_SCH_INGRESS=y
 CONFIG_SYNC_FILE=y
+CONFIG_TLS=y
+CONFIG_TLS_DEVICE=y
 CONFIG_UDMABUF=y
 CONFIG_USER_NS=y
 CONFIG_VXLAN=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
new file mode 100644
index 0000000000000..4e9f8a2be8a8f
--- /dev/null
+++ b/tools/testing/selftests/drivers/net/hw/tls_hw_offload.c
@@ -0,0 +1,886 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * TLS Hardware Offload Two-Node Test
+ *
+ * Tests kTLS hardware offload between two physical nodes using
+ * hardcoded keys. Supports TLS 1.2 and AES-GCM-128/256.
+ *
+ * Both ends must run this helper: there is no handshake.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#include <limits.h>
+#include <time.h>
+#include <sys/time.h>
+#include <signal.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <netinet/tcp.h>
+#include <netdb.h>
+#include <linux/tls.h>
+
+#ifndef SOL_TLS
+#define SOL_TLS 282
+#endif
+
+#define TLS_RECORD_TYPE_HANDSHAKE		22
+#define TLS_RECORD_TYPE_ALERT			21
+#define TLS_RECORD_TYPE_DATA			23
+
+#define MIN_BUF_SIZE   16
+
+/* Initial key material */
+static struct tls12_crypto_info_aes_gcm_128 tls_info_key0_128 = {
+	.info = {
+		.version = TLS_1_2_VERSION,
+		.cipher_type = TLS_CIPHER_AES_GCM_128,
+	},
+	.iv = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 },
+	.key = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
+		 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10 },
+	.salt = { 0x01, 0x02, 0x03, 0x04 },
+	.rec_seq = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
+};
+
+static struct tls12_crypto_info_aes_gcm_256 tls_info_key0_256 = {
+	.info = {
+		.version = TLS_1_2_VERSION,
+		.cipher_type = TLS_CIPHER_AES_GCM_256,
+	},
+	.iv = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 },
+	.key = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
+		 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
+		 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
+		 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20 },
+	.salt = { 0x01, 0x02, 0x03, 0x04 },
+	.rec_seq = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
+};
+
+static int test_record_type;
+static int num_iterations = 100;
+static int cipher_type = TLS_CIPHER_AES_GCM_128;
+static int tls_version = TLS_1_2_VERSION;
+static int server_port = 4433;
+static char *server_ip;
+/* Address family to force: AF_UNSPEC (any), AF_INET (-4), AF_INET6 (-6). */
+static int force_family = AF_UNSPEC;
+
+static int send_size = 16384;
+static int random_size_max;
+/* Per-iteration progress output (-V). Off by default: the
+ * harness captures stdout in a pipe that is not drained until the helper
+ * exits, so unbounded per-record chatter (thousands of lines for the large
+ * echo variants) would fill the pipe, block printf(), stall the echo loop
+ * and surface as a bogus recv timeout on the peer. With -V off a run prints
+ * fixed setup/summary lines, comfortably inside a 64 KiB pipe.
+ */
+static int verbose;
+
+static const char *cipher_name(int cipher)
+{
+	switch (cipher) {
+	case TLS_CIPHER_AES_GCM_128: return "AES-GCM-128";
+	case TLS_CIPHER_AES_GCM_256: return "AES-GCM-256";
+	default: return "unknown";
+	}
+}
+
+static const char *version_name(int version)
+{
+	switch (version) {
+	case TLS_1_2_VERSION: return "TLS 1.2";
+	default: return "unknown";
+	}
+}
+
+static int setup_tls_ulp(int fd)
+{
+	int ret;
+
+	ret = setsockopt(fd, IPPROTO_TCP, TCP_ULP, "tls", sizeof("tls"));
+	if (ret < 0) {
+		printf("SETUP ERROR: TCP_ULP failed: %s\n", strerror(errno));
+		return -1;
+	}
+	return 0;
+}
+
+/* Echo mode drives both directions from a single thread: the
+ * client pushes a whole payload with one blocking send() and only reads the
+ * echo afterwards, while the server blocks in send() mid-echo. If a payload
+ * exceeds the peer's receive window the two sides deadlock - client stuck in
+ * send(), server stuck echoing, neither draining the other. Size the socket
+ * buffers so a full payload always fits in the peer's window (the forward
+ * send() then completes without needing the peer to read concurrently); the
+ * send/recv timeouts armed by set_io_timeouts() turn any residual stall into a
+ * loud EAGAIN instead of a hang.
+ */
+static void configure_echo_socket(int fd, int payload)
+{
+	int want = payload;
+
+	if (want < MIN_BUF_SIZE)
+		want = MIN_BUF_SIZE;
+
+	/* SO_*BUFFORCE bypasses the rmem_max/wmem_max sysctl caps (needs
+	 * CAP_NET_ADMIN); fall back to the best-effort, cap-limited option
+	 * when unprivileged - the timeouts below still turn any resulting
+	 * stall into a loud failure rather than a hang.
+	 */
+	if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &want, sizeof(want)) < 0)
+		setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &want, sizeof(want));
+	if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &want, sizeof(want)) < 0)
+		setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &want, sizeof(want));
+}
+
+/* Arm send/recv timeouts so any unexpected stall fails loudly with EAGAIN
+ * instead of hanging until the harness SIGKILLs us.
+ */
+static void set_io_timeouts(int fd)
+{
+	struct timeval tv = { .tv_sec = 8, .tv_usec = 0 };
+
+	setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
+	setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
+}
+
+/* Send the whole buffer, looping over short counts. A blocking SOCK_STREAM
+ * send() may return fewer bytes than requested (e.g. when SO_SNDTIMEO fires
+ * after partial progress) without setting errno, so a short count is not an
+ * error - only a negative return is.
+ */
+static int send_all(int fd, const char *buf, ssize_t len)
+{
+	ssize_t sent = 0;
+	ssize_t ret;
+
+	while (sent < len) {
+		ret = send(fd, buf + sent, len - sent, 0);
+		if (ret <= 0) {
+			/* 0 for a non-empty request would spin forever. */
+			printf("FAIL: send failed: %s\n",
+			       ret ? strerror(errno) : "no progress");
+			return -1;
+		}
+		sent += ret;
+	}
+	return 0;
+}
+
+static int recv_tls_message(int fd, char *buf, size_t buflen, int *record_type,
+			    int flags)
+{
+	char cmsg_buf[CMSG_SPACE(sizeof(unsigned char))];
+	struct msghdr msg = {0};
+	struct cmsghdr *cmsg;
+	struct iovec iov;
+	int ret;
+
+	iov.iov_base = buf;
+	iov.iov_len = buflen;
+
+	msg.msg_iov = &iov;
+	msg.msg_iovlen = 1;
+	msg.msg_control = cmsg_buf;
+	msg.msg_controllen = sizeof(cmsg_buf);
+
+	ret = recvmsg(fd, &msg, flags);
+	if (ret <= 0)
+		return ret;
+
+	cmsg = CMSG_FIRSTHDR(&msg);
+	if (cmsg && cmsg->cmsg_level == SOL_TLS &&
+	    cmsg->cmsg_type == TLS_GET_RECORD_TYPE)
+		*record_type = *((unsigned char *)CMSG_DATA(cmsg));
+
+	return ret;
+}
+
+static int install_tls_key(int fd, int direction, int cipher)
+{
+	const char *dir = direction == TLS_TX ? "TX" : "RX";
+	int ret;
+
+	if (verbose)
+		printf("Installing TLS_%s %s...\n", dir, cipher_name(cipher));
+
+	if (cipher == TLS_CIPHER_AES_GCM_256) {
+		struct tls12_crypto_info_aes_gcm_256 key;
+
+		memcpy(&key, &tls_info_key0_256, sizeof(key));
+		key.info.version = tls_version;
+		ret = setsockopt(fd, SOL_TLS, direction, &key, sizeof(key));
+	} else {
+		struct tls12_crypto_info_aes_gcm_128 key;
+
+		memcpy(&key, &tls_info_key0_128, sizeof(key));
+		key.info.version = tls_version;
+		ret = setsockopt(fd, SOL_TLS, direction, &key, sizeof(key));
+	}
+
+	if (ret < 0) {
+		printf("SETUP ERROR: TLS_%s %s failed: %s\n",
+		       dir, cipher_name(cipher), strerror(errno));
+		return -1;
+	}
+	printf("TLS_%s %s installed\n", dir, cipher_name(cipher));
+	return 0;
+}
+
+/* Open a TCP connection to server_ip:server_port, switch to the TLS
+ * ULP, and install initial TX/RX keys. Works over IPv4 or
+ * IPv6: getaddrinfo() resolves server_ip (honouring any -4/-6 forced
+ * family and %zone scope IDs in link-local addresses). Returns the fd on
+ * success, -1 on error (with the fd already closed).
+ */
+static int client_connect_tls(void)
+{
+	struct addrinfo hints = {0}, *res, *rp;
+	char port_str[16];
+	int csk = -1;
+	int ret;
+
+	hints.ai_family = force_family;
+	hints.ai_socktype = SOCK_STREAM;
+	hints.ai_protocol = IPPROTO_TCP;
+	snprintf(port_str, sizeof(port_str), "%d", server_port);
+
+	ret = getaddrinfo(server_ip, port_str, &hints, &res);
+	if (ret) {
+		printf("SETUP ERROR: getaddrinfo(%s): %s\n", server_ip,
+		       gai_strerror(ret));
+		return -1;
+	}
+
+	printf("Connecting to %s:%d...\n", server_ip, server_port);
+	for (rp = res; rp; rp = rp->ai_next) {
+		csk = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
+		if (csk < 0)
+			continue;
+		if (connect(csk, rp->ai_addr, rp->ai_addrlen) == 0)
+			break;
+		close(csk);
+		csk = -1;
+	}
+	freeaddrinfo(res);
+
+	if (csk < 0) {
+		printf("SETUP ERROR: connect to %s:%d failed: %s\n",
+		       server_ip, server_port, strerror(errno));
+		return -1;
+	}
+	printf("Connected!\n");
+
+	if (setup_tls_ulp(csk) < 0)
+		goto err;
+
+	if (install_tls_key(csk, TLS_TX, cipher_type) < 0 ||
+	    install_tls_key(csk, TLS_RX, cipher_type) < 0)
+		goto err;
+
+	set_io_timeouts(csk);
+	configure_echo_socket(csk, random_size_max > 0 ?
+				    random_size_max : send_size);
+
+	return csk;
+err:
+	close(csk);
+	return -1;
+}
+
+/* Drain `len` echoed bytes from the server and verify they match the
+ * payload we just sent.
+ */
+static int client_recv_echo(int fd, const char *sent, char *echo_buf,
+			    ssize_t len)
+{
+	ssize_t total = 0;
+	ssize_t n;
+
+	while (total < len) {
+		n = recv(fd, echo_buf + total, len - total, 0);
+		if (n < 0) {
+			printf("FAIL: Echo recv failed: %s\n", strerror(errno));
+			return -1;
+		}
+		if (n == 0) {
+			printf("FAIL: Connection closed during echo\n");
+			return -1;
+		}
+		total += n;
+	}
+
+	if (memcmp(sent, echo_buf, len) != 0) {
+		printf("FAIL: Echo data mismatch!\n");
+		return -1;
+	}
+	if (verbose)
+		printf("Received echo %zd bytes (ok)\n", total);
+	return 0;
+}
+
+static int do_client(void)
+{
+	char *buf = NULL, *echo_buf = NULL;
+	int max_size;
+	int csk = -1, i = 1;
+	int test_result = -1;
+	ssize_t n, total = 0;
+
+	max_size = random_size_max > 0 ? random_size_max : send_size;
+	if (max_size < MIN_BUF_SIZE)
+		max_size = MIN_BUF_SIZE;
+	buf = malloc(max_size);
+	echo_buf = malloc(max_size);
+	if (!buf || !echo_buf) {
+		printf("SETUP ERROR: failed to allocate buffers\n");
+		goto out;
+	}
+
+	csk = client_connect_tls();
+	if (csk < 0)
+		goto out;
+
+	printf("TLS setup complete.\n");
+
+	if (random_size_max > 0)
+		printf("Sending %d messages of random size (1..%d bytes)...\n",
+		       num_iterations, random_size_max);
+	else
+		printf("Sending %d messages of %d bytes...\n",
+		       num_iterations, send_size);
+
+	for (i = 1; i <= num_iterations; i++) {
+		int this_size;
+		int j;
+
+		if (random_size_max > 0)
+			this_size = (rand() % random_size_max) + 1;
+		else
+			this_size = send_size;
+
+		for (j = 0; j < this_size; j++)
+			buf[j] = rand() & 0xFF;
+
+		if (send_all(csk, buf, this_size) < 0)
+			goto out;
+		n = this_size;
+		total += n;
+
+		if (verbose)
+			printf("Sent %zd bytes (iteration %d)\n", n, i);
+		if (client_recv_echo(csk, buf, echo_buf, n) < 0)
+			goto out;
+	}
+
+	test_result = 0;
+out:
+	printf("Sent %d/%d iterations, %zd bytes\n", i - 1, num_iterations,
+	       total);
+	if (csk >= 0)
+		close(csk);
+	free(buf);
+	free(echo_buf);
+	return test_result;
+}
+
+/* Bind/listen on server_port, accept one client, switch to the TLS ULP
+ * and install initial keys.
+ * Returns the connected fd on success and writes the listener fd to
+ * *lsk_out so the caller can close it. Returns -1 on error, with all
+ * intermediate fds already closed and *lsk_out left at -1.
+ */
+static int server_accept_tls(int *lsk_out)
+{
+	struct addrinfo hints = {0}, *res, *rp;
+	int lsk = -1, csk, one = 1;
+	char port_str[16];
+	int ret;
+
+	*lsk_out = -1;
+
+	/* AI_PASSIVE gives a wildcard bind address for the chosen family
+	 * (0.0.0.0 / ::). The family is forced by -4/-6; when unspecified,
+	 * bind the first entry that works.
+	 */
+	hints.ai_family = force_family;
+	hints.ai_socktype = SOCK_STREAM;
+	hints.ai_protocol = IPPROTO_TCP;
+	hints.ai_flags = AI_PASSIVE;
+	snprintf(port_str, sizeof(port_str), "%d", server_port);
+
+	ret = getaddrinfo(NULL, port_str, &hints, &res);
+	if (ret) {
+		printf("SETUP ERROR: getaddrinfo(port %d): %s\n", server_port,
+		       gai_strerror(ret));
+		return -1;
+	}
+
+	for (rp = res; rp; rp = rp->ai_next) {
+		lsk = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
+		if (lsk < 0)
+			continue;
+		setsockopt(lsk, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
+		if (bind(lsk, rp->ai_addr, rp->ai_addrlen) == 0)
+			break;
+		close(lsk);
+		lsk = -1;
+	}
+	freeaddrinfo(res);
+
+	if (lsk < 0) {
+		printf("SETUP ERROR: failed to bind port %d: %s\n",
+		       server_port, strerror(errno));
+		return -1;
+	}
+
+	if (listen(lsk, 1) < 0) {
+		printf("SETUP ERROR: listen failed: %s\n", strerror(errno));
+		close(lsk);
+		return -1;
+	}
+
+	printf("Server listening on port %d\n", server_port);
+	printf("Waiting for client connection...\n");
+
+	/* Bound accept() so a client that never connects (a deploy or connect
+	 * failure on the peer) does not block the server forever. accept()
+	 * honours SO_RCVTIMEO on the listening socket; the client connects
+	 * right after wait_port_listen(), so 10s is generous, and it is well
+	 * inside the 20s the harness waits for the server to exit (the default
+	 * cmd.process() timeout) so the server is gone, and its listening port
+	 * released, before the next variant starts.
+	 */
+	{
+		struct timeval tv = { .tv_sec = 10, .tv_usec = 0 };
+
+		setsockopt(lsk, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
+	}
+
+	csk = accept(lsk, NULL, NULL);
+	if (csk < 0) {
+		if (errno == EAGAIN || errno == EWOULDBLOCK)
+			printf("SETUP ERROR: accept timed out; client never connected\n");
+		else
+			printf("SETUP ERROR: accept failed: %s\n", strerror(errno));
+		close(lsk);
+		return -1;
+	}
+	printf("Client connected!\n");
+
+	if (setup_tls_ulp(csk) < 0)
+		goto err;
+
+	if (install_tls_key(csk, TLS_TX, cipher_type) < 0 ||
+	    install_tls_key(csk, TLS_RX, cipher_type) < 0)
+		goto err;
+
+	set_io_timeouts(csk);
+	configure_echo_socket(csk, random_size_max > 0 ?
+				    random_size_max : send_size);
+
+	*lsk_out = lsk;
+	return csk;
+err:
+	close(csk);
+	close(lsk);
+	return -1;
+}
+
+static int do_server(void)
+{
+	int lsk = -1, csk = -1;
+	ssize_t n, total = 0;
+	int test_result = -1;
+	int recv_count = 0;
+	char *buf = NULL;
+	int record_type = 0;
+	int buf_size;
+
+	buf_size = send_size;
+	if (buf_size < MIN_BUF_SIZE)
+		buf_size = MIN_BUF_SIZE;
+	buf = malloc(buf_size);
+	if (!buf) {
+		printf("SETUP ERROR: failed to allocate buffer\n");
+		goto out;
+	}
+
+	csk = server_accept_tls(&lsk);
+	if (csk < 0)
+		goto out;
+
+	printf("TLS %s setup complete. Receiving...\n",
+	       cipher_name(cipher_type));
+
+	/* Echo everything back; the client verifies each echo. */
+	while (1) {
+		n = recv_tls_message(csk, buf, buf_size, &record_type, 0);
+		if (n == 0) {
+			printf("Connection closed by client\n");
+			break;
+		}
+		if (n < 0) {
+			printf("FAIL: recv failed: %s\n", strerror(errno));
+			goto out;
+		}
+
+		total += n;
+		recv_count++;
+		if (verbose)
+			printf("Received %zd bytes (total: %zd, count: %d)\n",
+			       n, total, recv_count);
+
+		if (send_all(csk, buf, n) < 0)
+			goto out;
+		if (verbose)
+			printf("Echoed %zd bytes back to client\n", n);
+	}
+
+	test_result = 0;
+out:
+	printf("Connection closed. Total received: %zd bytes in %d reads\n",
+	       total, recv_count);
+
+	if (csk >= 0)
+		close(csk);
+	if (lsk >= 0)
+		close(lsk);
+	free(buf);
+	return test_result;
+}
+
+static int send_record_type(int fd)
+{
+	char control[CMSG_SPACE(sizeof(unsigned char))] = {};
+	struct iovec iov = { .iov_base = "BBBB", .iov_len = 4 };
+	struct msghdr msg = {
+		.msg_iov = &iov,
+		.msg_iovlen = 1,
+		.msg_control = control,
+		.msg_controllen = sizeof(control),
+	};
+	struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
+	char ack[2];
+
+	if (send(fd, "AAAA", 4, MSG_MORE) != 4) {
+		printf("FAIL: send MSG_MORE failed: %s\n", strerror(errno));
+		return -1;
+	}
+	cmsg->cmsg_level = SOL_TLS;
+	cmsg->cmsg_type = TLS_SET_RECORD_TYPE;
+	cmsg->cmsg_len = CMSG_LEN(sizeof(unsigned char));
+	*CMSG_DATA(cmsg) = test_record_type;
+	if (sendmsg(fd, &msg, 0) != 4) {
+		printf("FAIL: sendmsg record type failed: %s\n",
+		       strerror(errno));
+		return -1;
+	}
+	return client_recv_echo(fd, "OK", ack, sizeof(ack));
+}
+
+static int expect_record(int fd, const char *data, unsigned char type)
+{
+	char control[CMSG_SPACE(sizeof(unsigned char))] = {};
+	char buf[16];
+	struct iovec iov = { .iov_base = buf, .iov_len = sizeof(buf) };
+	struct msghdr msg = {
+		.msg_iov = &iov,
+		.msg_iovlen = 1,
+		.msg_control = control,
+		.msg_controllen = sizeof(control),
+	};
+	struct cmsghdr *cmsg;
+	int ret;
+
+	ret = recvmsg(fd, &msg, 0);
+	if (ret != 4 || memcmp(buf, data, 4) ||
+	    (msg.msg_flags & (MSG_CTRUNC | MSG_TRUNC)) ||
+	    !(msg.msg_flags & MSG_EOR)) {
+		printf("FAIL: expected record '%s', got %d bytes, flags %#x\n",
+		       data, ret, msg.msg_flags);
+		return -1;
+	}
+	cmsg = CMSG_FIRSTHDR(&msg);
+	if (!cmsg || cmsg->cmsg_level != SOL_TLS ||
+	    cmsg->cmsg_type != TLS_GET_RECORD_TYPE ||
+	    cmsg->cmsg_len != CMSG_LEN(sizeof(unsigned char)) ||
+	    *CMSG_DATA(cmsg) != type) {
+		printf("FAIL: expected record type %u\n", type);
+		return -1;
+	}
+	return 0;
+}
+
+static int recv_record_type(int fd)
+{
+	char buf[16];
+	int ret;
+
+	if (expect_record(fd, "AAAA", TLS_RECORD_TYPE_DATA) ||
+	    expect_record(fd, "BBBB", test_record_type) ||
+	    send_all(fd, "OK", 2))
+		return -1;
+	ret = recv(fd, buf, sizeof(buf), 0);
+	if (ret) {
+		printf("FAIL: expected EOF after records, got %d\n", ret);
+		return -1;
+	}
+	return 0;
+}
+
+static int test_pending_record(int is_server)
+{
+	char *buf = NULL, *echo_buf = NULL;
+	int lsk = -1, csk = -1;
+	int test_result = -1;
+	int i;
+
+	buf = malloc(send_size);
+	echo_buf = malloc(send_size);
+	if (!buf || !echo_buf) {
+		printf("SETUP ERROR: failed to allocate buffers\n");
+		goto out;
+	}
+	memset(buf, 0xa5, send_size);
+
+	csk = is_server ? server_accept_tls(&lsk) : client_connect_tls();
+	if (csk < 0)
+		goto out;
+
+	/* Exercise hardware crypto before testing the record-type transition. */
+	for (i = 0; i < num_iterations; i++) {
+		if (!is_server && send_all(csk, buf, send_size) < 0)
+			goto out;
+		if (client_recv_echo(csk, buf, echo_buf, send_size) < 0)
+			goto out;
+		if (is_server && send_all(csk, buf, send_size) < 0)
+			goto out;
+	}
+
+	test_result = is_server ? recv_record_type(csk) : send_record_type(csk);
+out:
+	if (csk >= 0)
+		close(csk);
+	if (lsk >= 0)
+		close(lsk);
+	free(buf);
+	free(echo_buf);
+	return test_result;
+}
+
+static int parse_int_arg(const char *arg, int min, int max,
+			 const char *name, int *out)
+{
+	char *endp;
+	long val;
+
+	errno = 0;
+	val = strtol(arg, &endp, 10);
+	if (errno || endp == arg || *endp != '\0' || val < min || val > max) {
+		if (max == INT_MAX)
+			printf("ERROR: Invalid %s '%s'. Must be >= %d.\n",
+			       name, arg, min);
+		else
+			printf("ERROR: Invalid %s '%s'. Must be %d..%d.\n",
+			       name, arg, min, max);
+		return -1;
+	}
+	*out = (int)val;
+	return 0;
+}
+
+static int parse_cipher_option(const char *arg)
+{
+	if (strcmp(arg, "128") == 0) {
+		cipher_type = TLS_CIPHER_AES_GCM_128;
+		return 0;
+	} else if (strcmp(arg, "256") == 0) {
+		cipher_type = TLS_CIPHER_AES_GCM_256;
+		return 0;
+	}
+	printf("ERROR: Invalid cipher '%s'. Must be 128 or 256.\n", arg);
+	return -1;
+}
+
+static int parse_version_option(const char *arg)
+{
+	if (strcmp(arg, "1.2") == 0) {
+		tls_version = TLS_1_2_VERSION;
+		return 0;
+	}
+	printf("ERROR: Invalid TLS version '%s'. Must be 1.2.\n", arg);
+	return -1;
+}
+
+static void print_usage(const char *prog)
+{
+	printf("TLS Hardware Offload Two-Node Test\n\n");
+	printf("Usage:\n");
+	printf("  %s server [OPTIONS]\n", prog);
+	printf("  %s client -s <ip> [OPTIONS]\n", prog);
+	printf("\nOptions:\n");
+	printf("  -s <ip>       Server IP address, v4 or v6 (client, required)\n");
+	printf("  -p <port>     Server port (default: 4433)\n");
+	printf("  -4            Force IPv4 (default: auto/either)\n");
+	printf("  -6            Force IPv6 (default: auto/either)\n");
+	printf("  -b <size>     Send buffer size in bytes (default: 16384)\n");
+	printf("  -r <max>      Use random send buffer sizes (1..<max>)\n");
+	printf("  -v <version>  TLS version: 1.2 (default: 1.2)\n");
+	printf("  -c <cipher>   Cipher: 128 or 256 (default: 128)\n");
+	printf("  -n <N>        Number of send/echo iterations (default: 100)\n");
+	printf("  -t <type>     Test MSG_MORE followed by alert (21) or handshake (22)\n");
+	printf("  -V            Verbose: log every iteration\n");
+	printf("  -h            Show this help message\n");
+	printf("\nExample:\n");
+	printf("  Node A: %s server\n", prog);
+	printf("  Node B: %s client -s 192.168.20.2\n", prog);
+	printf("\nIPv6 Example:\n");
+	printf("  Node A: %s server -6\n", prog);
+	printf("  Node B: %s client -6 -s fd00::2\n", prog);
+}
+
+int main(int argc, char *argv[])
+{
+	int send_size_set = 0;
+	int is_server;
+	int opt;
+
+	/* When the peer aborts a TLS connection (e.g. tls_err_abort() on a
+	 * failed decrypt), a send() here would raise SIGPIPE and kill us by
+	 * signal, so the harness sees only a bare non-zero exit with no
+	 * "FAIL:" line. Ignore it and let send()/sendmsg() return EPIPE, which
+	 * send_all()/send_record_type() report.
+	 */
+	signal(SIGPIPE, SIG_IGN);
+
+	if (argc < 2 ||
+	    (strcmp(argv[1], "server") && strcmp(argv[1], "client"))) {
+		print_usage(argv[0]);
+		return 1;
+	}
+	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) {
+		switch (opt) {
+		case 's':
+			server_ip = optarg;
+			break;
+		case 'V':
+			verbose = 1;
+			break;
+		case '4':
+			if (force_family == AF_INET6) {
+				printf("ERROR: -4 and -6 are mutually exclusive\n");
+				return 1;
+			}
+			force_family = AF_INET;
+			break;
+		case '6':
+			if (force_family == AF_INET) {
+				printf("ERROR: -4 and -6 are mutually exclusive\n");
+				return 1;
+			}
+			force_family = AF_INET6;
+			break;
+		case 'p':
+			if (parse_int_arg(optarg, 1, 65535, "port",
+					  &server_port) < 0)
+				return 1;
+			break;
+		case 'b':
+			if (parse_int_arg(optarg, 1, INT_MAX, "buffer size",
+					  &send_size) < 0)
+				return 1;
+			send_size_set = 1;
+			break;
+		case 'r':
+			if (parse_int_arg(optarg, 1, INT_MAX, "random size",
+					  &random_size_max) < 0)
+				return 1;
+			break;
+		case 'c':
+			if (parse_cipher_option(optarg) < 0)
+				return 1;
+			break;
+		case 'v':
+			if (parse_version_option(optarg) < 0)
+				return 1;
+			break;
+		case 't':
+			if (parse_int_arg(optarg, TLS_RECORD_TYPE_ALERT,
+					  TLS_RECORD_TYPE_HANDSHAKE, "record type",
+					  &test_record_type) < 0)
+				return 1;
+			break;
+		case 'n':
+			/* The iteration loops use an inclusive int bound
+			 * (i <= num_iterations), so INT_MAX itself would
+			 * overflow the counter instead of terminating.
+			 */
+			if (parse_int_arg(optarg, 1, INT_MAX - 1,
+					  "iteration count",
+					  &num_iterations) < 0)
+				return 1;
+			break;
+		case 'h':
+			print_usage(argv[0]);
+			return 0;
+		default:
+			print_usage(argv[0]);
+			return 1;
+		}
+	}
+
+	if (send_size_set && random_size_max > 0) {
+		printf("ERROR: -b and -r are mutually exclusive\n");
+		return 1;
+	}
+
+	if (test_record_type && random_size_max) {
+		printf("ERROR: -t cannot be combined with -r\n");
+		return 1;
+	}
+
+	if (is_server) {
+		if (server_ip) {
+			printf("warning: -s is ignored in server mode\n");
+			server_ip = NULL;
+		}
+		if (random_size_max > 0) {
+			printf("warning: -r is ignored in server mode\n");
+			random_size_max = 0;
+		}
+	} else {
+		if (!server_ip) {
+			printf("ERROR: Client requires -s <ip> option\n");
+			return 1;
+		}
+	}
+
+	printf("TLS Version: %s\n", version_name(tls_version));
+	printf("Cipher: %s\n", cipher_name(cipher_type));
+	printf("Address family: %s\n",
+	       force_family == AF_INET ? "IPv4" :
+	       force_family == AF_INET6 ? "IPv6" : "auto");
+	if (random_size_max > 0)
+		printf("Buffer size: random (1..%d)\n", random_size_max);
+	else
+		printf("Buffer size: %d\n", send_size);
+
+	srand(time(NULL));
+
+	if (test_record_type)
+		return test_pending_record(is_server) ? 1 : 0;
+
+	if (is_server)
+		return do_server() ? 1 : 0;
+
+	return do_client() ? 1 : 0;
+}
diff --git a/tools/testing/selftests/drivers/net/hw/tls_hw_offload.py b/tools/testing/selftests/drivers/net/hw/tls_hw_offload.py
new file mode 100755
index 0000000000000..37f26e21a7b78
--- /dev/null
+++ b/tools/testing/selftests/drivers/net/hw/tls_hw_offload.py
@@ -0,0 +1,402 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-2.0
+
+"""Test kTLS hardware offload using a C helper binary."""
+
+import re
+import shlex
+import subprocess
+from collections import defaultdict
+
+from lib.py import ksft_run, ksft_exit, ksft_pr, KsftSkipEx
+from lib.py import ksft_ge, ksft_eq
+from lib.py import ksft_variants, KsftNamedVariant
+from lib.py import NetDrvEpEnv
+from lib.py import cmd, bkg, wait_port_listen, rand_port
+from lib.py import CmdExitFailure
+
+# Reading /proc/net/tls_stat is trivial locally, but on the remote it runs
+# over ssh, where connection setup can occasionally spike past the short
+# default cmd() timeout. Give these tiny reads plenty of headroom so a slow
+# ssh round-trip doesn't fail an otherwise-good variant.
+STATS_TIMEOUT_S = 30
+
+# `ethtool -S` counters on the DUT NIC, from the minimum set every TLS
+# offload driver should report (Documentation/networking/tls-offload.rst,
+# "Statistics"); mlx5, nfp, cxgb4 and funeth use exactly these names.
+# TlsTxDevice/TlsRxDevice in /proc/net/tls_stat only prove tls_dev_add()
+# accepted the offload:
+#  - *_packets increment once per packet the NIC actually encrypted or
+#    decrypted (mlx5 counts gso_segs, not records), so they prove the HW
+#    crypto path was exercised.
+#  - *_ctx increment once per tls_dev_add().
+# Missing NIC crypto counters remain optional.
+HW_NIC_COUNTERS = {
+    'Tx': {'crypto': 'tx_tls_encrypted_packets', 'ctx': 'tx_tls_ctx'},
+    'Rx': {'crypto': 'rx_tls_decrypted_packets', 'ctx': 'rx_tls_ctx'},
+}
+
+
+def check_tls_support(cfg):
+    """Require kTLS on both hosts and at least one DUT HW direction."""
+    # The tls module is autoloaded lazily on the first TCP_ULP="tls"
+    # setsockopt, so /proc/net/tls_stat (created from the module's pernet
+    # init) may not exist yet on a freshly booted host. Load the module
+    # explicitly before probing for it. Best effort only: with CONFIG_TLS=y
+    # (what the config fragment asks for) there is nothing to load, and
+    # modprobe may fail for reasons unrelated to kTLS (no modules.dep for a
+    # locally built kernel, no modprobe on a minimal rootfs). The
+    # /proc/net/tls_stat probe below is the authoritative check. Locally,
+    # cmd() runs without a shell, so a missing modprobe raises
+    # FileNotFoundError rather than returning a failed exit status.
+    try:
+        cmd("modprobe tls", fail=False)
+    except FileNotFoundError:
+        pass
+    cmd("modprobe tls", host=cfg.remote, fail=False)
+    try:
+        cmd("test -f /proc/net/tls_stat")
+        cmd("test -f /proc/net/tls_stat", host=cfg.remote)
+    except CmdExitFailure as e:
+        raise KsftSkipEx(f"kTLS not supported: {e}") from e
+
+    try:
+        features = cmd(f"ethtool -k {cfg.ifname}").stdout
+    except CmdExitFailure as e:
+        raise KsftSkipEx(f"Cannot determine TLS HW offload support: {e}") from e
+    cfg.tls_hw_directions = {
+        direction for direction in ('Tx', 'Rx')
+        if f'tls-hw-{direction.lower()}-offload: on' in features
+    }
+    if not cfg.tls_hw_directions:
+        raise KsftSkipEx("Device has no enabled TLS HW offload direction")
+
+
+def read_tls_stats(host=None):
+    """Snapshot the per-netns TLS MIB from /proc/net/tls_stat as a dict."""
+    # /proc/net/tls_stat exposes the per-netns TLS MIB (TLS_INC_STATS on
+    # sock_net(sk)). The test runs on a real NIC in the host namespace, so
+    # these counters are shared with anything else doing kTLS there. The
+    # strict before/after delta checks (zero error counters) assume no other
+    # kTLS activity in this namespace during a
+    # variant's window; concurrent kTLS users would perturb the deltas and
+    # cause spurious failures. Don't run other kTLS workloads alongside this
+    # test.
+    stats = defaultdict(int)
+    output = cmd("cat /proc/net/tls_stat", host=host, timeout=STATS_TIMEOUT_S)
+    for line in output.stdout.strip().split('\n'):
+        parts = line.split()
+        if len(parts) == 2:
+            stats[parts[0]] = int(parts[1])
+    return stats
+
+
+def read_nic_stats(cfg):
+    """Snapshot the DUT NIC's `ethtool -S` counters as a dict."""
+    # Driver per-record TLS counters from `ethtool -S` on the DUT NIC. Same
+    # before/after-delta caveat as read_tls_stats(): these are device-wide,
+    # so concurrent kTLS traffic on this NIC would perturb the deltas.
+    stats = defaultdict(int)
+    output = cmd(f"ethtool -S {cfg.ifname}").stdout
+    for line in output.strip().split('\n'):
+        key, sep, val = line.partition(':')
+        if sep and val.strip().isdigit():
+            stats[key.strip()] = int(val.strip())
+    return stats
+
+
+def stat_diff(before, after, key):
+    """Return the delta of counter `key` between two stat snapshots."""
+    return after[key] - before[key]
+
+
+def check_hw_crypto(cfg, nic_before, nic_after, hw_directions):
+    """Check DUT hardware crypto and initial key installs."""
+    for direction in hw_directions:
+        names = HW_NIC_COUNTERS[direction]
+
+        key = names['crypto']
+        if key in nic_after:
+            got = stat_diff(nic_before, nic_after, key)
+            ksft_ge(got, 1,
+                    comment=f"DUT {direction}: NIC reported no HW crypto "
+                            f"({key}={got})")
+        else:
+            ksft_pr(f"NOTE: DUT {direction}: '{key}' not exposed by "
+                    f"{cfg.ifname}, skipping HW crypto check")
+
+        key = names['ctx']
+        if key not in nic_after:
+            ksft_pr(f"NOTE: DUT {direction}: '{key}' not exposed by "
+                    f"{cfg.ifname}, skipping NIC context count check")
+            continue
+        ctx = stat_diff(nic_before, nic_after, key)
+        ksft_ge(ctx, 1,
+                comment=f"DUT {direction}: no HW context installed "
+                        f"({key}={ctx})")
+
+
+def check_path(before, after, direction, role, require_hw):
+    """Require HW for enabled DUT directions; otherwise HW or SW is fine."""
+    dev = stat_diff(before, after, f'Tls{direction}Device')
+    sw = stat_diff(before, after, f'Tls{direction}Sw')
+    if require_hw:
+        ksft_ge(dev, 1,
+                comment=f"{role} {direction}: HW offload not engaged "
+                        f"(Device={dev}, Sw={sw})")
+    else:
+        ksft_ge(dev + sw, 1,
+                comment=f"{role} {direction}: no TLS activity "
+                        f"(Device={dev}, Sw={sw})")
+
+
+def verify_tls_counters(stats_before, stats_after, is_dut, hw_directions=()):
+    """Verify TLS counters on one side of the connection.
+
+    is_dut: True for the local DUT.
+    hw_directions: DUT directions with enabled HW offload; other directions
+           may use SW kTLS but still undergo activity and error checks.
+    """
+    role = 'DUT' if is_dut else 'Peer'
+
+    # Echo mode drives both directions on both sides.
+    for direction in ('Tx', 'Rx'):
+        check_path(stats_before, stats_after, direction, role,
+                   require_hw=is_dut and direction in hw_directions)
+
+    ksft_eq(stat_diff(stats_before, stats_after, 'TlsDecryptError'), 0,
+            comment=f"{role}: TlsDecryptError expected 0")
+
+
+def stop_helper(helper):
+    """Reap a helper that is still running: SIGTERM, then SIGKILL.
+
+    cmd.process(terminate=True) sends SIGTERM and waits; if the process
+    ignores it there is no fallback and communicate() raises again from the
+    cleanup path, leaving the child alive. Escalate to SIGKILL instead.
+    """
+    try:
+        helper.process(terminate=True, fail=False, timeout=5)
+    except subprocess.TimeoutExpired:
+        helper.proc.kill()
+        helper.process(terminate=False, fail=False, timeout=5)
+
+
+def kill_remote_helper(cfg, helper_cmd):
+    """Stop this variant's remote helper and confirm that it has exited.
+
+    Signalling cmd.proc only reaches the local process, which for the ssh
+    backend is the ssh client, not the helper on the peer. Losing its stdout
+    does not stop the helper either: it ignores SIGPIPE so that a peer abort
+    is reported as EPIPE instead of a bare signal death. Left alone it keeps
+    driving kTLS (bumping the peer's TLS MIBs) into the next variant's
+    measurement window, or sits in accept() for the rest of its own timeout.
+    Match the complete command, including this variant's port, since the
+    netns backend uses the same binary path for both endpoints and other
+    runs. The anchors also exclude the shell executing the cleanup. Failure
+    to confirm exit must prevent later variants from taking counter
+    snapshots.
+    """
+    pattern = shlex.quote('^' + re.escape(helper_cmd) + '$')
+    cmd(f"""
+command -v pkill >/dev/null && command -v pgrep >/dev/null || exit 2
+for tls_signal in TERM KILL; do
+    pkill -"$tls_signal" -f -- {pattern}
+    tls_status=$?
+    [ "$tls_status" -le 1 ] || exit "$tls_status"
+    tls_attempt=0
+    while [ "$tls_attempt" -lt 50 ]; do
+        pgrep -f -- {pattern} >/dev/null
+        tls_status=$?
+        case "$tls_status" in
+            1) exit 0 ;;
+            0) ;;
+            *) exit "$tls_status" ;;
+        esac
+        sleep 0.1
+        tls_attempt=$((tls_attempt + 1))
+    done
+done
+echo 'TLS helper still running after SIGKILL' >&2
+exit 1
+""", host=cfg.remote, timeout=STATS_TIMEOUT_S)
+
+
+def run_tls_test(cfg, cipher="128", tls_version="1.2",
+                 buffer_size=None, random_max=None, ipver="4",
+                 record_type=None):
+    """Run the TLS offload test.
+
+    The DUT runs the TLS client and the remote runs the echo server.
+
+    ipver: '4' or '6' - IP version to run over. The C helper is forced to the
+           matching family with -4/-6 and connects to the peer's v4/v6 address.
+           Variants requesting '6' skip cleanly when the environment lacks IPv6
+           connectivity (require_ipver()).
+
+    The DUT (local) is the kernel under test; the remote is just a traffic
+    source/sink and may run any kernel without HW offload. Both sides run
+    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.
+    """
+    if cfg.cleanup_failed:
+        raise KsftSkipEx("Previous helper cleanup could not be confirmed")
+
+    cfg.require_ipver(ipver)
+
+    # Echo exercises both directions, allowing SW in a direction without
+    # HW support.
+    hw_directions = tuple(d for d in ('Tx', 'Rx') if d in cfg.tls_hw_directions)
+
+    if record_type and 'Tx' not in hw_directions:
+        raise KsftSkipEx("Record-type regression requires DUT TLS TX offload")
+
+    port = rand_port()
+    send_size = random_max or buffer_size
+
+    server_parts = [f"{cfg.bin_remote} server -p {port} -c {cipher}",
+                    f"-v {tls_version}", f"-{ipver}"]
+    if send_size:
+        server_parts.append(f"-b {send_size}")
+    if record_type:
+        server_parts.append(f"-t {record_type}")
+    server_cmd = " ".join(server_parts)
+
+    client_parts = [f"{cfg.bin_local} client -s {cfg.remote_addr_v[ipver]}",
+                    f"-p {port} -c {cipher} -v {tls_version} -{ipver}"]
+    if random_max:
+        client_parts.append(f"-r {random_max}")
+    elif buffer_size:
+        client_parts.append(f"-b {buffer_size}")
+    if record_type:
+        client_parts.append(f"-t {record_type}")
+    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)
+
+    # Both helpers run with their stdout captured in a pipe that is only
+    # drained once they exit, so the helper keeps its per-connection output
+    # small (see the note on verbose in tls_hw_offload.c); do not pass -V.
+    #
+    # On the failure path make sure nothing outlives the variant: a leaked
+    # helper keeps bumping the per-netns TLS counters (TlsDecryptError, ...)
+    # and would corrupt the before/after measurement
+    # window of a later variant. The local client is a direct child; the
+    # server on the peer needs kill_remote_helper().
+    server = None
+    client = None
+    try:
+        server = bkg(server_cmd, host=cfg.remote, exit_wait=True)
+        with server:
+            wait_port_listen(port, host=cfg.remote)
+            # Start the client in the background so we keep a handle to it.
+            # A foreground cmd() raises TimeoutExpired from inside its
+            # constructor if the client hangs, and since the child is not
+            # killed on timeout it would be left running with no handle to
+            # reap it.
+            client = cmd(client_cmd, background=True)
+            try:
+                client.process(terminate=False, fail=True, timeout=20)
+            finally:
+                if client.proc.poll() is None:
+                    stop_helper(client)
+    except BaseException:
+        # bkg.__exit__ reaps the server with a plain 20 s communicate()
+        # (SIGTERM first only on an exception). A server that hangs or
+        # ignores SIGTERM makes it raise TimeoutExpired with the process
+        # still alive; escalate to SIGKILL as for the client.
+        cfg.cleanup_failed = True
+        try:
+            try:
+                if client is not None and client.proc.poll() is None:
+                    stop_helper(client)
+            finally:
+                if server is not None and server.proc.poll() is None:
+                    stop_helper(server)
+        finally:
+            kill_remote_helper(cfg, server_cmd)
+        cfg.cleanup_failed = False
+        raise
+
+    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)
+
+    verify_tls_counters(stats_before_local, stats_after_local, is_dut=True,
+                        hw_directions=hw_directions)
+    check_hw_crypto(cfg, nic_before, nic_after, hw_directions)
+    verify_tls_counters(stats_before_remote, stats_after_remote, is_dut=False)
+
+
+# Drivers whose tls_dev_add() accepts only AES-GCM-128: nfp
+# (nfp_net_cipher_supported()), cxgb4 (chcr_ktls), funeth.
+GCM128_ONLY_DRIVERS = {"nfp", "nfp_netvf", "cxgb4", "funeth"}
+
+
+# The cipher/version matrix runs over IPv4; the socket setup is the only
+# IP-version-specific code path, so a single representative variant over
+# IPv6 is enough to cover it (it skips cleanly without v6 connectivity).
+# The suites below likewise stay on IPv4 to bound runtime.
+@ksft_variants([
+    KsftNamedVariant("tls12_aes128", "128", "1.2", "4"),
+    KsftNamedVariant("tls12_aes256", "256", "1.2", "4"),
+    KsftNamedVariant("tls12_aes128_ip6", "128", "1.2", "6"),
+])
+def test_tls_offload(cfg, cipher, tls_version, ipver):
+    """Cipher/version matrix over the HW offload data path."""
+    # The tls-hw-{tx,rx}-offload feature bits do not advertise cipher
+    # support, and there is no uAPI to query it. Skip AES-GCM-256 on drivers
+    # whose tls_dev_add() accepts only AES-GCM-128; keep the HW assertions
+    # for every other driver/cipher pair.
+    if tls_version == "1.2" and cipher == "256":
+        info = cmd(f"ethtool -i {cfg.ifname}", fail=False).stdout
+        for line in info.splitlines():
+            name, _, value = line.partition(':')
+            driver = value.strip()
+            if name.strip() == 'driver' and driver in GCM128_ONLY_DRIVERS:
+                raise KsftSkipEx(f"{driver} TLS offload supports only AES-GCM-128")
+
+    run_tls_test(cfg, cipher=cipher, tls_version=tls_version, ipver=ipver)
+
+
+@ksft_variants([
+    KsftNamedVariant("small_buf", 512),
+    KsftNamedVariant("large_buf", 2097152),
+    KsftNamedVariant("random_buf", None, 8192),
+])
+def test_tls_offload_sizes(cfg, buffer_size=None, random_max=None):
+    """Echo-mode TLS 1.2 across a range of buffer sizes."""
+    run_tls_test(cfg, cipher="128", tls_version="1.2",
+                 buffer_size=buffer_size, random_max=random_max)
+
+
+@ksft_variants([
+    KsftNamedVariant("handshake", 22),
+    KsftNamedVariant("alert", 21),
+])
+def test_tls_offload_record_type(cfg, record_type):
+    """RX setup must preserve the HW TX hook which flushes an open record."""
+    run_tls_test(cfg, record_type=record_type)
+
+
+def main() -> None:
+    """Set up the DUT/peer environment and run the offload test suites."""
+    with NetDrvEpEnv(__file__, nsim_test=False) as cfg:
+        cfg.bin_local = cfg.test_dir / "tls_hw_offload"
+        if not cfg.bin_local.exists():
+            raise KsftSkipEx(f"tls_hw_offload binary not found at {cfg.bin_local}")
+        cfg.bin_remote = cfg.remote.deploy(cfg.bin_local)
+        check_tls_support(cfg)
+        cfg.cleanup_failed = False
+
+        ksft_run([test_tls_offload, test_tls_offload_sizes,
+                  test_tls_offload_record_type], args=(cfg, ))
+    ksft_exit()
+
+
+if __name__ == "__main__":
+    main()

39/3 2026/10/21 04:14 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 19655
							output: 33
							thoughts: 236
						

Thoughts:
**Analyzing a Patch Series for KMSAN Fuzzing Needs**

Okay, so I've got this patch series in front of me, and my immediate goal is to figure out if it warrants a dedicated KMSAN fuzzing session. Let's break this down. First, I see the `MAINTAINERS` file has been updated, which usually means new testing or support infrastructure is involved. Then, I see a modification to `net/tls/tls_sw.c`. The change looks pretty focused around line 2591. It looks like we have a conditional assignment now: `ctx->push_pending_record`. Before, it was unconditional, and now it's only assigned if `tx` is true.

This seems significant, but I need more context. I'll need to use `read-file` or `grepper` on the area around line 2591 in `tls_sw.c` to understand the implications of this conditional logic. What's `tx`? What's `ctx`? What's `tls_sw_push_pending_record`? Does this change the flow in a way that KMSAN would find interesting? The addition of self-tests in `tools/testing/selftests/...` is a positive sign, but doesn't preclude the need for fuzzing. I need to understand what changed, and how the new logic interacts with the existing code to make an informed decision on whether to launch a dedicated fuzzing campaign. The self tests are useful, but might not expose all potential issues; fuzzing may still be relevant.



40/3 2026/10/21 04:14 tool grepper
0m Args:
{
  "Expression": "tls_set_sw_offload",
  "PathPrefixes": [
    "net/tls/"
  ]
}

Results:
{
  "Output": "net/tls/tls.h=147=int init_prot_info(struct tls_prot_info *prot,\n--\nnet/tls/tls.h-149-\t\t   const struct tls_cipher_desc *cipher_desc);\nnet/tls/tls.h:150:int tls_set_sw_offload(struct sock *sk, int tx,\nnet/tls/tls.h-151-\t\t       struct tls_crypto_info *new_crypto_info);\n--\nnet/tls/tls_device.c=1195=int tls_set_device_offload_rx(struct sock *sk, struct tls_context *ctx)\n--\nnet/tls/tls_device.c-1237-\tctx-\u003epriv_ctx_rx = context;\nnet/tls/tls_device.c:1238:\trc = tls_set_sw_offload(sk, 0, NULL);\nnet/tls/tls_device.c-1239-\tif (rc)\n--\nnet/tls/tls_main.c=623=static int do_tls_setsockopt_conf(struct sock *sk, sockptr_t optval,\n--\nnet/tls/tls_main.c-718-\t\t} else {\nnet/tls/tls_main.c:719:\t\t\trc = tls_set_sw_offload(sk, 1,\nnet/tls/tls_main.c-720-\t\t\t\t\t\tupdate ? crypto_info : NULL);\n--\nnet/tls/tls_main.c-738-\t\t} else {\nnet/tls/tls_main.c:739:\t\t\trc = tls_set_sw_offload(sk, 0,\nnet/tls/tls_main.c-740-\t\t\t\t\t\tupdate ? crypto_info : NULL);\n--\nnet/tls/tls_sw.c=2516=static void tls_finish_key_update(struct sock *sk, struct tls_context *tls_ctx)\n--\nnet/tls/tls_sw.c-2524-\nnet/tls/tls_sw.c:2525:int tls_set_sw_offload(struct sock *sk, int tx,\nnet/tls/tls_sw.c-2526-\t\t       struct tls_crypto_info *new_crypto_info)\n"
}

41/3 2026/10/21 04:14 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 20837
							output: 38
							thoughts: 28
						

Thoughts:
Okay, let's dive into this. Here's my take on those lines of code:

**Analyzing `net/tls/tls_sw.c` Around Line 2525-2610**

Alright, time to get my hands dirty. I'm focusing in on `net/tls/tls_sw.c` between lines 2525 and 2610. Based on what I've seen in the surrounding code and my understanding of the TLS/SSL stack, I'm betting this section likely deals with the heart of the handshake process, perhaps specifically the key exchange. Considering the general structure, I expect to see the handling of messages involved in exchanging cryptographic keys, like `ServerKeyExchange`, `ClientKeyExchange`, or maybe even the calculation and verification of the pre-master secret. I'm also ready to see some critical error handling. This could involve checking message lengths, validating signatures, or handling unexpected state transitions. I'm particularly interested in seeing how the code interfaces with the underlying crypto primitives. Are they using OpenSSL, mbedTLS, or something else entirely? And how are the keying material derived from the pre-master secret and the shared secrets derived? I also expect to see some interesting bitwise operations happening as they manipulate the keys and secrets. Let's see how well it's written and if it's following the latest security recommendations. I'll be looking for any obvious vulnerabilities or potential for side-channel attacks. I anticipate spending a good bit of time here, ensuring my understanding of this vital part of the stack is rock solid.



42/3 2026/10/21 04:14 tool read-file
0m Args:
{
  "File": "net/tls/tls_sw.c",
  "FirstLine": 2570,
  "LineCount": 50
}

Results:
{
  "Contents": "2570:\t\tcipher_desc = get_cipher_desc(src_crypto_info-\u003ecipher_type);\n2571:\t\tif (!cipher_desc) {\n2572:\t\t\trc = -EINVAL;\n2573:\t\t\tgoto free_priv;\n2574:\t\t}\n2575:\t\n2576:\t\trc = init_prot_info(prot, src_crypto_info, cipher_desc);\n2577:\t\tif (rc)\n2578:\t\t\tgoto free_priv;\n2579:\t\n2580:\t\tiv = crypto_info_iv(src_crypto_info, cipher_desc);\n2581:\t\tkey = crypto_info_key(src_crypto_info, cipher_desc);\n2582:\t\tsalt = crypto_info_salt(src_crypto_info, cipher_desc);\n2583:\t\trec_seq = crypto_info_rec_seq(src_crypto_info, cipher_desc);\n2584:\t\n2585:\t\tif (!*aead) {\n2586:\t\t\t*aead = crypto_alloc_aead(cipher_desc-\u003ecipher_name, 0, 0);\n2587:\t\t\tif (IS_ERR(*aead)) {\n2588:\t\t\t\trc = PTR_ERR(*aead);\n2589:\t\t\t\t*aead = NULL;\n2590:\t\t\t\tgoto free_priv;\n2591:\t\t\t}\n2592:\t\t}\n2593:\t\n2594:\t\tif (tx)\n2595:\t\t\tctx-\u003epush_pending_record = tls_sw_push_pending_record;\n2596:\t\n2597:\t\t/* setkey is the last operation that could fail during a\n2598:\t\t * rekey. if it succeeds, we can start modifying the\n2599:\t\t * context.\n2600:\t\t */\n2601:\t\trc = crypto_aead_setkey(*aead, key, cipher_desc-\u003ekey);\n2602:\t\tif (rc) {\n2603:\t\t\tif (new_crypto_info)\n2604:\t\t\t\tgoto out;\n2605:\t\t\telse\n2606:\t\t\t\tgoto free_aead;\n2607:\t\t}\n2608:\t\n2609:\t\tif (!new_crypto_info) {\n2610:\t\t\trc = crypto_aead_setauthsize(*aead, prot-\u003etag_size);\n2611:\t\t\tif (rc)\n2612:\t\t\t\tgoto free_aead;\n2613:\t\t}\n2614:\t\n2615:\t\tif (!tx \u0026\u0026 !new_crypto_info) {\n2616:\t\t\ttfm = crypto_aead_tfm(sw_ctx_rx-\u003eaead_recv);\n2617:\t\n2618:\t\t\ttls_update_rx_zc_capable(ctx);\n2619:\t\t\tsw_ctx_rx-\u003easync_capable =\n"
}

43/3 2026/10/21 04:14 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 22003
							output: 30
							thoughts: 23
						

Thoughts:
Here's my analysis of the provided thought process, tailored for an expert audience:

**Analyzing `ctx->push_pending_record`**

Okay, so I'm diving into this `ctx->push_pending_record` variable. My first instinct is to understand its purpose and lifecycle. Specifically, I need to know: what function or functions define and modify it, and where does it get consumed or referenced? I'm assuming "ctx" is some sort of context object, likely containing state relevant to a transaction, operation, or data structure. The "push_pending_record" part suggests a mechanism for buffering or queueing a record for a subsequent operation, possibly a write, commit, or propagation step. Understanding its role is critical to following the data flow and potential error conditions. I need to quickly identify all call sites related to this variable and then trace backward and forward to grasp the entire flow of its value. I'll probably start with a grep or code search, looking for assignments and uses to build the bigger picture.



44/3 2026/10/21 04:15 tool grepper
0m Args:
{
  "Expression": "push_pending_record",
  "PathPrefixes": [
    "net/tls/"
  ]
}

Results:
{
  "Output": "net/tls/tls_device.c=674=EXPORT_SYMBOL(tls_get_record);\nnet/tls/tls_device.c-675-\nnet/tls/tls_device.c:676:static int tls_device_push_pending_record(struct sock *sk, int flags)\nnet/tls/tls_device.c-677-{\n--\nnet/tls/tls_device.c=1065=int tls_set_device_offload(struct sock *sk)\n--\nnet/tls/tls_device.c-1137-\tclean_acked_data_enable(tcp_sk(sk), \u0026tls_tcp_clean_acked);\nnet/tls/tls_device.c:1138:\tctx-\u003epush_pending_record = tls_device_push_pending_record;\nnet/tls/tls_device.c-1139-\n--\nnet/tls/tls_main.c=226=static int tls_handle_open_record(struct sock *sk, int flags)\n--\nnet/tls/tls_main.c-230-\tif (tls_is_pending_open_record(ctx))\nnet/tls/tls_main.c:231:\t\treturn ctx-\u003epush_pending_record(sk, flags);\nnet/tls/tls_main.c-232-\n--\nnet/tls/tls_sw.c=701=static int bpf_exec_tx_verdict(struct sk_msg *msg, struct sock *sk,\n--\nnet/tls/tls_sw.c-714-\nnet/tls/tls_sw.c:715:static int tls_sw_push_pending_record(struct sock *sk, int flags)\nnet/tls/tls_sw.c-716-{\n--\nnet/tls/tls_sw.c=1031=void tls_sw_splice_eof(struct socket *sock)\n--\nnet/tls/tls_sw.c-1048-retry:\nnet/tls/tls_sw.c:1049:\t/* same checks as in tls_sw_push_pending_record() */\nnet/tls/tls_sw.c-1050-\trec = ctx-\u003eopen_rec;\n--\nnet/tls/tls_sw.c=2525=int tls_set_sw_offload(struct sock *sk, int tx,\n--\nnet/tls/tls_sw.c-2594-\tif (tx)\nnet/tls/tls_sw.c:2595:\t\tctx-\u003epush_pending_record = tls_sw_push_pending_record;\nnet/tls/tls_sw.c-2596-\n"
}

45/3 2026/10/21 04:15 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 22938
							output: 30
							thoughts: 1140
						

Thoughts:
**KMSAN Applicability Analysis for TLS Offload Fix**

Okay, so I've been looking at this patch in `net/tls/tls_device.c` and immediately see the flaw in the current logic.  Essentially, the code was unconditionally setting `ctx->push_pending_record` to `tls_sw_push_pending_record` during RX configuration, even if device offload TX was already set up. This overwrites the proper handler, meaning TX operations were using the incorrect software-based function!  The fix is straightforward: only modify `ctx->push_pending_record` if `tx` (TX flag) is true. The selftest covers this record-type mix quite well.

Now, the important question is: does this change warrant a KMSAN run? This is key.  I know my rules.  We don't waste resources on KMSAN unless there's a specific *uninitialized memory* risk that *only* KMSAN would catch. KASAN, LOCKDEP, and the other standard checks handle the more typical memory safety issues.

So, let's break this down. The patch changes this:

```c
-	ctx->push_pending_record = tls_sw_push_pending_record;
+	if (tx)
+		ctx->push_pending_record = tls_sw_push_pending_record;
```

In the pre-patch scenario, for RX configuration it *always* set the `push_pending_record` to the software function, regardless of whether a hardware TX had been set. Now, with the `if (tx)` check, it only sets the software one if `tx` is true.  The crux of the matter is whether this introduces an uninitialized state for `push_pending_record` in the "else" case, that is, when the TX flag is false: could the `push_pending_record` be left uninitialized if TX is not configured?

The key here is where `ctx` (the `tls_context` structure) is allocated. I need to understand its lifecycle and initialization to fully assess the risk. I should quickly go check the allocation of `struct tls_context *ctx` in the `net/tls` subsystem. If `ctx` is initialized elsewhere, and if `push_pending_record` has an initial default or a separate initialization path if TX is not configured, then this patch is safe.

If `push_pending_record` *isn't* handled properly elsewhere, then there's a risk of an uninitialized function pointer if TX is never configured, or if TX is only ever configured via hardware. If that is the case, then this introduces a clear risk of reading uninitialized memory, because now we will bypass the SW setup, and we need to check how the context is instantiated, and what `push_pending_record` initially is (or should be). In that case, **I'd set `NeedsKMSAN=true`**.  I'm going to go check where `struct tls_context *ctx` is allocated...



46/3 2026/10/21 04:15 tool grepper
0m Args:
{
  "Expression": "tls_ctx_create",
  "PathPrefixes": [
    "net/tls/"
  ]
}

Results:
{
  "Output": "net/tls/tls.h=137=void __net_exit tls_proc_fini(struct net *net);\nnet/tls/tls.h-138-\nnet/tls/tls.h:139:struct tls_context *tls_ctx_create(struct sock *sk);\nnet/tls/tls.h-140-void tls_ctx_free(struct sock *sk, struct tls_context *ctx);\n--\nnet/tls/tls_main.c=907=static int tls_disconnect(struct sock *sk, int flags)\n--\nnet/tls/tls_main.c-911-\nnet/tls/tls_main.c:912:struct tls_context *tls_ctx_create(struct sock *sk)\nnet/tls/tls_main.c-913-{\n--\nnet/tls/tls_main.c=1038=static int tls_init(struct sock *sk)\n--\nnet/tls/tls_main.c-1055-\twrite_lock_bh(\u0026sk-\u003esk_callback_lock);\nnet/tls/tls_main.c:1056:\tctx = tls_ctx_create(sk);\nnet/tls/tls_main.c-1057-\tif (!ctx) {\n"
}

47/3 2026/10/21 04:15 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 25083
							output: 37
							thoughts: 23
						

Thoughts:
Here's a first-person summary, tailored for an expert audience, of the thought process described:

**Diving into the TLS Context Creation**

Okay, let's get down to brass tacks. I need to understand the innards of the TLS context creation, specifically within the NetBSD kernel's network stack. The place to start, obviously, is `tls_ctx_create` and its implementation. I'm going to pull up the source code for that function in `net/tls/tls_main.c` right away. I'm looking for the core initialization logic here – what data structures are being allocated, what security parameters are being set, what crypto engines are being hooked up, how key material might be handled, and what error conditions are accounted for. This function is likely the linchpin, and the way it’s structured will greatly influence how TLS connections are later established and managed in NetBSD. I'm hoping it's well-commented, but even without, I know how to infer the intent from the code itself. My mental model of TLS architecture is already pretty solid, so I'll be looking for any NetBSD-specific nuances or design decisions that might be interesting.



48/3 2026/10/21 04:15 tool read-file
0m Args:
{
  "File": "net/tls/tls_main.c",
  "FirstLine": 910,
  "LineCount": 30
}

Results:
{
  "Contents": " 910:\t}\n 911:\t\n 912:\tstruct tls_context *tls_ctx_create(struct sock *sk)\n 913:\t{\n 914:\t\tstruct inet_connection_sock *icsk = inet_csk(sk);\n 915:\t\tstruct tls_context *ctx;\n 916:\t\n 917:\t\tctx = kzalloc_obj(*ctx, GFP_ATOMIC);\n 918:\t\tif (!ctx)\n 919:\t\t\treturn NULL;\n 920:\t\n 921:\t\tmutex_init(\u0026ctx-\u003etx_lock);\n 922:\t\tctx-\u003esk_proto = READ_ONCE(sk-\u003esk_prot);\n 923:\t\tctx-\u003esk = sk;\n 924:\t\t/* Release semantic of rcu_assign_pointer() ensures that\n 925:\t\t * ctx-\u003esk_proto is visible before changing sk-\u003esk_prot in\n 926:\t\t * update_sk_prot(), and prevents reading uninitialized value in\n 927:\t\t * tls_{getsockopt, setsockopt}. Note that we do not need a\n 928:\t\t * read barrier in tls_{getsockopt,setsockopt} as there is an\n 929:\t\t * address dependency between sk-\u003esk_proto-\u003e{getsockopt,setsockopt}\n 930:\t\t * and ctx-\u003esk_proto.\n 931:\t\t */\n 932:\t\trcu_assign_pointer(icsk-\u003eicsk_ulp_data, ctx);\n 933:\t\treturn ctx;\n 934:\t}\n 935:\t\n 936:\tstatic void build_proto_ops(struct proto_ops ops[TLS_NUM_CONFIG][TLS_NUM_CONFIG],\n 937:\t\t\t\t    const struct proto_ops *base)\n 938:\t{\n 939:\t\tops[TLS_BASE][TLS_BASE] = *base;\n"
}

49/3 2026/10/21 04:15 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 25897
							output: 218
							thoughts: 907
						

Thoughts:
**Analyzing the kTLS Offload Configuration Fix**

Okay, let's break this down. My initial observation is that `ctx` is allocated using `kzalloc_obj`, which is critical because it zero-initializes the entire `tls_context` structure. This immediately mitigates the primary concern about uninitialized memory at the allocation stage. If `tx` isn't set, then `push_pending_record` retains its zero value or whatever value was previously assigned, likely by `tls_set_device_offload`. Diving into `tls_handle_open_record`, I see it uses `tls_is_pending_open_record`, which checks if `ctx->open_rec` is non-NULL. The open record only gets created during TX operations.  If TX is device offload, `ctx->push_pending_record` gets set to `tls_device_push_pending_record`.

The bug is in how RX offload configuration was previously handled. It looks like the code was erroneously overwriting `ctx->push_pending_record` with `tls_sw_push_pending_record` even when hardware TX offload had already been configured! The fix, `if (tx) ctx->push_pending_record = tls_sw_push_pending_record;`, prevents this overwrite during RX setup.

Now, my primary concern is whether this change introduces any risk of uninitialized memory usage or potential information leaks. Let's systematically go through the checks:

*   **No New Allocations:** No new memory allocations were introduced by this change, so we don't have to worry about allocation failures or uninitialized data in new allocations.
*   **Initialization is Robust:** There are no uninitialized variables or struct fields introduced. `ctx` is zero-initialized and any modifications are based on function arguments, preventing initialization errors.
*   **`kzalloc` is the Key:** `ctx` is kzalloc'd, guaranteeing zero-initialization of all members, including those function pointers, meaning we don't have to worry about undefined behavior.
*   **No Data Exposure:**  No data is copied to userspace and no new socket options are exposed to the user. This means even if uninitialized memory existed (which it doesn't), the user can't see it.
*   **Beyond the Fix:** The rest of the diff involves MAINTAINERS updates, documentation, and self-tests – which are only improvements, and not relevant to the KMSAN concerns.

Therefore, `NeedsKMSAN` is definitively false here.

Let me double-check:

*   **User Space Structures:** This patch doesn't modify kernel structures that are sent to user space, eliminating any risk there.
*   **Conditional Logic and Uninitialized Variables:** The conditional logic depends on the function argument `tx`, which is either 0 or 1, representing RX or TX setup, respectively. It's not dependent on potentially uninitialized variables.
*   **Data Structure Manipulation:** This patch modifies the conditional assignment of a *function pointer* in the `tls_context` structure, but `tls_context` has already been allocated and initialized.
*   **Bounds and Length Checks:**  The patch doesn't touch any bounds checks or lengths, so this is not a concern.

The bug being fixed was solely a functional issue in kTLS offload configuration where configuring RX offload inadvertently clobbered the function pointer `ctx->push_pending_record` on sockets also using HW TX offload. It's purely a control-flow/logic bug, not an uninitialized memory problem. No uninitialized memory is read or leaked.

Standard detectors like KASAN, LOCKDEP, and UBSAN are sufficient for this functional fix. KMSAN would be irrelevant.

Here's how I would summarize this:

1.  **Nature of the Patch:** The patch addresses a bug in `net/tls/tls_sw.c`. The `tls_set_sw_offload()` function inappropriately sets `ctx->push_pending_record` regardless of whether TX or RX offload is being configured. This caused issues when HW TX offload was followed by SW or HW RX offload, overwriting the TX pending record push callback. The patch fixes this by ensuring `ctx->push_pending_record` is only set when `tx` is true. The rest of the patch provides improvements to documentation and self-tests.
2.  **KMSAN vs. KASAN:**
    *   No memory is allocated or read without initialization. `struct tls_context` is allocated with `kzalloc_obj`, zero-initializing all members including function pointers.
    *   No kernel memory is leaked to user space or uninitialized struct padding exposed.
    *   The change is a conditional assignment of a function pointer based on an


50/3 2026/10/21 04:15 tool set-results
0m Args:
{
  "KMSANReasoning": "The patch modifies `tls_set_sw_offload()` in `net/tls/tls_sw.c` so that `ctx-\u003epush_pending_record` is only set when configuring the TX path (`if (tx)`). Previously, configuring RX offload on a socket that had hardware TX offload would overwrite `ctx-\u003epush_pending_record` with `tls_sw_push_pending_record`. The remainder of the patch adds a self-test and documentation.\n\n`struct tls_context` is allocated via `kzalloc_obj()` in `tls_ctx_create()`, ensuring all fields are zero-initialized from the start. The change merely guards the assignment of a function pointer based on the function argument `tx`. It does not introduce or expose any uninitialized memory reads, uninitialized branching conditions, or information leaks to userspace. Therefore, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false
}

Results:
{
  "KMSANReasoning": "The patch modifies `tls_set_sw_offload()` in `net/tls/tls_sw.c` so that `ctx-\u003epush_pending_record` is only set when configuring the TX path (`if (tx)`). Previously, configuring RX offload on a socket that had hardware TX offload would overwrite `ctx-\u003epush_pending_record` with `tls_sw_push_pending_record`. The remainder of the patch adds a self-test and documentation.\n\n`struct tls_context` is allocated via `kzalloc_obj()` in `tls_ctx_create()`, ensuring all fields are zero-initialized from the start. The change merely guards the assignment of a function pointer based on the function argument `tx`. It does not introduce or expose any uninitialized memory reads, uninitialized branching conditions, or information leaks to userspace. Therefore, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false
}

LLM Calls Summary:
Total Calls Total Tokens Avg Tokens Total Duration (Seconds) Avg Duration (Seconds)
Tool Calls Summary:
Total Calls Total Duration (Seconds) Avg Duration (Seconds)