can.txt 55 KB

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