can.rst 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437
  1. ===================================
  2. SocketCAN - Controller Area Network
  3. ===================================
  4. Overview / What is SocketCAN
  5. ============================
  6. The socketcan package is an implementation of CAN protocols
  7. (Controller Area Network) for Linux. CAN is a networking technology
  8. which has widespread use in automation, embedded devices, and
  9. automotive fields. While there have been other CAN implementations
  10. for Linux based on character devices, SocketCAN uses the Berkeley
  11. socket API, the Linux network stack and implements the CAN device
  12. drivers as network interfaces. The CAN socket API has been designed
  13. as similar as possible to the TCP/IP protocols to allow programmers,
  14. familiar with network programming, to easily learn how to use CAN
  15. sockets.
  16. .. _socketcan-motivation:
  17. Motivation / Why Using the Socket API
  18. =====================================
  19. There have been CAN implementations for Linux before SocketCAN so the
  20. question arises, why we have started another project. Most existing
  21. implementations come as a device driver for some CAN hardware, they
  22. are based on character devices and provide comparatively little
  23. functionality. Usually, there is only a hardware-specific device
  24. driver which provides a character device interface to send and
  25. receive raw CAN frames, directly to/from the controller hardware.
  26. Queueing of frames and higher-level transport protocols like ISO-TP
  27. have to be implemented in user space applications. Also, most
  28. character-device implementations support only one single process to
  29. open the device at a time, similar to a serial interface. Exchanging
  30. the CAN controller requires employment of another device driver and
  31. often the need for adaption of large parts of the application to the
  32. new driver's API.
  33. SocketCAN was designed to overcome all of these limitations. A new
  34. protocol family has been implemented which provides a socket interface
  35. to user space applications and which builds upon the Linux network
  36. layer, enabling use all of the provided queueing functionality. A device
  37. driver for CAN controller hardware registers itself with the Linux
  38. network layer as a network device, so that CAN frames from the
  39. controller can be passed up to the network layer and on to the CAN
  40. protocol family module and also vice-versa. Also, the protocol family
  41. module provides an API for transport protocol modules to register, so
  42. that any number of transport protocols can be loaded or unloaded
  43. dynamically. In fact, the can core module alone does not provide any
  44. protocol and cannot be used without loading at least one additional
  45. protocol module. Multiple sockets can be opened at the same time,
  46. on different or the same protocol module and they can listen/send
  47. frames on different or the same CAN IDs. Several sockets listening on
  48. the same interface for frames with the same CAN ID are all passed the
  49. same received matching CAN frames. An application wishing to
  50. communicate using a specific transport protocol, e.g. ISO-TP, just
  51. selects that protocol when opening the socket, and then can read and
  52. write application data byte streams, without having to deal with
  53. CAN-IDs, frames, etc.
  54. Similar functionality visible from user-space could be provided by a
  55. character device, too, but this would lead to a technically inelegant
  56. solution for a couple of reasons:
  57. * **Intricate usage:** Instead of passing a protocol argument to
  58. socket(2) and using bind(2) to select a CAN interface and CAN ID, an
  59. application would have to do all these operations using ioctl(2)s.
  60. * **Code duplication:** A character device cannot make use of the Linux
  61. network queueing code, so all that code would have to be duplicated
  62. for CAN networking.
  63. * **Abstraction:** In most existing character-device implementations, the
  64. hardware-specific device driver for a CAN controller directly
  65. provides the character device for the application to work with.
  66. This is at least very unusual in Unix systems for both, char and
  67. block devices. For example you don't have a character device for a
  68. certain UART of a serial interface, a certain sound chip in your
  69. computer, a SCSI or IDE controller providing access to your hard
  70. disk or tape streamer device. Instead, you have abstraction layers
  71. which provide a unified character or block device interface to the
  72. application on the one hand, and a interface for hardware-specific
  73. device drivers on the other hand. These abstractions are provided
  74. by subsystems like the tty layer, the audio subsystem or the SCSI
  75. and IDE subsystems for the devices mentioned above.
  76. The easiest way to implement a CAN device driver is as a character
  77. device without such a (complete) abstraction layer, as is done by most
  78. existing drivers. The right way, however, would be to add such a
  79. layer with all the functionality like registering for certain CAN
  80. IDs, supporting several open file descriptors and (de)multiplexing
  81. CAN frames between them, (sophisticated) queueing of CAN frames, and
  82. providing an API for device drivers to register with. However, then
  83. it would be no more difficult, or may be even easier, to use the
  84. networking framework provided by the Linux kernel, and this is what
  85. SocketCAN does.
  86. The use of the networking framework of the Linux kernel is just the
  87. natural and most appropriate way to implement CAN for Linux.
  88. .. _socketcan-concept:
  89. SocketCAN Concept
  90. =================
  91. As described in :ref:`socketcan-motivation` the main goal of SocketCAN is to
  92. provide a socket interface to user space applications which builds
  93. upon the Linux network layer. In contrast to the commonly known
  94. TCP/IP and ethernet networking, the CAN bus is a broadcast-only(!)
  95. medium that has no MAC-layer addressing like ethernet. The CAN-identifier
  96. (can_id) is used for arbitration on the CAN-bus. Therefore the CAN-IDs
  97. have to be chosen uniquely on the bus. When designing a CAN-ECU
  98. network the CAN-IDs are mapped to be sent by a specific ECU.
  99. For this reason a CAN-ID can be treated best as a kind of source address.
  100. .. _socketcan-receive-lists:
  101. Receive Lists
  102. -------------
  103. The network transparent access of multiple applications leads to the
  104. problem that different applications may be interested in the same
  105. CAN-IDs from the same CAN network interface. The SocketCAN core
  106. module - which implements the protocol family CAN - provides several
  107. high efficient receive lists for this reason. If e.g. a user space
  108. application opens a CAN RAW socket, the raw protocol module itself
  109. requests the (range of) CAN-IDs from the SocketCAN core that are
  110. requested by the user. The subscription and unsubscription of
  111. CAN-IDs can be done for specific CAN interfaces or for all(!) known
  112. CAN interfaces with the can_rx_(un)register() functions provided to
  113. CAN protocol modules by the SocketCAN core (see :ref:`socketcan-core-module`).
  114. To optimize the CPU usage at runtime the receive lists are split up
  115. into several specific lists per device that match the requested
  116. filter complexity for a given use-case.
  117. .. _socketcan-local-loopback1:
  118. Local Loopback of Sent Frames
  119. -----------------------------
  120. As known from other networking concepts the data exchanging
  121. applications may run on the same or different nodes without any
  122. change (except for the according addressing information):
  123. .. code::
  124. ___ ___ ___ _______ ___
  125. | _ | | _ | | _ | | _ _ | | _ |
  126. ||A|| ||B|| ||C|| ||A| |B|| ||C||
  127. |___| |___| |___| |_______| |___|
  128. | | | | |
  129. -----------------(1)- CAN bus -(2)---------------
  130. To ensure that application A receives the same information in the
  131. example (2) as it would receive in example (1) there is need for
  132. some kind of local loopback of the sent CAN frames on the appropriate
  133. node.
  134. The Linux network devices (by default) just can handle the
  135. transmission and reception of media dependent frames. Due to the
  136. arbitration on the CAN bus the transmission of a low prio CAN-ID
  137. may be delayed by the reception of a high prio CAN frame. To
  138. reflect the correct [#f1]_ traffic on the node the loopback of the sent
  139. data has to be performed right after a successful transmission. If
  140. the CAN network interface is not capable of performing the loopback for
  141. some reason the SocketCAN core can do this task as a fallback solution.
  142. See :ref:`socketcan-local-loopback1` for details (recommended).
  143. The loopback functionality is enabled by default to reflect standard
  144. networking behaviour for CAN applications. Due to some requests from
  145. the RT-SocketCAN group the loopback optionally may be disabled for each
  146. separate socket. See sockopts from the CAN RAW sockets in :ref:`socketcan-raw-sockets`.
  147. .. [#f1] you really like to have this when you're running analyser
  148. tools like 'candump' or 'cansniffer' on the (same) node.
  149. .. _socketcan-network-problem-notifications:
  150. Network Problem Notifications
  151. -----------------------------
  152. The use of the CAN bus may lead to several problems on the physical
  153. and media access control layer. Detecting and logging of these lower
  154. layer problems is a vital requirement for CAN users to identify
  155. hardware issues on the physical transceiver layer as well as
  156. arbitration problems and error frames caused by the different
  157. ECUs. The occurrence of detected errors are important for diagnosis
  158. and have to be logged together with the exact timestamp. For this
  159. reason the CAN interface driver can generate so called Error Message
  160. Frames that can optionally be passed to the user application in the
  161. same way as other CAN frames. Whenever an error on the physical layer
  162. or the MAC layer is detected (e.g. by the CAN controller) the driver
  163. creates an appropriate error message frame. Error messages frames can
  164. be requested by the user application using the common CAN filter
  165. mechanisms. Inside this filter definition the (interested) type of
  166. errors may be selected. The reception of error messages is disabled
  167. by default. The format of the CAN error message frame is briefly
  168. described in the Linux header file "include/uapi/linux/can/error.h".
  169. How to use SocketCAN
  170. ====================
  171. Like TCP/IP, you first need to open a socket for communicating over a
  172. CAN network. Since SocketCAN implements a new protocol family, you
  173. need to pass PF_CAN as the first argument to the socket(2) system
  174. call. Currently, there are two CAN protocols to choose from, the raw
  175. socket protocol and the broadcast manager (BCM). So to open a socket,
  176. you would write::
  177. s = socket(PF_CAN, SOCK_RAW, CAN_RAW);
  178. and::
  179. s = socket(PF_CAN, SOCK_DGRAM, CAN_BCM);
  180. respectively. After the successful creation of the socket, you would
  181. normally use the bind(2) system call to bind the socket to a CAN
  182. interface (which is different from TCP/IP due to different addressing
  183. - see :ref:`socketcan-concept`). After binding (CAN_RAW) or connecting (CAN_BCM)
  184. the socket, you can read(2) and write(2) from/to the socket or use
  185. send(2), sendto(2), sendmsg(2) and the recv* counterpart operations
  186. on the socket as usual. There are also CAN specific socket options
  187. described below.
  188. The basic CAN frame structure and the sockaddr structure are defined
  189. in include/linux/can.h:
  190. .. code-block:: C
  191. struct can_frame {
  192. canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */
  193. __u8 can_dlc; /* frame payload length in byte (0 .. 8) */
  194. __u8 __pad; /* padding */
  195. __u8 __res0; /* reserved / padding */
  196. __u8 __res1; /* reserved / padding */
  197. __u8 data[8] __attribute__((aligned(8)));
  198. };
  199. The alignment of the (linear) payload data[] to a 64bit boundary
  200. allows the user to define their own structs and unions to easily access
  201. the CAN payload. There is no given byteorder on the CAN bus by
  202. default. A read(2) system call on a CAN_RAW socket transfers a
  203. struct can_frame to the user space.
  204. The sockaddr_can structure has an interface index like the
  205. PF_PACKET socket, that also binds to a specific interface:
  206. .. code-block:: C
  207. struct sockaddr_can {
  208. sa_family_t can_family;
  209. int can_ifindex;
  210. union {
  211. /* transport protocol class address info (e.g. ISOTP) */
  212. struct { canid_t rx_id, tx_id; } tp;
  213. /* reserved for future CAN protocols address information */
  214. } can_addr;
  215. };
  216. To determine the interface index an appropriate ioctl() has to
  217. be used (example for CAN_RAW sockets without error checking):
  218. .. code-block:: C
  219. int s;
  220. struct sockaddr_can addr;
  221. struct ifreq ifr;
  222. s = socket(PF_CAN, SOCK_RAW, CAN_RAW);
  223. strcpy(ifr.ifr_name, "can0" );
  224. ioctl(s, SIOCGIFINDEX, &ifr);
  225. addr.can_family = AF_CAN;
  226. addr.can_ifindex = ifr.ifr_ifindex;
  227. bind(s, (struct sockaddr *)&addr, sizeof(addr));
  228. (..)
  229. To bind a socket to all(!) CAN interfaces the interface index must
  230. be 0 (zero). In this case the socket receives CAN frames from every
  231. enabled CAN interface. To determine the originating CAN interface
  232. the system call recvfrom(2) may be used instead of read(2). To send
  233. on a socket that is bound to 'any' interface sendto(2) is needed to
  234. specify the outgoing interface.
  235. Reading CAN frames from a bound CAN_RAW socket (see above) consists
  236. of reading a struct can_frame:
  237. .. code-block:: C
  238. struct can_frame frame;
  239. nbytes = read(s, &frame, sizeof(struct can_frame));
  240. if (nbytes < 0) {
  241. perror("can raw socket read");
  242. return 1;
  243. }
  244. /* paranoid check ... */
  245. if (nbytes < sizeof(struct can_frame)) {
  246. fprintf(stderr, "read: incomplete CAN frame\n");
  247. return 1;
  248. }
  249. /* do something with the received CAN frame */
  250. Writing CAN frames can be done similarly, with the write(2) system call::
  251. nbytes = write(s, &frame, sizeof(struct can_frame));
  252. When the CAN interface is bound to 'any' existing CAN interface
  253. (addr.can_ifindex = 0) it is recommended to use recvfrom(2) if the
  254. information about the originating CAN interface is needed:
  255. .. code-block:: C
  256. struct sockaddr_can addr;
  257. struct ifreq ifr;
  258. socklen_t len = sizeof(addr);
  259. struct can_frame frame;
  260. nbytes = recvfrom(s, &frame, sizeof(struct can_frame),
  261. 0, (struct sockaddr*)&addr, &len);
  262. /* get interface name of the received CAN frame */
  263. ifr.ifr_ifindex = addr.can_ifindex;
  264. ioctl(s, SIOCGIFNAME, &ifr);
  265. printf("Received a CAN frame from interface %s", ifr.ifr_name);
  266. To write CAN frames on sockets bound to 'any' CAN interface the
  267. outgoing interface has to be defined certainly:
  268. .. code-block:: C
  269. strcpy(ifr.ifr_name, "can0");
  270. ioctl(s, SIOCGIFINDEX, &ifr);
  271. addr.can_ifindex = ifr.ifr_ifindex;
  272. addr.can_family = AF_CAN;
  273. nbytes = sendto(s, &frame, sizeof(struct can_frame),
  274. 0, (struct sockaddr*)&addr, sizeof(addr));
  275. An accurate timestamp can be obtained with an ioctl(2) call after reading
  276. a message from the socket:
  277. .. code-block:: C
  278. struct timeval tv;
  279. ioctl(s, SIOCGSTAMP, &tv);
  280. The timestamp has a resolution of one microsecond and is set automatically
  281. at the reception of a CAN frame.
  282. Remark about CAN FD (flexible data rate) support:
  283. Generally the handling of CAN FD is very similar to the formerly described
  284. examples. The new CAN FD capable CAN controllers support two different
  285. bitrates for the arbitration phase and the payload phase of the CAN FD frame
  286. and up to 64 bytes of payload. This extended payload length breaks all the
  287. kernel interfaces (ABI) which heavily rely on the CAN frame with fixed eight
  288. bytes of payload (struct can_frame) like the CAN_RAW socket. Therefore e.g.
  289. the CAN_RAW socket supports a new socket option CAN_RAW_FD_FRAMES that
  290. switches the socket into a mode that allows the handling of CAN FD frames
  291. and (legacy) CAN frames simultaneously (see :ref:`socketcan-rawfd`).
  292. The struct canfd_frame is defined in include/linux/can.h:
  293. .. code-block:: C
  294. struct canfd_frame {
  295. canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */
  296. __u8 len; /* frame payload length in byte (0 .. 64) */
  297. __u8 flags; /* additional flags for CAN FD */
  298. __u8 __res0; /* reserved / padding */
  299. __u8 __res1; /* reserved / padding */
  300. __u8 data[64] __attribute__((aligned(8)));
  301. };
  302. The struct canfd_frame and the existing struct can_frame have the can_id,
  303. the payload length and the payload data at the same offset inside their
  304. structures. This allows to handle the different structures very similar.
  305. When the content of a struct can_frame is copied into a struct canfd_frame
  306. all structure elements can be used as-is - only the data[] becomes extended.
  307. When introducing the struct canfd_frame it turned out that the data length
  308. code (DLC) of the struct can_frame was used as a length information as the
  309. length and the DLC has a 1:1 mapping in the range of 0 .. 8. To preserve
  310. the easy handling of the length information the canfd_frame.len element
  311. contains a plain length value from 0 .. 64. So both canfd_frame.len and
  312. can_frame.can_dlc are equal and contain a length information and no DLC.
  313. For details about the distinction of CAN and CAN FD capable devices and
  314. the mapping to the bus-relevant data length code (DLC), see :ref:`socketcan-can-fd-driver`.
  315. The length of the two CAN(FD) frame structures define the maximum transfer
  316. unit (MTU) of the CAN(FD) network interface and skbuff data length. Two
  317. definitions are specified for CAN specific MTUs in include/linux/can.h:
  318. .. code-block:: C
  319. #define CAN_MTU (sizeof(struct can_frame)) == 16 => 'legacy' CAN frame
  320. #define CANFD_MTU (sizeof(struct canfd_frame)) == 72 => CAN FD frame
  321. .. _socketcan-raw-sockets:
  322. RAW Protocol Sockets with can_filters (SOCK_RAW)
  323. ------------------------------------------------
  324. Using CAN_RAW sockets is extensively comparable to the commonly
  325. known access to CAN character devices. To meet the new possibilities
  326. provided by the multi user SocketCAN approach, some reasonable
  327. defaults are set at RAW socket binding time:
  328. - The filters are set to exactly one filter receiving everything
  329. - The socket only receives valid data frames (=> no error message frames)
  330. - The loopback of sent CAN frames is enabled (see :ref:`socketcan-local-loopback2`)
  331. - The socket does not receive its own sent frames (in loopback mode)
  332. These default settings may be changed before or after binding the socket.
  333. To use the referenced definitions of the socket options for CAN_RAW
  334. sockets, include <linux/can/raw.h>.
  335. .. _socketcan-rawfilter:
  336. RAW socket option CAN_RAW_FILTER
  337. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  338. The reception of CAN frames using CAN_RAW sockets can be controlled
  339. by defining 0 .. n filters with the CAN_RAW_FILTER socket option.
  340. The CAN filter structure is defined in include/linux/can.h:
  341. .. code-block:: C
  342. struct can_filter {
  343. canid_t can_id;
  344. canid_t can_mask;
  345. };
  346. A filter matches, when:
  347. .. code-block:: C
  348. <received_can_id> & mask == can_id & mask
  349. which is analogous to known CAN controllers hardware filter semantics.
  350. The filter can be inverted in this semantic, when the CAN_INV_FILTER
  351. bit is set in can_id element of the can_filter structure. In
  352. contrast to CAN controller hardware filters the user may set 0 .. n
  353. receive filters for each open socket separately:
  354. .. code-block:: C
  355. struct can_filter rfilter[2];
  356. rfilter[0].can_id = 0x123;
  357. rfilter[0].can_mask = CAN_SFF_MASK;
  358. rfilter[1].can_id = 0x200;
  359. rfilter[1].can_mask = 0x700;
  360. setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter));
  361. To disable the reception of CAN frames on the selected CAN_RAW socket:
  362. .. code-block:: C
  363. setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);
  364. To set the filters to zero filters is quite obsolete as to not read
  365. data causes the raw socket to discard the received CAN frames. But
  366. having this 'send only' use-case we may remove the receive list in the
  367. Kernel to save a little (really a very little!) CPU usage.
  368. CAN Filter Usage Optimisation
  369. .............................
  370. The CAN filters are processed in per-device filter lists at CAN frame
  371. reception time. To reduce the number of checks that need to be performed
  372. while walking through the filter lists the CAN core provides an optimized
  373. filter handling when the filter subscription focusses on a single CAN ID.
  374. For the possible 2048 SFF CAN identifiers the identifier is used as an index
  375. to access the corresponding subscription list without any further checks.
  376. For the 2^29 possible EFF CAN identifiers a 10 bit XOR folding is used as
  377. hash function to retrieve the EFF table index.
  378. To benefit from the optimized filters for single CAN identifiers the
  379. CAN_SFF_MASK or CAN_EFF_MASK have to be set into can_filter.mask together
  380. with set CAN_EFF_FLAG and CAN_RTR_FLAG bits. A set CAN_EFF_FLAG bit in the
  381. can_filter.mask makes clear that it matters whether a SFF or EFF CAN ID is
  382. subscribed. E.g. in the example from above:
  383. .. code-block:: C
  384. rfilter[0].can_id = 0x123;
  385. rfilter[0].can_mask = CAN_SFF_MASK;
  386. both SFF frames with CAN ID 0x123 and EFF frames with 0xXXXXX123 can pass.
  387. To filter for only 0x123 (SFF) and 0x12345678 (EFF) CAN identifiers the
  388. filter has to be defined in this way to benefit from the optimized filters:
  389. .. code-block:: C
  390. struct can_filter rfilter[2];
  391. rfilter[0].can_id = 0x123;
  392. rfilter[0].can_mask = (CAN_EFF_FLAG | CAN_RTR_FLAG | CAN_SFF_MASK);
  393. rfilter[1].can_id = 0x12345678 | CAN_EFF_FLAG;
  394. rfilter[1].can_mask = (CAN_EFF_FLAG | CAN_RTR_FLAG | CAN_EFF_MASK);
  395. setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter));
  396. RAW Socket Option CAN_RAW_ERR_FILTER
  397. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  398. As described in :ref:`socketcan-network-problem-notifications` the CAN interface driver can generate so
  399. called Error Message Frames that can optionally be passed to the user
  400. application in the same way as other CAN frames. The possible
  401. errors are divided into different error classes that may be filtered
  402. using the appropriate error mask. To register for every possible
  403. error condition CAN_ERR_MASK can be used as value for the error mask.
  404. The values for the error mask are defined in linux/can/error.h:
  405. .. code-block:: C
  406. can_err_mask_t err_mask = ( CAN_ERR_TX_TIMEOUT | CAN_ERR_BUSOFF );
  407. setsockopt(s, SOL_CAN_RAW, CAN_RAW_ERR_FILTER,
  408. &err_mask, sizeof(err_mask));
  409. RAW Socket Option CAN_RAW_LOOPBACK
  410. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  411. To meet multi user needs the local loopback is enabled by default
  412. (see :ref:`socketcan-local-loopback1` for details). But in some embedded use-cases
  413. (e.g. when only one application uses the CAN bus) this loopback
  414. functionality can be disabled (separately for each socket):
  415. .. code-block:: C
  416. int loopback = 0; /* 0 = disabled, 1 = enabled (default) */
  417. setsockopt(s, SOL_CAN_RAW, CAN_RAW_LOOPBACK, &loopback, sizeof(loopback));
  418. RAW socket option CAN_RAW_RECV_OWN_MSGS
  419. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  420. When the local loopback is enabled, all the sent CAN frames are
  421. looped back to the open CAN sockets that registered for the CAN
  422. frames' CAN-ID on this given interface to meet the multi user
  423. needs. The reception of the CAN frames on the same socket that was
  424. sending the CAN frame is assumed to be unwanted and therefore
  425. disabled by default. This default behaviour may be changed on
  426. demand:
  427. .. code-block:: C
  428. int recv_own_msgs = 1; /* 0 = disabled (default), 1 = enabled */
  429. setsockopt(s, SOL_CAN_RAW, CAN_RAW_RECV_OWN_MSGS,
  430. &recv_own_msgs, sizeof(recv_own_msgs));
  431. .. _socketcan-rawfd:
  432. RAW Socket Option CAN_RAW_FD_FRAMES
  433. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  434. CAN FD support in CAN_RAW sockets can be enabled with a new socket option
  435. CAN_RAW_FD_FRAMES which is off by default. When the new socket option is
  436. not supported by the CAN_RAW socket (e.g. on older kernels), switching the
  437. CAN_RAW_FD_FRAMES option returns the error -ENOPROTOOPT.
  438. Once CAN_RAW_FD_FRAMES is enabled the application can send both CAN frames
  439. and CAN FD frames. OTOH the application has to handle CAN and CAN FD frames
  440. when reading from the socket:
  441. .. code-block:: C
  442. CAN_RAW_FD_FRAMES enabled: CAN_MTU and CANFD_MTU are allowed
  443. CAN_RAW_FD_FRAMES disabled: only CAN_MTU is allowed (default)
  444. Example:
  445. .. code-block:: C
  446. [ remember: CANFD_MTU == sizeof(struct canfd_frame) ]
  447. struct canfd_frame cfd;
  448. nbytes = read(s, &cfd, CANFD_MTU);
  449. if (nbytes == CANFD_MTU) {
  450. printf("got CAN FD frame with length %d\n", cfd.len);
  451. /* cfd.flags contains valid data */
  452. } else if (nbytes == CAN_MTU) {
  453. printf("got legacy CAN frame with length %d\n", cfd.len);
  454. /* cfd.flags is undefined */
  455. } else {
  456. fprintf(stderr, "read: invalid CAN(FD) frame\n");
  457. return 1;
  458. }
  459. /* the content can be handled independently from the received MTU size */
  460. printf("can_id: %X data length: %d data: ", cfd.can_id, cfd.len);
  461. for (i = 0; i < cfd.len; i++)
  462. printf("%02X ", cfd.data[i]);
  463. When reading with size CANFD_MTU only returns CAN_MTU bytes that have
  464. been received from the socket a legacy CAN frame has been read into the
  465. provided CAN FD structure. Note that the canfd_frame.flags data field is
  466. not specified in the struct can_frame and therefore it is only valid in
  467. CANFD_MTU sized CAN FD frames.
  468. Implementation hint for new CAN applications:
  469. To build a CAN FD aware application use struct canfd_frame as basic CAN
  470. data structure for CAN_RAW based applications. When the application is
  471. executed on an older Linux kernel and switching the CAN_RAW_FD_FRAMES
  472. socket option returns an error: No problem. You'll get legacy CAN frames
  473. or CAN FD frames and can process them the same way.
  474. When sending to CAN devices make sure that the device is capable to handle
  475. CAN FD frames by checking if the device maximum transfer unit is CANFD_MTU.
  476. The CAN device MTU can be retrieved e.g. with a SIOCGIFMTU ioctl() syscall.
  477. RAW socket option CAN_RAW_JOIN_FILTERS
  478. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  479. The CAN_RAW socket can set multiple CAN identifier specific filters that
  480. lead to multiple filters in the af_can.c filter processing. These filters
  481. are indenpendent from each other which leads to logical OR'ed filters when
  482. applied (see :ref:`socketcan-rawfilter`).
  483. This socket option joines the given CAN filters in the way that only CAN
  484. frames are passed to user space that matched *all* given CAN filters. The
  485. semantic for the applied filters is therefore changed to a logical AND.
  486. This is useful especially when the filterset is a combination of filters
  487. where the CAN_INV_FILTER flag is set in order to notch single CAN IDs or
  488. CAN ID ranges from the incoming traffic.
  489. RAW Socket Returned Message Flags
  490. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  491. When using recvmsg() call, the msg->msg_flags may contain following flags:
  492. MSG_DONTROUTE:
  493. set when the received frame was created on the local host.
  494. MSG_CONFIRM:
  495. set when the frame was sent via the socket it is received on.
  496. This flag can be interpreted as a 'transmission confirmation' when the
  497. CAN driver supports the echo of frames on driver level, see
  498. :ref:`socketcan-local-loopback1` and :ref:`socketcan-local-loopback2`.
  499. In order to receive such messages, CAN_RAW_RECV_OWN_MSGS must be set.
  500. Broadcast Manager Protocol Sockets (SOCK_DGRAM)
  501. -----------------------------------------------
  502. The Broadcast Manager protocol provides a command based configuration
  503. interface to filter and send (e.g. cyclic) CAN messages in kernel space.
  504. Receive filters can be used to down sample frequent messages; detect events
  505. such as message contents changes, packet length changes, and do time-out
  506. monitoring of received messages.
  507. Periodic transmission tasks of CAN frames or a sequence of CAN frames can be
  508. created and modified at runtime; both the message content and the two
  509. possible transmit intervals can be altered.
  510. A BCM socket is not intended for sending individual CAN frames using the
  511. struct can_frame as known from the CAN_RAW socket. Instead a special BCM
  512. configuration message is defined. The basic BCM configuration message used
  513. to communicate with the broadcast manager and the available operations are
  514. defined in the linux/can/bcm.h include. The BCM message consists of a
  515. message header with a command ('opcode') followed by zero or more CAN frames.
  516. The broadcast manager sends responses to user space in the same form:
  517. .. code-block:: C
  518. struct bcm_msg_head {
  519. __u32 opcode; /* command */
  520. __u32 flags; /* special flags */
  521. __u32 count; /* run 'count' times with ival1 */
  522. struct timeval ival1, ival2; /* count and subsequent interval */
  523. canid_t can_id; /* unique can_id for task */
  524. __u32 nframes; /* number of can_frames following */
  525. struct can_frame frames[0];
  526. };
  527. The aligned payload 'frames' uses the same basic CAN frame structure defined
  528. at the beginning of :ref:`socketcan-rawfd` and in the include/linux/can.h include. All
  529. messages to the broadcast manager from user space have this structure.
  530. Note a CAN_BCM socket must be connected instead of bound after socket
  531. creation (example without error checking):
  532. .. code-block:: C
  533. int s;
  534. struct sockaddr_can addr;
  535. struct ifreq ifr;
  536. s = socket(PF_CAN, SOCK_DGRAM, CAN_BCM);
  537. strcpy(ifr.ifr_name, "can0");
  538. ioctl(s, SIOCGIFINDEX, &ifr);
  539. addr.can_family = AF_CAN;
  540. addr.can_ifindex = ifr.ifr_ifindex;
  541. connect(s, (struct sockaddr *)&addr, sizeof(addr));
  542. (..)
  543. The broadcast manager socket is able to handle any number of in flight
  544. transmissions or receive filters concurrently. The different RX/TX jobs are
  545. distinguished by the unique can_id in each BCM message. However additional
  546. CAN_BCM sockets are recommended to communicate on multiple CAN interfaces.
  547. When the broadcast manager socket is bound to 'any' CAN interface (=> the
  548. interface index is set to zero) the configured receive filters apply to any
  549. CAN interface unless the sendto() syscall is used to overrule the 'any' CAN
  550. interface index. When using recvfrom() instead of read() to retrieve BCM
  551. socket messages the originating CAN interface is provided in can_ifindex.
  552. Broadcast Manager Operations
  553. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  554. The opcode defines the operation for the broadcast manager to carry out,
  555. or details the broadcast managers response to several events, including
  556. user requests.
  557. Transmit Operations (user space to broadcast manager):
  558. TX_SETUP:
  559. Create (cyclic) transmission task.
  560. TX_DELETE:
  561. Remove (cyclic) transmission task, requires only can_id.
  562. TX_READ:
  563. Read properties of (cyclic) transmission task for can_id.
  564. TX_SEND:
  565. Send one CAN frame.
  566. Transmit Responses (broadcast manager to user space):
  567. TX_STATUS:
  568. Reply to TX_READ request (transmission task configuration).
  569. TX_EXPIRED:
  570. Notification when counter finishes sending at initial interval
  571. 'ival1'. Requires the TX_COUNTEVT flag to be set at TX_SETUP.
  572. Receive Operations (user space to broadcast manager):
  573. RX_SETUP:
  574. Create RX content filter subscription.
  575. RX_DELETE:
  576. Remove RX content filter subscription, requires only can_id.
  577. RX_READ:
  578. Read properties of RX content filter subscription for can_id.
  579. Receive Responses (broadcast manager to user space):
  580. RX_STATUS:
  581. Reply to RX_READ request (filter task configuration).
  582. RX_TIMEOUT:
  583. Cyclic message is detected to be absent (timer ival1 expired).
  584. RX_CHANGED:
  585. BCM message with updated CAN frame (detected content change).
  586. Sent on first message received or on receipt of revised CAN messages.
  587. Broadcast Manager Message Flags
  588. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  589. When sending a message to the broadcast manager the 'flags' element may
  590. contain the following flag definitions which influence the behaviour:
  591. SETTIMER:
  592. Set the values of ival1, ival2 and count
  593. STARTTIMER:
  594. Start the timer with the actual values of ival1, ival2
  595. and count. Starting the timer leads simultaneously to emit a CAN frame.
  596. TX_COUNTEVT:
  597. Create the message TX_EXPIRED when count expires
  598. TX_ANNOUNCE:
  599. A change of data by the process is emitted immediately.
  600. TX_CP_CAN_ID:
  601. Copies the can_id from the message header to each
  602. subsequent frame in frames. This is intended as usage simplification. For
  603. TX tasks the unique can_id from the message header may differ from the
  604. can_id(s) stored for transmission in the subsequent struct can_frame(s).
  605. RX_FILTER_ID:
  606. Filter by can_id alone, no frames required (nframes=0).
  607. RX_CHECK_DLC:
  608. A change of the DLC leads to an RX_CHANGED.
  609. RX_NO_AUTOTIMER:
  610. Prevent automatically starting the timeout monitor.
  611. RX_ANNOUNCE_RESUME:
  612. If passed at RX_SETUP and a receive timeout occurred, a
  613. RX_CHANGED message will be generated when the (cyclic) receive restarts.
  614. TX_RESET_MULTI_IDX:
  615. Reset the index for the multiple frame transmission.
  616. RX_RTR_FRAME:
  617. Send reply for RTR-request (placed in op->frames[0]).
  618. Broadcast Manager Transmission Timers
  619. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  620. Periodic transmission configurations may use up to two interval timers.
  621. In this case the BCM sends a number of messages ('count') at an interval
  622. 'ival1', then continuing to send at another given interval 'ival2'. When
  623. only one timer is needed 'count' is set to zero and only 'ival2' is used.
  624. When SET_TIMER and START_TIMER flag were set the timers are activated.
  625. The timer values can be altered at runtime when only SET_TIMER is set.
  626. Broadcast Manager message sequence transmission
  627. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  628. Up to 256 CAN frames can be transmitted in a sequence in the case of a cyclic
  629. TX task configuration. The number of CAN frames is provided in the 'nframes'
  630. element of the BCM message head. The defined number of CAN frames are added
  631. as array to the TX_SETUP BCM configuration message:
  632. .. code-block:: C
  633. /* create a struct to set up a sequence of four CAN frames */
  634. struct {
  635. struct bcm_msg_head msg_head;
  636. struct can_frame frame[4];
  637. } mytxmsg;
  638. (..)
  639. mytxmsg.msg_head.nframes = 4;
  640. (..)
  641. write(s, &mytxmsg, sizeof(mytxmsg));
  642. With every transmission the index in the array of CAN frames is increased
  643. and set to zero at index overflow.
  644. Broadcast Manager Receive Filter Timers
  645. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  646. The timer values ival1 or ival2 may be set to non-zero values at RX_SETUP.
  647. When the SET_TIMER flag is set the timers are enabled:
  648. ival1:
  649. Send RX_TIMEOUT when a received message is not received again within
  650. the given time. When START_TIMER is set at RX_SETUP the timeout detection
  651. is activated directly - even without a former CAN frame reception.
  652. ival2:
  653. Throttle the received message rate down to the value of ival2. This
  654. is useful to reduce messages for the application when the signal inside the
  655. CAN frame is stateless as state changes within the ival2 periode may get
  656. lost.
  657. Broadcast Manager Multiplex Message Receive Filter
  658. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  659. To filter for content changes in multiplex message sequences an array of more
  660. than one CAN frames can be passed in a RX_SETUP configuration message. The
  661. data bytes of the first CAN frame contain the mask of relevant bits that
  662. have to match in the subsequent CAN frames with the received CAN frame.
  663. If one of the subsequent CAN frames is matching the bits in that frame data
  664. mark the relevant content to be compared with the previous received content.
  665. Up to 257 CAN frames (multiplex filter bit mask CAN frame plus 256 CAN
  666. filters) can be added as array to the TX_SETUP BCM configuration message:
  667. .. code-block:: C
  668. /* usually used to clear CAN frame data[] - beware of endian problems! */
  669. #define U64_DATA(p) (*(unsigned long long*)(p)->data)
  670. struct {
  671. struct bcm_msg_head msg_head;
  672. struct can_frame frame[5];
  673. } msg;
  674. msg.msg_head.opcode = RX_SETUP;
  675. msg.msg_head.can_id = 0x42;
  676. msg.msg_head.flags = 0;
  677. msg.msg_head.nframes = 5;
  678. U64_DATA(&msg.frame[0]) = 0xFF00000000000000ULL; /* MUX mask */
  679. U64_DATA(&msg.frame[1]) = 0x01000000000000FFULL; /* data mask (MUX 0x01) */
  680. U64_DATA(&msg.frame[2]) = 0x0200FFFF000000FFULL; /* data mask (MUX 0x02) */
  681. U64_DATA(&msg.frame[3]) = 0x330000FFFFFF0003ULL; /* data mask (MUX 0x33) */
  682. U64_DATA(&msg.frame[4]) = 0x4F07FC0FF0000000ULL; /* data mask (MUX 0x4F) */
  683. write(s, &msg, sizeof(msg));
  684. Broadcast Manager CAN FD Support
  685. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  686. The programming API of the CAN_BCM depends on struct can_frame which is
  687. given as array directly behind the bcm_msg_head structure. To follow this
  688. schema for the CAN FD frames a new flag 'CAN_FD_FRAME' in the bcm_msg_head
  689. flags indicates that the concatenated CAN frame structures behind the
  690. bcm_msg_head are defined as struct canfd_frame:
  691. .. code-block:: C
  692. struct {
  693. struct bcm_msg_head msg_head;
  694. struct canfd_frame frame[5];
  695. } msg;
  696. msg.msg_head.opcode = RX_SETUP;
  697. msg.msg_head.can_id = 0x42;
  698. msg.msg_head.flags = CAN_FD_FRAME;
  699. msg.msg_head.nframes = 5;
  700. (..)
  701. When using CAN FD frames for multiplex filtering the MUX mask is still
  702. expected in the first 64 bit of the struct canfd_frame data section.
  703. Connected Transport Protocols (SOCK_SEQPACKET)
  704. ----------------------------------------------
  705. (to be written)
  706. Unconnected Transport Protocols (SOCK_DGRAM)
  707. --------------------------------------------
  708. (to be written)
  709. .. _socketcan-core-module:
  710. SocketCAN Core Module
  711. =====================
  712. The SocketCAN core module implements the protocol family
  713. PF_CAN. CAN protocol modules are loaded by the core module at
  714. runtime. The core module provides an interface for CAN protocol
  715. modules to subscribe needed CAN IDs (see :ref:`socketcan-receive-lists`).
  716. can.ko Module Params
  717. --------------------
  718. - **stats_timer**:
  719. To calculate the SocketCAN core statistics
  720. (e.g. current/maximum frames per second) this 1 second timer is
  721. invoked at can.ko module start time by default. This timer can be
  722. disabled by using stattimer=0 on the module commandline.
  723. - **debug**:
  724. (removed since SocketCAN SVN r546)
  725. procfs content
  726. --------------
  727. As described in :ref:`socketcan-receive-lists` the SocketCAN core uses several filter
  728. lists to deliver received CAN frames to CAN protocol modules. These
  729. receive lists, their filters and the count of filter matches can be
  730. checked in the appropriate receive list. All entries contain the
  731. device and a protocol module identifier::
  732. foo@bar:~$ cat /proc/net/can/rcvlist_all
  733. receive list 'rx_all':
  734. (vcan3: no entry)
  735. (vcan2: no entry)
  736. (vcan1: no entry)
  737. device can_id can_mask function userdata matches ident
  738. vcan0 000 00000000 f88e6370 f6c6f400 0 raw
  739. (any: no entry)
  740. In this example an application requests any CAN traffic from vcan0::
  741. rcvlist_all - list for unfiltered entries (no filter operations)
  742. rcvlist_eff - list for single extended frame (EFF) entries
  743. rcvlist_err - list for error message frames masks
  744. rcvlist_fil - list for mask/value filters
  745. rcvlist_inv - list for mask/value filters (inverse semantic)
  746. rcvlist_sff - list for single standard frame (SFF) entries
  747. Additional procfs files in /proc/net/can::
  748. stats - SocketCAN core statistics (rx/tx frames, match ratios, ...)
  749. reset_stats - manual statistic reset
  750. version - prints the SocketCAN core version and the ABI version
  751. Writing Own CAN Protocol Modules
  752. --------------------------------
  753. To implement a new protocol in the protocol family PF_CAN a new
  754. protocol has to be defined in include/linux/can.h .
  755. The prototypes and definitions to use the SocketCAN core can be
  756. accessed by including include/linux/can/core.h .
  757. In addition to functions that register the CAN protocol and the
  758. CAN device notifier chain there are functions to subscribe CAN
  759. frames received by CAN interfaces and to send CAN frames::
  760. can_rx_register - subscribe CAN frames from a specific interface
  761. can_rx_unregister - unsubscribe CAN frames from a specific interface
  762. can_send - transmit a CAN frame (optional with local loopback)
  763. For details see the kerneldoc documentation in net/can/af_can.c or
  764. the source code of net/can/raw.c or net/can/bcm.c .
  765. CAN Network Drivers
  766. ===================
  767. Writing a CAN network device driver is much easier than writing a
  768. CAN character device driver. Similar to other known network device
  769. drivers you mainly have to deal with:
  770. - TX: Put the CAN frame from the socket buffer to the CAN controller.
  771. - RX: Put the CAN frame from the CAN controller to the socket buffer.
  772. See e.g. at Documentation/networking/netdevices.rst . The differences
  773. for writing CAN network device driver are described below:
  774. General Settings
  775. ----------------
  776. .. code-block:: C
  777. dev->type = ARPHRD_CAN; /* the netdevice hardware type */
  778. dev->flags = IFF_NOARP; /* CAN has no arp */
  779. dev->mtu = CAN_MTU; /* sizeof(struct can_frame) -> legacy CAN interface */
  780. or alternative, when the controller supports CAN with flexible data rate:
  781. dev->mtu = CANFD_MTU; /* sizeof(struct canfd_frame) -> CAN FD interface */
  782. The struct can_frame or struct canfd_frame is the payload of each socket
  783. buffer (skbuff) in the protocol family PF_CAN.
  784. .. _socketcan-local-loopback2:
  785. Local Loopback of Sent Frames
  786. -----------------------------
  787. As described in :ref:`socketcan-local-loopback1` the CAN network device driver should
  788. support a local loopback functionality similar to the local echo
  789. e.g. of tty devices. In this case the driver flag IFF_ECHO has to be
  790. set to prevent the PF_CAN core from locally echoing sent frames
  791. (aka loopback) as fallback solution::
  792. dev->flags = (IFF_NOARP | IFF_ECHO);
  793. CAN Controller Hardware Filters
  794. -------------------------------
  795. To reduce the interrupt load on deep embedded systems some CAN
  796. controllers support the filtering of CAN IDs or ranges of CAN IDs.
  797. These hardware filter capabilities vary from controller to
  798. controller and have to be identified as not feasible in a multi-user
  799. networking approach. The use of the very controller specific
  800. hardware filters could make sense in a very dedicated use-case, as a
  801. filter on driver level would affect all users in the multi-user
  802. system. The high efficient filter sets inside the PF_CAN core allow
  803. to set different multiple filters for each socket separately.
  804. Therefore the use of hardware filters goes to the category 'handmade
  805. tuning on deep embedded systems'. The author is running a MPC603e
  806. @133MHz with four SJA1000 CAN controllers from 2002 under heavy bus
  807. load without any problems ...
  808. The Virtual CAN Driver (vcan)
  809. -----------------------------
  810. Similar to the network loopback devices, vcan offers a virtual local
  811. CAN interface. A full qualified address on CAN consists of
  812. - a unique CAN Identifier (CAN ID)
  813. - the CAN bus this CAN ID is transmitted on (e.g. can0)
  814. so in common use cases more than one virtual CAN interface is needed.
  815. The virtual CAN interfaces allow the transmission and reception of CAN
  816. frames without real CAN controller hardware. Virtual CAN network
  817. devices are usually named 'vcanX', like vcan0 vcan1 vcan2 ...
  818. When compiled as a module the virtual CAN driver module is called vcan.ko
  819. Since Linux Kernel version 2.6.24 the vcan driver supports the Kernel
  820. netlink interface to create vcan network devices. The creation and
  821. removal of vcan network devices can be managed with the ip(8) tool::
  822. - Create a virtual CAN network interface:
  823. $ ip link add type vcan
  824. - Create a virtual CAN network interface with a specific name 'vcan42':
  825. $ ip link add dev vcan42 type vcan
  826. - Remove a (virtual CAN) network interface 'vcan42':
  827. $ ip link del vcan42
  828. The CAN Network Device Driver Interface
  829. ---------------------------------------
  830. The CAN network device driver interface provides a generic interface
  831. to setup, configure and monitor CAN network devices. The user can then
  832. configure the CAN device, like setting the bit-timing parameters, via
  833. the netlink interface using the program "ip" from the "IPROUTE2"
  834. utility suite. The following chapter describes briefly how to use it.
  835. Furthermore, the interface uses a common data structure and exports a
  836. set of common functions, which all real CAN network device drivers
  837. should use. Please have a look to the SJA1000 or MSCAN driver to
  838. understand how to use them. The name of the module is can-dev.ko.
  839. Netlink interface to set/get devices properties
  840. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  841. The CAN device must be configured via netlink interface. The supported
  842. netlink message types are defined and briefly described in
  843. "include/linux/can/netlink.h". CAN link support for the program "ip"
  844. of the IPROUTE2 utility suite is available and it can be used as shown
  845. below:
  846. Setting CAN device properties::
  847. $ ip link set can0 type can help
  848. Usage: ip link set DEVICE type can
  849. [ bitrate BITRATE [ sample-point SAMPLE-POINT] ] |
  850. [ tq TQ prop-seg PROP_SEG phase-seg1 PHASE-SEG1
  851. phase-seg2 PHASE-SEG2 [ sjw SJW ] ]
  852. [ dbitrate BITRATE [ dsample-point SAMPLE-POINT] ] |
  853. [ dtq TQ dprop-seg PROP_SEG dphase-seg1 PHASE-SEG1
  854. dphase-seg2 PHASE-SEG2 [ dsjw SJW ] ]
  855. [ loopback { on | off } ]
  856. [ listen-only { on | off } ]
  857. [ triple-sampling { on | off } ]
  858. [ one-shot { on | off } ]
  859. [ berr-reporting { on | off } ]
  860. [ fd { on | off } ]
  861. [ fd-non-iso { on | off } ]
  862. [ presume-ack { on | off } ]
  863. [ restart-ms TIME-MS ]
  864. [ restart ]
  865. Where: BITRATE := { 1..1000000 }
  866. SAMPLE-POINT := { 0.000..0.999 }
  867. TQ := { NUMBER }
  868. PROP-SEG := { 1..8 }
  869. PHASE-SEG1 := { 1..8 }
  870. PHASE-SEG2 := { 1..8 }
  871. SJW := { 1..4 }
  872. RESTART-MS := { 0 | NUMBER }
  873. Display CAN device details and statistics::
  874. $ ip -details -statistics link show can0
  875. 2: can0: <NOARP,UP,LOWER_UP,ECHO> mtu 16 qdisc pfifo_fast state UP qlen 10
  876. link/can
  877. can <TRIPLE-SAMPLING> state ERROR-ACTIVE restart-ms 100
  878. bitrate 125000 sample_point 0.875
  879. tq 125 prop-seg 6 phase-seg1 7 phase-seg2 2 sjw 1
  880. sja1000: tseg1 1..16 tseg2 1..8 sjw 1..4 brp 1..64 brp-inc 1
  881. clock 8000000
  882. re-started bus-errors arbit-lost error-warn error-pass bus-off
  883. 41 17457 0 41 42 41
  884. RX: bytes packets errors dropped overrun mcast
  885. 140859 17608 17457 0 0 0
  886. TX: bytes packets errors dropped carrier collsns
  887. 861 112 0 41 0 0
  888. More info to the above output:
  889. "<TRIPLE-SAMPLING>"
  890. Shows the list of selected CAN controller modes: LOOPBACK,
  891. LISTEN-ONLY, or TRIPLE-SAMPLING.
  892. "state ERROR-ACTIVE"
  893. The current state of the CAN controller: "ERROR-ACTIVE",
  894. "ERROR-WARNING", "ERROR-PASSIVE", "BUS-OFF" or "STOPPED"
  895. "restart-ms 100"
  896. Automatic restart delay time. If set to a non-zero value, a
  897. restart of the CAN controller will be triggered automatically
  898. in case of a bus-off condition after the specified delay time
  899. in milliseconds. By default it's off.
  900. "bitrate 125000 sample-point 0.875"
  901. Shows the real bit-rate in bits/sec and the sample-point in the
  902. range 0.000..0.999. If the calculation of bit-timing parameters
  903. is enabled in the kernel (CONFIG_CAN_CALC_BITTIMING=y), the
  904. bit-timing can be defined by setting the "bitrate" argument.
  905. Optionally the "sample-point" can be specified. By default it's
  906. 0.000 assuming CIA-recommended sample-points.
  907. "tq 125 prop-seg 6 phase-seg1 7 phase-seg2 2 sjw 1"
  908. Shows the time quanta in ns, propagation segment, phase buffer
  909. segment 1 and 2 and the synchronisation jump width in units of
  910. tq. They allow to define the CAN bit-timing in a hardware
  911. independent format as proposed by the Bosch CAN 2.0 spec (see
  912. chapter 8 of http://www.semiconductors.bosch.de/pdf/can2spec.pdf).
  913. "sja1000: tseg1 1..16 tseg2 1..8 sjw 1..4 brp 1..64 brp-inc 1 clock 8000000"
  914. Shows the bit-timing constants of the CAN controller, here the
  915. "sja1000". The minimum and maximum values of the time segment 1
  916. and 2, the synchronisation jump width in units of tq, the
  917. bitrate pre-scaler and the CAN system clock frequency in Hz.
  918. These constants could be used for user-defined (non-standard)
  919. bit-timing calculation algorithms in user-space.
  920. "re-started bus-errors arbit-lost error-warn error-pass bus-off"
  921. Shows the number of restarts, bus and arbitration lost errors,
  922. and the state changes to the error-warning, error-passive and
  923. bus-off state. RX overrun errors are listed in the "overrun"
  924. field of the standard network statistics.
  925. Setting the CAN Bit-Timing
  926. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  927. The CAN bit-timing parameters can always be defined in a hardware
  928. independent format as proposed in the Bosch CAN 2.0 specification
  929. specifying the arguments "tq", "prop_seg", "phase_seg1", "phase_seg2"
  930. and "sjw"::
  931. $ ip link set canX type can tq 125 prop-seg 6 \
  932. phase-seg1 7 phase-seg2 2 sjw 1
  933. If the kernel option CONFIG_CAN_CALC_BITTIMING is enabled, CIA
  934. recommended CAN bit-timing parameters will be calculated if the bit-
  935. rate is specified with the argument "bitrate"::
  936. $ ip link set canX type can bitrate 125000
  937. Note that this works fine for the most common CAN controllers with
  938. standard bit-rates but may *fail* for exotic bit-rates or CAN system
  939. clock frequencies. Disabling CONFIG_CAN_CALC_BITTIMING saves some
  940. space and allows user-space tools to solely determine and set the
  941. bit-timing parameters. The CAN controller specific bit-timing
  942. constants can be used for that purpose. They are listed by the
  943. following command::
  944. $ ip -details link show can0
  945. ...
  946. sja1000: clock 8000000 tseg1 1..16 tseg2 1..8 sjw 1..4 brp 1..64 brp-inc 1
  947. Starting and Stopping the CAN Network Device
  948. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  949. A CAN network device is started or stopped as usual with the command
  950. "ifconfig canX up/down" or "ip link set canX up/down". Be aware that
  951. you *must* define proper bit-timing parameters for real CAN devices
  952. before you can start it to avoid error-prone default settings::
  953. $ ip link set canX up type can bitrate 125000
  954. A device may enter the "bus-off" state if too many errors occurred on
  955. the CAN bus. Then no more messages are received or sent. An automatic
  956. bus-off recovery can be enabled by setting the "restart-ms" to a
  957. non-zero value, e.g.::
  958. $ ip link set canX type can restart-ms 100
  959. Alternatively, the application may realize the "bus-off" condition
  960. by monitoring CAN error message frames and do a restart when
  961. appropriate with the command::
  962. $ ip link set canX type can restart
  963. Note that a restart will also create a CAN error message frame (see
  964. also :ref:`socketcan-network-problem-notifications`).
  965. .. _socketcan-can-fd-driver:
  966. CAN FD (Flexible Data Rate) Driver Support
  967. ------------------------------------------
  968. CAN FD capable CAN controllers support two different bitrates for the
  969. arbitration phase and the payload phase of the CAN FD frame. Therefore a
  970. second bit timing has to be specified in order to enable the CAN FD bitrate.
  971. Additionally CAN FD capable CAN controllers support up to 64 bytes of
  972. payload. The representation of this length in can_frame.can_dlc and
  973. canfd_frame.len for userspace applications and inside the Linux network
  974. layer is a plain value from 0 .. 64 instead of the CAN 'data length code'.
  975. The data length code was a 1:1 mapping to the payload length in the legacy
  976. CAN frames anyway. The payload length to the bus-relevant DLC mapping is
  977. only performed inside the CAN drivers, preferably with the helper
  978. functions can_dlc2len() and can_len2dlc().
  979. The CAN netdevice driver capabilities can be distinguished by the network
  980. devices maximum transfer unit (MTU)::
  981. MTU = 16 (CAN_MTU) => sizeof(struct can_frame) => 'legacy' CAN device
  982. MTU = 72 (CANFD_MTU) => sizeof(struct canfd_frame) => CAN FD capable device
  983. The CAN device MTU can be retrieved e.g. with a SIOCGIFMTU ioctl() syscall.
  984. N.B. CAN FD capable devices can also handle and send legacy CAN frames.
  985. When configuring CAN FD capable CAN controllers an additional 'data' bitrate
  986. has to be set. This bitrate for the data phase of the CAN FD frame has to be
  987. at least the bitrate which was configured for the arbitration phase. This
  988. second bitrate is specified analogue to the first bitrate but the bitrate
  989. setting keywords for the 'data' bitrate start with 'd' e.g. dbitrate,
  990. dsample-point, dsjw or dtq and similar settings. When a data bitrate is set
  991. within the configuration process the controller option "fd on" can be
  992. specified to enable the CAN FD mode in the CAN controller. This controller
  993. option also switches the device MTU to 72 (CANFD_MTU).
  994. The first CAN FD specification presented as whitepaper at the International
  995. CAN Conference 2012 needed to be improved for data integrity reasons.
  996. Therefore two CAN FD implementations have to be distinguished today:
  997. - ISO compliant: The ISO 11898-1:2015 CAN FD implementation (default)
  998. - non-ISO compliant: The CAN FD implementation following the 2012 whitepaper
  999. Finally there are three types of CAN FD controllers:
  1000. 1. ISO compliant (fixed)
  1001. 2. non-ISO compliant (fixed, like the M_CAN IP core v3.0.1 in m_can.c)
  1002. 3. ISO/non-ISO CAN FD controllers (switchable, like the PEAK PCAN-USB FD)
  1003. The current ISO/non-ISO mode is announced by the CAN controller driver via
  1004. netlink and displayed by the 'ip' tool (controller option FD-NON-ISO).
  1005. The ISO/non-ISO-mode can be altered by setting 'fd-non-iso {on|off}' for
  1006. switchable CAN FD controllers only.
  1007. Example configuring 500 kbit/s arbitration bitrate and 4 Mbit/s data bitrate::
  1008. $ ip link set can0 up type can bitrate 500000 sample-point 0.75 \
  1009. dbitrate 4000000 dsample-point 0.8 fd on
  1010. $ ip -details link show can0
  1011. 5: can0: <NOARP,UP,LOWER_UP,ECHO> mtu 72 qdisc pfifo_fast state UNKNOWN \
  1012. mode DEFAULT group default qlen 10
  1013. link/can promiscuity 0
  1014. can <FD> state ERROR-ACTIVE (berr-counter tx 0 rx 0) restart-ms 0
  1015. bitrate 500000 sample-point 0.750
  1016. tq 50 prop-seg 14 phase-seg1 15 phase-seg2 10 sjw 1
  1017. pcan_usb_pro_fd: tseg1 1..64 tseg2 1..16 sjw 1..16 brp 1..1024 \
  1018. brp-inc 1
  1019. dbitrate 4000000 dsample-point 0.800
  1020. dtq 12 dprop-seg 7 dphase-seg1 8 dphase-seg2 4 dsjw 1
  1021. pcan_usb_pro_fd: dtseg1 1..16 dtseg2 1..8 dsjw 1..4 dbrp 1..1024 \
  1022. dbrp-inc 1
  1023. clock 80000000
  1024. Example when 'fd-non-iso on' is added on this switchable CAN FD adapter::
  1025. can <FD,FD-NON-ISO> state ERROR-ACTIVE (berr-counter tx 0 rx 0) restart-ms 0
  1026. Supported CAN Hardware
  1027. ----------------------
  1028. Please check the "Kconfig" file in "drivers/net/can" to get an actual
  1029. list of the support CAN hardware. On the SocketCAN project website
  1030. (see :ref:`socketcan-resources`) there might be further drivers available, also for
  1031. older kernel versions.
  1032. .. _socketcan-resources:
  1033. SocketCAN Resources
  1034. ===================
  1035. The Linux CAN / SocketCAN project resources (project site / mailing list)
  1036. are referenced in the MAINTAINERS file in the Linux source tree.
  1037. Search for CAN NETWORK [LAYERS|DRIVERS].
  1038. Credits
  1039. =======
  1040. - Oliver Hartkopp (PF_CAN core, filters, drivers, bcm, SJA1000 driver)
  1041. - Urs Thuermann (PF_CAN core, kernel integration, socket interfaces, raw, vcan)
  1042. - Jan Kizka (RT-SocketCAN core, Socket-API reconciliation)
  1043. - Wolfgang Grandegger (RT-SocketCAN core & drivers, Raw Socket-API reviews, CAN device driver interface, MSCAN driver)
  1044. - Robert Schwebel (design reviews, PTXdist integration)
  1045. - Marc Kleine-Budde (design reviews, Kernel 2.6 cleanups, drivers)
  1046. - Benedikt Spranger (reviews)
  1047. - Thomas Gleixner (LKML reviews, coding style, posting hints)
  1048. - Andrey Volkov (kernel subtree structure, ioctls, MSCAN driver)
  1049. - Matthias Brukner (first SJA1000 CAN netdevice implementation Q2/2003)
  1050. - Klaus Hitschler (PEAK driver integration)
  1051. - Uwe Koppe (CAN netdevices with PF_PACKET approach)
  1052. - Michael Schulze (driver layer loopback requirement, RT CAN drivers review)
  1053. - Pavel Pisa (Bit-timing calculation)
  1054. - Sascha Hauer (SJA1000 platform driver)
  1055. - Sebastian Haas (SJA1000 EMS PCI driver)
  1056. - Markus Plessing (SJA1000 EMS PCI driver)
  1057. - Per Dalen (SJA1000 Kvaser PCI driver)
  1058. - Sam Ravnborg (reviews, coding style, kbuild help)