← Documents Documentation/networking/j1939.rst GitHub 원문 ↗

Linux 6.18.37 · Networking

J1939 Documentation

Linux J1939 스택의 주소 지정, PGN, TP/ETP 전송, 소켓 옵션, timestamp 오류 큐와 주소 확보 API를 설명합니다.

Source pathDocumentation/networking/j1939.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

요약·해설

j1939.rst:1-1135

J1939는 CAN의 8바이트 한계를 넘어 최대 111MiB 페이로드를 TP/ETP 세션으로 전송하고, 64비트 NAME과 8비트 주소를 결합해 ECU를 식별합니다. Linux 커널은 여러 프로세스 사이의 주소 상태와 transport session을 공유해 충돌과 타이밍 문제를 줄입니다.

애플리케이션은 `SOCK_DGRAM` 소켓에 순수 페이로드를 넘기며 커널이 크기에 따라 simple, TP, ETP를 선택합니다. 운영 환경에서는 `bind`/`connect` 필터, `SO_J1939_FILTER`, broadcast 허용, 송신 우선순위, 오류 큐와 timestamping을 함께 설계해야 합니다.

핵심 계층
계층핵심 요소
식별29비트 CAN ID, PGN, SA/DA, 64비트 NAME
전송Simple, TP, ETP
수신bind/connect, whitelist filter, promiscuous
관찰SO_J1939_ERRQUEUE, SO_TIMESTAMPING, tskey
주소 관리Address Claiming, 250ms 검증, j1939acd

J1939 소켓을 구성할 때 확인할 항목입니다.

TP/ETP 세션 관찰
페이로드 송신크기별 Simple/TP/ETP 선택CAN 프레임 스케줄ACK 또는 EOMAtimestamp/error queue
수신 RTSTP/ETP 세션 생성DPO/데이터 수신완료 또는 RX_ABORT통계/error queue

송신부터 오류 큐 통지까지의 운영 흐름입니다.

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

