j1939.rst 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. .. SPDX-License-Identifier: (GPL-2.0 OR MIT)
  2. ===================
  3. J1939 Documentation
  4. ===================
  5. Overview / What Is J1939
  6. ========================
  7. SAE J1939 defines a higher layer protocol on CAN. It implements a more
  8. sophisticated addressing scheme and extends the maximum packet size above 8
  9. bytes. Several derived specifications exist, which differ from the original
  10. J1939 on the application level, like MilCAN A, NMEA2000, and especially
  11. ISO-11783 (ISOBUS). This last one specifies the so-called ETP (Extended
  12. Transport Protocol), which has been included in this implementation. This
  13. results in a maximum packet size of ((2 ^ 24) - 1) * 7 bytes == 111 MiB.
  14. Specifications used
  15. -------------------
  16. * SAE J1939-21 : data link layer
  17. * SAE J1939-81 : network management
  18. * ISO 11783-6 : Virtual Terminal (Extended Transport Protocol)
  19. .. _j1939-motivation:
  20. Motivation
  21. ==========
  22. Given the fact there's something like SocketCAN with an API similar to BSD
  23. sockets, we found some reasons to justify a kernel implementation for the
  24. addressing and transport methods used by J1939.
  25. * **Addressing:** when a process on an ECU communicates via J1939, it should
  26. not necessarily know its source address. Although, at least one process per
  27. ECU should know the source address. Other processes should be able to reuse
  28. that address. This way, address parameters for different processes
  29. cooperating for the same ECU, are not duplicated. This way of working is
  30. closely related to the UNIX concept, where programs do just one thing and do
  31. it well.
  32. * **Dynamic addressing:** Address Claiming in J1939 is time critical.
  33. Furthermore, data transport should be handled properly during the address
  34. negotiation. Putting this functionality in the kernel eliminates it as a
  35. requirement for _every_ user space process that communicates via J1939. This
  36. results in a consistent J1939 bus with proper addressing.
  37. * **Transport:** both TP & ETP reuse some PGNs to relay big packets over them.
  38. Different processes may thus use the same TP & ETP PGNs without actually
  39. knowing it. The individual TP & ETP sessions _must_ be serialized
  40. (synchronized) between different processes. The kernel solves this problem
  41. properly and eliminates the serialization (synchronization) as a requirement
  42. for _every_ user space process that communicates via J1939.
  43. J1939 defines some other features (relaying, gateway, fast packet transport,
  44. ...). In-kernel code for these would not contribute to protocol stability.
  45. Therefore, these parts are left to user space.
  46. The J1939 sockets operate on CAN network devices (see SocketCAN). Any J1939
  47. user space library operating on CAN raw sockets will still operate properly.
  48. Since such a library does not communicate with the in-kernel implementation, care
  49. must be taken that these two do not interfere. In practice, this means they
  50. cannot share ECU addresses. A single ECU (or virtual ECU) address is used by
  51. the library exclusively, or by the in-kernel system exclusively.
  52. J1939 concepts
  53. ==============
  54. PGN
  55. ---
  56. The J1939 protocol uses the 29-bit CAN identifier with the following structure:
  57. ============ ============== ====================
  58. 29 bit CAN-ID
  59. --------------------------------------------------
  60. Bit positions within the CAN-ID
  61. --------------------------------------------------
  62. 28 ... 26 25 ... 8 7 ... 0
  63. ============ ============== ====================
  64. Priority PGN SA (Source Address)
  65. ============ ============== ====================
  66. The PGN (Parameter Group Number) is a number to identify a packet. The PGN
  67. is composed as follows:
  68. ============ ============== ================= =================
  69. PGN
  70. ------------------------------------------------------------------
  71. Bit positions within the CAN-ID
  72. ------------------------------------------------------------------
  73. 25 24 23 ... 16 15 ... 8
  74. ============ ============== ================= =================
  75. R (Reserved) DP (Data Page) PF (PDU Format) PS (PDU Specific)
  76. ============ ============== ================= =================
  77. In J1939-21 distinction is made between PDU1 format (where PF < 240) and PDU2
  78. format (where PF >= 240). Furthermore, when using the PDU2 format, the PS-field
  79. contains a so-called Group Extension, which is part of the PGN. When using PDU2
  80. format, the Group Extension is set in the PS-field.
  81. ============== ========================
  82. PDU1 Format (specific) (peer to peer)
  83. ----------------------------------------
  84. Bit positions within the CAN-ID
  85. ----------------------------------------
  86. 23 ... 16 15 ... 8
  87. ============== ========================
  88. 00h ... EFh DA (Destination address)
  89. ============== ========================
  90. ============== ========================
  91. PDU2 Format (global) (broadcast)
  92. ----------------------------------------
  93. Bit positions within the CAN-ID
  94. ----------------------------------------
  95. 23 ... 16 15 ... 8
  96. ============== ========================
  97. F0h ... FFh GE (Group Extension)
  98. ============== ========================
  99. On the other hand, when using PDU1 format, the PS-field contains a so-called
  100. Destination Address, which is _not_ part of the PGN. When communicating a PGN
  101. from user space to kernel (or vice versa) and PDU1 format is used, the PS-field
  102. of the PGN shall be set to zero. The Destination Address shall be set
  103. elsewhere.
  104. Regarding PGN mapping to 29-bit CAN identifier, the Destination Address shall
  105. be get/set from/to the appropriate bits of the identifier by the kernel.
  106. Addressing
  107. ----------
  108. Both static and dynamic addressing methods can be used.
  109. For static addresses, no extra checks are made by the kernel and provided
  110. addresses are considered right. This responsibility is for the OEM or system
  111. integrator.
  112. For dynamic addressing, so-called Address Claiming, extra support is foreseen
  113. in the kernel. In J1939 any ECU is known by its 64-bit NAME. At the moment of
  114. a successful address claim, the kernel keeps track of both NAME and source
  115. address being claimed. This serves as a base for filter schemes. By default,
  116. packets with a destination that is not locally will be rejected.
  117. Mixed mode packets (from a static to a dynamic address or vice versa) are
  118. allowed. The BSD sockets define separate API calls for getting/setting the
  119. local & remote address and are applicable for J1939 sockets.
  120. Filtering
  121. ---------
  122. J1939 defines white list filters per socket that a user can set in order to
  123. receive a subset of the J1939 traffic. Filtering can be based on:
  124. * SA
  125. * SOURCE_NAME
  126. * PGN
  127. When multiple filters are in place for a single socket, and a packet comes in
  128. that matches several of those filters, the packet is only received once for
  129. that socket.
  130. How to Use J1939
  131. ================
  132. API Calls
  133. ---------
  134. On CAN, you first need to open a socket for communicating over a CAN network.
  135. To use J1939, ``#include <linux/can/j1939.h>``. From there, ``<linux/can.h>`` will be
  136. included too. To open a socket, use:
  137. .. code-block:: C
  138. s = socket(PF_CAN, SOCK_DGRAM, CAN_J1939);
  139. J1939 does use ``SOCK_DGRAM`` sockets. In the J1939 specification, connections are
  140. mentioned in the context of transport protocol sessions. These still deliver
  141. packets to the other end (using several CAN packets). ``SOCK_STREAM`` is not
  142. supported.
  143. After the successful creation of the socket, you would normally use the ``bind(2)``
  144. and/or ``connect(2)`` system call to bind the socket to a CAN interface. After
  145. binding and/or connecting the socket, you can ``read(2)`` and ``write(2)`` from/to the
  146. socket or use ``send(2)``, ``sendto(2)``, ``sendmsg(2)`` and the ``recv*()`` counterpart
  147. operations on the socket as usual. There are also J1939 specific socket options
  148. described below.
  149. In order to send data, a ``bind(2)`` must have been successful. ``bind(2)`` assigns a
  150. local address to a socket.
  151. Different from CAN is that the payload data is just the data that get sends,
  152. without its header info. The header info is derived from the sockaddr supplied
  153. to ``bind(2)``, ``connect(2)``, ``sendto(2)`` and ``recvfrom(2)``. A ``write(2)`` with size 4 will
  154. result in a packet with 4 bytes.
  155. The sockaddr structure has extensions for use with J1939 as specified below:
  156. .. code-block:: C
  157. struct sockaddr_can {
  158. sa_family_t can_family;
  159. int can_ifindex;
  160. union {
  161. struct {
  162. __u64 name;
  163. /* pgn:
  164. * 8 bit: PS in PDU2 case, else 0
  165. * 8 bit: PF
  166. * 1 bit: DP
  167. * 1 bit: reserved
  168. */
  169. __u32 pgn;
  170. __u8 addr;
  171. } j1939;
  172. } can_addr;
  173. }
  174. ``can_family`` & ``can_ifindex`` serve the same purpose as for other SocketCAN sockets.
  175. ``can_addr.j1939.pgn`` specifies the PGN (max 0x3ffff). Individual bits are
  176. specified above.
  177. ``can_addr.j1939.name`` contains the 64-bit J1939 NAME.
  178. ``can_addr.j1939.addr`` contains the address.
  179. The ``bind(2)`` system call assigns the local address, i.e. the source address when
  180. sending packages. If a PGN during ``bind(2)`` is set, it's used as a RX filter.
  181. I.e. only packets with a matching PGN are received. If an ADDR or NAME is set
  182. it is used as a receive filter, too. It will match the destination NAME or ADDR
  183. of the incoming packet. The NAME filter will work only if appropriate Address
  184. Claiming for this name was done on the CAN bus and registered/cached by the
  185. kernel.
  186. On the other hand ``connect(2)`` assigns the remote address, i.e. the destination
  187. address. The PGN from ``connect(2)`` is used as the default PGN when sending
  188. packets. If ADDR or NAME is set it will be used as the default destination ADDR
  189. or NAME. Further a set ADDR or NAME during ``connect(2)`` is used as a receive
  190. filter. It will match the source NAME or ADDR of the incoming packet.
  191. Both ``write(2)`` and ``send(2)`` will send a packet with local address from ``bind(2)`` and the
  192. remote address from ``connect(2)``. Use ``sendto(2)`` to overwrite the destination
  193. address.
  194. If ``can_addr.j1939.name`` is set (!= 0) the NAME is looked up by the kernel and
  195. the corresponding ADDR is used. If ``can_addr.j1939.name`` is not set (== 0),
  196. ``can_addr.j1939.addr`` is used.
  197. When creating a socket, reasonable defaults are set. Some options can be
  198. modified with ``setsockopt(2)`` & ``getsockopt(2)``.
  199. RX path related options:
  200. - ``SO_J1939_FILTER`` - configure array of filters
  201. - ``SO_J1939_PROMISC`` - disable filters set by ``bind(2)`` and ``connect(2)``
  202. By default no broadcast packets can be send or received. To enable sending or
  203. receiving broadcast packets use the socket option ``SO_BROADCAST``:
  204. .. code-block:: C
  205. int value = 1;
  206. setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &value, sizeof(value));
  207. The following diagram illustrates the RX path:
  208. .. code::
  209. +--------------------+
  210. | incoming packet |
  211. +--------------------+
  212. |
  213. V
  214. +--------------------+
  215. | SO_J1939_PROMISC? |
  216. +--------------------+
  217. | |
  218. no | | yes
  219. | |
  220. .---------' `---------.
  221. | |
  222. +---------------------------+ |
  223. | bind() + connect() + | |
  224. | SOCK_BROADCAST filter | |
  225. +---------------------------+ |
  226. | |
  227. |<---------------------'
  228. V
  229. +---------------------------+
  230. | SO_J1939_FILTER |
  231. +---------------------------+
  232. |
  233. V
  234. +---------------------------+
  235. | socket recv() |
  236. +---------------------------+
  237. TX path related options:
  238. ``SO_J1939_SEND_PRIO`` - change default send priority for the socket
  239. Message Flags during send() and Related System Calls
  240. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  241. ``send(2)``, ``sendto(2)`` and ``sendmsg(2)`` take a 'flags' argument. Currently
  242. supported flags are:
  243. * ``MSG_DONTWAIT``, i.e. non-blocking operation.
  244. recvmsg(2)
  245. ^^^^^^^^^^
  246. In most cases ``recvmsg(2)`` is needed if you want to extract more information than
  247. ``recvfrom(2)`` can provide. For example package priority and timestamp. The
  248. Destination Address, name and packet priority (if applicable) are attached to
  249. the msghdr in the ``recvmsg(2)`` call. They can be extracted using ``cmsg(3)`` macros,
  250. with ``cmsg_level == SOL_J1939 && cmsg_type == SCM_J1939_DEST_ADDR``,
  251. ``SCM_J1939_DEST_NAME`` or ``SCM_J1939_PRIO``. The returned data is a ``uint8_t`` for
  252. ``priority`` and ``dst_addr``, and ``uint64_t`` for ``dst_name``.
  253. .. code-block:: C
  254. uint8_t priority, dst_addr;
  255. uint64_t dst_name;
  256. for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
  257. switch (cmsg->cmsg_level) {
  258. case SOL_CAN_J1939:
  259. if (cmsg->cmsg_type == SCM_J1939_DEST_ADDR)
  260. dst_addr = *CMSG_DATA(cmsg);
  261. else if (cmsg->cmsg_type == SCM_J1939_DEST_NAME)
  262. memcpy(&dst_name, CMSG_DATA(cmsg), cmsg->cmsg_len - CMSG_LEN(0));
  263. else if (cmsg->cmsg_type == SCM_J1939_PRIO)
  264. priority = *CMSG_DATA(cmsg);
  265. break;
  266. }
  267. }
  268. Dynamic Addressing
  269. ------------------
  270. Distinction has to be made between using the claimed address and doing an
  271. address claim. To use an already claimed address, one has to fill in the
  272. ``j1939.name`` member and provide it to ``bind(2)``. If the name had claimed an address
  273. earlier, all further messages being sent will use that address. And the
  274. ``j1939.addr`` member will be ignored.
  275. An exception on this is PGN 0x0ee00. This is the "Address Claim/Cannot Claim
  276. Address" message and the kernel will use the ``j1939.addr`` member for that PGN if
  277. necessary.
  278. To claim an address following code example can be used:
  279. .. code-block:: C
  280. struct sockaddr_can baddr = {
  281. .can_family = AF_CAN,
  282. .can_addr.j1939 = {
  283. .name = name,
  284. .addr = J1939_IDLE_ADDR,
  285. .pgn = J1939_NO_PGN, /* to disable bind() rx filter for PGN */
  286. },
  287. .can_ifindex = if_nametoindex("can0"),
  288. };
  289. bind(sock, (struct sockaddr *)&baddr, sizeof(baddr));
  290. /* for Address Claiming broadcast must be allowed */
  291. int value = 1;
  292. setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &value, sizeof(value));
  293. /* configured advanced RX filter with PGN needed for Address Claiming */
  294. const struct j1939_filter filt[] = {
  295. {
  296. .pgn = J1939_PGN_ADDRESS_CLAIMED,
  297. .pgn_mask = J1939_PGN_PDU1_MAX,
  298. }, {
  299. .pgn = J1939_PGN_REQUEST,
  300. .pgn_mask = J1939_PGN_PDU1_MAX,
  301. }, {
  302. .pgn = J1939_PGN_ADDRESS_COMMANDED,
  303. .pgn_mask = J1939_PGN_MAX,
  304. },
  305. };
  306. setsockopt(sock, SOL_CAN_J1939, SO_J1939_FILTER, &filt, sizeof(filt));
  307. uint64_t dat = htole64(name);
  308. const struct sockaddr_can saddr = {
  309. .can_family = AF_CAN,
  310. .can_addr.j1939 = {
  311. .pgn = J1939_PGN_ADDRESS_CLAIMED,
  312. .addr = J1939_NO_ADDR,
  313. },
  314. };
  315. /* Afterwards do a sendto(2) with data set to the NAME (Little Endian). If the
  316. * NAME provided, does not match the j1939.name provided to bind(2), EPROTO
  317. * will be returned.
  318. */
  319. sendto(sock, dat, sizeof(dat), 0, (const struct sockaddr *)&saddr, sizeof(saddr));
  320. If no-one else contests the address claim within 250ms after transmission, the
  321. kernel marks the NAME-SA assignment as valid. The valid assignment will be kept
  322. among other valid NAME-SA assignments. From that point, any socket bound to the
  323. NAME can send packets.
  324. If another ECU claims the address, the kernel will mark the NAME-SA expired.
  325. No socket bound to the NAME can send packets (other than address claims). To
  326. claim another address, some socket bound to NAME, must ``bind(2)`` again, but with
  327. only ``j1939.addr`` changed to the new SA, and must then send a valid address claim
  328. packet. This restarts the state machine in the kernel (and any other
  329. participant on the bus) for this NAME.
  330. ``can-utils`` also include the ``j1939acd`` tool, so it can be used as code example or as
  331. default Address Claiming daemon.
  332. Send Examples
  333. -------------
  334. Static Addressing
  335. ^^^^^^^^^^^^^^^^^
  336. This example will send a PGN (0x12300) from SA 0x20 to DA 0x30.
  337. Bind:
  338. .. code-block:: C
  339. struct sockaddr_can baddr = {
  340. .can_family = AF_CAN,
  341. .can_addr.j1939 = {
  342. .name = J1939_NO_NAME,
  343. .addr = 0x20,
  344. .pgn = J1939_NO_PGN,
  345. },
  346. .can_ifindex = if_nametoindex("can0"),
  347. };
  348. bind(sock, (struct sockaddr *)&baddr, sizeof(baddr));
  349. Now, the socket 'sock' is bound to the SA 0x20. Since no ``connect(2)`` was called,
  350. at this point we can use only ``sendto(2)`` or ``sendmsg(2)``.
  351. Send:
  352. .. code-block:: C
  353. const struct sockaddr_can saddr = {
  354. .can_family = AF_CAN,
  355. .can_addr.j1939 = {
  356. .name = J1939_NO_NAME;
  357. .addr = 0x30,
  358. .pgn = 0x12300,
  359. },
  360. };
  361. sendto(sock, dat, sizeof(dat), 0, (const struct sockaddr *)&saddr, sizeof(saddr));