All of lore.kernel.org
 help / color / mirror / Atom feed
* [PATCH net-next 0/23] pull-request: can-next 2026-12-03
@ 2026-12-02 23:04 Marc Kleine-Budde
  2026-12-02 23:04 ` [PATCH net-next 01/23] selftests: can: install net/lib.sh with the CAN tests Marc Kleine-Budde
                   ` (22 more replies)
  0 siblings, 23 replies; 27+ messages in thread
From: Marc Kleine-Budde @ 2026-12-02 23:04 UTC (permalink / raw)
  To: netdev; +Cc: davem, kuba, linux-can, kernel

Hello netdev-team,

this is a pull request of 23 patches for net-next/main.

The first 9 patches are by Oleksij Rempel and add self tests for the
CAN J1939 protocol.

The remaining patches target the peak_usb driver and fix various
problems mainly found by LLM review. The first is by Stefan Günther,
the remaining ones by Stéphane Grosjean.

regards,
Marc

The following changes since commit c63b67b946fcd4efb24439f70ee081dfa485dc40:

  tools: ynl: reject missing regen path argument (2026-12-02 19:13:17 +0100)

are available in the Git repository at:

  git://git.kernel.org/pub/scm/linux/kernel/git/mkl/linux-can-next.git tags/linux-can-next-for-7.5-20261203

for you to fetch changes up to bd650ec39de3abb8339c5b453f3e48da389d1e52:

  Merge patch series "can: peak_usb: fixes and input validation hardening" (2026-12-02 23:58:16 +0100)

----------------------------------------------------------------
linux-can-next-for-7.5-20261203

----------------------------------------------------------------
Marc Kleine-Budde (2):
      Merge patch series "selftests: can: add J1939 socket and transport tests"
      Merge patch series "can: peak_usb: fixes and input validation hardening"

Oleksij Rempel (9):
      selftests: can: install net/lib.sh with the CAN tests
      selftests: can: add J1939 test helper header and library
      selftests: can: add J1939 base functional tests
      selftests: can: add J1939 socket option and metadata tests
      selftests: can: add J1939 addressing and concurrency tests
      selftests: can: add J1939 wire-format tests against CAN_RAW
      selftests: can: add J1939 TP/ETP multi-frame tests against CAN_RAW
      selftests: can: cover J1939 transport abort and timeout paths
      selftests: can: check SO_J1939_PROMISC receive effect

Stefan Günther (1):
      can: peak_usb: fix missing CAN_ERR_FLAG when reporting error counters

Stéphane Grosjean (13):
      can: peak_usb: harden PCAN-USB message validation
      can: peak_usb: replace open-coded bitmask operations with bitops
      can: peak_usb: harden channel handling in PCAN-USB FD
      can: peak_usb: fix RX cursor desync for self-received RTR frames with SRR
      can: peak_usb: reject records for unset channels in PCAN-USB Pro
      can: peak_usb: register the netdevs only once all channels are set up
      can: peak_usb: validate the data length of PCAN-USB Pro CAN records
      can: peak_usb: don't read past the message in PCAN-USB Pro decoders
      can: peak_usb: dump undecodable URBs once and rate limit decode errors
      can: peak_usb: don't return an uninitialized PCAN-USB CAN channel ID
      can: peak_usb: pass the dev_num argument of PCAN-USB Pro GETDEVID
      can: peak_usb: don't send uninitialized stack bytes to PCAN-USB devices
      can: peak_usb: don't send uninitialized heap bytes in restart commands

 MAINTAINERS                                        |   1 +
 drivers/net/can/usb/peak_usb/pcan_usb.c            |  69 +-
 drivers/net/can/usb/peak_usb/pcan_usb_core.c       | 111 ++-
 drivers/net/can/usb/peak_usb/pcan_usb_core.h       |  10 +-
 drivers/net/can/usb/peak_usb/pcan_usb_fd.c         |  91 +-
 drivers/net/can/usb/peak_usb/pcan_usb_pro.c        |  85 +-
 tools/testing/selftests/net/can/.gitignore         |   6 +
 tools/testing/selftests/net/can/Makefile           |  26 +-
 tools/testing/selftests/net/can/config             |   3 +
 tools/testing/selftests/net/can/j1939_gw.c         | 129 +++
 tools/testing/selftests/net/can/j1939_helpers.c    | 593 +++++++++++++
 tools/testing/selftests/net/can/j1939_helpers.h    | 328 +++++++
 tools/testing/selftests/net/can/j1939_lib.sh       | 171 ++++
 tools/testing/selftests/net/can/j1939_tests.h      |  99 +++
 tools/testing/selftests/net/can/test_j1939_addr.c  | 233 +++++
 tools/testing/selftests/net/can/test_j1939_addr.sh |   4 +
 tools/testing/selftests/net/can/test_j1939_base.c  | 241 ++++++
 tools/testing/selftests/net/can/test_j1939_base.sh |   7 +
 tools/testing/selftests/net/can/test_j1939_multi.c | 964 +++++++++++++++++++++
 .../testing/selftests/net/can/test_j1939_multi.sh  |   4 +
 tools/testing/selftests/net/can/test_j1939_opts.c  | 442 ++++++++++
 tools/testing/selftests/net/can/test_j1939_opts.sh |   4 +
 tools/testing/selftests/net/can/test_j1939_wire.c  | 202 +++++
 tools/testing/selftests/net/can/test_j1939_wire.sh |   4 +
 24 files changed, 3709 insertions(+), 118 deletions(-)
 create mode 100644 tools/testing/selftests/net/can/j1939_gw.c
 create mode 100644 tools/testing/selftests/net/can/j1939_helpers.c
 create mode 100644 tools/testing/selftests/net/can/j1939_helpers.h
 create mode 100644 tools/testing/selftests/net/can/j1939_lib.sh
 create mode 100644 tools/testing/selftests/net/can/j1939_tests.h
 create mode 100644 tools/testing/selftests/net/can/test_j1939_addr.c
 create mode 100755 tools/testing/selftests/net/can/test_j1939_addr.sh
 create mode 100644 tools/testing/selftests/net/can/test_j1939_base.c
 create mode 100755 tools/testing/selftests/net/can/test_j1939_base.sh
 create mode 100644 tools/testing/selftests/net/can/test_j1939_multi.c
 create mode 100755 tools/testing/selftests/net/can/test_j1939_multi.sh
 create mode 100644 tools/testing/selftests/net/can/test_j1939_opts.c
 create mode 100755 tools/testing/selftests/net/can/test_j1939_opts.sh
 create mode 100644 tools/testing/selftests/net/can/test_j1939_wire.c
 create mode 100755 tools/testing/selftests/net/can/test_j1939_wire.sh

^ permalink raw reply	[flat|nested] 27+ messages in thread

* [PATCH net-next 01/23] selftests: can: install net/lib.sh with the CAN tests
  2026-12-02 23:04 [PATCH net-next 0/23] pull-request: can-next 2026-12-03 Marc Kleine-Budde
@ 2026-12-02 23:04 ` Marc Kleine-Budde
  2026-12-02 23:15   ` netdev-bot+sinfo
  2026-12-02 23:04 ` [PATCH net-next 02/23] selftests: can: add J1939 test helper header and library Marc Kleine-Budde
                   ` (21 subsequent siblings)
  22 siblings, 1 reply; 27+ messages in thread
From: Marc Kleine-Budde @ 2026-12-02 23:04 UTC (permalink / raw)
  To: netdev; +Cc: davem, kuba, linux-can, kernel, Oleksij Rempel, Marc Kleine-Budde

From: Oleksij Rempel <o.rempel@pengutronix.de>

Add ../lib.sh and ../lib/sh/*.sh to TEST_INCLUDES. net/lib.sh sources
lib/sh/defer.sh. The install needs lib.sh and the lib/sh scripts.

test_raw_filter.sh sources ../lib.sh, but the Makefile does not install
lib.sh. A full selftest install works, because the net tests install
lib.sh. An install of only net/can does not work. The installed
test_raw_filter.sh cannot find lib.sh.

Found by installing the tests with "make TARGETS=net/can install". With
this change the installed test_raw_filter.sh runs.

Fixes: 77442ffa83e8 ("selftests: can: Import tst-filter from can-tests")
Signed-off-by: Oleksij Rempel <o.rempel@pengutronix.de>
Link: https://patch.msgid.link/20261130-j1939-selftests-v7-1-2491693ccb8d@pengutronix.de
Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
---
 tools/testing/selftests/net/can/Makefile | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/tools/testing/selftests/net/can/Makefile b/tools/testing/selftests/net/can/Makefile
index 5b82e60a03e7..3adaa13dcbfa 100644
--- a/tools/testing/selftests/net/can/Makefile
+++ b/tools/testing/selftests/net/can/Makefile
@@ -6,6 +6,8 @@ CFLAGS += -Wall -Wl,--no-as-needed -O2 -g -I$(top_srcdir)/usr/include $(KHDR_INC
 
 TEST_PROGS := test_raw_filter.sh
 
+TEST_INCLUDES := ../lib.sh $(wildcard ../lib/sh/*.sh)
+
 TEST_GEN_FILES := test_raw_filter
 
 include ../../lib.mk

base-commit: c63b67b946fcd4efb24439f70ee081dfa485dc40
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH net-next 02/23] selftests: can: add J1939 test helper header and library
  2026-12-02 23:04 [PATCH net-next 0/23] pull-request: can-next 2026-12-03 Marc Kleine-Budde
  2026-12-02 23:04 ` [PATCH net-next 01/23] selftests: can: install net/lib.sh with the CAN tests Marc Kleine-Budde
@ 2026-12-02 23:04 ` Marc Kleine-Budde
  2026-12-02 23:26   ` sashiko-bot
  2026-12-02 23:04 ` [PATCH net-next 03/23] selftests: can: add J1939 base functional tests Marc Kleine-Budde
                   ` (20 subsequent siblings)
  22 siblings, 1 reply; 27+ messages in thread
From: Marc Kleine-Budde @ 2026-12-02 23:04 UTC (permalink / raw)
  To: netdev; +Cc: davem, kuba, linux-can, kernel, Oleksij Rempel, Marc Kleine-Budde

From: Oleksij Rempel <o.rempel@pengutronix.de>

Add code shared by the later J1939 selftests. j1939_helpers.h and
j1939_helpers.c hold the C helpers for socket setup, timed receive and
CAN id encoding. They also hold the helpers for TP and ETP frames. Only
the multi-frame tests build those frames. j1939_tests.h holds the parts
that use the kselftest harness: the fixture setup macros and
j1939_test_main(). j1939_lib.sh holds the vcan setup and cleanup and the
test runner. A wrapper sources j1939_lib.sh and runs the test binary of
the same name.

j1939_lib.sh runs the tests only on vcan interfaces that it creates
itself. The tests that follow send frames as other nodes, so they must
not run on a real CAN bus.

By default the CAN_RAW peer gets its own vcan. The new j1939_gw sets up
CAN gateway rules that route frames between that vcan and the vcan of
the J1939 sockets. On one shared interface, the peer can read a frame
before the stack has handled the echo of that frame. A quick reply from
the peer then cancels a transport session. Behind the gateway, with RPS
turned off on the peer's vcan, the peer sees the frame only after the
stack has handled its echo. If RPS cannot be turned off, j1939_lib.sh
warns. J1939_SHARED_IF=1 runs the tests on one interface, with a
warning.

open_raw_rcvbuf() pins the test thread to the CPU it runs on. The
peer's frames enter the stack through netif_rx(), which keeps the order
only per CPU. On PREEMPT_RT, when a tool moved the test between CPUs
while other tasks sent CAN frames, a CAN_RAW reader on the J1939
interface saw the peer's frames out of order. The pin keeps the
scheduler from moving the test. It does not stop such a tool, which sets
the CPU affinity from outside, so the pin was not tested against that
failure. If the pinning fails, the test warns and runs unpinned.

Signed-off-by: Oleksij Rempel <o.rempel@pengutronix.de>
Link: https://patch.msgid.link/20261130-j1939-selftests-v7-2-2491693ccb8d@pengutronix.de
[mkl: add j1939 tests to J1939 section in MAINTAINERS]
[mkl: switch to static_assert(), use exiting DIV_ROUND_UP]
Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
---
 MAINTAINERS                                   |   1 +
 tools/testing/selftests/net/can/.gitignore    |   1 +
 tools/testing/selftests/net/can/Makefile      |   6 +-
 tools/testing/selftests/net/can/j1939_gw.c    | 129 +++++
 .../testing/selftests/net/can/j1939_helpers.c | 516 ++++++++++++++++++
 .../testing/selftests/net/can/j1939_helpers.h | 283 ++++++++++
 tools/testing/selftests/net/can/j1939_lib.sh  | 171 ++++++
 tools/testing/selftests/net/can/j1939_tests.h |  99 ++++
 8 files changed, 1205 insertions(+), 1 deletion(-)
 create mode 100644 tools/testing/selftests/net/can/j1939_gw.c
 create mode 100644 tools/testing/selftests/net/can/j1939_helpers.c
 create mode 100644 tools/testing/selftests/net/can/j1939_helpers.h
 create mode 100644 tools/testing/selftests/net/can/j1939_lib.sh
 create mode 100644 tools/testing/selftests/net/can/j1939_tests.h

diff --git a/MAINTAINERS b/MAINTAINERS
index 9336fa93ce38..56906f770199 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -6051,6 +6051,7 @@ S:	Maintained
 F:	Documentation/networking/j1939.rst
 F:	include/uapi/linux/can/j1939.h
 F:	net/can/j1939/
+F:	tools/testing/selftests/net/can/*j1939*
 
 CANAAN/KENDRYTE K210 SOC FPIOA DRIVER
 M:	Damien Le Moal <dlemoal@kernel.org>
diff --git a/tools/testing/selftests/net/can/.gitignore b/tools/testing/selftests/net/can/.gitignore
index 764a53fc837f..30cd8b40d0f8 100644
--- a/tools/testing/selftests/net/can/.gitignore
+++ b/tools/testing/selftests/net/can/.gitignore
@@ -1,2 +1,3 @@
 # SPDX-License-Identifier: GPL-2.0-only
+j1939_gw
 test_raw_filter
diff --git a/tools/testing/selftests/net/can/Makefile b/tools/testing/selftests/net/can/Makefile
index 3adaa13dcbfa..cf0b06974d54 100644
--- a/tools/testing/selftests/net/can/Makefile
+++ b/tools/testing/selftests/net/can/Makefile
@@ -2,12 +2,16 @@
 
 top_srcdir = ../../../../..
 
-CFLAGS += -Wall -Wl,--no-as-needed -O2 -g -I$(top_srcdir)/usr/include $(KHDR_INCLUDES)
+CFLAGS += -Wall -Wl,--no-as-needed -O2 -g -I$(top_srcdir)/usr/include -I$(top_srcdir)/tools/include $(KHDR_INCLUDES)
 
 TEST_PROGS := test_raw_filter.sh
 
+TEST_FILES := j1939_lib.sh
+
 TEST_INCLUDES := ../lib.sh $(wildcard ../lib/sh/*.sh)
 
 TEST_GEN_FILES := test_raw_filter
+# sets up the CAN gateway for j1939_lib.sh
+TEST_GEN_FILES += j1939_gw
 
 include ../../lib.mk
diff --git a/tools/testing/selftests/net/can/j1939_gw.c b/tools/testing/selftests/net/can/j1939_gw.c
new file mode 100644
index 000000000000..4018432add9a
--- /dev/null
+++ b/tools/testing/selftests/net/can/j1939_gw.c
@@ -0,0 +1,129 @@
+// SPDX-License-Identifier: (GPL-2.0-only OR BSD-3-Clause)
+/*
+ * Add CAN gateway (CONFIG_CAN_GW) rules that route frames both ways between
+ * two interfaces. j1939_lib.sh uses this because iproute2 cannot set up these
+ * rules. The kernel removes a rule when its interface is deleted.
+ *
+ * Usage: j1939_gw IF_A IF_B
+ */
+#include <errno.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <net/if.h>
+#include <sys/socket.h>
+
+#include <linux/can.h>
+#include <linux/can/gw.h>
+#include <linux/kernel.h>
+#include <linux/netlink.h>
+#include <linux/rtnetlink.h>
+
+/* an RTM_NEWROUTE request for a CAN->CAN rule, see net/can/gw.c */
+struct cgw_req {
+	struct nlmsghdr nh;
+	struct rtcanmsg rtcan;
+	struct rtattr src_attr;
+	__u32 src_ifindex;
+	struct rtattr dst_attr;
+	__u32 dst_ifindex;
+};
+
+struct cgw_ack {
+	struct nlmsghdr nh;
+	struct nlmsgerr err;
+};
+
+static_assert(offsetof(struct cgw_req, src_attr) ==
+	      NLMSG_SPACE(sizeof(struct rtcanmsg)),
+	      "the attributes must follow the aligned rtcanmsg");
+static_assert(offsetof(struct cgw_req, dst_attr) ==
+	      offsetof(struct cgw_req, src_attr) + RTA_SPACE(sizeof(__u32)),
+	      "the attributes must be packed as netlink aligns them");
+
+/* Add a rule from src to dst; return 0 or a negative errno. */
+static int cgw_add(int nl, unsigned int src, unsigned int dst)
+{
+	struct cgw_req req = {
+		.nh = {
+			.nlmsg_len = sizeof(req),
+			.nlmsg_type = RTM_NEWROUTE,
+			.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK,
+		},
+		.rtcan = {
+			.can_family = AF_CAN,
+			.gwtype = CGW_TYPE_CAN_CAN,
+			/*
+			 * a vcan has no bus, so only the echo reaches the
+			 * sockets on dst
+			 */
+			.flags = CGW_FLAGS_CAN_ECHO,
+		},
+		.src_attr = {
+			.rta_len = RTA_LENGTH(sizeof(req.src_ifindex)),
+			.rta_type = CGW_SRC_IF,
+		},
+		.src_ifindex = src,
+		.dst_attr = {
+			.rta_len = RTA_LENGTH(sizeof(req.dst_ifindex)),
+			.rta_type = CGW_DST_IF,
+		},
+		.dst_ifindex = dst,
+	};
+	struct cgw_ack ack;
+
+	if (send(nl, &req, sizeof(req), 0) < 0)
+		return -errno;
+	if (recv(nl, &ack, sizeof(ack), 0) < 0)
+		return -errno;
+
+	if (ack.nh.nlmsg_type != NLMSG_ERROR)
+		return -EPROTO;
+	return ack.err.error;
+}
+
+enum {
+	ARG_IF_A = 1,
+	ARG_IF_B,
+	ARG_COUNT	/* argc, including argv[0] */
+};
+
+int main(int argc, char **argv)
+{
+	unsigned int if_a, if_b;
+	int nl, ret;
+
+	if (argc != ARG_COUNT) {
+		fprintf(stderr, "usage: %s IF_A IF_B\n", argv[0]);
+		return EXIT_FAILURE;
+	}
+
+	if_a = if_nametoindex(argv[ARG_IF_A]);
+	if_b = if_nametoindex(argv[ARG_IF_B]);
+	if (!if_a || !if_b) {
+		fprintf(stderr, "%s: unknown interface\n", argv[0]);
+		return EXIT_FAILURE;
+	}
+
+	nl = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
+	if (nl < 0) {
+		fprintf(stderr, "%s: netlink socket: %s\n", argv[0],
+			strerror(errno));
+		return EXIT_FAILURE;
+	}
+
+	ret = cgw_add(nl, if_a, if_b);
+	if (!ret)
+		ret = cgw_add(nl, if_b, if_a);
+
+	close(nl);
+	if (ret) {
+		fprintf(stderr, "%s: cannot add CAN gateway rule: %s\n",
+			argv[0], strerror(-ret));
+		return EXIT_FAILURE;
+	}
+	return EXIT_SUCCESS;
+}
diff --git a/tools/testing/selftests/net/can/j1939_helpers.c b/tools/testing/selftests/net/can/j1939_helpers.c
new file mode 100644
index 000000000000..38c584d9c286
--- /dev/null
+++ b/tools/testing/selftests/net/can/j1939_helpers.c
@@ -0,0 +1,516 @@
+// SPDX-License-Identifier: (GPL-2.0-only OR BSD-3-Clause)
+/* Code of the shared J1939 selftest helpers, see j1939_helpers.h. */
+#include <sched.h>
+#include <sys/ioctl.h>
+
+#include "j1939_helpers.h"
+
+char CANIF[IFNAMSIZ];
+char CANIF_RAW[IFNAMSIZ];
+bool j1939_needs_raw;
+
+int j1939_id_prio(canid_t id)
+{
+	return (id >> J1939_ID_PRIO_SHIFT) & J1939_ID_PRIO_MASK;
+}
+
+int j1939_id_pgn(canid_t id)
+{
+	return (id >> J1939_ID_PGN_SHIFT) & J1939_PGN_MAX;
+}
+
+static int j1939_id_pf(canid_t id)
+{
+	return J1939_PF(j1939_id_pgn(id));
+}
+
+int j1939_id_ps(canid_t id)
+{
+	return j1939_id_pgn(id) & UINT8_MAX;
+}
+
+int j1939_id_sa(canid_t id)
+{
+	return id & UINT8_MAX;
+}
+
+bool j1939_is_data_frame(canid_t can_id)
+{
+	return (can_id & (CAN_EFF_FLAG | CAN_RTR_FLAG | CAN_ERR_FLAG)) ==
+	       CAN_EFF_FLAG;
+}
+
+/* Pin the calling thread to the CPU it runs on; any one CPU keeps the order. */
+static bool j1939_pin_cpu_ok(void)
+{
+	cpu_set_t set;
+	int cpu;
+
+	cpu = sched_getcpu();
+	if (cpu < 0)
+		return false;
+
+	CPU_ZERO(&set);
+	CPU_SET(cpu, &set);
+	return !sched_setaffinity(0, sizeof(set), &set);
+}
+
+int j1939_timing_ms(int relaxed_ms, int strict_ms)
+{
+	return getenv("J1939_STRICT_TIMING") ? strict_ms : relaxed_ms;
+}
+
+static int if_index(const char *ifname)
+{
+	struct ifreq ifr = {};
+	int idx = -1;
+	int s;
+
+	s = socket(PF_CAN, SOCK_DGRAM, CAN_J1939);
+	if (s < 0)
+		return -1;
+	snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s", ifname);
+	if (!ioctl(s, SIOCGIFINDEX, &ifr))
+		idx = ifr.ifr_ifindex;
+	close(s);
+	return idx;
+}
+
+int j1939_if_index(void)
+{
+	return if_index(CANIF);
+}
+
+/* Fill a sockaddr_can with the J1939 address (name, addr, pgn). */
+static void j1939_fill_sockaddr(struct sockaddr_can *out, int ifindex,
+				name_t name, uint8_t addr, pgn_t pgn)
+{
+	memset(out, 0, sizeof(*out));
+	out->can_family = AF_CAN;
+	out->can_ifindex = ifindex;
+	out->can_addr.j1939.name = name;
+	out->can_addr.j1939.addr = addr;
+	out->can_addr.j1939.pgn = pgn;
+}
+
+int j1939_open_flags(int ifindex, name_t name, uint8_t sa, pgn_t pgn, int flags)
+{
+	struct sockaddr_can addr;
+	int one = 1;
+	int s;
+
+	s = socket(PF_CAN, SOCK_DGRAM, CAN_J1939);
+	if (s < 0)
+		return -1;
+
+	if ((flags & J1939_OPEN_BCAST) &&
+	    setsockopt(s, SOL_SOCKET, SO_BROADCAST, &one, sizeof(one))) {
+		close(s);
+		return -1;
+	}
+
+	j1939_fill_sockaddr(&addr, ifindex, name, sa, pgn);
+	if (bind(s, (struct sockaddr *)&addr, sizeof(addr))) {
+		close(s);
+		return -1;
+	}
+	return s;
+}
+
+int j1939_open(int ifindex, uint8_t sa, pgn_t pgn)
+{
+	return j1939_open_flags(ifindex, J1939_NO_NAME, sa, pgn,
+				J1939_OPEN_NONE);
+}
+
+/* Connect a J1939 socket to the peer (name, da, pgn). */
+static bool j1939_connect_name_ok(int s, int ifindex, name_t name, uint8_t da,
+				  pgn_t pgn)
+{
+	struct sockaddr_can addr;
+
+	j1939_fill_sockaddr(&addr, ifindex, name, da, pgn);
+	return !connect(s, (struct sockaddr *)&addr, sizeof(addr));
+}
+
+bool j1939_connect_ok(int s, int ifindex, uint8_t da, pgn_t pgn)
+{
+	return j1939_connect_name_ok(s, ifindex, J1939_NO_NAME, da, pgn);
+}
+
+/* sendto() len bytes from buf to the J1939 destination dst. */
+static ssize_t j1939_sendto_addr(int s, const void *buf, size_t len,
+				 const struct sockaddr_can *dst)
+{
+	return sendto(s, buf, len, 0, (const struct sockaddr *)dst,
+		      sizeof(*dst));
+}
+
+/* sendto() len bytes from buf to the J1939 (name, da, pgn) destination. */
+static ssize_t j1939_sendto(int s, const void *buf, size_t len, int ifindex,
+			    name_t name, uint8_t da, pgn_t pgn)
+{
+	struct sockaddr_can dst;
+
+	j1939_fill_sockaddr(&dst, ifindex, name, da, pgn);
+	return j1939_sendto_addr(s, buf, len, &dst);
+}
+
+bool j1939_sendto_ok(int s, const void *buf, size_t len, int ifindex,
+		     name_t name, uint8_t da, pgn_t pgn)
+{
+	ssize_t want_len = len;
+
+	return j1939_sendto(s, buf, len, ifindex, name, da, pgn) == want_len;
+}
+
+bool send_all_ok(int s, const void *buf, size_t len)
+{
+	ssize_t want_len = len;
+
+	return send(s, buf, len, 0) == want_len;
+}
+
+bool write_all_ok(int fd, const void *buf, size_t len)
+{
+	ssize_t want_len = len;
+
+	return write(fd, buf, len) == want_len;
+}
+
+bool read_all_ok(int fd, void *buf, size_t len)
+{
+	ssize_t want_len = len;
+
+	return read(fd, buf, len) == want_len;
+}
+
+int open_raw_rcvbuf(int rcvbuf)
+{
+	struct sockaddr_can addr = {
+		.can_family = AF_CAN,
+	};
+	int s;
+
+	if (!j1939_needs_raw) {
+		fprintf(stderr, "# %s: the test did not pass J1939_NEEDS_RAW\n",
+			__func__);
+		errno = EINVAL;
+		return -1;
+	}
+
+	/*
+	 * netif_rx() keeps the peer's frames in order only per CPU, so keep
+	 * the scheduler from moving this thread.
+	 */
+	if (!j1939_pin_cpu_ok()) {
+		fprintf(stderr, "# %s: cannot pin to one CPU: %d\n", __func__,
+			errno);
+	}
+
+	addr.can_ifindex = if_index(CANIF_RAW);
+
+	s = socket(PF_CAN, SOCK_RAW, CAN_RAW);
+	if (s < 0)
+		return -1;
+
+	if (rcvbuf != J1939_RAW_RCVBUF_DEFAULT &&
+	    setsockopt(s, SOL_SOCKET, SO_RCVBUFFORCE, &rcvbuf,
+		       sizeof(rcvbuf))) {
+		fprintf(stderr, "# %s: SO_RCVBUFFORCE(%d) failed: %d\n",
+			__func__, rcvbuf, errno);
+	}
+
+	if (bind(s, (struct sockaddr *)&addr, sizeof(addr))) {
+		close(s);
+		return -1;
+	}
+	return s;
+}
+
+int open_raw(void)
+{
+	return open_raw_rcvbuf(J1939_RAW_RCVBUF_DEFAULT);
+}
+
+/* poll() + recv(): returns the recv() result, or -1 on timeout/error. */
+static ssize_t recv_timeout(int s, void *buf, size_t len, int timeout_ms)
+{
+	struct pollfd pfd = { .fd = s, .events = POLLIN };
+
+	if (poll(&pfd, 1, timeout_ms) <= 0)
+		return -1;
+	return recv(s, buf, len, 0);
+}
+
+bool recvfrom_verify_ok(int s, const void *want, size_t len, int timeout_ms,
+			struct sockaddr_can *src)
+{
+	struct pollfd pfd = { .fd = s, .events = POLLIN };
+	socklen_t src_len = sizeof(*src);
+	ssize_t want_len = len;
+	uint8_t *rx_buf;
+	ssize_t n = -1;
+	size_t rx_len;
+	bool ok;
+
+	rx_len = len + 1;
+	rx_buf = malloc(rx_len);
+	if (!rx_buf)
+		return false;
+
+	if (poll(&pfd, 1, timeout_ms) > 0) {
+		n = recvfrom(s, rx_buf, rx_len, 0, (struct sockaddr *)src,
+			     &src_len);
+	}
+	ok = n == want_len && !memcmp(want, rx_buf, len);
+
+	free(rx_buf);
+	return ok;
+}
+
+bool recv_verify_ok(int s, const void *want, size_t len, int timeout_ms)
+{
+	return recvfrom_verify_ok(s, want, len, timeout_ms, NULL);
+}
+
+bool send_recv_verify_ok(int tx, int rx, const void *buf, size_t len,
+			 int timeout_ms)
+{
+	if (!send_all_ok(tx, buf, len))
+		return false;
+	return recv_verify_ok(rx, buf, len, timeout_ms);
+}
+
+bool recv_frame_ok(int raw, struct can_frame *frame, int timeout_ms)
+{
+	ssize_t want_len = sizeof(*frame);
+
+	return recv_timeout(raw, frame, sizeof(*frame), timeout_ms) == want_len;
+}
+
+/*
+ * Build the 29-bit CAN id of a J1939 frame. prio must fit in
+ * J1939_ID_PRIO_BITS, and the PS byte of a PDU1 pgn must be 0.
+ */
+static canid_t j1939_canid(uint8_t prio, pgn_t pgn, uint8_t da, uint8_t sa)
+{
+	canid_t id;
+
+	id = CAN_EFF_FLAG | (prio << J1939_ID_PRIO_SHIFT) |
+	     (pgn << J1939_ID_PGN_SHIFT) | sa;
+
+	/* PDU1: the destination goes into the PS byte; PDU2 ignores da */
+	if (J1939_IS_PDU1(pgn))
+		id |= da << J1939_ID_PGN_SHIFT;
+	return id;
+}
+
+void cm_dat_init(uint8_t *dat, uint8_t cmd)
+{
+	memset(dat, J1939_FILL_BYTE, CAN_MAX_DLEN);
+	dat[J1939_CM_CMD_OFF] = cmd;
+}
+
+static void put_le(uint8_t *p, uint32_t v, size_t n)
+{
+	size_t i;
+
+	for (i = 0; i < n; i++)
+		p[i] = v >> (CHAR_BIT * i);
+}
+
+static uint32_t get_le(const uint8_t *p, size_t n)
+{
+	uint32_t v = 0;
+	size_t i;
+
+	for (i = 0; i < n; i++) {
+		uint32_t byte = p[i];
+
+		v |= byte << (CHAR_BIT * i);
+	}
+	return v;
+}
+
+void put_le16(uint8_t *p, uint16_t v)
+{
+	put_le(p, v, sizeof(v));
+}
+
+void put_le24(uint8_t *p, uint32_t v)
+{
+	put_le(p, v, J1939_LE24_LEN);
+}
+
+void put_le32(uint8_t *p, uint32_t v)
+{
+	put_le(p, v, sizeof(v));
+}
+
+uint16_t get_le16(const uint8_t *p)
+{
+	return get_le(p, sizeof(uint16_t));
+}
+
+uint32_t get_le24(const uint8_t *p)
+{
+	return get_le(p, J1939_LE24_LEN);
+}
+
+uint32_t get_le32(const uint8_t *p)
+{
+	return get_le(p, sizeof(uint32_t));
+}
+
+void put_pgn(uint8_t *dat, pgn_t pgn)
+{
+	put_le24(&dat[J1939_CM_PGN_OFF], pgn);
+}
+
+bool send_raw8_ok(int raw, uint8_t prio, pgn_t pgn, uint8_t da, uint8_t sa,
+		  const uint8_t dat[CAN_MAX_DLEN])
+{
+	struct can_frame f = {};
+
+	f.can_id = j1939_canid(prio, pgn, da, sa);
+	f.can_dlc = CAN_MAX_DLEN;
+	memcpy(f.data, dat, CAN_MAX_DLEN);
+	return write_all_ok(raw, &f, sizeof(f));
+}
+
+size_t j1939_dt_chunk_len(size_t size, size_t off)
+{
+	size_t n;
+
+	n = size - off;
+	return n < J1939_DT_DATA_LEN ? n : J1939_DT_DATA_LEN;
+}
+
+bool send_dt_ok(int raw, uint8_t prio, pgn_t dt_pgn, uint8_t da, uint8_t sa,
+		uint8_t seq, const uint8_t *payload, size_t off, size_t size)
+{
+	uint8_t dat[CAN_MAX_DLEN];
+
+	/* a DT frame carries at least one payload byte from off */
+	if (off >= size)
+		return false;
+
+	memset(dat, J1939_FILL_BYTE, sizeof(dat));
+	dat[J1939_DT_SEQ_OFF] = seq;
+	memcpy(&dat[J1939_DT_DATA_OFF], payload + off,
+	       j1939_dt_chunk_len(size, off));
+	return send_raw8_ok(raw, prio, dt_pgn, da, sa, dat);
+}
+
+static_assert(__builtin_types_compatible_p(__typeof__(NSEC_PER_SEC),
+					   long long) &&
+	      __builtin_types_compatible_p(__typeof__(NSEC_PER_MSEC),
+					   long long),
+	      "timespec_diff_ms() needs signed long long arithmetic");
+
+long timespec_diff_ms(const struct timespec *a, const struct timespec *b)
+{
+	return ((b->tv_sec - a->tv_sec) * NSEC_PER_SEC +
+		(b->tv_nsec - a->tv_nsec)) / NSEC_PER_MSEC;
+}
+
+/* Set *deadline to timeout_ms from now on CLOCK_MONOTONIC. */
+static void deadline_after_ms(struct timespec *deadline, int timeout_ms)
+{
+	clock_gettime(CLOCK_MONOTONIC, deadline);
+	deadline->tv_sec += timeout_ms / MSEC_PER_SEC;
+	deadline->tv_nsec += (timeout_ms % MSEC_PER_SEC) * NSEC_PER_MSEC;
+	if (deadline->tv_nsec >= NSEC_PER_SEC) {
+		deadline->tv_sec++;
+		deadline->tv_nsec -= NSEC_PER_SEC;
+	}
+}
+
+/*
+ * Poll and recv on raw until match() accepts a frame, or time out. match()
+ * gets the raw can_id; the j1939_id_*() decoders mask the flag bits. Other
+ * traffic must not extend the wait, so poll against a fixed deadline.
+ */
+static bool recv_match_ok(int raw, int timeout_ms, struct can_frame *frame,
+			  bool (*match)(canid_t id, const void *ctx),
+			  const void *ctx)
+{
+	struct pollfd pfd = { .fd = raw, .events = POLLIN };
+	struct timespec now, deadline;
+	int remaining = timeout_ms;
+
+	deadline_after_ms(&deadline, timeout_ms);
+
+	while (remaining > 0) {
+		if (poll(&pfd, 1, remaining) <= 0)
+			return false;
+		if (recv(raw, frame, sizeof(*frame), 0) < 0)
+			return false;
+		if (j1939_is_data_frame(frame->can_id) &&
+		    match(frame->can_id, ctx))
+			return true;
+		clock_gettime(CLOCK_MONOTONIC, &now);
+		remaining = timespec_diff_ms(&now, &deadline);
+	}
+	return false;
+}
+
+struct j1939_peer_match {
+	uint8_t want_pf;
+	uint8_t want_da;
+	uint8_t want_sa;
+};
+
+static bool match_peer_dest(canid_t id, const void *ctx)
+{
+	const struct j1939_peer_match *m = ctx;
+
+	return j1939_id_pf(id) == m->want_pf &&
+	       j1939_id_ps(id) == m->want_da &&
+	       j1939_id_sa(id) == m->want_sa;
+}
+
+bool recv_for_peer_ok(int raw, uint8_t want_pf, uint8_t want_da,
+		      uint8_t want_sa, struct can_frame *frame, int timeout_ms)
+{
+	struct j1939_peer_match m = {
+		.want_pf = want_pf,
+		.want_da = want_da,
+		.want_sa = want_sa,
+	};
+
+	return recv_match_ok(raw, timeout_ms, frame, match_peer_dest, &m);
+}
+
+bool recv_cm_cmd_ok(int raw, uint8_t want_pf, uint8_t want_da, uint8_t want_sa,
+		    struct can_frame *frame, int timeout_ms, uint8_t want_cmd)
+{
+	if (!recv_for_peer_ok(raw, want_pf, want_da, want_sa, frame,
+			      timeout_ms))
+		return false;
+	return frame->data[J1939_CM_CMD_OFF] == want_cmd;
+}
+
+/* Arbitrary; keeps fill_pattern() from being the plain byte offset. */
+#define J1939_PATTERN_SEED	0x3c
+
+void fill_pattern(uint8_t *buf, size_t len)
+{
+	size_t i;
+
+	for (i = 0; i < len; i++)
+		buf[i] = i ^ (i >> CHAR_BIT) ^ J1939_PATTERN_SEED;
+}
+
+bool can_proto_missing(int type, int proto)
+{
+	int probe;
+
+	probe = socket(PF_CAN, type, proto);
+	if (probe < 0)
+		return errno == EAFNOSUPPORT || errno == EPROTONOSUPPORT;
+
+	close(probe);
+	return false;
+}
diff --git a/tools/testing/selftests/net/can/j1939_helpers.h b/tools/testing/selftests/net/can/j1939_helpers.h
new file mode 100644
index 000000000000..87961b5bbb15
--- /dev/null
+++ b/tools/testing/selftests/net/can/j1939_helpers.h
@@ -0,0 +1,283 @@
+/* SPDX-License-Identifier: (GPL-2.0-only OR BSD-3-Clause) */
+/*
+ * Shared helpers for the J1939 selftests.
+ *
+ * The individual tests are standalone kselftest binaries. This header
+ * declares the helpers they share, and j1939_helpers.c holds their code.
+ * The parts that use the kselftest harness are in j1939_tests.h.
+ *
+ * Helpers named *_ok() return true on success and false on failure, with
+ * errno set where a system call failed. Helpers that return a file
+ * descriptor or an ifindex return -1 on failure.
+ *
+ * Timing modes: timer checks use relaxed bounds by default, so that slow
+ * machines such as QEMU in CI pass. Set J1939_STRICT_TIMING in the
+ * environment (any value) for tight bounds on a real machine.
+ */
+#ifndef __SELFTESTS_NET_CAN_J1939_HELPERS_H__
+#define __SELFTESTS_NET_CAN_J1939_HELPERS_H__
+
+#include <errno.h>
+#include <limits.h>
+#include <poll.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <unistd.h>
+
+#include <net/if.h>
+#include <sys/socket.h>
+
+#include <linux/build_bug.h>
+#include <linux/can.h>
+#include <linux/can/j1939.h>
+#include <linux/can/raw.h>
+#include <linux/if.h>
+#include <linux/math.h>
+
+#include "clock-helpers.h"
+
+/*
+ * How long to wait for an expected frame or message. Not a protocol timer: a
+ * guess with room for a slow VM.
+ */
+#define J1939_RECV_TIMEOUT_MS	2000
+
+/*
+ * Timeout for a check that expects no frame. Long enough that a real
+ * local frame would have arrived, so a timeout means "nothing came".
+ * Much shorter than J1939_RECV_TIMEOUT_MS, to keep the test fast. A guess.
+ */
+#define J1939_NEG_RECV_TIMEOUT_MS	300
+static_assert(J1939_NEG_RECV_TIMEOUT_MS < J1939_RECV_TIMEOUT_MS,
+	      "J1939_NEG_RECV_TIMEOUT_MS must be the shorter timeout");
+
+/* Send priority of a new J1939 socket, see j1939_sk_init() in the kernel. */
+#define J1939_PRIO_DEFAULT	6
+
+/* Unused data bytes are sent as 0xff (SAE J1939-21:2001 Figures 14, 15). */
+#define J1939_FILL_BYTE		0xff
+
+/*
+ * PGN fields: PF is the second byte, PS the low byte. A PF of at least
+ * J1939_PDU2_PF_MIN selects PDU2, and PS is not an address
+ * (SAE J1939-21:2001 sections 5.1.2 and 5.2.5).
+ */
+#define J1939_PGN_PF_SHIFT	CHAR_BIT	/* below PF: the PS byte */
+#define J1939_PDU2_PF_MIN	0xf0
+#define J1939_PF(pgn)		(((pgn) >> J1939_PGN_PF_SHIFT) & UINT8_MAX)
+#define J1939_IS_PDU1(pgn)	(J1939_PF(pgn) < J1939_PDU2_PF_MIN)
+
+/* Data Page bit of a PGN (SAE J1939-21:2001 sections 5.1.2 and 5.2.3) */
+#define J1939_PGN_DP		0x10000
+
+/*
+ * Fields of the 29-bit CAN id (SAE J1939-21:2001 section 5.2): the priority,
+ * then the PGN, whose PS byte holds the destination of a PDU1 frame, then
+ * the source address in the low byte. The j1939_id_*() decoders mask their
+ * field, so they take a can_id with the CAN_*_FLAG bits still set.
+ */
+#define J1939_ID_PRIO_BITS	3
+#define J1939_ID_PRIO_SHIFT	(CAN_EFF_ID_BITS - J1939_ID_PRIO_BITS)
+#define J1939_ID_PRIO_MASK	((1U << J1939_ID_PRIO_BITS) - 1)
+#define J1939_ID_PGN_SHIFT	CHAR_BIT	/* below the PGN: the SA byte */
+static_assert(((J1939_PGN_MAX + 1) << J1939_ID_PGN_SHIFT) ==
+	      1U << J1939_ID_PRIO_SHIFT,
+	      "the PGN field must end where the priority starts");
+
+int j1939_id_prio(canid_t id);
+int j1939_id_pgn(canid_t id);
+int j1939_id_ps(canid_t id);
+int j1939_id_sa(canid_t id);
+
+/* Bytes in a 24-bit field of a TP or ETP control frame. */
+#define J1939_LE24_LEN		3
+
+/*
+ * Byte offsets in TP and ETP frames (SAE J1939-21:2001 Figures 14 and 15,
+ * ISO 11783-6:2004 K.2.2.1 and K.2.3).
+ */
+#define J1939_CM_CMD_OFF	0	/* control byte */
+#define J1939_CM_PGN_OFF	5	/* message PGN, J1939_LE24_LEN bytes */
+#define J1939_DT_SEQ_OFF	0	/* sequence number */
+#define J1939_DT_DATA_OFF	1	/* first payload byte */
+static_assert(J1939_CM_PGN_OFF + J1939_LE24_LEN == CAN_MAX_DLEN,
+	      "the message PGN is the last field of a control frame");
+
+/* Sizes and limits. */
+#define J1939_SF_MAX_SIZE	CAN_MAX_DLEN	/* largest single frame */
+
+/* payload bytes in one TP/ETP data (DT) frame */
+#define J1939_DT_DATA_LEN	(CAN_MAX_DLEN - J1939_DT_DATA_OFF)
+
+/* highest TP sequence number: the field is one byte */
+#define J1939_DT_SEQ_MAX	UINT8_MAX
+
+/* largest TP message; anything larger needs ETP */
+#define J1939_TP_MAX_SIZE	(J1939_DT_SEQ_MAX * J1939_DT_DATA_LEN)
+static_assert(J1939_TP_MAX_SIZE == 1785,
+	      "SAE J1939-21:2001 section 5.10.1.1 gives 1785 bytes");
+
+/* number of TP/ETP DT packets needed for len bytes, rounded up */
+#define J1939_NUM_PKTS(len)	DIV_ROUND_UP((len), J1939_DT_DATA_LEN)
+
+/*
+ * J1939 uses 29-bit data frames only. Its CAN filter in net/can/j1939/main.c
+ * drops RTR frames, and error frames never reach it.
+ */
+bool j1939_is_data_frame(canid_t can_id);
+
+/*
+ * Size of a CAN_RAW receive buffer for every frame of the largest ETP test
+ * message. A guess with plenty of headroom, not computed. Set best-effort
+ * via SO_RCVBUFFORCE.
+ */
+#define J1939_RAW_BIG_RCVBUF	(8 * 1024 * 1024)
+
+/* Flags for j1939_open_flags(). */
+#define J1939_OPEN_NONE		0
+#define J1939_OPEN_BCAST	0x1
+
+/* rcvbuf value for open_raw_rcvbuf(): keep the default receive buffer. */
+#define J1939_RAW_RCVBUF_DEFAULT	0
+
+/*
+ * Set by j1939_test_main() from the environment: CANIF is the interface of
+ * the J1939 sockets, CANIF_RAW is the interface of the CAN_RAW peer and
+ * defaults to CANIF.
+ */
+extern char CANIF[IFNAMSIZ];
+extern char CANIF_RAW[IFNAMSIZ];
+
+/* Set by j1939_test_main(): the test passed J1939_NEEDS_RAW. */
+extern bool j1939_needs_raw;
+
+/*
+ * Return relaxed_ms by default, or strict_ms if J1939_STRICT_TIMING is set in
+ * the environment. See "Timing modes" at the top of this file.
+ */
+int j1939_timing_ms(int relaxed_ms, int strict_ms);
+
+/* Resolve the ifindex of the interface named by CANIF. */
+int j1939_if_index(void);
+
+/*
+ * Open a J1939 socket bound to (name, sa, pgn); flags may set
+ * J1939_OPEN_BCAST.
+ */
+int j1939_open_flags(int ifindex, name_t name, uint8_t sa, pgn_t pgn,
+		     int flags);
+
+/* Open a J1939 socket bound to (sa, pgn) with no NAME and no broadcast. */
+int j1939_open(int ifindex, uint8_t sa, pgn_t pgn);
+
+/* Connect a J1939 socket to the peer (da, pgn), with no NAME. */
+bool j1939_connect_ok(int s, int ifindex, uint8_t da, pgn_t pgn);
+
+/* One sendto() that sent all len bytes; no retry. */
+bool j1939_sendto_ok(int s, const void *buf, size_t len, int ifindex,
+		     name_t name, uint8_t da, pgn_t pgn);
+
+/* One send(), write() or read() that moved all len bytes; no retry. */
+bool send_all_ok(int s, const void *buf, size_t len);
+bool write_all_ok(int fd, const void *buf, size_t len);
+bool read_all_ok(int fd, void *buf, size_t len);
+
+/*
+ * Open a CAN_RAW socket on CANIF_RAW. This also pins the calling thread to
+ * the CPU it runs on, or warns if that fails. Unless rcvbuf is
+ * J1939_RAW_RCVBUF_DEFAULT, request that SO_RCVBUFFORCE size (best-effort: a
+ * failure is logged, not fatal). Fail with EINVAL if the test did not pass
+ * J1939_NEEDS_RAW to j1939_test_main().
+ */
+int open_raw_rcvbuf(int rcvbuf);
+
+/* open_raw_rcvbuf() with the default receive buffer. */
+int open_raw(void);
+
+/*
+ * recvfrom() one message on s within timeout_ms, check that it is the len
+ * bytes in want, and return the sender in *src unless src is NULL. The buffer
+ * has one spare byte, so a longer message fails the check.
+ */
+bool recvfrom_verify_ok(int s, const void *want, size_t len, int timeout_ms,
+			struct sockaddr_can *src);
+
+/* recvfrom_verify_ok() without the sender. */
+bool recv_verify_ok(int s, const void *want, size_t len, int timeout_ms);
+
+/* Send len bytes on tx and verify they arrive byte-for-byte on rx. */
+bool send_recv_verify_ok(int tx, int rx, const void *buf, size_t len,
+			 int timeout_ms);
+
+/* Receive one whole CAN frame from a raw socket within timeout_ms. */
+bool recv_frame_ok(int raw, struct can_frame *frame, int timeout_ms);
+
+/*
+ * Start a TP/ETP control frame: every byte J1939_FILL_BYTE, then the control
+ * byte cmd.
+ */
+void cm_dat_init(uint8_t *dat, uint8_t cmd);
+
+/*
+ * Little-endian codecs for the multi-byte fields of TP/ETP connection
+ * management (CM) frames (host-agnostic).
+ */
+void put_le16(uint8_t *p, uint16_t v);
+void put_le24(uint8_t *p, uint32_t v);
+void put_le32(uint8_t *p, uint32_t v);
+uint16_t get_le16(const uint8_t *p);
+uint32_t get_le24(const uint8_t *p);
+uint32_t get_le32(const uint8_t *p);
+
+/* Embed the PGN of the transported message into a TP/ETP control frame. */
+void put_pgn(uint8_t *dat, pgn_t pgn);
+
+/*
+ * Send one J1939-encoded frame of CAN_MAX_DLEN bytes. prio is the J1939
+ * priority, 0 (highest) to 7; the PS byte of a PDU1 pgn must be 0.
+ */
+bool send_raw8_ok(int raw, uint8_t prio, pgn_t pgn, uint8_t da, uint8_t sa,
+		  const uint8_t dat[CAN_MAX_DLEN]);
+
+/*
+ * Payload bytes of the DT frame that starts at offset off of a message of
+ * size bytes; off must be below size.
+ */
+size_t j1939_dt_chunk_len(size_t size, size_t off);
+
+/*
+ * Send a TP/ETP data (DT) frame: sequence number seq and up to
+ * J1939_DT_DATA_LEN bytes from offset off of payload, a message of size
+ * bytes.
+ */
+bool send_dt_ok(int raw, uint8_t prio, pgn_t dt_pgn, uint8_t da, uint8_t sa,
+		uint8_t seq, const uint8_t *payload, size_t off, size_t size);
+
+/* Milliseconds from a to b (negative if b is earlier), CLOCK_MONOTONIC. */
+long timespec_diff_ms(const struct timespec *a, const struct timespec *b);
+
+/*
+ * Receive the next frame whose CAN-id PF == want_pf, sent from want_sa to
+ * want_da (PS).
+ */
+bool recv_for_peer_ok(int raw, uint8_t want_pf, uint8_t want_da,
+		      uint8_t want_sa, struct can_frame *frame, int timeout_ms);
+
+/* recv_for_peer_ok() and check that the control byte is want_cmd. */
+bool recv_cm_cmd_ok(int raw, uint8_t want_pf, uint8_t want_da, uint8_t want_sa,
+		    struct can_frame *frame, int timeout_ms, uint8_t want_cmd);
+
+/*
+ * Fill buf with a deterministic, position-dependent byte pattern. The
+ * i >> CHAR_BIT term makes each 256-byte block of the first 64 KiB differ.
+ */
+void fill_pattern(uint8_t *buf, size_t len);
+
+/* Is the CAN protocol proto missing from this kernel? */
+bool can_proto_missing(int type, int proto);
+
+#endif /* __SELFTESTS_NET_CAN_J1939_HELPERS_H__ */
diff --git a/tools/testing/selftests/net/can/j1939_lib.sh b/tools/testing/selftests/net/can/j1939_lib.sh
new file mode 100644
index 000000000000..afea744608fd
--- /dev/null
+++ b/tools/testing/selftests/net/can/j1939_lib.sh
@@ -0,0 +1,171 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Shared bring-up for the J1939 selftest wrappers. A wrapper sources this
+# file and runs the test binary of the same name, without .sh:
+#
+#	source "$(dirname "$0")/j1939_lib.sh"
+#
+# By default it creates and deletes two vcan interfaces: CANIF (default vcan0)
+# for the J1939 sockets and CANIF_RAW (default vcan1) for the CAN_RAW peer. It
+# routes frames between them with the CAN gateway, runs the test binary through
+# the kselftest net lib and reports the result. The tests send frames as other
+# nodes, so they must not run on a real CAN bus. The test is skipped if an
+# interface name does not start with "vcan".
+#
+# J1939_SHARED_IF=1 puts the peer on CANIF and needs no gateway. The peer may
+# then read a frame before the stack has handled the echo of that frame, and a
+# quick reply from the peer can cancel a TP session. Behind the gateway, with
+# RPS turned off on CANIF_RAW, the peer reads each frame only after the stack
+# has handled its echo; if RPS cannot be turned off, setup() warns.
+#
+# A wrapper whose test opens no CAN_RAW socket sets J1939_NO_PEER=1 before it
+# sources this file. Then the library sets up no CANIF_RAW vcan and no
+# gateway. A test that passes J1939_NEEDS_RAW fails at start.
+#
+# For the J1939_STRICT_TIMING timing mode, see j1939_helpers.h.
+
+# shellcheck disable=SC2034 # used by tests_run in lib.sh
+ALL_TESTS="j1939_run"
+
+test_dir=$(dirname "$0")
+net_dir=$test_dir/..
+# shellcheck source=../lib.sh
+source "$net_dir/lib.sh"
+
+export CANIF=${CANIF:-"vcan0"}
+
+# where the CAN_RAW peer runs: gateway (default), shared or none
+if [ "${J1939_NO_PEER:-0}" = 1 ]; then
+	export J1939_NO_PEER
+	unset CANIF_RAW
+	j1939_peer=none
+elif [ "${J1939_SHARED_IF:-0}" = 1 ]; then
+	export CANIF_RAW=$CANIF
+	j1939_peer=shared
+else
+	export CANIF_RAW=${CANIF_RAW:-"vcan1"}
+	j1939_peer=gateway
+fi
+
+J1939_TEST_PROG=$(basename "$0" .sh)
+
+# Undo only what this script did: delete a vcan we created, and bring
+# down an interface only if we brought it up. A failed setup() (e.g. an
+# interface already exists) must not disturb a pre-existing interface.
+created=()
+brought_up=()
+
+j1939_skip()
+{
+	echo "SKIP: $1"
+	exit "$ksft_skip"
+}
+
+vcan_setup()
+{
+	local dev=$1
+
+	if [[ $dev != vcan* ]]; then
+		j1939_skip "interface name '$dev' does not start with vcan"
+	fi
+
+	if ip link show "$dev" >/dev/null 2>&1; then
+		j1939_skip "$dev already exists; delete it and run the test again"
+	fi
+
+	if ! ip link add name "$dev" type vcan; then
+		j1939_skip "cannot create $dev (no vcan support or no permission)"
+	fi
+	created+=("$dev")
+
+	if ! ip link set dev "$dev" up; then
+		j1939_skip "cannot bring up $dev"
+	fi
+	brought_up+=("$dev")
+}
+
+# With RPS, the peer could get a frame on another CPU before the stack
+# has handled its echo. An empty mask reads as zeros and commas.
+rps_off()
+{
+	local rps=/sys/class/net/$1/queues/rx-0/rps_cpus
+
+	[ -e "$rps" ] || return 0
+	[ -n "$(tr -d '0,\n' < "$rps")" ] || return 0
+	echo 0 2>/dev/null > "$rps"
+}
+
+setup()
+{
+	local gw=$test_dir/j1939_gw
+	local rc
+
+	vcan_setup "$CANIF"
+
+	# shared or none: no second vcan
+	[ "$j1939_peer" = gateway ] || return 0
+
+	if [ "$CANIF_RAW" = "$CANIF" ]; then
+		j1939_skip "CANIF_RAW is CANIF ($CANIF); set another CANIF_RAW or J1939_SHARED_IF=1"
+	fi
+
+	vcan_setup "$CANIF_RAW"
+
+	if ! rps_off "$CANIF_RAW"; then
+		echo "WARNING: RPS stays on for $CANIF_RAW; the peer can overtake the stack's echo"
+	fi
+
+	# rtnetlink does not load can-gw on demand
+	modprobe -q can-gw 2>/dev/null
+
+	"$gw" "$CANIF" "$CANIF_RAW"
+	rc=$?
+
+	# shell: 126 not executable, 127 not found, 128+n killed by signal n
+	if [ "$rc" -ge 126 ]; then
+		echo "FAIL: $gw did not run or crashed (exit $rc)"
+		exit "$ksft_fail"
+	fi
+
+	if [ "$rc" -ne 0 ]; then
+		j1939_skip "cannot route $CANIF <-> $CANIF_RAW (can-gw?); try J1939_SHARED_IF=1"
+	fi
+}
+
+cleanup()
+{
+	local dev
+
+	for dev in "${brought_up[@]}"; do
+		ip link set dev "$dev" down 2>/dev/null
+	done
+	for dev in "${created[@]}"; do
+		ip link delete "$dev" 2>/dev/null
+	done
+}
+
+j1939_run()
+{
+	local rc
+
+	"$test_dir/$J1939_TEST_PROG"
+	rc=$?
+
+	# The test binary exits ksft_skip when it cannot run (see
+	# j1939_test_main()); keep that a skip instead of letting check_err
+	# turn any non-zero into a failure.
+	if [ "$rc" -eq "$ksft_skip" ]; then
+		ret_set_ksft_status "$ksft_skip" ""
+	else
+		check_err "$rc"
+	fi
+	log_test "$J1939_TEST_PROG"
+}
+
+trap cleanup EXIT
+setup
+
+tests_run
+
+exit "$EXIT_STATUS"
diff --git a/tools/testing/selftests/net/can/j1939_tests.h b/tools/testing/selftests/net/can/j1939_tests.h
new file mode 100644
index 000000000000..df8604d65fa2
--- /dev/null
+++ b/tools/testing/selftests/net/can/j1939_tests.h
@@ -0,0 +1,99 @@
+/* SPDX-License-Identifier: (GPL-2.0-only OR BSD-3-Clause) */
+/*
+ * The parts of the J1939 selftest helpers that use the kselftest harness:
+ * the fixture setup macros and j1939_test_main(). The other helpers are in
+ * j1939_helpers.h, which this header includes.
+ *
+ * Each test binary is run by its .sh wrapper (see j1939_lib.sh), which sets up
+ * the vcan interfaces and passes their names in the CANIF and CANIF_RAW
+ * environment variables; with J1939_NO_PEER=1 it passes no CANIF_RAW.
+ */
+#ifndef __SELFTESTS_NET_CAN_J1939_TESTS_H__
+#define __SELFTESTS_NET_CAN_J1939_TESTS_H__
+
+#include "kselftest_harness.h"
+#include "j1939_helpers.h"
+
+/*
+ * FIXTURE_SETUP helper: resolve CANIF's ifindex into self->ifindex and abort
+ * the test if it cannot be found. Used as a statement:
+ * J1939_SETUP_IFINDEX(self);
+ */
+#define J1939_SETUP_IFINDEX(self)					       \
+	do {								       \
+		(self)->ifindex = j1939_if_index();			       \
+		ASSERT_GE((self)->ifindex, 0)				       \
+			TH_LOG("failed to resolve ifindex for '%s': %d",       \
+			       CANIF, errno);				       \
+	} while (0)
+
+/*
+ * FIXTURE_SETUP helper: open a CAN_RAW socket on CANIF_RAW into self->raw
+ * with the given SO_RCVBUFFORCE size (or J1939_RAW_RCVBUF_DEFAULT) and abort
+ * the test if it cannot be opened. This also pins the test to one CPU, see
+ * open_raw_rcvbuf(). Used as a statement: J1939_SETUP_RAW(self, rcvbuf);
+ */
+#define J1939_SETUP_RAW(self, rcvbuf)					       \
+	do {								       \
+		(self)->raw = open_raw_rcvbuf(rcvbuf);			       \
+		ASSERT_GE((self)->raw, 0)				       \
+			TH_LOG("failed to open raw socket: %d", errno);	       \
+	} while (0)
+
+/*
+ * Flags for j1939_test_main(): what the test binary needs besides CAN_J1939.
+ */
+#define J1939_NEEDS_NONE	0
+#define J1939_NEEDS_RAW		0x1	/* opens CAN_RAW sockets */
+
+/*
+ * Body of each test's main(): require CANIF in the environment and a kernel
+ * with CAN_J1939, then run the harness. J1939_NEEDS_RAW marks a test that
+ * opens CAN_RAW sockets; only such a test may open them. It needs CAN_RAW
+ * support and fails at start if the wrapper set J1939_NO_PEER=1. A missing
+ * protocol skips the test. Warn when the CAN_RAW peer shares CANIF (see
+ * j1939_lib.sh).
+ */
+static inline int j1939_test_main(int argc, char **argv, unsigned int flags)
+{
+	const char *raw_ifname;
+	const char *no_peer;
+	const char *ifname;
+
+	ifname = getenv("CANIF");
+	if (!ifname) {
+		fprintf(stderr, "# CANIF must name the test interface\n");
+		return KSFT_SKIP;
+	}
+	strncpy(CANIF, ifname, sizeof(CANIF) - 1);
+
+	raw_ifname = getenv("CANIF_RAW");
+	if (!raw_ifname || !*raw_ifname)
+		raw_ifname = ifname;
+	strncpy(CANIF_RAW, raw_ifname, sizeof(CANIF_RAW) - 1);
+
+	j1939_needs_raw = flags & J1939_NEEDS_RAW;
+	no_peer = getenv("J1939_NO_PEER");
+	if (j1939_needs_raw && no_peer && !strcmp(no_peer, "1")) {
+		fprintf(stderr, "# J1939_NO_PEER=1, but CAN_RAW peer needed\n");
+		return KSFT_FAIL;
+	}
+
+	if (can_proto_missing(SOCK_DGRAM, CAN_J1939)) {
+		fprintf(stderr, "# kernel lacks CAN_J1939\n");
+		return KSFT_SKIP;
+	}
+	if (j1939_needs_raw && can_proto_missing(SOCK_RAW, CAN_RAW)) {
+		fprintf(stderr, "# kernel lacks CAN_RAW\n");
+		return KSFT_SKIP;
+	}
+
+	if (j1939_needs_raw && !strcmp(CANIF_RAW, CANIF)) {
+		fprintf(stderr, "# WARNING: peer shares %s; TP/ETP may fail\n",
+			CANIF);
+	}
+
+	return test_harness_run(argc, argv);
+}
+
+#endif /* __SELFTESTS_NET_CAN_J1939_TESTS_H__ */
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH net-next 03/23] selftests: can: add J1939 base functional tests
  2026-12-02 23:04 [PATCH net-next 0/23] pull-request: can-next 2026-12-03 Marc Kleine-Budde
  2026-12-02 23:04 ` [PATCH net-next 01/23] selftests: can: install net/lib.sh with the CAN tests Marc Kleine-Budde
  2026-12-02 23:04 ` [PATCH net-next 02/23] selftests: can: add J1939 test helper header and library Marc Kleine-Budde