원문 전체 펼치기
1 .. SPDX-License-Identifier: (GPL-2.0 OR MIT)
2
3 ===================
4 J1939 Documentation
5 ===================
6
7 Overview / What Is J1939
8 ========================
9
10 SAE J1939 defines a higher layer protocol on CAN. It implements a more
11 sophisticated addressing scheme and extends the maximum packet size above 8
12 bytes. Several derived specifications exist, which differ from the original
13 J1939 on the application level, like MilCAN A, NMEA2000, and especially
14 ISO-11783 (ISOBUS). This last one specifies the so-called ETP (Extended
15 Transport Protocol), which has been included in this implementation. This
16 results in a maximum packet size of ((2 ^ 24) - 1) * 7 bytes == 111 MiB.
17
18 Specifications used
19 -------------------
20
21 * SAE J1939-21 : data link layer
22 * SAE J1939-81 : network management
23 * ISO 11783-6 : Virtual Terminal (Extended Transport Protocol)
24
25 .. _j1939-motivation:
26
27 Motivation
28 ==========
29
30 Given the fact there's something like SocketCAN with an API similar to BSD
31 sockets, we found some reasons to justify a kernel implementation for the
32 addressing and transport methods used by J1939.
33
34 * **Addressing:** when a process on an ECU communicates via J1939, it should
35 not necessarily know its source address. Although, at least one process per
36 ECU should know the source address. Other processes should be able to reuse
37 that address. This way, address parameters for different processes
38 cooperating for the same ECU, are not duplicated. This way of working is
39 closely related to the UNIX concept, where programs do just one thing and do
40 it well.
41
42 * **Dynamic addressing:** Address Claiming in J1939 is time critical.
43 Furthermore, data transport should be handled properly during the address
44 negotiation. Putting this functionality in the kernel eliminates it as a
45 requirement for _every_ user space process that communicates via J1939. This
46 results in a consistent J1939 bus with proper addressing.
47
48 * **Transport:** both TP & ETP reuse some PGNs to relay big packets over them.
49 Different processes may thus use the same TP & ETP PGNs without actually
50 knowing it. The individual TP & ETP sessions _must_ be serialized
51 (synchronized) between different processes. The kernel solves this problem
52 properly and eliminates the serialization (synchronization) as a requirement
53 for _every_ user space process that communicates via J1939.
54
55 J1939 defines some other features (relaying, gateway, fast packet transport,
56 ...). In-kernel code for these would not contribute to protocol stability.
57 Therefore, these parts are left to user space.
58
59 The J1939 sockets operate on CAN network devices (see SocketCAN). Any J1939
60 user space library operating on CAN raw sockets will still operate properly.
61 Since such a library does not communicate with the in-kernel implementation, care
62 must be taken that these two do not interfere. In practice, this means they
63 cannot share ECU addresses. A single ECU (or virtual ECU) address is used by
64 the library exclusively, or by the in-kernel system exclusively.
65
66 J1939 concepts
67 ==============
68
69 Data Sent to the J1939 Stack
70 ----------------------------
71
72 The data buffers sent to the J1939 stack from user space are not CAN frames
73 themselves. Instead, they are payloads that the J1939 stack converts into
74 proper CAN frames based on the size of the buffer and the type of transfer. The
75 size of the buffer influences how the stack processes the data and determines
76 the internal code path used for the transfer.
77
78 **Handling of Different Buffer Sizes:**
79
80 - **Buffers with a size of 8 bytes or less:**
81
82 - These are handled as simple sessions internally within the stack.
83
84 - The stack converts the buffer directly into a single CAN frame without
85 fragmentation.
86
87 - This type of transfer does not require an actual client (receiver) on the
88 receiving side.
89
90 - **Buffers up to 1785 bytes:**
91
92 - These are automatically handled as J1939 Transport Protocol (TP) transfers.
93
94 - Internally, the stack splits the buffer into multiple 8-byte CAN frames.
95
96 - TP transfers can be unicast or broadcast.
97
98 - **Broadcast TP:** Does not require a receiver on the other side and can be
99 used in broadcast scenarios.
100
101 - **Unicast TP:** Requires an active receiver (client) on the other side to
102 acknowledge the transfer.
103
104 - **Buffers from 1786 bytes up to 111 MiB:**
105
106 - These are handled as ISO 11783 Extended Transport Protocol (ETP) transfers.
107
108 - ETP transfers are used for larger payloads and are split into multiple CAN
109 frames internally.
110
111 - **ETP transfers (unicast):** Require a receiver on the other side to
112 process the incoming data and acknowledge each step of the transfer.
113
114 - ETP transfers cannot be broadcast like TP transfers, and always require a
115 receiver for operation.
116
117 **Non-Blocking Operation with `MSG_DONTWAIT`:**
118
119 The J1939 stack supports non-blocking operation when used in combination with
120 the `MSG_DONTWAIT` flag. In this mode, the stack attempts to take as much data
121 as the available memory for the socket allows. It returns the amount of data
122 that was successfully taken, and it is the responsibility of user space to
123 monitor this value and handle partial transfers.
124
125 - If the stack cannot take the entire buffer, it returns the number of bytes
126 successfully taken, and user space should handle the remainder.
127
128 - **Error handling:** When using `MSG_DONTWAIT`, the user must rely on the
129 error queue to detect transfer errors. See the **SO_J1939_ERRQUEUE** section
130 for details on how to subscribe to error notifications. Without the error
131 queue, there is no other way for user space to be notified of transfer errors
132 during non-blocking operations.
133
134 **Behavior and Requirements:**
135
136 - **Simple transfers (<= 8 bytes):** Do not require a receiver on the other
137 side, making them easy to send without needing address claiming or
138 coordination with a destination.
139
140 - **Unicast TP/ETP:** Requires a receiver on the other side to complete the
141 transfer. The receiver must acknowledge the transfer for the session to
142 proceed successfully.
143
144 - **Broadcast TP:** Allows sending data without a receiver, but only works for
145 TP transfers. ETP cannot be broadcast and always needs a receiving client.
146
147 These different behaviors depend heavily on the size of the buffer provided to
148 the stack, and the appropriate transport mechanism (TP or ETP) is selected
149 based on the payload size. The stack automatically manages the fragmentation
150 and reassembly of large payloads and ensures that the correct CAN frames are
151 generated and transmitted for each session.
152
153 PGN
154 ---
155
156 The J1939 protocol uses the 29-bit CAN identifier with the following structure:
157
158 ============ ============== ====================
159 29 bit CAN-ID
160 --------------------------------------------------
161 Bit positions within the CAN-ID
162 --------------------------------------------------
163 28 ... 26 25 ... 8 7 ... 0
164 ============ ============== ====================
165 Priority PGN SA (Source Address)
166 ============ ============== ====================
167
168 The PGN (Parameter Group Number) is a number to identify a packet. The PGN
169 is composed as follows:
170
171 ============ ============== ================= =================
172 PGN
173 ------------------------------------------------------------------
174 Bit positions within the CAN-ID
175 ------------------------------------------------------------------
176 25 24 23 ... 16 15 ... 8
177 ============ ============== ================= =================
178 R (Reserved) DP (Data Page) PF (PDU Format) PS (PDU Specific)
179 ============ ============== ================= =================
180
181 In J1939-21 distinction is made between PDU1 format (where PF < 240) and PDU2
182 format (where PF >= 240). Furthermore, when using the PDU2 format, the PS-field
183 contains a so-called Group Extension, which is part of the PGN. When using PDU2
184 format, the Group Extension is set in the PS-field.
185
186 ============== ========================
187 PDU1 Format (specific) (peer to peer)
188 ----------------------------------------
189 Bit positions within the CAN-ID
190 ----------------------------------------
191 23 ... 16 15 ... 8
192 ============== ========================
193 00h ... EFh DA (Destination address)
194 ============== ========================
195
196 ============== ========================
197 PDU2 Format (global) (broadcast)
198 ----------------------------------------
199 Bit positions within the CAN-ID
200 ----------------------------------------
201 23 ... 16 15 ... 8
202 ============== ========================
203 F0h ... FFh GE (Group Extension)
204 ============== ========================
205
206 On the other hand, when using PDU1 format, the PS-field contains a so-called
207 Destination Address, which is _not_ part of the PGN. When communicating a PGN
208 from user space to kernel (or vice versa) and PDU1 format is used, the PS-field
209 of the PGN shall be set to zero. The Destination Address shall be set
210 elsewhere.
211
212 Regarding PGN mapping to 29-bit CAN identifier, the Destination Address shall
213 be get/set from/to the appropriate bits of the identifier by the kernel.
214
215
216 Addressing
217 ----------
218
219 Both static and dynamic addressing methods can be used.
220
221 For static addresses, no extra checks are made by the kernel and provided
222 addresses are considered right. This responsibility is for the OEM or system
223 integrator.
224
225 For dynamic addressing, so-called Address Claiming, extra support is foreseen
226 in the kernel. In J1939 any ECU is known by its 64-bit NAME. At the moment of
227 a successful address claim, the kernel keeps track of both NAME and source
228 address being claimed. This serves as a base for filter schemes. By default,
229 packets with a destination that is not locally will be rejected.
230
231 Mixed mode packets (from a static to a dynamic address or vice versa) are
232 allowed. The BSD sockets define separate API calls for getting/setting the
233 local & remote address and are applicable for J1939 sockets.
234
235 Filtering
236 ---------
237
238 J1939 defines white list filters per socket that a user can set in order to
239 receive a subset of the J1939 traffic. Filtering can be based on:
240
241 * SA
242 * SOURCE_NAME
243 * PGN
244
245 When multiple filters are in place for a single socket, and a packet comes in
246 that matches several of those filters, the packet is only received once for
247 that socket.
248
249 How to Use J1939
250 ================
251
252 API Calls
253 ---------
254
255 On CAN, you first need to open a socket for communicating over a CAN network.
256 To use J1939, ``#include <linux/can/j1939.h>``. From there, ``<linux/can.h>`` will be
257 included too. To open a socket, use:
258
259 .. code-block:: C
260
261 s = socket(PF_CAN, SOCK_DGRAM, CAN_J1939);
262
263 J1939 does use ``SOCK_DGRAM`` sockets. In the J1939 specification, connections are
264 mentioned in the context of transport protocol sessions. These still deliver
265 packets to the other end (using several CAN packets). ``SOCK_STREAM`` is not
266 supported.
267
268 After the successful creation of the socket, you would normally use the ``bind(2)``
269 and/or ``connect(2)`` system call to bind the socket to a CAN interface. After
270 binding and/or connecting the socket, you can ``read(2)`` and ``write(2)`` from/to the
271 socket or use ``send(2)``, ``sendto(2)``, ``sendmsg(2)`` and the ``recv*()`` counterpart
272 operations on the socket as usual. There are also J1939 specific socket options
273 described below.
274
275 In order to send data, a ``bind(2)`` must have been successful. ``bind(2)`` assigns a
276 local address to a socket.
277
278 Different from CAN is that the payload data is just the data that get sends,
279 without its header info. The header info is derived from the sockaddr supplied
280 to ``bind(2)``, ``connect(2)``, ``sendto(2)`` and ``recvfrom(2)``. A ``write(2)`` with size 4 will
281 result in a packet with 4 bytes.
282
283 The sockaddr structure has extensions for use with J1939 as specified below:
284
285 .. code-block:: C
286
287 struct sockaddr_can {
288 sa_family_t can_family;
289 int can_ifindex;
290 union {
291 struct {
292 __u64 name;
293 /* pgn:
294 * 8 bit: PS in PDU2 case, else 0
295 * 8 bit: PF
296 * 1 bit: DP
297 * 1 bit: reserved
298 */
299 __u32 pgn;
300 __u8 addr;
301 } j1939;
302 } can_addr;
303 }
304
305 ``can_family`` & ``can_ifindex`` serve the same purpose as for other SocketCAN sockets.
306
307 ``can_addr.j1939.pgn`` specifies the PGN (max 0x3ffff). Individual bits are
308 specified above.
309
310 ``can_addr.j1939.name`` contains the 64-bit J1939 NAME.
311
312 ``can_addr.j1939.addr`` contains the address.
313
314 The ``bind(2)`` system call assigns the local address, i.e. the source address when
315 sending packages. If a PGN during ``bind(2)`` is set, it's used as a RX filter.
316 I.e. only packets with a matching PGN are received. If an ADDR or NAME is set
317 it is used as a receive filter, too. It will match the destination NAME or ADDR
318 of the incoming packet. The NAME filter will work only if appropriate Address
319 Claiming for this name was done on the CAN bus and registered/cached by the
320 kernel.
321
322 On the other hand ``connect(2)`` assigns the remote address, i.e. the destination
323 address. The PGN from ``connect(2)`` is used as the default PGN when sending
324 packets. If ADDR or NAME is set it will be used as the default destination ADDR
325 or NAME. Further a set ADDR or NAME during ``connect(2)`` is used as a receive
326 filter. It will match the source NAME or ADDR of the incoming packet.
327
328 Both ``write(2)`` and ``send(2)`` will send a packet with local address from ``bind(2)`` and the
329 remote address from ``connect(2)``. Use ``sendto(2)`` to overwrite the destination
330 address.
331
332 If ``can_addr.j1939.name`` is set (!= 0) the NAME is looked up by the kernel and
333 the corresponding ADDR is used. If ``can_addr.j1939.name`` is not set (== 0),
334 ``can_addr.j1939.addr`` is used.
335
336 When creating a socket, reasonable defaults are set. Some options can be
337 modified with ``setsockopt(2)`` & ``getsockopt(2)``.
338
339 RX path related options:
340
341 - ``SO_J1939_FILTER`` - configure array of filters
342 - ``SO_J1939_PROMISC`` - disable filters set by ``bind(2)`` and ``connect(2)``
343
344 By default no broadcast packets can be send or received. To enable sending or
345 receiving broadcast packets use the socket option ``SO_BROADCAST``:
346
347 .. code-block:: C
348
349 int value = 1;
350 setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &value, sizeof(value));
351
352 The following diagram illustrates the RX path:
353
354 .. code::
355
356 +--------------------+
357 | incoming packet |
358 +--------------------+
359 |
360 V
361 +--------------------+
362 | SO_J1939_PROMISC? |
363 +--------------------+
364 | |
365 no | | yes
366 | |
367 .---------' `---------.
368 | |
369 +---------------------------+ |
370 | bind() + connect() + | |
371 | SOCK_BROADCAST filter | |
372 +---------------------------+ |
373 | |
374 |<---------------------'
375 V
376 +---------------------------+
377 | SO_J1939_FILTER |
378 +---------------------------+
379 |
380 V
381 +---------------------------+
382 | socket recv() |
383 +---------------------------+
384
385 TX path related options:
386 ``SO_J1939_SEND_PRIO`` - change default send priority for the socket
387
388 Message Flags during send() and Related System Calls
389 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
390
391 ``send(2)``, ``sendto(2)`` and ``sendmsg(2)`` take a 'flags' argument. Currently
392 supported flags are:
393
394 * ``MSG_DONTWAIT``, i.e. non-blocking operation.
395
396 recvmsg(2)
397 ^^^^^^^^^^
398
399 In most cases ``recvmsg(2)`` is needed if you want to extract more information than
400 ``recvfrom(2)`` can provide. For example package priority and timestamp. The
401 Destination Address, name and packet priority (if applicable) are attached to
402 the msghdr in the ``recvmsg(2)`` call. They can be extracted using ``cmsg(3)`` macros,
403 with ``cmsg_level == SOL_J1939 && cmsg_type == SCM_J1939_DEST_ADDR``,
404 ``SCM_J1939_DEST_NAME`` or ``SCM_J1939_PRIO``. The returned data is a ``uint8_t`` for
405 ``priority`` and ``dst_addr``, and ``uint64_t`` for ``dst_name``.
406
407 .. code-block:: C
408
409 uint8_t priority, dst_addr;
410 uint64_t dst_name;
411
412 for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
413 switch (cmsg->cmsg_level) {
414 case SOL_CAN_J1939:
415 if (cmsg->cmsg_type == SCM_J1939_DEST_ADDR)
416 dst_addr = *CMSG_DATA(cmsg);
417 else if (cmsg->cmsg_type == SCM_J1939_DEST_NAME)
418 memcpy(&dst_name, CMSG_DATA(cmsg), cmsg->cmsg_len - CMSG_LEN(0));
419 else if (cmsg->cmsg_type == SCM_J1939_PRIO)
420 priority = *CMSG_DATA(cmsg);
421 break;
422 }
423 }
424
425 setsockopt(2)
426 ^^^^^^^^^^^^^
427
428 The ``setsockopt(2)`` function is used to configure various socket-level
429 options for J1939 communication. The following options are supported:
430
431 ``SO_J1939_FILTER``
432 ~~~~~~~~~~~~~~~~~~~
433
434 The ``SO_J1939_FILTER`` option is essential when the default behavior of
435 ``bind(2)`` and ``connect(2)`` is insufficient for specific use cases. By
436 default, ``bind(2)`` and ``connect(2)`` allow a socket to be associated with a
437 single unicast or broadcast address. However, there are scenarios where finer
438 control over the incoming messages is required, such as filtering by Parameter
439 Group Number (PGN) rather than by addresses.
440
441 For example, in a system where multiple types of J1939 messages are being
442 transmitted, a process might only be interested in a subset of those messages,
443 such as specific PGNs, and not want to receive all messages destined for its
444 address or broadcast to the bus.
445
446 By applying the ``SO_J1939_FILTER`` option, you can filter messages based on:
447
448 - **Source Address (SA)**: Filter messages coming from specific source
449 addresses.
450
451 - **Source Name**: Filter messages coming from ECUs with specific NAME
452 identifiers.
453
454 - **Parameter Group Number (PGN)**: Focus on receiving messages with specific
455 PGNs, filtering out irrelevant ones.
456
457 This filtering mechanism is particularly useful when:
458
459 - You want to receive a subset of messages based on their PGNs, even if the
460 address is the same.
461
462 - You need to handle both broadcast and unicast messages but only care about
463 certain message types or parameters.
464
465 - The ``bind(2)`` and ``connect(2)`` functions only allow binding to a single
466 address, which might not be sufficient if the process needs to handle multiple
467 PGNs but does not want to open multiple sockets.
468
469 To remove existing filters, you can pass ``optval == NULL`` or ``optlen == 0``
470 to ``setsockopt(2)``. This will clear all currently set filters. If you want to
471 **update** the set of filters, you must pass the updated filter set to
472 ``setsockopt(2)``, as the new filter set will **replace** the old one entirely.
473 This behavior ensures that any previous filter configuration is discarded and
474 only the new set is applied.
475
476 Example of removing all filters:
477
478 .. code-block:: c
479
480 setsockopt(sock, SOL_CAN_J1939, SO_J1939_FILTER, NULL, 0);
481
482 **Maximum number of filters:** The maximum amount of filters that can be
483 applied using ``SO_J1939_FILTER`` is defined by ``J1939_FILTER_MAX``, which is
484 set to 512. This means you can configure up to 512 individual filters to match
485 your specific filtering needs.
486
487 Practical use case: **Monitoring Address Claiming**
488
489 One practical use case is monitoring the J1939 address claiming process by
490 filtering for specific PGNs related to address claiming. This allows a process
491 to monitor and handle address claims without processing unrelated messages.
492
493 Example:
494
495 .. code-block:: c
496
497 struct j1939_filter filt[] = {
498 {
499 .pgn = J1939_PGN_ADDRESS_CLAIMED,
500 .pgn_mask = J1939_PGN_PDU1_MAX,
501 }, {
502 .pgn = J1939_PGN_REQUEST,
503 .pgn_mask = J1939_PGN_PDU1_MAX,
504 }, {
505 .pgn = J1939_PGN_ADDRESS_COMMANDED,
506 .pgn_mask = J1939_PGN_MAX,
507 },
508 };
509 setsockopt(sock, SOL_CAN_J1939, SO_J1939_FILTER, &filt, sizeof(filt));
510
511 In this example, the socket will only receive messages with the PGNs related to
512 address claiming: ``J1939_PGN_ADDRESS_CLAIMED``, ``J1939_PGN_REQUEST``, and
513 ``J1939_PGN_ADDRESS_COMMANDED``. This is particularly useful in scenarios where
514 you want to monitor and process address claims without being overwhelmed by
515 other traffic on the J1939 network.
516
517 ``SO_J1939_PROMISC``
518 ~~~~~~~~~~~~~~~~~~~~
519
520 The ``SO_J1939_PROMISC`` option enables socket-level promiscuous mode. When
521 this option is enabled, the socket will receive all J1939 traffic, regardless
522 of any filters set by ``bind()`` or ``connect()``. This is analogous to
523 enabling promiscuous mode for an Ethernet interface, where all traffic on the
524 network segment is captured.
525
526 However, **`SO_J1939_FILTER` has a higher priority** compared to
527 ``SO_J1939_PROMISC``. This means that even in promiscuous mode, you can reduce
528 the number of packets received by applying specific filters with
529 `SO_J1939_FILTER`. The filters will limit which packets are passed to the
530 socket, allowing for more refined traffic selection while promiscuous mode is
531 active.
532
533 The acceptable value size for this option is ``sizeof(int)``, and the value is
534 only differentiated between `0` and non-zero. A value of `0` disables
535 promiscuous mode, while any non-zero value enables it.
536
537 This combination can be useful for debugging or monitoring specific types of
538 traffic while still capturing a broad set of messages.
539
540 Example:
541
542 .. code-block:: c
543
544 int value = 1;
545 setsockopt(sock, SOL_CAN_J1939, SO_J1939_PROMISC, &value, sizeof(value));
546
547 In this example, setting ``value`` to any non-zero value (e.g., `1`) enables
548 promiscuous mode, allowing the socket to receive all J1939 traffic on the
549 network.
550
551 ``SO_BROADCAST``
552 ~~~~~~~~~~~~~~~~
553
554 The ``SO_BROADCAST`` option enables the sending and receiving of broadcast
555 messages. By default, broadcast messages are disabled for J1939 sockets. When
556 this option is enabled, the socket will be allowed to send and receive
557 broadcast packets on the J1939 network.
558
559 Due to the nature of the CAN bus as a shared medium, all messages transmitted
560 on the bus are visible to all participants. In the context of J1939,
561 broadcasting refers to using a specific destination address field, where the
562 destination address is set to a value that indicates the message is intended
563 for all participants (usually a global address such as 0xFF). Enabling the
564 broadcast option allows the socket to send and receive such broadcast messages.
565
566 The acceptable value size for this option is ``sizeof(int)``, and the value is
567 only differentiated between `0` and non-zero. A value of `0` disables the
568 ability to send and receive broadcast messages, while any non-zero value
569 enables it.
570
571 Example:
572
573 .. code-block:: c
574
575 int value = 1;
576 setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &value, sizeof(value));
577
578 In this example, setting ``value`` to any non-zero value (e.g., `1`) enables
579 the socket to send and receive broadcast messages.
580
581 ``SO_J1939_SEND_PRIO``
582 ~~~~~~~~~~~~~~~~~~~~~~
583
584 The ``SO_J1939_SEND_PRIO`` option sets the priority of outgoing J1939 messages
585 for the socket. In J1939, messages can have different priorities, and lower
586 numerical values indicate higher priority. This option allows the user to
587 control the priority of messages sent from the socket by adjusting the priority
588 bits in the CAN identifier.
589
590 The acceptable value **size** for this option is ``sizeof(int)``, and the value
591 is expected to be in the range of 0 to 7, where `0` is the highest priority,
592 and `7` is the lowest. By default, the priority is set to `6` if this option is
593 not explicitly configured.
594
595 Note that the priority values `0` and `1` can only be set if the process has
596 the `CAP_NET_ADMIN` capability. These are reserved for high-priority traffic
597 and require administrative privileges.
598
599 Example:
600
601 .. code-block:: c
602
603 int prio = 3; // Priority value between 0 (highest) and 7 (lowest)
604 setsockopt(sock, SOL_CAN_J1939, SO_J1939_SEND_PRIO, &prio, sizeof(prio));
605
606 In this example, the priority is set to `3`, meaning the outgoing messages will
607 be sent with a moderate priority level.
608
609 ``SO_J1939_ERRQUEUE``
610 ~~~~~~~~~~~~~~~~~~~~~
611
612 The ``SO_J1939_ERRQUEUE`` option enables the socket to receive error messages
613 from the error queue, providing diagnostic information about transmission
614 failures, protocol violations, or other issues that occur during J1939
615 communication. Once this option is set, user space is required to handle
616 ``MSG_ERRQUEUE`` messages.
617
618 Setting ``SO_J1939_ERRQUEUE`` to ``0`` will purge any currently present error
619 messages in the error queue. When enabled, error messages can be retrieved
620 using the ``recvmsg(2)`` system call.
621
622 When subscribing to the error queue, the following error events can be
623 accessed:
624
625 - **``J1939_EE_INFO_TX_ABORT``**: Transmission abort errors.
626 - **``J1939_EE_INFO_RX_RTS``**: Reception of RTS (Request to Send) control
627 frames.
628 - **``J1939_EE_INFO_RX_DPO``**: Reception of data packets with Data Page Offset
629 (DPO).
630 - **``J1939_EE_INFO_RX_ABORT``**: Reception abort errors.
631
632 The error queue can be used to correlate errors with specific message transfer
633 sessions using the session ID (``tskey``). The session ID is assigned via the
634 ``SOF_TIMESTAMPING_OPT_ID`` flag, which is set by enabling the
635 ``SO_TIMESTAMPING`` option.
636
637 If ``SO_J1939_ERRQUEUE`` is activated, the user is required to pull messages
638 from the error queue, meaning that using plain ``recv(2)`` is not sufficient
639 anymore. The user must use ``recvmsg(2)`` with appropriate flags to handle
640 error messages. Failure to do so can result in the socket becoming blocked with
641 unprocessed error messages in the queue.
642
643 It is **recommended** that ``SO_J1939_ERRQUEUE`` be used in combination with
644 ``SO_TIMESTAMPING`` in most cases. This enables proper error handling along
645 with session tracking and timestamping, providing a more detailed analysis of
646 message transfers and errors.
647
648 The acceptable value **size** for this option is ``sizeof(int)``, and the value
649 is only differentiated between ``0`` and non-zero. A value of ``0`` disables
650 error queue reception and purges any existing error messages, while any
651 non-zero value enables it.
652
653 Example:
654
655 .. code-block:: c
656
657 int enable = 1; // Enable error queue reception
658 setsockopt(sock, SOL_CAN_J1939, SO_J1939_ERRQUEUE, &enable, sizeof(enable));
659
660 // Enable timestamping with session tracking via tskey
661 int timestamping = SOF_TIMESTAMPING_OPT_ID | SOF_TIMESTAMPING_TX_ACK |
662 SOF_TIMESTAMPING_TX_SCHED |
663 SOF_TIMESTAMPING_RX_SOFTWARE | SOF_TIMESTAMPING_OPT_CMSG;
664 setsockopt(sock, SOL_SOCKET, SO_TIMESTAMPING, &timestamping,
665 sizeof(timestamping));
666
667 When enabled, error messages can be retrieved using ``recvmsg(2)``. By
668 combining ``SO_J1939_ERRQUEUE`` with ``SO_TIMESTAMPING`` (with
669 ``SOF_TIMESTAMPING_OPT_ID`` and ``SOF_TIMESTAMPING_OPT_CMSG`` enabled), the
670 user can track message transfers, retrieve precise timestamps, and correlate
671 errors with specific sessions.
672
673 For more information on enabling timestamps and session tracking, refer to the
674 `SO_TIMESTAMPING` section.
675
676 ``SO_TIMESTAMPING``
677 ~~~~~~~~~~~~~~~~~~~
678
679 The ``SO_TIMESTAMPING`` option allows the socket to receive timestamps for
680 various events related to message transmissions and receptions in J1939. This
681 option is often used in combination with ``SO_J1939_ERRQUEUE`` to provide
682 detailed diagnostic information, session tracking, and precise timing data for
683 message transfers.
684
685 In J1939, all payloads provided by user space, regardless of size, are
686 processed by the kernel as **sessions**. This includes both single-frame
687 messages (up to 8 bytes) and multi-frame protocols such as the Transport
688 Protocol (TP) and Extended Transport Protocol (ETP). Even for small,
689 single-frame messages, the kernel creates a session to manage the transmission
690 and reception. The concept of sessions allows the kernel to manage various
691 aspects of the protocol, such as reassembling multi-frame messages and tracking
692 the status of transmissions.
693
694 When receiving extended error messages from the error queue, the error
695 information is delivered through a `struct sock_extended_err`, accessible via
696 the control message (``cmsg``) retrieved using the ``recvmsg(2)`` system call.
697
698 There are two typical origins for the extended error messages in J1939:
699
700 1. ``serr->ee_origin == SO_EE_ORIGIN_TIMESTAMPING``:
701
702 In this case, the `serr->ee_info` field will contain one of the following
703 timestamp types:
704
705 - ``SCM_TSTAMP_SCHED``: This timestamp is valid for Extended Transport
706 Protocol (ETP) transfers and simple transfers (8 bytes or less). It
707 indicates when a message or set of frames has been scheduled for
708 transmission.
709
710 - For simple transfers (8 bytes or less), it marks the point when the
711 message is queued and ready to be sent onto the CAN bus.
712
713 - For ETP transfers, it is sent after receiving a CTS (Clear to Send)
714 frame on the sender side, indicating that a new set of frames has been
715 scheduled for transmission.
716
717 - The Transport Protocol (TP) case is currently not implemented for this
718 timestamp.
719
720 - On the receiver side, the counterpart to this event for ETP is
721 represented by the ``J1939_EE_INFO_RX_DPO`` message, which indicates the
722 reception of a Data Page Offset (DPO) control frame.
723
724 - ``SCM_TSTAMP_ACK``: This timestamp indicates the acknowledgment of the
725 message or session.
726
727 - For simple transfers (8 bytes or less), it marks when the message has
728 been sent and an echo confirmation has been received from the CAN
729 controller, indicating that the frame was transmitted onto the bus.
730
731 - For multi-frame transfers (TP or ETP), it signifies that the entire
732 session has been acknowledged, typically after receiving the End of
733 Message Acknowledgment (EOMA) packet.
734
735 2. ``serr->ee_origin == SO_EE_ORIGIN_LOCAL``:
736
737 In this case, the `serr->ee_info` field will contain one of the following
738 J1939 stack-specific message types:
739
740 - ``J1939_EE_INFO_TX_ABORT``: This message indicates that the transmission
741 of a message or session was aborted. The cause of the abort can come from
742 various sources:
743
744 - **CAN stack failure**: The J1939 stack was unable to pass the frame to
745 the CAN framework for transmission.
746
747 - **Echo failure**: The J1939 stack did not receive an echo confirmation
748 from the CAN controller, meaning the frame may not have been successfully
749 transmitted to the CAN bus.
750
751 - **Protocol-level issues**: For multi-frame transfers (TP/ETP), this
752 could include protocol-related errors, such as an abort signaled by the
753 receiver or a timeout at the protocol level, which causes the session to
754 terminate prematurely.
755
756 - The corresponding error code is stored in ``serr->ee_data``
757 (``session->err`` on kernel side), providing additional details about
758 the specific reason for the abort.
759
760 - ``J1939_EE_INFO_RX_RTS``: This message indicates that the J1939 stack has
761 received a Request to Send (RTS) control frame, signaling the start of a
762 multi-frame transfer using the Transport Protocol (TP) or Extended
763 Transport Protocol (ETP).
764
765 - It informs the receiver that the sender is ready to transmit a
766 multi-frame message and includes details about the total message size
767 and the number of frames to be sent.
768
769 - Statistics such as ``J1939_NLA_TOTAL_SIZE``, ``J1939_NLA_PGN``,
770 ``J1939_NLA_SRC_NAME``, and ``J1939_NLA_DEST_NAME`` are provided along
771 with the ``J1939_EE_INFO_RX_RTS`` message, giving detailed information
772 about the incoming transfer.
773
774 - ``J1939_EE_INFO_RX_DPO``: This message indicates that the J1939 stack has
775 received a Data Page Offset (DPO) control frame, which is part of the
776 Extended Transport Protocol (ETP).
777
778 - The DPO frame signals the continuation of an ETP multi-frame message by
779 indicating the offset position in the data being transferred. It helps
780 the receiver manage large data sets by identifying which portion of the
781 message is being received.
782
783 - It is typically paired with a corresponding ``SCM_TSTAMP_SCHED`` event
784 on the sender side, which indicates when the next set of frames is
785 scheduled for transmission.
786
787 - This event includes statistics such as ``J1939_NLA_BYTES_ACKED``, which
788 tracks the number of bytes acknowledged up to that point in the session.
789
790 - ``J1939_EE_INFO_RX_ABORT``: This message indicates that the reception of a
791 multi-frame message (Transport Protocol or Extended Transport Protocol) has
792 been aborted.
793
794 - The abort can be triggered by protocol-level errors such as timeouts, an
795 unexpected frame, or a specific abort request from the sender.
796
797 - This message signals that the receiver cannot continue processing the
798 transfer, and the session is terminated.
799
800 - The corresponding error code is stored in ``serr->ee_data``
801 (``session->err`` on kernel side ), providing further details about the
802 reason for the abort, such as protocol violations or timeouts.
803
804 - After receiving this message, the receiver discards the partially received
805 frames, and the multi-frame session is considered incomplete.
806
807 In both cases, if ``SOF_TIMESTAMPING_OPT_ID`` is enabled, ``serr->ee_data``
808 will be set to the session’s unique identifier (``session->tskey``). This
809 allows user space to track message transfers by their session identifier across
810 multiple frames or stages.
811
812 In all other cases, ``serr->ee_errno`` will be set to ``ENOMSG``, except for
813 the ``J1939_EE_INFO_TX_ABORT`` and ``J1939_EE_INFO_RX_ABORT`` cases, where the
814 kernel sets ``serr->ee_data`` to the error stored in ``session->err``. All
815 protocol-specific errors are converted to standard kernel error values and
816 stored in ``session->err``. These error values are unified across system calls
817 and ``serr->ee_errno``. Some of the known error values are described in the
818 `Error Codes in the J1939 Stack` section.
819
820 When the `J1939_EE_INFO_RX_RTS` message is provided, it will include the
821 following statistics for multi-frame messages (TP and ETP):
822
823 - ``J1939_NLA_TOTAL_SIZE``: Total size of the message in the session.
824 - ``J1939_NLA_PGN``: Parameter Group Number (PGN) identifying the message type.
825 - ``J1939_NLA_SRC_NAME``: 64-bit name of the source ECU.
826 - ``J1939_NLA_DEST_NAME``: 64-bit name of the destination ECU.
827 - ``J1939_NLA_SRC_ADDR``: 8-bit source address of the sending ECU.
828 - ``J1939_NLA_DEST_ADDR``: 8-bit destination address of the receiving ECU.
829
830 - For other messages (including single-frame messages), only the following
831 statistic is included:
832
833 - ``J1939_NLA_BYTES_ACKED``: Number of bytes successfully acknowledged in the
834 session.
835
836 The key flags for ``SO_TIMESTAMPING`` include:
837
838 - ``SOF_TIMESTAMPING_OPT_ID``: Enables the use of a unique session identifier
839 (``tskey``) for each transfer. This identifier helps track message transfers
840 and errors as distinct sessions in user space. When this option is enabled,
841 ``serr->ee_data`` will be set to ``session->tskey``.
842
843 - ``SOF_TIMESTAMPING_OPT_CMSG``: Sends timestamp information through control
844 messages (``struct scm_timestamping``), allowing the application to retrieve
845 timestamps alongside the data.
846
847 - ``SOF_TIMESTAMPING_TX_SCHED``: Provides the timestamp for when a message is
848 scheduled for transmission (``SCM_TSTAMP_SCHED``).
849
850 - ``SOF_TIMESTAMPING_TX_ACK``: Provides the timestamp for when a message
851 transmission is fully acknowledged (``SCM_TSTAMP_ACK``).
852
853 - ``SOF_TIMESTAMPING_RX_SOFTWARE``: Provides timestamps for reception-related
854 events (e.g., ``J1939_EE_INFO_RX_RTS``, ``J1939_EE_INFO_RX_DPO``,
855 ``J1939_EE_INFO_RX_ABORT``).
856
857 These flags enable detailed monitoring of message lifecycles, including
858 transmission scheduling, acknowledgments, reception timestamps, and gathering
859 detailed statistics about the communication session, especially for multi-frame
860 payloads like TP and ETP.
861
862 Example:
863
864 .. code-block:: c
865
866 // Enable timestamping with various options, including session tracking and
867 // statistics
868 int sock_opt = SOF_TIMESTAMPING_OPT_CMSG |
869 SOF_TIMESTAMPING_TX_ACK |
870 SOF_TIMESTAMPING_TX_SCHED |
871 SOF_TIMESTAMPING_OPT_ID |
872 SOF_TIMESTAMPING_RX_SOFTWARE;
873
874 setsockopt(sock, SOL_SOCKET, SO_TIMESTAMPING, &sock_opt, sizeof(sock_opt));
875
876
877
878 Dynamic Addressing
879 ------------------
880
881 Distinction has to be made between using the claimed address and doing an
882 address claim. To use an already claimed address, one has to fill in the
883 ``j1939.name`` member and provide it to ``bind(2)``. If the name had claimed an address
884 earlier, all further messages being sent will use that address. And the
885 ``j1939.addr`` member will be ignored.
886
887 An exception on this is PGN 0x0ee00. This is the "Address Claim/Cannot Claim
888 Address" message and the kernel will use the ``j1939.addr`` member for that PGN if
889 necessary.
890
891 To claim an address following code example can be used:
892
893 .. code-block:: C
894
895 struct sockaddr_can baddr = {
896 .can_family = AF_CAN,
897 .can_addr.j1939 = {
898 .name = name,
899 .addr = J1939_IDLE_ADDR,
900 .pgn = J1939_NO_PGN, /* to disable bind() rx filter for PGN */
901 },
902 .can_ifindex = if_nametoindex("can0"),
903 };
904
905 bind(sock, (struct sockaddr *)&baddr, sizeof(baddr));
906
907 /* for Address Claiming broadcast must be allowed */
908 int value = 1;
909 setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &value, sizeof(value));
910
911 /* configured advanced RX filter with PGN needed for Address Claiming */
912 const struct j1939_filter filt[] = {
913 {
914 .pgn = J1939_PGN_ADDRESS_CLAIMED,
915 .pgn_mask = J1939_PGN_PDU1_MAX,
916 }, {
917 .pgn = J1939_PGN_REQUEST,
918 .pgn_mask = J1939_PGN_PDU1_MAX,
919 }, {
920 .pgn = J1939_PGN_ADDRESS_COMMANDED,
921 .pgn_mask = J1939_PGN_MAX,
922 },
923 };
924
925 setsockopt(sock, SOL_CAN_J1939, SO_J1939_FILTER, &filt, sizeof(filt));
926
927 uint64_t dat = htole64(name);
928 const struct sockaddr_can saddr = {
929 .can_family = AF_CAN,
930 .can_addr.j1939 = {
931 .pgn = J1939_PGN_ADDRESS_CLAIMED,
932 .addr = J1939_NO_ADDR,
933 },
934 };
935
936 /* Afterwards do a sendto(2) with data set to the NAME (Little Endian). If the
937 * NAME provided, does not match the j1939.name provided to bind(2), EPROTO
938 * will be returned.
939 */
940 sendto(sock, dat, sizeof(dat), 0, (const struct sockaddr *)&saddr, sizeof(saddr));
941
942 If no-one else contests the address claim within 250ms after transmission, the
943 kernel marks the NAME-SA assignment as valid. The valid assignment will be kept
944 among other valid NAME-SA assignments. From that point, any socket bound to the
945 NAME can send packets.
946
947 If another ECU claims the address, the kernel will mark the NAME-SA expired.
948 No socket bound to the NAME can send packets (other than address claims). To
949 claim another address, some socket bound to NAME, must ``bind(2)`` again, but with
950 only ``j1939.addr`` changed to the new SA, and must then send a valid address claim
951 packet. This restarts the state machine in the kernel (and any other
952 participant on the bus) for this NAME.
953
954 ``can-utils`` also include the ``j1939acd`` tool, so it can be used as code example or as
955 default Address Claiming daemon.
956
957 Send Examples
958 -------------
959
960 Static Addressing
961 ^^^^^^^^^^^^^^^^^
962
963 This example will send a PGN (0x12300) from SA 0x20 to DA 0x30.
964
965 Bind:
966
967 .. code-block:: C
968
969 struct sockaddr_can baddr = {
970 .can_family = AF_CAN,
971 .can_addr.j1939 = {
972 .name = J1939_NO_NAME,
973 .addr = 0x20,
974 .pgn = J1939_NO_PGN,
975 },
976 .can_ifindex = if_nametoindex("can0"),
977 };
978
979 bind(sock, (struct sockaddr *)&baddr, sizeof(baddr));
980
981 Now, the socket 'sock' is bound to the SA 0x20. Since no ``connect(2)`` was called,
982 at this point we can use only ``sendto(2)`` or ``sendmsg(2)``.
983
984 Send:
985
986 .. code-block:: C
987
988 const struct sockaddr_can saddr = {
989 .can_family = AF_CAN,
990 .can_addr.j1939 = {
991 .name = J1939_NO_NAME;
992 .addr = 0x30,
993 .pgn = 0x12300,
994 },
995 };
996
997 sendto(sock, dat, sizeof(dat), 0, (const struct sockaddr *)&saddr, sizeof(saddr));
998
999
1000 Error Codes in the J1939 Stack
1001 ------------------------------
1003 This section lists all potential kernel error codes that can be exposed to user
1004 space when interacting with the J1939 stack. It includes both standard error
1005 codes and those derived from protocol-specific abort codes.
1007 - ``EAGAIN``: Operation would block; retry may succeed. One common reason is
1008 that an active TP or ETP session exists, and an attempt was made to start a
1009 new overlapping TP or ETP session between the same peers.
1011 - ``ENETDOWN``: Network is down. This occurs when the CAN interface is switched
1012 to the "down" state.
1014 - ``ENOBUFS``: No buffer space available. This error occurs when the CAN
1015 interface's transmit (TX) queue is full, and no more messages can be queued.
1017 - ``EOVERFLOW``: Value too large for defined data type. In J1939, this can
1018 happen if the requested data lies outside of the queued buffer. For example,
1019 if a CTS (Clear to Send) requests an offset not available in the kernel buffer
1020 because user space did not provide enough data.
1022 - ``EBUSY``: Device or resource is busy. For example, this occurs if an
1023 identical session is already active and the stack is unable to recover from
1024 the condition.
1026 - ``EACCES``: Permission denied. This error can occur, for example, when
1027 attempting to send broadcast messages, but the socket is not configured with
1028 ``SO_BROADCAST``.
1030 - ``EADDRNOTAVAIL``: Address not available. This error occurs in cases such as:
1032 - When attempting to use ``getsockname(2)`` to retrieve the peer's address,
1033 but the socket is not connected.
1035 - When trying to send data to or from a NAME, but address claiming for the
1036 NAME was not performed or detected by the stack.
1038 - ``EBADFD``: File descriptor in bad state. This error can occur if:
1040 - Attempting to send data to an unbound socket.
1042 - The socket is bound but has no source name, and the source address is
1043 ``J1939_NO_ADDR``.
1045 - The ``can_ifindex`` is incorrect.
1047 - ``EFAULT``: Bad address. Occurs mostly when the stack can't copy from or to a
1048 sockptr, when there is insufficient data from user space, or when the buffer
1049 provided by user space is not large enough for the requested data.
1051 - ``EINTR``: A signal occurred before any data was transmitted; see ``signal(7)``.
1053 - ``EINVAL``: Invalid argument passed. For example:
1055 - ``msg->msg_namelen`` is less than ``J1939_MIN_NAMELEN``.
1057 - ``addr->can_family`` is not equal to ``AF_CAN``.
1059 - An incorrect PGN was provided.
1061 - ``ENODEV``: No such device. This happens when the CAN network device cannot
1062 be found for the provided ``can_ifindex`` or if ``can_ifindex`` is 0.
1064 - ``ENOMEM``: Out of memory. Typically related to issues with memory allocation
1065 in the stack.
1067 - ``ENOPROTOOPT``: Protocol not available. This can occur when using
1068 ``getsockopt(2)`` or ``setsockopt(2)`` if the requested socket option is not
1069 available.
1071 - ``EDESTADDRREQ``: Destination address required. This error occurs:
1073 - In the case of ``connect(2)``, if the ``struct sockaddr *uaddr`` is ``NULL``.
1075 - In the case of ``send*(2)``, if there is an attempt to send an ETP message
1076 to a broadcast address.
1078 - ``EDOM``: Argument out of domain. This error may happen if attempting to send
1079 a TP or ETP message to a PGN that is reserved for control PGNs for TP or ETP
1080 operations.
1082 - ``EIO``: I/O error. This can occur if the amount of data provided to the
1083 socket for a TP or ETP session does not match the announced amount of data for
1084 the session.
1086 - ``ENOENT``: No such file or directory. This can happen when the stack
1087 attempts to transfer CTS or EOMA but cannot find a matching receiving socket
1088 anymore.
1090 - ``ENOIOCTLCMD``: No ioctls are available for the socket layer.
1092 - ``EPERM``: Operation not permitted. For example, this can occur if a
1093 requested action requires ``CAP_NET_ADMIN`` privileges.
1095 - ``ENETUNREACH``: Network unreachable. Most likely, this occurs when frames
1096 cannot be transmitted to the CAN bus.
1098 - ``ETIME``: Timer expired. This can happen if a timeout occurs while
1099 attempting to send a simple message, for example, when an echo message from
1100 the controller is not received.
1102 - ``EPROTO``: Protocol error.
1104 - Used for various protocol-level errors in J1939, including:
1106 - Duplicate sequence number.
1108 - Unexpected EDPO or ECTS packet.
1110 - Invalid PGN or offset in EDPO/ECTS.
1112 - Number of EDPO packets exceeded CTS allowance.
1114 - Any other protocol-level error.
1116 - ``EMSGSIZE``: Message too long.
1118 - ``ENOMSG``: No message available.
1120 - ``EALREADY``: The ECU is already engaged in one or more connection-managed
1121 sessions and cannot support another.
1123 - ``EHOSTUNREACH``: A timeout occurred, and the session was aborted.
1125 - ``EBADMSG``: CTS (Clear to Send) messages were received during an active data
1126 transfer, causing an abort.
1128 - ``ENOTRECOVERABLE``: The maximum retransmission request limit was reached,
1129 and the session cannot recover.
1131 - ``ENOTCONN``: An unexpected data transfer packet was received.
1133 - ``EILSEQ``: A bad sequence number was received, and the software could not
1134 recover.

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

