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