@ 2026-12-02 23:04 ` Marc Kleine-Budde
  2026-12-02 23:04 ` [PATCH net-next 04/23] selftests: can: add J1939 socket option and metadata tests Marc Kleine-Budde
                   ` (19 subsequent siblings)
  22 siblings, 0 replies; 27+ messages in thread
From: Marc Kleine-Budde @ 2026-12-02 23:04 UTC (permalink / raw)
  To: netdev; +Cc: davem, kuba, linux-can, kernel, Oleksij Rempel, Marc Kleine-Budde

From: Oleksij Rempel <o.rempel@pengutronix.de>

Add a functional selftest for the SAE J1939 socket interface. It sends
between CAN_J1939 sockets over a vcan interface and checks payload
integrity for single frame, TP and ETP sizes, the boundaries between
them, and single-frame and BAM broadcast. A single-frame broadcast
reaches a receiver only with SO_BROADCAST.

Enable CONFIG_CAN_J1939, CONFIG_CAN_RAW and CONFIG_CAN_GW in the test
config: CAN_RAW for the CAN_RAW peer of the later tests, CAN_GW for the
gateway that j1939_lib.sh sets up. This test opens no CAN_RAW socket and
skips only without CAN_J1939.

Signed-off-by: Oleksij Rempel <o.rempel@pengutronix.de>
Link: https://patch.msgid.link/20261130-j1939-selftests-v7-3-2491693ccb8d@pengutronix.de
[mkl: switch to static_assert()]
Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
---
 tools/testing/selftests/net/can/.gitignore    |   1 +
 tools/testing/selftests/net/can/Makefile      |  14 +-
 tools/testing/selftests/net/can/config        |   3 +
 .../testing/selftests/net/can/j1939_helpers.c |  11 +
 .../testing/selftests/net/can/j1939_helpers.h |   8 +
 .../selftests/net/can/test_j1939_base.c       | 241 ++++++++++++++++++
 .../selftests/net/can/test_j1939_base.sh      |   7 +
 7 files changed, 283 insertions(+), 2 deletions(-)
 create mode 100644 tools/testing/selftests/net/can/test_j1939_base.c
 create mode 100755 tools/testing/selftests/net/can/test_j1939_base.sh

diff --git a/tools/testing/selftests/net/can/.gitignore b/tools/testing/selftests/net/can/.gitignore
index 30cd8b40d0f8..e566019425c8 100644
--- a/tools/testing/selftests/net/can/.gitignore
+++ b/tools/testing/selftests/net/can/.gitignore
@@ -1,3 +1,4 @@
 # SPDX-License-Identifier: GPL-2.0-only
 j1939_gw
+test_j1939_base
 test_raw_filter
diff --git a/tools/testing/selftests/net/can/Makefile b/tools/testing/selftests/net/can/Makefile
index cf0b06974d54..b09887a0d31f 100644
--- a/tools/testing/selftests/net/can/Makefile
+++ b/tools/testing/selftests/net/can/Makefile
@@ -4,14 +4,24 @@ top_srcdir = ../../../../..
 
 CFLAGS += -Wall -Wl,--no-as-needed -O2 -g -I$(top_srcdir)/usr/include -I$(top_srcdir)/tools/include $(KHDR_INCLUDES)
 
-TEST_PROGS := test_raw_filter.sh
+LOCAL_HDRS := j1939_helpers.h j1939_tests.h ../../clock-helpers.h
+
+TEST_PROGS := \
+	test_j1939_base.sh \
+	test_raw_filter.sh \
+# end of TEST_PROGS
 
 TEST_FILES := j1939_lib.sh
 
 TEST_INCLUDES := ../lib.sh $(wildcard ../lib/sh/*.sh)
 
-TEST_GEN_FILES := test_raw_filter
+# each .sh in TEST_PROGS runs the binary of the same name
+TEST_GEN_FILES := $(TEST_PROGS:.sh=)
+
 # sets up the CAN gateway for j1939_lib.sh
 TEST_GEN_FILES += j1939_gw
 
 include ../../lib.mk
+
+# the J1939 tests link the shared helper code
+$(filter $(OUTPUT)/test_j1939_%,$(TEST_GEN_FILES)): j1939_helpers.c
diff --git a/tools/testing/selftests/net/can/config b/tools/testing/selftests/net/can/config
index 188f79796670..e124727f63b6 100644
--- a/tools/testing/selftests/net/can/config
+++ b/tools/testing/selftests/net/can/config
@@ -1,3 +1,6 @@
 CONFIG_CAN=m
 CONFIG_CAN_DEV=m
+CONFIG_CAN_GW=m
+CONFIG_CAN_J1939=m
+CONFIG_CAN_RAW=m
 CONFIG_CAN_VCAN=m
diff --git a/tools/testing/selftests/net/can/j1939_helpers.c b/tools/testing/selftests/net/can/j1939_helpers.c
index 38c584d9c286..1045575a8a4e 100644
--- a/tools/testing/selftests/net/can/j1939_helpers.c
+++ b/tools/testing/selftests/net/can/j1939_helpers.c
@@ -243,6 +243,17 @@ static ssize_t recv_timeout(int s, void *buf, size_t len, int timeout_ms)
 	return recv(s, buf, len, 0);
 }
 
+bool recv_none_ok(int s)
+{
+	struct pollfd pfd = { .fd = s, .events = POLLIN };
+	uint8_t drop;
+
+	if (poll(&pfd, 1, J1939_NEG_RECV_TIMEOUT_MS) == 0)
+		return true;
+	recv(s, &drop, sizeof(drop), MSG_DONTWAIT);
+	return false;
+}
+
 bool recvfrom_verify_ok(int s, const void *want, size_t len, int timeout_ms,
 			struct sockaddr_can *src)
 {
diff --git a/tools/testing/selftests/net/can/j1939_helpers.h b/tools/testing/selftests/net/can/j1939_helpers.h
index 87961b5bbb15..0235d8ce2a8e 100644
--- a/tools/testing/selftests/net/can/j1939_helpers.h
+++ b/tools/testing/selftests/net/can/j1939_helpers.h
@@ -198,6 +198,14 @@ int open_raw_rcvbuf(int rcvbuf);
 /* open_raw_rcvbuf() with the default receive buffer. */
 int open_raw(void);
 
+/*
+ * Return true if poll() on s times out after J1939_NEG_RECV_TIMEOUT_MS.
+ * Otherwise (a message, a socket error or a poll() failure) do one recv()
+ * with MSG_DONTWAIT and return false. That recv() drops a waiting message
+ * or clears a pending socket error.
+ */
+bool recv_none_ok(int s);
+
 /*
  * recvfrom() one message on s within timeout_ms, check that it is the len
  * bytes in want, and return the sender in *src unless src is NULL. The buffer
diff --git a/tools/testing/selftests/net/can/test_j1939_base.c b/tools/testing/selftests/net/can/test_j1939_base.c
new file mode 100644
index 000000000000..e36f5117a54e
--- /dev/null
+++ b/tools/testing/selftests/net/can/test_j1939_base.c
@@ -0,0 +1,241 @@
+// SPDX-License-Identifier: (GPL-2.0-only OR BSD-3-Clause)
+/*
+ * J1939 base functional selftests.
+ *
+ * Send between SOCK_DGRAM/CAN_J1939 sockets over a vcan interface and verify
+ * payload integrity across the transport-size transitions:
+ * a single frame (PDU1), Transport Protocol, Extended Transport Protocol, the
+ * exact boundaries between them, and single-frame and BAM broadcast (PDU2).
+ *
+ * Run by test_j1939_base.sh, see j1939_tests.h.
+ */
+#include <errno.h>
+
+#include "j1939_tests.h"
+
+/* arbitrary addresses and PGNs, within the asserts below */
+#define SA_TX			0x80
+#define SA_RX			0x90
+#define PGN_PDU1		0x0ab00	/* destination specific */
+#define PGN_PDU2		0x0feee	/* broadcast */
+static_assert(J1939_IS_PDU1(PGN_PDU1) && !J1939_IS_PDU1(PGN_PDU2),
+	      "PGN_PDU1 must be PDU1 and PGN_PDU2 must be PDU2");
+static_assert((PGN_PDU1 & UINT8_MAX) == 0,
+	      "the kernel rejects a PDU1 PGN whose PS byte is not 0");
+static_assert(PGN_PDU1 <= J1939_PGN_MAX && PGN_PDU2 <= J1939_PGN_MAX,
+	      "PGN_PDU1 and PGN_PDU2 must be valid PGNs");
+static_assert(SA_TX != SA_RX && SA_TX <= J1939_MAX_UNICAST_ADDR &&
+	      SA_RX <= J1939_MAX_UNICAST_ADDR,
+	      "SA_TX and SA_RX must be two different unicast addresses");
+
+/* An arbitrary TP size inside the TP range, and one that needs ETP. */
+#define TP_SIZE			128
+#define ETP_SIZE		2000
+static_assert(TP_SIZE > J1939_SF_MAX_SIZE, "TP_SIZE must need TP");
+static_assert(TP_SIZE < J1939_TP_MAX_SIZE, "TP_SIZE must fit TP");
+static_assert(ETP_SIZE > J1939_TP_MAX_SIZE, "ETP_SIZE must need ETP");
+
+/*
+ * Longest gap the spec allows before a BAM data packet (SAE J1939-21:2001
+ * section 5.12.3). The kernel waits 50 ms, see j1939_session_tx_rts() and
+ * j1939_session_tx_dat().
+ */
+#define BAM_PKT_GAP_MAX_MS	200
+
+FIXTURE(j1939_base)
+{
+	int ifindex;
+	int tx;
+	int rx;
+	int rx_no_bcast;	/* a receiver without SO_BROADCAST */
+	bool bcast;
+};
+
+FIXTURE_SETUP(j1939_base)
+{
+	self->tx = -1;
+	self->rx = -1;
+	self->rx_no_bcast = -1;
+	J1939_SETUP_IFINDEX(self);
+}
+
+FIXTURE_TEARDOWN(j1939_base)
+{
+	if (self->tx >= 0)
+		close(self->tx);
+	if (self->rx >= 0)
+		close(self->rx);
+	if (self->rx_no_bcast >= 0)
+		close(self->rx_no_bcast);
+}
+
+/*
+ * Set up a receiver bound to (rx_addr, pgn) and a sender bound to SA_TX and
+ * connected to (tx_dst, pgn). Any pair opened by a previous call is closed
+ * first. bcast opens both sockets with J1939_OPEN_BCAST, for the PDU2 and BAM
+ * tests.
+ */
+static bool pair_up_ok(FIXTURE_DATA(j1939_base) *self, uint8_t rx_addr,
+		       uint8_t tx_dst, pgn_t pgn, bool bcast)
+{
+	int flags;
+
+	flags = bcast ? J1939_OPEN_BCAST : J1939_OPEN_NONE;
+	self->bcast = bcast;
+	if (self->tx >= 0) {
+		close(self->tx);
+		self->tx = -1;
+	}
+	if (self->rx >= 0) {
+		close(self->rx);
+		self->rx = -1;
+	}
+
+	self->rx = j1939_open_flags(self->ifindex, J1939_NO_NAME, rx_addr, pgn,
+				    flags);
+	if (self->rx < 0) {
+		fprintf(stderr, "# open rx failed: %d\n", errno);
+		return false;
+	}
+
+	self->tx = j1939_open_flags(self->ifindex, J1939_NO_NAME, SA_TX,
+				    J1939_NO_PGN, flags);
+	if (self->tx < 0) {
+		fprintf(stderr, "# open tx failed: %d\n", errno);
+		return false;
+	}
+
+	if (!j1939_connect_ok(self->tx, self->ifindex, tx_dst, pgn)) {
+		fprintf(stderr, "# connect tx failed: %d\n", errno);
+		return false;
+	}
+
+	return true;
+}
+
+/*
+ * Send a deterministic payload of the given size on tx and verify it is
+ * received byte for byte on rx.
+ */
+static bool roundtrip_ok(FIXTURE_DATA(j1939_base) *self, size_t size)
+{
+	int timeout_ms = J1939_RECV_TIMEOUT_MS;
+	uint8_t *tx_buf;
+	bool ok;
+
+	/* a BAM message arrives only after all its packet gaps */
+	if (self->bcast && size > J1939_SF_MAX_SIZE)
+		timeout_ms += J1939_NUM_PKTS(size) * BAM_PKT_GAP_MAX_MS;
+
+	tx_buf = malloc(size);
+	if (!tx_buf) {
+		fprintf(stderr, "# alloc failed\n");
+		return false;
+	}
+	fill_pattern(tx_buf, size);
+
+	errno = 0;
+	ok = send_recv_verify_ok(self->tx, self->rx, tx_buf, size, timeout_ms);
+	if (!ok) {
+		fprintf(stderr, "# round-trip failed at size %zu: %s\n", size,
+			errno ? strerror(errno) : "no or wrong data");
+	}
+
+	free(tx_buf);
+	return ok;
+}
+
+/* Largest single frame, unicast PDU1. */
+TEST_F(j1939_base, single_frame_pdu1)
+{
+	ASSERT_TRUE(pair_up_ok(self, SA_RX, SA_RX, PGN_PDU1, false));
+	EXPECT_TRUE(roundtrip_ok(self, J1939_SF_MAX_SIZE));
+}
+
+/* Transport Protocol, unicast. */
+TEST_F(j1939_base, tp_roundtrip)
+{
+	ASSERT_TRUE(pair_up_ok(self, SA_RX, SA_RX, PGN_PDU1, false));
+	EXPECT_TRUE(roundtrip_ok(self, TP_SIZE));
+}
+
+/* Extended Transport Protocol, unicast. */
+TEST_F(j1939_base, etp_roundtrip)
+{
+	ASSERT_TRUE(pair_up_ok(self, SA_RX, SA_RX, PGN_PDU1, false));
+	EXPECT_TRUE(roundtrip_ok(self, ETP_SIZE));
+}
+
+/*
+ * Sizes on both sides of the single frame / TP and TP / ETP limits. Only the
+ * payload is checked here, not which transport carried it.
+ */
+TEST_F(j1939_base, size_boundaries)
+{
+	static const size_t sizes[] = {
+		J1939_SF_MAX_SIZE, J1939_SF_MAX_SIZE + 1,
+		J1939_TP_MAX_SIZE, J1939_TP_MAX_SIZE + 1,
+	};
+	size_t k;
+
+	for (k = 0; k < ARRAY_SIZE(sizes); k++) {
+		ASSERT_TRUE(pair_up_ok(self, SA_RX, SA_RX, PGN_PDU1, false));
+		EXPECT_TRUE(roundtrip_ok(self, sizes[k]))
+			TH_LOG("failed at boundary size %zu", sizes[k]);
+	}
+}
+
+/* Single-frame broadcast, PDU2. */
+TEST_F(j1939_base, single_frame_broadcast_pdu2)
+{
+	ASSERT_TRUE(pair_up_ok(self, SA_RX, J1939_NO_ADDR, PGN_PDU2, true));
+	EXPECT_TRUE(roundtrip_ok(self, J1939_SF_MAX_SIZE));
+}
+
+/* BAM (broadcast transport). */
+TEST_F(j1939_base, bam_broadcast)
+{
+	ASSERT_TRUE(pair_up_ok(self, SA_RX, J1939_NO_ADDR, PGN_PDU2, true));
+	EXPECT_TRUE(roundtrip_ok(self, TP_SIZE));
+}
+
+/* A single-frame broadcast reaches only a receiver with SO_BROADCAST. */
+TEST_F(j1939_base, bcast_needs_so_broadcast)
+{
+	uint8_t second_buf[J1939_SF_MAX_SIZE];
+	uint8_t tx_buf[J1939_SF_MAX_SIZE];
+	int enable = 1;
+
+	fill_pattern(tx_buf, sizeof(tx_buf));
+	memcpy(second_buf, tx_buf, sizeof(second_buf));
+	second_buf[0] ^= UINT8_MAX;
+
+	ASSERT_TRUE(pair_up_ok(self, SA_RX, J1939_NO_ADDR, PGN_PDU2, true));
+	self->rx_no_bcast = j1939_open(self->ifindex, SA_RX, PGN_PDU2);
+	ASSERT_GE(self->rx_no_bcast, 0)
+		TH_LOG("open rx_no_bcast failed: %d", errno);
+
+	/* the receiver with SO_BROADCAST shows that the frame went out */
+	ASSERT_TRUE(send_recv_verify_ok(self->tx, self->rx, tx_buf,
+					sizeof(tx_buf), J1939_RECV_TIMEOUT_MS));
+	EXPECT_TRUE(recv_none_ok(self->rx_no_bcast))
+		TH_LOG("a receiver without SO_BROADCAST got a frame or error");
+
+	/*
+	 * Set SO_BROADCAST and send a second frame. It must arrive now.
+	 * That shows the first frame was dropped for the missing flag,
+	 * not for another reason. The second frame has its own payload,
+	 * so a late first frame cannot be mistaken for it.
+	 */
+	ASSERT_EQ(setsockopt(self->rx_no_bcast, SOL_SOCKET, SO_BROADCAST,
+			     &enable, sizeof(enable)), 0);
+	EXPECT_TRUE(send_recv_verify_ok(self->tx, self->rx_no_bcast,
+					second_buf, sizeof(second_buf),
+					J1939_RECV_TIMEOUT_MS))
+		TH_LOG("second broadcast missing or not the expected payload");
+}
+
+int main(int argc, char **argv)
+{
+	return j1939_test_main(argc, argv, J1939_NEEDS_NONE);
+}
diff --git a/tools/testing/selftests/net/can/test_j1939_base.sh b/tools/testing/selftests/net/can/test_j1939_base.sh
new file mode 100755
index 000000000000..dd19cd469651
--- /dev/null
+++ b/tools/testing/selftests/net/can/test_j1939_base.sh
@@ -0,0 +1,7 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+
+# test_j1939_base opens no CAN_RAW socket
+# shellcheck disable=SC2034 # read by j1939_lib.sh
+J1939_NO_PEER=1
+source "$(dirname "$0")/j1939_lib.sh"
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH net-next 04/23] selftests: can: add J1939 socket option and metadata tests
  2026-12-02 23:04 [PATCH net-next 0/23] pull-request: can-next 2026-12-03 Marc Kleine-Budde
                   ` (2 preceding siblings ...)
  2026-12-02 23:04 ` [PATCH net-next 03/23] selftests: can: add J1939 base functional tests Marc Kleine-Budde
@ 2026-12-02 23:04 ` Marc Kleine-Budde
  2026-12-02 23:04 ` [PATCH net-next 05/23] selftests: can: add J1939 addressing and concurrency tests Marc Kleine-Budde
                   ` (18 subsequent siblings)
  22 siblings, 0 replies; 27+ messages in thread