개요와 적용 규격

1-24

SAE J1939는 CAN 위에서 동작하는 상위 계층 프로토콜입니다. 기본 CAN보다 정교한 주소 지정 방식을 제공하고 최대 패킷 크기를 8바이트보다 크게 확장합니다. MilCAN A, NMEA2000, ISO-11783(ISOBUS)처럼 응용 계층이 달라진 파생 규격도 있으며, 이 구현에는 ISO-11783의 ETP(Extended Transport Protocol)가 포함됩니다. 따라서 최대 패킷 크기는 `((2 ^ 24) - 1) * 7`바이트, 즉 111MiB입니다.

이 구현이 참조하는 규격은 데이터 링크 계층을 정의하는 SAE J1939-21, 네트워크 관리를 정의하는 SAE J1939-81, Virtual Terminal과 ETP를 정의하는 ISO 11783-6입니다.

.. SPDX-License-Identifier: (GPL-2.0 OR MIT)

===================
J1939 Documentation
===================

Overview / What Is J1939
========================

SAE J1939 defines a higher layer protocol on CAN. It implements a more
sophisticated addressing scheme and extends the maximum packet size above 8
bytes. Several derived specifications exist, which differ from the original
J1939 on the application level, like MilCAN A, NMEA2000, and especially
ISO-11783 (ISOBUS). This last one specifies the so-called ETP (Extended
Transport Protocol), which has been included in this implementation. This
results in a maximum packet size of ((2 ^ 24) - 1) * 7 bytes == 111 MiB.

