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