From: Marc Kleine-Budde @ 2026-12-02 23:04 UTC (permalink / raw)
  To: netdev; +Cc: davem, kuba, linux-can, kernel, Oleksij Rempel, Marc Kleine-Budde

From: Oleksij Rempel <o.rempel@pengutronix.de>

Add a selftest for the J1939 socket options and send metadata. The send
priority is checked on the wire via a CAN_RAW peer, and the option values
are read back with getsockopt. The test also covers the SO_J1939_FILTER
PGN whitelist, unconnected sendto(), a bind() with a wrong address family
and the SO_J1939_ERRQUEUE TX-completion ACK.

Signed-off-by: Oleksij Rempel <o.rempel@pengutronix.de>
Link: https://patch.msgid.link/20261130-j1939-selftests-v7-4-2491693ccb8d@pengutronix.de
[mkl: switch to static_assert()]
Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
---
 tools/testing/selftests/net/can/.gitignore    |   1 +
 tools/testing/selftests/net/can/Makefile      |   1 +
 .../testing/selftests/net/can/j1939_helpers.c |  59 ++++
 .../testing/selftests/net/can/j1939_helpers.h |  26 ++
 .../selftests/net/can/test_j1939_opts.c       | 308 ++++++++++++++++++
 .../selftests/net/can/test_j1939_opts.sh      |   4 +
 6 files changed, 399 insertions(+)
 create mode 100644 tools/testing/selftests/net/can/test_j1939_opts.c
 create mode 100755 tools/testing/selftests/net/can/test_j1939_opts.sh

diff --git a/tools/testing/selftests/net/can/.gitignore b/tools/testing/selftests/net/can/.gitignore
index e566019425c8..75c078a2492e 100644
--- a/tools/testing/selftests/net/can/.gitignore
+++ b/tools/testing/selftests/net/can/.gitignore
@@ -1,4 +1,5 @@
 # SPDX-License-Identifier: GPL-2.0-only
 j1939_gw
 test_j1939_base
+test_j1939_opts
 test_raw_filter
diff --git a/tools/testing/selftests/net/can/Makefile b/tools/testing/selftests/net/can/Makefile
index b09887a0d31f..996b5bbd715a 100644
--- a/tools/testing/selftests/net/can/Makefile
+++ b/tools/testing/selftests/net/can/Makefile
@@ -8,6 +8,7 @@ LOCAL_HDRS := j1939_helpers.h j1939_tests.h ../../clock-helpers.h
 
 TEST_PROGS := \
 	test_j1939_base.sh \
+	test_j1939_opts.sh \
 	test_raw_filter.sh \
 # end of TEST_PROGS
 
diff --git a/tools/testing/selftests/net/can/j1939_helpers.c b/tools/testing/selftests/net/can/j1939_helpers.c
index 1045575a8a4e..c705a8957776 100644
--- a/tools/testing/selftests/net/can/j1939_helpers.c
+++ b/tools/testing/selftests/net/can/j1939_helpers.c
@@ -503,6 +503,65 @@ bool recv_cm_cmd_ok(int raw, uint8_t want_pf, uint8_t want_da, uint8_t want_sa,
 	return frame->data[J1939_CM_CMD_OFF] == want_cmd;
 }
 
+bool j1939_set_flag_ok(int s, int optname, int val)
+{
+	return setsockopt(s, SOL_CAN_J1939, optname, &val, sizeof(val)) >= 0;
+}
+
+bool errqueue_enable_ack_ok(int s)
+{
+	int tstamp_flags = SOF_TIMESTAMPING_TX_ACK;
+
+	if (!j1939_set_flag_ok(s, SO_J1939_ERRQUEUE, 1))
+		return false;
+
+	return !setsockopt(s, SOL_SOCKET, SO_TIMESTAMPING, &tstamp_flags,
+			   sizeof(tstamp_flags));
+}
+
+/* Does the error-queue message msg carry the TX-completion ACK? */
+static bool msg_has_tstamp_ack(struct msghdr *msg)
+{
+	struct cmsghdr *cmsg;
+
+	for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
+		struct sock_extended_err *serr;
+
+		if (cmsg->cmsg_level != SOL_CAN_J1939 ||
+		    cmsg->cmsg_type != SCM_J1939_ERRQUEUE)
+			continue;
+
+		serr = (struct sock_extended_err *)CMSG_DATA(cmsg);
+		if (serr->ee_errno == ENOMSG &&
+		    serr->ee_origin == SO_EE_ORIGIN_TIMESTAMPING &&
+		    serr->ee_info == SCM_TSTAMP_ACK)
+			return true;
+	}
+	return false;
+}
+
+bool errqueue_read_ack_ok(int s)
+{
+	struct pollfd pfd = { .fd = s, .events = POLLERR };
+	union {
+		char buf[CMSG_SPACE(sizeof(struct sock_extended_err))];
+		struct cmsghdr align;	/* portable cmsg alignment */
+	} ctrl;
+	struct msghdr msg = {
+		.msg_control = ctrl.buf,
+		.msg_controllen = sizeof(ctrl.buf),
+	};
+
+	if (poll(&pfd, 1, J1939_RECV_TIMEOUT_MS) <= 0)
+		return false;
+	if (recvmsg(s, &msg, MSG_ERRQUEUE) < 0)
+		return false;
+	if (msg.msg_flags & MSG_CTRUNC)
+		return false;
+
+	return msg_has_tstamp_ack(&msg);
+}
+
 /* Arbitrary; keeps fill_pattern() from being the plain byte offset. */
 #define J1939_PATTERN_SEED	0x3c
 
diff --git a/tools/testing/selftests/net/can/j1939_helpers.h b/tools/testing/selftests/net/can/j1939_helpers.h
index 0235d8ce2a8e..bc4ffeea06c4 100644
--- a/tools/testing/selftests/net/can/j1939_helpers.h
+++ b/tools/testing/selftests/net/can/j1939_helpers.h
@@ -35,8 +35,10 @@
 #include <linux/can.h>
 #include <linux/can/j1939.h>
 #include <linux/can/raw.h>
+#include <linux/errqueue.h>
 #include <linux/if.h>
 #include <linux/math.h>
+#include <linux/net_tstamp.h>
 
 #include "clock-helpers.h"
 
@@ -279,6 +281,30 @@ bool recv_for_peer_ok(int raw, uint8_t want_pf, uint8_t want_da,
 bool recv_cm_cmd_ok(int raw, uint8_t want_pf, uint8_t want_da, uint8_t want_sa,
 		    struct can_frame *frame, int timeout_ms, uint8_t want_cmd);
 
+/*
+ * Set the J1939 flag option optname (SO_J1939_PROMISC or SO_J1939_ERRQUEUE)
+ * to val. A stack bug makes setsockopt() return val instead of 0 on success
+ * (j1939_sk_setsockopt_flag()), so any value >= 0 counts as success.
+ */
+bool j1939_set_flag_ok(int s, int optname, int val);
+
+/*
+ * Enable the error queue of s with SOF_TIMESTAMPING_TX_ACK only: a finished
+ * send then queues one TX-completion ACK, or an abort entry if the session
+ * fails (__j1939_sk_errqueue() in net/can/j1939/socket.c). The kernel reads
+ * the timestamping flags when the session ends, so the caller may call this
+ * function after the send, as long as the session has not ended.
+ */
+bool errqueue_enable_ack_ok(int s);
+
+/*
+ * Read one message from the error queue of s, set up by
+ * errqueue_enable_ack_ok(), and check that it is the TX-completion ACK. With
+ * those flags the kernel returns each entry with one cmsg, SCM_J1939_ERRQUEUE.
+ * No iovec is passed, so no message data is read.
+ */
+bool errqueue_read_ack_ok(int s);
+
 /*
  * Fill buf with a deterministic, position-dependent byte pattern. The
  * i >> CHAR_BIT term makes each 256-byte block of the first 64 KiB differ.
diff --git a/tools/testing/selftests/net/can/test_j1939_opts.c b/tools/testing/selftests/net/can/test_j1939_opts.c
new file mode 100644
index 000000000000..b535acea198c
--- /dev/null
+++ b/tools/testing/selftests/net/can/test_j1939_opts.c
@@ -0,0 +1,308 @@
+// SPDX-License-Identifier: (GPL-2.0-only OR BSD-3-Clause)
+/*
+ * J1939 socket option and metadata selftests.
+ *
+ * On top of the basic transport, cover the user-visible J1939 socket options
+ * and addressing: the SO_J1939_FILTER PGN whitelist, the SO_J1939_SEND_PRIO
+ * send priority seen in the CAN id (via a CAN_RAW peer, including the kernel's
+ * default), unconnected sendto(2), a wrong-family bind rejection,
+ * SO_J1939_ERRQUEUE TX-completion notifications, and set/getsockopt
+ * round-trips of SO_J1939_SEND_PRIO, SO_J1939_PROMISC and SO_J1939_ERRQUEUE.
+ *
+ * Run by test_j1939_opts.sh, see j1939_tests.h.
+ */
+#include <errno.h>
+
+#include "j1939_tests.h"
+
+/* arbitrary addresses */
+#define SA_TX			0x80
+#define SA_RX			0x90
+static_assert(SA_TX != SA_RX && SA_TX <= J1939_MAX_UNICAST_ADDR &&
+	      SA_RX <= J1939_MAX_UNICAST_ADDR,
+	      "SA_TX and SA_RX must be two different unicast addresses");
+
+/* two different destination-specific PGNs, otherwise arbitrary */
+#define PGN_A			0x0ab00
+#define PGN_B			0x0cd00
+static_assert(J1939_IS_PDU1(PGN_A) && J1939_IS_PDU1(PGN_B) && PGN_A != PGN_B,
+	      "PGN_A and PGN_B must be two different PDU1 PGNs");
+static_assert((PGN_A & UINT8_MAX) == 0 && (PGN_B & UINT8_MAX) == 0,
+	      "the kernel rejects a PDU1 PGN whose PS byte is not 0");
+static_assert(PGN_A <= J1939_PGN_MAX && PGN_B <= J1939_PGN_MAX,
+	      "PGN_A and PGN_B must be valid PGNs");
+
+/*
+ * SO_J1939_SEND_PRIO values below this one need CAP_NET_ADMIN
+ * (j1939_sk_setsockopt()).
+ */
+#define PRIO_MIN_UNPRIV		2
+
+/* a valid priority that needs no privilege and differs from the default */
+#define PRIO_SET		3
+static_assert(PRIO_SET >= PRIO_MIN_UNPRIV && PRIO_SET <= J1939_ID_PRIO_MASK &&
+	      PRIO_SET != J1939_PRIO_DEFAULT,
+	      "PRIO_SET must be a valid, unprivileged, non-default priority");
+
+/*
+ * An arbitrary size that needs TP, so that the ACK ends a multi-frame
+ * session.
+ */
+#define ERRQUEUE_MSG_SIZE	128
+static_assert(ERRQUEUE_MSG_SIZE > J1939_SF_MAX_SIZE,
+	      "ERRQUEUE_MSG_SIZE must need TP");
+static_assert(ERRQUEUE_MSG_SIZE <= J1939_TP_MAX_SIZE,
+	      "ERRQUEUE_MSG_SIZE must fit TP");
+
+/*
+ * Read the next CAN frame from a raw socket and return its J1939 priority, or
+ * -1 on timeout or if it is not a J1939 data frame.
+ */
+static int raw_prio(int raw, int timeout_ms)
+{
+	struct can_frame frame;
+
+	if (!recv_frame_ok(raw, &frame, timeout_ms) ||
+	    !j1939_is_data_frame(frame.can_id))
+		return -1;
+	return j1939_id_prio(frame.can_id);
+}
+
+/*
+ * Set an int J1939 sockopt, read it back, and return the value read, or -1 if
+ * a call fails. errno is 0 if both calls succeed. SO_J1939_SEND_PRIO must
+ * return 0; the flag options go through j1939_set_flag_ok().
+ */
+static int sockopt_roundtrip(int s, int optname, int val)
+{
+	socklen_t len;
+	bool set_ok;
+	int got;
+
+	errno = 0;
+	if (optname == SO_J1939_SEND_PRIO) {
+		set_ok = !setsockopt(s, SOL_CAN_J1939, optname, &val,
+				     sizeof(val));
+	} else {
+		set_ok = j1939_set_flag_ok(s, optname, val);
+	}
+	if (!set_ok)
+		return -1;
+	len = sizeof(got);
+	if (getsockopt(s, SOL_CAN_J1939, optname, &got, &len) < 0)
+		return -1;
+	return got;
+}
+
+FIXTURE(j1939_opts)
+{
+	int ifindex;
+	int tx;
+	int rx;
+	int raw;
+};
+
+FIXTURE_SETUP(j1939_opts)
+{
+	self->tx = -1;
+	self->rx = -1;
+	self->raw = -1;
+
+	J1939_SETUP_IFINDEX(self);
+
+	J1939_SETUP_RAW(self, J1939_RAW_RCVBUF_DEFAULT);
+}
+
+FIXTURE_TEARDOWN(j1939_opts)
+{
+	if (self->tx >= 0)
+		close(self->tx);
+	if (self->rx >= 0)
+		close(self->rx);
+	if (self->raw >= 0)
+		close(self->raw);
+}
+
+/* SO_J1939_FILTER whitelists PGN_A; PGN_A is received, PGN_B is dropped. */
+TEST_F(j1939_opts, filter_pgn)
+{
+	struct j1939_filter filt = {
+		.pgn = PGN_A,
+		.pgn_mask = J1939_PGN_MAX,
+	};
+	struct sockaddr_can src = {};
+	uint8_t tx_buf[CAN_MAX_DLEN];
+
+	fill_pattern(tx_buf, sizeof(tx_buf));
+
+	self->rx = j1939_open(self->ifindex, SA_RX, J1939_NO_PGN);
+	ASSERT_GE(self->rx, 0);
+	ASSERT_EQ(setsockopt(self->rx, SOL_CAN_J1939, SO_J1939_FILTER,
+			     &filt, sizeof(filt)), 0)
+		TH_LOG("SO_J1939_FILTER failed: %d", errno);
+
+	self->tx = j1939_open(self->ifindex, SA_TX, J1939_NO_PGN);
+	ASSERT_GE(self->tx, 0);
+
+	/* PGN_A must pass the filter */
+	ASSERT_TRUE(j1939_sendto_ok(self->tx, tx_buf, sizeof(tx_buf),
+				    self->ifindex, J1939_NO_NAME, SA_RX, PGN_A))
+		TH_LOG("sendto PGN_A failed: %d", errno);
+	EXPECT_TRUE(recv_verify_ok(self->rx, tx_buf, sizeof(tx_buf),
+				   J1939_RECV_TIMEOUT_MS))
+		TH_LOG("PGN_A was not received despite matching filter");
+
+	/*
+	 * The filter must drop PGN_B. Send PGN_B, then PGN_A, and read PGN_A.
+	 * A leaked PGN_B shows up before PGN_A, or during the recv_none_ok()
+	 * wait after it.
+	 */
+	ASSERT_TRUE(j1939_sendto_ok(self->tx, tx_buf, sizeof(tx_buf),
+				    self->ifindex, J1939_NO_NAME, SA_RX, PGN_B))
+		TH_LOG("sendto PGN_B failed: %d", errno);
+	ASSERT_TRUE(j1939_sendto_ok(self->tx, tx_buf, sizeof(tx_buf),
+				    self->ifindex, J1939_NO_NAME, SA_RX, PGN_A))
+		TH_LOG("sendto PGN_A failed: %d", errno);
+	ASSERT_TRUE(recvfrom_verify_ok(self->rx, tx_buf, sizeof(tx_buf),
+				       J1939_RECV_TIMEOUT_MS, &src))
+		TH_LOG("PGN_A after PGN_B was not received");
+	EXPECT_EQ(src.can_addr.j1939.pgn, filt.pgn)
+		TH_LOG("PGN_B was received before PGN_A");
+	EXPECT_TRUE(recv_none_ok(self->rx))
+		TH_LOG("rx got another frame or an error after PGN_A");
+}
+
+/* Without SO_J1939_SEND_PRIO the kernel's default priority is used. */
+TEST_F(j1939_opts, send_prio_default)
+{
+	uint8_t buf[CAN_MAX_DLEN] = {};
+
+	self->tx = j1939_open(self->ifindex, SA_TX, J1939_NO_PGN);
+	ASSERT_GE(self->tx, 0);
+
+	ASSERT_TRUE(j1939_sendto_ok(self->tx, buf, sizeof(buf), self->ifindex,
+				    J1939_NO_NAME, SA_RX, PGN_A));
+
+	EXPECT_EQ(raw_prio(self->raw, J1939_RECV_TIMEOUT_MS),
+		  J1939_PRIO_DEFAULT);
+}
+
+/* SO_J1939_SEND_PRIO changes the priority carried in the CAN id. */
+TEST_F(j1939_opts, send_prio_set)
+{
+	uint8_t buf[CAN_MAX_DLEN] = {};
+	int prio = PRIO_SET;
+
+	self->tx = j1939_open(self->ifindex, SA_TX, J1939_NO_PGN);
+	ASSERT_GE(self->tx, 0);
+	ASSERT_EQ(setsockopt(self->tx, SOL_CAN_J1939, SO_J1939_SEND_PRIO,
+			     &prio, sizeof(prio)), 0)
+		TH_LOG("SO_J1939_SEND_PRIO failed: %d", errno);
+
+	ASSERT_TRUE(j1939_sendto_ok(self->tx, buf, sizeof(buf), self->ifindex,
+				    J1939_NO_NAME, SA_RX, PGN_A));
+
+	EXPECT_EQ(raw_prio(self->raw, J1939_RECV_TIMEOUT_MS), PRIO_SET);
+}
+
+/* An unconnected socket can address a peer via sendto(2). */
+TEST_F(j1939_opts, sendto_unconnected)
+{
+	uint8_t tx_buf[CAN_MAX_DLEN];
+
+	fill_pattern(tx_buf, sizeof(tx_buf));
+
+	self->rx = j1939_open(self->ifindex, SA_RX, PGN_A);
+	ASSERT_GE(self->rx, 0);
+	self->tx = j1939_open(self->ifindex, SA_TX, J1939_NO_PGN);
+	ASSERT_GE(self->tx, 0);
+
+	ASSERT_TRUE(j1939_sendto_ok(self->tx, tx_buf, sizeof(tx_buf),
+				    self->ifindex, J1939_NO_NAME, SA_RX,
+				    PGN_A));
+
+	EXPECT_TRUE(recv_verify_ok(self->rx, tx_buf, sizeof(tx_buf),
+				   J1939_RECV_TIMEOUT_MS));
+}
+
+/* A bind(2) with a wrong address family is rejected. */
+TEST_F(j1939_opts, bind_wrong_family)
+{
+	struct sockaddr_can addr = {
+		.can_family = AF_INET,
+		.can_ifindex = self->ifindex,
+	};
+	int s;
+
+	s = socket(PF_CAN, SOCK_DGRAM, CAN_J1939);
+	ASSERT_GE(s, 0);
+	EXPECT_LT(bind(s, (struct sockaddr *)&addr, sizeof(addr)), 0)
+		TH_LOG("bind with AF_INET unexpectedly succeeded");
+	EXPECT_EQ(errno, EINVAL);
+	close(s);
+}
+
+/* SO_J1939_ERRQUEUE delivers TX completion notifications for a TP send. */
+TEST_F(j1939_opts, errqueue_tx_completion)
+{
+	uint8_t tx_buf[ERRQUEUE_MSG_SIZE];
+
+	fill_pattern(tx_buf, sizeof(tx_buf));
+
+	self->tx = j1939_open(self->ifindex, SA_TX, J1939_NO_PGN);
+	ASSERT_GE(self->tx, 0);
+
+	ASSERT_TRUE(errqueue_enable_ack_ok(self->tx))
+		TH_LOG("enabling the error queue failed: %d", errno);
+
+	/* A receiver lets the TP session complete and be acknowledged. */
+	self->rx = j1939_open(self->ifindex, SA_RX, PGN_A);
+	ASSERT_GE(self->rx, 0);
+
+	ASSERT_TRUE(j1939_sendto_ok(self->tx, tx_buf, sizeof(tx_buf),
+				    self->ifindex, J1939_NO_NAME, SA_RX,
+				    PGN_A));
+
+	ASSERT_TRUE(recv_verify_ok(self->rx, tx_buf, sizeof(tx_buf),
+				   J1939_RECV_TIMEOUT_MS));
+
+	EXPECT_TRUE(errqueue_read_ack_ok(self->tx))
+		TH_LOG("no SCM_TSTAMP_ACK TX completion on the error queue");
+}
+
+/* getsockopt(2) reads back SO_J1939_SEND_PRIO. */
+TEST_F(j1939_opts, getsockopt_send_prio)
+{
+	self->tx = j1939_open(self->ifindex, SA_TX, J1939_NO_PGN);
+	ASSERT_GE(self->tx, 0);
+	EXPECT_EQ(sockopt_roundtrip(self->tx, SO_J1939_SEND_PRIO, PRIO_SET),
+		  PRIO_SET)
+		TH_LOG("SO_J1939_SEND_PRIO round-trip failed: %d", errno);
+}
+
+/* getsockopt(2) reads back the SO_J1939_PROMISC flag, set and cleared. */
+TEST_F(j1939_opts, getsockopt_promisc)
+{
+	self->tx = j1939_open(self->ifindex, SA_TX, J1939_NO_PGN);
+	ASSERT_GE(self->tx, 0);
+	EXPECT_EQ(sockopt_roundtrip(self->tx, SO_J1939_PROMISC, 1), 1)
+		TH_LOG("SO_J1939_PROMISC set round-trip failed: %d", errno);
+	EXPECT_EQ(sockopt_roundtrip(self->tx, SO_J1939_PROMISC, 0), 0)
+		TH_LOG("SO_J1939_PROMISC clear round-trip failed: %d", errno);
+}
+
+/* getsockopt(2) reads back the SO_J1939_ERRQUEUE flag, set and cleared. */
+TEST_F(j1939_opts, getsockopt_errqueue)
+{
+	self->tx = j1939_open(self->ifindex, SA_TX, J1939_NO_PGN);
+	ASSERT_GE(self->tx, 0);
+	EXPECT_EQ(sockopt_roundtrip(self->tx, SO_J1939_ERRQUEUE, 1), 1)
+		TH_LOG("SO_J1939_ERRQUEUE set round-trip failed: %d", errno);
+	EXPECT_EQ(sockopt_roundtrip(self->tx, SO_J1939_ERRQUEUE, 0), 0)
+		TH_LOG("SO_J1939_ERRQUEUE clear round-trip failed: %d", errno);
+}
+
+int main(int argc, char **argv)
+{
+	return j1939_test_main(argc, argv, J1939_NEEDS_RAW);
+}
diff --git a/tools/testing/selftests/net/can/test_j1939_opts.sh b/tools/testing/selftests/net/can/test_j1939_opts.sh
new file mode 100755
index 000000000000..61f65365ec56
--- /dev/null
+++ b/tools/testing/selftests/net/can/test_j1939_opts.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+
+source "$(dirname "$0")/j1939_lib.sh"
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH net-next 05/23] selftests: can: add J1939 addressing and concurrency tests
  2026-12-02 23:04 [PATCH net-next 0/23] pull-request: can-next 2026-12-03 Marc Kleine-Budde
                   ` (3 preceding siblings ...)
  2026-12-02 23:04 ` [PATCH net-next 04/23] selftests: can: add J1939 socket option and metadata tests Marc Kleine-Budde