Specifications used
-------------------

* SAE J1939-21 : data link layer
* SAE J1939-81 : network management
* ISO 11783-6  : Virtual Terminal (Extended Transport Protocol)

커널 구현의 필요성

25-64

SocketCAN에 BSD 소켓과 비슷한 API가 이미 있지만, J1939의 주소 지정과 전송 방식은 커널에서 처리할 이유가 있습니다. 한 ECU 안의 여러 프로세스가 모두 자기 소스 주소를 따로 관리하지 않고, 주소를 아는 한 프로세스가 확보한 ECU 주소를 다른 프로세스도 재사용할 수 있습니다. 이는 프로그램마다 한 가지 역할에 집중한다는 UNIX 방식과도 맞습니다.

J1939 Address Claiming은 시간 제약이 강하고 주소 협상 중의 데이터 전송도 일관되게 처리해야 합니다. 이를 커널에 두면 모든 사용자 공간 프로그램이 같은 상태 기계와 타이밍을 각각 구현할 필요가 없고, 버스 전체에서 주소 상태가 일관되게 유지됩니다.

TP와 ETP는 큰 패킷을 전달할 때 공통 PGN을 재사용합니다. 서로 모르는 여러 프로세스가 같은 제어 PGN을 사용할 수 있으므로 개별 TP/ETP 세션을 직렬화해야 하며, 커널이 이 동기화를 담당합니다. 반면 relay, gateway, fast packet transport처럼 커널 구현이 프로토콜 안정성에 직접 기여하지 않는 기능은 사용자 공간에 남깁니다.

J1939 소켓은 CAN 네트워크 장치에서 동작하며 CAN raw 소켓 기반 사용자 공간 라이브러리와 공존할 수 있습니다. 다만 두 구현은 서로 상태를 공유하지 않으므로 같은 ECU 주소를 동시에 사용하면 안 됩니다. 하나의 실제 또는 가상 ECU 주소는 사용자 공간 라이브러리나 커널 J1939 스택 중 한쪽이 독점해야 합니다.

.. _j1939-motivation:

Motivation
==========

Given the fact there's something like SocketCAN with an API similar to BSD
sockets, we found some reasons to justify a kernel implementation for the
addressing and transport methods used by J1939.

* **Addressing:** when a process on an ECU communicates via J1939, it should
  not necessarily know its source address. Although, at least one process per
  ECU should know the source address. Other processes should be able to reuse
  that address. This way, address parameters for different processes
  cooperating for the same ECU, are not duplicated. This way of working is
  closely related to the UNIX concept, where programs do just one thing and do
  it well.

* **Dynamic addressing:** Address Claiming in J1939 is time critical.
  Furthermore, data transport should be handled properly during the address
  negotiation. Putting this functionality in the kernel eliminates it as a
  requirement for _every_ user space process that communicates via J1939. This
  results in a consistent J1939 bus with proper addressing.

* **Transport:** both TP & ETP reuse some PGNs to relay big packets over them.
  Different processes may thus use the same TP & ETP PGNs without actually
  knowing it. The individual TP & ETP sessions _must_ be serialized
  (synchronized) between different processes. The kernel solves this problem
  properly and eliminates the serialization (synchronization) as a requirement
  for _every_ user space process that communicates via J1939.

J1939 defines some other features (relaying, gateway, fast packet transport,
...). In-kernel code for these would not contribute to protocol stability.
Therefore, these parts are left to user space.

The J1939 sockets operate on CAN network devices (see SocketCAN). Any J1939
user space library operating on CAN raw sockets will still operate properly.
Since such a library does not communicate with the in-kernel implementation, care
must be taken that these two do not interfere. In practice, this means they
cannot share ECU addresses. A single ECU (or virtual ECU) address is used by
the library exclusively, or by the in-kernel system exclusively.

페이로드 크기와 전송 방식

65-151

사용자 공간이 J1939 스택에 넘기는 버퍼는 CAN 프레임 자체가 아니라 페이로드입니다. 스택은 버퍼 크기와 전송 종류에 따라 올바른 CAN 프레임을 만들고, 큰 페이로드는 자동으로 분할하고 수신 측에서 재조립합니다.

8바이트 이하는 내부적으로 simple session으로 처리되어 단일 CAN 프레임이 되며 실제 수신자가 없어도 전송할 수 있습니다. 1,785바이트 이하는 J1939 TP로 처리되어 여러 8바이트 CAN 프레임으로 나뉩니다. TP broadcast는 수신자가 없어도 되지만 TP unicast는 상대가 전송을 확인해야 합니다.

1,786바이트부터 111MiB까지는 ISO 11783 ETP를 사용합니다. ETP는 항상 unicast이며, 수신자가 각 전송 단계를 처리하고 확인해야 합니다. TP와 달리 ETP broadcast는 지원하지 않습니다.

`MSG_DONTWAIT`를 지정하면 스택은 소켓에 사용 가능한 메모리만큼만 데이터를 받아들이고 실제로 받은 바이트 수를 반환할 수 있습니다. 사용자 공간은 부분 전송 뒤 남은 데이터를 직접 처리해야 하며, 비차단 전송의 실패를 통지받으려면 `SO_J1939_ERRQUEUE`를 활성화하고 오류 큐를 소비해야 합니다.

페이로드 크기별 전송
크기방식broadcast수신자 필요
0~8바이트Simple / 단일 CAN 프레임가능아니요
9~1,785바이트TP가능unicast만 필요
1,786바이트~111MiBETP불가항상 필요

버퍼 크기에 따라 커널이 선택하는 세션과 수신자 요구 조건입니다.


J1939 concepts
==============

Data Sent to the J1939 Stack
----------------------------

The data buffers sent to the J1939 stack from user space are not CAN frames
themselves. Instead, they are payloads that the J1939 stack converts into
proper CAN frames based on the size of the buffer and the type of transfer. The
size of the buffer influences how the stack processes the data and determines
the internal code path used for the transfer.

**Handling of Different Buffer Sizes:**

- **Buffers with a size of 8 bytes or less:**

  - These are handled as simple sessions internally within the stack.

  - The stack converts the buffer directly into a single CAN frame without
    fragmentation.

  - This type of transfer does not require an actual client (receiver) on the
    receiving side.

- **Buffers up to 1785 bytes:**

  - These are automatically handled as J1939 Transport Protocol (TP) transfers.

  - Internally, the stack splits the buffer into multiple 8-byte CAN frames.

  - TP transfers can be unicast or broadcast.

  - **Broadcast TP:** Does not require a receiver on the other side and can be
    used in broadcast scenarios.

  - **Unicast TP:** Requires an active receiver (client) on the other side to
    acknowledge the transfer.

- **Buffers from 1786 bytes up to 111 MiB:**

  - These are handled as ISO 11783 Extended Transport Protocol (ETP) transfers.

  - ETP transfers are used for larger payloads and are split into multiple CAN
    frames internally.

  - **ETP transfers (unicast):** Require a receiver on the other side to
    process the incoming data and acknowledge each step of the transfer.

  - ETP transfers cannot be broadcast like TP transfers, and always require a
    receiver for operation.

**Non-Blocking Operation with `MSG_DONTWAIT`:**

The J1939 stack supports non-blocking operation when used in combination with
the `MSG_DONTWAIT` flag. In this mode, the stack attempts to take as much data
as the available memory for the socket allows. It returns the amount of data
that was successfully taken, and it is the responsibility of user space to
monitor this value and handle partial transfers.

- If the stack cannot take the entire buffer, it returns the number of bytes
  successfully taken, and user space should handle the remainder.

- **Error handling:** When using `MSG_DONTWAIT`, the user must rely on the
  error queue to detect transfer errors. See the **SO_J1939_ERRQUEUE** section
  for details on how to subscribe to error notifications. Without the error
  queue, there is no other way for user space to be notified of transfer errors
  during non-blocking operations.

**Behavior and Requirements:**

- **Simple transfers (<= 8 bytes):** Do not require a receiver on the other
  side, making them easy to send without needing address claiming or
  coordination with a destination.

- **Unicast TP/ETP:** Requires a receiver on the other side to complete the
  transfer. The receiver must acknowledge the transfer for the session to
  proceed successfully.

- **Broadcast TP:** Allows sending data without a receiver, but only works for
  TP transfers. ETP cannot be broadcast and always needs a receiving client.

These different behaviors depend heavily on the size of the buffer provided to
the stack, and the appropriate transport mechanism (TP or ETP) is selected
based on the payload size. The stack automatically manages the fragmentation
and reassembly of large payloads and ensures that the correct CAN frames are
generated and transmitted for each session.

