can.txt 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837
  1. ============================================================================
  2. can.txt
  3. Readme file for the Controller Area Network Protocol Family (aka Socket CAN)
  4. This file contains
  5. 1 Overview / What is Socket CAN
  6. 2 Motivation / Why using the socket API
  7. 3 Socket CAN concept
  8. 3.1 receive lists
  9. 3.2 local loopback of sent frames
  10. 3.3 network security issues (capabilities)
  11. 3.4 network problem notifications
  12. 4 How to use Socket CAN
  13. 4.1 RAW protocol sockets with can_filters (SOCK_RAW)
  14. 4.1.1 RAW socket option CAN_RAW_FILTER
  15. 4.1.2 RAW socket option CAN_RAW_ERR_FILTER
  16. 4.1.3 RAW socket option CAN_RAW_LOOPBACK
  17. 4.1.4 RAW socket option CAN_RAW_RECV_OWN_MSGS
  18. 4.1.5 RAW socket returned message flags
  19. 4.2 Broadcast Manager protocol sockets (SOCK_DGRAM)
  20. 4.3 connected transport protocols (SOCK_SEQPACKET)
  21. 4.4 unconnected transport protocols (SOCK_DGRAM)
  22. 5 Socket CAN core module
  23. 5.1 can.ko module params
  24. 5.2 procfs content
  25. 5.3 writing own CAN protocol modules
  26. 6 CAN network drivers
  27. 6.1 general settings
  28. 6.2 local loopback of sent frames
  29. 6.3 CAN controller hardware filters
  30. 6.4 The virtual CAN driver (vcan)
  31. 6.5 The CAN network device driver interface
  32. 6.5.1 Netlink interface to set/get devices properties
  33. 6.5.2 Setting the CAN bit-timing
  34. 6.5.3 Starting and stopping the CAN network device
  35. 6.6 supported CAN hardware
  36. 7 Socket CAN resources
  37. 8 Credits
  38. ============================================================================
  39. 1. Overview / What is Socket CAN
  40. --------------------------------
  41. The socketcan package is an implementation of CAN protocols
  42. (Controller Area Network) for Linux. CAN is a networking technology
  43. which has widespread use in automation, embedded devices, and
  44. automotive fields. While there have been other CAN implementations
  45. for Linux based on character devices, Socket CAN uses the Berkeley
  46. socket API, the Linux network stack and implements the CAN device
  47. drivers as network interfaces. The CAN socket API has been designed
  48. as similar as possible to the TCP/IP protocols to allow programmers,
  49. familiar with network programming, to easily learn how to use CAN
  50. sockets.
  51. 2. Motivation / Why using the socket API
  52. ----------------------------------------
  53. There have been CAN implementations for Linux before Socket CAN so the
  54. question arises, why we have started another project. Most existing
  55. implementations come as a device driver for some CAN hardware, they
  56. are based on character devices and provide comparatively little
  57. functionality. Usually, there is only a hardware-specific device
  58. driver which provides a character device interface to send and
  59. receive raw CAN frames, directly to/from the controller hardware.
  60. Queueing of frames and higher-level transport protocols like ISO-TP
  61. have to be implemented in user space applications. Also, most
  62. character-device implementations support only one single process to
  63. open the device at a time, similar to a serial interface. Exchanging
  64. the CAN controller requires employment of another device driver and
  65. often the need for adaption of large parts of the application to the
  66. new driver's API.
  67. Socket CAN was designed to overcome all of these limitations. A new
  68. protocol family has been implemented which provides a socket interface
  69. to user space applications and which builds upon the Linux network
  70. layer, so to use all of the provided queueing functionality. A device
  71. driver for CAN controller hardware registers itself with the Linux
  72. network layer as a network device, so that CAN frames from the
  73. controller can be passed up to the network layer and on to the CAN
  74. protocol family module and also vice-versa. Also, the protocol family
  75. module provides an API for transport protocol modules to register, so
  76. that any number of transport protocols can be loaded or unloaded
  77. dynamically. In fact, the can core module alone does not provide any
  78. protocol and cannot be used without loading at least one additional
  79. protocol module. Multiple sockets can be opened at the same time,
  80. on different or the same protocol module and they can listen/send
  81. frames on different or the same CAN IDs. Several sockets listening on
  82. the same interface for frames with the same CAN ID are all passed the
  83. same received matching CAN frames. An application wishing to
  84. communicate using a specific transport protocol, e.g. ISO-TP, just
  85. selects that protocol when opening the socket, and then can read and
  86. write application data byte streams, without having to deal with
  87. CAN-IDs, frames, etc.
  88. Similar functionality visible from user-space could be provided by a
  89. character device, too, but this would lead to a technically inelegant
  90. solution for a couple of reasons:
  91. * Intricate usage. Instead of passing a protocol argument to
  92. socket(2) and using bind(2) to select a CAN interface and CAN ID, an
  93. application would have to do all these operations using ioctl(2)s.
  94. * Code duplication. A character device cannot make use of the Linux
  95. network queueing code, so all that code would have to be duplicated
  96. for CAN networking.
  97. * Abstraction. In most existing character-device implementations, the
  98. hardware-specific device driver for a CAN controller directly
  99. provides the character device for the application to work with.
  100. This is at least very unusual in Unix systems for both, char and
  101. block devices. For example you don't have a character device for a
  102. certain UART of a serial interface, a certain sound chip in your
  103. computer, a SCSI or IDE controller providing access to your hard
  104. disk or tape streamer device. Instead, you have abstraction layers
  105. which provide a unified character or block device interface to the
  106. application on the one hand, and a interface for hardware-specific
  107. device drivers on the other hand. These abstractions are provided
  108. by subsystems like the tty layer, the audio subsystem or the SCSI
  109. and IDE subsystems for the devices mentioned above.
  110. The easiest way to implement a CAN device driver is as a character
  111. device without such a (complete) abstraction layer, as is done by most
  112. existing drivers. The right way, however, would be to add such a
  113. layer with all the functionality like registering for certain CAN
  114. IDs, supporting several open file descriptors and (de)multiplexing
  115. CAN frames between them, (sophisticated) queueing of CAN frames, and
  116. providing an API for device drivers to register with. However, then
  117. it would be no more difficult, or may be even easier, to use the
  118. networking framework provided by the Linux kernel, and this is what
  119. Socket CAN does.
  120. The use of the networking framework of the Linux kernel is just the
  121. natural and most appropriate way to implement CAN for Linux.
  122. 3. Socket CAN concept
  123. ---------------------
  124. As described in chapter 2 it is the main goal of Socket CAN to
  125. provide a socket interface to user space applications which builds
  126. upon the Linux network layer. In contrast to the commonly known
  127. TCP/IP and ethernet networking, the CAN bus is a broadcast-only(!)
  128. medium that has no MAC-layer addressing like ethernet. The CAN-identifier
  129. (can_id) is used for arbitration on the CAN-bus. Therefore the CAN-IDs
  130. have to be chosen uniquely on the bus. When designing a CAN-ECU
  131. network the CAN-IDs are mapped to be sent by a specific ECU.
  132. For this reason a CAN-ID can be treated best as a kind of source address.
  133. 3.1 receive lists
  134. The network transparent access of multiple applications leads to the
  135. problem that different applications may be interested in the same
  136. CAN-IDs from the same CAN network interface. The Socket CAN core
  137. module - which implements the protocol family CAN - provides several
  138. high efficient receive lists for this reason. If e.g. a user space
  139. application opens a CAN RAW socket, the raw protocol module itself
  140. requests the (range of) CAN-IDs from the Socket CAN core that are
  141. requested by the user. The subscription and unsubscription of
  142. CAN-IDs can be done for specific CAN interfaces or for all(!) known
  143. CAN interfaces with the can_rx_(un)register() functions provided to
  144. CAN protocol modules by the SocketCAN core (see chapter 5).
  145. To optimize the CPU usage at runtime the receive lists are split up
  146. into several specific lists per device that match the requested
  147. filter complexity for a given use-case.
  148. 3.2 local loopback of sent frames
  149. As known from other networking concepts the data exchanging
  150. applications may run on the same or different nodes without any
  151. change (except for the according addressing information):
  152. ___ ___ ___ _______ ___
  153. | _ | | _ | | _ | | _ _ | | _ |
  154. ||A|| ||B|| ||C|| ||A| |B|| ||C||
  155. |___| |___| |___| |_______| |___|
  156. | | | | |
  157. -----------------(1)- CAN bus -(2)---------------
  158. To ensure that application A receives the same information in the
  159. example (2) as it would receive in example (1) there is need for
  160. some kind of local loopback of the sent CAN frames on the appropriate
  161. node.
  162. The Linux network devices (by default) just can handle the
  163. transmission and reception of media dependent frames. Due to the
  164. arbitration on the CAN bus the transmission of a low prio CAN-ID
  165. may be delayed by the reception of a high prio CAN frame. To
  166. reflect the correct* traffic on the node the loopback of the sent
  167. data has to be performed right after a successful transmission. If
  168. the CAN network interface is not capable of performing the loopback for
  169. some reason the SocketCAN core can do this task as a fallback solution.
  170. See chapter 6.2 for details (recommended).
  171. The loopback functionality is enabled by default to reflect standard
  172. networking behaviour for CAN applications. Due to some requests from
  173. the RT-SocketCAN group the loopback optionally may be disabled for each
  174. separate socket. See sockopts from the CAN RAW sockets in chapter 4.1.
  175. * = you really like to have this when you're running analyser tools
  176. like 'candump' or 'cansniffer' on the (same) node.
  177. 3.3 network security issues (capabilities)
  178. The Controller Area Network is a local field bus transmitting only
  179. broadcast messages without any routing and security concepts.
  180. In the majority of cases the user application has to deal with
  181. raw CAN frames. Therefore it might be reasonable NOT to restrict
  182. the CAN access only to the user root, as known from other networks.
  183. Since the currently implemented CAN_RAW and CAN_BCM sockets can only
  184. send and receive frames to/from CAN interfaces it does not affect
  185. security of others networks to allow all users to access the CAN.
  186. To enable non-root users to access CAN_RAW and CAN_BCM protocol
  187. sockets the Kconfig options CAN_RAW_USER and/or CAN_BCM_USER may be
  188. selected at kernel compile time.
  189. 3.4 network problem notifications
  190. The use of the CAN bus may lead to several problems on the physical
  191. and media access control layer. Detecting and logging of these lower
  192. layer problems is a vital requirement for CAN users to identify
  193. hardware issues on the physical transceiver layer as well as
  194. arbitration problems and error frames caused by the different
  195. ECUs. The occurrence of detected errors are important for diagnosis
  196. and have to be logged together with the exact timestamp. For this
  197. reason the CAN interface driver can generate so called Error Frames
  198. that can optionally be passed to the user application in the same
  199. way as other CAN frames. Whenever an error on the physical layer
  200. or the MAC layer is detected (e.g. by the CAN controller) the driver
  201. creates an appropriate error frame. Error frames can be requested by
  202. the user application using the common CAN filter mechanisms. Inside
  203. this filter definition the (interested) type of errors may be
  204. selected. The reception of error frames is disabled by default.
  205. The format of the CAN error frame is briefly described in the Linux
  206. header file "include/linux/can/error.h".
  207. 4. How to use Socket CAN
  208. ------------------------
  209. Like TCP/IP, you first need to open a socket for communicating over a
  210. CAN network. Since Socket CAN implements a new protocol family, you
  211. need to pass PF_CAN as the first argument to the socket(2) system
  212. call. Currently, there are two CAN protocols to choose from, the raw
  213. socket protocol and the broadcast manager (BCM). So to open a socket,
  214. you would write
  215. s = socket(PF_CAN, SOCK_RAW, CAN_RAW);
  216. and
  217. s = socket(PF_CAN, SOCK_DGRAM, CAN_BCM);
  218. respectively. After the successful creation of the socket, you would
  219. normally use the bind(2) system call to bind the socket to a CAN
  220. interface (which is different from TCP/IP due to different addressing
  221. - see chapter 3). After binding (CAN_RAW) or connecting (CAN_BCM)
  222. the socket, you can read(2) and write(2) from/to the socket or use
  223. send(2), sendto(2), sendmsg(2) and the recv* counterpart operations
  224. on the socket as usual. There are also CAN specific socket options
  225. described below.
  226. The basic CAN frame structure and the sockaddr structure are defined
  227. in include/linux/can.h:
  228. struct can_frame {
  229. canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */
  230. __u8 can_dlc; /* data length code: 0 .. 8 */
  231. __u8 data[8] __attribute__((aligned(8)));
  232. };
  233. The alignment of the (linear) payload data[] to a 64bit boundary
  234. allows the user to define own structs and unions to easily access the
  235. CAN payload. There is no given byteorder on the CAN bus by
  236. default. A read(2) system call on a CAN_RAW socket transfers a
  237. struct can_frame to the user space.
  238. The sockaddr_can structure has an interface index like the
  239. PF_PACKET socket, that also binds to a specific interface:
  240. struct sockaddr_can {
  241. sa_family_t can_family;
  242. int can_ifindex;
  243. union {
  244. /* transport protocol class address info (e.g. ISOTP) */
  245. struct { canid_t rx_id, tx_id; } tp;
  246. /* reserved for future CAN protocols address information */
  247. } can_addr;
  248. };
  249. To determine the interface index an appropriate ioctl() has to
  250. be used (example for CAN_RAW sockets without error checking):
  251. int s;
  252. struct sockaddr_can addr;
  253. struct ifreq ifr;
  254. s = socket(PF_CAN, SOCK_RAW, CAN_RAW);
  255. strcpy(ifr.ifr_name, "can0" );
  256. ioctl(s, SIOCGIFINDEX, &ifr);
  257. addr.can_family = AF_CAN;
  258. addr.can_ifindex = ifr.ifr_ifindex;
  259. bind(s, (struct sockaddr *)&addr, sizeof(addr));
  260. (..)
  261. To bind a socket to all(!) CAN interfaces the interface index must
  262. be 0 (zero). In this case the socket receives CAN frames from every
  263. enabled CAN interface. To determine the originating CAN interface
  264. the system call recvfrom(2) may be used instead of read(2). To send
  265. on a socket that is bound to 'any' interface sendto(2) is needed to
  266. specify the outgoing interface.
  267. Reading CAN frames from a bound CAN_RAW socket (see above) consists
  268. of reading a struct can_frame:
  269. struct can_frame frame;
  270. nbytes = read(s, &frame, sizeof(struct can_frame));
  271. if (nbytes < 0) {
  272. perror("can raw socket read");
  273. return 1;
  274. }
  275. /* paranoid check ... */
  276. if (nbytes < sizeof(struct can_frame)) {
  277. fprintf(stderr, "read: incomplete CAN frame\n");
  278. return 1;
  279. }
  280. /* do something with the received CAN frame */
  281. Writing CAN frames can be done similarly, with the write(2) system call:
  282. nbytes = write(s, &frame, sizeof(struct can_frame));
  283. When the CAN interface is bound to 'any' existing CAN interface
  284. (addr.can_ifindex = 0) it is recommended to use recvfrom(2) if the
  285. information about the originating CAN interface is needed:
  286. struct sockaddr_can addr;
  287. struct ifreq ifr;
  288. socklen_t len = sizeof(addr);
  289. struct can_frame frame;
  290. nbytes = recvfrom(s, &frame, sizeof(struct can_frame),
  291. 0, (struct sockaddr*)&addr, &len);
  292. /* get interface name of the received CAN frame */
  293. ifr.ifr_ifindex = addr.can_ifindex;
  294. ioctl(s, SIOCGIFNAME, &ifr);
  295. printf("Received a CAN frame from interface %s", ifr.ifr_name);
  296. To write CAN frames on sockets bound to 'any' CAN interface the
  297. outgoing interface has to be defined certainly.
  298. strcpy(ifr.ifr_name, "can0");
  299. ioctl(s, SIOCGIFINDEX, &ifr);
  300. addr.can_ifindex = ifr.ifr_ifindex;
  301. addr.can_family = AF_CAN;
  302. nbytes = sendto(s, &frame, sizeof(struct can_frame),
  303. 0, (struct sockaddr*)&addr, sizeof(addr));
  304. 4.1 RAW protocol sockets with can_filters (SOCK_RAW)
  305. Using CAN_RAW sockets is extensively comparable to the commonly
  306. known access to CAN character devices. To meet the new possibilities
  307. provided by the multi user SocketCAN approach, some reasonable
  308. defaults are set at RAW socket binding time:
  309. - The filters are set to exactly one filter receiving everything
  310. - The socket only receives valid data frames (=> no error frames)
  311. - The loopback of sent CAN frames is enabled (see chapter 3.2)
  312. - The socket does not receive its own sent frames (in loopback mode)
  313. These default settings may be changed before or after binding the socket.
  314. To use the referenced definitions of the socket options for CAN_RAW
  315. sockets, include <linux/can/raw.h>.
  316. 4.1.1 RAW socket option CAN_RAW_FILTER
  317. The reception of CAN frames using CAN_RAW sockets can be controlled
  318. by defining 0 .. n filters with the CAN_RAW_FILTER socket option.
  319. The CAN filter structure is defined in include/linux/can.h:
  320. struct can_filter {
  321. canid_t can_id;
  322. canid_t can_mask;
  323. };
  324. A filter matches, when
  325. <received_can_id> & mask == can_id & mask
  326. which is analogous to known CAN controllers hardware filter semantics.
  327. The filter can be inverted in this semantic, when the CAN_INV_FILTER
  328. bit is set in can_id element of the can_filter structure. In
  329. contrast to CAN controller hardware filters the user may set 0 .. n
  330. receive filters for each open socket separately:
  331. struct can_filter rfilter[2];
  332. rfilter[0].can_id = 0x123;
  333. rfilter[0].can_mask = CAN_SFF_MASK;
  334. rfilter[1].can_id = 0x200;
  335. rfilter[1].can_mask = 0x700;
  336. setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter));
  337. To disable the reception of CAN frames on the selected CAN_RAW socket:
  338. setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);
  339. To set the filters to zero filters is quite obsolete as not read
  340. data causes the raw socket to discard the received CAN frames. But
  341. having this 'send only' use-case we may remove the receive list in the
  342. Kernel to save a little (really a very little!) CPU usage.
  343. 4.1.2 RAW socket option CAN_RAW_ERR_FILTER
  344. As described in chapter 3.4 the CAN interface driver can generate so
  345. called Error Frames that can optionally be passed to the user
  346. application in the same way as other CAN frames. The possible
  347. errors are divided into different error classes that may be filtered
  348. using the appropriate error mask. To register for every possible
  349. error condition CAN_ERR_MASK can be used as value for the error mask.
  350. The values for the error mask are defined in linux/can/error.h .
  351. can_err_mask_t err_mask = ( CAN_ERR_TX_TIMEOUT | CAN_ERR_BUSOFF );
  352. setsockopt(s, SOL_CAN_RAW, CAN_RAW_ERR_FILTER,
  353. &err_mask, sizeof(err_mask));
  354. 4.1.3 RAW socket option CAN_RAW_LOOPBACK
  355. To meet multi user needs the local loopback is enabled by default
  356. (see chapter 3.2 for details). But in some embedded use-cases
  357. (e.g. when only one application uses the CAN bus) this loopback
  358. functionality can be disabled (separately for each socket):
  359. int loopback = 0; /* 0 = disabled, 1 = enabled (default) */
  360. setsockopt(s, SOL_CAN_RAW, CAN_RAW_LOOPBACK, &loopback, sizeof(loopback));
  361. 4.1.4 RAW socket option CAN_RAW_RECV_OWN_MSGS
  362. When the local loopback is enabled, all the sent CAN frames are
  363. looped back to the open CAN sockets that registered for the CAN
  364. frames' CAN-ID on this given interface to meet the multi user
  365. needs. The reception of the CAN frames on the same socket that was
  366. sending the CAN frame is assumed to be unwanted and therefore
  367. disabled by default. This default behaviour may be changed on
  368. demand:
  369. int recv_own_msgs = 1; /* 0 = disabled (default), 1 = enabled */
  370. setsockopt(s, SOL_CAN_RAW, CAN_RAW_RECV_OWN_MSGS,
  371. &recv_own_msgs, sizeof(recv_own_msgs));
  372. 4.1.5 RAW socket returned message flags
  373. When using recvmsg() call, the msg->msg_flags may contain following flags:
  374. MSG_DONTROUTE: set when the received frame was created on the local host.
  375. MSG_CONFIRM: set when the frame was sent via the socket it is received on.
  376. This flag can be interpreted as a 'transmission confirmation' when the
  377. CAN driver supports the echo of frames on driver level, see 3.2 and 6.2.
  378. In order to receive such messages, CAN_RAW_RECV_OWN_MSGS must be set.
  379. 4.2 Broadcast Manager protocol sockets (SOCK_DGRAM)
  380. 4.3 connected transport protocols (SOCK_SEQPACKET)
  381. 4.4 unconnected transport protocols (SOCK_DGRAM)
  382. 5. Socket CAN core module
  383. -------------------------
  384. The Socket CAN core module implements the protocol family
  385. PF_CAN. CAN protocol modules are loaded by the core module at
  386. runtime. The core module provides an interface for CAN protocol
  387. modules to subscribe needed CAN IDs (see chapter 3.1).
  388. 5.1 can.ko module params
  389. - stats_timer: To calculate the Socket CAN core statistics
  390. (e.g. current/maximum frames per second) this 1 second timer is
  391. invoked at can.ko module start time by default. This timer can be
  392. disabled by using stattimer=0 on the module commandline.
  393. - debug: (removed since SocketCAN SVN r546)
  394. 5.2 procfs content
  395. As described in chapter 3.1 the Socket CAN core uses several filter
  396. lists to deliver received CAN frames to CAN protocol modules. These
  397. receive lists, their filters and the count of filter matches can be
  398. checked in the appropriate receive list. All entries contain the
  399. device and a protocol module identifier:
  400. foo@bar:~$ cat /proc/net/can/rcvlist_all
  401. receive list 'rx_all':
  402. (vcan3: no entry)
  403. (vcan2: no entry)
  404. (vcan1: no entry)
  405. device can_id can_mask function userdata matches ident
  406. vcan0 000 00000000 f88e6370 f6c6f400 0 raw
  407. (any: no entry)
  408. In this example an application requests any CAN traffic from vcan0.
  409. rcvlist_all - list for unfiltered entries (no filter operations)
  410. rcvlist_eff - list for single extended frame (EFF) entries
  411. rcvlist_err - list for error frames masks
  412. rcvlist_fil - list for mask/value filters
  413. rcvlist_inv - list for mask/value filters (inverse semantic)
  414. rcvlist_sff - list for single standard frame (SFF) entries
  415. Additional procfs files in /proc/net/can
  416. stats - Socket CAN core statistics (rx/tx frames, match ratios, ...)
  417. reset_stats - manual statistic reset
  418. version - prints the Socket CAN core version and the ABI version
  419. 5.3 writing own CAN protocol modules
  420. To implement a new protocol in the protocol family PF_CAN a new
  421. protocol has to be defined in include/linux/can.h .
  422. The prototypes and definitions to use the Socket CAN core can be
  423. accessed by including include/linux/can/core.h .
  424. In addition to functions that register the CAN protocol and the
  425. CAN device notifier chain there are functions to subscribe CAN
  426. frames received by CAN interfaces and to send CAN frames:
  427. can_rx_register - subscribe CAN frames from a specific interface
  428. can_rx_unregister - unsubscribe CAN frames from a specific interface
  429. can_send - transmit a CAN frame (optional with local loopback)
  430. For details see the kerneldoc documentation in net/can/af_can.c or
  431. the source code of net/can/raw.c or net/can/bcm.c .
  432. 6. CAN network drivers
  433. ----------------------
  434. Writing a CAN network device driver is much easier than writing a
  435. CAN character device driver. Similar to other known network device
  436. drivers you mainly have to deal with:
  437. - TX: Put the CAN frame from the socket buffer to the CAN controller.
  438. - RX: Put the CAN frame from the CAN controller to the socket buffer.
  439. See e.g. at Documentation/networking/netdevices.txt . The differences
  440. for writing CAN network device driver are described below:
  441. 6.1 general settings
  442. dev->type = ARPHRD_CAN; /* the netdevice hardware type */
  443. dev->flags = IFF_NOARP; /* CAN has no arp */
  444. dev->mtu = sizeof(struct can_frame);
  445. The struct can_frame is the payload of each socket buffer in the
  446. protocol family PF_CAN.
  447. 6.2 local loopback of sent frames
  448. As described in chapter 3.2 the CAN network device driver should
  449. support a local loopback functionality similar to the local echo
  450. e.g. of tty devices. In this case the driver flag IFF_ECHO has to be
  451. set to prevent the PF_CAN core from locally echoing sent frames
  452. (aka loopback) as fallback solution:
  453. dev->flags = (IFF_NOARP | IFF_ECHO);
  454. 6.3 CAN controller hardware filters
  455. To reduce the interrupt load on deep embedded systems some CAN
  456. controllers support the filtering of CAN IDs or ranges of CAN IDs.
  457. These hardware filter capabilities vary from controller to
  458. controller and have to be identified as not feasible in a multi-user
  459. networking approach. The use of the very controller specific
  460. hardware filters could make sense in a very dedicated use-case, as a
  461. filter on driver level would affect all users in the multi-user
  462. system. The high efficient filter sets inside the PF_CAN core allow
  463. to set different multiple filters for each socket separately.
  464. Therefore the use of hardware filters goes to the category 'handmade
  465. tuning on deep embedded systems'. The author is running a MPC603e
  466. @133MHz with four SJA1000 CAN controllers from 2002 under heavy bus
  467. load without any problems ...
  468. 6.4 The virtual CAN driver (vcan)
  469. Similar to the network loopback devices, vcan offers a virtual local
  470. CAN interface. A full qualified address on CAN consists of
  471. - a unique CAN Identifier (CAN ID)
  472. - the CAN bus this CAN ID is transmitted on (e.g. can0)
  473. so in common use cases more than one virtual CAN interface is needed.
  474. The virtual CAN interfaces allow the transmission and reception of CAN
  475. frames without real CAN controller hardware. Virtual CAN network
  476. devices are usually named 'vcanX', like vcan0 vcan1 vcan2 ...
  477. When compiled as a module the virtual CAN driver module is called vcan.ko
  478. Since Linux Kernel version 2.6.24 the vcan driver supports the Kernel
  479. netlink interface to create vcan network devices. The creation and
  480. removal of vcan network devices can be managed with the ip(8) tool:
  481. - Create a virtual CAN network interface:
  482. $ ip link add type vcan
  483. - Create a virtual CAN network interface with a specific name 'vcan42':
  484. $ ip link add dev vcan42 type vcan
  485. - Remove a (virtual CAN) network interface 'vcan42':
  486. $ ip link del vcan42
  487. 6.5 The CAN network device driver interface
  488. The CAN network device driver interface provides a generic interface
  489. to setup, configure and monitor CAN network devices. The user can then
  490. configure the CAN device, like setting the bit-timing parameters, via
  491. the netlink interface using the program "ip" from the "IPROUTE2"
  492. utility suite. The following chapter describes briefly how to use it.
  493. Furthermore, the interface uses a common data structure and exports a
  494. set of common functions, which all real CAN network device drivers
  495. should use. Please have a look to the SJA1000 or MSCAN driver to
  496. understand how to use them. The name of the module is can-dev.ko.
  497. 6.5.1 Netlink interface to set/get devices properties
  498. The CAN device must be configured via netlink interface. The supported
  499. netlink message types are defined and briefly described in
  500. "include/linux/can/netlink.h". CAN link support for the program "ip"
  501. of the IPROUTE2 utility suite is avaiable and it can be used as shown
  502. below:
  503. - Setting CAN device properties:
  504. $ ip link set can0 type can help
  505. Usage: ip link set DEVICE type can
  506. [ bitrate BITRATE [ sample-point SAMPLE-POINT] ] |
  507. [ tq TQ prop-seg PROP_SEG phase-seg1 PHASE-SEG1
  508. phase-seg2 PHASE-SEG2 [ sjw SJW ] ]
  509. [ loopback { on | off } ]
  510. [ listen-only { on | off } ]
  511. [ triple-sampling { on | off } ]
  512. [ restart-ms TIME-MS ]
  513. [ restart ]
  514. Where: BITRATE := { 1..1000000 }
  515. SAMPLE-POINT := { 0.000..0.999 }
  516. TQ := { NUMBER }
  517. PROP-SEG := { 1..8 }
  518. PHASE-SEG1 := { 1..8 }
  519. PHASE-SEG2 := { 1..8 }
  520. SJW := { 1..4 }
  521. RESTART-MS := { 0 | NUMBER }
  522. - Display CAN device details and statistics:
  523. $ ip -details -statistics link show can0
  524. 2: can0: <NOARP,UP,LOWER_UP,ECHO> mtu 16 qdisc pfifo_fast state UP qlen 10
  525. link/can
  526. can <TRIPLE-SAMPLING> state ERROR-ACTIVE restart-ms 100
  527. bitrate 125000 sample_point 0.875
  528. tq 125 prop-seg 6 phase-seg1 7 phase-seg2 2 sjw 1
  529. sja1000: tseg1 1..16 tseg2 1..8 sjw 1..4 brp 1..64 brp-inc 1
  530. clock 8000000
  531. re-started bus-errors arbit-lost error-warn error-pass bus-off
  532. 41 17457 0 41 42 41
  533. RX: bytes packets errors dropped overrun mcast
  534. 140859 17608 17457 0 0 0
  535. TX: bytes packets errors dropped carrier collsns
  536. 861 112 0 41 0 0
  537. More info to the above output:
  538. "<TRIPLE-SAMPLING>"
  539. Shows the list of selected CAN controller modes: LOOPBACK,
  540. LISTEN-ONLY, or TRIPLE-SAMPLING.
  541. "state ERROR-ACTIVE"
  542. The current state of the CAN controller: "ERROR-ACTIVE",
  543. "ERROR-WARNING", "ERROR-PASSIVE", "BUS-OFF" or "STOPPED"
  544. "restart-ms 100"
  545. Automatic restart delay time. If set to a non-zero value, a
  546. restart of the CAN controller will be triggered automatically
  547. in case of a bus-off condition after the specified delay time
  548. in milliseconds. By default it's off.
  549. "bitrate 125000 sample_point 0.875"
  550. Shows the real bit-rate in bits/sec and the sample-point in the
  551. range 0.000..0.999. If the calculation of bit-timing parameters
  552. is enabled in the kernel (CONFIG_CAN_CALC_BITTIMING=y), the
  553. bit-timing can be defined by setting the "bitrate" argument.
  554. Optionally the "sample-point" can be specified. By default it's
  555. 0.000 assuming CIA-recommended sample-points.
  556. "tq 125 prop-seg 6 phase-seg1 7 phase-seg2 2 sjw 1"
  557. Shows the time quanta in ns, propagation segment, phase buffer
  558. segment 1 and 2 and the synchronisation jump width in units of
  559. tq. They allow to define the CAN bit-timing in a hardware
  560. independent format as proposed by the Bosch CAN 2.0 spec (see
  561. chapter 8 of http://www.semiconductors.bosch.de/pdf/can2spec.pdf).
  562. "sja1000: tseg1 1..16 tseg2 1..8 sjw 1..4 brp 1..64 brp-inc 1
  563. clock 8000000"
  564. Shows the bit-timing constants of the CAN controller, here the
  565. "sja1000". The minimum and maximum values of the time segment 1
  566. and 2, the synchronisation jump width in units of tq, the
  567. bitrate pre-scaler and the CAN system clock frequency in Hz.
  568. These constants could be used for user-defined (non-standard)
  569. bit-timing calculation algorithms in user-space.
  570. "re-started bus-errors arbit-lost error-warn error-pass bus-off"
  571. Shows the number of restarts, bus and arbitration lost errors,
  572. and the state changes to the error-warning, error-passive and
  573. bus-off state. RX overrun errors are listed in the "overrun"
  574. field of the standard network statistics.
  575. 6.5.2 Setting the CAN bit-timing
  576. The CAN bit-timing parameters can always be defined in a hardware
  577. independent format as proposed in the Bosch CAN 2.0 specification
  578. specifying the arguments "tq", "prop_seg", "phase_seg1", "phase_seg2"
  579. and "sjw":
  580. $ ip link set canX type can tq 125 prop-seg 6 \
  581. phase-seg1 7 phase-seg2 2 sjw 1
  582. If the kernel option CONFIG_CAN_CALC_BITTIMING is enabled, CIA
  583. recommended CAN bit-timing parameters will be calculated if the bit-
  584. rate is specified with the argument "bitrate":
  585. $ ip link set canX type can bitrate 125000
  586. Note that this works fine for the most common CAN controllers with
  587. standard bit-rates but may *fail* for exotic bit-rates or CAN system
  588. clock frequencies. Disabling CONFIG_CAN_CALC_BITTIMING saves some
  589. space and allows user-space tools to solely determine and set the
  590. bit-timing parameters. The CAN controller specific bit-timing
  591. constants can be used for that purpose. They are listed by the
  592. following command:
  593. $ ip -details link show can0
  594. ...
  595. sja1000: clock 8000000 tseg1 1..16 tseg2 1..8 sjw 1..4 brp 1..64 brp-inc 1
  596. 6.5.3 Starting and stopping the CAN network device
  597. A CAN network device is started or stopped as usual with the command
  598. "ifconfig canX up/down" or "ip link set canX up/down". Be aware that
  599. you *must* define proper bit-timing parameters for real CAN devices
  600. before you can start it to avoid error-prone default settings:
  601. $ ip link set canX up type can bitrate 125000
  602. A device may enter the "bus-off" state if too much errors occurred on
  603. the CAN bus. Then no more messages are received or sent. An automatic
  604. bus-off recovery can be enabled by setting the "restart-ms" to a
  605. non-zero value, e.g.:
  606. $ ip link set canX type can restart-ms 100
  607. Alternatively, the application may realize the "bus-off" condition
  608. by monitoring CAN error frames and do a restart when appropriate with
  609. the command:
  610. $ ip link set canX type can restart
  611. Note that a restart will also create a CAN error frame (see also
  612. chapter 3.4).
  613. 6.6 Supported CAN hardware
  614. Please check the "Kconfig" file in "drivers/net/can" to get an actual
  615. list of the support CAN hardware. On the Socket CAN project website
  616. (see chapter 7) there might be further drivers available, also for
  617. older kernel versions.
  618. 7. Socket CAN resources
  619. -----------------------
  620. You can find further resources for Socket CAN like user space tools,
  621. support for old kernel versions, more drivers, mailing lists, etc.
  622. at the BerliOS OSS project website for Socket CAN:
  623. http://developer.berlios.de/projects/socketcan
  624. If you have questions, bug fixes, etc., don't hesitate to post them to
  625. the Socketcan-Users mailing list. But please search the archives first.
  626. 8. Credits
  627. ----------
  628. Oliver Hartkopp (PF_CAN core, filters, drivers, bcm, SJA1000 driver)
  629. Urs Thuermann (PF_CAN core, kernel integration, socket interfaces, raw, vcan)
  630. Jan Kizka (RT-SocketCAN core, Socket-API reconciliation)
  631. Wolfgang Grandegger (RT-SocketCAN core & drivers, Raw Socket-API reviews,
  632. CAN device driver interface, MSCAN driver)
  633. Robert Schwebel (design reviews, PTXdist integration)
  634. Marc Kleine-Budde (design reviews, Kernel 2.6 cleanups, drivers)
  635. Benedikt Spranger (reviews)
  636. Thomas Gleixner (LKML reviews, coding style, posting hints)
  637. Andrey Volkov (kernel subtree structure, ioctls, MSCAN driver)
  638. Matthias Brukner (first SJA1000 CAN netdevice implementation Q2/2003)
  639. Klaus Hitschler (PEAK driver integration)
  640. Uwe Koppe (CAN netdevices with PF_PACKET approach)
  641. Michael Schulze (driver layer loopback requirement, RT CAN drivers review)
  642. Pavel Pisa (Bit-timing calculation)
  643. Sascha Hauer (SJA1000 platform driver)
  644. Sebastian Haas (SJA1000 EMS PCI driver)
  645. Markus Plessing (SJA1000 EMS PCI driver)
  646. Per Dalen (SJA1000 Kvaser PCI driver)
  647. Sam Ravnborg (reviews, coding style, kbuild help)