@ 2026-12-02 23:04 ` Marc Kleine-Budde
  2026-12-02 23:04 ` [PATCH net-next 06/23] selftests: can: add J1939 wire-format tests against CAN_RAW Marc Kleine-Budde
                   ` (17 subsequent siblings)
  22 siblings, 0 replies; 27+ messages in thread
From: Marc Kleine-Budde @ 2026-12-02 23:04 UTC (permalink / raw)
  To: netdev; +Cc: davem, kuba, linux-can, kernel, Oleksij Rempel, Marc Kleine-Budde

From: Oleksij Rempel <o.rempel@pengutronix.de>

Add a selftest for J1939 NAME binding and source addresses: a socket
bound to a NAME reads it back with getsockname(), and a socket bound to
a source address sends frames with that address in the CAN id. A stress
test runs several TP sessions at the same time, each with its own
payload.

Signed-off-by: Oleksij Rempel <o.rempel@pengutronix.de>
Link: https://patch.msgid.link/20261130-j1939-selftests-v7-5-2491693ccb8d@pengutronix.de
[mkl: switch to static_assert()]
Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
---
 tools/testing/selftests/net/can/.gitignore    |   1 +
 tools/testing/selftests/net/can/Makefile      |   1 +
 .../selftests/net/can/test_j1939_addr.c       | 233 ++++++++++++++++++
 .../selftests/net/can/test_j1939_addr.sh      |   4 +
 4 files changed, 239 insertions(+)
 create mode 100644 tools/testing/selftests/net/can/test_j1939_addr.c
 create mode 100755 tools/testing/selftests/net/can/test_j1939_addr.sh

diff --git a/tools/testing/selftests/net/can/.gitignore b/tools/testing/selftests/net/can/.gitignore
index 75c078a2492e..1a6e89cdceb4 100644
--- a/tools/testing/selftests/net/can/.gitignore
+++ b/tools/testing/selftests/net/can/.gitignore
@@ -1,5 +1,6 @@
 # SPDX-License-Identifier: GPL-2.0-only
 j1939_gw
+test_j1939_addr
 test_j1939_base
 test_j1939_opts
 test_raw_filter
diff --git a/tools/testing/selftests/net/can/Makefile b/tools/testing/selftests/net/can/Makefile
index 996b5bbd715a..0ca1d1801ff5 100644
--- a/tools/testing/selftests/net/can/Makefile
+++ b/tools/testing/selftests/net/can/Makefile
@@ -7,6 +7,7 @@ CFLAGS += -Wall -Wl,--no-as-needed -O2 -g -I$(top_srcdir)/usr/include -I$(top_sr
 LOCAL_HDRS := j1939_helpers.h j1939_tests.h ../../clock-helpers.h
 
 TEST_PROGS := \
+	test_j1939_addr.sh \
 	test_j1939_base.sh \
 	test_j1939_opts.sh \
 	test_raw_filter.sh \
diff --git a/tools/testing/selftests/net/can/test_j1939_addr.c b/tools/testing/selftests/net/can/test_j1939_addr.c
new file mode 100644
index 000000000000..b73e4b59fbe5
--- /dev/null
+++ b/tools/testing/selftests/net/can/test_j1939_addr.c
@@ -0,0 +1,233 @@
+// SPDX-License-Identifier: (GPL-2.0-only OR BSD-3-Clause)
+/*
+ * J1939 addressing and concurrency selftests.
+ *
+ * Cover binding a NAME and reading it back, and the bound source address in
+ * the CAN id. Also run many concurrent transport sessions.
+ *
+ * Run by test_j1939_addr.sh, see j1939_tests.h.
+ */
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <sys/wait.h>
+
+#include "j1939_tests.h"
+
+/* fixed unicast addresses, arbitrary */
+#define SA_TX			0x80
+#define SA_RX			0x90
+
+/* stress session i sends from SA_STRESS_TX + i to SA_STRESS_RX + i */
+#define SA_STRESS_TX		0x40
+#define SA_STRESS_RX		0x20
+
+/* NAME, arbitrary */
+#define NAME_TX			0x00000000c0ffee01ULL
+
+/* PGN, arbitrary */
+#define PGN_TEST		0x0ab00
+static_assert(J1939_IS_PDU1(PGN_TEST), "PGN_TEST must be PDU1");
+
+/* stress run, arbitrary tuning */
+#define STRESS_N		8
+#define STRESS_SIZE		128	/* a TP size */
+static_assert(STRESS_SIZE > J1939_SF_MAX_SIZE, "STRESS_SIZE must need TP");
+static_assert(STRESS_SIZE <= J1939_TP_MAX_SIZE, "STRESS_SIZE must fit TP");
+/* the stress addresses lie below the fixed ones, which differ */
+static_assert(SA_STRESS_RX + STRESS_N <= SA_STRESS_TX &&
+	      SA_STRESS_TX + STRESS_N <= SA_TX &&
+	      SA_STRESS_TX + STRESS_N <= SA_RX && SA_TX != SA_RX,
+	      "test addresses overlap");
+static_assert((SA_TX <= J1939_MAX_UNICAST_ADDR) &&
+	      (SA_RX <= J1939_MAX_UNICAST_ADDR),
+	      "the fixed addresses must be unicast");
+
+/* ends of a pipe(2) fd pair */
+enum { PIPE_RD, PIPE_WR, PIPE_NUM };
+
+static int j1939_open_name(int ifindex, name_t name, uint8_t sa, pgn_t pgn)
+{
+	return j1939_open_flags(ifindex, name, sa, pgn, J1939_OPEN_NONE);
+}
+
+/*
+ * One TP transfer from sa_tx to sa_rx. The payload depends on sa_tx, so a
+ * receiver that gets the data of another session fails. After the setup, write
+ * one byte to ready, close it and wait until the parent closes go, so that all
+ * sessions start together.
+ * Returns the exit status of the child process.
+ */
+static int stress_child(int ifindex, uint8_t sa_tx, uint8_t sa_rx, int ready,
+			int go)
+{
+	uint8_t tx_buf[STRESS_SIZE];
+	struct sockaddr_can src;
+	int rc = EXIT_FAILURE;
+	bool setup, signalled;
+	char c = 0;	/* the sync byte, any value */
+	int tx, rx;
+	size_t i;
+
+	fill_pattern(tx_buf, sizeof(tx_buf));
+	for (i = 0; i < sizeof(tx_buf); i++)
+		tx_buf[i] ^= sa_tx;
+
+	rx = j1939_open(ifindex, sa_rx, PGN_TEST);
+	tx = j1939_open(ifindex, sa_tx, J1939_NO_PGN);
+	setup = rx >= 0 && tx >= 0;
+	if (setup)
+		setup = j1939_connect_ok(tx, ifindex, sa_rx, PGN_TEST);
+
+	/*
+	 * Signal even after a setup error, and close ready at once: then the
+	 * parent gets EOF, not a hang, if a child dies before its write.
+	 */
+	signalled = write_all_ok(ready, &c, sizeof(c));
+	close(ready);
+
+	if (!signalled)
+		goto out;
+	/* read() returns 0 at EOF, when the parent closes go */
+	if (read(go, &c, sizeof(c)) != 0)
+		goto out;
+	if (!setup)
+		goto out;
+
+	if (!send_all_ok(tx, tx_buf, sizeof(tx_buf)))
+		goto out;
+
+	if (recvfrom_verify_ok(rx, tx_buf, sizeof(tx_buf),
+			       J1939_RECV_TIMEOUT_MS, &src) &&
+	    src.can_addr.j1939.addr == sa_tx)
+		rc = EXIT_SUCCESS;
+out:
+	if (rx >= 0)
+		close(rx);
+	if (tx >= 0)
+		close(tx);
+	return rc;
+}
+
+FIXTURE(j1939_addr)
+{
+	int ifindex;
+	int tx;
+	int raw;
+};
+
+FIXTURE_SETUP(j1939_addr)
+{
+	self->tx = -1;
+	self->raw = -1;
+
+	J1939_SETUP_IFINDEX(self);
+}
+
+FIXTURE_TEARDOWN(j1939_addr)
+{
+	if (self->tx >= 0)
+		close(self->tx);
+	if (self->raw >= 0)
+		close(self->raw);
+}
+
+/* Bind with a NAME and read it back with getsockname(2). */
+TEST_F(j1939_addr, name_bind_getsockname)
+{
+	struct sockaddr_can addr = {};
+	socklen_t len = sizeof(addr);
+
+	self->tx = j1939_open_name(self->ifindex, NAME_TX, SA_TX, J1939_NO_PGN);
+	ASSERT_GE(self->tx, 0)
+		TH_LOG("bind with NAME failed: %d", errno);
+
+	ASSERT_EQ(getsockname(self->tx, (struct sockaddr *)&addr, &len), 0);
+	EXPECT_EQ(addr.can_addr.j1939.name, NAME_TX);
+	EXPECT_EQ(addr.can_addr.j1939.addr, SA_TX);
+}
+
+/* The bound source address is used as source address on the wire. */
+TEST_F(j1939_addr, source_sa_on_wire)
+{
+	uint8_t buf[CAN_MAX_DLEN] = {};
+	struct can_frame frame;
+
+	self->raw = open_raw();
+	ASSERT_GE(self->raw, 0);
+
+	/* static source address: no address claim needed to transmit */
+	self->tx = j1939_open(self->ifindex, SA_TX, J1939_NO_PGN);
+	ASSERT_GE(self->tx, 0);
+	ASSERT_TRUE(j1939_connect_ok(self->tx, self->ifindex, SA_RX, PGN_TEST));
+
+	ASSERT_TRUE(send_all_ok(self->tx, buf, sizeof(buf)));
+
+	ASSERT_TRUE(recv_frame_ok(self->raw, &frame, J1939_RECV_TIMEOUT_MS));
+	ASSERT_TRUE(j1939_is_data_frame(frame.can_id))
+		TH_LOG("CAN id 0x%08x is not a 29-bit data frame",
+		       frame.can_id);
+	EXPECT_EQ(j1939_id_sa(frame.can_id), SA_TX)
+		TH_LOG("source address on wire is 0x%02x, expected 0x%02x",
+		       j1939_id_sa(frame.can_id), SA_TX);
+}
+
+/* Many concurrent transport-protocol sessions run without corruption. */
+TEST_F(j1939_addr, stress_concurrent_sessions)
+{
+	pid_t pids[STRESS_N];
+	int ready[PIPE_NUM];
+	int go[PIPE_NUM];
+	int failed = 0;
+	int i, n;
+	char c;
+
+	ASSERT_EQ(pipe(ready), 0);
+	ASSERT_EQ(pipe(go), 0);
+
+	for (n = 0; n < STRESS_N; n++) {
+		pids[n] = fork();
+		if (pids[n] < 0)
+			break;
+		if (pids[n] == 0) {
+			close(ready[PIPE_RD]);
+			close(go[PIPE_WR]);
+			_exit(stress_child(self->ifindex, SA_STRESS_TX + n,
+					   SA_STRESS_RX + n, ready[PIPE_WR],
+					   go[PIPE_RD]));
+		}
+	}
+
+	close(ready[PIPE_WR]);
+	close(go[PIPE_RD]);
+
+	/* wait until all children are set up, then start them */
+	for (i = 0; i < n; i++) {
+		if (!read_all_ok(ready[PIPE_RD], &c, sizeof(c)))
+			break;
+	}
+	close(ready[PIPE_RD]);
+	close(go[PIPE_WR]);
+
+	for (i = 0; i < n; i++) {
+		int status;
+
+		if (waitpid(pids[i], &status, 0) < 0) {
+			failed++;
+			continue;
+		}
+		if (!WIFEXITED(status) || WEXITSTATUS(status) != EXIT_SUCCESS)
+			failed++;
+	}
+
+	ASSERT_EQ(n, STRESS_N)
+		TH_LOG("fork failed after %d of %d children", n, STRESS_N);
+	EXPECT_EQ(failed, 0)
+		TH_LOG("%d of %d concurrent sessions failed", failed, STRESS_N);
+}
+
+int main(int argc, char **argv)
+{
+	return j1939_test_main(argc, argv, J1939_NEEDS_RAW);
+}
diff --git a/tools/testing/selftests/net/can/test_j1939_addr.sh b/tools/testing/selftests/net/can/test_j1939_addr.sh
new file mode 100755
index 000000000000..61f65365ec56
--- /dev/null
+++ b/tools/testing/selftests/net/can/test_j1939_addr.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+
+source "$(dirname "$0")/j1939_lib.sh"
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH net-next 06/23] selftests: can: add J1939 wire-format tests against CAN_RAW
  2026-12-02 23:04 [PATCH net-next 0/23] pull-request: can-next 2026-12-03 Marc Kleine-Budde
                   ` (4 preceding siblings ...)
  2026-12-02 23:04 ` [PATCH net-next 05/23] selftests: can: add J1939 addressing and concurrency tests Marc Kleine-Budde
@ 2026-12-02 23:04 ` Marc Kleine-Budde
  2026-12-02 23:04 ` [PATCH net-next 07/23] selftests: can: add J1939 TP/ETP multi-frame " Marc Kleine-Budde
                   ` (16 subsequent siblings)
  22 siblings, 0 replies; 27+ messages in thread
From: Marc Kleine-Budde @ 2026-12-02 23:04 UTC (permalink / raw)
  To: netdev; +Cc: davem, kuba, linux-can, kernel, Oleksij Rempel, Marc Kleine-Budde

From: Oleksij Rempel <o.rempel@pengutronix.de>

Check J1939 single frames against a CAN_RAW socket in both directions,
for PDU1 and PDU2, both with the DP bit set: the CAN id and payload of a
J1939 send, and the payload, source address and PGN that the J1939
socket gets for an injected frame.

The base test sends between two J1939 sockets, so a CAN id encoding bug
and a matching decoding bug in the kernel cancel out there. CAN_RAW does
not use the J1939 code, so it checks each direction on its own.

Signed-off-by: Oleksij Rempel <o.rempel@pengutronix.de>
Link: https://patch.msgid.link/20261130-j1939-selftests-v7-6-2491693ccb8d@pengutronix.de
[mkl: switch to static_assert()]
Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
---
 tools/testing/selftests/net/can/.gitignore    |   1 +
 tools/testing/selftests/net/can/Makefile      |   1 +
 .../selftests/net/can/test_j1939_wire.c       | 202 ++++++++++++++++++
 .../selftests/net/can/test_j1939_wire.sh      |   4 +
 4 files changed, 208 insertions(+)
 create mode 100644 tools/testing/selftests/net/can/test_j1939_wire.c
 create mode 100755 tools/testing/selftests/net/can/test_j1939_wire.sh

diff --git a/tools/testing/selftests/net/can/.gitignore b/tools/testing/selftests/net/can/.gitignore
index 1a6e89cdceb4..6c6b18a9deda 100644
--- a/tools/testing/selftests/net/can/.gitignore
+++ b/tools/testing/selftests/net/can/.gitignore
@@ -3,4 +3,5 @@ j1939_gw
 test_j1939_addr
 test_j1939_base
 test_j1939_opts
+test_j1939_wire
 test_raw_filter
diff --git a/tools/testing/selftests/net/can/Makefile b/tools/testing/selftests/net/can/Makefile
index 0ca1d1801ff5..76ee20ff7830 100644
--- a/tools/testing/selftests/net/can/Makefile
+++ b/tools/testing/selftests/net/can/Makefile
@@ -10,6 +10,7 @@ TEST_PROGS := \
 	test_j1939_addr.sh \
 	test_j1939_base.sh \
 	test_j1939_opts.sh \
+	test_j1939_wire.sh \
 	test_raw_filter.sh \
 # end of TEST_PROGS
 
diff --git a/tools/testing/selftests/net/can/test_j1939_wire.c b/tools/testing/selftests/net/can/test_j1939_wire.c
new file mode 100644
index 000000000000..334975425ca8
--- /dev/null
+++ b/tools/testing/selftests/net/can/test_j1939_wire.c
@@ -0,0 +1,202 @@
+// SPDX-License-Identifier: (GPL-2.0-only OR BSD-3-Clause)
+/*
+ * J1939 wire-format selftests: a J1939 socket against CAN_RAW.
+ *
+ * Run by test_j1939_wire.sh, see j1939_tests.h.
+ */
+#include <errno.h>
+
+#include "j1939_tests.h"
+
+/* arbitrary addresses and PGNs, within the asserts below */
+#define SA_LOCAL		0x90	/* the J1939 socket under test */
+#define SA_PEER			0x20	/* the CAN_RAW peer */
+/* a destination-specific and a broadcast PGN, both with DP set */
+#define PGN_PDU1		(J1939_PGN_DP | 0x0ab00)
+#define PGN_PDU2		(J1939_PGN_DP | 0x0feee)
+static_assert(J1939_IS_PDU1(PGN_PDU1) && !J1939_IS_PDU1(PGN_PDU2),
+	      "PGN_PDU1 must be PDU1 and PGN_PDU2 must be PDU2");
+static_assert((PGN_PDU1 & J1939_PGN_DP) && (PGN_PDU2 & J1939_PGN_DP),
+	      "both PGNs must have the DP bit set");
+static_assert((PGN_PDU1 & UINT8_MAX) == 0,
+	      "the kernel rejects a PDU1 PGN whose PS byte is not 0");
+static_assert(PGN_PDU1 <= J1939_PGN_MAX && PGN_PDU2 <= J1939_PGN_MAX,
+	      "PGN_PDU1 and PGN_PDU2 must be valid PGNs");
+static_assert((SA_LOCAL != SA_PEER) &&
+	      (SA_LOCAL <= J1939_MAX_UNICAST_ADDR) &&
+	      (SA_PEER <= J1939_MAX_UNICAST_ADDR),
+	      "SA_LOCAL and SA_PEER must be two different unicast addresses");
+
+#define PRIO			J1939_PRIO_DEFAULT
+
+FIXTURE(j1939_wire)
+{
+	int ifindex;
+	int j1939;
+	int raw;
+};
+
+FIXTURE_SETUP(j1939_wire)
+{
+	self->j1939 = -1;
+	self->raw = -1;
+
+	J1939_SETUP_IFINDEX(self);
+
+	J1939_SETUP_RAW(self, J1939_RAW_RCVBUF_DEFAULT);
+}
+
+FIXTURE_TEARDOWN(j1939_wire)
+{
+	if (self->j1939 >= 0)
+		close(self->j1939);
+	if (self->raw >= 0)
+		close(self->raw);
+}
+
+/*
+ * Inject one CAN frame from the raw peer and check that the J1939 socket
+ * receives the same CAN_MAX_DLEN-byte payload, from SA_PEER and with PGN pgn.
+ * Opens the J1939 RX socket into self->j1939 (the fixture teardown closes it).
+ * open_flags are the J1939_OPEN_* flags of the socket. pgn is the PGN of the
+ * injected frame and the one the socket binds to; da is the frame's
+ * destination.
+ */
+static bool rx_single_frame_ok(FIXTURE_DATA(j1939_wire) *self, int open_flags,
+			       pgn_t pgn, uint8_t da,
+			       const uint8_t payload[CAN_MAX_DLEN])
+{
+	struct sockaddr_can src = {};
+
+	self->j1939 = j1939_open_flags(self->ifindex, J1939_NO_NAME, SA_LOCAL,
+				       pgn, open_flags);
+	if (self->j1939 < 0) {
+		fprintf(stderr, "# open failed: %d\n", errno);
+		return false;
+	}
+
+	if (!send_raw8_ok(self->raw, PRIO, pgn, da, SA_PEER, payload)) {
+		fprintf(stderr, "# raw send failed: %d\n", errno);
+		return false;
+	}
+
+	if (!recvfrom_verify_ok(self->j1939, payload, CAN_MAX_DLEN,
+				J1939_RECV_TIMEOUT_MS, &src)) {
+		fprintf(stderr, "# payload missing or not the one sent\n");
+		return false;
+	}
+
+	if (src.can_addr.j1939.addr != SA_PEER ||
+	    src.can_addr.j1939.pgn != pgn) {
+		fprintf(stderr, "# SA/PGN 0x%02x/0x%05x, want 0x%02x/0x%05x\n",
+			src.can_addr.j1939.addr, src.can_addr.j1939.pgn,
+			SA_PEER, pgn);
+		return false;
+	}
+	return true;
+}
+
+/*
+ * Send one CAN_MAX_DLEN-byte payload from the J1939 socket to the raw peer and
+ * return the CAN frame seen on the wire via *frame, so each caller can assert
+ * the id fields it cares about. Opens the J1939 TX socket into self->j1939
+ * (the fixture teardown closes it) and connects it to (da, pgn);
+ * open_flags are its J1939_OPEN_* flags.
+ */
+static bool tx_to_raw_send_recv_ok(FIXTURE_DATA(j1939_wire) *self,
+				   int open_flags, pgn_t pgn, uint8_t da,
+				   const uint8_t payload[CAN_MAX_DLEN],
+				   struct can_frame *frame)
+{
+	self->j1939 = j1939_open_flags(self->ifindex, J1939_NO_NAME, SA_LOCAL,
+				       J1939_NO_PGN, open_flags);
+	if (self->j1939 < 0) {
+		fprintf(stderr, "# open failed: %d\n", errno);
+		return false;
+	}
+
+	if (!j1939_connect_ok(self->j1939, self->ifindex, da, pgn)) {
+		fprintf(stderr, "# connect failed: %d\n", errno);
+		return false;
+	}
+
+	if (!send_all_ok(self->j1939, payload, CAN_MAX_DLEN)) {
+		fprintf(stderr, "# send failed: %d\n", errno);
+		return false;
+	}
+
+	if (!recv_frame_ok(self->raw, frame, J1939_RECV_TIMEOUT_MS)) {
+		fprintf(stderr, "# no frame on the raw socket\n");
+		return false;
+	}
+	return true;
+}
+
+/* J1939 TX -> CAN_RAW: destination-specific (PDU1) single frame. */
+TEST_F(j1939_wire, tx_pdu1_to_raw)
+{
+	uint8_t payload[CAN_MAX_DLEN];
+	struct can_frame frame;
+
+	fill_pattern(payload, sizeof(payload));
+	ASSERT_TRUE(tx_to_raw_send_recv_ok(self, J1939_OPEN_NONE, PGN_PDU1,
+					   SA_PEER, payload, &frame));
+	ASSERT_TRUE(j1939_is_data_frame(frame.can_id))
+		TH_LOG("CAN id 0x%08x is not a 29-bit data frame",
+		       frame.can_id);
+
+	EXPECT_EQ(j1939_id_prio(frame.can_id), PRIO);
+	EXPECT_EQ(j1939_id_sa(frame.can_id), SA_LOCAL);
+	EXPECT_EQ(j1939_id_ps(frame.can_id), SA_PEER);
+	/* PGN, with the PS (the destination) masked off */
+	EXPECT_EQ(j1939_id_pgn(frame.can_id) & J1939_PGN_PDU1_MAX, PGN_PDU1);
+
+	ASSERT_EQ(frame.can_dlc, sizeof(payload));
+	EXPECT_EQ(memcmp(frame.data, payload, sizeof(payload)), 0);
+}
+
+/* CAN_RAW -> J1939 RX: destination-specific (PDU1) single frame. */
+TEST_F(j1939_wire, rx_pdu1_from_raw)
+{
+	uint8_t payload[CAN_MAX_DLEN];
+
+	fill_pattern(payload, sizeof(payload));
+	ASSERT_TRUE(rx_single_frame_ok(self, J1939_OPEN_NONE, PGN_PDU1,
+				       SA_LOCAL, payload));
+}
+
+/* J1939 TX -> CAN_RAW: broadcast (PDU2) single frame. */
+TEST_F(j1939_wire, tx_pdu2_to_raw)
+{
+	uint8_t payload[CAN_MAX_DLEN];
+	struct can_frame frame;
+
+	fill_pattern(payload, sizeof(payload));
+	ASSERT_TRUE(tx_to_raw_send_recv_ok(self, J1939_OPEN_BCAST, PGN_PDU2,
+					   J1939_NO_ADDR, payload, &frame));
+	ASSERT_TRUE(j1939_is_data_frame(frame.can_id))
+		TH_LOG("CAN id 0x%08x is not a 29-bit data frame",
+		       frame.can_id);
+
+	EXPECT_EQ(j1939_id_prio(frame.can_id), PRIO);
+	EXPECT_EQ(j1939_id_sa(frame.can_id), SA_LOCAL);
+	EXPECT_EQ(j1939_id_pgn(frame.can_id), PGN_PDU2);
+
+	ASSERT_EQ(frame.can_dlc, sizeof(payload));
+	EXPECT_EQ(memcmp(frame.data, payload, sizeof(payload)), 0);
+}
+
+/* CAN_RAW -> J1939 RX: broadcast (PDU2) single frame. */
+TEST_F(j1939_wire, rx_pdu2_from_raw)
+{
+	uint8_t payload[CAN_MAX_DLEN];
+
+	fill_pattern(payload, sizeof(payload));
+	ASSERT_TRUE(rx_single_frame_ok(self, J1939_OPEN_BCAST, PGN_PDU2,
+				       J1939_NO_ADDR, payload));
+}
+
+int main(int argc, char **argv)
+{
+	return j1939_test_main(argc, argv, J1939_NEEDS_RAW);
+}
diff --git a/tools/testing/selftests/net/can/test_j1939_wire.sh b/tools/testing/selftests/net/can/test_j1939_wire.sh
new file mode 100755
index 000000000000..61f65365ec56
--- /dev/null
+++ b/tools/testing/selftests/net/can/test_j1939_wire.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+
+source "$(dirname "$0")/j1939_lib.sh"
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH net-next 07/23] selftests: can: add J1939 TP/ETP multi-frame tests against CAN_RAW
  2026-12-02 23:04 [PATCH net-next 0/23] pull-request: can-next 2026-12-03 Marc Kleine-Budde
                   ` (5 preceding siblings ...)
  2026-12-02 23:04 ` [PATCH net-next 06/23] selftests: can: add J1939 wire-format tests against CAN_RAW Marc Kleine-Budde