29비트 CAN ID와 PGN

152-215

J1939의 29비트 CAN 식별자는 비트 28~26의 Priority, 비트 25~8의 PGN, 비트 7~0의 SA(Source Address)로 구성됩니다. PGN은 패킷 종류를 식별하며 R(Reserved), DP(Data Page), PF(PDU Format), PS(PDU Specific) 필드를 포함합니다.

PDU1은 `PF < 240`인 peer-to-peer 형식입니다. 이때 PS는 목적지 주소 DA이며 PGN의 일부가 아닙니다. 따라서 사용자 공간과 커널 사이에서 PDU1 PGN을 전달할 때 PS 비트는 0이어야 하고 목적지 주소는 별도 필드에 둡니다. 커널이 DA를 29비트 CAN ID의 해당 위치에 넣거나 꺼냅니다.

PDU2는 `PF >= 240`인 global/broadcast 형식입니다. 이 경우 PS는 Group Extension(GE)이며 PGN의 일부입니다. 그러므로 PDU2에서는 PS 값을 PGN에 포함해 지정합니다.

J1939 식별자 구성
구조상위 필드중간 필드하위 필드
29비트 CAN IDPriority: 28~26PGN: 25~8SA: 7~0
PGNR: 25 / DP: 24PF: 23~16PS: 15~8
PDU1PF 00h~EFhPS=DADA는 PGN 밖
PDU2PF F0h~FFhPS=GEGE는 PGN 안

원문의 표를 필드 관계가 드러나도록 정리했습니다.


PGN
---

The J1939 protocol uses the 29-bit CAN identifier with the following structure:

  ============  ==============  ====================
  29 bit CAN-ID
  --------------------------------------------------
  Bit positions within the CAN-ID
  --------------------------------------------------
  28 ... 26     25 ... 8        7 ... 0
  ============  ==============  ====================
  Priority      PGN             SA (Source Address)
  ============  ==============  ====================

The PGN (Parameter Group Number) is a number to identify a packet. The PGN
is composed as follows:

  ============  ==============  =================  =================
  PGN
  ------------------------------------------------------------------
  Bit positions within the CAN-ID
  ------------------------------------------------------------------
  25            24              23 ... 16          15 ... 8
  ============  ==============  =================  =================
  R (Reserved)  DP (Data Page)  PF (PDU Format)    PS (PDU Specific)
  ============  ==============  =================  =================

In J1939-21 distinction is made between PDU1 format (where PF < 240) and PDU2
format (where PF >= 240). Furthermore, when using the PDU2 format, the PS-field
contains a so-called Group Extension, which is part of the PGN. When using PDU2
format, the Group Extension is set in the PS-field.

  ==============  ========================
  PDU1 Format (specific) (peer to peer)
  ----------------------------------------
  Bit positions within the CAN-ID
  ----------------------------------------
  23 ... 16       15 ... 8
  ==============  ========================
  00h ... EFh     DA (Destination address)
  ==============  ========================

  ==============  ========================
  PDU2 Format (global) (broadcast)
  ----------------------------------------
  Bit positions within the CAN-ID
  ----------------------------------------
  23 ... 16       15 ... 8
  ==============  ========================
  F0h ... FFh     GE (Group Extension)
  ==============  ========================

On the other hand, when using PDU1 format, the PS-field contains a so-called
Destination Address, which is _not_ part of the PGN. When communicating a PGN
from user space to kernel (or vice versa) and PDU1 format is used, the PS-field
of the PGN shall be set to zero. The Destination Address shall be set
elsewhere.

Regarding PGN mapping to 29-bit CAN identifier, the Destination Address shall
be get/set from/to the appropriate bits of the identifier by the kernel.

정적·동적 주소 지정과 필터

216-248

정적 주소와 동적 주소를 모두 사용할 수 있습니다. 정적 주소는 커널이 추가 검증하지 않고 올바른 값으로 간주하므로 OEM 또는 시스템 통합자가 충돌 없이 관리해야 합니다.

동적 주소 지정은 Address Claiming으로 처리합니다. J1939에서 ECU는 64비트 NAME으로 식별되며, 주소 확보가 성공하면 커널은 NAME과 확보한 소스 주소의 대응을 추적하고 이를 필터 기반으로 사용합니다. 기본적으로 목적지가 로컬이 아닌 패킷은 거부합니다. 정적 주소에서 동적 주소로, 또는 그 반대로 보내는 혼합 모드도 허용됩니다.

소켓별 whitelist 필터는 SA, `SOURCE_NAME`, PGN을 기준으로 트래픽 일부만 받을 수 있게 합니다. 한 패킷이 같은 소켓의 여러 필터와 동시에 일치해도 해당 소켓에는 한 번만 전달됩니다.

Addressing
----------

Both static and dynamic addressing methods can be used.

For static addresses, no extra checks are made by the kernel and provided
addresses are considered right. This responsibility is for the OEM or system
integrator.

For dynamic addressing, so-called Address Claiming, extra support is foreseen
in the kernel. In J1939 any ECU is known by its 64-bit NAME. At the moment of
a successful address claim, the kernel keeps track of both NAME and source
address being claimed. This serves as a base for filter schemes. By default,
packets with a destination that is not locally will be rejected.

Mixed mode packets (from a static to a dynamic address or vice versa) are
allowed. The BSD sockets define separate API calls for getting/setting the
local & remote address and are applicable for J1939 sockets.

Filtering
---------

J1939 defines white list filters per socket that a user can set in order to
receive a subset of the J1939 traffic. Filtering can be based on:

* SA
* SOURCE_NAME
* PGN

When multiple filters are in place for a single socket, and a packet comes in
that matches several of those filters, the packet is only received once for
that socket.

소켓 생성, bind와 connect

249-337

`<linux/can/j1939.h>`를 포함하고 `socket(PF_CAN, SOCK_DGRAM, CAN_J1939)`로 J1939 datagram 소켓을 만듭니다. J1939의 transport session은 여러 CAN 패킷으로 하나의 패킷을 전달하지만 `SOCK_STREAM`은 지원하지 않습니다. 소켓을 만든 뒤 `bind(2)`와 필요하면 `connect(2)`를 호출하고 일반적인 `read`, `write`, `send*`, `recv*` 계열 호출을 사용합니다.

전송하려면 먼저 `bind(2)`가 성공해 로컬 주소가 정해져 있어야 합니다. 애플리케이션은 헤더 없이 페이로드만 넘기며, 헤더 정보는 `bind`, `connect`, `sendto`, `recvfrom`에 쓰는 `sockaddr_can`에서 얻습니다. 예를 들어 4바이트를 `write`하면 4바이트 J1939 페이로드가 전송됩니다.

`sockaddr_can`의 `can_family`와 `can_ifindex`는 다른 SocketCAN 소켓과 같은 의미입니다. `can_addr.j1939.pgn`은 최대 `0x3ffff`인 PGN, `name`은 64비트 J1939 NAME, `addr`은 주소입니다.

`bind(2)`는 송신 시 소스가 되는 로컬 주소를 지정합니다. 함께 지정한 PGN은 수신 PGN 필터가 되고 ADDR 또는 NAME은 들어오는 패킷의 목적지 필터가 됩니다. NAME 필터는 그 NAME의 Address Claiming이 버스에서 수행되어 커널 캐시에 등록된 경우에만 동작합니다.

`connect(2)`는 원격 목적지와 송신 기본 PGN을 지정합니다. 여기서 지정한 ADDR 또는 NAME은 들어오는 패킷의 소스 필터로도 쓰입니다. `write`와 `send`는 `bind`의 로컬 주소와 `connect`의 원격 주소를 사용하고, `sendto`로 목적지를 덮어쓸 수 있습니다. NAME이 0이 아니면 커널이 NAME에 대응하는 주소를 찾고, NAME이 0이면 `addr`를 직접 사용합니다.

How to Use J1939
================

API Calls
---------

On CAN, you first need to open a socket for communicating over a CAN network.
To use J1939, ``#include <linux/can/j1939.h>``. From there, ``<linux/can.h>`` will be
included too. To open a socket, use:

.. code-block:: C

    s = socket(PF_CAN, SOCK_DGRAM, CAN_J1939);

J1939 does use ``SOCK_DGRAM`` sockets. In the J1939 specification, connections are
mentioned in the context of transport protocol sessions. These still deliver
packets to the other end (using several CAN packets). ``SOCK_STREAM`` is not
supported.

After the successful creation of the socket, you would normally use the ``bind(2)``
and/or ``connect(2)`` system call to bind the socket to a CAN interface. After
binding and/or connecting the socket, you can ``read(2)`` and ``write(2)`` from/to the
socket or use ``send(2)``, ``sendto(2)``, ``sendmsg(2)`` and the ``recv*()`` counterpart
operations on the socket as usual. There are also J1939 specific socket options
described below.

In order to send data, a ``bind(2)`` must have been successful. ``bind(2)`` assigns a
local address to a socket.

Different from CAN is that the payload data is just the data that get sends,
without its header info. The header info is derived from the sockaddr supplied
to ``bind(2)``, ``connect(2)``, ``sendto(2)`` and ``recvfrom(2)``. A ``write(2)`` with size 4 will
result in a packet with 4 bytes.

The sockaddr structure has extensions for use with J1939 as specified below:

.. code-block:: C

      struct sockaddr_can {
         sa_family_t can_family;
         int         can_ifindex;
         union {
            struct {
               __u64 name;
                        /* pgn:
                         * 8 bit: PS in PDU2 case, else 0
                         * 8 bit: PF
                         * 1 bit: DP
                         * 1 bit: reserved
                         */
               __u32 pgn;
               __u8  addr;
            } j1939;
         } can_addr;
      }

``can_family`` & ``can_ifindex`` serve the same purpose as for other SocketCAN sockets.

``can_addr.j1939.pgn`` specifies the PGN (max 0x3ffff). Individual bits are
specified above.

``can_addr.j1939.name`` contains the 64-bit J1939 NAME.

``can_addr.j1939.addr`` contains the address.

The ``bind(2)`` system call assigns the local address, i.e. the source address when
sending packages. If a PGN during ``bind(2)`` is set, it's used as a RX filter.
I.e. only packets with a matching PGN are received. If an ADDR or NAME is set
it is used as a receive filter, too. It will match the destination NAME or ADDR
of the incoming packet. The NAME filter will work only if appropriate Address
Claiming for this name was done on the CAN bus and registered/cached by the
kernel.

On the other hand ``connect(2)`` assigns the remote address, i.e. the destination
address. The PGN from ``connect(2)`` is used as the default PGN when sending
packets. If ADDR or NAME is set it will be used as the default destination ADDR
or NAME. Further a set ADDR or NAME during ``connect(2)`` is used as a receive
filter. It will match the source NAME or ADDR of the incoming packet.

Both ``write(2)`` and ``send(2)`` will send a packet with local address from ``bind(2)`` and the
remote address from ``connect(2)``. Use ``sendto(2)`` to overwrite the destination
address.

If ``can_addr.j1939.name`` is set (!= 0) the NAME is looked up by the kernel and
the corresponding ADDR is used. If ``can_addr.j1939.name`` is not set (== 0),
``can_addr.j1939.addr`` is used.

When creating a socket, reasonable defaults are set. Some options can be
modified with ``setsockopt(2)`` & ``getsockopt(2)``.

RX/TX 경로 옵션과 메시지 플래그

338-395

RX 경로에는 필터 배열을 구성하는 `SO_J1939_FILTER`와 `bind`/`connect` 필터를 우회하는 `SO_J1939_PROMISC`가 있습니다. 기본적으로 broadcast 송수신은 금지되며 `SOL_SOCKET`의 `SO_BROADCAST`에 0이 아닌 값을 설정해야 허용됩니다. TX 경로에서는 `SO_J1939_SEND_PRIO`로 소켓의 기본 송신 우선순위를 바꿉니다.

수신 패킷은 먼저 promiscuous 여부를 확인합니다. promiscuous가 아니면 `bind`와 `connect`, `SO_BROADCAST` 조건을 통과해야 하고, 그 뒤에는 두 경로 모두 `SO_J1939_FILTER`를 적용한 다음 소켓 수신 큐로 들어갑니다. `send`, `sendto`, `sendmsg`의 현재 지원 플래그는 비차단 동작을 요청하는 `MSG_DONTWAIT`입니다.

J1939 RX 경로
수신 패킷SO_J1939_PROMISC? = 아니요bind + connect + SO_BROADCAST 필터SO_J1939_FILTERsocket recv()
수신 패킷SO_J1939_PROMISC? = 예SO_J1939_FILTERsocket recv()

원문의 ASCII 흐름도를 같은 분기 의미의 구조화 도식으로 옮겼습니다.


RX path related options:

- ``SO_J1939_FILTER`` - configure array of filters
- ``SO_J1939_PROMISC`` - disable filters set by ``bind(2)`` and ``connect(2)``

By default no broadcast packets can be send or received. To enable sending or
receiving broadcast packets use the socket option ``SO_BROADCAST``:

.. code-block:: C

     int value = 1;
     setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &value, sizeof(value));

The following diagram illustrates the RX path:

.. code::

                    +--------------------+
                    |  incoming packet   |
                    +--------------------+
                              |
                              V
                    +--------------------+
                    | SO_J1939_PROMISC?  |
                    +--------------------+
                             |  |
                         no  |  | yes
                             |  |
                   .---------'  `---------.
                   |                      |
     +---------------------------+        |
     | bind() + connect() +      |        |
     | SOCK_BROADCAST filter     |        |
     +---------------------------+        |
                   |                      |
                   |<---------------------'
                   V
     +---------------------------+
     |      SO_J1939_FILTER      |
     +---------------------------+
                   |
                   V
     +---------------------------+
     |        socket recv()      |
     +---------------------------+

TX path related options:
``SO_J1939_SEND_PRIO`` - change default send priority for the socket

Message Flags during send() and Related System Calls
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

``send(2)``, ``sendto(2)`` and ``sendmsg(2)`` take a 'flags' argument. Currently
supported flags are:

* ``MSG_DONTWAIT``, i.e. non-blocking operation.

recvmsg 제어 메시지

396-424

패킷 우선순위나 timestamp처럼 `recvfrom(2)`보다 많은 정보가 필요하면 보통 `recvmsg(2)`를 사용합니다. 목적지 주소, 목적지 NAME, 패킷 우선순위는 `msghdr`의 control message로 전달됩니다.

`cmsg(3)` 매크로로 control message를 순회하면서 J1939 레벨과 `SCM_J1939_DEST_ADDR`, `SCM_J1939_DEST_NAME`, `SCM_J1939_PRIO` 타입을 확인합니다. 우선순위와 목적지 주소는 `uint8_t`, 목적지 NAME은 `uint64_t`입니다. 예제 코드는 `CMSG_FIRSTHDR`, `CMSG_NXTHDR`, `CMSG_DATA`를 사용해 세 값을 추출합니다.

