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