@ 2026-12-02 23:04 ` Marc Kleine-Budde
  2026-12-02 23:04 ` [PATCH net-next 08/23] selftests: can: cover J1939 transport abort and timeout paths Marc Kleine-Budde
                   ` (15 subsequent siblings)
  22 siblings, 0 replies; 27+ messages in thread
From: Marc Kleine-Budde @ 2026-12-02 23:04 UTC (permalink / raw)
  To: netdev; +Cc: davem, kuba, linux-can, kernel, Oleksij Rempel, Marc Kleine-Budde

From: Oleksij Rempel <o.rempel@pengutronix.de>

Add Transport Protocol (TP) and Extended Transport Protocol (ETP)
round-trip tests in both directions, with a CAN_RAW socket as the
transport peer. The raw peer sees the frames as they are on the wire, so
a framing bug in the kernel cannot cancel out against its own decoder.

The tests use a PGN with the DP bit set and check it in each control
frame the kernel sends. In the TX tests, the peer's EOMA must end the
session. The kernel then queues a TX-completion ACK on the socket's
error queue. No ACK may come before the EOMA.

The stack updates a session from the loopback echo of its own TP and
ETP frames. A CAN_RAW peer on the same vcan can read that echo first.
If the peer replies quickly, the stack can cancel the session. By
default the peer runs on its own vcan behind the CAN gateway that
j1939_lib.sh sets up. j1939_lib.sh also turns RPS off on that vcan, so
the peer gets each frame only after the stack has handled its echo; it
warns if it cannot. J1939_SHARED_IF=1 puts the peer back on the same
vcan, with a warning.

Signed-off-by: Oleksij Rempel <o.rempel@pengutronix.de>
Link: https://patch.msgid.link/20261130-j1939-selftests-v7-7-2491693ccb8d@pengutronix.de
[mkl: switch to static_assert()]
Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
---
 tools/testing/selftests/net/can/.gitignore    |   1 +
 tools/testing/selftests/net/can/Makefile      |   1 +
 .../testing/selftests/net/can/j1939_helpers.c |   7 +
 .../testing/selftests/net/can/j1939_helpers.h |   6 +
 .../selftests/net/can/test_j1939_multi.c      | 695 ++++++++++++++++++
 .../selftests/net/can/test_j1939_multi.sh     |   4 +
 6 files changed, 714 insertions(+)
 create mode 100644 tools/testing/selftests/net/can/test_j1939_multi.c
 create mode 100755 tools/testing/selftests/net/can/test_j1939_multi.sh

diff --git a/tools/testing/selftests/net/can/.gitignore b/tools/testing/selftests/net/can/.gitignore
index 6c6b18a9deda..c6071caef4e9 100644
--- a/tools/testing/selftests/net/can/.gitignore
+++ b/tools/testing/selftests/net/can/.gitignore
@@ -2,6 +2,7 @@
 j1939_gw
 test_j1939_addr
 test_j1939_base
+test_j1939_multi
 test_j1939_opts
 test_j1939_wire
 test_raw_filter
diff --git a/tools/testing/selftests/net/can/Makefile b/tools/testing/selftests/net/can/Makefile
index 76ee20ff7830..c3e5060b5ceb 100644
--- a/tools/testing/selftests/net/can/Makefile
+++ b/tools/testing/selftests/net/can/Makefile
@@ -9,6 +9,7 @@ LOCAL_HDRS := j1939_helpers.h j1939_tests.h ../../clock-helpers.h
 TEST_PROGS := \
 	test_j1939_addr.sh \
 	test_j1939_base.sh \
+	test_j1939_multi.sh \
 	test_j1939_opts.sh \
 	test_j1939_wire.sh \
 	test_raw_filter.sh \
diff --git a/tools/testing/selftests/net/can/j1939_helpers.c b/tools/testing/selftests/net/can/j1939_helpers.c
index c705a8957776..da3293348185 100644
--- a/tools/testing/selftests/net/can/j1939_helpers.c
+++ b/tools/testing/selftests/net/can/j1939_helpers.c
@@ -562,6 +562,13 @@ bool errqueue_read_ack_ok(int s)
 	return msg_has_tstamp_ack(&msg);
 }
 
+bool errqueue_empty_ok(int s)
+{
+	struct pollfd pfd = { .fd = s, .events = POLLERR };
+
+	return poll(&pfd, 1, J1939_NEG_RECV_TIMEOUT_MS) == 0;
+}
+
 /* Arbitrary; keeps fill_pattern() from being the plain byte offset. */
 #define J1939_PATTERN_SEED	0x3c
 
diff --git a/tools/testing/selftests/net/can/j1939_helpers.h b/tools/testing/selftests/net/can/j1939_helpers.h
index bc4ffeea06c4..7f8004f02c3b 100644
--- a/tools/testing/selftests/net/can/j1939_helpers.h
+++ b/tools/testing/selftests/net/can/j1939_helpers.h
@@ -305,6 +305,12 @@ bool errqueue_enable_ack_ok(int s);
  */
 bool errqueue_read_ack_ok(int s);
 
+/*
+ * Does POLLERR stay clear on s for J1939_NEG_RECV_TIMEOUT_MS? An error-queue
+ * entry or a pending socket error sets it. Also false if poll() fails.
+ */
+bool errqueue_empty_ok(int s);
+
 /*
  * Fill buf with a deterministic, position-dependent byte pattern. The
  * i >> CHAR_BIT term makes each 256-byte block of the first 64 KiB differ.
diff --git a/tools/testing/selftests/net/can/test_j1939_multi.c b/tools/testing/selftests/net/can/test_j1939_multi.c
new file mode 100644
index 000000000000..410e602a475c
--- /dev/null
+++ b/tools/testing/selftests/net/can/test_j1939_multi.c
@@ -0,0 +1,695 @@
+// SPDX-License-Identifier: (GPL-2.0-only OR BSD-3-Clause)
+/*
+ * J1939 multi-frame wire selftests: TP and ETP against CAN_RAW.
+ *
+ * A CAN_RAW socket plays the transport peer against the kernel J1939 stack,
+ * in both directions. It takes the other side of the RTS/CTS/DT/EOMA
+ * exchange, for TP with a short message and for ETP with a payload that
+ * spans several CTS blocks (DPO windows).
+ *
+ * Known stack race: the stack updates a session from the loopback echo of
+ * its own TP and ETP frames. A CAN_RAW peer on the same vcan can read
+ * that echo first. If the peer replies quickly, the stack can cancel the
+ * session. See j1939_lib.sh for where the peer runs. The fix belongs in
+ * the stack; this file does not work around it.
+ *
+ * Run by test_j1939_multi.sh, see j1939_tests.h.
+ */
+#include <errno.h>
+
+#include "j1939_tests.h"
+
+/* arbitrary addresses */
+#define SA_LOCAL		0x90	/* the J1939 socket under test */
+#define SA_PEER			0x20	/* the CAN_RAW transport peer */
+static_assert((SA_LOCAL != SA_PEER) &&
+	      (SA_LOCAL <= J1939_MAX_UNICAST_ADDR) &&
+	      (SA_PEER <= J1939_MAX_UNICAST_ADDR),
+	      "SA_LOCAL and SA_PEER must be two different unicast addresses");
+/*
+ * transported message PGN, an arbitrary PDU2 PGN with the DP bit set so a
+ * PGN cut to 16 bits fails the check
+ */
+#define PGN_DATA		(J1939_PGN_DP | 0x0feef)
+static_assert(PGN_DATA & J1939_PGN_DP, "PGN_DATA must have the DP bit set");
+static_assert(!J1939_IS_PDU1(PGN_DATA) && PGN_DATA <= J1939_PGN_MAX,
+	      "PGN_DATA must be a valid PDU2 PGN");
+
+/*
+ * Priority for the TP and ETP frames this test injects as the CAN_RAW
+ * peer. SAE J1939-21:2001 lists 7 as the TP.CM/TP.DT default and
+ * ISO 11783-6:2004 Annex K gives 6 for ETP. The stack checks neither, so
+ * one value serves both.
+ */
+#define PRIO			7
+
+/*
+ * PGNs, control bytes and field byte offsets (_OFF) of TP (SAE J1939-21:2001
+ * sections 5.10.3 and 5.10.4) and ETP (ISO 11783-6:2004 K.2.2.1 and K.2.3).
+ */
+
+/* PGNs */
+#define TP_CM			0x0ec00
+#define TP_DT			0x0eb00
+#define ETP_CM			0x0c800
+#define ETP_DT			0x0c700
+
+/* control bytes */
+#define TP_CMD_RTS		0x10
+#define TP_CMD_CTS		0x11
+#define TP_CMD_EOMA		0x13
+
+#define ETP_CMD_RTS		0x14
+#define ETP_CMD_CTS		0x15
+#define ETP_CMD_DPO		0x16
+#define ETP_CMD_EOMA		0x17
+
+/* field offsets */
+#define TP_RTS_SIZE_OFF		1	/* le16 */
+#define TP_RTS_PKTS_OFF		3
+#define TP_RTS_MAX_PKTS_OFF	4
+#define TP_CTS_PKTS_OFF		1
+#define TP_CTS_NEXT_OFF		2
+#define TP_EOMA_SIZE_OFF	1	/* le16 */
+#define TP_EOMA_PKTS_OFF	3
+
+/* TP.CM_RTS max packets per CTS: no limit (SAE J1939-21:2001 section 5.10.3) */
+#define TP_RTS_NO_LIMIT		0xff
+
+#define ETP_RTS_SIZE_OFF	1	/* le32 */
+#define ETP_CTS_PKTS_OFF	1
+#define ETP_CTS_NEXT_OFF	2	/* le24 */
+#define ETP_DPO_PKTS_OFF	1
+#define ETP_DPO_BASE_OFF	2	/* le24, packets before this block */
+#define ETP_EOMA_SIZE_OFF	1	/* le32 */
+
+/*
+ * largest ETP.CTS packet count: the field is one byte. It is also the
+ * kernel's ETP block (pkt.block, applied in j1939_session_tx_cts()).
+ */
+#define ETP_CTS_MAX_PKTS	UINT8_MAX
+/* TP and ETP packet numbers start at 1 */
+#define TP_FIRST_PKT		1
+/* TP counts DT sequence numbers from the start of the message */
+#define TP_BASE_PKT		0
+
+/*
+ * arbitrary message sizes, within the asserts below: TP of several
+ * packets and above 255 bytes, ETP of several ETP.CTS blocks
+ */
+#define TP_SIZE			300
+static_assert(TP_SIZE > J1939_SF_MAX_SIZE, "TP_SIZE must need TP");
+static_assert(TP_SIZE <= J1939_TP_MAX_SIZE, "TP_SIZE must fit TP");
+static_assert(TP_SIZE > UINT8_MAX,
+	      "TP_SIZE must use the high byte of the TP.CM size field");
+static_assert(TP_SIZE % J1939_DT_DATA_LEN != 0,
+	      "the last TP DT frame must be partial, so its fill is checked");
+
+#define ETP_SIZE		6000U
+static_assert(ETP_SIZE > J1939_TP_MAX_SIZE, "ETP_SIZE must need ETP");
+static_assert(J1939_NUM_PKTS(ETP_SIZE) > ETP_CTS_MAX_PKTS,
+	      "ETP_SIZE must span several ETP.CTS blocks");
+static_assert(ETP_SIZE % J1939_DT_DATA_LEN != 0,
+	      "the last ETP DT frame must be partial, so its fill is checked");
+static_assert(J1939_NUM_PKTS(ETP_SIZE) % ETP_CTS_MAX_PKTS != 0,
+	      "the last ETP block must be partial");
+
+/* an RTS per-CTS limit as large as the message: all packets in one CTS */
+#define TP_CTS_ALL		J1939_NUM_PKTS(TP_SIZE)
+static_assert(TP_CTS_ALL <= UINT8_MAX, "the TP.CM packet counts are one byte");
+
+FIXTURE(j1939_multi)
+{
+	int ifindex;
+	int j1939;
+	int raw;
+};
+
+FIXTURE_SETUP(j1939_multi)
+{
+	self->j1939 = -1;
+	self->raw = -1;
+
+	J1939_SETUP_IFINDEX(self);
+
+	J1939_SETUP_RAW(self, J1939_RAW_BIG_RCVBUF);
+}
+
+FIXTURE_TEARDOWN(j1939_multi)
+{
+	if (self->j1939 >= 0)
+		close(self->j1939);
+	if (self->raw >= 0)
+		close(self->raw);
+}
+
+/*
+ * Finish a TP/ETP control frame by embedding its data PGN and sending it on the
+ * control PGN. dat must already hold the command and its command-specific
+ * bytes.
+ */
+static bool send_cm_frame_ok(int raw, uint8_t prio, pgn_t cm_pgn, uint8_t da,
+			     uint8_t sa, uint8_t *dat, pgn_t data_pgn)
+{
+	put_pgn(dat, data_pgn);
+	return send_raw8_ok(raw, prio, cm_pgn, da, sa, dat);
+}
+
+/* send_cm_frame_ok() from the peer to the kernel, for PGN_DATA. */
+static bool peer_send_cm_ok(int raw, pgn_t cm_pgn, uint8_t *dat)
+{
+	return send_cm_frame_ok(raw, PRIO, cm_pgn, SA_LOCAL, SA_PEER, dat,
+				PGN_DATA);
+}
+
+/*
+ * Receive the next control frame on cm_pgn from the kernel to the peer and
+ * check that it is a full frame with the control byte cmd and PGN_DATA.
+ */
+static bool recv_kernel_cm_ok(int raw, pgn_t cm_pgn, uint8_t cmd,
+			      struct can_frame *frame, int timeout_ms)
+{
+	if (!recv_cm_cmd_ok(raw, J1939_PF(cm_pgn), SA_PEER, SA_LOCAL, frame,
+			    timeout_ms, cmd))
+		return false;
+
+	return frame->len == CAN_MAX_DLEN &&
+	       get_le24(&frame->data[J1939_CM_PGN_OFF]) == PGN_DATA;
+}
+
+/*
+ * Build and send a TP.CM_RTS: message size, total packets and max packets/CTS.
+ */
+static bool send_tp_rts_ok(int raw, uint8_t prio, pgn_t pgn, uint8_t da,
+			   uint8_t sa, uint16_t size, uint8_t total_pkts,
+			   uint8_t max_cts_pkts)
+{
+	uint8_t dat[CAN_MAX_DLEN];
+
+	cm_dat_init(dat, TP_CMD_RTS);
+	put_le16(&dat[TP_RTS_SIZE_OFF], size);
+	dat[TP_RTS_PKTS_OFF] = total_pkts;
+	dat[TP_RTS_MAX_PKTS_OFF] = max_cts_pkts;
+	return send_cm_frame_ok(raw, prio, TP_CM, da, sa, dat, pgn);
+}
+
+/*
+ * Send a burst of count DT frames for the block starting at the 1-based packet
+ * next, each carrying up to J1939_DT_DATA_LEN payload bytes from the matching
+ * absolute offset. The first frame has sequence number first_seq: TP numbers
+ * packets across the whole message (next), ETP starts again at TP_FIRST_PKT
+ * in each DPO block.
+ */
+static bool send_dt_burst_ok(int raw, uint8_t prio, pgn_t dt_pgn, uint8_t da,
+			     uint8_t sa, unsigned int next, unsigned int count,
+			     const uint8_t *payload, size_t size,
+			     unsigned int first_seq)
+{
+	unsigned int i;
+
+	for (i = 0; i < count; i++) {
+		size_t abs_pkt;
+		uint8_t seq;
+
+		abs_pkt = next - 1 + i;
+		seq = first_seq + i;
+		if (!send_dt_ok(raw, prio, dt_pgn, da, sa, seq, payload,
+				abs_pkt * J1939_DT_DATA_LEN, size))
+			return false;
+	}
+	return true;
+}
+
+/* send_dt_burst_ok() for TP, which numbers packets across the message */
+static bool send_tp_dt_burst_ok(int raw, uint8_t da, uint8_t sa,
+				unsigned int next, unsigned int count,
+				const uint8_t *payload, size_t size)
+{
+	return send_dt_burst_ok(raw, PRIO, TP_DT, da, sa, next, count, payload,
+				size, next);
+}
+
+/*
+ * Check a CTS or ETP.CTS from the kernel that asks for cts_pkts packets from
+ * the 1-based packet next. The peer has sent `sent` of num_pkts packets, so
+ * the kernel must ask for packet sent + 1 and for
+ * min(cts_limit, num_pkts - sent) packets, see j1939_session_tx_cts(). No
+ * frame is lost here, so no resend is expected
+ * (SAE J1939-21:2001 section 5.10.3.2 allows one for TP).
+ */
+static bool cts_accept_ok(unsigned int cts_pkts, unsigned int next,
+			  unsigned int sent, unsigned int num_pkts,
+			  unsigned int cts_limit)
+{
+	unsigned int want;
+
+	want = num_pkts - sent;
+	if (want > cts_limit)
+		want = cts_limit;
+	if (cts_pkts == want && next == sent + 1)
+		return true;
+
+	fprintf(stderr, "# CTS for %u packets from %u, want %u from %u\n",
+		cts_pkts, next, want, sent + 1);
+	return false;
+}
+
+/*
+ * Answer each CTS from the kernel with a DT burst from the peer, until
+ * num_pkts are delivered. Each CTS must ask for cts_limit packets, or for the
+ * rest, see cts_accept_ok().
+ */
+static bool tp_serve_cts_ok(int raw, const uint8_t *payload, size_t size,
+			    unsigned int num_pkts, unsigned int cts_limit)
+{
+	struct can_frame frame;
+	unsigned int sent = 0;
+
+	while (sent < num_pkts) {
+		unsigned int cts_pkts, next;
+
+		if (!recv_kernel_cm_ok(raw, TP_CM, TP_CMD_CTS, &frame,
+				       J1939_RECV_TIMEOUT_MS)) {
+			fprintf(stderr, "# no well-formed TP CTS at %u/%u\n",
+				sent, num_pkts);
+			return false;
+		}
+
+		cts_pkts = frame.data[TP_CTS_PKTS_OFF];
+		next = frame.data[TP_CTS_NEXT_OFF];	/* 1-based */
+		if (!cts_accept_ok(cts_pkts, next, sent, num_pkts, cts_limit))
+			return false;
+
+		if (!send_tp_dt_burst_ok(raw, SA_LOCAL, SA_PEER, next, cts_pkts,
+					 payload, size))
+			return false;
+
+		sent += cts_pkts;
+	}
+	return true;
+}
+
+/*
+ * Answer each ETP.CTS from the kernel with a DPO and the block's DT frames,
+ * until all size bytes of payload are delivered. Each ETP.CTS must ask
+ * for a full block of ETP_CTS_MAX_PKTS packets, or for the rest.
+ */
+static bool etp_rx_serve_cts_ok(int raw, const uint8_t *payload, size_t size)
+{
+	uint8_t dat[CAN_MAX_DLEN];
+	struct can_frame frame;
+	unsigned int num_pkts;
+	unsigned int sent = 0;
+
+	num_pkts = J1939_NUM_PKTS(size);
+	while (sent < num_pkts) {
+		unsigned int cts_pkts, next;
+
+		if (!recv_kernel_cm_ok(raw, ETP_CM, ETP_CMD_CTS, &frame,
+				       J1939_RECV_TIMEOUT_MS)) {
+			fprintf(stderr, "# no well-formed ETP CTS at %u/%u\n",
+				sent, num_pkts);
+			return false;
+		}
+
+		cts_pkts = frame.data[ETP_CTS_PKTS_OFF];
+		next = get_le24(&frame.data[ETP_CTS_NEXT_OFF]);	/* 1-based */
+		if (!cts_accept_ok(cts_pkts, next, sent, num_pkts,
+				   ETP_CTS_MAX_PKTS))
+			return false;
+
+		cm_dat_init(dat, ETP_CMD_DPO);
+		dat[ETP_DPO_PKTS_OFF] = cts_pkts;
+		put_le24(&dat[ETP_DPO_BASE_OFF], next - 1);
+		if (!peer_send_cm_ok(raw, ETP_CM, dat))
+			return false;
+
+		if (!send_dt_burst_ok(raw, PRIO, ETP_DT, SA_LOCAL, SA_PEER,
+				      next, cts_pkts, payload, size,
+				      TP_FIRST_PKT))
+			return false;
+
+		sent += cts_pkts;
+	}
+	return true;
+}
+
+/* Message offset of a DT frame's payload; base_pkt as for unpack_dt_into() */
+static size_t dt_off(const struct can_frame *frame, unsigned int base_pkt)
+{
+	return (base_pkt + (frame->data[J1939_DT_SEQ_OFF] - 1)) *
+	       J1939_DT_DATA_LEN;
+}
+
+/*
+ * Scatter a received DT frame's payload into buf, a message of size bytes,
+ * at the offset implied by its sequence number. base_pkt is the number of
+ * packets before this block (TP_BASE_PKT for TP, the DPO offset for ETP);
+ * seq counts from 1 inside the block.
+ */
+static void unpack_dt_into(uint8_t *buf, size_t size, unsigned int base_pkt,
+			   const struct can_frame *frame)
+{
+	size_t off;
+
+	off = dt_off(frame, base_pkt);
+	/* drop a frame with a bad sequence number instead of overrunning buf */
+	if (off >= size)
+		return;
+
+	memcpy(buf + off, &frame->data[J1939_DT_DATA_OFF],
+	       j1939_dt_chunk_len(size, off));
+}
+
+/* Are the bytes after the payload in a DT frame all J1939_FILL_BYTE? */
+static bool dt_fill_ok(const struct can_frame *frame, size_t size,
+		       unsigned int base_pkt)
+{
+	size_t off;
+	size_t i;
+
+	off = dt_off(frame, base_pkt);
+	if (off >= size)
+		return true;	/* a bad sequence number fails elsewhere */
+	for (i = J1939_DT_DATA_OFF + j1939_dt_chunk_len(size, off);
+	     i < CAN_MAX_DLEN; i++) {
+		if (frame->data[i] != J1939_FILL_BYTE)
+			return false;
+	}
+	return true;
+}
+
+/*
+ * Receive count DT frames on dt_pgn from the kernel and scatter them into
+ * buf, a message of size bytes; base_pkt as for unpack_dt_into(). Each frame
+ * must have CAN_MAX_DLEN bytes (the kernel pads the last one with
+ * J1939_FILL_BYTE, see j1939_tp_tx_dat(), and dt_fill_ok() checks it) and the
+ * sequence number TP_FIRST_PKT + i. That holds for an ETP block and for a TP
+ * CTS window that starts at the first packet.
+ */
+static bool recv_dt_block_ok(int raw, pgn_t dt_pgn, uint8_t *buf, size_t size,
+			     unsigned int base_pkt, unsigned int count)
+{
+	struct can_frame frame;
+	unsigned int i;
+
+	for (i = 0; i < count; i++) {
+		if (!recv_for_peer_ok(raw, J1939_PF(dt_pgn), SA_PEER, SA_LOCAL,
+				      &frame, J1939_RECV_TIMEOUT_MS)) {
+			fprintf(stderr, "# missing DT %u of %u\n",
+				i + TP_FIRST_PKT, count);
+			return false;
+		}
+		if (frame.len != CAN_MAX_DLEN ||
+		    frame.data[J1939_DT_SEQ_OFF] != TP_FIRST_PKT + i) {
+			fprintf(stderr, "# DT %u of %u: len %u, seq %u\n",
+				i + TP_FIRST_PKT, count, frame.len,
+				frame.data[J1939_DT_SEQ_OFF]);
+			return false;
+		}
+		if (!dt_fill_ok(&frame, size, base_pkt)) {
+			fprintf(stderr, "# DT %u of %u: bad fill bytes\n",
+				i + TP_FIRST_PKT, count);
+			return false;
+		}
+		unpack_dt_into(buf, size, base_pkt, &frame);
+	}
+	return true;
+}
+
+/*
+ * Open a TP RX j1939 socket and send the RTS for a TP_SIZE message that
+ * starts a receive session.
+ */
+static bool tp_rx_open_and_send_rts_ok(int *j1939, int raw, int ifindex,
+				       uint8_t cts_limit)
+{
+	*j1939 = j1939_open(ifindex, SA_LOCAL, PGN_DATA);
+	if (*j1939 < 0)
+		return false;
+
+	return send_tp_rts_ok(raw, PRIO, PGN_DATA, SA_LOCAL, SA_PEER, TP_SIZE,
+			      J1939_NUM_PKTS(TP_SIZE), cts_limit);
+}
+
+/*
+ * TP-RX round-trip: open the j1939 socket, drive a full TP receive from the
+ * raw peer advertising cts_limit packets per CTS, and verify the reassembled
+ * payload against the sent pattern. Each CTS must ask for cts_limit packets,
+ * or for the rest, see cts_accept_ok(). The kernel's EOMA frame is returned
+ * via *eoma_out.
+ */
+static bool tp_rx_roundtrip_ok(FIXTURE_DATA(j1939_multi) *self,
+			       uint8_t cts_limit, struct can_frame *eoma_out)
+{
+	uint8_t payload[TP_SIZE];
+
+	fill_pattern(payload, sizeof(payload));
+
+	if (!tp_rx_open_and_send_rts_ok(&self->j1939, self->raw, self->ifindex,
+					cts_limit))
+		return false;
+
+	if (!tp_serve_cts_ok(self->raw, payload, sizeof(payload),
+			     J1939_NUM_PKTS(TP_SIZE), cts_limit))
+		return false;
+
+	if (!recv_kernel_cm_ok(self->raw, TP_CM, TP_CMD_EOMA, eoma_out,
+			       J1939_RECV_TIMEOUT_MS))
+		return false;
+
+	return recv_verify_ok(self->j1939, payload, sizeof(payload),
+			      J1939_RECV_TIMEOUT_MS);
+}
+
+/*
+ * TP RX: the CAN_RAW peer transmits a TP message to the J1939 socket.
+ * raw sends RTS, then answers each CTS from the kernel with DT frames.
+ */
+TEST_F(j1939_multi, tp_rx_from_raw)
+{
+	struct can_frame frame;
+
+	/* the RTS allows all packets in one CTS */
+	ASSERT_TRUE(tp_rx_roundtrip_ok(self, TP_CTS_ALL, &frame))
+		TH_LOG("TP RX round-trip against the raw peer failed");
+
+	/* frame is the kernel's EOMA */
+	EXPECT_EQ(get_le16(&frame.data[TP_EOMA_SIZE_OFF]), TP_SIZE);
+	EXPECT_EQ(frame.data[TP_EOMA_PKTS_OFF], J1939_NUM_PKTS(TP_SIZE));
+}
+
+/*
+ * Start a TP/ETP transmit session from the J1939 socket: open a socket bound
+ * to SA_LOCAL with no PGN, connect to the peer, send the size bytes of
+ * payload and collect the kernel's RTS from the raw peer (cm_pgn/rts_cmd
+ * select TP or ETP). *j1939 holds the fd before connect() or send() can
+ * fail, so the fixture teardown closes it.
+ */
+static bool tx_start_session_ok(int *j1939, int raw, int ifindex,
+				const void *payload, size_t size, pgn_t cm_pgn,
+				uint8_t rts_cmd, struct can_frame *rts)
+{
+	*j1939 = j1939_open(ifindex, SA_LOCAL, J1939_NO_PGN);
+	if (*j1939 < 0)
+		return false;
+
+	if (!j1939_connect_ok(*j1939, ifindex, SA_PEER, PGN_DATA))
+		return false;
+
+	if (!send_all_ok(*j1939, payload, size))
+		return false;
+
+	return recv_kernel_cm_ok(raw, cm_pgn, rts_cmd, rts,
+				 J1939_RECV_TIMEOUT_MS);
+}
+
+static bool tp_tx_start_session_ok(FIXTURE_DATA(j1939_multi) *self,
+				   const void *payload, size_t size,
+				   struct can_frame *rts)
+{
+	return tx_start_session_ok(&self->j1939, self->raw, self->ifindex,
+				   payload, size, TP_CM, TP_CMD_RTS, rts);
+}
+
+static bool etp_tx_start_session_ok(FIXTURE_DATA(j1939_multi) *self,
+				    const void *payload, size_t size,
+				    struct can_frame *rts)
+{
+	return tx_start_session_ok(&self->j1939, self->raw, self->ifindex,
+				   payload, size, ETP_CM, ETP_CMD_RTS, rts);
+}
+
+/*
+ * TP TX: the J1939 socket transmits a TP message to the CAN_RAW peer.
+ * raw answers the kernel's RTS with a CTS, collects the DT frames and
+ * acknowledges with EOMA, which completes the session. The socket then
+ * gets the TX-completion ACK.
+ */
+TEST_F(j1939_multi, tp_tx_to_raw)
+{
+	unsigned int num_pkts = J1939_NUM_PKTS(TP_SIZE);
+	uint8_t dat[CAN_MAX_DLEN];
+	uint8_t payload[TP_SIZE];
+	uint8_t rx_buf[TP_SIZE];
+	struct can_frame frame;
+
+	fill_pattern(payload, sizeof(payload));
+	memset(rx_buf, 0, sizeof(rx_buf));
+
+	ASSERT_TRUE(tp_tx_start_session_ok(self, payload, sizeof(payload),
+					   &frame));
+	ASSERT_TRUE(errqueue_enable_ack_ok(self->j1939));
+
+	EXPECT_EQ(get_le16(&frame.data[TP_RTS_SIZE_OFF]), TP_SIZE);
+	EXPECT_EQ(frame.data[TP_RTS_PKTS_OFF], num_pkts);
+	EXPECT_TRUE(frame.data[TP_RTS_MAX_PKTS_OFF] == num_pkts ||
+		    frame.data[TP_RTS_MAX_PKTS_OFF] == TP_RTS_NO_LIMIT);
+
+	/* request all packets in one CTS, starting at the first */
+	cm_dat_init(dat, TP_CMD_CTS);
+	dat[TP_CTS_PKTS_OFF] = num_pkts;
+	dat[TP_CTS_NEXT_OFF] = TP_FIRST_PKT;
+	ASSERT_TRUE(peer_send_cm_ok(self->raw, TP_CM, dat));
+
+	ASSERT_TRUE(recv_dt_block_ok(self->raw, TP_DT, rx_buf, sizeof(rx_buf),
+				     TP_BASE_PKT, num_pkts));
+	EXPECT_TRUE(errqueue_empty_ok(self->j1939))
+		TH_LOG("error-queue entry or socket error before the EOMA");
+
+	cm_dat_init(dat, TP_CMD_EOMA);
+	put_le16(&dat[TP_EOMA_SIZE_OFF], TP_SIZE);
+	dat[TP_EOMA_PKTS_OFF] = num_pkts;
+	ASSERT_TRUE(peer_send_cm_ok(self->raw, TP_CM, dat));
+
+	EXPECT_EQ(memcmp(payload, rx_buf, sizeof(payload)), 0);
+	EXPECT_TRUE(errqueue_read_ack_ok(self->j1939))
+		TH_LOG("no TX-completion ACK after the EOMA");
+}
+
+/*
+ * ETP RX: the CAN_RAW peer transmits an ETP message to the J1939 socket.
+ * The kernel requests blocks with ETP.CTS; raw answers each with a DPO and
+ * the block's DT frames. The payload spans several ETP.CTS blocks.
+ */
+TEST_F(j1939_multi, etp_rx_from_raw)
+{
+	static uint8_t payload[ETP_SIZE];
+	uint8_t dat[CAN_MAX_DLEN];
+	struct can_frame frame;
+
+	fill_pattern(payload, sizeof(payload));
+
+	self->j1939 = j1939_open(self->ifindex, SA_LOCAL, PGN_DATA);
+	ASSERT_GE(self->j1939, 0);
+
+	cm_dat_init(dat, ETP_CMD_RTS);
+	put_le32(&dat[ETP_RTS_SIZE_OFF], ETP_SIZE);
+	ASSERT_TRUE(peer_send_cm_ok(self->raw, ETP_CM, dat));
+
+	ASSERT_TRUE(etp_rx_serve_cts_ok(self->raw, payload, sizeof(payload)));
+
+	ASSERT_TRUE(recv_kernel_cm_ok(self->raw, ETP_CM, ETP_CMD_EOMA, &frame,
+				      J1939_RECV_TIMEOUT_MS))
+		TH_LOG("no well-formed ETP EOMA from kernel after last DT");
+	EXPECT_EQ(get_le32(&frame.data[ETP_EOMA_SIZE_OFF]), ETP_SIZE);
+
+	EXPECT_TRUE(recv_verify_ok(self->j1939, payload, sizeof(payload),
+				   J1939_RECV_TIMEOUT_MS))
+		TH_LOG("J1939 socket did not get the exact ETP message");
+}
+
+/*
+ * Ask the kernel for the next ETP block of cts_pkts packets, after got
+ * packets are already received. Check its DPO and receive the block into
+ * rx_buf, a message of size bytes.
+ */
+static bool etp_tx_serve_block_ok(FIXTURE_DATA(j1939_multi) *self,
+				  uint8_t *rx_buf, size_t size,
+				  unsigned int got, unsigned int cts_pkts)
+{
+	unsigned int dpo_num, dpo_base_pkt;
+	uint8_t dat[CAN_MAX_DLEN];
+	struct can_frame frame;
+	unsigned int next;
+
+	next = got + 1;		/* 1-based */
+	cm_dat_init(dat, ETP_CMD_CTS);
+	dat[ETP_CTS_PKTS_OFF] = cts_pkts;
+	put_le24(&dat[ETP_CTS_NEXT_OFF], next);
+	if (!peer_send_cm_ok(self->raw, ETP_CM, dat))
+		return false;
+
+	if (!recv_kernel_cm_ok(self->raw, ETP_CM, ETP_CMD_DPO, &frame,
+			       J1939_RECV_TIMEOUT_MS)) {
+		fprintf(stderr, "# no well-formed DPO after %u packets\n", got);
+		return false;
+	}
+
+	dpo_num = frame.data[ETP_DPO_PKTS_OFF];
+	dpo_base_pkt = get_le24(&frame.data[ETP_DPO_BASE_OFF]);
+	if (dpo_num != cts_pkts || dpo_base_pkt != got) {
+		fprintf(stderr, "# DPO for %u after %u, want %u after %u\n",
+			dpo_num, dpo_base_pkt, cts_pkts, got);
+		return false;
+	}
+
+	return recv_dt_block_ok(self->raw, ETP_DT, rx_buf, size, dpo_base_pkt,
+				dpo_num);
+}
+
+/*
+ * ETP TX: the J1939 socket transmits an ETP message to the CAN_RAW peer.
+ * raw requests the data in blocks of up to ETP_CTS_MAX_PKTS packets
+ * (ETP.CTS). For each block the kernel sends a DPO and the DT frames. The
+ * EOMA from raw completes the session, and the socket then gets the
+ * TX-completion ACK.
+ */
+TEST_F(j1939_multi, etp_tx_to_raw)
+{
+	unsigned int num_pkts = J1939_NUM_PKTS(ETP_SIZE);
+	static uint8_t payload[ETP_SIZE];
+	static uint8_t rx_buf[ETP_SIZE];
+	uint8_t dat[CAN_MAX_DLEN];
+	struct can_frame frame;
+	unsigned int got = 0;
+
+	fill_pattern(payload, sizeof(payload));
+	memset(rx_buf, 0, sizeof(rx_buf));
+
+	ASSERT_TRUE(etp_tx_start_session_ok(self, payload, sizeof(payload),
+					    &frame));
+	ASSERT_TRUE(errqueue_enable_ack_ok(self->j1939));
+
+	EXPECT_EQ(get_le32(&frame.data[ETP_RTS_SIZE_OFF]), ETP_SIZE);
+
+	while (got < num_pkts) {
+		unsigned int cts_pkts;
+
+		cts_pkts = num_pkts - got;
+		if (cts_pkts > ETP_CTS_MAX_PKTS)
+			cts_pkts = ETP_CTS_MAX_PKTS;
+
+		ASSERT_TRUE(etp_tx_serve_block_ok(self, rx_buf, sizeof(rx_buf),
+						  got, cts_pkts))
+			TH_LOG("ETP block after %u/%u packets failed", got,
+			       num_pkts);
+		got += cts_pkts;
+	}
+
+	EXPECT_TRUE(errqueue_empty_ok(self->j1939))
+		TH_LOG("error-queue entry or socket error before the EOMA");
+
+	cm_dat_init(dat, ETP_CMD_EOMA);
+	put_le32(&dat[ETP_EOMA_SIZE_OFF], ETP_SIZE);
+	ASSERT_TRUE(peer_send_cm_ok(self->raw, ETP_CM, dat));
+
+	EXPECT_EQ(memcmp(payload, rx_buf, sizeof(payload)), 0);
+	EXPECT_TRUE(errqueue_read_ack_ok(self->j1939))
+		TH_LOG("no TX-completion ACK after the EOMA");
+}
+
+int main(int argc, char **argv)
+{
+	return j1939_test_main(argc, argv, J1939_NEEDS_RAW);
+}
diff --git a/tools/testing/selftests/net/can/test_j1939_multi.sh b/tools/testing/selftests/net/can/test_j1939_multi.sh
new file mode 100755
index 000000000000..61f65365ec56
--- /dev/null
+++ b/tools/testing/selftests/net/can/test_j1939_multi.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+
+source "$(dirname "$0")/j1939_lib.sh"
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH net-next 08/23] selftests: can: cover J1939 transport abort and timeout paths
  2026-12-02 23:04 [PATCH net-next 0/23] pull-request: can-next 2026-12-03 Marc Kleine-Budde
                   ` (6 preceding siblings ...)
  2026-12-02 23:04 ` [PATCH net-next 07/23] selftests: can: add J1939 TP/ETP multi-frame " Marc Kleine-Budde
@ 2026-12-02 23:04 ` Marc Kleine-Budde
  2026-12-02 23:04 ` [PATCH net-next 09/23] selftests: can: check SO_J1939_PROMISC receive effect Marc Kleine-Budde
                   ` (14 subsequent siblings)
  22 siblings, 0 replies; 27+ messages in thread
From: Marc Kleine-Budde @ 2026-12-02 23:04 UTC (permalink / raw)
  To: netdev; +Cc: davem, kuba, linux-can, kernel, Oleksij Rempel, Marc Kleine-Budde

From: Oleksij Rempel <o.rempel@pengutronix.de>

Add transport edge cases to the multi-frame tests. The round-trip tests
only run transfers that succeed, and no TP transfer there is split into
CTS blocks. They leave out these cases:

- a CTS that asks for fewer packets than the message has
- the T3 timeout, when no CTS follows the RTS
- the T2 timeout, when no DT follows the CTS
- an Abort from the peer

The timeouts must end in a Connection Abort. The Abort from the peer must
cancel an incoming session.

Signed-off-by: Oleksij Rempel <o.rempel@pengutronix.de>
Link: https://patch.msgid.link/20261130-j1939-selftests-v7-8-2491693ccb8d@pengutronix.de
[mkl: switch to static_assert()]
Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
---
 .../testing/selftests/net/can/j1939_helpers.h |   7 +-
 .../selftests/net/can/test_j1939_multi.c      | 271 +++++++++++++++++-
 2 files changed, 276 insertions(+), 2 deletions(-)

diff --git a/tools/testing/selftests/net/can/j1939_helpers.h b/tools/testing/selftests/net/can/j1939_helpers.h
index 7f8004f02c3b..8ce10c445a1c 100644
--- a/tools/testing/selftests/net/can/j1939_helpers.h
+++ b/tools/testing/selftests/net/can/j1939_helpers.h
@@ -12,7 +12,12 @@
  *
  * Timing modes: timer checks use relaxed bounds by default, so that slow
  * machines such as QEMU in CI pass. Set J1939_STRICT_TIMING in the
- * environment (any value) for tight bounds on a real machine.
+ * environment (any value) for tight bounds on a real machine:
+ *
+ *	J1939_STRICT_TIMING=1 ./test_j1939_multi.sh
+ *
+ * Where a bound differs between the modes, the check picks it with
+ * j1939_timing_ms().
  */
 #ifndef __SELFTESTS_NET_CAN_J1939_HELPERS_H__
 #define __SELFTESTS_NET_CAN_J1939_HELPERS_H__
diff --git a/tools/testing/selftests/net/can/test_j1939_multi.c b/tools/testing/selftests/net/can/test_j1939_multi.c
index 410e602a475c..ad1085472cbb 100644
--- a/tools/testing/selftests/net/can/test_j1939_multi.c
+++ b/tools/testing/selftests/net/can/test_j1939_multi.c
@@ -5,7 +5,8 @@
  * A CAN_RAW socket plays the transport peer against the kernel J1939 stack,
  * in both directions. It takes the other side of the RTS/CTS/DT/EOMA
  * exchange, for TP with a short message and for ETP with a payload that
- * spans several CTS blocks (DPO windows).
+ * spans several CTS blocks (DPO windows). The tests also cover the TP CTS
+ * block limit and the TP abort and timeout paths.
  *
  * Known stack race: the stack updates a session from the loopback echo of
  * its own TP and ETP frames. A CAN_RAW peer on the same vcan can read