recvmsg(2)
^^^^^^^^^^

In most cases ``recvmsg(2)`` is needed if you want to extract more information than
``recvfrom(2)`` can provide. For example package priority and timestamp. The
Destination Address, name and packet priority (if applicable) are attached to
the msghdr in the ``recvmsg(2)`` call. They can be extracted using ``cmsg(3)`` macros,
with ``cmsg_level == SOL_J1939 && cmsg_type == SCM_J1939_DEST_ADDR``,
``SCM_J1939_DEST_NAME`` or ``SCM_J1939_PRIO``. The returned data is a ``uint8_t`` for
``priority`` and ``dst_addr``, and ``uint64_t`` for ``dst_name``.

.. code-block:: C

        uint8_t priority, dst_addr;
        uint64_t dst_name;

        for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
                switch (cmsg->cmsg_level) {
                case SOL_CAN_J1939:
                        if (cmsg->cmsg_type == SCM_J1939_DEST_ADDR)
                                dst_addr = *CMSG_DATA(cmsg);
                        else if (cmsg->cmsg_type == SCM_J1939_DEST_NAME)
                                memcpy(&dst_name, CMSG_DATA(cmsg), cmsg->cmsg_len - CMSG_LEN(0));
                        else if (cmsg->cmsg_type == SCM_J1939_PRIO)
                                priority = *CMSG_DATA(cmsg);
                        break;
                }
        }

필터, promiscuous, broadcast와 우선순위

425-608

`SO_J1939_FILTER`는 `bind`와 `connect`가 제공하는 단일 주소 중심 필터보다 세밀한 수신 선택이 필요할 때 사용합니다. 소스 주소, 소스 NAME, PGN을 조합해 관심 있는 패킷만 받을 수 있고, 여러 PGN을 처리하면서 소켓을 여러 개 열고 싶지 않은 경우에도 유용합니다.

기존 필터를 제거하려면 `optval == NULL` 또는 `optlen == 0`으로 `setsockopt`를 호출합니다. 필터를 갱신할 때는 새 필터 집합이 기존 집합 전체를 대체합니다. 최대 필터 수 `J1939_FILTER_MAX`는 512입니다. 주소 확보를 감시하는 예제는 `J1939_PGN_ADDRESS_CLAIMED`, `J1939_PGN_REQUEST`, `J1939_PGN_ADDRESS_COMMANDED`만 통과시킵니다.

`SO_J1939_PROMISC`는 `bind()`와 `connect()`가 설정한 수신 조건을 무시하고 모든 J1939 트래픽을 받게 합니다. 그러나 `SO_J1939_FILTER`가 더 높은 우선순위를 가지므로 promiscuous 모드에서도 별도 필터로 패킷 범위를 줄일 수 있습니다. 값 크기는 `sizeof(int)`이며 0은 끄기, 0이 아닌 값은 켜기입니다.

`SO_BROADCAST`는 broadcast 메시지 송수신을 허용합니다. CAN 버스의 모든 참가자가 프레임을 볼 수 있다는 물리 특성과 별개로, J1939에서 global 목적지 주소로 보내는 논리적 broadcast를 소켓에 허용하는 옵션입니다. `SOL_SOCKET` 레벨에서 `sizeof(int)` 크기의 0이 아닌 값을 지정합니다.

`SO_J1939_SEND_PRIO`는 송신 CAN 식별자의 우선순위 비트를 설정합니다. 값은 0~7이며 숫자가 작을수록 우선순위가 높고 기본값은 6입니다. 0과 1은 고우선순위 트래픽용이므로 `CAP_NET_ADMIN` 권한이 있어야 설정할 수 있습니다.

setsockopt(2)
^^^^^^^^^^^^^

The ``setsockopt(2)`` function is used to configure various socket-level
options for J1939 communication. The following options are supported:

``SO_J1939_FILTER``
~~~~~~~~~~~~~~~~~~~

The ``SO_J1939_FILTER`` option is essential when the default behavior of
``bind(2)`` and ``connect(2)`` is insufficient for specific use cases. By
default, ``bind(2)`` and ``connect(2)`` allow a socket to be associated with a
single unicast or broadcast address. However, there are scenarios where finer
control over the incoming messages is required, such as filtering by Parameter
Group Number (PGN) rather than by addresses.

For example, in a system where multiple types of J1939 messages are being
transmitted, a process might only be interested in a subset of those messages,
such as specific PGNs, and not want to receive all messages destined for its
address or broadcast to the bus.

By applying the ``SO_J1939_FILTER`` option, you can filter messages based on:

- **Source Address (SA)**: Filter messages coming from specific source
  addresses.

- **Source Name**: Filter messages coming from ECUs with specific NAME
  identifiers.

- **Parameter Group Number (PGN)**: Focus on receiving messages with specific
  PGNs, filtering out irrelevant ones.

This filtering mechanism is particularly useful when:

- You want to receive a subset of messages based on their PGNs, even if the
  address is the same.

- You need to handle both broadcast and unicast messages but only care about
  certain message types or parameters.

- The ``bind(2)`` and ``connect(2)`` functions only allow binding to a single
  address, which might not be sufficient if the process needs to handle multiple
  PGNs but does not want to open multiple sockets.

To remove existing filters, you can pass ``optval == NULL`` or ``optlen == 0``
to ``setsockopt(2)``. This will clear all currently set filters. If you want to
**update** the set of filters, you must pass the updated filter set to
``setsockopt(2)``, as the new filter set will **replace** the old one entirely.
This behavior ensures that any previous filter configuration is discarded and
only the new set is applied.

Example of removing all filters:

.. code-block:: c

    setsockopt(sock, SOL_CAN_J1939, SO_J1939_FILTER, NULL, 0);

**Maximum number of filters:** The maximum amount of filters that can be
applied using ``SO_J1939_FILTER`` is defined by ``J1939_FILTER_MAX``, which is
set to 512. This means you can configure up to 512 individual filters to match
your specific filtering needs.

Practical use case: **Monitoring Address Claiming**

One practical use case is monitoring the J1939 address claiming process by
filtering for specific PGNs related to address claiming. This allows a process
to monitor and handle address claims without processing unrelated messages.

Example:

.. code-block:: c

    struct j1939_filter filt[] = {
        {
            .pgn = J1939_PGN_ADDRESS_CLAIMED,
            .pgn_mask = J1939_PGN_PDU1_MAX,
        }, {
            .pgn = J1939_PGN_REQUEST,
            .pgn_mask = J1939_PGN_PDU1_MAX,
        }, {
            .pgn = J1939_PGN_ADDRESS_COMMANDED,
            .pgn_mask = J1939_PGN_MAX,
        },
    };
    setsockopt(sock, SOL_CAN_J1939, SO_J1939_FILTER, &filt, sizeof(filt));

In this example, the socket will only receive messages with the PGNs related to
address claiming: ``J1939_PGN_ADDRESS_CLAIMED``, ``J1939_PGN_REQUEST``, and
``J1939_PGN_ADDRESS_COMMANDED``. This is particularly useful in scenarios where
you want to monitor and process address claims without being overwhelmed by
other traffic on the J1939 network.

``SO_J1939_PROMISC``
~~~~~~~~~~~~~~~~~~~~

The ``SO_J1939_PROMISC`` option enables socket-level promiscuous mode. When
this option is enabled, the socket will receive all J1939 traffic, regardless
of any filters set by ``bind()`` or ``connect()``. This is analogous to
enabling promiscuous mode for an Ethernet interface, where all traffic on the
network segment is captured.

However, **`SO_J1939_FILTER` has a higher priority** compared to
``SO_J1939_PROMISC``. This means that even in promiscuous mode, you can reduce
the number of packets received by applying specific filters with
`SO_J1939_FILTER`. The filters will limit which packets are passed to the
socket, allowing for more refined traffic selection while promiscuous mode is
active.

The acceptable value size for this option is ``sizeof(int)``, and the value is
only differentiated between `0` and non-zero. A value of `0` disables
promiscuous mode, while any non-zero value enables it.

This combination can be useful for debugging or monitoring specific types of
traffic while still capturing a broad set of messages.

Example:

.. code-block:: c

    int value = 1;
    setsockopt(sock, SOL_CAN_J1939, SO_J1939_PROMISC, &value, sizeof(value));

In this example, setting ``value`` to any non-zero value (e.g., `1`) enables
promiscuous mode, allowing the socket to receive all J1939 traffic on the
network.

``SO_BROADCAST``
~~~~~~~~~~~~~~~~

The ``SO_BROADCAST`` option enables the sending and receiving of broadcast
messages. By default, broadcast messages are disabled for J1939 sockets. When
this option is enabled, the socket will be allowed to send and receive
broadcast packets on the J1939 network.

Due to the nature of the CAN bus as a shared medium, all messages transmitted
on the bus are visible to all participants. In the context of J1939,
broadcasting refers to using a specific destination address field, where the
destination address is set to a value that indicates the message is intended
for all participants (usually a global address such as 0xFF). Enabling the
broadcast option allows the socket to send and receive such broadcast messages.

The acceptable value size for this option is ``sizeof(int)``, and the value is
only differentiated between `0` and non-zero. A value of `0` disables the
ability to send and receive broadcast messages, while any non-zero value
enables it.

Example:

.. code-block:: c

    int value = 1;
    setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &value, sizeof(value));

In this example, setting ``value`` to any non-zero value (e.g., `1`) enables
the socket to send and receive broadcast messages.

``SO_J1939_SEND_PRIO``
~~~~~~~~~~~~~~~~~~~~~~

The ``SO_J1939_SEND_PRIO`` option sets the priority of outgoing J1939 messages
for the socket. In J1939, messages can have different priorities, and lower
numerical values indicate higher priority. This option allows the user to
control the priority of messages sent from the socket by adjusting the priority
bits in the CAN identifier.

The acceptable value **size** for this option is ``sizeof(int)``, and the value
is expected to be in the range of 0 to 7, where `0` is the highest priority,
and `7` is the lowest. By default, the priority is set to `6` if this option is
not explicitly configured.

Note that the priority values `0` and `1` can only be set if the process has
the `CAP_NET_ADMIN` capability. These are reserved for high-priority traffic
and require administrative privileges.

Example:

.. code-block:: c

    int prio = 3;  // Priority value between 0 (highest) and 7 (lowest)
    setsockopt(sock, SOL_CAN_J1939, SO_J1939_SEND_PRIO, &prio, sizeof(prio));

In this example, the priority is set to `3`, meaning the outgoing messages will
be sent with a moderate priority level.

SO_J1939_ERRQUEUE와 세션 추적

609-675

`SO_J1939_ERRQUEUE`는 전송 실패, 프로토콜 위반 등 J1939 통신 문제의 진단 정보를 소켓 오류 큐로 보냅니다. 활성화한 뒤에는 사용자 공간이 `recvmsg(2)`와 `MSG_ERRQUEUE`로 큐를 계속 소비해야 합니다. 평범한 `recv(2)`만 사용하면 처리되지 않은 오류가 쌓여 소켓이 막힐 수 있습니다. 값을 0으로 설정하면 기능을 끄면서 현재 오류 큐도 비웁니다.

구독할 수 있는 이벤트는 송신 중단 `J1939_EE_INFO_TX_ABORT`, RTS 수신 `J1939_EE_INFO_RX_RTS`, DPO 수신 `J1939_EE_INFO_RX_DPO`, 수신 중단 `J1939_EE_INFO_RX_ABORT`입니다.

오류를 특정 전송 세션과 연결하려면 `SO_TIMESTAMPING`에서 `SOF_TIMESTAMPING_OPT_ID`를 활성화해 세션 ID인 `tskey`를 사용합니다. 대부분의 경우 `SO_J1939_ERRQUEUE`와 `SO_TIMESTAMPING`을 함께 쓰는 것이 권장되며, 예제는 세션 식별자, TX 스케줄, TX 확인, RX 소프트웨어 timestamp와 control message 전달을 함께 켭니다.

``SO_J1939_ERRQUEUE``
~~~~~~~~~~~~~~~~~~~~~

The ``SO_J1939_ERRQUEUE`` option enables the socket to receive error messages
from the error queue, providing diagnostic information about transmission
failures, protocol violations, or other issues that occur during J1939
communication. Once this option is set, user space is required to handle
``MSG_ERRQUEUE`` messages.

Setting ``SO_J1939_ERRQUEUE`` to ``0`` will purge any currently present error
messages in the error queue. When enabled, error messages can be retrieved
using the ``recvmsg(2)`` system call.

When subscribing to the error queue, the following error events can be
accessed:

- **``J1939_EE_INFO_TX_ABORT``**: Transmission abort errors.
- **``J1939_EE_INFO_RX_RTS``**: Reception of RTS (Request to Send) control
  frames.
- **``J1939_EE_INFO_RX_DPO``**: Reception of data packets with Data Page Offset
  (DPO).
- **``J1939_EE_INFO_RX_ABORT``**: Reception abort errors.

The error queue can be used to correlate errors with specific message transfer
sessions using the session ID (``tskey``). The session ID is assigned via the
``SOF_TIMESTAMPING_OPT_ID`` flag, which is set by enabling the
``SO_TIMESTAMPING`` option.

If ``SO_J1939_ERRQUEUE`` is activated, the user is required to pull messages
from the error queue, meaning that using plain ``recv(2)`` is not sufficient
anymore. The user must use ``recvmsg(2)`` with appropriate flags to handle
error messages. Failure to do so can result in the socket becoming blocked with
unprocessed error messages in the queue.

It is **recommended** that ``SO_J1939_ERRQUEUE`` be used in combination with
``SO_TIMESTAMPING`` in most cases. This enables proper error handling along
with session tracking and timestamping, providing a more detailed analysis of
message transfers and errors.

The acceptable value **size** for this option is ``sizeof(int)``, and the value
is only differentiated between ``0`` and non-zero. A value of ``0`` disables
error queue reception and purges any existing error messages, while any
non-zero value enables it.

Example:

.. code-block:: c

    int enable = 1;  // Enable error queue reception
    setsockopt(sock, SOL_CAN_J1939, SO_J1939_ERRQUEUE, &enable, sizeof(enable));

    // Enable timestamping with session tracking via tskey
    int timestamping = SOF_TIMESTAMPING_OPT_ID | SOF_TIMESTAMPING_TX_ACK |
                       SOF_TIMESTAMPING_TX_SCHED |
                       SOF_TIMESTAMPING_RX_SOFTWARE | SOF_TIMESTAMPING_OPT_CMSG;
    setsockopt(sock, SOL_SOCKET, SO_TIMESTAMPING, &timestamping,
               sizeof(timestamping));

