blob: 820f55344edc0a035358fa643bbe79c48d4d887f [file] [log] [blame]
Oliver Hartkoppf7ab97f2007-11-16 16:09:28 -08001============================================================================
2
3can.txt
4
5Readme file for the Controller Area Network Protocol Family (aka Socket CAN)
6
7This file contains
8
9 1 Overview / What is Socket CAN
10
11 2 Motivation / Why using the socket API
12
13 3 Socket CAN concept
14 3.1 receive lists
15 3.2 local loopback of sent frames
16 3.3 network security issues (capabilities)
17 3.4 network problem notifications
18
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
Oliver Hartkoppea53fe02012-06-16 12:01:58 +020025 4.1.5 RAW socket option CAN_RAW_FD_FRAMES
26 4.1.6 RAW socket returned message flags
Oliver Hartkoppf7ab97f2007-11-16 16:09:28 -080027 4.2 Broadcast Manager protocol sockets (SOCK_DGRAM)
28 4.3 connected transport protocols (SOCK_SEQPACKET)
29 4.4 unconnected transport protocols (SOCK_DGRAM)
30
31 5 Socket CAN core module
32 5.1 can.ko module params
33 5.2 procfs content
34 5.3 writing own CAN protocol modules
35
36 6 CAN network drivers
37 6.1 general settings
38 6.2 local loopback of sent frames
39 6.3 CAN controller hardware filters
Oliver Hartkoppe5d23042008-09-23 14:53:14 -070040 6.4 The virtual CAN driver (vcan)
Wolfgang Grandeggere20dad92009-05-15 23:39:27 +000041 6.5 The CAN network device driver interface
42 6.5.1 Netlink interface to set/get devices properties
43 6.5.2 Setting the CAN bit-timing
44 6.5.3 Starting and stopping the CAN network device
Oliver Hartkoppea53fe02012-06-16 12:01:58 +020045 6.6 CAN FD (flexible data rate) driver support
46 6.7 supported CAN hardware
Oliver Hartkoppf7ab97f2007-11-16 16:09:28 -080047
Wolfgang Grandeggere20dad92009-05-15 23:39:27 +000048 7 Socket CAN resources
49
50 8 Credits
Oliver Hartkoppf7ab97f2007-11-16 16:09:28 -080051
52============================================================================
53
541. Overview / What is Socket CAN
55--------------------------------
56
57The socketcan package is an implementation of CAN protocols
58(Controller Area Network) for Linux. CAN is a networking technology
59which has widespread use in automation, embedded devices, and
60automotive fields. While there have been other CAN implementations
61for Linux based on character devices, Socket CAN uses the Berkeley
62socket API, the Linux network stack and implements the CAN device
63drivers as network interfaces. The CAN socket API has been designed
64as similar as possible to the TCP/IP protocols to allow programmers,
65familiar with network programming, to easily learn how to use CAN
66sockets.
67
682. Motivation / Why using the socket API
69----------------------------------------
70
71There have been CAN implementations for Linux before Socket CAN so the
72question arises, why we have started another project. Most existing
73implementations come as a device driver for some CAN hardware, they
74are based on character devices and provide comparatively little
75functionality. Usually, there is only a hardware-specific device
76driver which provides a character device interface to send and
77receive raw CAN frames, directly to/from the controller hardware.
78Queueing of frames and higher-level transport protocols like ISO-TP
79have to be implemented in user space applications. Also, most
80character-device implementations support only one single process to
81open the device at a time, similar to a serial interface. Exchanging
82the CAN controller requires employment of another device driver and
83often the need for adaption of large parts of the application to the
84new driver's API.
85
86Socket CAN was designed to overcome all of these limitations. A new
87protocol family has been implemented which provides a socket interface
88to user space applications and which builds upon the Linux network
89layer, so to use all of the provided queueing functionality. A device
90driver for CAN controller hardware registers itself with the Linux
91network layer as a network device, so that CAN frames from the
92controller can be passed up to the network layer and on to the CAN
93protocol family module and also vice-versa. Also, the protocol family
94module provides an API for transport protocol modules to register, so
95that any number of transport protocols can be loaded or unloaded
96dynamically. In fact, the can core module alone does not provide any
97protocol and cannot be used without loading at least one additional
98protocol module. Multiple sockets can be opened at the same time,
99on different or the same protocol module and they can listen/send
100frames on different or the same CAN IDs. Several sockets listening on
101the same interface for frames with the same CAN ID are all passed the
102same received matching CAN frames. An application wishing to
103communicate using a specific transport protocol, e.g. ISO-TP, just
104selects that protocol when opening the socket, and then can read and
105write application data byte streams, without having to deal with
106CAN-IDs, frames, etc.
107
108Similar functionality visible from user-space could be provided by a
109character device, too, but this would lead to a technically inelegant
110solution for a couple of reasons:
111
112* Intricate usage. Instead of passing a protocol argument to
113 socket(2) and using bind(2) to select a CAN interface and CAN ID, an
114 application would have to do all these operations using ioctl(2)s.
115
116* Code duplication. A character device cannot make use of the Linux
117 network queueing code, so all that code would have to be duplicated
118 for CAN networking.
119
120* Abstraction. In most existing character-device implementations, the
121 hardware-specific device driver for a CAN controller directly
122 provides the character device for the application to work with.
123 This is at least very unusual in Unix systems for both, char and
124 block devices. For example you don't have a character device for a
125 certain UART of a serial interface, a certain sound chip in your
126 computer, a SCSI or IDE controller providing access to your hard
127 disk or tape streamer device. Instead, you have abstraction layers
128 which provide a unified character or block device interface to the
129 application on the one hand, and a interface for hardware-specific
130 device drivers on the other hand. These abstractions are provided
131 by subsystems like the tty layer, the audio subsystem or the SCSI
132 and IDE subsystems for the devices mentioned above.
133
134 The easiest way to implement a CAN device driver is as a character
135 device without such a (complete) abstraction layer, as is done by most
136 existing drivers. The right way, however, would be to add such a
137 layer with all the functionality like registering for certain CAN
138 IDs, supporting several open file descriptors and (de)multiplexing
139 CAN frames between them, (sophisticated) queueing of CAN frames, and
140 providing an API for device drivers to register with. However, then
141 it would be no more difficult, or may be even easier, to use the
142 networking framework provided by the Linux kernel, and this is what
143 Socket CAN does.
144
145 The use of the networking framework of the Linux kernel is just the
146 natural and most appropriate way to implement CAN for Linux.
147
1483. Socket CAN concept
149---------------------
150
151 As described in chapter 2 it is the main goal of Socket CAN to
152 provide a socket interface to user space applications which builds
153 upon the Linux network layer. In contrast to the commonly known
154 TCP/IP and ethernet networking, the CAN bus is a broadcast-only(!)
155 medium that has no MAC-layer addressing like ethernet. The CAN-identifier
156 (can_id) is used for arbitration on the CAN-bus. Therefore the CAN-IDs
157 have to be chosen uniquely on the bus. When designing a CAN-ECU
158 network the CAN-IDs are mapped to be sent by a specific ECU.
159 For this reason a CAN-ID can be treated best as a kind of source address.
160
161 3.1 receive lists
162
163 The network transparent access of multiple applications leads to the
164 problem that different applications may be interested in the same
165 CAN-IDs from the same CAN network interface. The Socket CAN core
166 module - which implements the protocol family CAN - provides several
167 high efficient receive lists for this reason. If e.g. a user space
168 application opens a CAN RAW socket, the raw protocol module itself
169 requests the (range of) CAN-IDs from the Socket CAN core that are
170 requested by the user. The subscription and unsubscription of
171 CAN-IDs can be done for specific CAN interfaces or for all(!) known
172 CAN interfaces with the can_rx_(un)register() functions provided to
173 CAN protocol modules by the SocketCAN core (see chapter 5).
174 To optimize the CPU usage at runtime the receive lists are split up
175 into several specific lists per device that match the requested
176 filter complexity for a given use-case.
177
178 3.2 local loopback of sent frames
179
180 As known from other networking concepts the data exchanging
181 applications may run on the same or different nodes without any
182 change (except for the according addressing information):
183
184 ___ ___ ___ _______ ___
185 | _ | | _ | | _ | | _ _ | | _ |
186 ||A|| ||B|| ||C|| ||A| |B|| ||C||
187 |___| |___| |___| |_______| |___|
188 | | | | |
189 -----------------(1)- CAN bus -(2)---------------
190
191 To ensure that application A receives the same information in the
192 example (2) as it would receive in example (1) there is need for
193 some kind of local loopback of the sent CAN frames on the appropriate
194 node.
195
196 The Linux network devices (by default) just can handle the
197 transmission and reception of media dependent frames. Due to the
Matt LaPlanted9195882008-07-25 19:45:33 -0700198 arbitration on the CAN bus the transmission of a low prio CAN-ID
Oliver Hartkoppf7ab97f2007-11-16 16:09:28 -0800199 may be delayed by the reception of a high prio CAN frame. To
200 reflect the correct* traffic on the node the loopback of the sent
201 data has to be performed right after a successful transmission. If
202 the CAN network interface is not capable of performing the loopback for
203 some reason the SocketCAN core can do this task as a fallback solution.
204 See chapter 6.2 for details (recommended).
205
206 The loopback functionality is enabled by default to reflect standard
207 networking behaviour for CAN applications. Due to some requests from
208 the RT-SocketCAN group the loopback optionally may be disabled for each
209 separate socket. See sockopts from the CAN RAW sockets in chapter 4.1.
210
211 * = you really like to have this when you're running analyser tools
212 like 'candump' or 'cansniffer' on the (same) node.
213
214 3.3 network security issues (capabilities)
215
216 The Controller Area Network is a local field bus transmitting only
217 broadcast messages without any routing and security concepts.
218 In the majority of cases the user application has to deal with
219 raw CAN frames. Therefore it might be reasonable NOT to restrict
220 the CAN access only to the user root, as known from other networks.
221 Since the currently implemented CAN_RAW and CAN_BCM sockets can only
222 send and receive frames to/from CAN interfaces it does not affect
223 security of others networks to allow all users to access the CAN.
224 To enable non-root users to access CAN_RAW and CAN_BCM protocol
225 sockets the Kconfig options CAN_RAW_USER and/or CAN_BCM_USER may be
226 selected at kernel compile time.
227
228 3.4 network problem notifications
229
230 The use of the CAN bus may lead to several problems on the physical
231 and media access control layer. Detecting and logging of these lower
232 layer problems is a vital requirement for CAN users to identify
233 hardware issues on the physical transceiver layer as well as
234 arbitration problems and error frames caused by the different
235 ECUs. The occurrence of detected errors are important for diagnosis
236 and have to be logged together with the exact timestamp. For this
Oliver Hartkoppd6e640f2012-05-08 22:20:33 +0200237 reason the CAN interface driver can generate so called Error Message
238 Frames that can optionally be passed to the user application in the
239 same way as other CAN frames. Whenever an error on the physical layer
Oliver Hartkoppf7ab97f2007-11-16 16:09:28 -0800240 or the MAC layer is detected (e.g. by the CAN controller) the driver
Oliver Hartkoppd6e640f2012-05-08 22:20:33 +0200241 creates an appropriate error message frame. Error messages frames can
242 be requested by the user application using the common CAN filter
243 mechanisms. Inside this filter definition the (interested) type of
244 errors may be selected. The reception of error messages is disabled
245 by default. The format of the CAN error message frame is briefly
246 described in the Linux header file "include/linux/can/error.h".
Oliver Hartkoppf7ab97f2007-11-16 16:09:28 -0800247
2484. How to use Socket CAN
249------------------------
250
251 Like TCP/IP, you first need to open a socket for communicating over a
252 CAN network. Since Socket CAN implements a new protocol family, you
253 need to pass PF_CAN as the first argument to the socket(2) system
254 call. Currently, there are two CAN protocols to choose from, the raw
255 socket protocol and the broadcast manager (BCM). So to open a socket,
256 you would write
257
258 s = socket(PF_CAN, SOCK_RAW, CAN_RAW);
259
260 and
261
262 s = socket(PF_CAN, SOCK_DGRAM, CAN_BCM);
263
264 respectively. After the successful creation of the socket, you would
265 normally use the bind(2) system call to bind the socket to a CAN
266 interface (which is different from TCP/IP due to different addressing
267 - see chapter 3). After binding (CAN_RAW) or connecting (CAN_BCM)
268 the socket, you can read(2) and write(2) from/to the socket or use
269 send(2), sendto(2), sendmsg(2) and the recv* counterpart operations
270 on the socket as usual. There are also CAN specific socket options
271 described below.
272
273 The basic CAN frame structure and the sockaddr structure are defined
274 in include/linux/can.h:
275
276 struct can_frame {
277 canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */
Oliver Hartkoppea53fe02012-06-16 12:01:58 +0200278 __u8 can_dlc; /* frame payload length in byte (0 .. 8) */
Oliver Hartkoppf7ab97f2007-11-16 16:09:28 -0800279 __u8 data[8] __attribute__((aligned(8)));
280 };
281
282 The alignment of the (linear) payload data[] to a 64bit boundary
283 allows the user to define own structs and unions to easily access the
284 CAN payload. There is no given byteorder on the CAN bus by
285 default. A read(2) system call on a CAN_RAW socket transfers a
286 struct can_frame to the user space.
287
288 The sockaddr_can structure has an interface index like the
289 PF_PACKET socket, that also binds to a specific interface:
290
291 struct sockaddr_can {
292 sa_family_t can_family;
293 int can_ifindex;
294 union {
Oliver Hartkopp56690c22008-04-15 00:46:38 -0700295 /* transport protocol class address info (e.g. ISOTP) */
296 struct { canid_t rx_id, tx_id; } tp;
297
298 /* reserved for future CAN protocols address information */
Oliver Hartkoppf7ab97f2007-11-16 16:09:28 -0800299 } can_addr;
300 };
301
302 To determine the interface index an appropriate ioctl() has to
303 be used (example for CAN_RAW sockets without error checking):
304
305 int s;
306 struct sockaddr_can addr;
307 struct ifreq ifr;
308
309 s = socket(PF_CAN, SOCK_RAW, CAN_RAW);
310
311 strcpy(ifr.ifr_name, "can0" );
312 ioctl(s, SIOCGIFINDEX, &ifr);
313
314 addr.can_family = AF_CAN;
315 addr.can_ifindex = ifr.ifr_ifindex;
316
317 bind(s, (struct sockaddr *)&addr, sizeof(addr));
318
319 (..)
320
321 To bind a socket to all(!) CAN interfaces the interface index must
322 be 0 (zero). In this case the socket receives CAN frames from every
323 enabled CAN interface. To determine the originating CAN interface
324 the system call recvfrom(2) may be used instead of read(2). To send
325 on a socket that is bound to 'any' interface sendto(2) is needed to
326 specify the outgoing interface.
327
328 Reading CAN frames from a bound CAN_RAW socket (see above) consists
329 of reading a struct can_frame:
330
331 struct can_frame frame;
332
333 nbytes = read(s, &frame, sizeof(struct can_frame));
334
335 if (nbytes < 0) {
336 perror("can raw socket read");
337 return 1;
338 }
339
Matt LaPlante19f59462009-04-27 15:06:31 +0200340 /* paranoid check ... */
Oliver Hartkoppf7ab97f2007-11-16 16:09:28 -0800341 if (nbytes < sizeof(struct can_frame)) {
342 fprintf(stderr, "read: incomplete CAN frame\n");
343 return 1;
344 }
345
346 /* do something with the received CAN frame */
347
348 Writing CAN frames can be done similarly, with the write(2) system call:
349
350 nbytes = write(s, &frame, sizeof(struct can_frame));
351
352 When the CAN interface is bound to 'any' existing CAN interface
353 (addr.can_ifindex = 0) it is recommended to use recvfrom(2) if the
354 information about the originating CAN interface is needed:
355
356 struct sockaddr_can addr;
357 struct ifreq ifr;
358 socklen_t len = sizeof(addr);
359 struct can_frame frame;
360
361 nbytes = recvfrom(s, &frame, sizeof(struct can_frame),
362 0, (struct sockaddr*)&addr, &len);
363
364 /* get interface name of the received CAN frame */
365 ifr.ifr_ifindex = addr.can_ifindex;
366 ioctl(s, SIOCGIFNAME, &ifr);
367 printf("Received a CAN frame from interface %s", ifr.ifr_name);
368
369 To write CAN frames on sockets bound to 'any' CAN interface the
370 outgoing interface has to be defined certainly.
371
372 strcpy(ifr.ifr_name, "can0");
373 ioctl(s, SIOCGIFINDEX, &ifr);
374 addr.can_ifindex = ifr.ifr_ifindex;
375 addr.can_family = AF_CAN;
376
377 nbytes = sendto(s, &frame, sizeof(struct can_frame),
378 0, (struct sockaddr*)&addr, sizeof(addr));
379
Oliver Hartkoppea53fe02012-06-16 12:01:58 +0200380 Remark about CAN FD (flexible data rate) support:
381
382 Generally the handling of CAN FD is very similar to the formerly described
383 examples. The new CAN FD capable CAN controllers support two different
384 bitrates for the arbitration phase and the payload phase of the CAN FD frame
385 and up to 64 bytes of payload. This extended payload length breaks all the
386 kernel interfaces (ABI) which heavily rely on the CAN frame with fixed eight
387 bytes of payload (struct can_frame) like the CAN_RAW socket. Therefore e.g.
388 the CAN_RAW socket supports a new socket option CAN_RAW_FD_FRAMES that
389 switches the socket into a mode that allows the handling of CAN FD frames
390 and (legacy) CAN frames simultaneously (see section 4.1.5).
391
392 The struct canfd_frame is defined in include/linux/can.h:
393
394 struct canfd_frame {
395 canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */
396 __u8 len; /* frame payload length in byte (0 .. 64) */
397 __u8 flags; /* additional flags for CAN FD */
398 __u8 __res0; /* reserved / padding */
399 __u8 __res1; /* reserved / padding */
400 __u8 data[64] __attribute__((aligned(8)));
401 };
402
403 The struct canfd_frame and the existing struct can_frame have the can_id,
404 the payload length and the payload data at the same offset inside their
405 structures. This allows to handle the different structures very similar.
406 When the content of a struct can_frame is copied into a struct canfd_frame
407 all structure elements can be used as-is - only the data[] becomes extended.
408
409 When introducing the struct canfd_frame it turned out that the data length
410 code (DLC) of the struct can_frame was used as a length information as the
411 length and the DLC has a 1:1 mapping in the range of 0 .. 8. To preserve
412 the easy handling of the length information the canfd_frame.len element
413 contains a plain length value from 0 .. 64. So both canfd_frame.len and
414 can_frame.can_dlc are equal and contain a length information and no DLC.
415 For details about the distinction of CAN and CAN FD capable devices and
416 the mapping to the bus-relevant data length code (DLC), see chapter 6.6.
417
418 The length of the two CAN(FD) frame structures define the maximum transfer
419 unit (MTU) of the CAN(FD) network interface and skbuff data length. Two
420 definitions are specified for CAN specific MTUs in include/linux/can.h :
421
422 #define CAN_MTU (sizeof(struct can_frame)) == 16 => 'legacy' CAN frame
423 #define CANFD_MTU (sizeof(struct canfd_frame)) == 72 => CAN FD frame
424
Oliver Hartkoppf7ab97f2007-11-16 16:09:28 -0800425 4.1 RAW protocol sockets with can_filters (SOCK_RAW)
426
427 Using CAN_RAW sockets is extensively comparable to the commonly
428 known access to CAN character devices. To meet the new possibilities
429 provided by the multi user SocketCAN approach, some reasonable
430 defaults are set at RAW socket binding time:
431
432 - The filters are set to exactly one filter receiving everything
Oliver Hartkoppd6e640f2012-05-08 22:20:33 +0200433 - The socket only receives valid data frames (=> no error message frames)
Oliver Hartkoppf7ab97f2007-11-16 16:09:28 -0800434 - The loopback of sent CAN frames is enabled (see chapter 3.2)
435 - The socket does not receive its own sent frames (in loopback mode)
436
437 These default settings may be changed before or after binding the socket.
438 To use the referenced definitions of the socket options for CAN_RAW
439 sockets, include <linux/can/raw.h>.
440
441 4.1.1 RAW socket option CAN_RAW_FILTER
442
443 The reception of CAN frames using CAN_RAW sockets can be controlled
444 by defining 0 .. n filters with the CAN_RAW_FILTER socket option.
445
446 The CAN filter structure is defined in include/linux/can.h:
447
448 struct can_filter {
449 canid_t can_id;
450 canid_t can_mask;
451 };
452
453 A filter matches, when
454
455 <received_can_id> & mask == can_id & mask
456
457 which is analogous to known CAN controllers hardware filter semantics.
458 The filter can be inverted in this semantic, when the CAN_INV_FILTER
459 bit is set in can_id element of the can_filter structure. In
460 contrast to CAN controller hardware filters the user may set 0 .. n
461 receive filters for each open socket separately:
462
463 struct can_filter rfilter[2];
464
465 rfilter[0].can_id = 0x123;
466 rfilter[0].can_mask = CAN_SFF_MASK;
467 rfilter[1].can_id = 0x200;
468 rfilter[1].can_mask = 0x700;
469
470 setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter));
471
472 To disable the reception of CAN frames on the selected CAN_RAW socket:
473
474 setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);
475
476 To set the filters to zero filters is quite obsolete as not read
477 data causes the raw socket to discard the received CAN frames. But
478 having this 'send only' use-case we may remove the receive list in the
479 Kernel to save a little (really a very little!) CPU usage.
480
481 4.1.2 RAW socket option CAN_RAW_ERR_FILTER
482
483 As described in chapter 3.4 the CAN interface driver can generate so
Oliver Hartkoppd6e640f2012-05-08 22:20:33 +0200484 called Error Message Frames that can optionally be passed to the user
Oliver Hartkoppf7ab97f2007-11-16 16:09:28 -0800485 application in the same way as other CAN frames. The possible
486 errors are divided into different error classes that may be filtered
487 using the appropriate error mask. To register for every possible
488 error condition CAN_ERR_MASK can be used as value for the error mask.
489 The values for the error mask are defined in linux/can/error.h .
490
491 can_err_mask_t err_mask = ( CAN_ERR_TX_TIMEOUT | CAN_ERR_BUSOFF );
492
493 setsockopt(s, SOL_CAN_RAW, CAN_RAW_ERR_FILTER,
494 &err_mask, sizeof(err_mask));
495
496 4.1.3 RAW socket option CAN_RAW_LOOPBACK
497
498 To meet multi user needs the local loopback is enabled by default
499 (see chapter 3.2 for details). But in some embedded use-cases
500 (e.g. when only one application uses the CAN bus) this loopback
501 functionality can be disabled (separately for each socket):
502
503 int loopback = 0; /* 0 = disabled, 1 = enabled (default) */
504
505 setsockopt(s, SOL_CAN_RAW, CAN_RAW_LOOPBACK, &loopback, sizeof(loopback));
506
507 4.1.4 RAW socket option CAN_RAW_RECV_OWN_MSGS
508
509 When the local loopback is enabled, all the sent CAN frames are
510 looped back to the open CAN sockets that registered for the CAN
511 frames' CAN-ID on this given interface to meet the multi user
512 needs. The reception of the CAN frames on the same socket that was
513 sending the CAN frame is assumed to be unwanted and therefore
514 disabled by default. This default behaviour may be changed on
515 demand:
516
517 int recv_own_msgs = 1; /* 0 = disabled (default), 1 = enabled */
518
519 setsockopt(s, SOL_CAN_RAW, CAN_RAW_RECV_OWN_MSGS,
520 &recv_own_msgs, sizeof(recv_own_msgs));
521
Oliver Hartkoppea53fe02012-06-16 12:01:58 +0200522 4.1.5 RAW socket option CAN_RAW_FD_FRAMES
523
524 CAN FD support in CAN_RAW sockets can be enabled with a new socket option
525 CAN_RAW_FD_FRAMES which is off by default. When the new socket option is
526 not supported by the CAN_RAW socket (e.g. on older kernels), switching the
527 CAN_RAW_FD_FRAMES option returns the error -ENOPROTOOPT.
528
529 Once CAN_RAW_FD_FRAMES is enabled the application can send both CAN frames
530 and CAN FD frames. OTOH the application has to handle CAN and CAN FD frames
531 when reading from the socket.
532
533 CAN_RAW_FD_FRAMES enabled: CAN_MTU and CANFD_MTU are allowed
534 CAN_RAW_FD_FRAMES disabled: only CAN_MTU is allowed (default)
535
536 Example:
537 [ remember: CANFD_MTU == sizeof(struct canfd_frame) ]
538
539 struct canfd_frame cfd;
540
541 nbytes = read(s, &cfd, CANFD_MTU);
542
543 if (nbytes == CANFD_MTU) {
544 printf("got CAN FD frame with length %d\n", cfd.len);
545 /* cfd.flags contains valid data */
546 } else if (nbytes == CAN_MTU) {
547 printf("got legacy CAN frame with length %d\n", cfd.len);
548 /* cfd.flags is undefined */
549 } else {
550 fprintf(stderr, "read: invalid CAN(FD) frame\n");
551 return 1;
552 }
553
554 /* the content can be handled independently from the received MTU size */
555
556 printf("can_id: %X data length: %d data: ", cfd.can_id, cfd.len);
557 for (i = 0; i < cfd.len; i++)
558 printf("%02X ", cfd.data[i]);
559
560 When reading with size CANFD_MTU only returns CAN_MTU bytes that have
561 been received from the socket a legacy CAN frame has been read into the
562 provided CAN FD structure. Note that the canfd_frame.flags data field is
563 not specified in the struct can_frame and therefore it is only valid in
564 CANFD_MTU sized CAN FD frames.
565
566 As long as the payload length is <=8 the received CAN frames from CAN FD
567 capable CAN devices can be received and read by legacy sockets too. When
568 user-generated CAN FD frames have a payload length <=8 these can be send
569 by legacy CAN network interfaces too. Sending CAN FD frames with payload
570 length > 8 to a legacy CAN network interface returns an -EMSGSIZE error.
571
572 Implementation hint for new CAN applications:
573
574 To build a CAN FD aware application use struct canfd_frame as basic CAN
575 data structure for CAN_RAW based applications. When the application is
576 executed on an older Linux kernel and switching the CAN_RAW_FD_FRAMES
577 socket option returns an error: No problem. You'll get legacy CAN frames
578 or CAN FD frames and can process them the same way.
579
580 When sending to CAN devices make sure that the device is capable to handle
581 CAN FD frames by checking if the device maximum transfer unit is CANFD_MTU.
582 The CAN device MTU can be retrieved e.g. with a SIOCGIFMTU ioctl() syscall.
583
584 4.1.6 RAW socket returned message flags
Oliver Hartkopp1e556592010-10-19 09:32:04 +0000585
586 When using recvmsg() call, the msg->msg_flags may contain following flags:
587
588 MSG_DONTROUTE: set when the received frame was created on the local host.
589
590 MSG_CONFIRM: set when the frame was sent via the socket it is received on.
591 This flag can be interpreted as a 'transmission confirmation' when the
592 CAN driver supports the echo of frames on driver level, see 3.2 and 6.2.
593 In order to receive such messages, CAN_RAW_RECV_OWN_MSGS must be set.
594
Oliver Hartkoppf7ab97f2007-11-16 16:09:28 -0800595 4.2 Broadcast Manager protocol sockets (SOCK_DGRAM)
596 4.3 connected transport protocols (SOCK_SEQPACKET)
597 4.4 unconnected transport protocols (SOCK_DGRAM)
598
599
6005. Socket CAN core module
601-------------------------
602
603 The Socket CAN core module implements the protocol family
604 PF_CAN. CAN protocol modules are loaded by the core module at
605 runtime. The core module provides an interface for CAN protocol
606 modules to subscribe needed CAN IDs (see chapter 3.1).
607
608 5.1 can.ko module params
609
610 - stats_timer: To calculate the Socket CAN core statistics
611 (e.g. current/maximum frames per second) this 1 second timer is
612 invoked at can.ko module start time by default. This timer can be
Matt LaPlanted9195882008-07-25 19:45:33 -0700613 disabled by using stattimer=0 on the module commandline.
Oliver Hartkoppf7ab97f2007-11-16 16:09:28 -0800614
615 - debug: (removed since SocketCAN SVN r546)
616
617 5.2 procfs content
618
619 As described in chapter 3.1 the Socket CAN core uses several filter
620 lists to deliver received CAN frames to CAN protocol modules. These
621 receive lists, their filters and the count of filter matches can be
622 checked in the appropriate receive list. All entries contain the
623 device and a protocol module identifier:
624
625 foo@bar:~$ cat /proc/net/can/rcvlist_all
626
627 receive list 'rx_all':
628 (vcan3: no entry)
629 (vcan2: no entry)
630 (vcan1: no entry)
631 device can_id can_mask function userdata matches ident
632 vcan0 000 00000000 f88e6370 f6c6f400 0 raw
633 (any: no entry)
634
635 In this example an application requests any CAN traffic from vcan0.
636
637 rcvlist_all - list for unfiltered entries (no filter operations)
638 rcvlist_eff - list for single extended frame (EFF) entries
Oliver Hartkoppd6e640f2012-05-08 22:20:33 +0200639 rcvlist_err - list for error message frames masks
Oliver Hartkoppf7ab97f2007-11-16 16:09:28 -0800640 rcvlist_fil - list for mask/value filters
641 rcvlist_inv - list for mask/value filters (inverse semantic)
642 rcvlist_sff - list for single standard frame (SFF) entries
643
644 Additional procfs files in /proc/net/can
645
646 stats - Socket CAN core statistics (rx/tx frames, match ratios, ...)
647 reset_stats - manual statistic reset
648 version - prints the Socket CAN core version and the ABI version
649
650 5.3 writing own CAN protocol modules
651
652 To implement a new protocol in the protocol family PF_CAN a new
653 protocol has to be defined in include/linux/can.h .
654 The prototypes and definitions to use the Socket CAN core can be
655 accessed by including include/linux/can/core.h .
656 In addition to functions that register the CAN protocol and the
657 CAN device notifier chain there are functions to subscribe CAN
658 frames received by CAN interfaces and to send CAN frames:
659
660 can_rx_register - subscribe CAN frames from a specific interface
661 can_rx_unregister - unsubscribe CAN frames from a specific interface
662 can_send - transmit a CAN frame (optional with local loopback)
663
664 For details see the kerneldoc documentation in net/can/af_can.c or
665 the source code of net/can/raw.c or net/can/bcm.c .
666
6676. CAN network drivers
668----------------------
669
670 Writing a CAN network device driver is much easier than writing a
671 CAN character device driver. Similar to other known network device
672 drivers you mainly have to deal with:
673
674 - TX: Put the CAN frame from the socket buffer to the CAN controller.
675 - RX: Put the CAN frame from the CAN controller to the socket buffer.
676
677 See e.g. at Documentation/networking/netdevices.txt . The differences
678 for writing CAN network device driver are described below:
679
680 6.1 general settings
681
682 dev->type = ARPHRD_CAN; /* the netdevice hardware type */
683 dev->flags = IFF_NOARP; /* CAN has no arp */
684
Oliver Hartkoppea53fe02012-06-16 12:01:58 +0200685 dev->mtu = CAN_MTU; /* sizeof(struct can_frame) -> legacy CAN interface */
Oliver Hartkoppf7ab97f2007-11-16 16:09:28 -0800686
Oliver Hartkoppea53fe02012-06-16 12:01:58 +0200687 or alternative, when the controller supports CAN with flexible data rate:
688 dev->mtu = CANFD_MTU; /* sizeof(struct canfd_frame) -> CAN FD interface */
689
690 The struct can_frame or struct canfd_frame is the payload of each socket
691 buffer (skbuff) in the protocol family PF_CAN.
Oliver Hartkoppf7ab97f2007-11-16 16:09:28 -0800692
693 6.2 local loopback of sent frames
694
695 As described in chapter 3.2 the CAN network device driver should
696 support a local loopback functionality similar to the local echo
697 e.g. of tty devices. In this case the driver flag IFF_ECHO has to be
698 set to prevent the PF_CAN core from locally echoing sent frames
699 (aka loopback) as fallback solution:
700
701 dev->flags = (IFF_NOARP | IFF_ECHO);
702
703 6.3 CAN controller hardware filters
704
705 To reduce the interrupt load on deep embedded systems some CAN
706 controllers support the filtering of CAN IDs or ranges of CAN IDs.
707 These hardware filter capabilities vary from controller to
708 controller and have to be identified as not feasible in a multi-user
709 networking approach. The use of the very controller specific
710 hardware filters could make sense in a very dedicated use-case, as a
711 filter on driver level would affect all users in the multi-user
712 system. The high efficient filter sets inside the PF_CAN core allow
713 to set different multiple filters for each socket separately.
714 Therefore the use of hardware filters goes to the category 'handmade
715 tuning on deep embedded systems'. The author is running a MPC603e
716 @133MHz with four SJA1000 CAN controllers from 2002 under heavy bus
717 load without any problems ...
718
Oliver Hartkoppe5d23042008-09-23 14:53:14 -0700719 6.4 The virtual CAN driver (vcan)
720
721 Similar to the network loopback devices, vcan offers a virtual local
722 CAN interface. A full qualified address on CAN consists of
723
724 - a unique CAN Identifier (CAN ID)
725 - the CAN bus this CAN ID is transmitted on (e.g. can0)
726
727 so in common use cases more than one virtual CAN interface is needed.
728
729 The virtual CAN interfaces allow the transmission and reception of CAN
730 frames without real CAN controller hardware. Virtual CAN network
731 devices are usually named 'vcanX', like vcan0 vcan1 vcan2 ...
732 When compiled as a module the virtual CAN driver module is called vcan.ko
733
734 Since Linux Kernel version 2.6.24 the vcan driver supports the Kernel
735 netlink interface to create vcan network devices. The creation and
736 removal of vcan network devices can be managed with the ip(8) tool:
737
738 - Create a virtual CAN network interface:
Wolfgang Grandeggere20dad92009-05-15 23:39:27 +0000739 $ ip link add type vcan
Oliver Hartkoppe5d23042008-09-23 14:53:14 -0700740
741 - Create a virtual CAN network interface with a specific name 'vcan42':
Wolfgang Grandeggere20dad92009-05-15 23:39:27 +0000742 $ ip link add dev vcan42 type vcan
Oliver Hartkoppe5d23042008-09-23 14:53:14 -0700743
744 - Remove a (virtual CAN) network interface 'vcan42':
Wolfgang Grandeggere20dad92009-05-15 23:39:27 +0000745 $ ip link del vcan42
Oliver Hartkoppe5d23042008-09-23 14:53:14 -0700746
Wolfgang Grandeggere20dad92009-05-15 23:39:27 +0000747 6.5 The CAN network device driver interface
Oliver Hartkoppe5d23042008-09-23 14:53:14 -0700748
Wolfgang Grandeggere20dad92009-05-15 23:39:27 +0000749 The CAN network device driver interface provides a generic interface
750 to setup, configure and monitor CAN network devices. The user can then
751 configure the CAN device, like setting the bit-timing parameters, via
752 the netlink interface using the program "ip" from the "IPROUTE2"
753 utility suite. The following chapter describes briefly how to use it.
754 Furthermore, the interface uses a common data structure and exports a
755 set of common functions, which all real CAN network device drivers
756 should use. Please have a look to the SJA1000 or MSCAN driver to
757 understand how to use them. The name of the module is can-dev.ko.
Oliver Hartkoppe5d23042008-09-23 14:53:14 -0700758
Wolfgang Grandeggere20dad92009-05-15 23:39:27 +0000759 6.5.1 Netlink interface to set/get devices properties
Oliver Hartkoppf7ab97f2007-11-16 16:09:28 -0800760
Wolfgang Grandeggere20dad92009-05-15 23:39:27 +0000761 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"
Masanari Iidac94bed8e2012-04-10 00:22:13 +0900764 of the IPROUTE2 utility suite is available and it can be used as shown
Wolfgang Grandeggere20dad92009-05-15 23:39:27 +0000765 below:
Oliver Hartkoppf7ab97f2007-11-16 16:09:28 -0800766
Wolfgang Grandeggere20dad92009-05-15 23:39:27 +0000767 - Setting CAN device properties:
Oliver Hartkoppf7ab97f2007-11-16 16:09:28 -0800768
Wolfgang Grandeggere20dad92009-05-15 23:39:27 +0000769 $ ip link set can0 type can help
770 Usage: ip link set DEVICE type can
771 [ bitrate BITRATE [ sample-point SAMPLE-POINT] ] |
772 [ tq TQ prop-seg PROP_SEG phase-seg1 PHASE-SEG1
773 phase-seg2 PHASE-SEG2 [ sjw SJW ] ]
Oliver Hartkoppf7ab97f2007-11-16 16:09:28 -0800774
Wolfgang Grandeggere20dad92009-05-15 23:39:27 +0000775 [ loopback { on | off } ]
776 [ listen-only { on | off } ]
777 [ triple-sampling { on | off } ]
Oliver Hartkoppf7ab97f2007-11-16 16:09:28 -0800778
Wolfgang Grandeggere20dad92009-05-15 23:39:27 +0000779 [ restart-ms TIME-MS ]
780 [ restart ]
Oliver Hartkoppf7ab97f2007-11-16 16:09:28 -0800781
Wolfgang Grandeggere20dad92009-05-15 23:39:27 +0000782 Where: BITRATE := { 1..1000000 }
783 SAMPLE-POINT := { 0.000..0.999 }
784 TQ := { NUMBER }
785 PROP-SEG := { 1..8 }
786 PHASE-SEG1 := { 1..8 }
787 PHASE-SEG2 := { 1..8 }
788 SJW := { 1..4 }
789 RESTART-MS := { 0 | NUMBER }
Oliver Hartkoppf7ab97f2007-11-16 16:09:28 -0800790
Wolfgang Grandeggere20dad92009-05-15 23:39:27 +0000791 - Display CAN device details and statistics:
792
793 $ ip -details -statistics link show can0
794 2: can0: <NOARP,UP,LOWER_UP,ECHO> mtu 16 qdisc pfifo_fast state UP qlen 10
795 link/can
796 can <TRIPLE-SAMPLING> state ERROR-ACTIVE restart-ms 100
797 bitrate 125000 sample_point 0.875
798 tq 125 prop-seg 6 phase-seg1 7 phase-seg2 2 sjw 1
799 sja1000: tseg1 1..16 tseg2 1..8 sjw 1..4 brp 1..64 brp-inc 1
800 clock 8000000
801 re-started bus-errors arbit-lost error-warn error-pass bus-off
802 41 17457 0 41 42 41
803 RX: bytes packets errors dropped overrun mcast
804 140859 17608 17457 0 0 0
805 TX: bytes packets errors dropped carrier collsns
806 861 112 0 41 0 0
807
808 More info to the above output:
809
810 "<TRIPLE-SAMPLING>"
811 Shows the list of selected CAN controller modes: LOOPBACK,
812 LISTEN-ONLY, or TRIPLE-SAMPLING.
813
814 "state ERROR-ACTIVE"
815 The current state of the CAN controller: "ERROR-ACTIVE",
816 "ERROR-WARNING", "ERROR-PASSIVE", "BUS-OFF" or "STOPPED"
817
818 "restart-ms 100"
819 Automatic restart delay time. If set to a non-zero value, a
820 restart of the CAN controller will be triggered automatically
821 in case of a bus-off condition after the specified delay time
822 in milliseconds. By default it's off.
823
824 "bitrate 125000 sample_point 0.875"
825 Shows the real bit-rate in bits/sec and the sample-point in the
826 range 0.000..0.999. If the calculation of bit-timing parameters
827 is enabled in the kernel (CONFIG_CAN_CALC_BITTIMING=y), the
828 bit-timing can be defined by setting the "bitrate" argument.
829 Optionally the "sample-point" can be specified. By default it's
830 0.000 assuming CIA-recommended sample-points.
831
832 "tq 125 prop-seg 6 phase-seg1 7 phase-seg2 2 sjw 1"
833 Shows the time quanta in ns, propagation segment, phase buffer
834 segment 1 and 2 and the synchronisation jump width in units of
835 tq. They allow to define the CAN bit-timing in a hardware
836 independent format as proposed by the Bosch CAN 2.0 spec (see
837 chapter 8 of http://www.semiconductors.bosch.de/pdf/can2spec.pdf).
838
839 "sja1000: tseg1 1..16 tseg2 1..8 sjw 1..4 brp 1..64 brp-inc 1
840 clock 8000000"
841 Shows the bit-timing constants of the CAN controller, here the
842 "sja1000". The minimum and maximum values of the time segment 1
843 and 2, the synchronisation jump width in units of tq, the
844 bitrate pre-scaler and the CAN system clock frequency in Hz.
845 These constants could be used for user-defined (non-standard)
846 bit-timing calculation algorithms in user-space.
847
848 "re-started bus-errors arbit-lost error-warn error-pass bus-off"
849 Shows the number of restarts, bus and arbitration lost errors,
850 and the state changes to the error-warning, error-passive and
851 bus-off state. RX overrun errors are listed in the "overrun"
852 field of the standard network statistics.
853
854 6.5.2 Setting the CAN bit-timing
855
856 The CAN bit-timing parameters can always be defined in a hardware
857 independent format as proposed in the Bosch CAN 2.0 specification
858 specifying the arguments "tq", "prop_seg", "phase_seg1", "phase_seg2"
859 and "sjw":
860
861 $ ip link set canX type can tq 125 prop-seg 6 \
862 phase-seg1 7 phase-seg2 2 sjw 1
863
864 If the kernel option CONFIG_CAN_CALC_BITTIMING is enabled, CIA
865 recommended CAN bit-timing parameters will be calculated if the bit-
866 rate is specified with the argument "bitrate":
867
868 $ ip link set canX type can bitrate 125000
869
870 Note that this works fine for the most common CAN controllers with
871 standard bit-rates but may *fail* for exotic bit-rates or CAN system
872 clock frequencies. Disabling CONFIG_CAN_CALC_BITTIMING saves some
873 space and allows user-space tools to solely determine and set the
874 bit-timing parameters. The CAN controller specific bit-timing
875 constants can be used for that purpose. They are listed by the
876 following command:
877
878 $ ip -details link show can0
879 ...
880 sja1000: clock 8000000 tseg1 1..16 tseg2 1..8 sjw 1..4 brp 1..64 brp-inc 1
881
882 6.5.3 Starting and stopping the CAN network device
883
884 A CAN network device is started or stopped as usual with the command
885 "ifconfig canX up/down" or "ip link set canX up/down". Be aware that
886 you *must* define proper bit-timing parameters for real CAN devices
887 before you can start it to avoid error-prone default settings:
888
889 $ ip link set canX up type can bitrate 125000
890
891 A device may enter the "bus-off" state if too much errors occurred on
892 the CAN bus. Then no more messages are received or sent. An automatic
893 bus-off recovery can be enabled by setting the "restart-ms" to a
894 non-zero value, e.g.:
895
896 $ ip link set canX type can restart-ms 100
897
898 Alternatively, the application may realize the "bus-off" condition
Oliver Hartkoppd6e640f2012-05-08 22:20:33 +0200899 by monitoring CAN error message frames and do a restart when
900 appropriate with the command:
Wolfgang Grandeggere20dad92009-05-15 23:39:27 +0000901
902 $ ip link set canX type can restart
903
Oliver Hartkoppd6e640f2012-05-08 22:20:33 +0200904 Note that a restart will also create a CAN error message frame (see
905 also chapter 3.4).
Wolfgang Grandeggere20dad92009-05-15 23:39:27 +0000906
Oliver Hartkoppea53fe02012-06-16 12:01:58 +0200907 6.6 CAN FD (flexible data rate) driver support
908
909 CAN FD capable CAN controllers support two different bitrates for the
910 arbitration phase and the payload phase of the CAN FD frame. Therefore a
911 second bittiming has to be specified in order to enable the CAN FD bitrate.
912
913 Additionally CAN FD capable CAN controllers support up to 64 bytes of
914 payload. The representation of this length in can_frame.can_dlc and
915 canfd_frame.len for userspace applications and inside the Linux network
916 layer is a plain value from 0 .. 64 instead of the CAN 'data length code'.
917 The data length code was a 1:1 mapping to the payload length in the legacy
918 CAN frames anyway. The payload length to the bus-relevant DLC mapping is
919 only performed inside the CAN drivers, preferably with the helper
920 functions can_dlc2len() and can_len2dlc().
921
922 The CAN netdevice driver capabilities can be distinguished by the network
923 devices maximum transfer unit (MTU):
924
925 MTU = 16 (CAN_MTU) => sizeof(struct can_frame) => 'legacy' CAN device
926 MTU = 72 (CANFD_MTU) => sizeof(struct canfd_frame) => CAN FD capable device
927
928 The CAN device MTU can be retrieved e.g. with a SIOCGIFMTU ioctl() syscall.
929 N.B. CAN FD capable devices can also handle and send legacy CAN frames.
930
931 FIXME: Add details about the CAN FD controller configuration when available.
932
933 6.7 Supported CAN hardware
Wolfgang Grandeggere20dad92009-05-15 23:39:27 +0000934
935 Please check the "Kconfig" file in "drivers/net/can" to get an actual
936 list of the support CAN hardware. On the Socket CAN project website
937 (see chapter 7) there might be further drivers available, also for
938 older kernel versions.
939
9407. Socket CAN resources
941-----------------------
942
943 You can find further resources for Socket CAN like user space tools,
944 support for old kernel versions, more drivers, mailing lists, etc.
945 at the BerliOS OSS project website for Socket CAN:
946
947 http://developer.berlios.de/projects/socketcan
948
949 If you have questions, bug fixes, etc., don't hesitate to post them to
950 the Socketcan-Users mailing list. But please search the archives first.
951
9528. Credits
Oliver Hartkoppf7ab97f2007-11-16 16:09:28 -0800953----------
954
Wolfgang Grandeggere20dad92009-05-15 23:39:27 +0000955 Oliver Hartkopp (PF_CAN core, filters, drivers, bcm, SJA1000 driver)
Oliver Hartkoppf7ab97f2007-11-16 16:09:28 -0800956 Urs Thuermann (PF_CAN core, kernel integration, socket interfaces, raw, vcan)
957 Jan Kizka (RT-SocketCAN core, Socket-API reconciliation)
Wolfgang Grandeggere20dad92009-05-15 23:39:27 +0000958 Wolfgang Grandegger (RT-SocketCAN core & drivers, Raw Socket-API reviews,
959 CAN device driver interface, MSCAN driver)
Oliver Hartkoppf7ab97f2007-11-16 16:09:28 -0800960 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)
Wolfgang Grandeggere20dad92009-05-15 23:39:27 +0000964 Andrey Volkov (kernel subtree structure, ioctls, MSCAN driver)
Oliver Hartkoppf7ab97f2007-11-16 16:09:28 -0800965 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)
Wolfgang Grandeggere20dad92009-05-15 23:39:27 +0000969 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)