@@ -58,6 +59,7 @@ static_assert(!J1939_IS_PDU1(PGN_DATA) && PGN_DATA <= J1939_PGN_MAX,
 #define TP_CMD_RTS		0x10
 #define TP_CMD_CTS		0x11
 #define TP_CMD_EOMA		0x13
+#define TP_CMD_ABORT		0xff
 
 #define ETP_CMD_RTS		0x14
 #define ETP_CMD_CTS		0x15
@@ -72,6 +74,7 @@ static_assert(!J1939_IS_PDU1(PGN_DATA) && PGN_DATA <= J1939_PGN_MAX,
 #define TP_CTS_NEXT_OFF		2
 #define TP_EOMA_SIZE_OFF	1	/* le16 */
 #define TP_EOMA_PKTS_OFF	3
+#define TP_ABORT_REASON_OFF	1
 
 /* TP.CM_RTS max packets per CTS: no limit (SAE J1939-21:2001 section 5.10.3) */
 #define TP_RTS_NO_LIMIT		0xff
@@ -118,6 +121,67 @@ static_assert(J1939_NUM_PKTS(ETP_SIZE) % ETP_CTS_MAX_PKTS != 0,
 #define TP_CTS_ALL		J1939_NUM_PKTS(TP_SIZE)
 static_assert(TP_CTS_ALL <= UINT8_MAX, "the TP.CM packet counts are one byte");
 
+/*
+ * arbitrary limit on packets per CTS, sent in the RTS, below the packet
+ * count of TP_SIZE
+ */
+#define TP_CTS_LIMIT		3U
+static_assert(J1939_NUM_PKTS(TP_SIZE) > TP_CTS_LIMIT,
+	      "TP_SIZE must need more packets than TP_CTS_LIMIT");
+static_assert(J1939_NUM_PKTS(TP_SIZE) % TP_CTS_LIMIT != 0,
+	      "the last TP CTS window must be partial");
+
+/*
+ * Connection Abort reasons (SAE J1939-21:2001 Table 6); the kernel names them
+ * J1939_XTP_ABORT_*.
+ */
+#define ABORT_REASON_BUSY	1
+#define ABORT_REASON_TIMEOUT	3
+
+/*
+ * TP responder T2: wait for the next DT after CTS (SAE J1939-21:2001
+ * section 5.10.2.4 and Figure C1).
+ */
+#define TP_T2_MS		1250
+/*
+ * TP originator T3: wait for a CTS after RTS (SAE J1939-21:2001 section
+ * 5.10.2.4 and Figure C1).
+ */
+#define TP_T3_MS		1250
+
+/*
+ * Bounds for the time from before the test opens its socket to the kernel's
+ * abort.
+ * The values below are guesses, not spec values.
+ */
+
+/* relaxed (default, for slow VMs): catches a timer that fires early or never */
+#define TP_RELAXED_EARLY_MS	450
+#define TP_RELAXED_LATE_MS	1250
+#define TP_RELAXED_MIN_MS(t)	((t) - TP_RELAXED_EARLY_MS)
+#define TP_RELAXED_MAX_MS(t)	((t) + TP_RELAXED_LATE_MS)
+
+/* strict: also catches a doubled timer */
+#define TP_STRICT_EARLY_MS	100
+#define TP_STRICT_LATE_MS	200
+#define TP_STRICT_MIN_MS(t)	((t) - TP_STRICT_EARLY_MS)
+#define TP_STRICT_MAX_MS(t)	((t) + TP_STRICT_LATE_MS)
+
+/* for any timer: the relaxed bounds must contain the strict bounds */
+static_assert(TP_RELAXED_EARLY_MS >= TP_STRICT_EARLY_MS,
+	      "the relaxed minimum must not be above the strict one");
+static_assert(TP_RELAXED_LATE_MS >= TP_STRICT_LATE_MS,
+	      "the relaxed maximum must not be below the strict one");
+static_assert(TP_T2_MS > TP_RELAXED_EARLY_MS,
+	      "TP_T2_MS must exceed TP_RELAXED_EARLY_MS");
+static_assert(TP_T3_MS > TP_RELAXED_EARLY_MS,
+	      "TP_T3_MS must exceed TP_RELAXED_EARLY_MS");
+/* so that strict mode catches a doubled T2 or T3 */
+static_assert(TP_STRICT_LATE_MS < TP_T2_MS,
+	      "TP_STRICT_LATE_MS must stay below TP_T2_MS");
+static_assert(TP_STRICT_LATE_MS < TP_T3_MS,
+	      "TP_STRICT_LATE_MS must stay below TP_T3_MS");
+
 FIXTURE(j1939_multi)
 {
 	int ifindex;
@@ -567,6 +631,116 @@ TEST_F(j1939_multi, tp_tx_to_raw)
 		TH_LOG("no TX-completion ACK after the EOMA");
 }
 
+/*
+ * TP RX, per-CTS block limit: the RTS asks for at most TP_CTS_LIMIT packets
+ * per CTS, fewer than the message has. Each CTS from the kernel must ask
+ * for TP_CTS_LIMIT packets, or for the rest.
+ */
+TEST_F(j1939_multi, tp_rx_cts_block_limit)
+{
+	struct can_frame frame;
+
+	ASSERT_TRUE(tp_rx_roundtrip_ok(self, TP_CTS_LIMIT, &frame))
+		TH_LOG("TP RX round-trip against the raw peer failed");
+
+	/* frame is the kernel's EOMA */
+	EXPECT_EQ(get_le16(&frame.data[TP_EOMA_SIZE_OFF]), TP_SIZE);
+	EXPECT_EQ(frame.data[TP_EOMA_PKTS_OFF], J1939_NUM_PKTS(TP_SIZE));
+}
+
+/* Set *min_ms and *max_ms to the abort bounds of a TP timer of timer_ms. */
+static void tp_abort_window(int timer_ms, int *min_ms, int *max_ms)
+{
+	*min_ms = j1939_timing_ms(TP_RELAXED_MIN_MS(timer_ms),
+				  TP_STRICT_MIN_MS(timer_ms));
+	*max_ms = j1939_timing_ms(TP_RELAXED_MAX_MS(timer_ms),
+				  TP_STRICT_MAX_MS(timer_ms));
+}
+
+/*
+ * Wait until max_ms after t0 for the kernel's Connection Abort to the peer
+ * and store it in *frame; *elapsed_ms gets the time from t0 to its arrival.
+ */
+static bool recv_abort_timed_ok(int raw, const struct timespec *t0, int max_ms,
+				struct can_frame *frame, long *elapsed_ms)
+{
+	struct timespec now;
+	bool ok;
+
+	clock_gettime(CLOCK_MONOTONIC, &now);
+	*elapsed_ms = timespec_diff_ms(t0, &now);
+	if (*elapsed_ms > max_ms)
+		return false;
+
+	ok = recv_kernel_cm_ok(raw, TP_CM, TP_CMD_ABORT, frame,
+			       max_ms - *elapsed_ms);
+	clock_gettime(CLOCK_MONOTONIC, &now);
+	*elapsed_ms = timespec_diff_ms(t0, &now);
+	return ok;
+}
+
+/*
+ * Wait for an error on s and return it (SO_ERROR), or 0 if none came within
+ * J1939_RECV_TIMEOUT_MS.
+ */
+static int sock_wait_error(int s)
+{
+	struct pollfd pfd = { .fd = s };
+	socklen_t len;
+	int err;
+
+	if (poll(&pfd, 1, J1939_RECV_TIMEOUT_MS) <= 0)
+		return 0;
+	if (!(pfd.revents & POLLERR))
+		return 0;
+
+	len = sizeof(err);
+	if (getsockopt(s, SOL_SOCKET, SO_ERROR, &err, &len))
+		return 0;
+	return err;
+}
+
+/*
+ * TP TX, RTS->CTS timeout: the J1939 socket starts a TP transmit; the raw peer
+ * receives the RTS but never answers with a CTS. The kernel must give up after
+ * T3 (TP_T3_MS), send a Connection Abort and report the error to the sender.
+ *
+ * The kernel starts T3 when it sends the RTS, and starts it again when it
+ * receives its own RTS back from the CAN echo (j1939_xtp_rx_rts() in
+ * net/can/j1939/transport.c). The wait is timed from before the socket is
+ * opened, so a delay in this test cannot make the abort look early.
+ */
+TEST_F(j1939_multi, tp_tx_rts_cts_timeout)
+{
+	uint8_t payload[TP_SIZE];
+	struct can_frame frame;
+	struct timespec t0;
+	int min_ms, max_ms;
+	long elapsed_ms;
+
+	fill_pattern(payload, sizeof(payload));
+	tp_abort_window(TP_T3_MS, &min_ms, &max_ms);
+
+	clock_gettime(CLOCK_MONOTONIC, &t0);
+	ASSERT_TRUE(tp_tx_start_session_ok(self, payload, sizeof(payload),
+					   &frame));
+
+	ASSERT_TRUE(recv_abort_timed_ok(self->raw, &t0, max_ms, &frame,
+					&elapsed_ms))
+		TH_LOG("kernel did not send a Connection Abort within %d ms",
+		       max_ms);
+
+	/* the T3 timer has to run before the abort */
+	ASSERT_GE(elapsed_ms, min_ms)
+		TH_LOG("abort after only %ld ms, expected at least %d ms",
+		       elapsed_ms, min_ms);
+	EXPECT_EQ(frame.data[TP_ABORT_REASON_OFF], ABORT_REASON_TIMEOUT);
+
+	/* j1939_xtp_abort_to_errno() reports a timeout as EHOSTUNREACH */
+	EXPECT_EQ(sock_wait_error(self->j1939), EHOSTUNREACH)
+		TH_LOG("the sender did not see the aborted session");
+}
+
 /*
  * ETP RX: the CAN_RAW peer transmits an ETP message to the J1939 socket.
  * The kernel requests blocks with ETP.CTS; raw answers each with a DPO and
@@ -689,6 +863,101 @@ TEST_F(j1939_multi, etp_tx_to_raw)
 		TH_LOG("no TX-completion ACK after the EOMA");
 }
 
+/* Send a TP.CM_Abort control frame from the peer to the kernel. */
+static bool send_abort_ok(int raw, uint8_t reason)
+{
+	uint8_t dat[CAN_MAX_DLEN];
+
+	cm_dat_init(dat, TP_CMD_ABORT);
+	dat[TP_ABORT_REASON_OFF] = reason;
+	return peer_send_cm_ok(raw, TP_CM, dat);
+}
+
+/*
+ * Open a TP RX j1939 socket, send an RTS that allows all packets in one CTS
+ * and check that the first CTS asks for all of them.
+ */
+static bool tp_rx_start_session_ok(int *j1939, int raw, int ifindex,
+				   struct can_frame *cts)
+{
+	unsigned int sent = 0;
+
+	if (!tp_rx_open_and_send_rts_ok(j1939, raw, ifindex, TP_CTS_ALL))
+		return false;
+
+	if (!recv_kernel_cm_ok(raw, TP_CM, TP_CMD_CTS, cts,
+			       J1939_RECV_TIMEOUT_MS))
+		return false;
+
+	return cts_accept_ok(cts->data[TP_CTS_PKTS_OFF],
+			     cts->data[TP_CTS_NEXT_OFF], sent,
+			     J1939_NUM_PKTS(TP_SIZE), TP_CTS_ALL);
+}
+
+/*
+ * TP RX timeout: the CAN_RAW peer opens a session with RTS but never sends the
+ * data; the kernel's T2 timer must abort the session and emit a TP.CM_Abort.
+ * The kernel starts its receive timer when it gets the RTS
+ * (j1939_xtp_rx_rts()). It starts it again as T2 when it sends the CTS
+ * (j1939_session_tx_cts()) and on the CAN echo of that CTS
+ * (j1939_xtp_rx_cts_one()). The wait is timed from before the socket is
+ * opened.
+ */
+TEST_F(j1939_multi, tp_rx_timeout)
+{
+	struct can_frame frame;
+	struct timespec t0;
+	int min_ms, max_ms;
+	long elapsed_ms;
+
+	tp_abort_window(TP_T2_MS, &min_ms, &max_ms);
+
+	clock_gettime(CLOCK_MONOTONIC, &t0);
+	ASSERT_TRUE(tp_rx_start_session_ok(&self->j1939, self->raw,
+					   self->ifindex, &frame))
+		TH_LOG("failed to open and start the TP rx session");
+
+	ASSERT_TRUE(recv_abort_timed_ok(self->raw, &t0, max_ms, &frame,
+					&elapsed_ms))
+		TH_LOG("kernel did not abort the stalled rx session");
+
+	/* the T2 timer has to run before the abort */
+	ASSERT_GE(elapsed_ms, min_ms)
+		TH_LOG("abort after only %ld ms, expected at least %d ms",
+		       elapsed_ms, min_ms);
+	EXPECT_EQ(frame.data[TP_ABORT_REASON_OFF], ABORT_REASON_TIMEOUT);
+}
+
+/*
+ * TP RX abort: the CAN_RAW peer aborts an open session; the kernel must cancel
+ * it and deliver nothing to the J1939 socket.
+ */
+TEST_F(j1939_multi, tp_rx_abort_from_raw)
+{
+	unsigned int num_pkts = J1939_NUM_PKTS(TP_SIZE);
+	uint8_t payload[TP_SIZE];
+	struct can_frame frame;
+
+	fill_pattern(payload, sizeof(payload));
+
+	ASSERT_TRUE(tp_rx_start_session_ok(&self->j1939, self->raw,
+					   self->ifindex, &frame))
+		TH_LOG("failed to open and start the TP rx session");
+
+	ASSERT_TRUE(send_abort_ok(self->raw, ABORT_REASON_BUSY));
+
+	/*
+	 * Send all DT frames anyway. A kernel that ignored the abort would
+	 * deliver the message.
+	 */
+	ASSERT_TRUE(send_tp_dt_burst_ok(self->raw, SA_LOCAL, SA_PEER,
+					TP_FIRST_PKT, num_pkts, payload,
+					sizeof(payload)));
+
+	EXPECT_TRUE(recv_none_ok(self->j1939))
+		TH_LOG("socket delivered data despite the abort");
+}
+
 int main(int argc, char **argv)
 {
 	return j1939_test_main(argc, argv, J1939_NEEDS_RAW);
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH net-next 09/23] selftests: can: check SO_J1939_PROMISC receive effect
  2026-12-02 23:04 [PATCH net-next 0/23] pull-request: can-next 2026-12-03 Marc Kleine-Budde
                   ` (7 preceding siblings ...)
  2026-12-02 23:04 ` [PATCH net-next 08/23] selftests: can: cover J1939 transport abort and timeout paths Marc Kleine-Budde
@ 2026-12-02 23:04 ` Marc Kleine-Budde
  2026-12-02 23:04 ` [PATCH net-next 10/23] can: peak_usb: fix missing CAN_ERR_FLAG when reporting error counters Marc Kleine-Budde
                   ` (13 subsequent siblings)
  22 siblings, 0 replies; 27+ messages in thread
From: Marc Kleine-Budde @ 2026-12-02 23:04 UTC (permalink / raw)
  To: netdev; +Cc: davem, kuba, linux-can, kernel, Oleksij Rempel, Marc Kleine-Budde

From: Oleksij Rempel <o.rempel@pengutronix.de>

Add a test that SO_J1939_PROMISC changes what the RX path delivers. The
existing coverage only round-trips the flag through set/getsockopt, so a
kernel that stores the flag but never acts on it still passes.

The test uses one probe per filter. One probe goes to a different
address from the bound one. The other has a different PGN. The test
sends the probes three times: before the flag is set, while the flag is
set, and after the flag is cleared. The probes must arrive only while
the flag is set. After the flag is cleared, the test also sends a frame
for the bound address and PGN. That frame must arrive.

Signed-off-by: Oleksij Rempel <o.rempel@pengutronix.de>
Link: https://patch.msgid.link/20261130-j1939-selftests-v7-9-2491693ccb8d@pengutronix.de
[mkl: switch to static_assert()]
Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
---
 .../selftests/net/can/test_j1939_opts.c       | 138 +++++++++++++++++-
 1 file changed, 136 insertions(+), 2 deletions(-)

diff --git a/tools/testing/selftests/net/can/test_j1939_opts.c b/tools/testing/selftests/net/can/test_j1939_opts.c
index b535acea198c..ab54119ecbd0 100644
--- a/tools/testing/selftests/net/can/test_j1939_opts.c
+++ b/tools/testing/selftests/net/can/test_j1939_opts.c
@@ -6,8 +6,9 @@
  * and addressing: the SO_J1939_FILTER PGN whitelist, the SO_J1939_SEND_PRIO
  * send priority seen in the CAN id (via a CAN_RAW peer, including the kernel's
  * default), unconnected sendto(2), a wrong-family bind rejection,
- * SO_J1939_ERRQUEUE TX-completion notifications, and set/getsockopt
- * round-trips of SO_J1939_SEND_PRIO, SO_J1939_PROMISC and SO_J1939_ERRQUEUE.
+ * SO_J1939_ERRQUEUE TX-completion notifications, the SO_J1939_PROMISC receive
+ * effect, and set/getsockopt round-trips of SO_J1939_SEND_PRIO,
+ * SO_J1939_PROMISC and SO_J1939_ERRQUEUE.
  *
  * Run by test_j1939_opts.sh, see j1939_tests.h.
  */
@@ -18,6 +19,10 @@
 /* arbitrary addresses */
 #define SA_TX			0x80
 #define SA_RX			0x90
+#define SA_OTHER		0x50	/* neither SA_TX nor SA_RX */
+static_assert(SA_OTHER != SA_TX && SA_OTHER != SA_RX &&
+	      SA_OTHER <= J1939_MAX_UNICAST_ADDR,
+	      "SA_OTHER must be a third unicast address");
 static_assert(SA_TX != SA_RX && SA_TX <= J1939_MAX_UNICAST_ADDR &&
 	      SA_RX <= J1939_MAX_UNICAST_ADDR,
 	      "SA_TX and SA_RX must be two different unicast addresses");
@@ -172,6 +177,135 @@ TEST_F(j1939_opts, filter_pgn)
 		TH_LOG("rx got another frame or an error after PGN_A");
 }
 
+/*
+ * rx binds to (PROMISC_BOUND_DA, PROMISC_BOUND_PGN). Without SO_J1939_PROMISC
+ * it must not get the probes below. Each probe differs from the binding only
+ * in the address or only in the PGN, so each filter is tested on its own.
+ */
+#define PROMISC_BOUND_DA	SA_RX
+#define PROMISC_BOUND_PGN	PGN_A
+#define PROMISC_OTHER_DA	SA_OTHER
+#define PROMISC_OTHER_PGN	PGN_B
+static_assert((PROMISC_OTHER_DA != PROMISC_BOUND_DA) &&
+	      (PROMISC_OTHER_PGN != PROMISC_BOUND_PGN),
+	      "each probe must differ from the binding");
+static_assert(J1939_IS_PDU1(PROMISC_BOUND_PGN) &&
+	      PROMISC_BOUND_DA <= J1939_MAX_UNICAST_ADDR,
+	      "the binding must be a unicast address and a PDU1 PGN");
+static_assert(J1939_IS_PDU1(PROMISC_OTHER_PGN) &&
+	      PROMISC_OTHER_DA <= J1939_MAX_UNICAST_ADDR,
+	      "the probes must use a unicast address and a PDU1 PGN");
+
+enum { PROBE_OTHER_PGN, PROBE_OTHER_DA, PROBE_NUM };
+
+static const struct {
+	uint8_t da;
+	pgn_t pgn;
+} promisc_probes[] = {
+	[PROBE_OTHER_PGN] = { PROMISC_BOUND_DA, PROMISC_OTHER_PGN },
+	[PROBE_OTHER_DA] = { PROMISC_OTHER_DA, PROMISC_BOUND_PGN },
+};
+
+static_assert(ARRAY_SIZE(promisc_probes) == PROBE_NUM,
+	      "promisc_probes needs one row per probe");
+
+/*
+ * Send every probe from tx and check that rx gets none of them. Keep
+ * sending after a probe arrives, so each filter is checked on its own.
+ * Return false if rx gets a probe or reports an error. Also return false
+ * at once if a probe cannot be sent.
+ */
+static bool no_probe_received_ok(FIXTURE_DATA(j1939_opts) *self,
+				 const uint8_t *buf, size_t len)
+{
+	bool ok = true;
+	size_t i;
+
+	for (i = 0; i < ARRAY_SIZE(promisc_probes); i++) {
+		if (!j1939_sendto_ok(self->tx, buf, len, self->ifindex,
+				     J1939_NO_NAME, promisc_probes[i].da,
+				     promisc_probes[i].pgn)) {
+			fprintf(stderr, "# sendto probe %zu failed: %d\n", i,
+				errno);
+			return false;
+		}
+		if (!recv_none_ok(self->rx)) {
+			fprintf(stderr, "# rx got probe %zu or an error\n", i);
+			ok = false;
+		}
+	}
+	return ok;
+}
+
+/* SO_J1939_PROMISC delivers frames that do not match the bound (addr, pgn). */
+TEST_F(j1939_opts, promisc_receive)
+{
+	const pgn_t bound_pgn = PROMISC_BOUND_PGN;
+	struct sockaddr_can match_src = {};
+	uint8_t match_buf[CAN_MAX_DLEN];
+	uint8_t tx_buf[CAN_MAX_DLEN];
+	size_t i;
+
+	fill_pattern(tx_buf, sizeof(tx_buf));
+	memcpy(match_buf, tx_buf, sizeof(match_buf));
+	match_buf[0] ^= UINT8_MAX;
+
+	self->rx = j1939_open(self->ifindex, PROMISC_BOUND_DA,
+			      PROMISC_BOUND_PGN);
+	ASSERT_GE(self->rx, 0);
+	self->tx = j1939_open(self->ifindex, SA_TX, J1939_NO_PGN);
+	ASSERT_GE(self->tx, 0);
+
+	EXPECT_TRUE(no_probe_received_ok(self, tx_buf, sizeof(tx_buf)))
+		TH_LOG("probe check without promisc failed");
+
+	ASSERT_TRUE(j1939_set_flag_ok(self->rx, SO_J1939_PROMISC, 1))
+		TH_LOG("setting SO_J1939_PROMISC failed: %d", errno);
+
+	for (i = 0; i < ARRAY_SIZE(promisc_probes); i++) {
+		struct sockaddr_can src = {};
+		bool got;
+
+		ASSERT_TRUE(j1939_sendto_ok(self->tx, tx_buf, sizeof(tx_buf),
+					    self->ifindex, J1939_NO_NAME,
+					    promisc_probes[i].da,
+					    promisc_probes[i].pgn))
+			TH_LOG("sendto probe %zu failed: %d", i, errno);
+		got = recvfrom_verify_ok(self->rx, tx_buf, sizeof(tx_buf),
+					 J1939_RECV_TIMEOUT_MS, &src);
+		EXPECT_TRUE(got)
+			TH_LOG("probe %zu not received despite promisc", i);
+		if (!got)
+			continue;
+
+		/* the probes carry the same payload, so check which one came */
+		EXPECT_EQ(src.can_addr.j1939.pgn, promisc_probes[i].pgn)
+			TH_LOG("probe %zu came with PGN 0x%05x", i,
+			       src.can_addr.j1939.pgn);
+	}
+
+	/* with promisc cleared, the bound (addr, pgn) filters again */
+	ASSERT_TRUE(j1939_set_flag_ok(self->rx, SO_J1939_PROMISC, 0))
+		TH_LOG("clearing SO_J1939_PROMISC failed: %d", errno);
+	EXPECT_TRUE(no_probe_received_ok(self, tx_buf, sizeof(tx_buf)))
+		TH_LOG("probe check after clearing promisc failed");
+
+	/*
+	 * Send a frame for the bound address and PGN. It must still
+	 * arrive. A socket that receives nothing would pass the probe
+	 * check after clearing, too. The frame has its own payload, so a
+	 * late probe cannot be mistaken for it.
+	 */
+	ASSERT_TRUE(j1939_sendto_ok(self->tx, match_buf, sizeof(match_buf),
+				    self->ifindex, J1939_NO_NAME,
+				    PROMISC_BOUND_DA, PROMISC_BOUND_PGN))
+		TH_LOG("sendto of the matching frame failed: %d", errno);
+	ASSERT_TRUE(recvfrom_verify_ok(self->rx, match_buf, sizeof(match_buf),
+				       J1939_RECV_TIMEOUT_MS, &match_src))
+		TH_LOG("no matching frame after promisc was cleared");
+	EXPECT_EQ(match_src.can_addr.j1939.pgn, bound_pgn);
+}
+
 /* Without SO_J1939_SEND_PRIO the kernel's default priority is used. */
 TEST_F(j1939_opts, send_prio_default)
 {
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH net-next 10/23] can: peak_usb: fix missing CAN_ERR_FLAG when reporting error counters
  2026-12-02 23:04 [PATCH net-next 0/23] pull-request: can-next 2026-12-03 Marc Kleine-Budde
                   ` (8 preceding siblings ...)
  2026-12-02 23:04 ` [PATCH net-next 09/23] selftests: can: check SO_J1939_PROMISC receive effect Marc Kleine-Budde
@ 2026-12-02 23:04 ` Marc Kleine-Budde
  2026-12-02 23:04 ` [PATCH net-next 11/23] can: peak_usb: harden PCAN-USB message validation Marc Kleine-Budde
                   ` (12 subsequent siblings)
  22 siblings, 0 replies; 27+ messages in thread
From: Marc Kleine-Budde @ 2026-12-02 23:04 UTC (permalink / raw)
  To: netdev
  Cc: davem, kuba, linux-can, kernel, Stefan Günther, stable,
	Stéphane Grosjean, Marc Kleine-Budde

From: Stefan Günther <stefangun@pm.me>

When the device reports error counters, the driver incorrectly uses an
assignment (=) instead of a bitwise OR (|=) for CAN_ERR_CNT. This wipes
out the CAN_ERR_FLAG and CAN_ERR_CRTL flags, causing the error frame to
be sent to userspace as a regular CAN frame with ID 0x200.

Fix this by using a bitwise OR to preserve the flags.

Signed-off-by: Stefan Günther <stefangun@pm.me>
Cc: stable@vger.kernel.org
Fixes: 3e5c291c7942 ("can: add CAN_ERR_CNT flag to notify availability of error counter")
Signed-off-by: Stéphane Grosjean <s.grosjean@peak-system.fr>
Link: https://patch.msgid.link/20261126-canfd_check_channel_idx-v9-1-abe0099b4585@peak-system.fr
Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
---
 drivers/net/can/usb/peak_usb/pcan_usb.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/drivers/net/can/usb/peak_usb/pcan_usb.c b/drivers/net/can/usb/peak_usb/pcan_usb.c
index 8fd058c32856..785224e00c4e 100644
--- a/drivers/net/can/usb/peak_usb/pcan_usb.c
+++ b/drivers/net/can/usb/peak_usb/pcan_usb.c
@@ -526,7 +526,7 @@ static int pcan_usb_decode_error(struct pcan_usb_msg_context *mc, u8 n,
 			/* Supply TX/RX error counters in case of
 			 * controller error.
 			 */
-			cf->can_id = CAN_ERR_CNT;
+			cf->can_id |= CAN_ERR_CNT;
 			cf->data[6] = mc->pdev->bec.txerr;
 			cf->data[7] = mc->pdev->bec.rxerr;
 		}
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH net-next 11/23] can: peak_usb: harden PCAN-USB message validation
  2026-12-02 23:04 [PATCH net-next 0/23] pull-request: can-next 2026-12-03 Marc Kleine-Budde
                   ` (9 preceding siblings ...)
  2026-12-02 23:04 ` [PATCH net-next 10/23] can: peak_usb: fix missing CAN_ERR_FLAG when reporting error counters Marc Kleine-Budde
@ 2026-12-02 23:04 ` Marc Kleine-Budde
  2026-12-02 23:04 ` [PATCH net-next 12/23] can: peak_usb: replace open-coded bitmask operations with bitops Marc Kleine-Budde
                   ` (11 subsequent siblings)
  22 siblings, 0 replies; 27+ messages in thread
From: Marc Kleine-Budde @ 2026-12-02 23:04 UTC (permalink / raw)
  To: netdev
  Cc: davem, kuba, linux-can, kernel, Stéphane Grosjean, stable,
	Marc Kleine-Budde

From: Stéphane Grosjean <s.grosjean@peak-system.fr>

Add boundary checks when parsing PCAN-USB messages and reject
malformed buffers whose contents would otherwise lead to accesses
outside the received USB data area.

This prevents potential out-of-bounds memory accesses caused by
corrupted or malicious device messages.

Fixes: 46be265d3388 ("can: usb: PEAK-System Technik PCAN-USB specific part")
Cc: stable@vger.kernel.org
Signed-off-by: Stéphane Grosjean <s.grosjean@peak-system.fr>
Link: https://patch.msgid.link/20261126-canfd_check_channel_idx-v9-2-abe0099b4585@peak-system.fr
Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
---
 drivers/net/can/usb/peak_usb/pcan_usb.c | 26 +++++++++++++++++--------
 1 file changed, 18 insertions(+), 8 deletions(-)

diff --git a/drivers/net/can/usb/peak_usb/pcan_usb.c b/drivers/net/can/usb/peak_usb/pcan_usb.c
index 785224e00c4e..f79b651ab4a7 100644
--- a/drivers/net/can/usb/peak_usb/pcan_usb.c
+++ b/drivers/net/can/usb/peak_usb/pcan_usb.c
@@ -558,6 +558,8 @@ static int pcan_usb_handle_bus_evt(struct pcan_usb_msg_context *mc, u8 ir)
 	switch (ir) {
 	case PCAN_USB_ERR_CNT_DEC:
 	case PCAN_USB_ERR_CNT_INC:
+		if ((mc->ptr + 3) > mc->end)
+			return -EINVAL;
 
 		/* save rx/tx error counters from in the device context */
 		pdev->bec.rxerr = mc->ptr[1];
@@ -696,8 +698,11 @@ static int pcan_usb_decode_data(struct pcan_usb_msg_context *mc, u8 status_len)
 		mc->ptr += rec_len;
 
 		/* Ignore next byte (client private id) if SRR bit is set */
-		if (can_id_flags & PCAN_USB_TX_SRR)
+		if (can_id_flags & PCAN_USB_TX_SRR) {
+			if ((mc->ptr + 1) > mc->end)
+				goto decode_failed;
 			mc->ptr++;
+		}
 
 		/* update statistics */
 		mc->netdev->stats.rx_bytes += cf->len;
@@ -733,14 +738,19 @@ static int pcan_usb_decode_msg(struct peak_usb_device *dev, u8 *ibuf, u32 lbuf)
 	int err;
 
 	for (err = 0; mc.rec_idx < mc.rec_cnt && !err; mc.rec_idx++) {
-		u8 sl = *mc.ptr++;
-
-		/* handle status and error frames here */
-		if (sl & PCAN_USB_STATUSLEN_INTERNAL) {
-			err = pcan_usb_decode_status(&mc, sl);
-		/* handle normal can frames here */
+		/* check if status_len byte can be read next */
+		if (mc.ptr >= mc.end) {
+			err = -EINVAL;
 		} else {
-			err = pcan_usb_decode_data(&mc, sl);
+			u8 sl = *mc.ptr++;
+
+			/* handle status and error frames here */
+			if (sl & PCAN_USB_STATUSLEN_INTERNAL) {
+				err = pcan_usb_decode_status(&mc, sl);
+			/* handle normal can frames here */
+			} else {
+				err = pcan_usb_decode_data(&mc, sl);
+			}
 		}
 	}
 
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH net-next 12/23] can: peak_usb: replace open-coded bitmask operations with bitops
  2026-12-02 23:04 [PATCH net-next 0/23] pull-request: can-next 2026-12-03 Marc Kleine-Budde
                   ` (10 preceding siblings ...)
  2026-12-02 23:04 ` [PATCH net-next 11/23] can: peak_usb: harden PCAN-USB message validation Marc Kleine-Budde
@ 2026-12-02 23:04 ` Marc Kleine-Budde
  2026-12-02 23:04 ` [PATCH net-next 13/23] can: peak_usb: harden channel handling in PCAN-USB FD Marc Kleine-Budde
                   ` (10 subsequent siblings)
  22 siblings, 0 replies; 27+ messages in thread
From: Marc Kleine-Budde @ 2026-12-02 23:04 UTC (permalink / raw)
  To: netdev
  Cc: davem, kuba, linux-can, kernel, Stéphane Grosjean,
	Marc Kleine-Budde

From: Stéphane Grosjean <s.grosjean@peak-system.fr>

The PCAN_USB_STATE_* flags of struct peak_usb_device are set, cleared
and tested from different contexts (ndo_open/ndo_stop, USB disconnect,
URB completion) with non-atomic open-coded bitmask operations.

Turn these flags into bit numbers, make the state field an unsigned
long and use set_bit(), clear_bit() and test_bit() instead, so that
updating one flag can no longer overwrite a concurrent update of
another one. The next patch relies on this to clear CONNECTED while a
channel may be opened.

dev->state is zeroed by alloc_candev(), so setting CONNECTED with
set_bit() at creation is equivalent to the former assignment.

Signed-off-by: Stéphane Grosjean <s.grosjean@peak-system.fr>
Link: https://patch.msgid.link/20261126-canfd_check_channel_idx-v9-3-abe0099b4585@peak-system.fr
Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
---
 drivers/net/can/usb/peak_usb/pcan_usb.c      |  4 ++--
 drivers/net/can/usb/peak_usb/pcan_usb_core.c | 10 +++++-----
 drivers/net/can/usb/peak_usb/pcan_usb_core.h |  9 ++++++---
 drivers/net/can/usb/peak_usb/pcan_usb_fd.c   |  2 +-
 drivers/net/can/usb/peak_usb/pcan_usb_pro.c  |  6 +++---
 5 files changed, 17 insertions(+), 14 deletions(-)

diff --git a/drivers/net/can/usb/peak_usb/pcan_usb.c b/drivers/net/can/usb/peak_usb/pcan_usb.c
index f79b651ab4a7..76cf042a9f11 100644
--- a/drivers/net/can/usb/peak_usb/pcan_usb.c
+++ b/drivers/net/can/usb/peak_usb/pcan_usb.c
@@ -158,7 +158,7 @@ static int pcan_usb_send_cmd(struct peak_usb_device *dev, u8 f, u8 n, u8 *p)
 	int actual_length;
 
 	/* usb device unregistered? */
-	if (!(dev->state & PCAN_USB_STATE_CONNECTED))
+	if (!test_bit(PCAN_USB_STATE_CONNECTED, &dev->state))
 		return 0;
 
 	dev->cmd_buf[PCAN_USB_CMD_FUNC] = f;
@@ -188,7 +188,7 @@ static int pcan_usb_wait_rsp(struct peak_usb_device *dev, u8 f, u8 n, u8 *p)
 	int actual_length;
 
 	/* usb device unregistered? */
-	if (!(dev->state & PCAN_USB_STATE_CONNECTED))
+	if (!test_bit(PCAN_USB_STATE_CONNECTED, &dev->state))
 		return 0;
 
 	/* first, send command */
diff --git a/drivers/net/can/usb/peak_usb/pcan_usb_core.c b/drivers/net/can/usb/peak_usb/pcan_usb_core.c
index 55aad01cd8ca..a1b17e1e6fea 100644
--- a/drivers/net/can/usb/peak_usb/pcan_usb_core.c
+++ b/drivers/net/can/usb/peak_usb/pcan_usb_core.c
@@ -263,7 +263,7 @@ static void peak_usb_read_bulk_callback(struct urb *urb)
 	/* protect from any incoming empty msgs */
 	if ((urb->actual_length > 0) && (dev->adapter->dev_decode_buf)) {
 		/* handle these kinds of msgs only if _start callback called */
-		if (dev->state & PCAN_USB_STATE_STARTED) {
+		if (test_bit(PCAN_USB_STATE_STARTED, &dev->state)) {
 			err = dev->adapter->dev_decode_buf(dev, urb);
 			if (err)
 				pcan_dump_mem("received usb message",
@@ -537,7 +537,7 @@ static int peak_usb_start(struct peak_usb_device *dev)
 			goto err_adapter;
 	}
 
-	dev->state |= PCAN_USB_STATE_STARTED;
+	set_bit(PCAN_USB_STATE_STARTED, &dev->state);
 
 	/* can set bus on now */
 	if (dev->adapter->dev_set_bus) {
@@ -631,7 +631,7 @@ static int peak_usb_ndo_stop(struct net_device *netdev)
 {
 	struct peak_usb_device *dev = netdev_priv(netdev);
 
-	dev->state &= ~PCAN_USB_STATE_STARTED;
+	clear_bit(PCAN_USB_STATE_STARTED, &dev->state);
 	netif_stop_queue(netdev);
 
 	close_candev(netdev);
@@ -941,7 +941,7 @@ static int peak_usb_create_dev(const struct peak_usb_adapter *peak_usb_adapter,
 	dev->netdev = netdev;
 	dev->adapter = peak_usb_adapter;
 	dev->ctrl_idx = ctrl_idx;
-	dev->state = PCAN_USB_STATE_CONNECTED;
+	set_bit(PCAN_USB_STATE_CONNECTED, &dev->state);
 
 	dev->ep_msg_in = peak_usb_adapter->ep_msg_in;
 	dev->ep_msg_out = peak_usb_adapter->ep_msg_out[ctrl_idx];
@@ -1044,7 +1044,7 @@ static void peak_usb_disconnect(struct usb_interface *intf)
 		char name[IFNAMSIZ];
 
 		dev_prev_siblings = dev->prev_siblings;
-		dev->state &= ~PCAN_USB_STATE_CONNECTED;
+		clear_bit(PCAN_USB_STATE_CONNECTED, &dev->state);
 		strscpy(name, netdev->name, IFNAMSIZ);
 
 		unregister_candev(netdev);
diff --git a/drivers/net/can/usb/peak_usb/pcan_usb_core.h b/drivers/net/can/usb/peak_usb/pcan_usb_core.h
index 65999f04f4b7..234d20f81154 100644
--- a/drivers/net/can/usb/peak_usb/pcan_usb_core.h
+++ b/drivers/net/can/usb/peak_usb/pcan_usb_core.h
@@ -103,15 +103,18 @@ struct peak_tx_urb_context {
 	struct urb *urb;
 };
 
-#define PCAN_USB_STATE_CONNECTED	0x00000001
-#define PCAN_USB_STATE_STARTED		0x00000002
+/* bit numbers for struct peak_usb_device::state (used with set_bit()/
+ * clear_bit()/test_bit() for atomic read-modify-write across contexts)
+ */
+#define PCAN_USB_STATE_CONNECTED	0
+#define PCAN_USB_STATE_STARTED		1
 
 /* PEAK-System USB device */
 struct peak_usb_device {
 	struct can_priv can;
 	const struct peak_usb_adapter *adapter;
 	unsigned int ctrl_idx;
-	u32 state;
+	unsigned long state;
 
 	struct usb_device *udev;
 	struct net_device *netdev;
diff --git a/drivers/net/can/usb/peak_usb/pcan_usb_fd.c b/drivers/net/can/usb/peak_usb/pcan_usb_fd.c
index 39f0740421c3..729d294f71e5 100644
--- a/drivers/net/can/usb/peak_usb/pcan_usb_fd.c
+++ b/drivers/net/can/usb/peak_usb/pcan_usb_fd.c
@@ -202,7 +202,7 @@ static int pcan_usb_fd_send_cmd(struct peak_usb_device *dev, void *cmd_tail)
 	ptrdiff_t cmd_len;
 
 	/* usb device unregistered? */
-	if (!(dev->state & PCAN_USB_STATE_CONNECTED))
+	if (!test_bit(PCAN_USB_STATE_CONNECTED, &dev->state))
 		return 0;
 
 	/* if a packet is not filled completely by commands, the command list
diff --git a/drivers/net/can/usb/peak_usb/pcan_usb_pro.c b/drivers/net/can/usb/peak_usb/pcan_usb_pro.c
index b6be8c19e537..e38aee7834ce 100644
--- a/drivers/net/can/usb/peak_usb/pcan_usb_pro.c
+++ b/drivers/net/can/usb/peak_usb/pcan_usb_pro.c
@@ -210,7 +210,7 @@ static int pcan_usb_pro_send_cmd(struct peak_usb_device *dev,
 	int err;
 
 	/* usb device unregistered? */
-	if (!(dev->state & PCAN_USB_STATE_CONNECTED))
+	if (!test_bit(PCAN_USB_STATE_CONNECTED, &dev->state))
 		return 0;
 
 	err = usb_bulk_msg(dev->udev,
@@ -234,7 +234,7 @@ static int pcan_usb_pro_wait_rsp(struct peak_usb_device *dev,
 	int i, err = 0;
 
 	/* usb device unregistered? */
-	if (!(dev->state & PCAN_USB_STATE_CONNECTED))
+	if (!test_bit(PCAN_USB_STATE_CONNECTED, &dev->state))
 		return 0;
 
 	req_data_type = pum->u.rec_buffer[4];
@@ -318,7 +318,7 @@ int pcan_usb_pro_send_req(struct peak_usb_device *dev, int req_id,
 	unsigned int p;
 
 	/* usb device unregistered? */
-	if (!(dev->state & PCAN_USB_STATE_CONNECTED))
+	if (!test_bit(PCAN_USB_STATE_CONNECTED, &dev->state))
 		return 0;
 
 	req_type = USB_TYPE_VENDOR | USB_RECIP_OTHER;
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH net-next 13/23] can: peak_usb: harden channel handling in PCAN-USB FD
  2026-12-02 23:04 [PATCH net-next 0/23] pull-request: can-next 2026-12-03 Marc Kleine-Budde
                   ` (11 preceding siblings ...)
  2026-12-02 23:04 ` [PATCH net-next 12/23] can: peak_usb: replace open-coded bitmask operations with bitops Marc Kleine-Budde
@ 2026-12-02 23:04 ` Marc Kleine-Budde
  2026-12-02 23:04 ` [PATCH net-next 14/23] can: peak_usb: fix RX cursor desync for self-received RTR frames with SRR Marc Kleine-Budde
                   ` (9 subsequent siblings)
  22 siblings, 0 replies; 27+ messages in thread
From: Marc Kleine-Budde @ 2026-12-02 23:04 UTC (permalink / raw)
  To: netdev
  Cc: davem, kuba, linux-can, kernel, Stéphane Grosjean,
	Marc Kleine-Budde

From: Stéphane Grosjean <s.grosjean@peak-system.fr>

Records received from PCAN-USB FD family devices carry a CAN channel
number used to index the adapter CAN device table usb_if->dev[].

The decoders only checked this number against the size of the table
(2 entries). On single-channel adapters (PCAN-USB FD, PCAN-Chip USB),
dev[1] is never set, so a record for channel 1 led to a NULL pointer
dereference in URB completion context. On two-channel adapters, a
channel slot is also NULL until that channel has been initialized,
while the RX URBs of channel 0 may already be running.

Check the channel number against the number of controllers of the
adapter and reject records for a channel whose slot is empty. Such a
record makes the decoder stop processing the rest of the URB.

When probing a channel fails after its slot has been filled, the channel
is freed but its slot kept pointing to it. Clear the slot in
pcan_usb_fd_free() and, before freeing the channel, stop RX on this
channel and on the sibling channels already created, since the whole
interface is then released anyway. Slots are published with
smp_store_release() and read with READ_ONCE().

Finally, peak_usb_disconnect() now stops RX on all channels before
unregistering any of them: it clears CONNECTED, which makes
peak_usb_ndo_open() fail, then poisons the RX anchors. This matters
when it is called from the probe error path, where the USB core has
not disabled the interface.

CONNECTED is cleared under RTNL, to serialize with peak_usb_ndo_open():
otherwise, an ndo_open() that has already passed the CONNECTED test
may have anchored an RX URB without having submitted it yet, which
makes usb_poison_anchored_urbs() busy-wait until it is submitted.

Fixes: 0a25e1f4f185 ("can: peak_usb: add support for PEAK new CANFD USB adapters")
Signed-off-by: Stéphane Grosjean <s.grosjean@peak-system.fr>
Link: https://patch.msgid.link/20261126-canfd_check_channel_idx-v9-4-abe0099b4585@peak-system.fr
Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
---
 drivers/net/can/usb/peak_usb/pcan_usb_core.c | 39 +++++++++++-
 drivers/net/can/usb/peak_usb/pcan_usb_fd.c   | 62 +++++++++++++++-----
 2 files changed, 84 insertions(+), 17 deletions(-)

diff --git a/drivers/net/can/usb/peak_usb/pcan_usb_core.c b/drivers/net/can/usb/peak_usb/pcan_usb_core.c
index a1b17e1e6fea..f5c39b43b0fa 100644
--- a/drivers/net/can/usb/peak_usb/pcan_usb_core.c
+++ b/drivers/net/can/usb/peak_usb/pcan_usb_core.c
@@ -13,6 +13,7 @@
 #include <linux/init.h>
 #include <linux/module.h>
 #include <linux/netdevice.h>
+#include <linux/rtnetlink.h>
 #include <linux/signal.h>
 #include <linux/slab.h>
 #include <linux/sysfs.h>
@@ -574,6 +575,9 @@ static int peak_usb_ndo_open(struct net_device *netdev)
 	struct peak_usb_device *dev = netdev_priv(netdev);
 	int err;
 
+	if (!test_bit(PCAN_USB_STATE_CONNECTED, &dev->state))
+		return -ENODEV;
+
 	/* common open */
 	err = open_candev(netdev);
 	if (err)
@@ -904,6 +908,29 @@ int pcan_get_ts_info(struct net_device *dev, struct kernel_ethtool_ts_info *info
 	return 0;
 }
 
+/*
+ * stop RX on dev and on all its previous siblings: clearing CONNECTED makes
+ * peak_usb_ndo_open() fail, then poisoning the RX anchors waits for running
+ * completion handlers and makes any later submission on them fail.
+ *
+ * peak_usb_ndo_open() runs under RTNL: clearing CONNECTED under RTNL ensures
+ * that no ndo_open() is in progress (so no RX URB is anchored but not yet
+ * submitted, which usb_poison_anchored_urbs() would busy-wait on) and that
+ * any later one fails.
+ */
+static void peak_usb_stop_rx(struct peak_usb_device *dev)
+{
+	struct peak_usb_device *d;
+
+	rtnl_lock();
+	for (d = dev; d; d = d->prev_siblings)
+		clear_bit(PCAN_USB_STATE_CONNECTED, &d->state);
+	rtnl_unlock();
+
+	for (d = dev; d; d = d->prev_siblings)
+		usb_poison_anchored_urbs(&d->rx_submitted);
+}
+
 /*
  * create one device which is attached to CAN controller #ctrl_idx of the
  * usb adapter.
@@ -1014,6 +1041,13 @@ static int peak_usb_create_dev(const struct peak_usb_adapter *peak_usb_adapter,
 	return 0;
 
 adap_dev_free:
+	/* the whole interface is released when probing a channel fails:
+	 * stop RX on this channel, which may already be open, and on the
+	 * channels already created, since their RX URBs may carry records
+	 * for this one.
+	 */
+	peak_usb_stop_rx(dev);
+
 	if (dev->adapter->dev_free)
 		dev->adapter->dev_free(dev);
 
@@ -1038,13 +1072,14 @@ static void peak_usb_disconnect(struct usb_interface *intf)
 	struct peak_usb_device *dev;
 	struct peak_usb_device *dev_prev_siblings;
 
-	/* unregister as many netdev devices as siblings */
+	/* stop RX on all channels before unregistering and freeing them */
+	peak_usb_stop_rx(usb_get_intfdata(intf));
+
 	for (dev = usb_get_intfdata(intf); dev; dev = dev_prev_siblings) {
 		struct net_device *netdev = dev->netdev;
 		char name[IFNAMSIZ];
 
 		dev_prev_siblings = dev->prev_siblings;
-		clear_bit(PCAN_USB_STATE_CONNECTED, &dev->state);
 		strscpy(name, netdev->name, IFNAMSIZ);
 
 		unregister_candev(netdev);
diff --git a/drivers/net/can/usb/peak_usb/pcan_usb_fd.c b/drivers/net/can/usb/peak_usb/pcan_usb_fd.c
index 729d294f71e5..43c16e743c15 100644
--- a/drivers/net/can/usb/peak_usb/pcan_usb_fd.c
+++ b/drivers/net/can/usb/peak_usb/pcan_usb_fd.c
@@ -60,6 +60,7 @@ struct __packed pcan_ufd_fw_info {
 
 /* handle device specific info used by the netdevices */
 struct pcan_usb_fd_if {
+	const struct peak_usb_adapter *adapter;
 	struct peak_usb_device	*dev[PCAN_USB_MAX_CHANNEL];
 	struct pcan_ufd_fw_info	fw_info;
 	struct peak_time_ref	time_ref;
@@ -536,10 +537,16 @@ static int pcan_usb_fd_decode_canmsg(struct pcan_usb_fd_if *usb_if,
 	struct sk_buff *skb;
 	const u16 rx_msg_flags = le16_to_cpu(rm->flags);
 
-	if (pucan_msg_get_channel(rm) >= ARRAY_SIZE(usb_if->dev))
-		return -ENOMEM;
+	/* Reject invalid channel numbers reported by the firmware */
+	if (pucan_msg_get_channel(rm) >= usb_if->adapter->ctrl_count)
+		return -EINVAL;
+
+	dev = READ_ONCE(usb_if->dev[pucan_msg_get_channel(rm)]);
+
+	/* reject records for a channel that is not (or no longer) set up */
+	if (!dev)
+		return -EINVAL;
 
-	dev = usb_if->dev[pucan_msg_get_channel(rm)];
 	netdev = dev->netdev;
 
 	if (rx_msg_flags & PUCAN_MSG_EXT_DATA_LEN) {
@@ -605,10 +612,16 @@ static int pcan_usb_fd_decode_status(struct pcan_usb_fd_if *usb_if,
 	struct can_frame *cf;
 	struct sk_buff *skb;
 
-	if (pucan_stmsg_get_channel(sm) >= ARRAY_SIZE(usb_if->dev))
-		return -ENOMEM;
+	/* Reject invalid channel numbers reported by the firmware */
+	if (pucan_stmsg_get_channel(sm) >= usb_if->adapter->ctrl_count)
+		return -EINVAL;
+
+	dev = READ_ONCE(usb_if->dev[pucan_stmsg_get_channel(sm)]);
+
+	/* reject records for a channel that is not (or no longer) set up */
+	if (!dev)
+		return -EINVAL;
 
-	dev = usb_if->dev[pucan_stmsg_get_channel(sm)];
 	pdev = container_of(dev, struct pcan_usb_fd_device, dev);
 	netdev = dev->netdev;
 
@@ -662,10 +675,16 @@ static int pcan_usb_fd_decode_error(struct pcan_usb_fd_if *usb_if,
 	struct pcan_usb_fd_device *pdev;
 	struct peak_usb_device *dev;
 
-	if (pucan_ermsg_get_channel(er) >= ARRAY_SIZE(usb_if->dev))
+	/* Reject invalid channel numbers reported by the firmware */
+	if (pucan_ermsg_get_channel(er) >= usb_if->adapter->ctrl_count)
+		return -EINVAL;
+
+	dev = READ_ONCE(usb_if->dev[pucan_ermsg_get_channel(er)]);
+
+	/* reject records for a channel that is not (or no longer) set up */
+	if (!dev)
 		return -EINVAL;
 
-	dev = usb_if->dev[pucan_ermsg_get_channel(er)];
 	pdev = container_of(dev, struct pcan_usb_fd_device, dev);
 
 	/* keep a trace of tx and rx error counters for later use */
@@ -685,10 +704,16 @@ static int pcan_usb_fd_decode_overrun(struct pcan_usb_fd_if *usb_if,
 	struct can_frame *cf;
 	struct sk_buff *skb;
 
-	if (pufd_omsg_get_channel(ov) >= ARRAY_SIZE(usb_if->dev))
+	/* Reject invalid channel numbers reported by the firmware */
+	if (pufd_omsg_get_channel(ov) >= usb_if->adapter->ctrl_count)
+		return -EINVAL;
+
+	dev = READ_ONCE(usb_if->dev[pufd_omsg_get_channel(ov)]);
+
+	/* reject records for a channel that is not (or no longer) set up */
+	if (!dev)
 		return -EINVAL;
 
-	dev = usb_if->dev[pufd_omsg_get_channel(ov)];
 	netdev = dev->netdev;
 
 	/* allocate an skb to store the error frame */
@@ -986,6 +1011,9 @@ static int pcan_usb_fd_init(struct peak_usb_device *dev)
 		if (!pdev->usb_if)
 			goto err_out;
 
+		/* needed by the decoders to check channel numbers */
+		pdev->usb_if->adapter = dev->adapter;
+
 		/* allocate command buffer once for all for the interface */
 		pdev->cmd_buffer_addr = kzalloc(PCAN_UFD_CMD_BUFFER_SIZE,
 						GFP_KERNEL);
@@ -1059,7 +1087,8 @@ static int pcan_usb_fd_init(struct peak_usb_device *dev)
 		fw_info = &pdev->usb_if->fw_info;
 	}
 
-	pdev->usb_if->dev[dev->ctrl_idx] = dev;
+	/* publish dev to the decoders, after the ctrlmode copies above */
+	smp_store_release(&pdev->usb_if->dev[dev->ctrl_idx], dev);
 	dev->can_channel_id =
 		le32_to_cpu(pdev->usb_if->fw_info.dev_id[dev->ctrl_idx]);
 
@@ -1129,14 +1158,17 @@ static void pcan_usb_fd_exit(struct peak_usb_device *dev)
 	}
 }
 
-/* called when the USB adapter is unplugged */
+/* called when the USB adapter is unplugged, or when probing a sibling fails */
 static void pcan_usb_fd_free(struct peak_usb_device *dev)
 {
+	struct pcan_usb_fd_device *pdev =
+		container_of(dev, struct pcan_usb_fd_device, dev);
+
+	/* clear this channel's slot: dev is going to be freed */
+	WRITE_ONCE(pdev->usb_if->dev[dev->ctrl_idx], NULL);
+
 	/* last device: can free shared objects now */
 	if (!dev->prev_siblings && !dev->next_siblings) {
-		struct pcan_usb_fd_device *pdev =
-			container_of(dev, struct pcan_usb_fd_device, dev);
-
 		/* free commands buffer */
 		kfree(pdev->cmd_buffer_addr);
 
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH net-next 14/23] can: peak_usb: fix RX cursor desync for self-received RTR frames with SRR
  2026-12-02 23:04 [PATCH net-next 0/23] pull-request: can-next 2026-12-03 Marc Kleine-Budde
                   ` (12 preceding siblings ...)
  2026-12-02 23:04 ` [PATCH net-next 13/23] can: peak_usb: harden channel handling in PCAN-USB FD Marc Kleine-Budde
@ 2026-12-02 23:04 ` Marc Kleine-Budde
  2026-12-02 23:04 ` [PATCH net-next 15/23] can: peak_usb: reject records for unset channels in PCAN-USB Pro Marc Kleine-Budde
                   ` (8 subsequent siblings)
  22 siblings, 0 replies; 27+ messages in thread
From: Marc Kleine-Budde @ 2026-12-02 23:04 UTC (permalink / raw)
  To: netdev
  Cc: davem, kuba, linux-can, kernel, Stéphane Grosjean, stable,
	Marc Kleine-Budde

From: Stéphane Grosjean <s.grosjean@peak-system.fr>

pcan_usb_encode_msg() appends a one-byte "writer id" whenever
PCAN_USB_TX_SRR is set in can_id_flags, for both RTR and non-RTR
frames: the data block and the SRR writer id byte are two independent,
unconditional steps.

pcan_usb_decode_data() only consumed that extra byte in the non-RTR
branch, inside the same conditional block that reads the CAN data
payload. A self-received RTR frame with the SRR bit set (e.g. a
loopback echo with CAN_CTRLMODE_LOOPBACK) therefore left the RX cursor
one byte short, causing the private id byte to be misparsed as the
next record's status/len byte and the rest of the URB to be misparsed
or rejected.

Move the private id byte skip out of the RTR/non-RTR branch so it is
applied whenever SRR is set, matching the encoder's layout.

Since a frame can now be dropped when this byte is missing, update
rx_bytes together with rx_packets, once the frame has been fully
decoded.

Fixes: 3a7939495ce8 ("can: peak_usb: PCAN-USB: add support of loopback and one-shot mode")
Cc: stable@vger.kernel.org
Signed-off-by: Stéphane Grosjean <s.grosjean@peak-system.fr>
Link: https://patch.msgid.link/20261126-canfd_check_channel_idx-v9-5-abe0099b4585@peak-system.fr
Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
---
 drivers/net/can/usb/peak_usb/pcan_usb.c | 24 ++++++++++++++----------
 1 file changed, 14 insertions(+), 10 deletions(-)

diff --git a/drivers/net/can/usb/peak_usb/pcan_usb.c b/drivers/net/can/usb/peak_usb/pcan_usb.c
index 76cf042a9f11..90f69afcba97 100644
--- a/drivers/net/can/usb/peak_usb/pcan_usb.c
+++ b/drivers/net/can/usb/peak_usb/pcan_usb.c
@@ -655,6 +655,7 @@ static int pcan_usb_decode_data(struct pcan_usb_msg_context *mc, u8 status_len)
 	struct sk_buff *skb;
 	struct can_frame *cf;
 	struct skb_shared_hwtstamps *hwts;
+	u8 rx_bytes = 0;
 	u32 can_id_flags;
 
 	skb = alloc_can_skb(mc->netdev, &cf);
@@ -696,18 +697,21 @@ static int pcan_usb_decode_data(struct pcan_usb_msg_context *mc, u8 status_len)
 
 		memcpy(cf->data, mc->ptr, cf->len);
 		mc->ptr += rec_len;
-
-		/* Ignore next byte (client private id) if SRR bit is set */
-		if (can_id_flags & PCAN_USB_TX_SRR) {
-			if ((mc->ptr + 1) > mc->end)
-				goto decode_failed;
-			mc->ptr++;
-		}
-
-		/* update statistics */
-		mc->netdev->stats.rx_bytes += cf->len;
+		rx_bytes = cf->len;
 	}
+
+	/* Ignore next byte (client private id) if SRR bit is set.
+	 * Note: this test must be done even when the frame is an RTR frame.
+	 */
+	if (can_id_flags & PCAN_USB_TX_SRR) {
+		if ((mc->ptr + 1) > mc->end)
+			goto decode_failed;
+		mc->ptr++;
+	}
+
+	/* update statistics */
 	mc->netdev->stats.rx_packets++;
+	mc->netdev->stats.rx_bytes += rx_bytes;
 
 	/* convert timestamp into kernel time */
 	hwts = skb_hwtstamps(skb);
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH net-next 15/23] can: peak_usb: reject records for unset channels in PCAN-USB Pro
  2026-12-02 23:04 [PATCH net-next 0/23] pull-request: can-next 2026-12-03 Marc Kleine-Budde
                   ` (13 preceding siblings ...)
  2026-12-02 23:04 ` [PATCH net-next 14/23] can: peak_usb: fix RX cursor desync for self-received RTR frames with SRR Marc Kleine-Budde
@ 2026-12-02 23:04 ` Marc Kleine-Budde
  2026-12-02 23:04 ` [PATCH net-next 16/23] can: peak_usb: register the netdevs only once all channels are set up Marc Kleine-Budde
                   ` (7 subsequent siblings)
  22 siblings, 0 replies; 27+ messages in thread
From: Marc Kleine-Budde @ 2026-12-02 23:04 UTC (permalink / raw)
  To: netdev
  Cc: davem, kuba, linux-can, kernel, Stéphane Grosjean,
	Marc Kleine-Budde

From: Stéphane Grosjean <s.grosjean@peak-system.fr>

Records received from a PCAN-USB Pro device carry a CAN channel number
used to index the CAN device table usb_if->dev[]. The decoders only
check this number against the size of the table.

The slot of channel 1 stays NULL until that channel has been
initialized, while the RX URBs of channel 0, which share the same
bulk-in endpoint, may already be running. A record for channel 1
received in that window leads to a NULL pointer dereference in URB
completion context. Moreover, when probing channel 1 fails after its
slot has been filled, the slot keeps pointing to the freed channel.

Reject records for a channel whose slot is empty, and clear the slot
of a channel in pcan_usb_pro_free(). Slots are published with
smp_store_release() and read with READ_ONCE().

Fixes: d8a199355f8f ("can: usb: PEAK-System Technik PCAN-USB Pro specific part")
Signed-off-by: Stéphane Grosjean <s.grosjean@peak-system.fr>
Link: https://patch.msgid.link/20261126-canfd_check_channel_idx-v9-6-abe0099b4585@peak-system.fr
Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
---
 drivers/net/can/usb/peak_usb/pcan_usb_pro.c | 20 +++++++++++++++++---
 1 file changed, 17 insertions(+), 3 deletions(-)

diff --git a/drivers/net/can/usb/peak_usb/pcan_usb_pro.c b/drivers/net/can/usb/peak_usb/pcan_usb_pro.c
index e38aee7834ce..9e2f48683a9d 100644
--- a/drivers/net/can/usb/peak_usb/pcan_usb_pro.c
+++ b/drivers/net/can/usb/peak_usb/pcan_usb_pro.c
@@ -543,7 +543,12 @@ static int pcan_usb_pro_handle_canmsg(struct pcan_usb_pro_interface *usb_if,
 	if (ctrl_idx >= ARRAY_SIZE(usb_if->dev))
 		return -EINVAL;
 
-	dev = usb_if->dev[ctrl_idx];
+	dev = READ_ONCE(usb_if->dev[ctrl_idx]);
+
+	/* reject records for a channel that is not (or no longer) set up */
+	if (!dev)
+		return -EINVAL;
+
 	netdev = dev->netdev;
 
 	skb = alloc_can_skb(netdev, &can_frame);
@@ -590,7 +595,12 @@ static int pcan_usb_pro_handle_error(struct pcan_usb_pro_interface *usb_if,
 	if (ctrl_idx >= ARRAY_SIZE(usb_if->dev))
 		return -EINVAL;
 
-	dev = usb_if->dev[ctrl_idx];
+	dev = READ_ONCE(usb_if->dev[ctrl_idx]);
+
+	/* reject records for a channel that is not (or no longer) set up */
+	if (!dev)
+		return -EINVAL;
+
 	netdev = dev->netdev;
 
 	/* nothing should be sent while in BUS_OFF state */
@@ -933,7 +943,8 @@ static int pcan_usb_pro_init(struct peak_usb_device *dev)
 	}
 
 	pdev->usb_if = usb_if;
-	usb_if->dev[dev->ctrl_idx] = dev;
+	/* publish dev to the decoders */
+	smp_store_release(&usb_if->dev[dev->ctrl_idx], dev);
 
 	/* set LED in default state (end of init phase) */
 	pcan_usb_pro_set_led(dev, PCAN_USBPRO_LED_DEVICE, 1);
@@ -981,6 +992,9 @@ static void pcan_usb_pro_exit(struct peak_usb_device *dev)
  */
 static void pcan_usb_pro_free(struct peak_usb_device *dev)
 {
+	/* clear this channel's slot: dev is going to be freed */
+	WRITE_ONCE(pcan_usb_pro_dev_if(dev)->dev[dev->ctrl_idx], NULL);
+
 	/* last device: can free pcan_usb_pro_interface object now */
 	if (!dev->prev_siblings && !dev->next_siblings)
 		kfree(pcan_usb_pro_dev_if(dev));
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH net-next 16/23] can: peak_usb: register the netdevs only once all channels are set up
  2026-12-02 23:04 [PATCH net-next 0/23] pull-request: can-next 2026-12-03 Marc Kleine-Budde
                   ` (14 preceding siblings ...)
  2026-12-02 23:04 ` [PATCH net-next 15/23] can: peak_usb: reject records for unset channels in PCAN-USB Pro Marc Kleine-Budde
@ 2026-12-02 23:04 ` Marc Kleine-Budde
  2026-12-02 23:04 ` [PATCH net-next 17/23] can: peak_usb: validate the data length of PCAN-USB Pro CAN records Marc Kleine-Budde
                   ` (6 subsequent siblings)
  22 siblings, 0 replies; 27+ messages in thread
From: Marc Kleine-Budde @ 2026-12-02 23:04 UTC (permalink / raw)
  To: netdev
  Cc: davem, kuba, linux-can, kernel, Stéphane Grosjean,
	Marc Kleine-Budde

From: Stéphane Grosjean <s.grosjean@peak-system.fr>

peak_usb_create_dev() registers the netdev of a channel before calling
dev_init(), dev_set_bus() and dev_get_can_channel_id(). Userspace can
therefore open or configure the netdev while the channel is still being
initialized, outside of rtnl_lock():

- peak_usb_ndo_open() may run before dev_init() has set up the adapter
  private data, e.g. pdev->usb_if, which is then dereferenced while
  still NULL by pcan_usb_pro_start() or pcan_usb_fd_start();
- the commands sent by the open or bittiming callbacks may race with
  the ones sent by dev_init() on the same command buffer;
- dev_set_bus(dev, 0) may switch the controller off right after
  peak_usb_ndo_open() has started it.

On multi-channel adapters, the same applies to the channels already
created while a sibling is being initialized, since they share the
interface resources: on PCAN-USB Pro FD and PCAN-USB X6, the command
buffer and the firmware info used by the sibling init, and the
ctrlmode copied from the first channel.

Moreover, if dev_init() or dev_set_bus() fails, the adapter private
data is released before unregister_candev(), which closes the netdev
if it has been opened in the meantime, and then accesses the released
data (interface object and, on the CAN FD adapters, command buffer).

Register the netdevs in peak_usb_probe(), only once all the channels of
the interface have been initialized, and only unregister (and report as
removed) the registered ones in peak_usb_disconnect(). Since no netdev
is registered while the channels are being created, there is no RX to
stop anymore when creating a channel fails. If registering a netdev
fails, peak_usb_disconnect() still stops RX on the channels already
registered, which may have been opened in the meantime. Since the
channel id is now read before the netdev is registered, PCAN-USB reports
a failure to read it with dev_err() instead of netdev_err().

Fixes: bb4785551f64 ("can: usb: PEAK-System Technik USB adapters driver core")
Signed-off-by: Stéphane Grosjean <s.grosjean@peak-system.fr>
Link: https://patch.msgid.link/20261126-canfd_check_channel_idx-v9-7-abe0099b4585@peak-system.fr
Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
---
 drivers/net/can/usb/peak_usb/pcan_usb.c      |  7 +-
 drivers/net/can/usb/peak_usb/pcan_usb_core.c | 72 ++++++++++++--------
 drivers/net/can/usb/peak_usb/pcan_usb_core.h |  1 +
 3 files changed, 49 insertions(+), 31 deletions(-)

diff --git a/drivers/net/can/usb/peak_usb/pcan_usb.c b/drivers/net/can/usb/peak_usb/pcan_usb.c
index 90f69afcba97..451d08421504 100644
--- a/drivers/net/can/usb/peak_usb/pcan_usb.c
+++ b/drivers/net/can/usb/peak_usb/pcan_usb.c
@@ -390,9 +390,12 @@ static int pcan_usb_get_can_channel_id(struct peak_usb_device *dev, u32 *can_ch_
 	int err;
 
 	err = pcan_usb_wait_rsp(dev, PCAN_USB_CMD_DEVID, PCAN_USB_GET, args);
+	/* explicit use of dev_xxx() instead of netdev_xxx() here: this is
+	 * also called during probe, before the netdev is registered.
+	 */
 	if (err)
-		netdev_err(dev->netdev, "getting can channel id failure: %d\n", err);
-
+		dev_err(dev->netdev->dev.parent,
+			"getting can channel id failure: %d\n", err);
 	else
 		*can_ch_id = args[0];
 
diff --git a/drivers/net/can/usb/peak_usb/pcan_usb_core.c b/drivers/net/can/usb/peak_usb/pcan_usb_core.c
index f5c39b43b0fa..e5198ec5c760 100644
--- a/drivers/net/can/usb/peak_usb/pcan_usb_core.c
+++ b/drivers/net/can/usb/peak_usb/pcan_usb_core.c
@@ -1006,15 +1006,6 @@ static int peak_usb_create_dev(const struct peak_usb_adapter *peak_usb_adapter,
 	SET_NETDEV_DEV(netdev, &intf->dev);
 	netdev->dev_id = ctrl_idx;
 
-	err = register_candev(netdev);
-	if (err) {
-		dev_err(&intf->dev, "couldn't register CAN device: %d\n", err);
-		goto lbl_restore_intf_data;
-	}
-
-	if (dev->prev_siblings)
-		(dev->prev_siblings)->next_siblings = dev;
-
 	/* keep hw revision into the netdevice */
 	tmp16 = le16_to_cpu(usb_dev->descriptor.bcdDevice);
 	dev->device_rev = tmp16 >> 8;
@@ -1022,7 +1013,7 @@ static int peak_usb_create_dev(const struct peak_usb_adapter *peak_usb_adapter,
 	if (dev->adapter->dev_init) {
 		err = dev->adapter->dev_init(dev);
 		if (err)
-			goto lbl_unregister_candev;
+			goto lbl_restore_intf_data;
 	}
 
 	/* set bus off */
@@ -1035,25 +1026,15 @@ static int peak_usb_create_dev(const struct peak_usb_adapter *peak_usb_adapter,
 	/* get CAN channel id early */
 	dev->adapter->dev_get_can_channel_id(dev, &dev->can_channel_id);
 
-	netdev_info(netdev, "attached to %s channel %u (device 0x%08X)\n",
-		    peak_usb_adapter->name, ctrl_idx, dev->can_channel_id);
+	if (dev->prev_siblings)
+		(dev->prev_siblings)->next_siblings = dev;
 
 	return 0;
 
 adap_dev_free:
-	/* the whole interface is released when probing a channel fails:
-	 * stop RX on this channel, which may already be open, and on the
-	 * channels already created, since their RX URBs may carry records
-	 * for this one.
-	 */
-	peak_usb_stop_rx(dev);
-
 	if (dev->adapter->dev_free)
 		dev->adapter->dev_free(dev);
 
-lbl_unregister_candev:
-	unregister_candev(netdev);
-
 lbl_restore_intf_data:
 	usb_set_intfdata(intf, dev->prev_siblings);
 	kfree(dev->cmd_buf);
@@ -1078,11 +1059,15 @@ static void peak_usb_disconnect(struct usb_interface *intf)
 	for (dev = usb_get_intfdata(intf); dev; dev = dev_prev_siblings) {
 		struct net_device *netdev = dev->netdev;
 		char name[IFNAMSIZ];
+		bool registered;
 
 		dev_prev_siblings = dev->prev_siblings;
 		strscpy(name, netdev->name, IFNAMSIZ);
 
-		unregister_candev(netdev);
+		/* on probe error, some netdevs may not be registered yet */
+		registered = test_bit(PCAN_USB_STATE_REGISTERED, &dev->state);
+		if (registered)
+			unregister_candev(netdev);
 
 		kfree(dev->cmd_buf);
 		dev->next_siblings = NULL;
@@ -1090,7 +1075,8 @@ static void peak_usb_disconnect(struct usb_interface *intf)
 			dev->adapter->dev_free(dev);
 
 		free_candev(netdev);
-		dev_info(&intf->dev, "%s removed\n", name);
+		if (registered)
+			dev_info(&intf->dev, "%s removed\n", name);
 	}
 
 	usb_set_intfdata(intf, NULL);
@@ -1103,6 +1089,7 @@ static int peak_usb_probe(struct usb_interface *intf,
 			  const struct usb_device_id *id)
 {
 	const struct peak_usb_adapter *peak_usb_adapter;
+	struct peak_usb_device *dev;
 	int i, err = -ENOMEM;
 
 	/* get corresponding PCAN-USB adapter */
@@ -1117,13 +1104,40 @@ static int peak_usb_probe(struct usb_interface *intf,
 
 	for (i = 0; i < peak_usb_adapter->ctrl_count; i++) {
 		err = peak_usb_create_dev(peak_usb_adapter, intf, i);
-		if (err) {
-			/* deregister already created devices */
-			peak_usb_disconnect(intf);
-			break;
-		}
+		if (err)
+			goto lbl_disconnect;
 	}
 
+	/* register the netdevs only once all the channels are set up: the
+	 * channels of an interface share resources (command buffer, firmware
+	 * info, ctrlmode copied from the 1st channel...) that must not be
+	 * used through a netdev while a sibling is being initialized.
+	 */
+	for (dev = usb_get_intfdata(intf); dev->prev_siblings;
+	     dev = dev->prev_siblings)
+		;
+
+	for (; dev; dev = dev->next_siblings) {
+		err = register_candev(dev->netdev);
+		if (err) {
+			dev_err(&intf->dev, "couldn't register CAN device: %d\n",
+				err);
+			goto lbl_disconnect;
+		}
+		set_bit(PCAN_USB_STATE_REGISTERED, &dev->state);
+
+		netdev_info(dev->netdev,
+			    "attached to %s channel %u (device 0x%08X)\n",
+			    peak_usb_adapter->name, dev->ctrl_idx,
+			    dev->can_channel_id);
+	}
+
+	return 0;
+
+lbl_disconnect:
+	/* unregister (if needed) and free already created devices */
+	peak_usb_disconnect(intf);
+
 	return err;
 }
 
diff --git a/drivers/net/can/usb/peak_usb/pcan_usb_core.h b/drivers/net/can/usb/peak_usb/pcan_usb_core.h
index 234d20f81154..bed2b3c70f82 100644
--- a/drivers/net/can/usb/peak_usb/pcan_usb_core.h
+++ b/drivers/net/can/usb/peak_usb/pcan_usb_core.h
@@ -108,6 +108,7 @@ struct peak_tx_urb_context {
  */
 #define PCAN_USB_STATE_CONNECTED	0
 #define PCAN_USB_STATE_STARTED		1
+#define PCAN_USB_STATE_REGISTERED	2
 
 /* PEAK-System USB device */
 struct peak_usb_device {
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH net-next 17/23] can: peak_usb: validate the data length of PCAN-USB Pro CAN records
  2026-12-02 23:04 [PATCH net-next 0/23] pull-request: can-next 2026-12-03 Marc Kleine-Budde
                   ` (15 preceding siblings ...)
  2026-12-02 23:04 ` [PATCH net-next 16/23] can: peak_usb: register the netdevs only once all channels are set up Marc Kleine-Budde
@ 2026-12-02 23:04 ` Marc Kleine-Budde
  2026-12-02 23:04 ` [PATCH net-next 18/23] can: peak_usb: don't read past the message in PCAN-USB Pro decoders Marc Kleine-Budde
                   ` (5 subsequent siblings)
  22 siblings, 0 replies; 27+ messages in thread
From: Marc Kleine-Budde @ 2026-12-02 23:04 UTC (permalink / raw)
  To: netdev
  Cc: davem, kuba, linux-can, kernel, Stéphane Grosjean, stable,
	Marc Kleine-Budde

From: Stéphane Grosjean <s.grosjean@peak-system.fr>

The PCAN-USB Pro decoder takes the data length of a received CAN frame
from the 4-bit DLC field of the record, i.e. 0 to 15, and copies that
many bytes from the record into can_frame->data. This length is checked
neither against CAN_MAX_DLEN nor against the size of the record, which
depends on its type: RXMSG8, RXMSG4 and RXMSG0/RXRTR records carry 8, 4
and 0 data bytes. pcan_usb_pro_decode_buf() only checks that the record
fits in the URB, according to its type.

A faulty or malicious device can therefore make the driver:
- copy bytes located beyond the record into the frame, i.e. stale bytes
  of the RX buffer or, when the record ends the 1024-byte buffer, bytes
  beyond it, and deliver them to the CAN sockets;
- write up to 7 bytes past can_frame->data[] with a DLC of 9 to 15;
- deliver an RTR frame whose len is greater than CAN_MAX_DLEN.

Convert the DLC with can_cc_dlc2len() and reject a data frame whose
length exceeds the number of data bytes of its record type, as the
other malformed records are.

Found by Sashiko AI review.

Fixes: d8a199355f8f ("can: usb: PEAK-System Technik PCAN-USB Pro specific part")
Cc: stable@vger.kernel.org
Signed-off-by: Stéphane Grosjean <s.grosjean@peak-system.fr>
Link: https://patch.msgid.link/20261126-canfd_check_channel_idx-v9-8-abe0099b4585@peak-system.fr
Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
---
 drivers/net/can/usb/peak_usb/pcan_usb_pro.c | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)

diff --git a/drivers/net/can/usb/peak_usb/pcan_usb_pro.c b/drivers/net/can/usb/peak_usb/pcan_usb_pro.c
index 9e2f48683a9d..38307d452a5a 100644
--- a/drivers/net/can/usb/peak_usb/pcan_usb_pro.c
+++ b/drivers/net/can/usb/peak_usb/pcan_usb_pro.c
@@ -534,6 +534,7 @@ static int pcan_usb_pro_handle_canmsg(struct pcan_usb_pro_interface *usb_if,
 				      struct pcan_usb_pro_rxmsg *rx)
 {
 	const unsigned int ctrl_idx = (rx->len >> 4) & 0x0f;
+	const u8 len = can_cc_dlc2len(rx->len & 0x0f);
 	struct peak_usb_device *dev;
 	struct net_device *netdev;
 	struct can_frame *can_frame;
@@ -543,6 +544,12 @@ static int pcan_usb_pro_handle_canmsg(struct pcan_usb_pro_interface *usb_if,
 	if (ctrl_idx >= ARRAY_SIZE(usb_if->dev))
 		return -EINVAL;
 
+	/* the number of data bytes depends on the record type */
+	if (!(rx->flags & PCAN_USBPRO_RTR) &&
+	    len > pcan_usb_pro_sizeof_rec[rx->data_type] -
+		  offsetof(struct pcan_usb_pro_rxmsg, data))
+		return -EINVAL;
+
 	dev = READ_ONCE(usb_if->dev[ctrl_idx]);
 
 	/* reject records for a channel that is not (or no longer) set up */
@@ -556,7 +563,7 @@ static int pcan_usb_pro_handle_canmsg(struct pcan_usb_pro_interface *usb_if,
 		return -ENOMEM;
 
 	can_frame->can_id = le32_to_cpu(rx->id);
-	can_frame->len = rx->len & 0x0f;
+	can_frame->len = len;
 
 	if (rx->flags & PCAN_USBPRO_EXT)
 		can_frame->can_id |= CAN_EFF_FLAG;
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH net-next 18/23] can: peak_usb: don't read past the message in PCAN-USB Pro decoders
  2026-12-02 23:04 [PATCH net-next 0/23] pull-request: can-next 2026-12-03 Marc Kleine-Budde
                   ` (16 preceding siblings ...)
  2026-12-02 23:04 ` [PATCH net-next 17/23] can: peak_usb: validate the data length of PCAN-USB Pro CAN records Marc Kleine-Budde
@ 2026-12-02 23:04 ` Marc Kleine-Budde
  2026-12-02 23:04 ` [PATCH net-next 19/23] can: peak_usb: dump undecodable URBs once and rate limit decode errors Marc Kleine-Budde
                   ` (4 subsequent siblings)
  22 siblings, 0 replies; 27+ messages in thread
From: Marc Kleine-Budde @ 2026-12-02 23:04 UTC (permalink / raw)
  To: netdev
  Cc: davem, kuba, linux-can, kernel, Stéphane Grosjean,
	Marc Kleine-Budde

From: Stéphane Grosjean <s.grosjean@peak-system.fr>

The messages received from a PCAN-USB Pro device start with a record
count, followed by records whose size depends on their type, given by
their first byte. Both pcan_usb_pro_decode_buf() and
pcan_usb_pro_wait_rsp() trust this count:

- pcan_usb_pro_decode_buf() reads the type of the next record before
  checking that this record starts inside the URB. When the device
  claims more records than the URB holds, it reads the byte following
  the URB data, which is beyond the 1024-byte RX buffer when the URB
  fills it;
- pcan_usb_pro_wait_rsp() doesn't check the records against the
  received length at all. A truncated response is then accepted, and
  pcan_usb_pro_get_can_channel_id() returns stale bytes of its own
  request as the channel id. With the current callers, the walk only
  stays within the command buffer because its unused tail is zeroed.

Stop decoding a message at its end in both functions, and in
pcan_usb_pro_wait_rsp() also reject a record that doesn't fit in the
message.

Found by Sashiko AI review.

Fixes: d8a199355f8f ("can: usb: PEAK-System Technik PCAN-USB Pro specific part")
Signed-off-by: Stéphane Grosjean <s.grosjean@peak-system.fr>
Link: https://patch.msgid.link/20261126-canfd_check_channel_idx-v9-9-abe0099b4585@peak-system.fr
Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
---
 drivers/net/can/usb/peak_usb/pcan_usb_pro.c | 18 +++++++++++++++---
 1 file changed, 15 insertions(+), 3 deletions(-)

diff --git a/drivers/net/can/usb/peak_usb/pcan_usb_pro.c b/drivers/net/can/usb/peak_usb/pcan_usb_pro.c
index 38307d452a5a..88d21806207b 100644
--- a/drivers/net/can/usb/peak_usb/pcan_usb_pro.c
+++ b/drivers/net/can/usb/peak_usb/pcan_usb_pro.c
@@ -244,9 +244,9 @@ static int pcan_usb_pro_wait_rsp(struct peak_usb_device *dev,
 	for (i = 0; !err && i < PCAN_USBPRO_RSP_SUBMIT_MAX; i++) {
 		struct pcan_usb_pro_msg rsp;
 		union pcan_usb_pro_rec *pr;
+		u8 *pc, *rsp_end;
 		u32 r, rec_cnt;
 		u16 rec_len;
-		u8 *pc;
 
 		err = usb_bulk_msg(dev->udev,
 			usb_rcvbulkpipe(dev->udev, PCAN_USBPRO_EP_CMDIN),
@@ -271,13 +271,18 @@ static int pcan_usb_pro_wait_rsp(struct peak_usb_device *dev,
 		pc = pcan_msg_init(&rsp, pum->u.rec_buffer,
 			actual_length);
 
+		rsp_end = pum->u.rec_buffer + actual_length;
 		rec_cnt = le32_to_cpu(*rsp.u.rec_cnt);
 
 		/* loop on records stored into message */
 		for (r = 0; r < rec_cnt; r++) {
+			/* rec_cnt comes from the device: stay in the message */
+			if (pc >= rsp_end)
+				break;
+
 			pr = (union pcan_usb_pro_rec *)pc;
 			rec_len = pcan_usb_pro_sizeof_rec[pr->data_type];
-			if (!rec_len) {
+			if (!rec_len || pc + rec_len > rsp_end) {
 				netdev_err(dev->netdev,
 					   "got unprocessed record in msg\n");
 				pcan_dump_mem("rcvd rsp msg", pum->u.rec_buffer,
@@ -745,8 +750,15 @@ static int pcan_usb_pro_decode_buf(struct peak_usb_device *dev, struct urb *urb)
 	rec_cnt = le16_to_cpu(*usb_msg.u.rec_cnt_rd);
 	for (; rec_cnt > 0; rec_cnt--) {
 		union pcan_usb_pro_rec *pr = (union pcan_usb_pro_rec *)rec_ptr;
-		u16 sizeof_rec = pcan_usb_pro_sizeof_rec[pr->data_type];
+		u16 sizeof_rec;
 
+		/* rec_cnt comes from the device: don't read past the message */
+		if (rec_ptr >= msg_end) {
+			err = -EBADMSG;
+			break;
+		}
+
+		sizeof_rec = pcan_usb_pro_sizeof_rec[pr->data_type];
 		if (!sizeof_rec) {
 			netdev_err(netdev,
 				   "got unsupported rec in usb msg:\n");
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH net-next 19/23] can: peak_usb: dump undecodable URBs once and rate limit decode errors
  2026-12-02 23:04 [PATCH net-next 0/23] pull-request: can-next 2026-12-03 Marc Kleine-Budde
                   ` (17 preceding siblings ...)
  2026-12-02 23:04 ` [PATCH net-next 18/23] can: peak_usb: don't read past the message in PCAN-USB Pro decoders Marc Kleine-Budde
@ 2026-12-02 23:04 ` Marc Kleine-Budde
  2026-12-02 23:04 ` [PATCH net-next 20/23] can: peak_usb: don't return an uninitialized PCAN-USB CAN channel ID Marc Kleine-Budde
                   ` (3 subsequent siblings)
  22 siblings, 0 replies; 27+ messages in thread
From: Marc Kleine-Budde @ 2026-12-02 23:04 UTC (permalink / raw)
  To: netdev
  Cc: davem, kuba, linux-can, kernel, Stéphane Grosjean,
	Marc Kleine-Budde

From: Stéphane Grosjean <s.grosjean@peak-system.fr>

When the decoding of a received URB fails, peak_usb_read_bulk_callback()
dumps the whole RX buffer to the kernel log. The buffer is allocated with
kmalloc() and its size is the adapter RX buffer size (up to 2048 bytes),
so the bytes beyond urb->actual_length are uninitialized memory or
leftovers from previous transfers.

Moreover, the PCAN-USB Pro and PCAN-USB FD decoders already dump the
received bytes themselves before returning the error, so the same URB is
dumped twice. Neither these dumps nor the error messages printed by the
decoders are rate limited, while a faulty or malicious device can make
every transfer fail to decode, or carry unknown records.

Dump only the urb->actual_length bytes received, from
peak_usb_read_bulk_callback() only, and rate limit this dump as well as
the error messages the decoders print about the received data.

The dump and these messages are rate limited separately, so during a
burst one of them may be printed without the other. Drop the trailing
colon of the PCAN-USB Pro "got unsupported rec in usb msg" message,
which announced a dump that may no longer follow it.

The dumps and messages of the adapter decoders were pointed out by
Sashiko AI review.

Fixes: bb4785551f64 ("can: usb: PEAK-System Technik USB adapters driver core")
Signed-off-by: Stéphane Grosjean <s.grosjean@peak-system.fr>
Link: https://patch.msgid.link/20261126-canfd_check_channel_idx-v9-10-abe0099b4585@peak-system.fr
Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
---
 drivers/net/can/usb/peak_usb/pcan_usb.c      |  8 ++++--
 drivers/net/can/usb/peak_usb/pcan_usb_core.c |  4 +--
 drivers/net/can/usb/peak_usb/pcan_usb_fd.c   | 27 +++++++++---------
 drivers/net/can/usb/peak_usb/pcan_usb_pro.c  | 30 ++++++++++----------
 4 files changed, 35 insertions(+), 34 deletions(-)

diff --git a/drivers/net/can/usb/peak_usb/pcan_usb.c b/drivers/net/can/usb/peak_usb/pcan_usb.c
index 451d08421504..ff1921779065 100644
--- a/drivers/net/can/usb/peak_usb/pcan_usb.c
+++ b/drivers/net/can/usb/peak_usb/pcan_usb.c
@@ -637,7 +637,8 @@ static int pcan_usb_decode_status(struct pcan_usb_msg_context *mc,
 			return err;
 		break;
 	default:
-		netdev_err(mc->netdev, "unexpected function %u\n", f);
+		if (net_ratelimit())
+			netdev_err(mc->netdev, "unexpected function %u\n", f);
 		break;
 	}
 
@@ -776,8 +777,9 @@ static int pcan_usb_decode_buf(struct peak_usb_device *dev, struct urb *urb)
 			urb->actual_length);
 
 	} else if (urb->actual_length > 0) {
-		netdev_err(dev->netdev, "usb message length error (%u)\n",
-			urb->actual_length);
+		if (net_ratelimit())
+			netdev_err(dev->netdev, "usb message length error (%u)\n",
+				   urb->actual_length);
 		err = -EINVAL;
 	}
 
diff --git a/drivers/net/can/usb/peak_usb/pcan_usb_core.c b/drivers/net/can/usb/peak_usb/pcan_usb_core.c
index e5198ec5c760..1d306160fa35 100644
--- a/drivers/net/can/usb/peak_usb/pcan_usb_core.c
+++ b/drivers/net/can/usb/peak_usb/pcan_usb_core.c
@@ -266,10 +266,10 @@ static void peak_usb_read_bulk_callback(struct urb *urb)
 		/* handle these kinds of msgs only if _start callback called */
 		if (test_bit(PCAN_USB_STATE_STARTED, &dev->state)) {
 			err = dev->adapter->dev_decode_buf(dev, urb);
-			if (err)
+			if (err && net_ratelimit())
 				pcan_dump_mem("received usb message",
 					      urb->transfer_buffer,
-					      urb->transfer_buffer_length);
+					      urb->actual_length);
 		}
 	}
 
diff --git a/drivers/net/can/usb/peak_usb/pcan_usb_fd.c b/drivers/net/can/usb/peak_usb/pcan_usb_fd.c
index 43c16e743c15..cb5c457756da 100644
--- a/drivers/net/can/usb/peak_usb/pcan_usb_fd.c
+++ b/drivers/net/can/usb/peak_usb/pcan_usb_fd.c
@@ -801,15 +801,17 @@ static int pcan_usb_fd_decode_buf(struct peak_usb_device *dev, struct urb *urb)
 
 		/* check if the record goes out of current packet */
 		if (rx_msg_size > msg_end - msg_ptr) {
-			netdev_err(netdev,
-				   "got frag rec: should inc usb rx buf sze\n");
+			if (net_ratelimit())
+				netdev_err(netdev,
+					   "got frag rec: should inc usb rx buf sze\n");
 			err = -EBADMSG;
 			break;
 		}
 
 		rx_msg_min_size = pcan_usb_fd_rx_msg_min_size(rx_msg_type);
 		if (rx_msg_size < rx_msg_min_size) {
-			netdev_err(netdev, "got short rec\n");
+			if (net_ratelimit())
+				netdev_err(netdev, "got short rec\n");
 			err = -EBADMSG;
 			break;
 		}
@@ -818,7 +820,7 @@ static int pcan_usb_fd_decode_buf(struct peak_usb_device *dev, struct urb *urb)
 		case PUCAN_MSG_CAN_RX:
 			err = pcan_usb_fd_decode_canmsg(usb_if, rx_msg);
 			if (err < 0)
-				goto fail;
+				return err;
 			break;
 
 		case PCAN_UFD_MSG_CALIBRATION:
@@ -828,35 +830,32 @@ static int pcan_usb_fd_decode_buf(struct peak_usb_device *dev, struct urb *urb)
 		case PUCAN_MSG_ERROR:
 			err = pcan_usb_fd_decode_error(usb_if, rx_msg);
 			if (err < 0)
-				goto fail;
+				return err;
 			break;
 
 		case PUCAN_MSG_STATUS:
 			err = pcan_usb_fd_decode_status(usb_if, rx_msg);
 			if (err < 0)
-				goto fail;
+				return err;
 			break;
 
 		case PCAN_UFD_MSG_OVERRUN:
 			err = pcan_usb_fd_decode_overrun(usb_if, rx_msg);
 			if (err < 0)
-				goto fail;
+				return err;
 			break;
 
 		default:
-			netdev_err(netdev,
-				   "unhandled msg type 0x%02x (%d): ignored\n",
-				   rx_msg_type, rx_msg_type);
+			if (net_ratelimit())
+				netdev_err(netdev,
+					   "unhandled msg type 0x%02x (%d): ignored\n",
+					   rx_msg_type, rx_msg_type);
 			break;
 		}
 
 		msg_ptr += rx_msg_size;
 	}
 
-fail:
-	if (err)
-		pcan_dump_mem("received msg",
-			      urb->transfer_buffer, urb->actual_length);
 	return err;
 }
 
diff --git a/drivers/net/can/usb/peak_usb/pcan_usb_pro.c b/drivers/net/can/usb/peak_usb/pcan_usb_pro.c
index 88d21806207b..840658723648 100644
--- a/drivers/net/can/usb/peak_usb/pcan_usb_pro.c
+++ b/drivers/net/can/usb/peak_usb/pcan_usb_pro.c
@@ -741,7 +741,9 @@ static int pcan_usb_pro_decode_buf(struct peak_usb_device *dev, struct urb *urb)
 	rec_ptr = pcan_msg_init(&usb_msg, urb->transfer_buffer,
 					urb->actual_length);
 	if (!rec_ptr) {
-		netdev_err(netdev, "bad msg hdr len %d\n", urb->actual_length);
+		if (net_ratelimit())
+			netdev_err(netdev, "bad msg hdr len %d\n",
+				   urb->actual_length);
 		return -EINVAL;
 	}
 
@@ -760,16 +762,18 @@ static int pcan_usb_pro_decode_buf(struct peak_usb_device *dev, struct urb *urb)
 
 		sizeof_rec = pcan_usb_pro_sizeof_rec[pr->data_type];
 		if (!sizeof_rec) {
-			netdev_err(netdev,
-				   "got unsupported rec in usb msg:\n");
+			if (net_ratelimit())
+				netdev_err(netdev,
+					   "got unsupported rec in usb msg\n");
 			err = -ENOTSUPP;
 			break;
 		}
 
 		/* check if the record goes out of current packet */
 		if (rec_ptr + sizeof_rec > msg_end) {
-			netdev_err(netdev,
-				"got frag rec: should inc usb rx buf size\n");
+			if (net_ratelimit())
+				netdev_err(netdev,
+					   "got frag rec: should inc usb rx buf size\n");
 			err = -EBADMSG;
 			break;
 		}
@@ -781,13 +785,13 @@ static int pcan_usb_pro_decode_buf(struct peak_usb_device *dev, struct urb *urb)
 		case PCAN_USBPRO_RXRTR:
 			err = pcan_usb_pro_handle_canmsg(usb_if, &pr->rx_msg);
 			if (err < 0)
-				goto fail;
+				return err;
 			break;
 
 		case PCAN_USBPRO_RXSTATUS:
 			err = pcan_usb_pro_handle_error(usb_if, &pr->rx_status);
 			if (err < 0)
-				goto fail;
+				return err;
 			break;
 
 		case PCAN_USBPRO_RXTS:
@@ -795,20 +799,16 @@ static int pcan_usb_pro_decode_buf(struct peak_usb_device *dev, struct urb *urb)
 			break;
 
 		default:
-			netdev_err(netdev,
-				   "unhandled rec type 0x%02x (%d): ignored\n",
-				   pr->data_type, pr->data_type);
+			if (net_ratelimit())
+				netdev_err(netdev,
+					   "unhandled rec type 0x%02x (%d): ignored\n",
+					   pr->data_type, pr->data_type);
 			break;
 		}
 
 		rec_ptr += sizeof_rec;
 	}
 
-fail:
-	if (err)
-		pcan_dump_mem("received msg",
-			      urb->transfer_buffer, urb->actual_length);
-
 	return err;
 }
 
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH net-next 20/23] can: peak_usb: don't return an uninitialized PCAN-USB CAN channel ID
  2026-12-02 23:04 [PATCH net-next 0/23] pull-request: can-next 2026-12-03 Marc Kleine-Budde
                   ` (18 preceding siblings ...)
  2026-12-02 23:04 ` [PATCH net-next 19/23] can: peak_usb: dump undecodable URBs once and rate limit decode errors Marc Kleine-Budde
@ 2026-12-02 23:04 ` Marc Kleine-Budde
  2026-12-02 23:04 ` [PATCH net-next 21/23] can: peak_usb: pass the dev_num argument of PCAN-USB Pro GETDEVID Marc Kleine-Budde
                   ` (2 subsequent siblings)
  22 siblings, 0 replies; 27+ messages in thread
From: Marc Kleine-Budde @ 2026-12-02 23:04 UTC (permalink / raw)
  To: netdev
  Cc: davem, kuba, linux-can, kernel, Stéphane Grosjean, stable,
	Marc Kleine-Budde

From: Stéphane Grosjean <s.grosjean@peak-system.fr>

pcan_usb_get_can_channel_id() takes the CAN channel ID of a PCAN-USB
from the args[] array, which pcan_usb_wait_rsp() fills with the response
of the device. However, args[] is not initialized, and
pcan_usb_wait_rsp() returns success without touching it once the device
is no longer connected.

peak_usb_disconnect() clears PCAN_USB_STATE_CONNECTED before it
unregisters the netdevs. An ETHTOOL_GEEPROM request handled in this
window makes peak_usb_get_eeprom() copy an uninitialized stack byte to
userspace, and cache it in dev->can_channel_id.

Initialize args[], so that a null ID is returned in that case.

Found by Sashiko AI review.

Fixes: 36d007c6fc79 ("can: peak_usb: add ethtool interface to user-configurable CAN channel identifier")
Cc: stable@vger.kernel.org
Signed-off-by: Stéphane Grosjean <s.grosjean@peak-system.fr>
Link: https://patch.msgid.link/20261126-canfd_check_channel_idx-v9-11-abe0099b4585@peak-system.fr
Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
---
 drivers/net/can/usb/peak_usb/pcan_usb.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/drivers/net/can/usb/peak_usb/pcan_usb.c b/drivers/net/can/usb/peak_usb/pcan_usb.c
index ff1921779065..83cf6fe7d258 100644
--- a/drivers/net/can/usb/peak_usb/pcan_usb.c
+++ b/drivers/net/can/usb/peak_usb/pcan_usb.c
@@ -386,7 +386,7 @@ static int pcan_usb_get_serial(struct peak_usb_device *dev, u32 *serial_number)
  */
 static int pcan_usb_get_can_channel_id(struct peak_usb_device *dev, u32 *can_ch_id)
 {
-	u8 args[PCAN_USB_CMD_ARGS_LEN];
+	u8 args[PCAN_USB_CMD_ARGS_LEN] = {};
 	int err;
 
 	err = pcan_usb_wait_rsp(dev, PCAN_USB_CMD_DEVID, PCAN_USB_GET, args);
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH net-next 21/23] can: peak_usb: pass the dev_num argument of PCAN-USB Pro GETDEVID
  2026-12-02 23:04 [PATCH net-next 0/23] pull-request: can-next 2026-12-03 Marc Kleine-Budde
                   ` (19 preceding siblings ...)
  2026-12-02 23:04 ` [PATCH net-next 20/23] can: peak_usb: don't return an uninitialized PCAN-USB CAN channel ID Marc Kleine-Budde
@ 2026-12-02 23:04 ` Marc Kleine-Budde
  2026-12-02 23:04 ` [PATCH net-next 22/23] can: peak_usb: don't send uninitialized stack bytes to PCAN-USB devices Marc Kleine-Budde
  2026-12-02 23:04 ` [PATCH net-next 23/23] can: peak_usb: don't send uninitialized heap bytes in restart commands Marc Kleine-Budde
  22 siblings, 0 replies; 27+ messages in thread
From: Marc Kleine-Budde @ 2026-12-02 23:04 UTC (permalink / raw)
  To: netdev
  Cc: davem, kuba, linux-can, kernel, Stéphane Grosjean, stable,
	Marc Kleine-Budde

From: Stéphane Grosjean <s.grosjean@peak-system.fr>

pcan_usb_pro_get_can_channel_id() builds its GETDEVID record with
pcan_msg_add_rec(), passing only the channel index. However,
pcan_msg_add_rec() handles GETDEVID together with SETBTR and SETDEVID,
and also reads a second argument with va_arg(), to fill the dev_num
field of the record. Reading this missing argument is undefined
behavior: in practice, whatever value is left in the corresponding
register or stack slot is written to the request in dev->cmd_buf.

This value is sent to the device with each GETDEVID request. Moreover,
peak_usb_disconnect() clears PCAN_USB_STATE_CONNECTED before it
unregisters the netdevs, and once it is cleared,
pcan_usb_pro_send_cmd() and pcan_usb_pro_wait_rsp() return success
without any USB transfer. pcan_usb_pro_get_can_channel_id() then
returns the dev_num field of the request as the CAN channel ID, so an
ETHTOOL_GEEPROM request handled in this window makes
peak_usb_get_eeprom() copy that value to userspace, and cache it in
dev->can_channel_id.

Pass 0 as dev_num, so that the request is fully defined, and a null ID
is returned in that case.

Found by Sashiko AI review.

Fixes: d8a199355f8f ("can: usb: PEAK-System Technik PCAN-USB Pro specific part")
Cc: stable@vger.kernel.org
Signed-off-by: Stéphane Grosjean <s.grosjean@peak-system.fr>
Link: https://patch.msgid.link/20261126-canfd_check_channel_idx-v9-12-abe0099b4585@peak-system.fr
Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
---
 drivers/net/can/usb/peak_usb/pcan_usb_pro.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/drivers/net/can/usb/peak_usb/pcan_usb_pro.c b/drivers/net/can/usb/peak_usb/pcan_usb_pro.c
index 840658723648..0d014f4c08a7 100644
--- a/drivers/net/can/usb/peak_usb/pcan_usb_pro.c
+++ b/drivers/net/can/usb/peak_usb/pcan_usb_pro.c
@@ -435,7 +435,7 @@ static int pcan_usb_pro_get_can_channel_id(struct peak_usb_device *dev,
 	u8 *pc;
 
 	pc = pcan_msg_init_empty(&um, dev->cmd_buf, PCAN_USB_MAX_CMD_LEN);
-	pcan_msg_add_rec(&um, PCAN_USBPRO_GETDEVID, dev->ctrl_idx);
+	pcan_msg_add_rec(&um, PCAN_USBPRO_GETDEVID, dev->ctrl_idx, 0);
 
 	err =  pcan_usb_pro_send_cmd(dev, &um);
 	if (err)
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH net-next 22/23] can: peak_usb: don't send uninitialized stack bytes to PCAN-USB devices
  2026-12-02 23:04 [PATCH net-next 0/23] pull-request: can-next 2026-12-03 Marc Kleine-Budde
                   ` (20 preceding siblings ...)
  2026-12-02 23:04 ` [PATCH net-next 21/23] can: peak_usb: pass the dev_num argument of PCAN-USB Pro GETDEVID Marc Kleine-Budde
@ 2026-12-02 23:04 ` Marc Kleine-Budde
  2026-12-02 23:04 ` [PATCH net-next 23/23] can: peak_usb: don't send uninitialized heap bytes in restart commands Marc Kleine-Budde
  22 siblings, 0 replies; 27+ messages in thread
From: Marc Kleine-Budde @ 2026-12-02 23:04 UTC (permalink / raw)
  To: netdev
  Cc: davem, kuba, linux-can, kernel, Stéphane Grosjean, stable,
	Marc Kleine-Budde

From: Stéphane Grosjean <s.grosjean@peak-system.fr>

pcan_usb_send_cmd() copies the PCAN_USB_CMD_ARGS_LEN (14) bytes of the
args[] array of its caller into the command buffer, and sends the whole
command to the device.

pcan_usb_set_bittiming() only sets the first two bytes of its args[]
array, and pcan_usb_set_can_channel_id() only the first one. The other
12 or 13 bytes of these uninitialized stack arrays are thus sent to the
device each time the bitrate or the CAN channel ID is set.

Zero-initialize both arrays, as the other setters of the driver do.

Found by Sashiko AI review.

Fixes: 46be265d3388 ("can: usb: PEAK-System Technik PCAN-USB specific part")
Fixes: e7a7b3d22503 ("can: peak_usb: allow flashing of the CAN channel ID")
Cc: stable@vger.kernel.org
Signed-off-by: Stéphane Grosjean <s.grosjean@peak-system.fr>
Link: https://patch.msgid.link/20261126-canfd_check_channel_idx-v9-13-abe0099b4585@peak-system.fr
Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
---
 drivers/net/can/usb/peak_usb/pcan_usb.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/drivers/net/can/usb/peak_usb/pcan_usb.c b/drivers/net/can/usb/peak_usb/pcan_usb.c
index 83cf6fe7d258..2838e4ea2b4e 100644
--- a/drivers/net/can/usb/peak_usb/pcan_usb.c
+++ b/drivers/net/can/usb/peak_usb/pcan_usb.c
@@ -274,7 +274,7 @@ static int pcan_usb_set_led(struct peak_usb_device *dev, u8 onoff)
 static int pcan_usb_set_bittiming(struct peak_usb_device *dev,
 				  struct can_bittiming *bt)
 {
-	u8 args[PCAN_USB_CMD_ARGS_LEN];
+	u8 args[PCAN_USB_CMD_ARGS_LEN] = {};
 	u8 btr0, btr1;
 
 	btr0 = ((bt->brp - 1) & 0x3f) | (((bt->sjw - 1) & 0x3) << 6);
@@ -405,7 +405,7 @@ static int pcan_usb_get_can_channel_id(struct peak_usb_device *dev, u32 *can_ch_
 /* set a new CAN channel id in the flash memory of the device */
 static int pcan_usb_set_can_channel_id(struct peak_usb_device *dev, u32 can_ch_id)
 {
-	u8 args[PCAN_USB_CMD_ARGS_LEN];
+	u8 args[PCAN_USB_CMD_ARGS_LEN] = {};
 
 	/* this kind of device supports 8-bit values only */
 	if (can_ch_id > U8_MAX)
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH net-next 23/23] can: peak_usb: don't send uninitialized heap bytes in restart commands
  2026-12-02 23:04 [PATCH net-next 0/23] pull-request: can-next 2026-12-03 Marc Kleine-Budde
                   ` (21 preceding siblings ...)
  2026-12-02 23:04 ` [PATCH net-next 22/23] can: peak_usb: don't send uninitialized stack bytes to PCAN-USB devices Marc Kleine-Budde
@ 2026-12-02 23:04 ` Marc Kleine-Budde
  22 siblings, 0 replies; 27+ messages in thread
From: Marc Kleine-Budde @ 2026-12-02 23:04 UTC (permalink / raw)
  To: netdev
  Cc: davem, kuba, linux-can, kernel, Stéphane Grosjean, stable,
	Marc Kleine-Budde

From: Stéphane Grosjean <s.grosjean@peak-system.fr>

peak_usb_restart() allocates the buffer of the asynchronous restart
command with kmalloc(), and lets the dev_restart_async() callback of
the adapter build the command in it. None of these callbacks fills the
whole part of the buffer that it sends to the device:

- pcan_usb_restart_async() sets 3 of the PCAN_USB_CMD_LEN (16) bytes
  that it sends;
- pcan_usb_pro_restart_async() builds an 8-byte message, but sends the
  whole PCAN_USB_MAX_CMD_LEN (32) bytes buffer;
- pcan_usb_fd_build_restart_cmd() leaves the unused field of
  struct pucan_wr_err_cnt and the args of the final struct
  pucan_command unset.

Uninitialized heap bytes are thus sent to the device each time a
channel is restarted after bus off.

Allocate the buffer with kzalloc(), so that the unset bytes are zero,
as for the other command buffers of the driver.

Found while checking the other adapters for the uninitialized command
bytes reported by Sashiko AI review.

Fixes: bb4785551f64 ("can: usb: PEAK-System Technik USB adapters driver core")
Cc: stable@vger.kernel.org
Signed-off-by: Stéphane Grosjean <s.grosjean@peak-system.fr>
Link: https://patch.msgid.link/20261126-canfd_check_channel_idx-v9-14-abe0099b4585@peak-system.fr
Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
---
 drivers/net/can/usb/peak_usb/pcan_usb_core.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/drivers/net/can/usb/peak_usb/pcan_usb_core.c b/drivers/net/can/usb/peak_usb/pcan_usb_core.c
index 1d306160fa35..95c1454b4116 100644
--- a/drivers/net/can/usb/peak_usb/pcan_usb_core.c
+++ b/drivers/net/can/usb/peak_usb/pcan_usb_core.c
@@ -702,7 +702,7 @@ static int peak_usb_restart(struct peak_usb_device *dev)
 		return -ENOMEM;
 
 	/* also allocate enough space for the commands to send */
-	buf = kmalloc(PCAN_USB_MAX_CMD_LEN, GFP_ATOMIC);
+	buf = kzalloc(PCAN_USB_MAX_CMD_LEN, GFP_ATOMIC);
 	if (!buf) {
 		usb_free_urb(urb);
 		return -ENOMEM;
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* Re: [PATCH net-next 01/23] selftests: can: install net/lib.sh with the CAN tests
  2026-12-02 23:04 ` [PATCH net-next 01/23] selftests: can: install net/lib.sh with the CAN tests Marc Kleine-Budde
@ 2026-12-02 23:15   ` netdev-bot+sinfo
  0 siblings, 0 replies; 27+ messages in thread
From: netdev-bot+sinfo @ 2026-12-02 23:15 UTC (permalink / raw)
  To: Marc Kleine-Budde; +Cc: netdev, davem, kuba, linux-can, kernel, Oleksij Rempel

Hi!

This is an automated message. This series looks like a fix, but its
commit messages seem to be missing some information:

 - How the issue was discovered, e.g. hit in production, hit during
   development, syzbot report, manual code inspection, LLM or static
   analysis tool scan.

 - Whether the issue was actually triggered, or is only theoretical
   (e.g. found by LLM and not proven at runtime). If it was triggered
   please include the symptoms, like the stack trace or kernel messages.

Please do not repost the series just to address the above. Instead,
reply to this email with the missing information, so that reviewers
can take it into account.

*IMPORTANT*: If you do repost (for other reasons) - please include
the relevant info in the cover letter or commit messages.
-- 
The evaluation is done by an LLM so it may be wrong, if you think
that is the case please reply and explain.

^ permalink raw reply	[flat|nested] 27+ messages in thread

* Re: [PATCH net-next 02/23] selftests: can: add J1939 test helper header and library
  2026-12-02 23:04 ` [PATCH net-next 02/23] selftests: can: add J1939 test helper header and library Marc Kleine-Budde
@ 2026-12-02 23:26   ` sashiko-bot
  2026-12-02 23:29     ` Marc Kleine-Budde
  0 siblings, 1 reply; 27+ messages in thread
From: sashiko-bot @ 2026-12-02 23:26 UTC (permalink / raw)
  To: Marc Kleine-Budde
  Cc: linux-can, Oliver Hartkopp, Vincent Mailhol, Oleksij Rempel

Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Medium] selftests: can: undeclared static_assert() in j1939_gw.c due
  to UAPI header
--

commit 8a0b49ac9325ad4226e875680d89eb3fe0cedc60
Author: Oleksij Rempel <o.rempel@pengutronix.de>

selftests: can: add J1939 test helper header and library

This commit adds shared C and shell helpers, a kselftest harness header, and
a CAN gateway setup helper for J1939 selftests.

Link: https://patch.msgid.link/20261130-j1939-selftests-v7-2-2491693ccb8d@pengutronix.de

> diff --git a/tools/testing/selftests/net/can/Makefile b/tools/testing/selftests/net/can/Makefile
> index 3adaa13dcbfa3..cf0b06974d546 100644
> --- a/tools/testing/selftests/net/can/Makefile
> +++ b/tools/testing/selftests/net/can/Makefile
> @@ -2,12 +2,16 @@
>  
>  top_srcdir = ../../../../..
>  
> -CFLAGS += -Wall -Wl,--no-as-needed -O2 -g -I$(top_srcdir)/usr/include $(KHDR_INCLUDES)
> +CFLAGS += -Wall -Wl,--no-as-needed -O2 -g -I$(top_srcdir)/usr/include -I$(top_srcdir)/tools/include $(KHDR_INCLUDES)
[ ... ]
> diff --git a/tools/testing/selftests/net/can/j1939_gw.c b/tools/testing/selftests/net/can/j1939_gw.c
> new file mode 100644
> index 0000000000000..4018432add9a2
> --- /dev/null
> +++ b/tools/testing/selftests/net/can/j1939_gw.c
> @@ -0,0 +1,129 @@
[ ... ]
> +#include <linux/can.h>
> +#include <linux/can/gw.h>
> +#include <linux/kernel.h>
> +#include <linux/netlink.h>
> +#include <linux/rtnetlink.h>
> +
> +/* an RTM_NEWROUTE request for a CAN->CAN rule, see net/can/gw.c */
> +struct cgw_req {
> +	struct nlmsghdr nh;
> +	struct rtcanmsg rtcan;
> +	struct rtattr src_attr;
> +	__u32 src_ifindex;
> +	struct rtattr dst_attr;
> +	__u32 dst_ifindex;
> +};
> +
> +struct cgw_ack {
> +	struct nlmsghdr nh;
> +	struct nlmsgerr err;
> +};
> +
> +static_assert(offsetof(struct cgw_req, src_attr) ==
> +	      NLMSG_SPACE(sizeof(struct rtcanmsg)),
> +	      "the attributes must follow the aligned rtcanmsg");
> +static_assert(offsetof(struct cgw_req, dst_attr) ==
> +	      offsetof(struct cgw_req, src_attr) + RTA_SPACE(sizeof(__u32)),
> +	      "the attributes must be packed as netlink aligns them");

[Severity: Medium]
Can j1939_gw.c fail to build with an undeclared static_assert() on C11/C17
compilers?

CFLAGS puts -I$(top_srcdir)/usr/include ahead of
-I$(top_srcdir)/tools/include.  When UAPI headers have been exported to
usr/include (such as during make kselftest), <linux/kernel.h> resolves to
usr/include/linux/kernel.h instead of tools/include/linux/kernel.h, which does
not include <assert.h> or <linux/build_bug.h>.  Including <linux/build_bug.h>
(as j1939_helpers.h does) or <assert.h> directly in j1939_gw.c would avoid the
shadowing issue.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261202230853.2665144-1-mkl@pengutronix.de?part=2

^ permalink raw reply	[flat|nested] 27+ messages in thread

* Re: [PATCH net-next 02/23] selftests: can: add J1939 test helper header and library
  2026-12-02 23:26   ` sashiko-bot
@ 2026-12-02 23:29     ` Marc Kleine-Budde
  0 siblings, 0 replies; 27+ messages in thread
From: Marc Kleine-Budde @ 2026-12-02 23:29 UTC (permalink / raw)
  To: sashiko-bot; +Cc: linux-can, Oliver Hartkopp, Vincent Mailhol, Oleksij Rempel

[-- Attachment #1: Type: text/plain, Size: 546 bytes --]

On 02.12.2026 23:26:46, sashiko-bot@kernel.org wrote:
> Thank you for your contribution! Sashiko AI review found 1 potential
> issue to consider:
> - [Medium] selftests: can: undeclared static_assert() in j1939_gw.c due
>   to UAPI header

will fix

pw-bot: cr

Marc

-- 
Pengutronix e.K.                 | Marc Kleine-Budde          |
Embedded Linux                   | https://www.pengutronix.de |
Vertretung Nürnberg              | Phone: +49-5121-206917-129 |
Amtsgericht Hildesheim, HRA 2686 | Fax:   +49-5121-206917-9   |

[-- Attachment #2: signature.asc --]
[-- Type: application/pgp-signature, Size: 228 bytes --]

^ permalink raw reply	[flat|nested] 27+ messages in thread

end of thread, other threads:[~2026-12-02 23:29 UTC | newest]

Thread overview: 27+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-02 23:04 [PATCH net-next 0/23] pull-request: can-next 2026-12-03 Marc Kleine-Budde
2026-12-02 23:04 ` [PATCH net-next 01/23] selftests: can: install net/lib.sh with the CAN tests Marc Kleine-Budde
2026-12-02 23:15   ` netdev-bot+sinfo
2026-12-02 23:04 ` [PATCH net-next 02/23] selftests: can: add J1939 test helper header and library Marc Kleine-Budde
2026-12-02 23:26   ` sashiko-bot
2026-12-02 23:29     ` Marc Kleine-Budde
2026-12-02 23:04 ` [PATCH net-next 03/23] selftests: can: add J1939 base functional tests Marc Kleine-Budde
2026-12-02 23:04 ` [PATCH net-next 04/23] selftests: can: add J1939 socket option and metadata tests Marc Kleine-Budde
2026-12-02 23:04 ` [PATCH net-next 05/23] selftests: can: add J1939 addressing and concurrency tests Marc Kleine-Budde
2026-12-02 23:04 ` [PATCH net-next 06/23] selftests: can: add J1939 wire-format tests against CAN_RAW Marc Kleine-Budde
2026-12-02 23:04 ` [PATCH net-next 07/23] selftests: can: add J1939 TP/ETP multi-frame " Marc Kleine-Budde
2026-12-02 23:04 ` [PATCH net-next 08/23] selftests: can: cover J1939 transport abort and timeout paths Marc Kleine-Budde
2026-12-02 23:04 ` [PATCH net-next 09/23] selftests: can: check SO_J1939_PROMISC receive effect Marc Kleine-Budde
2026-12-02 23:04 ` [PATCH net-next 10/23] can: peak_usb: fix missing CAN_ERR_FLAG when reporting error counters Marc Kleine-Budde
2026-12-02 23:04 ` [PATCH net-next 11/23] can: peak_usb: harden PCAN-USB message validation Marc Kleine-Budde
2026-12-02 23:04 ` [PATCH net-next 12/23] can: peak_usb: replace open-coded bitmask operations with bitops Marc Kleine-Budde
2026-12-02 23:04 ` [PATCH net-next 13/23] can: peak_usb: harden channel handling in PCAN-USB FD Marc Kleine-Budde
2026-12-02 23:04 ` [PATCH net-next 14/23] can: peak_usb: fix RX cursor desync for self-received RTR frames with SRR Marc Kleine-Budde
2026-12-02 23:04 ` [PATCH net-next 15/23] can: peak_usb: reject records for unset channels in PCAN-USB Pro Marc Kleine-Budde
2026-12-02 23:04 ` [PATCH net-next 16/23] can: peak_usb: register the netdevs only once all channels are set up Marc Kleine-Budde
2026-12-02 23:04 ` [PATCH net-next 17/23] can: peak_usb: validate the data length of PCAN-USB Pro CAN records Marc Kleine-Budde
2026-12-02 23:04 ` [PATCH net-next 18/23] can: peak_usb: don't read past the message in PCAN-USB Pro decoders Marc Kleine-Budde
2026-12-02 23:04 ` [PATCH net-next 19/23] can: peak_usb: dump undecodable URBs once and rate limit decode errors Marc Kleine-Budde
2026-12-02 23:04 ` [PATCH net-next 20/23] can: peak_usb: don't return an uninitialized PCAN-USB CAN channel ID Marc Kleine-Budde
2026-12-02 23:04 ` [PATCH net-next 21/23] can: peak_usb: pass the dev_num argument of PCAN-USB Pro GETDEVID Marc Kleine-Budde
2026-12-02 23:04 ` [PATCH net-next 22/23] can: peak_usb: don't send uninitialized stack bytes to PCAN-USB devices Marc Kleine-Budde
2026-12-02 23:04 ` [PATCH net-next 23/23] can: peak_usb: don't send uninitialized heap bytes in restart commands Marc Kleine-Budde

This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.