When enabled, error messages can be retrieved using ``recvmsg(2)``. By
combining ``SO_J1939_ERRQUEUE`` with ``SO_TIMESTAMPING`` (with
``SOF_TIMESTAMPING_OPT_ID`` and ``SOF_TIMESTAMPING_OPT_CMSG`` enabled), the
user can track message transfers, retrieve precise timestamps, and correlate
errors with specific sessions.

For more information on enabling timestamps and session tracking, refer to the
`SO_TIMESTAMPING` section.

SO_TIMESTAMPING 이벤트와 통계

676-877

J1939에서 사용자 공간이 넘긴 모든 페이로드는 크기에 관계없이 세션으로 처리됩니다. 여기에는 8바이트 이하 단일 프레임과 TP/ETP 다중 프레임이 모두 포함됩니다. 오류 큐의 확장 오류는 `recvmsg(2)`의 control message에 든 `struct sock_extended_err`로 전달됩니다.

`serr->ee_origin == SO_EE_ORIGIN_TIMESTAMPING`일 때 `SCM_TSTAMP_SCHED`는 프레임 묶음이 송신 대상으로 스케줄된 시점을 뜻합니다. simple 전송에서는 CAN 버스에 내보낼 큐에 들어간 시점이고, ETP 송신 측에서는 CTS를 받은 뒤 새 프레임 묶음이 예약된 시점입니다. TP의 이 이벤트는 아직 구현되지 않았습니다. ETP 수신 측의 대응 이벤트는 DPO 제어 프레임 수신을 뜻하는 `J1939_EE_INFO_RX_DPO`입니다.

`SCM_TSTAMP_ACK`는 메시지 또는 세션의 확인 시점입니다. simple 전송에서는 CAN 컨트롤러의 echo를 받아 실제 버스 전송을 확인한 시점이고, TP/ETP에서는 보통 EOMA를 받아 전체 세션이 확인된 시점입니다.

`serr->ee_origin == SO_EE_ORIGIN_LOCAL`일 때 `J1939_EE_INFO_TX_ABORT`는 CAN 스택 전달 실패, echo 실패, 상대의 abort나 protocol timeout 같은 이유로 송신이 중단되었음을 뜻합니다. 구체적인 표준 오류 값은 `session->err`에서 온 값으로 제공됩니다. `J1939_EE_INFO_RX_RTS`는 TP/ETP 다중 프레임 전송 시작을 알리며 전체 크기, 프레임 수와 세션 식별 정보를 동반합니다.

`J1939_EE_INFO_RX_DPO`는 ETP의 Data Page Offset을 받아 큰 데이터 중 다음 부분의 위치를 알게 된 사건입니다. 송신 측 `SCM_TSTAMP_SCHED`와 대응하며 그 시점까지 확인된 바이트 수 `J1939_NLA_BYTES_ACKED`를 제공합니다. `J1939_EE_INFO_RX_ABORT`는 timeout, 예상하지 않은 프레임, 송신자의 abort 요청 등으로 수신 세션이 중단되었음을 나타내고 부분 수신 데이터는 폐기됩니다.

`SOF_TIMESTAMPING_OPT_ID`가 켜져 있으면 `serr->ee_data`에 세션 고유 식별자 `session->tskey`가 들어갑니다. 일반 통지의 `serr->ee_errno`는 `ENOMSG`이고, TX/RX abort에는 세션의 실제 표준 오류가 연결됩니다. `J1939_EE_INFO_RX_RTS`에는 `J1939_NLA_TOTAL_SIZE`, PGN, 송수신 NAME과 주소가 포함되며, 나머지 메시지는 확인된 바이트 수를 제공합니다.

주요 timestamping 플래그는 세션 ID를 켜는 `SOF_TIMESTAMPING_OPT_ID`, control message 전달을 켜는 `SOF_TIMESTAMPING_OPT_CMSG`, 스케줄 시점을 받는 `SOF_TIMESTAMPING_TX_SCHED`, 전송 확인을 받는 `SOF_TIMESTAMPING_TX_ACK`, RTS/DPO/abort 같은 수신 이벤트 timestamp를 받는 `SOF_TIMESTAMPING_RX_SOFTWARE`입니다.

오류 큐 이벤트
origininfo의미
TIMESTAMPINGSCM_TSTAMP_SCHEDsimple/ETP 송신 스케줄
TIMESTAMPINGSCM_TSTAMP_ACK프레임 echo 또는 TP/ETP 세션 확인
LOCALJ1939_EE_INFO_TX_ABORT송신 세션 중단
LOCALJ1939_EE_INFO_RX_RTS다중 프레임 수신 시작
LOCALJ1939_EE_INFO_RX_DPOETP 데이터 페이지 오프셋 수신
LOCALJ1939_EE_INFO_RX_ABORT수신 세션 중단

origin과 info 조합이 나타내는 세션 상태입니다.

``SO_TIMESTAMPING``
~~~~~~~~~~~~~~~~~~~

The ``SO_TIMESTAMPING`` option allows the socket to receive timestamps for
various events related to message transmissions and receptions in J1939. This
option is often used in combination with ``SO_J1939_ERRQUEUE`` to provide
detailed diagnostic information, session tracking, and precise timing data for
message transfers.

In J1939, all payloads provided by user space, regardless of size, are
processed by the kernel as **sessions**. This includes both single-frame
messages (up to 8 bytes) and multi-frame protocols such as the Transport
Protocol (TP) and Extended Transport Protocol (ETP). Even for small,
single-frame messages, the kernel creates a session to manage the transmission
and reception. The concept of sessions allows the kernel to manage various
aspects of the protocol, such as reassembling multi-frame messages and tracking
the status of transmissions.

When receiving extended error messages from the error queue, the error
information is delivered through a `struct sock_extended_err`, accessible via
the control message (``cmsg``) retrieved using the ``recvmsg(2)`` system call.

There are two typical origins for the extended error messages in J1939:

1. ``serr->ee_origin == SO_EE_ORIGIN_TIMESTAMPING``:

   In this case, the `serr->ee_info` field will contain one of the following
   timestamp types:

   - ``SCM_TSTAMP_SCHED``: This timestamp is valid for Extended Transport
     Protocol (ETP) transfers and simple transfers (8 bytes or less). It
     indicates when a message or set of frames has been scheduled for
     transmission.

     - For simple transfers (8 bytes or less), it marks the point when the
       message is queued and ready to be sent onto the CAN bus.

     - For ETP transfers, it is sent after receiving a CTS (Clear to Send)
       frame on the sender side, indicating that a new set of frames has been
       scheduled for transmission.

     - The Transport Protocol (TP) case is currently not implemented for this
       timestamp.

     - On the receiver side, the counterpart to this event for ETP is
       represented by the ``J1939_EE_INFO_RX_DPO`` message, which indicates the
       reception of a Data Page Offset (DPO) control frame.

   - ``SCM_TSTAMP_ACK``: This timestamp indicates the acknowledgment of the
     message or session.

     - For simple transfers (8 bytes or less), it marks when the message has
       been sent and an echo confirmation has been received from the CAN
       controller, indicating that the frame was transmitted onto the bus.

     - For multi-frame transfers (TP or ETP), it signifies that the entire
       session has been acknowledged, typically after receiving the End of
       Message Acknowledgment (EOMA) packet.

2. ``serr->ee_origin == SO_EE_ORIGIN_LOCAL``:

   In this case, the `serr->ee_info` field will contain one of the following
   J1939 stack-specific message types:

   - ``J1939_EE_INFO_TX_ABORT``: This message indicates that the transmission
     of a message or session was aborted. The cause of the abort can come from
     various sources:

     - **CAN stack failure**: The J1939 stack was unable to pass the frame to
       the CAN framework for transmission.

     - **Echo failure**: The J1939 stack did not receive an echo confirmation
       from the CAN controller, meaning the frame may not have been successfully
       transmitted to the CAN bus.

     - **Protocol-level issues**: For multi-frame transfers (TP/ETP), this
       could include protocol-related errors, such as an abort signaled by the
       receiver or a timeout at the protocol level, which causes the session to
       terminate prematurely.

     - The corresponding error code is stored in ``serr->ee_data``
       (``session->err`` on kernel side), providing additional details about
       the specific reason for the abort.

   - ``J1939_EE_INFO_RX_RTS``: This message indicates that the J1939 stack has
     received a Request to Send (RTS) control frame, signaling the start of a
     multi-frame transfer using the Transport Protocol (TP) or Extended
     Transport Protocol (ETP).

     - It informs the receiver that the sender is ready to transmit a
       multi-frame message and includes details about the total message size
       and the number of frames to be sent.

     - Statistics such as ``J1939_NLA_TOTAL_SIZE``, ``J1939_NLA_PGN``,
       ``J1939_NLA_SRC_NAME``, and ``J1939_NLA_DEST_NAME`` are provided along
       with the ``J1939_EE_INFO_RX_RTS`` message, giving detailed information
       about the incoming transfer.

   - ``J1939_EE_INFO_RX_DPO``: This message indicates that the J1939 stack has
     received a Data Page Offset (DPO) control frame, which is part of the
     Extended Transport Protocol (ETP).

     - The DPO frame signals the continuation of an ETP multi-frame message by
       indicating the offset position in the data being transferred. It helps
       the receiver manage large data sets by identifying which portion of the
       message is being received.

     - It is typically paired with a corresponding ``SCM_TSTAMP_SCHED`` event
       on the sender side, which indicates when the next set of frames is
       scheduled for transmission.

     - This event includes statistics such as ``J1939_NLA_BYTES_ACKED``, which
       tracks the number of bytes acknowledged up to that point in the session.

   - ``J1939_EE_INFO_RX_ABORT``: This message indicates that the reception of a
     multi-frame message (Transport Protocol or Extended Transport Protocol) has
     been aborted.

     - The abort can be triggered by protocol-level errors such as timeouts, an
       unexpected frame, or a specific abort request from the sender.

     - This message signals that the receiver cannot continue processing the
       transfer, and the session is terminated.

     - The corresponding error code is stored in ``serr->ee_data``
       (``session->err`` on kernel side ), providing further details about the
       reason for the abort, such as protocol violations or timeouts.

     - After receiving this message, the receiver discards the partially received
       frames, and the multi-frame session is considered incomplete.

In both cases, if ``SOF_TIMESTAMPING_OPT_ID`` is enabled, ``serr->ee_data``
will be set to the session’s unique identifier (``session->tskey``). This
allows user space to track message transfers by their session identifier across
multiple frames or stages.

In all other cases, ``serr->ee_errno`` will be set to ``ENOMSG``, except for
the ``J1939_EE_INFO_TX_ABORT`` and ``J1939_EE_INFO_RX_ABORT`` cases, where the
kernel sets ``serr->ee_data`` to the error stored in ``session->err``.  All
protocol-specific errors are converted to standard kernel error values and
stored in ``session->err``. These error values are unified across system calls
and ``serr->ee_errno``.  Some of the known error values are described in the
`Error Codes in the J1939 Stack` section.

When the `J1939_EE_INFO_RX_RTS` message is provided, it will include the
following statistics for multi-frame messages (TP and ETP):

  - ``J1939_NLA_TOTAL_SIZE``: Total size of the message in the session.
  - ``J1939_NLA_PGN``: Parameter Group Number (PGN) identifying the message type.
  - ``J1939_NLA_SRC_NAME``: 64-bit name of the source ECU.
  - ``J1939_NLA_DEST_NAME``: 64-bit name of the destination ECU.
  - ``J1939_NLA_SRC_ADDR``: 8-bit source address of the sending ECU.
  - ``J1939_NLA_DEST_ADDR``: 8-bit destination address of the receiving ECU.

- For other messages (including single-frame messages), only the following
  statistic is included:

  - ``J1939_NLA_BYTES_ACKED``: Number of bytes successfully acknowledged in the
    session.

The key flags for ``SO_TIMESTAMPING`` include:

- ``SOF_TIMESTAMPING_OPT_ID``: Enables the use of a unique session identifier
  (``tskey``) for each transfer. This identifier helps track message transfers
  and errors as distinct sessions in user space. When this option is enabled,
  ``serr->ee_data`` will be set to ``session->tskey``.

- ``SOF_TIMESTAMPING_OPT_CMSG``: Sends timestamp information through control
  messages (``struct scm_timestamping``), allowing the application to retrieve
  timestamps alongside the data.

- ``SOF_TIMESTAMPING_TX_SCHED``: Provides the timestamp for when a message is
  scheduled for transmission (``SCM_TSTAMP_SCHED``).

- ``SOF_TIMESTAMPING_TX_ACK``: Provides the timestamp for when a message
  transmission is fully acknowledged (``SCM_TSTAMP_ACK``).

- ``SOF_TIMESTAMPING_RX_SOFTWARE``: Provides timestamps for reception-related
  events (e.g., ``J1939_EE_INFO_RX_RTS``, ``J1939_EE_INFO_RX_DPO``,
  ``J1939_EE_INFO_RX_ABORT``).

These flags enable detailed monitoring of message lifecycles, including
transmission scheduling, acknowledgments, reception timestamps, and gathering
detailed statistics about the communication session, especially for multi-frame
payloads like TP and ETP.

Example:

.. code-block:: c

    // Enable timestamping with various options, including session tracking and
    // statistics
    int sock_opt = SOF_TIMESTAMPING_OPT_CMSG |
                   SOF_TIMESTAMPING_TX_ACK |
                   SOF_TIMESTAMPING_TX_SCHED |
                   SOF_TIMESTAMPING_OPT_ID |
                   SOF_TIMESTAMPING_RX_SOFTWARE;

    setsockopt(sock, SOL_SOCKET, SO_TIMESTAMPING, &sock_opt, sizeof(sock_opt));


동적 주소 확보

878-956

이미 확보된 주소를 사용하는 것과 주소를 새로 확보하는 것은 구분해야 합니다. 기존 주소를 쓰려면 `j1939.name`을 채워 `bind(2)`에 전달합니다. 그 NAME이 앞서 주소를 확보했다면 이후 송신은 그 주소를 사용하고 `j1939.addr`는 무시됩니다. 예외는 Address Claim/Cannot Claim Address 메시지인 PGN `0x0ee00`이며, 필요할 때 커널이 이 PGN에는 `j1939.addr` 값을 사용합니다.

주소 확보 예제는 NAME과 `J1939_IDLE_ADDR`, `J1939_NO_PGN`으로 `can0`에 bind하고 `SO_BROADCAST`를 활성화합니다. 이어 Address Claimed, Request, Address Commanded PGN만 받는 필터를 설정하고, NAME을 little-endian 64비트 값으로 바꿔 `J1939_PGN_ADDRESS_CLAIMED`와 `J1939_NO_ADDR` 목적지에 `sendto`합니다. 페이로드 NAME이 bind한 `j1939.name`과 다르면 `EPROTO`가 반환됩니다.

