J1939 Documentation¶
Overview / What Is J1939¶
SAE J1939 defines a higher layer protocol on CAN. It implements a moresophisticated addressing scheme and extends the maximum packet size above 8bytes. Several derived specifications exist, which differ from the originalJ1939 on the application level, like MilCAN A, NMEA2000, and especiallyISO-11783 (ISOBUS). This last one specifies the so-called ETP (ExtendedTransport Protocol), which has been included in this implementation. Thisresults 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)
Motivation¶
Given the fact there’s something like SocketCAN with an API similar to BSDsockets, we found some reasons to justify a kernel implementation for theaddressing and transport methods used by J1939.
Addressing: when a process on an ECU communicates via J1939, it shouldnot necessarily know its source address. Although, at least one process perECU should know the source address. Other processes should be able to reusethat address. This way, address parameters for different processescooperating for the same ECU, are not duplicated. This way of working isclosely related to the UNIX concept, where programs do just one thing and doit well.
Dynamic addressing: Address Claiming in J1939 is time critical.Furthermore, data transport should be handled properly during the addressnegotiation. Putting this functionality in the kernel eliminates it as arequirement for _every_ user space process that communicates via J1939. Thisresults 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 actuallyknowing it. The individual TP & ETP sessions _must_ be serialized(synchronized) between different processes. The kernel solves this problemproperly and eliminates the serialization (synchronization) as a requirementfor _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 J1939user space library operating on CAN raw sockets will still operate properly.Since such a library does not communicate with the in-kernel implementation, caremust be taken that these two do not interfere. In practice, this means theycannot share ECU addresses. A single ECU (or virtual ECU) address is used bythe library exclusively, or by the in-kernel system exclusively.
J1939 concepts¶
Data Sent to the J1939 Stack¶
The data buffers sent to the J1939 stack from user space are not CAN framesthemselves. Instead, they are payloads that the J1939 stack converts intoproper CAN frames based on the size of the buffer and the type of transfer. Thesize of the buffer influences how the stack processes the data and determinesthe 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 withoutfragmentation.
This type of transfer does not require an actual client (receiver) on thereceiving 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 beused in broadcast scenarios.
Unicast TP: Requires an active receiver (client) on the other side toacknowledge 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 CANframes internally.
ETP transfers (unicast): Require a receiver on the other side toprocess the incoming data and acknowledge each step of the transfer.
ETP transfers cannot be broadcast like TP transfers, and always require areceiver for operation.
Non-Blocking Operation with `MSG_DONTWAIT`:
The J1939 stack supports non-blocking operation when used in combination withtheMSG_DONTWAIT flag. In this mode, the stack attempts to take as much dataas the available memory for the socket allows. It returns the amount of datathat was successfully taken, and it is the responsibility of user space tomonitor this value and handle partial transfers.
If the stack cannot take the entire buffer, it returns the number of bytessuccessfully taken, and user space should handle the remainder.
Error handling: When usingMSG_DONTWAIT, the user must rely on theerror queue to detect transfer errors. See theSO_J1939_ERRQUEUE sectionfor details on how to subscribe to error notifications. Without the errorqueue, there is no other way for user space to be notified of transfer errorsduring non-blocking operations.
Behavior and Requirements:
Simple transfers (<= 8 bytes): Do not require a receiver on the otherside, making them easy to send without needing address claiming orcoordination with a destination.
Unicast TP/ETP: Requires a receiver on the other side to complete thetransfer. The receiver must acknowledge the transfer for the session toproceed successfully.
Broadcast TP: Allows sending data without a receiver, but only works forTP transfers. ETP cannot be broadcast and always needs a receiving client.
These different behaviors depend heavily on the size of the buffer provided tothe stack, and the appropriate transport mechanism (TP or ETP) is selectedbased on the payload size. The stack automatically manages the fragmentationand reassembly of large payloads and ensures that the correct CAN frames aregenerated and transmitted for each session.
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 PGNis 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 PDU2format (where PF >= 240). Furthermore, when using the PDU2 format, the PS-fieldcontains a so-called Group Extension, which is part of the PGN. When using PDU2format, 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-calledDestination Address, which is _not_ part of the PGN. When communicating a PGNfrom user space to kernel (or vice versa) and PDU1 format is used, the PS-fieldof the PGN shall be set to zero. The Destination Address shall be setelsewhere.
Regarding PGN mapping to 29-bit CAN identifier, the Destination Address shallbe get/set from/to the appropriate bits of the identifier by the kernel.
Addressing¶
Both static and dynamic addressing methods can be used.
For static addresses, no extra checks are made by the kernel and providedaddresses are considered right. This responsibility is for the OEM or systemintegrator.
For dynamic addressing, so-called Address Claiming, extra support is foreseenin the kernel. In J1939 any ECU is known by its 64-bit NAME. At the moment ofa successful address claim, the kernel keeps track of both NAME and sourceaddress 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) areallowed. The BSD sockets define separate API calls for getting/setting thelocal & remote address and are applicable for J1939 sockets.
Filtering¶
J1939 defines white list filters per socket that a user can set in order toreceive 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 inthat matches several of those filters, the packet is only received once forthat socket.
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 beincluded too. To open a socket, use:
s=socket(PF_CAN,SOCK_DGRAM,CAN_J1939);
J1939 does useSOCK_DGRAM sockets. In the J1939 specification, connections arementioned in the context of transport protocol sessions. These still deliverpackets to the other end (using several CAN packets).SOCK_STREAM is notsupported.
After the successful creation of the socket, you would normally use thebind(2)and/orconnect(2) system call to bind the socket to a CAN interface. Afterbinding and/or connecting the socket, you canread(2) andwrite(2) from/to thesocket or usesend(2),sendto(2),sendmsg(2) and therecv*() counterpartoperations on the socket as usual. There are also J1939 specific socket optionsdescribed below.
In order to send data, abind(2) must have been successful.bind(2) assigns alocal 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 suppliedtobind(2),connect(2),sendto(2) andrecvfrom(2). Awrite(2) with size 4 willresult in a packet with 4 bytes.
The sockaddr structure has extensions for use with J1939 as specified below:
structsockaddr_can{sa_family_tcan_family;intcan_ifindex;union{struct{__u64name;/* pgn: * 8 bit: PS in PDU2 case, else 0 * 8 bit: PF * 1 bit: DP * 1 bit: reserved */__u32pgn;__u8addr;}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 arespecified above.
can_addr.j1939.name contains the 64-bit J1939 NAME.
can_addr.j1939.addr contains the address.
Thebind(2) system call assigns the local address, i.e. the source address whensending packages. If a PGN duringbind(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 setit is used as a receive filter, too. It will match the destination NAME or ADDRof the incoming packet. The NAME filter will work only if appropriate AddressClaiming for this name was done on the CAN bus and registered/cached by thekernel.
On the other handconnect(2) assigns the remote address, i.e. the destinationaddress. The PGN fromconnect(2) is used as the default PGN when sendingpackets. If ADDR or NAME is set it will be used as the default destination ADDRor NAME. Further a set ADDR or NAME duringconnect(2) is used as a receivefilter. It will match the source NAME or ADDR of the incoming packet.
Bothwrite(2) andsend(2) will send a packet with local address frombind(2) and theremote address fromconnect(2). Usesendto(2) to overwrite the destinationaddress.
Ifcan_addr.j1939.name is set (!= 0) the NAME is looked up by the kernel andthe corresponding ADDR is used. Ifcan_addr.j1939.name is not set (== 0),can_addr.j1939.addr is used.
When creating a socket, reasonable defaults are set. Some options can bemodified withsetsockopt(2) &getsockopt(2).
RX path related options:
SO_J1939_FILTER- configure array of filtersSO_J1939_PROMISC- disable filters set bybind(2)andconnect(2)
By default no broadcast packets can be send or received. To enable sending orreceiving broadcast packets use the socket optionSO_BROADCAST:
intvalue=1;setsockopt(sock,SOL_SOCKET,SO_BROADCAST,&value,sizeof(value));
The following diagram illustrates the RX path:
+--------------------+ | 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) andsendmsg(2) take a ‘flags’ argument. Currentlysupported flags are:
MSG_DONTWAIT, i.e. non-blocking operation.
recvmsg(2)¶
In most casesrecvmsg(2) is needed if you want to extract more information thanrecvfrom(2) can provide. For example package priority and timestamp. TheDestination Address, name and packet priority (if applicable) are attached tothe msghdr in therecvmsg(2) call. They can be extracted usingcmsg(3) macros,withcmsg_level==SOL_J1939&&cmsg_type==SCM_J1939_DEST_ADDR,SCM_J1939_DEST_NAME orSCM_J1939_PRIO. The returned data is auint8_t forpriority anddst_addr, anduint64_t fordst_name.
uint8_tpriority,dst_addr;uint64_tdst_name;for(cmsg=CMSG_FIRSTHDR(&msg);cmsg;cmsg=CMSG_NXTHDR(&msg,cmsg)){switch(cmsg->cmsg_level){caseSOL_CAN_J1939:if(cmsg->cmsg_type==SCM_J1939_DEST_ADDR)dst_addr=*CMSG_DATA(cmsg);elseif(cmsg->cmsg_type==SCM_J1939_DEST_NAME)memcpy(&dst_name,CMSG_DATA(cmsg),cmsg->cmsg_len-CMSG_LEN(0));elseif(cmsg->cmsg_type==SCM_J1939_PRIO)priority=*CMSG_DATA(cmsg);break;}}
setsockopt(2)¶
Thesetsockopt(2) function is used to configure various socket-leveloptions for J1939 communication. The following options are supported:
SO_J1939_FILTER¶
TheSO_J1939_FILTER option is essential when the default behavior ofbind(2) andconnect(2) is insufficient for specific use cases. Bydefault,bind(2) andconnect(2) allow a socket to be associated with asingle unicast or broadcast address. However, there are scenarios where finercontrol over the incoming messages is required, such as filtering by ParameterGroup Number (PGN) rather than by addresses.
For example, in a system where multiple types of J1939 messages are beingtransmitted, 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 itsaddress or broadcast to the bus.
By applying theSO_J1939_FILTER option, you can filter messages based on:
Source Address (SA): Filter messages coming from specific sourceaddresses.
Source Name: Filter messages coming from ECUs with specific NAMEidentifiers.
Parameter Group Number (PGN): Focus on receiving messages with specificPGNs, 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 theaddress is the same.
You need to handle both broadcast and unicast messages but only care aboutcertain message types or parameters.
The
bind(2)andconnect(2)functions only allow binding to a singleaddress, which might not be sufficient if the process needs to handle multiplePGNs but does not want to open multiple sockets.
To remove existing filters, you can passoptval==NULL oroptlen==0tosetsockopt(2). This will clear all currently set filters. If you want toupdate the set of filters, you must pass the updated filter set tosetsockopt(2), as the new filter set willreplace the old one entirely.This behavior ensures that any previous filter configuration is discarded andonly the new set is applied.
Example of removing all filters:
setsockopt(sock,SOL_CAN_J1939,SO_J1939_FILTER,NULL,0);
Maximum number of filters: The maximum amount of filters that can beapplied usingSO_J1939_FILTER is defined byJ1939_FILTER_MAX, which isset to 512. This means you can configure up to 512 individual filters to matchyour specific filtering needs.
Practical use case:Monitoring Address Claiming
One practical use case is monitoring the J1939 address claiming process byfiltering for specific PGNs related to address claiming. This allows a processto monitor and handle address claims without processing unrelated messages.
Example:
structj1939_filterfilt[]={{.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 toaddress claiming:J1939_PGN_ADDRESS_CLAIMED,J1939_PGN_REQUEST, andJ1939_PGN_ADDRESS_COMMANDED. This is particularly useful in scenarios whereyou want to monitor and process address claims without being overwhelmed byother traffic on the J1939 network.
SO_J1939_PROMISC¶
TheSO_J1939_PROMISC option enables socket-level promiscuous mode. Whenthis option is enabled, the socket will receive all J1939 traffic, regardlessof any filters set bybind() orconnect(). This is analogous toenabling promiscuous mode for an Ethernet interface, where all traffic on thenetwork segment is captured.
However,`SO_J1939_FILTER` has a higher priority compared toSO_J1939_PROMISC. This means that even in promiscuous mode, you can reducethe number of packets received by applying specific filters withSO_J1939_FILTER. The filters will limit which packets are passed to thesocket, allowing for more refined traffic selection while promiscuous mode isactive.
The acceptable value size for this option issizeof(int), and the value isonly differentiated between0 and non-zero. A value of0 disablespromiscuous mode, while any non-zero value enables it.
This combination can be useful for debugging or monitoring specific types oftraffic while still capturing a broad set of messages.
Example:
intvalue=1;setsockopt(sock,SOL_CAN_J1939,SO_J1939_PROMISC,&value,sizeof(value));
In this example, settingvalue to any non-zero value (e.g.,1) enablespromiscuous mode, allowing the socket to receive all J1939 traffic on thenetwork.
SO_BROADCAST¶
TheSO_BROADCAST option enables the sending and receiving of broadcastmessages. By default, broadcast messages are disabled for J1939 sockets. Whenthis option is enabled, the socket will be allowed to send and receivebroadcast packets on the J1939 network.
Due to the nature of the CAN bus as a shared medium, all messages transmittedon the bus are visible to all participants. In the context of J1939,broadcasting refers to using a specific destination address field, where thedestination address is set to a value that indicates the message is intendedfor all participants (usually a global address such as 0xFF). Enabling thebroadcast option allows the socket to send and receive such broadcast messages.
The acceptable value size for this option issizeof(int), and the value isonly differentiated between0 and non-zero. A value of0 disables theability to send and receive broadcast messages, while any non-zero valueenables it.
Example:
intvalue=1;setsockopt(sock,SOL_SOCKET,SO_BROADCAST,&value,sizeof(value));
In this example, settingvalue to any non-zero value (e.g.,1) enablesthe socket to send and receive broadcast messages.
SO_J1939_SEND_PRIO¶
TheSO_J1939_SEND_PRIO option sets the priority of outgoing J1939 messagesfor the socket. In J1939, messages can have different priorities, and lowernumerical values indicate higher priority. This option allows the user tocontrol the priority of messages sent from the socket by adjusting the prioritybits in the CAN identifier.
The acceptable valuesize for this option issizeof(int), and the valueis expected to be in the range of 0 to 7, where0 is the highest priority,and7 is the lowest. By default, the priority is set to6 if this option isnot explicitly configured.
Note that the priority values0 and1 can only be set if the process hastheCAP_NET_ADMIN capability. These are reserved for high-priority trafficand require administrative privileges.
Example:
intprio=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 to3, meaning the outgoing messages willbe sent with a moderate priority level.
SO_J1939_ERRQUEUE¶
TheSO_J1939_ERRQUEUE option enables the socket to receive error messagesfrom the error queue, providing diagnostic information about transmissionfailures, protocol violations, or other issues that occur during J1939communication. Once this option is set, user space is required to handleMSG_ERRQUEUE messages.
SettingSO_J1939_ERRQUEUE to0 will purge any currently present errormessages in the error queue. When enabled, error messages can be retrievedusing therecvmsg(2) system call.
When subscribing to the error queue, the following error events can beaccessed:
``J1939_EE_INFO_TX_ABORT``: Transmission abort errors.
``J1939_EE_INFO_RX_RTS``: Reception of RTS (Request to Send) controlframes.
``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 transfersessions using the session ID (tskey). The session ID is assigned via theSOF_TIMESTAMPING_OPT_ID flag, which is set by enabling theSO_TIMESTAMPING option.
IfSO_J1939_ERRQUEUE is activated, the user is required to pull messagesfrom the error queue, meaning that using plainrecv(2) is not sufficientanymore. The user must userecvmsg(2) with appropriate flags to handleerror messages. Failure to do so can result in the socket becoming blocked withunprocessed error messages in the queue.
It isrecommended thatSO_J1939_ERRQUEUE be used in combination withSO_TIMESTAMPING in most cases. This enables proper error handling alongwith session tracking and timestamping, providing a more detailed analysis ofmessage transfers and errors.
The acceptable valuesize for this option issizeof(int), and the valueis only differentiated between0 and non-zero. A value of0 disableserror queue reception and purges any existing error messages, while anynon-zero value enables it.
Example:
intenable=1;// Enable error queue receptionsetsockopt(sock,SOL_CAN_J1939,SO_J1939_ERRQUEUE,&enable,sizeof(enable));// Enable timestamping with session tracking via tskeyinttimestamping=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,×tamping,sizeof(timestamping));
When enabled, error messages can be retrieved usingrecvmsg(2). BycombiningSO_J1939_ERRQUEUE withSO_TIMESTAMPING (withSOF_TIMESTAMPING_OPT_ID andSOF_TIMESTAMPING_OPT_CMSG enabled), theuser can track message transfers, retrieve precise timestamps, and correlateerrors with specific sessions.
For more information on enabling timestamps and session tracking, refer to theSO_TIMESTAMPING section.
SO_TIMESTAMPING¶
TheSO_TIMESTAMPING option allows the socket to receive timestamps forvarious events related to message transmissions and receptions in J1939. Thisoption is often used in combination withSO_J1939_ERRQUEUE to providedetailed diagnostic information, session tracking, and precise timing data formessage transfers.
In J1939, all payloads provided by user space, regardless of size, areprocessed by the kernel assessions. This includes both single-framemessages (up to 8 bytes) and multi-frame protocols such as the TransportProtocol (TP) and Extended Transport Protocol (ETP). Even for small,single-frame messages, the kernel creates a session to manage the transmissionand reception. The concept of sessions allows the kernel to manage variousaspects of the protocol, such as reassembling multi-frame messages and trackingthe status of transmissions.
When receiving extended error messages from the error queue, the errorinformation is delivered through astructsock_extended_err, accessible viathe control message (cmsg) retrieved using therecvmsg(2) system call.
There are two typical origins for the extended error messages in J1939:
serr->ee_origin==SO_EE_ORIGIN_TIMESTAMPING:In this case, theserr->ee_info field will contain one of the followingtimestamp types:
SCM_TSTAMP_SCHED: This timestamp is valid for Extended TransportProtocol (ETP) transfers and simple transfers (8 bytes or less). Itindicates when a message or set of frames has been scheduled fortransmission.For simple transfers (8 bytes or less), it marks the point when themessage 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 beenscheduled for transmission.
The Transport Protocol (TP) case is currently not implemented for thistimestamp.
On the receiver side, the counterpart to this event for ETP isrepresented by the
J1939_EE_INFO_RX_DPOmessage, which indicates thereception of a Data Page Offset (DPO) control frame.
SCM_TSTAMP_ACK: This timestamp indicates the acknowledgment of themessage or session.For simple transfers (8 bytes or less), it marks when the message hasbeen sent and an echo confirmation has been received from the CANcontroller, indicating that the frame was transmitted onto the bus.
For multi-frame transfers (TP or ETP), it signifies that the entiresession has been acknowledged, typically after receiving the End ofMessage Acknowledgment (EOMA) packet.
serr->ee_origin==SO_EE_ORIGIN_LOCAL:In this case, theserr->ee_info field will contain one of the followingJ1939 stack-specific message types:
J1939_EE_INFO_TX_ABORT: This message indicates that the transmissionof a message or session was aborted. The cause of the abort can come fromvarious sources:CAN stack failure: The J1939 stack was unable to pass the frame tothe CAN framework for transmission.
Echo failure: The J1939 stack did not receive an echo confirmationfrom the CAN controller, meaning the frame may not have been successfullytransmitted to the CAN bus.
Protocol-level issues: For multi-frame transfers (TP/ETP), thiscould include protocol-related errors, such as an abort signaled by thereceiver or a timeout at the protocol level, which causes the session toterminate prematurely.
The corresponding error code is stored in
serr->ee_data(session->erron kernel side), providing additional details aboutthe specific reason for the abort.
J1939_EE_INFO_RX_RTS: This message indicates that the J1939 stack hasreceived a Request to Send (RTS) control frame, signaling the start of amulti-frame transfer using the Transport Protocol (TP) or ExtendedTransport Protocol (ETP).It informs the receiver that the sender is ready to transmit amulti-frame message and includes details about the total message sizeand the number of frames to be sent.
Statistics such as
J1939_NLA_TOTAL_SIZE,J1939_NLA_PGN,J1939_NLA_SRC_NAME, andJ1939_NLA_DEST_NAMEare provided alongwith theJ1939_EE_INFO_RX_RTSmessage, giving detailed informationabout the incoming transfer.
J1939_EE_INFO_RX_DPO: This message indicates that the J1939 stack hasreceived a Data Page Offset (DPO) control frame, which is part of theExtended Transport Protocol (ETP).The DPO frame signals the continuation of an ETP multi-frame message byindicating the offset position in the data being transferred. It helpsthe receiver manage large data sets by identifying which portion of themessage is being received.
It is typically paired with a corresponding
SCM_TSTAMP_SCHEDeventon the sender side, which indicates when the next set of frames isscheduled for transmission.This event includes statistics such as
J1939_NLA_BYTES_ACKED, whichtracks the number of bytes acknowledged up to that point in the session.
J1939_EE_INFO_RX_ABORT: This message indicates that the reception of amulti-frame message (Transport Protocol or Extended Transport Protocol) hasbeen aborted.The abort can be triggered by protocol-level errors such as timeouts, anunexpected frame, or a specific abort request from the sender.
This message signals that the receiver cannot continue processing thetransfer, and the session is terminated.
The corresponding error code is stored in
serr->ee_data(session->erron kernel side ), providing further details about thereason for the abort, such as protocol violations or timeouts.After receiving this message, the receiver discards the partially receivedframes, and the multi-frame session is considered incomplete.
In both cases, ifSOF_TIMESTAMPING_OPT_ID is enabled,serr->ee_datawill be set to the session’s unique identifier (session->tskey). Thisallows user space to track message transfers by their session identifier acrossmultiple frames or stages.
In all other cases,serr->ee_errno will be set toENOMSG, except fortheJ1939_EE_INFO_TX_ABORT andJ1939_EE_INFO_RX_ABORT cases, where thekernel setsserr->ee_data to the error stored insession->err. Allprotocol-specific errors are converted to standard kernel error values andstored insession->err. These error values are unified across system callsandserr->ee_errno. Some of the known error values are described in theError Codes in the J1939 Stack section.
When theJ1939_EE_INFO_RX_RTS message is provided, it will include thefollowing 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 followingstatistic is included:
J1939_NLA_BYTES_ACKED: Number of bytes successfully acknowledged in thesession.
The key flags forSO_TIMESTAMPING include:
SOF_TIMESTAMPING_OPT_ID: Enables the use of a unique session identifier(tskey) for each transfer. This identifier helps track message transfersand errors as distinct sessions in user space. When this option is enabled,serr->ee_datawill be set tosession->tskey.SOF_TIMESTAMPING_OPT_CMSG: Sends timestamp information through controlmessages (structscm_timestamping), allowing the application to retrievetimestamps alongside the data.SOF_TIMESTAMPING_TX_SCHED: Provides the timestamp for when a message isscheduled for transmission (SCM_TSTAMP_SCHED).SOF_TIMESTAMPING_TX_ACK: Provides the timestamp for when a messagetransmission is fully acknowledged (SCM_TSTAMP_ACK).SOF_TIMESTAMPING_RX_SOFTWARE: Provides timestamps for reception-relatedevents (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, includingtransmission scheduling, acknowledgments, reception timestamps, and gatheringdetailed statistics about the communication session, especially for multi-framepayloads like TP and ETP.
Example:
// Enable timestamping with various options, including session tracking and// statisticsintsock_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));
Dynamic Addressing¶
Distinction has to be made between using the claimed address and doing anaddress claim. To use an already claimed address, one has to fill in thej1939.name member and provide it tobind(2). If the name had claimed an addressearlier, all further messages being sent will use that address. And thej1939.addr member will be ignored.
An exception on this is PGN 0x0ee00. This is the “Address Claim/Cannot ClaimAddress” message and the kernel will use thej1939.addr member for that PGN ifnecessary.
To claim an address following code example can be used:
structsockaddr_canbaddr={.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,(structsockaddr*)&baddr,sizeof(baddr));/* for Address Claiming broadcast must be allowed */intvalue=1;setsockopt(sock,SOL_SOCKET,SO_BROADCAST,&value,sizeof(value));/* configured advanced RX filter with PGN needed for Address Claiming */conststructj1939_filterfilt[]={{.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_tdat=htole64(name);conststructsockaddr_cansaddr={.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,(conststructsockaddr*)&saddr,sizeof(saddr));
If no-one else contests the address claim within 250ms after transmission, thekernel marks the NAME-SA assignment as valid. The valid assignment will be keptamong other valid NAME-SA assignments. From that point, any socket bound to theNAME 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). Toclaim another address, some socket bound to NAME, mustbind(2) again, but withonlyj1939.addr changed to the new SA, and must then send a valid address claimpacket. This restarts the state machine in the kernel (and any otherparticipant on the bus) for this NAME.
can-utils also include thej1939acd tool, so it can be used as code example or asdefault Address Claiming daemon.
Send Examples¶
Static Addressing¶
This example will send a PGN (0x12300) from SA 0x20 to DA 0x30.
Bind:
structsockaddr_canbaddr={.can_family=AF_CAN,.can_addr.j1939={.name=J1939_NO_NAME,.addr=0x20,.pgn=J1939_NO_PGN,},.can_ifindex=if_nametoindex("can0"),};bind(sock,(structsockaddr*)&baddr,sizeof(baddr));
Now, the socket ‘sock’ is bound to the SA 0x20. Since noconnect(2) was called,at this point we can use onlysendto(2) orsendmsg(2).
Send:
conststructsockaddr_cansaddr={.can_family=AF_CAN,.can_addr.j1939={.name=J1939_NO_NAME;.addr=0x30,.pgn=0x12300,},};sendto(sock,dat,sizeof(dat),0,(conststructsockaddr*)&saddr,sizeof(saddr));
Error Codes in the J1939 Stack¶
This section lists all potential kernel error codes that can be exposed to userspace when interacting with the J1939 stack. It includes both standard errorcodes and those derived from protocol-specific abort codes.
EAGAIN: Operation would block; retry may succeed. One common reason isthat an active TP or ETP session exists, and an attempt was made to start anew overlapping TP or ETP session between the same peers.ENETDOWN: Network is down. This occurs when the CAN interface is switchedto the “down” state.ENOBUFS: No buffer space available. This error occurs when the CANinterface’s transmit (TX) queue is full, and no more messages can be queued.EOVERFLOW: Value too large for defined data type. In J1939, this canhappen 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 bufferbecause user space did not provide enough data.EBUSY: Device or resource is busy. For example, this occurs if anidentical session is already active and the stack is unable to recover fromthe condition.EACCES: Permission denied. This error can occur, for example, whenattempting to send broadcast messages, but the socket is not configured withSO_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 theNAME 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_ifindexis incorrect.
EFAULT: Bad address. Occurs mostly when the stack can’t copy from or to asockptr, when there is insufficient data from user space, or when the bufferprovided by user space is not large enough for the requested data.EINTR: A signal occurred before any data was transmitted; seesignal(7).EINVAL: Invalid argument passed. For example:msg->msg_namelenis less thanJ1939_MIN_NAMELEN.addr->can_familyis not equal toAF_CAN.An incorrect PGN was provided.
ENODEV: No such device. This happens when the CAN network device cannotbe found for the providedcan_ifindexor ifcan_ifindexis 0.ENOMEM: Out of memory. Typically related to issues with memory allocationin the stack.ENOPROTOOPT: Protocol not available. This can occur when usinggetsockopt(2)orsetsockopt(2)if the requested socket option is notavailable.EDESTADDRREQ: Destination address required. This error occurs:In the case of
connect(2), if thestructsockaddr*uaddrisNULL.In the case of
send*(2), if there is an attempt to send an ETP messageto a broadcast address.
EDOM: Argument out of domain. This error may happen if attempting to senda TP or ETP message to a PGN that is reserved for control PGNs for TP or ETPoperations.EIO: I/O error. This can occur if the amount of data provided to thesocket for a TP or ETP session does not match the announced amount of data forthe session.ENOENT: No such file or directory. This can happen when the stackattempts to transfer CTS or EOMA but cannot find a matching receiving socketanymore.ENOIOCTLCMD: No ioctls are available for the socket layer.EPERM: Operation not permitted. For example, this can occur if arequested action requiresCAP_NET_ADMINprivileges.ENETUNREACH: Network unreachable. Most likely, this occurs when framescannot be transmitted to the CAN bus.ETIME: Timer expired. This can happen if a timeout occurs whileattempting to send a simple message, for example, when an echo message fromthe 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-managedsessions and cannot support another.EHOSTUNREACH: A timeout occurred, and the session was aborted.EBADMSG: CTS (Clear to Send) messages were received during an active datatransfer, 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 notrecover.