1 ============================================================================
5 Readme file for the Controller Area Network Protocol Family (aka Socket CAN)
9 1 Overview / What is Socket CAN
11 2 Motivation / Why using the socket API
15 3.2 local loopback of sent frames
16 3.3 network security issues (capabilities)
17 3.4 network problem notifications
19 4 How to use Socket CAN
20 4.1 RAW protocol sockets with can_filters (SOCK_RAW)
21 4.1.1 RAW socket option CAN_RAW_FILTER
22 4.1.2 RAW socket option CAN_RAW_ERR_FILTER
23 4.1.3 RAW socket option CAN_RAW_LOOPBACK
24 4.1.4 RAW socket option CAN_RAW_RECV_OWN_MSGS
25 4.1.5 RAW socket option CAN_RAW_FD_FRAMES
26 4.1.6 RAW socket returned message flags
27 4.2 Broadcast Manager protocol sockets (SOCK_DGRAM)
28 4.2.1 Broadcast Manager operations
29 4.2.2 Broadcast Manager message flags
30 4.2.3 Broadcast Manager transmission timers
31 4.2.4 Broadcast Manager message sequence transmission
32 4.2.5 Broadcast Manager receive filter timers
33 4.2.6 Broadcast Manager multiplex message receive filter
34 4.3 connected transport protocols (SOCK_SEQPACKET)
35 4.4 unconnected transport protocols (SOCK_DGRAM)
37 5 Socket CAN core module
38 5.1 can.ko module params
40 5.3 writing own CAN protocol modules
44 6.2 local loopback of sent frames
45 6.3 CAN controller hardware filters
46 6.4 The virtual CAN driver (vcan)
47 6.5 The CAN network device driver interface
48 6.5.1 Netlink interface to set/get devices properties
49 6.5.2 Setting the CAN bit-timing
50 6.5.3 Starting and stopping the CAN network device
51 6.6 CAN FD (flexible data rate) driver support
52 6.7 supported CAN hardware
54 7 Socket CAN resources
58 ============================================================================
60 1. Overview / What is Socket CAN
61 --------------------------------
63 The socketcan package is an implementation of CAN protocols
64 (Controller Area Network) for Linux. CAN is a networking technology
65 which has widespread use in automation, embedded devices, and
66 automotive fields. While there have been other CAN implementations
67 for Linux based on character devices, Socket CAN uses the Berkeley
68 socket API, the Linux network stack and implements the CAN device
69 drivers as network interfaces. The CAN socket API has been designed
70 as similar as possible to the TCP/IP protocols to allow programmers,
71 familiar with network programming, to easily learn how to use CAN
74 2. Motivation / Why using the socket API
75 ----------------------------------------
77 There have been CAN implementations for Linux before Socket CAN so the
78 question arises, why we have started another project. Most existing
79 implementations come as a device driver for some CAN hardware, they
80 are based on character devices and provide comparatively little
81 functionality. Usually, there is only a hardware-specific device
82 driver which provides a character device interface to send and
83 receive raw CAN frames, directly to/from the controller hardware.
84 Queueing of frames and higher-level transport protocols like ISO-TP
85 have to be implemented in user space applications. Also, most
86 character-device implementations support only one single process to
87 open the device at a time, similar to a serial interface. Exchanging
88 the CAN controller requires employment of another device driver and
89 often the need for adaption of large parts of the application to the
92 Socket CAN was designed to overcome all of these limitations. A new
93 protocol family has been implemented which provides a socket interface
94 to user space applications and which builds upon the Linux network
95 layer, so to use all of the provided queueing functionality. A device
96 driver for CAN controller hardware registers itself with the Linux
97 network layer as a network device, so that CAN frames from the
98 controller can be passed up to the network layer and on to the CAN
99 protocol family module and also vice-versa. Also, the protocol family
100 module provides an API for transport protocol modules to register, so
101 that any number of transport protocols can be loaded or unloaded
102 dynamically. In fact, the can core module alone does not provide any
103 protocol and cannot be used without loading at least one additional
104 protocol module. Multiple sockets can be opened at the same time,
105 on different or the same protocol module and they can listen/send
106 frames on different or the same CAN IDs. Several sockets listening on
107 the same interface for frames with the same CAN ID are all passed the
108 same received matching CAN frames. An application wishing to
109 communicate using a specific transport protocol, e.g. ISO-TP, just
110 selects that protocol when opening the socket, and then can read and
111 write application data byte streams, without having to deal with
112 CAN-IDs, frames, etc.
114 Similar functionality visible from user-space could be provided by a
115 character device, too, but this would lead to a technically inelegant
116 solution for a couple of reasons:
118 * Intricate usage. Instead of passing a protocol argument to
119 socket(2) and using bind(2) to select a CAN interface and CAN ID, an
120 application would have to do all these operations using ioctl(2)s.
122 * Code duplication. A character device cannot make use of the Linux
123 network queueing code, so all that code would have to be duplicated
126 * Abstraction. In most existing character-device implementations, the
127 hardware-specific device driver for a CAN controller directly
128 provides the character device for the application to work with.
129 This is at least very unusual in Unix systems for both, char and
130 block devices. For example you don't have a character device for a
131 certain UART of a serial interface, a certain sound chip in your
132 computer, a SCSI or IDE controller providing access to your hard
133 disk or tape streamer device. Instead, you have abstraction layers
134 which provide a unified character or block device interface to the
135 application on the one hand, and a interface for hardware-specific
136 device drivers on the other hand. These abstractions are provided
137 by subsystems like the tty layer, the audio subsystem or the SCSI
138 and IDE subsystems for the devices mentioned above.
140 The easiest way to implement a CAN device driver is as a character
141 device without such a (complete) abstraction layer, as is done by most
142 existing drivers. The right way, however, would be to add such a
143 layer with all the functionality like registering for certain CAN
144 IDs, supporting several open file descriptors and (de)multiplexing
145 CAN frames between them, (sophisticated) queueing of CAN frames, and
146 providing an API for device drivers to register with. However, then
147 it would be no more difficult, or may be even easier, to use the
148 networking framework provided by the Linux kernel, and this is what
151 The use of the networking framework of the Linux kernel is just the
152 natural and most appropriate way to implement CAN for Linux.
154 3. Socket CAN concept
155 ---------------------
157 As described in chapter 2 it is the main goal of Socket CAN to
158 provide a socket interface to user space applications which builds
159 upon the Linux network layer. In contrast to the commonly known
160 TCP/IP and ethernet networking, the CAN bus is a broadcast-only(!)
161 medium that has no MAC-layer addressing like ethernet. The CAN-identifier
162 (can_id) is used for arbitration on the CAN-bus. Therefore the CAN-IDs
163 have to be chosen uniquely on the bus. When designing a CAN-ECU
164 network the CAN-IDs are mapped to be sent by a specific ECU.
165 For this reason a CAN-ID can be treated best as a kind of source address.
169 The network transparent access of multiple applications leads to the
170 problem that different applications may be interested in the same
171 CAN-IDs from the same CAN network interface. The Socket CAN core
172 module - which implements the protocol family CAN - provides several
173 high efficient receive lists for this reason. If e.g. a user space
174 application opens a CAN RAW socket, the raw protocol module itself
175 requests the (range of) CAN-IDs from the Socket CAN core that are
176 requested by the user. The subscription and unsubscription of
177 CAN-IDs can be done for specific CAN interfaces or for all(!) known
178 CAN interfaces with the can_rx_(un)register() functions provided to
179 CAN protocol modules by the SocketCAN core (see chapter 5).
180 To optimize the CPU usage at runtime the receive lists are split up
181 into several specific lists per device that match the requested
182 filter complexity for a given use-case.
184 3.2 local loopback of sent frames
186 As known from other networking concepts the data exchanging
187 applications may run on the same or different nodes without any
188 change (except for the according addressing information):
190 ___ ___ ___ _______ ___
191 | _ | | _ | | _ | | _ _ | | _ |
192 ||A|| ||B|| ||C|| ||A| |B|| ||C||
193 |___| |___| |___| |_______| |___|
195 -----------------(1)- CAN bus -(2)---------------
197 To ensure that application A receives the same information in the
198 example (2) as it would receive in example (1) there is need for
199 some kind of local loopback of the sent CAN frames on the appropriate
202 The Linux network devices (by default) just can handle the
203 transmission and reception of media dependent frames. Due to the
204 arbitration on the CAN bus the transmission of a low prio CAN-ID
205 may be delayed by the reception of a high prio CAN frame. To
206 reflect the correct* traffic on the node the loopback of the sent
207 data has to be performed right after a successful transmission. If
208 the CAN network interface is not capable of performing the loopback for
209 some reason the SocketCAN core can do this task as a fallback solution.
210 See chapter 6.2 for details (recommended).
212 The loopback functionality is enabled by default to reflect standard
213 networking behaviour for CAN applications. Due to some requests from
214 the RT-SocketCAN group the loopback optionally may be disabled for each
215 separate socket. See sockopts from the CAN RAW sockets in chapter 4.1.
217 * = you really like to have this when you're running analyser tools
218 like 'candump' or 'cansniffer' on the (same) node.
220 3.3 network security issues (capabilities)
222 The Controller Area Network is a local field bus transmitting only
223 broadcast messages without any routing and security concepts.
224 In the majority of cases the user application has to deal with
225 raw CAN frames. Therefore it might be reasonable NOT to restrict
226 the CAN access only to the user root, as known from other networks.
227 Since the currently implemented CAN_RAW and CAN_BCM sockets can only
228 send and receive frames to/from CAN interfaces it does not affect
229 security of others networks to allow all users to access the CAN.
230 To enable non-root users to access CAN_RAW and CAN_BCM protocol
231 sockets the Kconfig options CAN_RAW_USER and/or CAN_BCM_USER may be
232 selected at kernel compile time.
234 3.4 network problem notifications
236 The use of the CAN bus may lead to several problems on the physical
237 and media access control layer. Detecting and logging of these lower
238 layer problems is a vital requirement for CAN users to identify
239 hardware issues on the physical transceiver layer as well as
240 arbitration problems and error frames caused by the different
241 ECUs. The occurrence of detected errors are important for diagnosis
242 and have to be logged together with the exact timestamp. For this
243 reason the CAN interface driver can generate so called Error Message
244 Frames that can optionally be passed to the user application in the
245 same way as other CAN frames. Whenever an error on the physical layer
246 or the MAC layer is detected (e.g. by the CAN controller) the driver
247 creates an appropriate error message frame. Error messages frames can
248 be requested by the user application using the common CAN filter
249 mechanisms. Inside this filter definition the (interested) type of
250 errors may be selected. The reception of error messages is disabled
251 by default. The format of the CAN error message frame is briefly
252 described in the Linux header file "include/linux/can/error.h".
254 4. How to use Socket CAN
255 ------------------------
257 Like TCP/IP, you first need to open a socket for communicating over a
258 CAN network. Since Socket CAN implements a new protocol family, you
259 need to pass PF_CAN as the first argument to the socket(2) system
260 call. Currently, there are two CAN protocols to choose from, the raw
261 socket protocol and the broadcast manager (BCM). So to open a socket,
264 s = socket(PF_CAN, SOCK_RAW, CAN_RAW);
268 s = socket(PF_CAN, SOCK_DGRAM, CAN_BCM);
270 respectively. After the successful creation of the socket, you would
271 normally use the bind(2) system call to bind the socket to a CAN
272 interface (which is different from TCP/IP due to different addressing
273 - see chapter 3). After binding (CAN_RAW) or connecting (CAN_BCM)
274 the socket, you can read(2) and write(2) from/to the socket or use
275 send(2), sendto(2), sendmsg(2) and the recv* counterpart operations
276 on the socket as usual. There are also CAN specific socket options
279 The basic CAN frame structure and the sockaddr structure are defined
280 in include/linux/can.h:
283 canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */
284 __u8 can_dlc; /* frame payload length in byte (0 .. 8) */
285 __u8 data[8] __attribute__((aligned(8)));
288 The alignment of the (linear) payload data[] to a 64bit boundary
289 allows the user to define own structs and unions to easily access the
290 CAN payload. There is no given byteorder on the CAN bus by
291 default. A read(2) system call on a CAN_RAW socket transfers a
292 struct can_frame to the user space.
294 The sockaddr_can structure has an interface index like the
295 PF_PACKET socket, that also binds to a specific interface:
297 struct sockaddr_can {
298 sa_family_t can_family;
301 /* transport protocol class address info (e.g. ISOTP) */
302 struct { canid_t rx_id, tx_id; } tp;
304 /* reserved for future CAN protocols address information */
308 To determine the interface index an appropriate ioctl() has to
309 be used (example for CAN_RAW sockets without error checking):
312 struct sockaddr_can addr;
315 s = socket(PF_CAN, SOCK_RAW, CAN_RAW);
317 strcpy(ifr.ifr_name, "can0" );
318 ioctl(s, SIOCGIFINDEX, &ifr);
320 addr.can_family = AF_CAN;
321 addr.can_ifindex = ifr.ifr_ifindex;
323 bind(s, (struct sockaddr *)&addr, sizeof(addr));
327 To bind a socket to all(!) CAN interfaces the interface index must
328 be 0 (zero). In this case the socket receives CAN frames from every
329 enabled CAN interface. To determine the originating CAN interface
330 the system call recvfrom(2) may be used instead of read(2). To send
331 on a socket that is bound to 'any' interface sendto(2) is needed to
332 specify the outgoing interface.
334 Reading CAN frames from a bound CAN_RAW socket (see above) consists
335 of reading a struct can_frame:
337 struct can_frame frame;
339 nbytes = read(s, &frame, sizeof(struct can_frame));
342 perror("can raw socket read");
346 /* paranoid check ... */
347 if (nbytes < sizeof(struct can_frame)) {
348 fprintf(stderr, "read: incomplete CAN frame\n");
352 /* do something with the received CAN frame */
354 Writing CAN frames can be done similarly, with the write(2) system call:
356 nbytes = write(s, &frame, sizeof(struct can_frame));
358 When the CAN interface is bound to 'any' existing CAN interface
359 (addr.can_ifindex = 0) it is recommended to use recvfrom(2) if the
360 information about the originating CAN interface is needed:
362 struct sockaddr_can addr;
364 socklen_t len = sizeof(addr);
365 struct can_frame frame;
367 nbytes = recvfrom(s, &frame, sizeof(struct can_frame),
368 0, (struct sockaddr*)&addr, &len);
370 /* get interface name of the received CAN frame */
371 ifr.ifr_ifindex = addr.can_ifindex;
372 ioctl(s, SIOCGIFNAME, &ifr);
373 printf("Received a CAN frame from interface %s", ifr.ifr_name);
375 To write CAN frames on sockets bound to 'any' CAN interface the
376 outgoing interface has to be defined certainly.
378 strcpy(ifr.ifr_name, "can0");
379 ioctl(s, SIOCGIFINDEX, &ifr);
380 addr.can_ifindex = ifr.ifr_ifindex;
381 addr.can_family = AF_CAN;
383 nbytes = sendto(s, &frame, sizeof(struct can_frame),
384 0, (struct sockaddr*)&addr, sizeof(addr));
386 Remark about CAN FD (flexible data rate) support:
388 Generally the handling of CAN FD is very similar to the formerly described
389 examples. The new CAN FD capable CAN controllers support two different
390 bitrates for the arbitration phase and the payload phase of the CAN FD frame
391 and up to 64 bytes of payload. This extended payload length breaks all the
392 kernel interfaces (ABI) which heavily rely on the CAN frame with fixed eight
393 bytes of payload (struct can_frame) like the CAN_RAW socket. Therefore e.g.
394 the CAN_RAW socket supports a new socket option CAN_RAW_FD_FRAMES that
395 switches the socket into a mode that allows the handling of CAN FD frames
396 and (legacy) CAN frames simultaneously (see section 4.1.5).
398 The struct canfd_frame is defined in include/linux/can.h:
401 canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */
402 __u8 len; /* frame payload length in byte (0 .. 64) */
403 __u8 flags; /* additional flags for CAN FD */
404 __u8 __res0; /* reserved / padding */
405 __u8 __res1; /* reserved / padding */
406 __u8 data[64] __attribute__((aligned(8)));
409 The struct canfd_frame and the existing struct can_frame have the can_id,
410 the payload length and the payload data at the same offset inside their
411 structures. This allows to handle the different structures very similar.
412 When the content of a struct can_frame is copied into a struct canfd_frame
413 all structure elements can be used as-is - only the data[] becomes extended.
415 When introducing the struct canfd_frame it turned out that the data length
416 code (DLC) of the struct can_frame was used as a length information as the
417 length and the DLC has a 1:1 mapping in the range of 0 .. 8. To preserve
418 the easy handling of the length information the canfd_frame.len element
419 contains a plain length value from 0 .. 64. So both canfd_frame.len and
420 can_frame.can_dlc are equal and contain a length information and no DLC.
421 For details about the distinction of CAN and CAN FD capable devices and
422 the mapping to the bus-relevant data length code (DLC), see chapter 6.6.
424 The length of the two CAN(FD) frame structures define the maximum transfer
425 unit (MTU) of the CAN(FD) network interface and skbuff data length. Two
426 definitions are specified for CAN specific MTUs in include/linux/can.h :
428 #define CAN_MTU (sizeof(struct can_frame)) == 16 => 'legacy' CAN frame
429 #define CANFD_MTU (sizeof(struct canfd_frame)) == 72 => CAN FD frame
431 4.1 RAW protocol sockets with can_filters (SOCK_RAW)
433 Using CAN_RAW sockets is extensively comparable to the commonly
434 known access to CAN character devices. To meet the new possibilities
435 provided by the multi user SocketCAN approach, some reasonable
436 defaults are set at RAW socket binding time:
438 - The filters are set to exactly one filter receiving everything
439 - The socket only receives valid data frames (=> no error message frames)
440 - The loopback of sent CAN frames is enabled (see chapter 3.2)
441 - The socket does not receive its own sent frames (in loopback mode)
443 These default settings may be changed before or after binding the socket.
444 To use the referenced definitions of the socket options for CAN_RAW
445 sockets, include <linux/can/raw.h>.
447 4.1.1 RAW socket option CAN_RAW_FILTER
449 The reception of CAN frames using CAN_RAW sockets can be controlled
450 by defining 0 .. n filters with the CAN_RAW_FILTER socket option.
452 The CAN filter structure is defined in include/linux/can.h:
459 A filter matches, when
461 <received_can_id> & mask == can_id & mask
463 which is analogous to known CAN controllers hardware filter semantics.
464 The filter can be inverted in this semantic, when the CAN_INV_FILTER
465 bit is set in can_id element of the can_filter structure. In
466 contrast to CAN controller hardware filters the user may set 0 .. n
467 receive filters for each open socket separately:
469 struct can_filter rfilter[2];
471 rfilter[0].can_id = 0x123;
472 rfilter[0].can_mask = CAN_SFF_MASK;
473 rfilter[1].can_id = 0x200;
474 rfilter[1].can_mask = 0x700;
476 setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter));
478 To disable the reception of CAN frames on the selected CAN_RAW socket:
480 setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);
482 To set the filters to zero filters is quite obsolete as not read
483 data causes the raw socket to discard the received CAN frames. But
484 having this 'send only' use-case we may remove the receive list in the
485 Kernel to save a little (really a very little!) CPU usage.
487 4.1.2 RAW socket option CAN_RAW_ERR_FILTER
489 As described in chapter 3.4 the CAN interface driver can generate so
490 called Error Message Frames that can optionally be passed to the user
491 application in the same way as other CAN frames. The possible
492 errors are divided into different error classes that may be filtered
493 using the appropriate error mask. To register for every possible
494 error condition CAN_ERR_MASK can be used as value for the error mask.
495 The values for the error mask are defined in linux/can/error.h .
497 can_err_mask_t err_mask = ( CAN_ERR_TX_TIMEOUT | CAN_ERR_BUSOFF );
499 setsockopt(s, SOL_CAN_RAW, CAN_RAW_ERR_FILTER,
500 &err_mask, sizeof(err_mask));
502 4.1.3 RAW socket option CAN_RAW_LOOPBACK
504 To meet multi user needs the local loopback is enabled by default
505 (see chapter 3.2 for details). But in some embedded use-cases
506 (e.g. when only one application uses the CAN bus) this loopback
507 functionality can be disabled (separately for each socket):
509 int loopback = 0; /* 0 = disabled, 1 = enabled (default) */
511 setsockopt(s, SOL_CAN_RAW, CAN_RAW_LOOPBACK, &loopback, sizeof(loopback));
513 4.1.4 RAW socket option CAN_RAW_RECV_OWN_MSGS
515 When the local loopback is enabled, all the sent CAN frames are
516 looped back to the open CAN sockets that registered for the CAN
517 frames' CAN-ID on this given interface to meet the multi user
518 needs. The reception of the CAN frames on the same socket that was
519 sending the CAN frame is assumed to be unwanted and therefore
520 disabled by default. This default behaviour may be changed on
523 int recv_own_msgs = 1; /* 0 = disabled (default), 1 = enabled */
525 setsockopt(s, SOL_CAN_RAW, CAN_RAW_RECV_OWN_MSGS,
526 &recv_own_msgs, sizeof(recv_own_msgs));
528 4.1.5 RAW socket option CAN_RAW_FD_FRAMES
530 CAN FD support in CAN_RAW sockets can be enabled with a new socket option
531 CAN_RAW_FD_FRAMES which is off by default. When the new socket option is
532 not supported by the CAN_RAW socket (e.g. on older kernels), switching the
533 CAN_RAW_FD_FRAMES option returns the error -ENOPROTOOPT.
535 Once CAN_RAW_FD_FRAMES is enabled the application can send both CAN frames
536 and CAN FD frames. OTOH the application has to handle CAN and CAN FD frames
537 when reading from the socket.
539 CAN_RAW_FD_FRAMES enabled: CAN_MTU and CANFD_MTU are allowed
540 CAN_RAW_FD_FRAMES disabled: only CAN_MTU is allowed (default)
543 [ remember: CANFD_MTU == sizeof(struct canfd_frame) ]
545 struct canfd_frame cfd;
547 nbytes = read(s, &cfd, CANFD_MTU);
549 if (nbytes == CANFD_MTU) {
550 printf("got CAN FD frame with length %d\n", cfd.len);
551 /* cfd.flags contains valid data */
552 } else if (nbytes == CAN_MTU) {
553 printf("got legacy CAN frame with length %d\n", cfd.len);
554 /* cfd.flags is undefined */
556 fprintf(stderr, "read: invalid CAN(FD) frame\n");
560 /* the content can be handled independently from the received MTU size */
562 printf("can_id: %X data length: %d data: ", cfd.can_id, cfd.len);
563 for (i = 0; i < cfd.len; i++)
564 printf("%02X ", cfd.data[i]);
566 When reading with size CANFD_MTU only returns CAN_MTU bytes that have
567 been received from the socket a legacy CAN frame has been read into the
568 provided CAN FD structure. Note that the canfd_frame.flags data field is
569 not specified in the struct can_frame and therefore it is only valid in
570 CANFD_MTU sized CAN FD frames.
572 As long as the payload length is <=8 the received CAN frames from CAN FD
573 capable CAN devices can be received and read by legacy sockets too. When
574 user-generated CAN FD frames have a payload length <=8 these can be send
575 by legacy CAN network interfaces too. Sending CAN FD frames with payload
576 length > 8 to a legacy CAN network interface returns an -EMSGSIZE error.
578 Implementation hint for new CAN applications:
580 To build a CAN FD aware application use struct canfd_frame as basic CAN
581 data structure for CAN_RAW based applications. When the application is
582 executed on an older Linux kernel and switching the CAN_RAW_FD_FRAMES
583 socket option returns an error: No problem. You'll get legacy CAN frames
584 or CAN FD frames and can process them the same way.
586 When sending to CAN devices make sure that the device is capable to handle
587 CAN FD frames by checking if the device maximum transfer unit is CANFD_MTU.
588 The CAN device MTU can be retrieved e.g. with a SIOCGIFMTU ioctl() syscall.
590 4.1.6 RAW socket returned message flags
592 When using recvmsg() call, the msg->msg_flags may contain following flags:
594 MSG_DONTROUTE: set when the received frame was created on the local host.
596 MSG_CONFIRM: set when the frame was sent via the socket it is received on.
597 This flag can be interpreted as a 'transmission confirmation' when the
598 CAN driver supports the echo of frames on driver level, see 3.2 and 6.2.
599 In order to receive such messages, CAN_RAW_RECV_OWN_MSGS must be set.
601 4.2 Broadcast Manager protocol sockets (SOCK_DGRAM)
603 The Broadcast Manager protocol provides a command based configuration
604 interface to filter and send (e.g. cyclic) CAN messages in kernel space.
606 Receive filters can be used to down sample frequent messages; detect events
607 such as message contents changes, packet length changes, and do time-out
608 monitoring of received messages.
610 Periodic transmission tasks of CAN frames or a sequence of CAN frames can be
611 created and modified at runtime; both the message content and the two
612 possible transmit intervals can be altered.
614 A BCM socket is not intended for sending individual CAN frames using the
615 struct can_frame as known from the CAN_RAW socket. Instead a special BCM
616 configuration message is defined. The basic BCM configuration message used
617 to communicate with the broadcast manager and the available operations are
618 defined in the linux/can/bcm.h include. The BCM message consists of a
619 message header with a command ('opcode') followed by zero or more CAN frames.
620 The broadcast manager sends responses to user space in the same form:
622 struct bcm_msg_head {
623 __u32 opcode; /* command */
624 __u32 flags; /* special flags */
625 __u32 count; /* run 'count' times with ival1 */
626 struct timeval ival1, ival2; /* count and subsequent interval */
627 canid_t can_id; /* unique can_id for task */
628 __u32 nframes; /* number of can_frames following */
629 struct can_frame frames[0];
632 The aligned payload 'frames' uses the same basic CAN frame structure defined
633 at the beginning of section 4 and in the include/linux/can.h include. All
634 messages to the broadcast manager from user space have this structure.
636 Note a CAN_BCM socket must be connected instead of bound after socket
637 creation (example without error checking):
640 struct sockaddr_can addr;
643 s = socket(PF_CAN, SOCK_DGRAM, CAN_BCM);
645 strcpy(ifr.ifr_name, "can0");
646 ioctl(s, SIOCGIFINDEX, &ifr);
648 addr.can_family = AF_CAN;
649 addr.can_ifindex = ifr.ifr_ifindex;
651 connect(s, (struct sockaddr *)&addr, sizeof(addr))
655 The broadcast manager socket is able to handle any number of in flight
656 transmissions or receive filters concurrently. The different RX/TX jobs are
657 distinguished by the unique can_id in each BCM message. However additional
658 CAN_BCM sockets are recommended to communicate on multiple CAN interfaces.
659 When the broadcast manager socket is bound to 'any' CAN interface (=> the
660 interface index is set to zero) the configured receive filters apply to any
661 CAN interface unless the sendto() syscall is used to overrule the 'any' CAN
662 interface index. When using recvfrom() instead of read() to retrieve BCM
663 socket messages the originating CAN interface is provided in can_ifindex.
665 4.2.1 Broadcast Manager operations
667 The opcode defines the operation for the broadcast manager to carry out,
668 or details the broadcast managers response to several events, including
671 Transmit Operations (user space to broadcast manager):
673 TX_SETUP: Create (cyclic) transmission task.
675 TX_DELETE: Remove (cyclic) transmission task, requires only can_id.
677 TX_READ: Read properties of (cyclic) transmission task for can_id.
679 TX_SEND: Send one CAN frame.
681 Transmit Responses (broadcast manager to user space):
683 TX_STATUS: Reply to TX_READ request (transmission task configuration).
685 TX_EXPIRED: Notification when counter finishes sending at initial interval
686 'ival1'. Requires the TX_COUNTEVT flag to be set at TX_SETUP.
688 Receive Operations (user space to broadcast manager):
690 RX_SETUP: Create RX content filter subscription.
692 RX_DELETE: Remove RX content filter subscription, requires only can_id.
694 RX_READ: Read properties of RX content filter subscription for can_id.
696 Receive Responses (broadcast manager to user space):
698 RX_STATUS: Reply to RX_READ request (filter task configuration).
700 RX_TIMEOUT: Cyclic message is detected to be absent (timer ival1 expired).
702 RX_CHANGED: BCM message with updated CAN frame (detected content change).
703 Sent on first message received or on receipt of revised CAN messages.
705 4.2.2 Broadcast Manager message flags
707 When sending a message to the broadcast manager the 'flags' element may
708 contain the following flag definitions which influence the behaviour:
710 SETTIMER: Set the values of ival1, ival2 and count
712 STARTTIMER: Start the timer with the actual values of ival1, ival2
713 and count. Starting the timer leads simultaneously to emit a CAN frame.
715 TX_COUNTEVT: Create the message TX_EXPIRED when count expires
717 TX_ANNOUNCE: A change of data by the process is emitted immediately.
719 TX_CP_CAN_ID: Copies the can_id from the message header to each
720 subsequent frame in frames. This is intended as usage simplification. For
721 TX tasks the unique can_id from the message header may differ from the
722 can_id(s) stored for transmission in the subsequent struct can_frame(s).
724 RX_FILTER_ID: Filter by can_id alone, no frames required (nframes=0).
726 RX_CHECK_DLC: A change of the DLC leads to an RX_CHANGED.
728 RX_NO_AUTOTIMER: Prevent automatically starting the timeout monitor.
730 RX_ANNOUNCE_RESUME: If passed at RX_SETUP and a receive timeout occured, a
731 RX_CHANGED message will be generated when the (cyclic) receive restarts.
733 TX_RESET_MULTI_IDX: Reset the index for the multiple frame transmission.
735 RX_RTR_FRAME: Send reply for RTR-request (placed in op->frames[0]).
737 4.2.3 Broadcast Manager transmission timers
739 Periodic transmission configurations may use up to two interval timers.
740 In this case the BCM sends a number of messages ('count') at an interval
741 'ival1', then continuing to send at another given interval 'ival2'. When
742 only one timer is needed 'count' is set to zero and only 'ival2' is used.
743 When SET_TIMER and START_TIMER flag were set the timers are activated.
744 The timer values can be altered at runtime when only SET_TIMER is set.
746 4.2.4 Broadcast Manager message sequence transmission
748 Up to 256 CAN frames can be transmitted in a sequence in the case of a cyclic
749 TX task configuration. The number of CAN frames is provided in the 'nframes'
750 element of the BCM message head. The defined number of CAN frames are added
751 as array to the TX_SETUP BCM configuration message.
753 /* create a struct to set up a sequence of four CAN frames */
755 struct bcm_msg_head msg_head;
756 struct can_frame frame[4];
763 write(s, &mytxmsg, sizeof(mytxmsg));
765 With every transmission the index in the array of CAN frames is increased
766 and set to zero at index overflow.
768 4.2.5 Broadcast Manager receive filter timers
770 The timer values ival1 or ival2 may be set to non-zero values at RX_SETUP.
771 When the SET_TIMER flag is set the timers are enabled:
773 ival1: Send RX_TIMEOUT when a received message is not received again within
774 the given time. When START_TIMER is set at RX_SETUP the timeout detection
775 is activated directly - even without a former CAN frame reception.
777 ival2: Throttle the received message rate down to the value of ival2. This
778 is useful to reduce messages for the application when the signal inside the
779 CAN frame is stateless as state changes within the ival2 periode may get
782 4.2.6 Broadcast Manager multiplex message receive filter
784 To filter for content changes in multiplex message sequences an array of more
785 than one CAN frames can be passed in a RX_SETUP configuration message. The
786 data bytes of the first CAN frame contain the mask of relevant bits that
787 have to match in the subsequent CAN frames with the received CAN frame.
788 If one of the subsequent CAN frames is matching the bits in that frame data
789 mark the relevant content to be compared with the previous received content.
790 Up to 257 CAN frames (multiplex filter bit mask CAN frame plus 256 CAN
791 filters) can be added as array to the TX_SETUP BCM configuration message.
793 /* usually used to clear CAN frame data[] - beware of endian problems! */
794 #define U64_DATA(p) (*(unsigned long long*)(p)->data)
797 struct bcm_msg_head msg_head;
798 struct can_frame frame[5];
801 msg.msg_head.opcode = RX_SETUP;
802 msg.msg_head.can_id = 0x42;
803 msg.msg_head.flags = 0;
804 msg.msg_head.nframes = 5;
805 U64_DATA(&msg.frame[0]) = 0xFF00000000000000ULL; /* MUX mask */
806 U64_DATA(&msg.frame[1]) = 0x01000000000000FFULL; /* data mask (MUX 0x01) */
807 U64_DATA(&msg.frame[2]) = 0x0200FFFF000000FFULL; /* data mask (MUX 0x02) */
808 U64_DATA(&msg.frame[3]) = 0x330000FFFFFF0003ULL; /* data mask (MUX 0x33) */
809 U64_DATA(&msg.frame[4]) = 0x4F07FC0FF0000000ULL; /* data mask (MUX 0x4F) */
811 write(s, &msg, sizeof(msg));
813 4.3 connected transport protocols (SOCK_SEQPACKET)
814 4.4 unconnected transport protocols (SOCK_DGRAM)
817 5. Socket CAN core module
818 -------------------------
820 The Socket CAN core module implements the protocol family
821 PF_CAN. CAN protocol modules are loaded by the core module at
822 runtime. The core module provides an interface for CAN protocol
823 modules to subscribe needed CAN IDs (see chapter 3.1).
825 5.1 can.ko module params
827 - stats_timer: To calculate the Socket CAN core statistics
828 (e.g. current/maximum frames per second) this 1 second timer is
829 invoked at can.ko module start time by default. This timer can be
830 disabled by using stattimer=0 on the module commandline.
832 - debug: (removed since SocketCAN SVN r546)
836 As described in chapter 3.1 the Socket CAN core uses several filter
837 lists to deliver received CAN frames to CAN protocol modules. These
838 receive lists, their filters and the count of filter matches can be
839 checked in the appropriate receive list. All entries contain the
840 device and a protocol module identifier:
842 foo@bar:~$ cat /proc/net/can/rcvlist_all
844 receive list 'rx_all':
848 device can_id can_mask function userdata matches ident
849 vcan0 000 00000000 f88e6370 f6c6f400 0 raw
852 In this example an application requests any CAN traffic from vcan0.
854 rcvlist_all - list for unfiltered entries (no filter operations)
855 rcvlist_eff - list for single extended frame (EFF) entries
856 rcvlist_err - list for error message frames masks
857 rcvlist_fil - list for mask/value filters
858 rcvlist_inv - list for mask/value filters (inverse semantic)
859 rcvlist_sff - list for single standard frame (SFF) entries
861 Additional procfs files in /proc/net/can
863 stats - Socket CAN core statistics (rx/tx frames, match ratios, ...)
864 reset_stats - manual statistic reset
865 version - prints the Socket CAN core version and the ABI version
867 5.3 writing own CAN protocol modules
869 To implement a new protocol in the protocol family PF_CAN a new
870 protocol has to be defined in include/linux/can.h .
871 The prototypes and definitions to use the Socket CAN core can be
872 accessed by including include/linux/can/core.h .
873 In addition to functions that register the CAN protocol and the
874 CAN device notifier chain there are functions to subscribe CAN
875 frames received by CAN interfaces and to send CAN frames:
877 can_rx_register - subscribe CAN frames from a specific interface
878 can_rx_unregister - unsubscribe CAN frames from a specific interface
879 can_send - transmit a CAN frame (optional with local loopback)
881 For details see the kerneldoc documentation in net/can/af_can.c or
882 the source code of net/can/raw.c or net/can/bcm.c .
884 6. CAN network drivers
885 ----------------------
887 Writing a CAN network device driver is much easier than writing a
888 CAN character device driver. Similar to other known network device
889 drivers you mainly have to deal with:
891 - TX: Put the CAN frame from the socket buffer to the CAN controller.
892 - RX: Put the CAN frame from the CAN controller to the socket buffer.
894 See e.g. at Documentation/networking/netdevices.txt . The differences
895 for writing CAN network device driver are described below:
899 dev->type = ARPHRD_CAN; /* the netdevice hardware type */
900 dev->flags = IFF_NOARP; /* CAN has no arp */
902 dev->mtu = CAN_MTU; /* sizeof(struct can_frame) -> legacy CAN interface */
904 or alternative, when the controller supports CAN with flexible data rate:
905 dev->mtu = CANFD_MTU; /* sizeof(struct canfd_frame) -> CAN FD interface */
907 The struct can_frame or struct canfd_frame is the payload of each socket
908 buffer (skbuff) in the protocol family PF_CAN.
910 6.2 local loopback of sent frames
912 As described in chapter 3.2 the CAN network device driver should
913 support a local loopback functionality similar to the local echo
914 e.g. of tty devices. In this case the driver flag IFF_ECHO has to be
915 set to prevent the PF_CAN core from locally echoing sent frames
916 (aka loopback) as fallback solution:
918 dev->flags = (IFF_NOARP | IFF_ECHO);
920 6.3 CAN controller hardware filters
922 To reduce the interrupt load on deep embedded systems some CAN
923 controllers support the filtering of CAN IDs or ranges of CAN IDs.
924 These hardware filter capabilities vary from controller to
925 controller and have to be identified as not feasible in a multi-user
926 networking approach. The use of the very controller specific
927 hardware filters could make sense in a very dedicated use-case, as a
928 filter on driver level would affect all users in the multi-user
929 system. The high efficient filter sets inside the PF_CAN core allow
930 to set different multiple filters for each socket separately.
931 Therefore the use of hardware filters goes to the category 'handmade
932 tuning on deep embedded systems'. The author is running a MPC603e
933 @133MHz with four SJA1000 CAN controllers from 2002 under heavy bus
934 load without any problems ...
936 6.4 The virtual CAN driver (vcan)
938 Similar to the network loopback devices, vcan offers a virtual local
939 CAN interface. A full qualified address on CAN consists of
941 - a unique CAN Identifier (CAN ID)
942 - the CAN bus this CAN ID is transmitted on (e.g. can0)
944 so in common use cases more than one virtual CAN interface is needed.
946 The virtual CAN interfaces allow the transmission and reception of CAN
947 frames without real CAN controller hardware. Virtual CAN network
948 devices are usually named 'vcanX', like vcan0 vcan1 vcan2 ...
949 When compiled as a module the virtual CAN driver module is called vcan.ko
951 Since Linux Kernel version 2.6.24 the vcan driver supports the Kernel
952 netlink interface to create vcan network devices. The creation and
953 removal of vcan network devices can be managed with the ip(8) tool:
955 - Create a virtual CAN network interface:
956 $ ip link add type vcan
958 - Create a virtual CAN network interface with a specific name 'vcan42':
959 $ ip link add dev vcan42 type vcan
961 - Remove a (virtual CAN) network interface 'vcan42':
964 6.5 The CAN network device driver interface
966 The CAN network device driver interface provides a generic interface
967 to setup, configure and monitor CAN network devices. The user can then
968 configure the CAN device, like setting the bit-timing parameters, via
969 the netlink interface using the program "ip" from the "IPROUTE2"
970 utility suite. The following chapter describes briefly how to use it.
971 Furthermore, the interface uses a common data structure and exports a
972 set of common functions, which all real CAN network device drivers
973 should use. Please have a look to the SJA1000 or MSCAN driver to
974 understand how to use them. The name of the module is can-dev.ko.
976 6.5.1 Netlink interface to set/get devices properties
978 The CAN device must be configured via netlink interface. The supported
979 netlink message types are defined and briefly described in
980 "include/linux/can/netlink.h". CAN link support for the program "ip"
981 of the IPROUTE2 utility suite is available and it can be used as shown
984 - Setting CAN device properties:
986 $ ip link set can0 type can help
987 Usage: ip link set DEVICE type can
988 [ bitrate BITRATE [ sample-point SAMPLE-POINT] ] |
989 [ tq TQ prop-seg PROP_SEG phase-seg1 PHASE-SEG1
990 phase-seg2 PHASE-SEG2 [ sjw SJW ] ]
992 [ loopback { on | off } ]
993 [ listen-only { on | off } ]
994 [ triple-sampling { on | off } ]
996 [ restart-ms TIME-MS ]
999 Where: BITRATE := { 1..1000000 }
1000 SAMPLE-POINT := { 0.000..0.999 }
1002 PROP-SEG := { 1..8 }
1003 PHASE-SEG1 := { 1..8 }
1004 PHASE-SEG2 := { 1..8 }
1006 RESTART-MS := { 0 | NUMBER }
1008 - Display CAN device details and statistics:
1010 $ ip -details -statistics link show can0
1011 2: can0: <NOARP,UP,LOWER_UP,ECHO> mtu 16 qdisc pfifo_fast state UP qlen 10
1013 can <TRIPLE-SAMPLING> state ERROR-ACTIVE restart-ms 100
1014 bitrate 125000 sample_point 0.875
1015 tq 125 prop-seg 6 phase-seg1 7 phase-seg2 2 sjw 1
1016 sja1000: tseg1 1..16 tseg2 1..8 sjw 1..4 brp 1..64 brp-inc 1
1018 re-started bus-errors arbit-lost error-warn error-pass bus-off
1020 RX: bytes packets errors dropped overrun mcast
1021 140859 17608 17457 0 0 0
1022 TX: bytes packets errors dropped carrier collsns
1025 More info to the above output:
1028 Shows the list of selected CAN controller modes: LOOPBACK,
1029 LISTEN-ONLY, or TRIPLE-SAMPLING.
1031 "state ERROR-ACTIVE"
1032 The current state of the CAN controller: "ERROR-ACTIVE",
1033 "ERROR-WARNING", "ERROR-PASSIVE", "BUS-OFF" or "STOPPED"
1036 Automatic restart delay time. If set to a non-zero value, a
1037 restart of the CAN controller will be triggered automatically
1038 in case of a bus-off condition after the specified delay time
1039 in milliseconds. By default it's off.
1041 "bitrate 125000 sample_point 0.875"
1042 Shows the real bit-rate in bits/sec and the sample-point in the
1043 range 0.000..0.999. If the calculation of bit-timing parameters
1044 is enabled in the kernel (CONFIG_CAN_CALC_BITTIMING=y), the
1045 bit-timing can be defined by setting the "bitrate" argument.
1046 Optionally the "sample-point" can be specified. By default it's
1047 0.000 assuming CIA-recommended sample-points.
1049 "tq 125 prop-seg 6 phase-seg1 7 phase-seg2 2 sjw 1"
1050 Shows the time quanta in ns, propagation segment, phase buffer
1051 segment 1 and 2 and the synchronisation jump width in units of
1052 tq. They allow to define the CAN bit-timing in a hardware
1053 independent format as proposed by the Bosch CAN 2.0 spec (see
1054 chapter 8 of http://www.semiconductors.bosch.de/pdf/can2spec.pdf).
1056 "sja1000: tseg1 1..16 tseg2 1..8 sjw 1..4 brp 1..64 brp-inc 1
1058 Shows the bit-timing constants of the CAN controller, here the
1059 "sja1000". The minimum and maximum values of the time segment 1
1060 and 2, the synchronisation jump width in units of tq, the
1061 bitrate pre-scaler and the CAN system clock frequency in Hz.
1062 These constants could be used for user-defined (non-standard)
1063 bit-timing calculation algorithms in user-space.
1065 "re-started bus-errors arbit-lost error-warn error-pass bus-off"
1066 Shows the number of restarts, bus and arbitration lost errors,
1067 and the state changes to the error-warning, error-passive and
1068 bus-off state. RX overrun errors are listed in the "overrun"
1069 field of the standard network statistics.
1071 6.5.2 Setting the CAN bit-timing
1073 The CAN bit-timing parameters can always be defined in a hardware
1074 independent format as proposed in the Bosch CAN 2.0 specification
1075 specifying the arguments "tq", "prop_seg", "phase_seg1", "phase_seg2"
1078 $ ip link set canX type can tq 125 prop-seg 6 \
1079 phase-seg1 7 phase-seg2 2 sjw 1
1081 If the kernel option CONFIG_CAN_CALC_BITTIMING is enabled, CIA
1082 recommended CAN bit-timing parameters will be calculated if the bit-
1083 rate is specified with the argument "bitrate":
1085 $ ip link set canX type can bitrate 125000
1087 Note that this works fine for the most common CAN controllers with
1088 standard bit-rates but may *fail* for exotic bit-rates or CAN system
1089 clock frequencies. Disabling CONFIG_CAN_CALC_BITTIMING saves some
1090 space and allows user-space tools to solely determine and set the
1091 bit-timing parameters. The CAN controller specific bit-timing
1092 constants can be used for that purpose. They are listed by the
1095 $ ip -details link show can0
1097 sja1000: clock 8000000 tseg1 1..16 tseg2 1..8 sjw 1..4 brp 1..64 brp-inc 1
1099 6.5.3 Starting and stopping the CAN network device
1101 A CAN network device is started or stopped as usual with the command
1102 "ifconfig canX up/down" or "ip link set canX up/down". Be aware that
1103 you *must* define proper bit-timing parameters for real CAN devices
1104 before you can start it to avoid error-prone default settings:
1106 $ ip link set canX up type can bitrate 125000
1108 A device may enter the "bus-off" state if too much errors occurred on
1109 the CAN bus. Then no more messages are received or sent. An automatic
1110 bus-off recovery can be enabled by setting the "restart-ms" to a
1111 non-zero value, e.g.:
1113 $ ip link set canX type can restart-ms 100
1115 Alternatively, the application may realize the "bus-off" condition
1116 by monitoring CAN error message frames and do a restart when
1117 appropriate with the command:
1119 $ ip link set canX type can restart
1121 Note that a restart will also create a CAN error message frame (see
1124 6.6 CAN FD (flexible data rate) driver support
1126 CAN FD capable CAN controllers support two different bitrates for the
1127 arbitration phase and the payload phase of the CAN FD frame. Therefore a
1128 second bittiming has to be specified in order to enable the CAN FD bitrate.
1130 Additionally CAN FD capable CAN controllers support up to 64 bytes of
1131 payload. The representation of this length in can_frame.can_dlc and
1132 canfd_frame.len for userspace applications and inside the Linux network
1133 layer is a plain value from 0 .. 64 instead of the CAN 'data length code'.
1134 The data length code was a 1:1 mapping to the payload length in the legacy
1135 CAN frames anyway. The payload length to the bus-relevant DLC mapping is
1136 only performed inside the CAN drivers, preferably with the helper
1137 functions can_dlc2len() and can_len2dlc().
1139 The CAN netdevice driver capabilities can be distinguished by the network
1140 devices maximum transfer unit (MTU):
1142 MTU = 16 (CAN_MTU) => sizeof(struct can_frame) => 'legacy' CAN device
1143 MTU = 72 (CANFD_MTU) => sizeof(struct canfd_frame) => CAN FD capable device
1145 The CAN device MTU can be retrieved e.g. with a SIOCGIFMTU ioctl() syscall.
1146 N.B. CAN FD capable devices can also handle and send legacy CAN frames.
1148 FIXME: Add details about the CAN FD controller configuration when available.
1150 6.7 Supported CAN hardware
1152 Please check the "Kconfig" file in "drivers/net/can" to get an actual
1153 list of the support CAN hardware. On the Socket CAN project website
1154 (see chapter 7) there might be further drivers available, also for
1155 older kernel versions.
1157 7. Socket CAN resources
1158 -----------------------
1160 You can find further resources for Socket CAN like user space tools,
1161 support for old kernel versions, more drivers, mailing lists, etc.
1162 at the BerliOS OSS project website for Socket CAN:
1164 http://developer.berlios.de/projects/socketcan
1166 If you have questions, bug fixes, etc., don't hesitate to post them to
1167 the Socketcan-Users mailing list. But please search the archives first.
1172 Oliver Hartkopp (PF_CAN core, filters, drivers, bcm, SJA1000 driver)
1173 Urs Thuermann (PF_CAN core, kernel integration, socket interfaces, raw, vcan)
1174 Jan Kizka (RT-SocketCAN core, Socket-API reconciliation)
1175 Wolfgang Grandegger (RT-SocketCAN core & drivers, Raw Socket-API reviews,
1176 CAN device driver interface, MSCAN driver)
1177 Robert Schwebel (design reviews, PTXdist integration)
1178 Marc Kleine-Budde (design reviews, Kernel 2.6 cleanups, drivers)
1179 Benedikt Spranger (reviews)
1180 Thomas Gleixner (LKML reviews, coding style, posting hints)
1181 Andrey Volkov (kernel subtree structure, ioctls, MSCAN driver)
1182 Matthias Brukner (first SJA1000 CAN netdevice implementation Q2/2003)
1183 Klaus Hitschler (PEAK driver integration)
1184 Uwe Koppe (CAN netdevices with PF_PACKET approach)
1185 Michael Schulze (driver layer loopback requirement, RT CAN drivers review)
1186 Pavel Pisa (Bit-timing calculation)
1187 Sascha Hauer (SJA1000 platform driver)
1188 Sebastian Haas (SJA1000 EMS PCI driver)
1189 Markus Plessing (SJA1000 EMS PCI driver)
1190 Per Dalen (SJA1000 Kvaser PCI driver)
1191 Sam Ravnborg (reviews, coding style, kbuild help)