전송 뒤 250ms 동안 다른 ECU가 이의를 제기하지 않으면 커널은 NAME-SA 대응을 유효하게 표시하고 같은 NAME에 bind한 소켓이 송신할 수 있게 합니다. 다른 ECU가 주소를 확보하면 기존 대응은 만료되어 주소 확보 메시지 외에는 보낼 수 없습니다. 같은 NAME에 bind한 소켓이 새 SA로 다시 bind하고 유효한 address claim을 보내면 커널과 버스 참가자의 상태 기계가 다시 시작됩니다. `can-utils`의 `j1939acd`는 예제이자 기본 address claiming daemon으로 사용할 수 있습니다.

Dynamic Addressing
------------------

Distinction has to be made between using the claimed address and doing an
address claim. To use an already claimed address, one has to fill in the
``j1939.name`` member and provide it to ``bind(2)``. If the name had claimed an address
earlier, all further messages being sent will use that address. And the
``j1939.addr`` member will be ignored.

An exception on this is PGN 0x0ee00. This is the "Address Claim/Cannot Claim
Address" message and the kernel will use the ``j1939.addr`` member for that PGN if
necessary.

To claim an address following code example can be used:

.. code-block:: C

        struct sockaddr_can baddr = {
                .can_family = AF_CAN,
                .can_addr.j1939 = {
                        .name = name,
                        .addr = J1939_IDLE_ADDR,
                        .pgn = J1939_NO_PGN,        /* to disable bind() rx filter for PGN */
                },
                .can_ifindex = if_nametoindex("can0"),
        };

        bind(sock, (struct sockaddr *)&baddr, sizeof(baddr));

        /* for Address Claiming broadcast must be allowed */
        int value = 1;
        setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &value, sizeof(value));

        /* configured advanced RX filter with PGN needed for Address Claiming */
        const struct j1939_filter filt[] = {
                {
                        .pgn = J1939_PGN_ADDRESS_CLAIMED,
                        .pgn_mask = J1939_PGN_PDU1_MAX,
                }, {
                        .pgn = J1939_PGN_REQUEST,
                        .pgn_mask = J1939_PGN_PDU1_MAX,
                }, {
                        .pgn = J1939_PGN_ADDRESS_COMMANDED,
                        .pgn_mask = J1939_PGN_MAX,
                },
        };

        setsockopt(sock, SOL_CAN_J1939, SO_J1939_FILTER, &filt, sizeof(filt));

        uint64_t dat = htole64(name);
        const struct sockaddr_can saddr = {
                .can_family = AF_CAN,
                .can_addr.j1939 = {
                        .pgn = J1939_PGN_ADDRESS_CLAIMED,
                        .addr = J1939_NO_ADDR,
                },
        };

        /* Afterwards do a sendto(2) with data set to the NAME (Little Endian). If the
         * NAME provided, does not match the j1939.name provided to bind(2), EPROTO
         * will be returned.
         */
        sendto(sock, dat, sizeof(dat), 0, (const struct sockaddr *)&saddr, sizeof(saddr));

If no-one else contests the address claim within 250ms after transmission, the
kernel marks the NAME-SA assignment as valid. The valid assignment will be kept
among other valid NAME-SA assignments. From that point, any socket bound to the
NAME can send packets.

If another ECU claims the address, the kernel will mark the NAME-SA expired.
No socket bound to the NAME can send packets (other than address claims). To
claim another address, some socket bound to NAME, must ``bind(2)`` again, but with
only ``j1939.addr`` changed to the new SA, and must then send a valid address claim
packet. This restarts the state machine in the kernel (and any other
participant on the bus) for this NAME.

``can-utils`` also include the ``j1939acd`` tool, so it can be used as code example or as
default Address Claiming daemon.

정적 주소 송신 예제

957-999

예제는 SA `0x20`에서 DA `0x30`으로 PGN `0x12300`을 보냅니다. `J1939_NO_NAME`, 주소 `0x20`, `J1939_NO_PGN`을 넣은 `sockaddr_can`으로 `can0`에 bind하면 소켓의 정적 소스 주소가 정해집니다.

`connect(2)`를 호출하지 않았으므로 이 시점에는 목적지를 매번 제공하는 `sendto(2)` 또는 `sendmsg(2)`만 사용할 수 있습니다. 송신용 `sockaddr_can`에는 NAME 없음, DA `0x30`, PGN `0x12300`을 넣고 페이로드와 함께 `sendto`에 넘깁니다.

Send Examples
-------------

Static Addressing
^^^^^^^^^^^^^^^^^

This example will send a PGN (0x12300) from SA 0x20 to DA 0x30.

Bind:

.. code-block:: C

        struct sockaddr_can baddr = {
                .can_family = AF_CAN,
                .can_addr.j1939 = {
                        .name = J1939_NO_NAME,
                        .addr = 0x20,
                        .pgn = J1939_NO_PGN,
                },
                .can_ifindex = if_nametoindex("can0"),
        };

        bind(sock, (struct sockaddr *)&baddr, sizeof(baddr));

Now, the socket 'sock' is bound to the SA 0x20. Since no ``connect(2)`` was called,
at this point we can use only ``sendto(2)`` or ``sendmsg(2)``.

Send:

.. code-block:: C

        const struct sockaddr_can saddr = {
                .can_family = AF_CAN,
                .can_addr.j1939 = {
                        .name = J1939_NO_NAME;
                        .addr = 0x30,
                        .pgn = 0x12300,
                },
        };

        sendto(sock, dat, sizeof(dat), 0, (const struct sockaddr *)&saddr, sizeof(saddr));

J1939 스택 오류 코드

1000-1135

`EAGAIN`은 작업이 막혀 재시도해야 함을 뜻하며, 같은 peer 사이에 활성 TP/ETP 세션이 있는데 겹치는 세션을 시작할 때 흔합니다. `ENETDOWN`은 CAN 인터페이스가 down 상태, `ENOBUFS`는 TX 큐가 가득 찬 상태, `EOVERFLOW`는 CTS가 사용자 공간이 아직 제공하지 않은 버퍼 오프셋을 요청하는 등 요구 데이터가 큐 범위를 벗어난 상태입니다. `EBUSY`는 동일한 세션이 이미 활성 상태여서 스택이 복구할 수 없을 때 발생합니다.

`EACCES`는 `SO_BROADCAST` 없이 broadcast를 보내는 경우 같은 권한 거부입니다. `EADDRNOTAVAIL`은 연결되지 않은 소켓의 peer 주소를 조회하거나 address claim이 없는 NAME으로 송수신하려 할 때 발생합니다. `EBADFD`는 bind하지 않은 소켓, 소스 NAME이 없으면서 주소도 `J1939_NO_ADDR`인 소켓, 잘못된 `can_ifindex`처럼 소켓 상태가 송신에 맞지 않을 때 발생합니다.

`EFAULT`는 사용자 버퍼 복사 실패나 부족한 데이터/버퍼, `EINTR`은 데이터 전송 전에 signal을 받은 경우입니다. `EINVAL`은 짧은 `msg_namelen`, `AF_CAN`이 아닌 family, 잘못된 PGN 등 인자 오류입니다. `ENODEV`는 `can_ifindex`가 0이거나 장치를 찾지 못한 경우, `ENOMEM`은 메모리 할당 실패, `ENOPROTOOPT`는 요청한 socket option을 사용할 수 없는 경우입니다.

`EDESTADDRREQ`는 `connect`의 주소가 NULL이거나 ETP를 broadcast 주소로 보내려 할 때 발생합니다. `EDOM`은 TP/ETP 제어용으로 예약된 PGN에 TP/ETP 데이터를 보내려는 경우입니다. `EIO`는 TP/ETP 세션에 제공된 데이터 양과 앞서 알린 양이 다른 경우, `ENOENT`는 CTS나 EOMA를 전달할 대응 수신 소켓을 더 이상 찾지 못한 경우입니다.

`ENOIOCTLCMD`는 소켓 계층에 사용할 ioctl이 없다는 뜻이고, `EPERM`은 `CAP_NET_ADMIN` 같은 권한이 필요한 작업을 요청했을 때 발생합니다. `ENETUNREACH`는 프레임을 CAN 버스로 전송할 수 없는 경우, `ETIME`은 simple 메시지 송신 중 컨트롤러 echo를 받지 못하는 등 timer가 만료된 경우입니다.

`EPROTO`는 중복 sequence number, 예상하지 않은 EDPO/ECTS, EDPO/ECTS의 잘못된 PGN 또는 offset, CTS 허용량을 넘은 EDPO 패킷 수 등 프로토콜 오류입니다. `EMSGSIZE`는 메시지가 너무 김, `ENOMSG`는 사용할 메시지가 없음, `EALREADY`는 ECU가 이미 하나 이상의 connection-managed session을 처리해 새 세션을 수용할 수 없음을 뜻합니다.

`EHOSTUNREACH`는 timeout으로 세션이 abort된 경우, `EBADMSG`는 활성 데이터 전송 중 CTS를 받아 abort한 경우입니다. `ENOTRECOVERABLE`은 최대 재전송 요청 한도에 도달해 복구할 수 없는 상태, `ENOTCONN`은 예상하지 않은 data transfer packet 수신, `EILSEQ`는 복구할 수 없는 잘못된 sequence number 수신을 뜻합니다.

오류 분류
분류대표 오류
자원·상태EAGAIN, ENOBUFS, EBUSY, ENOMEM, EALREADY
주소·장치EADDRNOTAVAIL, EBADFD, ENODEV, EDESTADDRREQ
인자·버퍼EFAULT, EINVAL, EOVERFLOW, EMSGSIZE
전송·시간ENETDOWN, ENETUNREACH, ETIME, EHOSTUNREACH
프로토콜EDOM, EIO, EPROTO, EBADMSG, ENOTCONN, EILSEQ
권한·옵션EACCES, EPERM, ENOPROTOOPT

긴 오류 목록을 원인별로 묶었습니다.

Error Codes in the J1939 Stack
------------------------------

This section lists all potential kernel error codes that can be exposed to user
space when interacting with the J1939 stack. It includes both standard error
codes and those derived from protocol-specific abort codes.

- ``EAGAIN``: Operation would block; retry may succeed. One common reason is
  that an active TP or ETP session exists, and an attempt was made to start a
  new overlapping TP or ETP session between the same peers.

- ``ENETDOWN``: Network is down. This occurs when the CAN interface is switched
  to the "down" state.

- ``ENOBUFS``: No buffer space available. This error occurs when the CAN
  interface's transmit (TX) queue is full, and no more messages can be queued.

- ``EOVERFLOW``: Value too large for defined data type. In J1939, this can
  happen if the requested data lies outside of the queued buffer. For example,
  if a CTS (Clear to Send) requests an offset not available in the kernel buffer
  because user space did not provide enough data.

- ``EBUSY``: Device or resource is busy. For example, this occurs if an
  identical session is already active and the stack is unable to recover from
  the condition.

- ``EACCES``: Permission denied. This error can occur, for example, when
  attempting to send broadcast messages, but the socket is not configured with
  ``SO_BROADCAST``.

- ``EADDRNOTAVAIL``: Address not available. This error occurs in cases such as:

  - When attempting to use ``getsockname(2)`` to retrieve the peer's address,
    but the socket is not connected.

  - When trying to send data to or from a NAME, but address claiming for the
    NAME was not performed or detected by the stack.

- ``EBADFD``: File descriptor in bad state. This error can occur if:

  - Attempting to send data to an unbound socket.

  - The socket is bound but has no source name, and the source address is
    ``J1939_NO_ADDR``.

  - The ``can_ifindex`` is incorrect.

- ``EFAULT``: Bad address. Occurs mostly when the stack can't copy from or to a
  sockptr, when there is insufficient data from user space, or when the buffer
  provided by user space is not large enough for the requested data.

- ``EINTR``: A signal occurred before any data was transmitted; see ``signal(7)``.

- ``EINVAL``: Invalid argument passed. For example:

  - ``msg->msg_namelen`` is less than ``J1939_MIN_NAMELEN``.

  - ``addr->can_family`` is not equal to ``AF_CAN``.

  - An incorrect PGN was provided.

- ``ENODEV``: No such device. This happens when the CAN network device cannot
  be found for the provided ``can_ifindex`` or if ``can_ifindex`` is 0.

- ``ENOMEM``: Out of memory. Typically related to issues with memory allocation
  in the stack.

- ``ENOPROTOOPT``: Protocol not available. This can occur when using
  ``getsockopt(2)`` or ``setsockopt(2)`` if the requested socket option is not
  available.

- ``EDESTADDRREQ``: Destination address required. This error occurs:

  - In the case of ``connect(2)``, if the ``struct sockaddr *uaddr`` is ``NULL``.

  - In the case of ``send*(2)``, if there is an attempt to send an ETP message
    to a broadcast address.

- ``EDOM``: Argument out of domain. This error may happen if attempting to send
  a TP or ETP message to a PGN that is reserved for control PGNs for TP or ETP
  operations.

- ``EIO``: I/O error. This can occur if the amount of data provided to the
  socket for a TP or ETP session does not match the announced amount of data for
  the session.

- ``ENOENT``: No such file or directory. This can happen when the stack
  attempts to transfer CTS or EOMA but cannot find a matching receiving socket
  anymore.

- ``ENOIOCTLCMD``: No ioctls are available for the socket layer.

- ``EPERM``: Operation not permitted. For example, this can occur if a
  requested action requires ``CAP_NET_ADMIN`` privileges.

- ``ENETUNREACH``: Network unreachable. Most likely, this occurs when frames
  cannot be transmitted to the CAN bus.

- ``ETIME``: Timer expired. This can happen if a timeout occurs while
  attempting to send a simple message, for example, when an echo message from
  the controller is not received.

- ``EPROTO``: Protocol error.

  - Used for various protocol-level errors in J1939, including:

    - Duplicate sequence number.

    - Unexpected EDPO or ECTS packet.

    - Invalid PGN or offset in EDPO/ECTS.

    - Number of EDPO packets exceeded CTS allowance.

    - Any other protocol-level error.

- ``EMSGSIZE``: Message too long.

- ``ENOMSG``: No message available.

- ``EALREADY``: The ECU is already engaged in one or more connection-managed
  sessions and cannot support another.

- ``EHOSTUNREACH``: A timeout occurred, and the session was aborted.

- ``EBADMSG``: CTS (Clear to Send) messages were received during an active data
  transfer, causing an abort.

- ``ENOTRECOVERABLE``: The maximum retransmission request limit was reached,
  and the session cannot recover.

- ``ENOTCONN``: An unexpected data transfer packet was received.

- ``EILSEQ``: A bad sequence number was received, and the software could not
  recover.