0001 ===================================
0002 SocketCAN - Controller Area Network
0003 ===================================
0004
0005 Overview / What is SocketCAN
0006 ============================
0007
0008 The socketcan package is an implementation of CAN protocols
0009 (Controller Area Network) for Linux. CAN is a networking technology
0010 which has widespread use in automation, embedded devices, and
0011 automotive fields. While there have been other CAN implementations
0012 for Linux based on character devices, SocketCAN uses the Berkeley
0013 socket API, the Linux network stack and implements the CAN device
0014 drivers as network interfaces. The CAN socket API has been designed
0015 as similar as possible to the TCP/IP protocols to allow programmers,
0016 familiar with network programming, to easily learn how to use CAN
0017 sockets.
0018
0019
0020 .. _socketcan-motivation:
0021
0022 Motivation / Why Using the Socket API
0023 =====================================
0024
0025 There have been CAN implementations for Linux before SocketCAN so the
0026 question arises, why we have started another project. Most existing
0027 implementations come as a device driver for some CAN hardware, they
0028 are based on character devices and provide comparatively little
0029 functionality. Usually, there is only a hardware-specific device
0030 driver which provides a character device interface to send and
0031 receive raw CAN frames, directly to/from the controller hardware.
0032 Queueing of frames and higher-level transport protocols like ISO-TP
0033 have to be implemented in user space applications. Also, most
0034 character-device implementations support only one single process to
0035 open the device at a time, similar to a serial interface. Exchanging
0036 the CAN controller requires employment of another device driver and
0037 often the need for adaption of large parts of the application to the
0038 new driver's API.
0039
0040 SocketCAN was designed to overcome all of these limitations. A new
0041 protocol family has been implemented which provides a socket interface
0042 to user space applications and which builds upon the Linux network
0043 layer, enabling use all of the provided queueing functionality. A device
0044 driver for CAN controller hardware registers itself with the Linux
0045 network layer as a network device, so that CAN frames from the
0046 controller can be passed up to the network layer and on to the CAN
0047 protocol family module and also vice-versa. Also, the protocol family
0048 module provides an API for transport protocol modules to register, so
0049 that any number of transport protocols can be loaded or unloaded
0050 dynamically. In fact, the can core module alone does not provide any
0051 protocol and cannot be used without loading at least one additional
0052 protocol module. Multiple sockets can be opened at the same time,
0053 on different or the same protocol module and they can listen/send
0054 frames on different or the same CAN IDs. Several sockets listening on
0055 the same interface for frames with the same CAN ID are all passed the
0056 same received matching CAN frames. An application wishing to
0057 communicate using a specific transport protocol, e.g. ISO-TP, just
0058 selects that protocol when opening the socket, and then can read and
0059 write application data byte streams, without having to deal with
0060 CAN-IDs, frames, etc.
0061
0062 Similar functionality visible from user-space could be provided by a
0063 character device, too, but this would lead to a technically inelegant
0064 solution for a couple of reasons:
0065
0066 * **Intricate usage:** Instead of passing a protocol argument to
0067 socket(2) and using bind(2) to select a CAN interface and CAN ID, an
0068 application would have to do all these operations using ioctl(2)s.
0069
0070 * **Code duplication:** A character device cannot make use of the Linux
0071 network queueing code, so all that code would have to be duplicated
0072 for CAN networking.
0073
0074 * **Abstraction:** In most existing character-device implementations, the
0075 hardware-specific device driver for a CAN controller directly
0076 provides the character device for the application to work with.
0077 This is at least very unusual in Unix systems for both, char and
0078 block devices. For example you don't have a character device for a
0079 certain UART of a serial interface, a certain sound chip in your
0080 computer, a SCSI or IDE controller providing access to your hard
0081 disk or tape streamer device. Instead, you have abstraction layers
0082 which provide a unified character or block device interface to the
0083 application on the one hand, and a interface for hardware-specific
0084 device drivers on the other hand. These abstractions are provided
0085 by subsystems like the tty layer, the audio subsystem or the SCSI
0086 and IDE subsystems for the devices mentioned above.
0087
0088 The easiest way to implement a CAN device driver is as a character
0089 device without such a (complete) abstraction layer, as is done by most
0090 existing drivers. The right way, however, would be to add such a
0091 layer with all the functionality like registering for certain CAN
0092 IDs, supporting several open file descriptors and (de)multiplexing
0093 CAN frames between them, (sophisticated) queueing of CAN frames, and
0094 providing an API for device drivers to register with. However, then
0095 it would be no more difficult, or may be even easier, to use the
0096 networking framework provided by the Linux kernel, and this is what
0097 SocketCAN does.
0098
0099 The use of the networking framework of the Linux kernel is just the
0100 natural and most appropriate way to implement CAN for Linux.
0101
0102
0103 .. _socketcan-concept:
0104
0105 SocketCAN Concept
0106 =================
0107
0108 As described in :ref:`socketcan-motivation` the main goal of SocketCAN is to
0109 provide a socket interface to user space applications which builds
0110 upon the Linux network layer. In contrast to the commonly known
0111 TCP/IP and ethernet networking, the CAN bus is a broadcast-only(!)
0112 medium that has no MAC-layer addressing like ethernet. The CAN-identifier
0113 (can_id) is used for arbitration on the CAN-bus. Therefore the CAN-IDs
0114 have to be chosen uniquely on the bus. When designing a CAN-ECU
0115 network the CAN-IDs are mapped to be sent by a specific ECU.
0116 For this reason a CAN-ID can be treated best as a kind of source address.
0117
0118
0119 .. _socketcan-receive-lists:
0120
0121 Receive Lists
0122 -------------
0123
0124 The network transparent access of multiple applications leads to the
0125 problem that different applications may be interested in the same
0126 CAN-IDs from the same CAN network interface. The SocketCAN core
0127 module - which implements the protocol family CAN - provides several
0128 high efficient receive lists for this reason. If e.g. a user space
0129 application opens a CAN RAW socket, the raw protocol module itself
0130 requests the (range of) CAN-IDs from the SocketCAN core that are
0131 requested by the user. The subscription and unsubscription of
0132 CAN-IDs can be done for specific CAN interfaces or for all(!) known
0133 CAN interfaces with the can_rx_(un)register() functions provided to
0134 CAN protocol modules by the SocketCAN core (see :ref:`socketcan-core-module`).
0135 To optimize the CPU usage at runtime the receive lists are split up
0136 into several specific lists per device that match the requested
0137 filter complexity for a given use-case.
0138
0139
0140 .. _socketcan-local-loopback1:
0141
0142 Local Loopback of Sent Frames
0143 -----------------------------
0144
0145 As known from other networking concepts the data exchanging
0146 applications may run on the same or different nodes without any
0147 change (except for the according addressing information):
0148
0149 .. code::
0150
0151 ___ ___ ___ _______ ___
0152 | _ | | _ | | _ | | _ _ | | _ |
0153 ||A|| ||B|| ||C|| ||A| |B|| ||C||
0154 |___| |___| |___| |_______| |___|
0155 | | | | |
0156 -----------------(1)- CAN bus -(2)---------------
0157
0158 To ensure that application A receives the same information in the
0159 example (2) as it would receive in example (1) there is need for
0160 some kind of local loopback of the sent CAN frames on the appropriate
0161 node.
0162
0163 The Linux network devices (by default) just can handle the
0164 transmission and reception of media dependent frames. Due to the
0165 arbitration on the CAN bus the transmission of a low prio CAN-ID
0166 may be delayed by the reception of a high prio CAN frame. To
0167 reflect the correct [#f1]_ traffic on the node the loopback of the sent
0168 data has to be performed right after a successful transmission. If
0169 the CAN network interface is not capable of performing the loopback for
0170 some reason the SocketCAN core can do this task as a fallback solution.
0171 See :ref:`socketcan-local-loopback2` for details (recommended).
0172
0173 The loopback functionality is enabled by default to reflect standard
0174 networking behaviour for CAN applications. Due to some requests from
0175 the RT-SocketCAN group the loopback optionally may be disabled for each
0176 separate socket. See sockopts from the CAN RAW sockets in :ref:`socketcan-raw-sockets`.
0177
0178 .. [#f1] you really like to have this when you're running analyser
0179 tools like 'candump' or 'cansniffer' on the (same) node.
0180
0181
0182 .. _socketcan-network-problem-notifications:
0183
0184 Network Problem Notifications
0185 -----------------------------
0186
0187 The use of the CAN bus may lead to several problems on the physical
0188 and media access control layer. Detecting and logging of these lower
0189 layer problems is a vital requirement for CAN users to identify
0190 hardware issues on the physical transceiver layer as well as
0191 arbitration problems and error frames caused by the different
0192 ECUs. The occurrence of detected errors are important for diagnosis
0193 and have to be logged together with the exact timestamp. For this
0194 reason the CAN interface driver can generate so called Error Message
0195 Frames that can optionally be passed to the user application in the
0196 same way as other CAN frames. Whenever an error on the physical layer
0197 or the MAC layer is detected (e.g. by the CAN controller) the driver
0198 creates an appropriate error message frame. Error messages frames can
0199 be requested by the user application using the common CAN filter
0200 mechanisms. Inside this filter definition the (interested) type of
0201 errors may be selected. The reception of error messages is disabled
0202 by default. The format of the CAN error message frame is briefly
0203 described in the Linux header file "include/uapi/linux/can/error.h".
0204
0205
0206 How to use SocketCAN
0207 ====================
0208
0209 Like TCP/IP, you first need to open a socket for communicating over a
0210 CAN network. Since SocketCAN implements a new protocol family, you
0211 need to pass PF_CAN as the first argument to the socket(2) system
0212 call. Currently, there are two CAN protocols to choose from, the raw
0213 socket protocol and the broadcast manager (BCM). So to open a socket,
0214 you would write::
0215
0216 s = socket(PF_CAN, SOCK_RAW, CAN_RAW);
0217
0218 and::
0219
0220 s = socket(PF_CAN, SOCK_DGRAM, CAN_BCM);
0221
0222 respectively. After the successful creation of the socket, you would
0223 normally use the bind(2) system call to bind the socket to a CAN
0224 interface (which is different from TCP/IP due to different addressing
0225 - see :ref:`socketcan-concept`). After binding (CAN_RAW) or connecting (CAN_BCM)
0226 the socket, you can read(2) and write(2) from/to the socket or use
0227 send(2), sendto(2), sendmsg(2) and the recv* counterpart operations
0228 on the socket as usual. There are also CAN specific socket options
0229 described below.
0230
0231 The Classical CAN frame structure (aka CAN 2.0B), the CAN FD frame structure
0232 and the sockaddr structure are defined in include/linux/can.h:
0233
0234 .. code-block:: C
0235
0236 struct can_frame {
0237 canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */
0238 union {
0239 /* CAN frame payload length in byte (0 .. CAN_MAX_DLEN)
0240 * was previously named can_dlc so we need to carry that
0241 * name for legacy support
0242 */
0243 __u8 len;
0244 __u8 can_dlc; /* deprecated */
0245 };
0246 __u8 __pad; /* padding */
0247 __u8 __res0; /* reserved / padding */
0248 __u8 len8_dlc; /* optional DLC for 8 byte payload length (9 .. 15) */
0249 __u8 data[8] __attribute__((aligned(8)));
0250 };
0251
0252 Remark: The len element contains the payload length in bytes and should be
0253 used instead of can_dlc. The deprecated can_dlc was misleadingly named as
0254 it always contained the plain payload length in bytes and not the so called
0255 'data length code' (DLC).
0256
0257 To pass the raw DLC from/to a Classical CAN network device the len8_dlc
0258 element can contain values 9 .. 15 when the len element is 8 (the real
0259 payload length for all DLC values greater or equal to 8).
0260
0261 The alignment of the (linear) payload data[] to a 64bit boundary
0262 allows the user to define their own structs and unions to easily access
0263 the CAN payload. There is no given byteorder on the CAN bus by
0264 default. A read(2) system call on a CAN_RAW socket transfers a
0265 struct can_frame to the user space.
0266
0267 The sockaddr_can structure has an interface index like the
0268 PF_PACKET socket, that also binds to a specific interface:
0269
0270 .. code-block:: C
0271
0272 struct sockaddr_can {
0273 sa_family_t can_family;
0274 int can_ifindex;
0275 union {
0276 /* transport protocol class address info (e.g. ISOTP) */
0277 struct { canid_t rx_id, tx_id; } tp;
0278
0279 /* J1939 address information */
0280 struct {
0281 /* 8 byte name when using dynamic addressing */
0282 __u64 name;
0283
0284 /* pgn:
0285 * 8 bit: PS in PDU2 case, else 0
0286 * 8 bit: PF
0287 * 1 bit: DP
0288 * 1 bit: reserved
0289 */
0290 __u32 pgn;
0291
0292 /* 1 byte address */
0293 __u8 addr;
0294 } j1939;
0295
0296 /* reserved for future CAN protocols address information */
0297 } can_addr;
0298 };
0299
0300 To determine the interface index an appropriate ioctl() has to
0301 be used (example for CAN_RAW sockets without error checking):
0302
0303 .. code-block:: C
0304
0305 int s;
0306 struct sockaddr_can addr;
0307 struct ifreq ifr;
0308
0309 s = socket(PF_CAN, SOCK_RAW, CAN_RAW);
0310
0311 strcpy(ifr.ifr_name, "can0" );
0312 ioctl(s, SIOCGIFINDEX, &ifr);
0313
0314 addr.can_family = AF_CAN;
0315 addr.can_ifindex = ifr.ifr_ifindex;
0316
0317 bind(s, (struct sockaddr *)&addr, sizeof(addr));
0318
0319 (..)
0320
0321 To bind a socket to all(!) CAN interfaces the interface index must
0322 be 0 (zero). In this case the socket receives CAN frames from every
0323 enabled CAN interface. To determine the originating CAN interface
0324 the system call recvfrom(2) may be used instead of read(2). To send
0325 on a socket that is bound to 'any' interface sendto(2) is needed to
0326 specify the outgoing interface.
0327
0328 Reading CAN frames from a bound CAN_RAW socket (see above) consists
0329 of reading a struct can_frame:
0330
0331 .. code-block:: C
0332
0333 struct can_frame frame;
0334
0335 nbytes = read(s, &frame, sizeof(struct can_frame));
0336
0337 if (nbytes < 0) {
0338 perror("can raw socket read");
0339 return 1;
0340 }
0341
0342 /* paranoid check ... */
0343 if (nbytes < sizeof(struct can_frame)) {
0344 fprintf(stderr, "read: incomplete CAN frame\n");
0345 return 1;
0346 }
0347
0348 /* do something with the received CAN frame */
0349
0350 Writing CAN frames can be done similarly, with the write(2) system call::
0351
0352 nbytes = write(s, &frame, sizeof(struct can_frame));
0353
0354 When the CAN interface is bound to 'any' existing CAN interface
0355 (addr.can_ifindex = 0) it is recommended to use recvfrom(2) if the
0356 information about the originating CAN interface is needed:
0357
0358 .. code-block:: C
0359
0360 struct sockaddr_can addr;
0361 struct ifreq ifr;
0362 socklen_t len = sizeof(addr);
0363 struct can_frame frame;
0364
0365 nbytes = recvfrom(s, &frame, sizeof(struct can_frame),
0366 0, (struct sockaddr*)&addr, &len);
0367
0368 /* get interface name of the received CAN frame */
0369 ifr.ifr_ifindex = addr.can_ifindex;
0370 ioctl(s, SIOCGIFNAME, &ifr);
0371 printf("Received a CAN frame from interface %s", ifr.ifr_name);
0372
0373 To write CAN frames on sockets bound to 'any' CAN interface the
0374 outgoing interface has to be defined certainly:
0375
0376 .. code-block:: C
0377
0378 strcpy(ifr.ifr_name, "can0");
0379 ioctl(s, SIOCGIFINDEX, &ifr);
0380 addr.can_ifindex = ifr.ifr_ifindex;
0381 addr.can_family = AF_CAN;
0382
0383 nbytes = sendto(s, &frame, sizeof(struct can_frame),
0384 0, (struct sockaddr*)&addr, sizeof(addr));
0385
0386 An accurate timestamp can be obtained with an ioctl(2) call after reading
0387 a message from the socket:
0388
0389 .. code-block:: C
0390
0391 struct timeval tv;
0392 ioctl(s, SIOCGSTAMP, &tv);
0393
0394 The timestamp has a resolution of one microsecond and is set automatically
0395 at the reception of a CAN frame.
0396
0397 Remark about CAN FD (flexible data rate) support:
0398
0399 Generally the handling of CAN FD is very similar to the formerly described
0400 examples. The new CAN FD capable CAN controllers support two different
0401 bitrates for the arbitration phase and the payload phase of the CAN FD frame
0402 and up to 64 bytes of payload. This extended payload length breaks all the
0403 kernel interfaces (ABI) which heavily rely on the CAN frame with fixed eight
0404 bytes of payload (struct can_frame) like the CAN_RAW socket. Therefore e.g.
0405 the CAN_RAW socket supports a new socket option CAN_RAW_FD_FRAMES that
0406 switches the socket into a mode that allows the handling of CAN FD frames
0407 and Classical CAN frames simultaneously (see :ref:`socketcan-rawfd`).
0408
0409 The struct canfd_frame is defined in include/linux/can.h:
0410
0411 .. code-block:: C
0412
0413 struct canfd_frame {
0414 canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */
0415 __u8 len; /* frame payload length in byte (0 .. 64) */
0416 __u8 flags; /* additional flags for CAN FD */
0417 __u8 __res0; /* reserved / padding */
0418 __u8 __res1; /* reserved / padding */
0419 __u8 data[64] __attribute__((aligned(8)));
0420 };
0421
0422 The struct canfd_frame and the existing struct can_frame have the can_id,
0423 the payload length and the payload data at the same offset inside their
0424 structures. This allows to handle the different structures very similar.
0425 When the content of a struct can_frame is copied into a struct canfd_frame
0426 all structure elements can be used as-is - only the data[] becomes extended.
0427
0428 When introducing the struct canfd_frame it turned out that the data length
0429 code (DLC) of the struct can_frame was used as a length information as the
0430 length and the DLC has a 1:1 mapping in the range of 0 .. 8. To preserve
0431 the easy handling of the length information the canfd_frame.len element
0432 contains a plain length value from 0 .. 64. So both canfd_frame.len and
0433 can_frame.len are equal and contain a length information and no DLC.
0434 For details about the distinction of CAN and CAN FD capable devices and
0435 the mapping to the bus-relevant data length code (DLC), see :ref:`socketcan-can-fd-driver`.
0436
0437 The length of the two CAN(FD) frame structures define the maximum transfer
0438 unit (MTU) of the CAN(FD) network interface and skbuff data length. Two
0439 definitions are specified for CAN specific MTUs in include/linux/can.h:
0440
0441 .. code-block:: C
0442
0443 #define CAN_MTU (sizeof(struct can_frame)) == 16 => Classical CAN frame
0444 #define CANFD_MTU (sizeof(struct canfd_frame)) == 72 => CAN FD frame
0445
0446
0447 .. _socketcan-raw-sockets:
0448
0449 RAW Protocol Sockets with can_filters (SOCK_RAW)
0450 ------------------------------------------------
0451
0452 Using CAN_RAW sockets is extensively comparable to the commonly
0453 known access to CAN character devices. To meet the new possibilities
0454 provided by the multi user SocketCAN approach, some reasonable
0455 defaults are set at RAW socket binding time:
0456
0457 - The filters are set to exactly one filter receiving everything
0458 - The socket only receives valid data frames (=> no error message frames)
0459 - The loopback of sent CAN frames is enabled (see :ref:`socketcan-local-loopback2`)
0460 - The socket does not receive its own sent frames (in loopback mode)
0461
0462 These default settings may be changed before or after binding the socket.
0463 To use the referenced definitions of the socket options for CAN_RAW
0464 sockets, include <linux/can/raw.h>.
0465
0466
0467 .. _socketcan-rawfilter:
0468
0469 RAW socket option CAN_RAW_FILTER
0470 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
0471
0472 The reception of CAN frames using CAN_RAW sockets can be controlled
0473 by defining 0 .. n filters with the CAN_RAW_FILTER socket option.
0474
0475 The CAN filter structure is defined in include/linux/can.h:
0476
0477 .. code-block:: C
0478
0479 struct can_filter {
0480 canid_t can_id;
0481 canid_t can_mask;
0482 };
0483
0484 A filter matches, when:
0485
0486 .. code-block:: C
0487
0488 <received_can_id> & mask == can_id & mask
0489
0490 which is analogous to known CAN controllers hardware filter semantics.
0491 The filter can be inverted in this semantic, when the CAN_INV_FILTER
0492 bit is set in can_id element of the can_filter structure. In
0493 contrast to CAN controller hardware filters the user may set 0 .. n
0494 receive filters for each open socket separately:
0495
0496 .. code-block:: C
0497
0498 struct can_filter rfilter[2];
0499
0500 rfilter[0].can_id = 0x123;
0501 rfilter[0].can_mask = CAN_SFF_MASK;
0502 rfilter[1].can_id = 0x200;
0503 rfilter[1].can_mask = 0x700;
0504
0505 setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter));
0506
0507 To disable the reception of CAN frames on the selected CAN_RAW socket:
0508
0509 .. code-block:: C
0510
0511 setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);
0512
0513 To set the filters to zero filters is quite obsolete as to not read
0514 data causes the raw socket to discard the received CAN frames. But
0515 having this 'send only' use-case we may remove the receive list in the
0516 Kernel to save a little (really a very little!) CPU usage.
0517
0518 CAN Filter Usage Optimisation
0519 .............................
0520
0521 The CAN filters are processed in per-device filter lists at CAN frame
0522 reception time. To reduce the number of checks that need to be performed
0523 while walking through the filter lists the CAN core provides an optimized
0524 filter handling when the filter subscription focusses on a single CAN ID.
0525
0526 For the possible 2048 SFF CAN identifiers the identifier is used as an index
0527 to access the corresponding subscription list without any further checks.
0528 For the 2^29 possible EFF CAN identifiers a 10 bit XOR folding is used as
0529 hash function to retrieve the EFF table index.
0530
0531 To benefit from the optimized filters for single CAN identifiers the
0532 CAN_SFF_MASK or CAN_EFF_MASK have to be set into can_filter.mask together
0533 with set CAN_EFF_FLAG and CAN_RTR_FLAG bits. A set CAN_EFF_FLAG bit in the
0534 can_filter.mask makes clear that it matters whether a SFF or EFF CAN ID is
0535 subscribed. E.g. in the example from above:
0536
0537 .. code-block:: C
0538
0539 rfilter[0].can_id = 0x123;
0540 rfilter[0].can_mask = CAN_SFF_MASK;
0541
0542 both SFF frames with CAN ID 0x123 and EFF frames with 0xXXXXX123 can pass.
0543
0544 To filter for only 0x123 (SFF) and 0x12345678 (EFF) CAN identifiers the
0545 filter has to be defined in this way to benefit from the optimized filters:
0546
0547 .. code-block:: C
0548
0549 struct can_filter rfilter[2];
0550
0551 rfilter[0].can_id = 0x123;
0552 rfilter[0].can_mask = (CAN_EFF_FLAG | CAN_RTR_FLAG | CAN_SFF_MASK);
0553 rfilter[1].can_id = 0x12345678 | CAN_EFF_FLAG;
0554 rfilter[1].can_mask = (CAN_EFF_FLAG | CAN_RTR_FLAG | CAN_EFF_MASK);
0555
0556 setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter));
0557
0558
0559 RAW Socket Option CAN_RAW_ERR_FILTER
0560 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
0561
0562 As described in :ref:`socketcan-network-problem-notifications` the CAN interface driver can generate so
0563 called Error Message Frames that can optionally be passed to the user
0564 application in the same way as other CAN frames. The possible
0565 errors are divided into different error classes that may be filtered
0566 using the appropriate error mask. To register for every possible
0567 error condition CAN_ERR_MASK can be used as value for the error mask.
0568 The values for the error mask are defined in linux/can/error.h:
0569
0570 .. code-block:: C
0571
0572 can_err_mask_t err_mask = ( CAN_ERR_TX_TIMEOUT | CAN_ERR_BUSOFF );
0573
0574 setsockopt(s, SOL_CAN_RAW, CAN_RAW_ERR_FILTER,
0575 &err_mask, sizeof(err_mask));
0576
0577
0578 RAW Socket Option CAN_RAW_LOOPBACK
0579 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
0580
0581 To meet multi user needs the local loopback is enabled by default
0582 (see :ref:`socketcan-local-loopback1` for details). But in some embedded use-cases
0583 (e.g. when only one application uses the CAN bus) this loopback
0584 functionality can be disabled (separately for each socket):
0585
0586 .. code-block:: C
0587
0588 int loopback = 0; /* 0 = disabled, 1 = enabled (default) */
0589
0590 setsockopt(s, SOL_CAN_RAW, CAN_RAW_LOOPBACK, &loopback, sizeof(loopback));
0591
0592
0593 RAW socket option CAN_RAW_RECV_OWN_MSGS
0594 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
0595
0596 When the local loopback is enabled, all the sent CAN frames are
0597 looped back to the open CAN sockets that registered for the CAN
0598 frames' CAN-ID on this given interface to meet the multi user
0599 needs. The reception of the CAN frames on the same socket that was
0600 sending the CAN frame is assumed to be unwanted and therefore
0601 disabled by default. This default behaviour may be changed on
0602 demand:
0603
0604 .. code-block:: C
0605
0606 int recv_own_msgs = 1; /* 0 = disabled (default), 1 = enabled */
0607
0608 setsockopt(s, SOL_CAN_RAW, CAN_RAW_RECV_OWN_MSGS,
0609 &recv_own_msgs, sizeof(recv_own_msgs));
0610
0611 Note that reception of a socket's own CAN frames are subject to the same
0612 filtering as other CAN frames (see :ref:`socketcan-rawfilter`).
0613
0614 .. _socketcan-rawfd:
0615
0616 RAW Socket Option CAN_RAW_FD_FRAMES
0617 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
0618
0619 CAN FD support in CAN_RAW sockets can be enabled with a new socket option
0620 CAN_RAW_FD_FRAMES which is off by default. When the new socket option is
0621 not supported by the CAN_RAW socket (e.g. on older kernels), switching the
0622 CAN_RAW_FD_FRAMES option returns the error -ENOPROTOOPT.
0623
0624 Once CAN_RAW_FD_FRAMES is enabled the application can send both CAN frames
0625 and CAN FD frames. OTOH the application has to handle CAN and CAN FD frames
0626 when reading from the socket:
0627
0628 .. code-block:: C
0629
0630 CAN_RAW_FD_FRAMES enabled: CAN_MTU and CANFD_MTU are allowed
0631 CAN_RAW_FD_FRAMES disabled: only CAN_MTU is allowed (default)
0632
0633 Example:
0634
0635 .. code-block:: C
0636
0637 [ remember: CANFD_MTU == sizeof(struct canfd_frame) ]
0638
0639 struct canfd_frame cfd;
0640
0641 nbytes = read(s, &cfd, CANFD_MTU);
0642
0643 if (nbytes == CANFD_MTU) {
0644 printf("got CAN FD frame with length %d\n", cfd.len);
0645 /* cfd.flags contains valid data */
0646 } else if (nbytes == CAN_MTU) {
0647 printf("got Classical CAN frame with length %d\n", cfd.len);
0648 /* cfd.flags is undefined */
0649 } else {
0650 fprintf(stderr, "read: invalid CAN(FD) frame\n");
0651 return 1;
0652 }
0653
0654 /* the content can be handled independently from the received MTU size */
0655
0656 printf("can_id: %X data length: %d data: ", cfd.can_id, cfd.len);
0657 for (i = 0; i < cfd.len; i++)
0658 printf("%02X ", cfd.data[i]);
0659
0660 When reading with size CANFD_MTU only returns CAN_MTU bytes that have
0661 been received from the socket a Classical CAN frame has been read into the
0662 provided CAN FD structure. Note that the canfd_frame.flags data field is
0663 not specified in the struct can_frame and therefore it is only valid in
0664 CANFD_MTU sized CAN FD frames.
0665
0666 Implementation hint for new CAN applications:
0667
0668 To build a CAN FD aware application use struct canfd_frame as basic CAN
0669 data structure for CAN_RAW based applications. When the application is
0670 executed on an older Linux kernel and switching the CAN_RAW_FD_FRAMES
0671 socket option returns an error: No problem. You'll get Classical CAN frames
0672 or CAN FD frames and can process them the same way.
0673
0674 When sending to CAN devices make sure that the device is capable to handle
0675 CAN FD frames by checking if the device maximum transfer unit is CANFD_MTU.
0676 The CAN device MTU can be retrieved e.g. with a SIOCGIFMTU ioctl() syscall.
0677
0678
0679 RAW socket option CAN_RAW_JOIN_FILTERS
0680 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
0681
0682 The CAN_RAW socket can set multiple CAN identifier specific filters that
0683 lead to multiple filters in the af_can.c filter processing. These filters
0684 are indenpendent from each other which leads to logical OR'ed filters when
0685 applied (see :ref:`socketcan-rawfilter`).
0686
0687 This socket option joines the given CAN filters in the way that only CAN
0688 frames are passed to user space that matched *all* given CAN filters. The
0689 semantic for the applied filters is therefore changed to a logical AND.
0690
0691 This is useful especially when the filterset is a combination of filters
0692 where the CAN_INV_FILTER flag is set in order to notch single CAN IDs or
0693 CAN ID ranges from the incoming traffic.
0694
0695
0696 RAW Socket Returned Message Flags
0697 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
0698
0699 When using recvmsg() call, the msg->msg_flags may contain following flags:
0700
0701 MSG_DONTROUTE:
0702 set when the received frame was created on the local host.
0703
0704 MSG_CONFIRM:
0705 set when the frame was sent via the socket it is received on.
0706 This flag can be interpreted as a 'transmission confirmation' when the
0707 CAN driver supports the echo of frames on driver level, see
0708 :ref:`socketcan-local-loopback1` and :ref:`socketcan-local-loopback2`.
0709 In order to receive such messages, CAN_RAW_RECV_OWN_MSGS must be set.
0710
0711
0712 Broadcast Manager Protocol Sockets (SOCK_DGRAM)
0713 -----------------------------------------------
0714
0715 The Broadcast Manager protocol provides a command based configuration
0716 interface to filter and send (e.g. cyclic) CAN messages in kernel space.
0717
0718 Receive filters can be used to down sample frequent messages; detect events
0719 such as message contents changes, packet length changes, and do time-out
0720 monitoring of received messages.
0721
0722 Periodic transmission tasks of CAN frames or a sequence of CAN frames can be
0723 created and modified at runtime; both the message content and the two
0724 possible transmit intervals can be altered.
0725
0726 A BCM socket is not intended for sending individual CAN frames using the
0727 struct can_frame as known from the CAN_RAW socket. Instead a special BCM
0728 configuration message is defined. The basic BCM configuration message used
0729 to communicate with the broadcast manager and the available operations are
0730 defined in the linux/can/bcm.h include. The BCM message consists of a
0731 message header with a command ('opcode') followed by zero or more CAN frames.
0732 The broadcast manager sends responses to user space in the same form:
0733
0734 .. code-block:: C
0735
0736 struct bcm_msg_head {
0737 __u32 opcode; /* command */
0738 __u32 flags; /* special flags */
0739 __u32 count; /* run 'count' times with ival1 */
0740 struct timeval ival1, ival2; /* count and subsequent interval */
0741 canid_t can_id; /* unique can_id for task */
0742 __u32 nframes; /* number of can_frames following */
0743 struct can_frame frames[0];
0744 };
0745
0746 The aligned payload 'frames' uses the same basic CAN frame structure defined
0747 at the beginning of :ref:`socketcan-rawfd` and in the include/linux/can.h include. All
0748 messages to the broadcast manager from user space have this structure.
0749
0750 Note a CAN_BCM socket must be connected instead of bound after socket
0751 creation (example without error checking):
0752
0753 .. code-block:: C
0754
0755 int s;
0756 struct sockaddr_can addr;
0757 struct ifreq ifr;
0758
0759 s = socket(PF_CAN, SOCK_DGRAM, CAN_BCM);
0760
0761 strcpy(ifr.ifr_name, "can0");
0762 ioctl(s, SIOCGIFINDEX, &ifr);
0763
0764 addr.can_family = AF_CAN;
0765 addr.can_ifindex = ifr.ifr_ifindex;
0766
0767 connect(s, (struct sockaddr *)&addr, sizeof(addr));
0768
0769 (..)
0770
0771 The broadcast manager socket is able to handle any number of in flight
0772 transmissions or receive filters concurrently. The different RX/TX jobs are
0773 distinguished by the unique can_id in each BCM message. However additional
0774 CAN_BCM sockets are recommended to communicate on multiple CAN interfaces.
0775 When the broadcast manager socket is bound to 'any' CAN interface (=> the
0776 interface index is set to zero) the configured receive filters apply to any
0777 CAN interface unless the sendto() syscall is used to overrule the 'any' CAN
0778 interface index. When using recvfrom() instead of read() to retrieve BCM
0779 socket messages the originating CAN interface is provided in can_ifindex.
0780
0781
0782 Broadcast Manager Operations
0783 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
0784
0785 The opcode defines the operation for the broadcast manager to carry out,
0786 or details the broadcast managers response to several events, including
0787 user requests.
0788
0789 Transmit Operations (user space to broadcast manager):
0790
0791 TX_SETUP:
0792 Create (cyclic) transmission task.
0793
0794 TX_DELETE:
0795 Remove (cyclic) transmission task, requires only can_id.
0796
0797 TX_READ:
0798 Read properties of (cyclic) transmission task for can_id.
0799
0800 TX_SEND:
0801 Send one CAN frame.
0802
0803 Transmit Responses (broadcast manager to user space):
0804
0805 TX_STATUS:
0806 Reply to TX_READ request (transmission task configuration).
0807
0808 TX_EXPIRED:
0809 Notification when counter finishes sending at initial interval
0810 'ival1'. Requires the TX_COUNTEVT flag to be set at TX_SETUP.
0811
0812 Receive Operations (user space to broadcast manager):
0813
0814 RX_SETUP:
0815 Create RX content filter subscription.
0816
0817 RX_DELETE:
0818 Remove RX content filter subscription, requires only can_id.
0819
0820 RX_READ:
0821 Read properties of RX content filter subscription for can_id.
0822
0823 Receive Responses (broadcast manager to user space):
0824
0825 RX_STATUS:
0826 Reply to RX_READ request (filter task configuration).
0827
0828 RX_TIMEOUT:
0829 Cyclic message is detected to be absent (timer ival1 expired).
0830
0831 RX_CHANGED:
0832 BCM message with updated CAN frame (detected content change).
0833 Sent on first message received or on receipt of revised CAN messages.
0834
0835
0836 Broadcast Manager Message Flags
0837 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
0838
0839 When sending a message to the broadcast manager the 'flags' element may
0840 contain the following flag definitions which influence the behaviour:
0841
0842 SETTIMER:
0843 Set the values of ival1, ival2 and count
0844
0845 STARTTIMER:
0846 Start the timer with the actual values of ival1, ival2
0847 and count. Starting the timer leads simultaneously to emit a CAN frame.
0848
0849 TX_COUNTEVT:
0850 Create the message TX_EXPIRED when count expires
0851
0852 TX_ANNOUNCE:
0853 A change of data by the process is emitted immediately.
0854
0855 TX_CP_CAN_ID:
0856 Copies the can_id from the message header to each
0857 subsequent frame in frames. This is intended as usage simplification. For
0858 TX tasks the unique can_id from the message header may differ from the
0859 can_id(s) stored for transmission in the subsequent struct can_frame(s).
0860
0861 RX_FILTER_ID:
0862 Filter by can_id alone, no frames required (nframes=0).
0863
0864 RX_CHECK_DLC:
0865 A change of the DLC leads to an RX_CHANGED.
0866
0867 RX_NO_AUTOTIMER:
0868 Prevent automatically starting the timeout monitor.
0869
0870 RX_ANNOUNCE_RESUME:
0871 If passed at RX_SETUP and a receive timeout occurred, a
0872 RX_CHANGED message will be generated when the (cyclic) receive restarts.
0873
0874 TX_RESET_MULTI_IDX:
0875 Reset the index for the multiple frame transmission.
0876
0877 RX_RTR_FRAME:
0878 Send reply for RTR-request (placed in op->frames[0]).
0879
0880 CAN_FD_FRAME:
0881 The CAN frames following the bcm_msg_head are struct canfd_frame's
0882
0883 Broadcast Manager Transmission Timers
0884 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
0885
0886 Periodic transmission configurations may use up to two interval timers.
0887 In this case the BCM sends a number of messages ('count') at an interval
0888 'ival1', then continuing to send at another given interval 'ival2'. When
0889 only one timer is needed 'count' is set to zero and only 'ival2' is used.
0890 When SET_TIMER and START_TIMER flag were set the timers are activated.
0891 The timer values can be altered at runtime when only SET_TIMER is set.
0892
0893
0894 Broadcast Manager message sequence transmission
0895 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
0896
0897 Up to 256 CAN frames can be transmitted in a sequence in the case of a cyclic
0898 TX task configuration. The number of CAN frames is provided in the 'nframes'
0899 element of the BCM message head. The defined number of CAN frames are added
0900 as array to the TX_SETUP BCM configuration message:
0901
0902 .. code-block:: C
0903
0904 /* create a struct to set up a sequence of four CAN frames */
0905 struct {
0906 struct bcm_msg_head msg_head;
0907 struct can_frame frame[4];
0908 } mytxmsg;
0909
0910 (..)
0911 mytxmsg.msg_head.nframes = 4;
0912 (..)
0913
0914 write(s, &mytxmsg, sizeof(mytxmsg));
0915
0916 With every transmission the index in the array of CAN frames is increased
0917 and set to zero at index overflow.
0918
0919
0920 Broadcast Manager Receive Filter Timers
0921 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
0922
0923 The timer values ival1 or ival2 may be set to non-zero values at RX_SETUP.
0924 When the SET_TIMER flag is set the timers are enabled:
0925
0926 ival1:
0927 Send RX_TIMEOUT when a received message is not received again within
0928 the given time. When START_TIMER is set at RX_SETUP the timeout detection
0929 is activated directly - even without a former CAN frame reception.
0930
0931 ival2:
0932 Throttle the received message rate down to the value of ival2. This
0933 is useful to reduce messages for the application when the signal inside the
0934 CAN frame is stateless as state changes within the ival2 periode may get
0935 lost.
0936
0937 Broadcast Manager Multiplex Message Receive Filter
0938 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
0939
0940 To filter for content changes in multiplex message sequences an array of more
0941 than one CAN frames can be passed in a RX_SETUP configuration message. The
0942 data bytes of the first CAN frame contain the mask of relevant bits that
0943 have to match in the subsequent CAN frames with the received CAN frame.
0944 If one of the subsequent CAN frames is matching the bits in that frame data
0945 mark the relevant content to be compared with the previous received content.
0946 Up to 257 CAN frames (multiplex filter bit mask CAN frame plus 256 CAN
0947 filters) can be added as array to the TX_SETUP BCM configuration message:
0948
0949 .. code-block:: C
0950
0951 /* usually used to clear CAN frame data[] - beware of endian problems! */
0952 #define U64_DATA(p) (*(unsigned long long*)(p)->data)
0953
0954 struct {
0955 struct bcm_msg_head msg_head;
0956 struct can_frame frame[5];
0957 } msg;
0958
0959 msg.msg_head.opcode = RX_SETUP;
0960 msg.msg_head.can_id = 0x42;
0961 msg.msg_head.flags = 0;
0962 msg.msg_head.nframes = 5;
0963 U64_DATA(&msg.frame[0]) = 0xFF00000000000000ULL; /* MUX mask */
0964 U64_DATA(&msg.frame[1]) = 0x01000000000000FFULL; /* data mask (MUX 0x01) */
0965 U64_DATA(&msg.frame[2]) = 0x0200FFFF000000FFULL; /* data mask (MUX 0x02) */
0966 U64_DATA(&msg.frame[3]) = 0x330000FFFFFF0003ULL; /* data mask (MUX 0x33) */
0967 U64_DATA(&msg.frame[4]) = 0x4F07FC0FF0000000ULL; /* data mask (MUX 0x4F) */
0968
0969 write(s, &msg, sizeof(msg));
0970
0971
0972 Broadcast Manager CAN FD Support
0973 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
0974
0975 The programming API of the CAN_BCM depends on struct can_frame which is
0976 given as array directly behind the bcm_msg_head structure. To follow this
0977 schema for the CAN FD frames a new flag 'CAN_FD_FRAME' in the bcm_msg_head
0978 flags indicates that the concatenated CAN frame structures behind the
0979 bcm_msg_head are defined as struct canfd_frame:
0980
0981 .. code-block:: C
0982
0983 struct {
0984 struct bcm_msg_head msg_head;
0985 struct canfd_frame frame[5];
0986 } msg;
0987
0988 msg.msg_head.opcode = RX_SETUP;
0989 msg.msg_head.can_id = 0x42;
0990 msg.msg_head.flags = CAN_FD_FRAME;
0991 msg.msg_head.nframes = 5;
0992 (..)
0993
0994 When using CAN FD frames for multiplex filtering the MUX mask is still
0995 expected in the first 64 bit of the struct canfd_frame data section.
0996
0997
0998 Connected Transport Protocols (SOCK_SEQPACKET)
0999 ----------------------------------------------
1000
1001 (to be written)
1002
1003
1004 Unconnected Transport Protocols (SOCK_DGRAM)
1005 --------------------------------------------
1006
1007 (to be written)
1008
1009
1010 .. _socketcan-core-module:
1011
1012 SocketCAN Core Module
1013 =====================
1014
1015 The SocketCAN core module implements the protocol family
1016 PF_CAN. CAN protocol modules are loaded by the core module at
1017 runtime. The core module provides an interface for CAN protocol
1018 modules to subscribe needed CAN IDs (see :ref:`socketcan-receive-lists`).
1019
1020
1021 can.ko Module Params
1022 --------------------
1023
1024 - **stats_timer**:
1025 To calculate the SocketCAN core statistics
1026 (e.g. current/maximum frames per second) this 1 second timer is
1027 invoked at can.ko module start time by default. This timer can be
1028 disabled by using stattimer=0 on the module commandline.
1029
1030 - **debug**:
1031 (removed since SocketCAN SVN r546)
1032
1033
1034 procfs content
1035 --------------
1036
1037 As described in :ref:`socketcan-receive-lists` the SocketCAN core uses several filter
1038 lists to deliver received CAN frames to CAN protocol modules. These
1039 receive lists, their filters and the count of filter matches can be
1040 checked in the appropriate receive list. All entries contain the
1041 device and a protocol module identifier::
1042
1043 foo@bar:~$ cat /proc/net/can/rcvlist_all
1044
1045 receive list 'rx_all':
1046 (vcan3: no entry)
1047 (vcan2: no entry)
1048 (vcan1: no entry)
1049 device can_id can_mask function userdata matches ident
1050 vcan0 000 00000000 f88e6370 f6c6f400 0 raw
1051 (any: no entry)
1052
1053 In this example an application requests any CAN traffic from vcan0::
1054
1055 rcvlist_all - list for unfiltered entries (no filter operations)
1056 rcvlist_eff - list for single extended frame (EFF) entries
1057 rcvlist_err - list for error message frames masks
1058 rcvlist_fil - list for mask/value filters
1059 rcvlist_inv - list for mask/value filters (inverse semantic)
1060 rcvlist_sff - list for single standard frame (SFF) entries
1061
1062 Additional procfs files in /proc/net/can::
1063
1064 stats - SocketCAN core statistics (rx/tx frames, match ratios, ...)
1065 reset_stats - manual statistic reset
1066 version - prints SocketCAN core and ABI version (removed in Linux 5.10)
1067
1068
1069 Writing Own CAN Protocol Modules
1070 --------------------------------
1071
1072 To implement a new protocol in the protocol family PF_CAN a new
1073 protocol has to be defined in include/linux/can.h .
1074 The prototypes and definitions to use the SocketCAN core can be
1075 accessed by including include/linux/can/core.h .
1076 In addition to functions that register the CAN protocol and the
1077 CAN device notifier chain there are functions to subscribe CAN
1078 frames received by CAN interfaces and to send CAN frames::
1079
1080 can_rx_register - subscribe CAN frames from a specific interface
1081 can_rx_unregister - unsubscribe CAN frames from a specific interface
1082 can_send - transmit a CAN frame (optional with local loopback)
1083
1084 For details see the kerneldoc documentation in net/can/af_can.c or
1085 the source code of net/can/raw.c or net/can/bcm.c .
1086
1087
1088 CAN Network Drivers
1089 ===================
1090
1091 Writing a CAN network device driver is much easier than writing a
1092 CAN character device driver. Similar to other known network device
1093 drivers you mainly have to deal with:
1094
1095 - TX: Put the CAN frame from the socket buffer to the CAN controller.
1096 - RX: Put the CAN frame from the CAN controller to the socket buffer.
1097
1098 See e.g. at Documentation/networking/netdevices.rst . The differences
1099 for writing CAN network device driver are described below:
1100
1101
1102 General Settings
1103 ----------------
1104
1105 .. code-block:: C
1106
1107 dev->type = ARPHRD_CAN; /* the netdevice hardware type */
1108 dev->flags = IFF_NOARP; /* CAN has no arp */
1109
1110 dev->mtu = CAN_MTU; /* sizeof(struct can_frame) -> Classical CAN interface */
1111
1112 or alternative, when the controller supports CAN with flexible data rate:
1113 dev->mtu = CANFD_MTU; /* sizeof(struct canfd_frame) -> CAN FD interface */
1114
1115 The struct can_frame or struct canfd_frame is the payload of each socket
1116 buffer (skbuff) in the protocol family PF_CAN.
1117
1118
1119 .. _socketcan-local-loopback2:
1120
1121 Local Loopback of Sent Frames
1122 -----------------------------
1123
1124 As described in :ref:`socketcan-local-loopback1` the CAN network device driver should
1125 support a local loopback functionality similar to the local echo
1126 e.g. of tty devices. In this case the driver flag IFF_ECHO has to be
1127 set to prevent the PF_CAN core from locally echoing sent frames
1128 (aka loopback) as fallback solution::
1129
1130 dev->flags = (IFF_NOARP | IFF_ECHO);
1131
1132
1133 CAN Controller Hardware Filters
1134 -------------------------------
1135
1136 To reduce the interrupt load on deep embedded systems some CAN
1137 controllers support the filtering of CAN IDs or ranges of CAN IDs.
1138 These hardware filter capabilities vary from controller to
1139 controller and have to be identified as not feasible in a multi-user
1140 networking approach. The use of the very controller specific
1141 hardware filters could make sense in a very dedicated use-case, as a
1142 filter on driver level would affect all users in the multi-user
1143 system. The high efficient filter sets inside the PF_CAN core allow
1144 to set different multiple filters for each socket separately.
1145 Therefore the use of hardware filters goes to the category 'handmade
1146 tuning on deep embedded systems'. The author is running a MPC603e
1147 @133MHz with four SJA1000 CAN controllers from 2002 under heavy bus
1148 load without any problems ...
1149
1150
1151 The Virtual CAN Driver (vcan)
1152 -----------------------------
1153
1154 Similar to the network loopback devices, vcan offers a virtual local
1155 CAN interface. A full qualified address on CAN consists of
1156
1157 - a unique CAN Identifier (CAN ID)
1158 - the CAN bus this CAN ID is transmitted on (e.g. can0)
1159
1160 so in common use cases more than one virtual CAN interface is needed.
1161
1162 The virtual CAN interfaces allow the transmission and reception of CAN
1163 frames without real CAN controller hardware. Virtual CAN network
1164 devices are usually named 'vcanX', like vcan0 vcan1 vcan2 ...
1165 When compiled as a module the virtual CAN driver module is called vcan.ko
1166
1167 Since Linux Kernel version 2.6.24 the vcan driver supports the Kernel
1168 netlink interface to create vcan network devices. The creation and
1169 removal of vcan network devices can be managed with the ip(8) tool::
1170
1171 - Create a virtual CAN network interface:
1172 $ ip link add type vcan
1173
1174 - Create a virtual CAN network interface with a specific name 'vcan42':
1175 $ ip link add dev vcan42 type vcan
1176
1177 - Remove a (virtual CAN) network interface 'vcan42':
1178 $ ip link del vcan42
1179
1180
1181 The CAN Network Device Driver Interface
1182 ---------------------------------------
1183
1184 The CAN network device driver interface provides a generic interface
1185 to setup, configure and monitor CAN network devices. The user can then
1186 configure the CAN device, like setting the bit-timing parameters, via
1187 the netlink interface using the program "ip" from the "IPROUTE2"
1188 utility suite. The following chapter describes briefly how to use it.
1189 Furthermore, the interface uses a common data structure and exports a
1190 set of common functions, which all real CAN network device drivers
1191 should use. Please have a look to the SJA1000 or MSCAN driver to
1192 understand how to use them. The name of the module is can-dev.ko.
1193
1194
1195 Netlink interface to set/get devices properties
1196 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1197
1198 The CAN device must be configured via netlink interface. The supported
1199 netlink message types are defined and briefly described in
1200 "include/linux/can/netlink.h". CAN link support for the program "ip"
1201 of the IPROUTE2 utility suite is available and it can be used as shown
1202 below:
1203
1204 Setting CAN device properties::
1205
1206 $ ip link set can0 type can help
1207 Usage: ip link set DEVICE type can
1208 [ bitrate BITRATE [ sample-point SAMPLE-POINT] ] |
1209 [ tq TQ prop-seg PROP_SEG phase-seg1 PHASE-SEG1
1210 phase-seg2 PHASE-SEG2 [ sjw SJW ] ]
1211
1212 [ dbitrate BITRATE [ dsample-point SAMPLE-POINT] ] |
1213 [ dtq TQ dprop-seg PROP_SEG dphase-seg1 PHASE-SEG1
1214 dphase-seg2 PHASE-SEG2 [ dsjw SJW ] ]
1215
1216 [ loopback { on | off } ]
1217 [ listen-only { on | off } ]
1218 [ triple-sampling { on | off } ]
1219 [ one-shot { on | off } ]
1220 [ berr-reporting { on | off } ]
1221 [ fd { on | off } ]
1222 [ fd-non-iso { on | off } ]
1223 [ presume-ack { on | off } ]
1224 [ cc-len8-dlc { on | off } ]
1225
1226 [ restart-ms TIME-MS ]
1227 [ restart ]
1228
1229 Where: BITRATE := { 1..1000000 }
1230 SAMPLE-POINT := { 0.000..0.999 }
1231 TQ := { NUMBER }
1232 PROP-SEG := { 1..8 }
1233 PHASE-SEG1 := { 1..8 }
1234 PHASE-SEG2 := { 1..8 }
1235 SJW := { 1..4 }
1236 RESTART-MS := { 0 | NUMBER }
1237
1238 Display CAN device details and statistics::
1239
1240 $ ip -details -statistics link show can0
1241 2: can0: <NOARP,UP,LOWER_UP,ECHO> mtu 16 qdisc pfifo_fast state UP qlen 10
1242 link/can
1243 can <TRIPLE-SAMPLING> state ERROR-ACTIVE restart-ms 100
1244 bitrate 125000 sample_point 0.875
1245 tq 125 prop-seg 6 phase-seg1 7 phase-seg2 2 sjw 1
1246 sja1000: tseg1 1..16 tseg2 1..8 sjw 1..4 brp 1..64 brp-inc 1
1247 clock 8000000
1248 re-started bus-errors arbit-lost error-warn error-pass bus-off
1249 41 17457 0 41 42 41
1250 RX: bytes packets errors dropped overrun mcast
1251 140859 17608 17457 0 0 0
1252 TX: bytes packets errors dropped carrier collsns
1253 861 112 0 41 0 0
1254
1255 More info to the above output:
1256
1257 "<TRIPLE-SAMPLING>"
1258 Shows the list of selected CAN controller modes: LOOPBACK,
1259 LISTEN-ONLY, or TRIPLE-SAMPLING.
1260
1261 "state ERROR-ACTIVE"
1262 The current state of the CAN controller: "ERROR-ACTIVE",
1263 "ERROR-WARNING", "ERROR-PASSIVE", "BUS-OFF" or "STOPPED"
1264
1265 "restart-ms 100"
1266 Automatic restart delay time. If set to a non-zero value, a
1267 restart of the CAN controller will be triggered automatically
1268 in case of a bus-off condition after the specified delay time
1269 in milliseconds. By default it's off.
1270
1271 "bitrate 125000 sample-point 0.875"
1272 Shows the real bit-rate in bits/sec and the sample-point in the
1273 range 0.000..0.999. If the calculation of bit-timing parameters
1274 is enabled in the kernel (CONFIG_CAN_CALC_BITTIMING=y), the
1275 bit-timing can be defined by setting the "bitrate" argument.
1276 Optionally the "sample-point" can be specified. By default it's
1277 0.000 assuming CIA-recommended sample-points.
1278
1279 "tq 125 prop-seg 6 phase-seg1 7 phase-seg2 2 sjw 1"
1280 Shows the time quanta in ns, propagation segment, phase buffer
1281 segment 1 and 2 and the synchronisation jump width in units of
1282 tq. They allow to define the CAN bit-timing in a hardware
1283 independent format as proposed by the Bosch CAN 2.0 spec (see
1284 chapter 8 of http://www.semiconductors.bosch.de/pdf/can2spec.pdf).
1285
1286 "sja1000: tseg1 1..16 tseg2 1..8 sjw 1..4 brp 1..64 brp-inc 1 clock 8000000"
1287 Shows the bit-timing constants of the CAN controller, here the
1288 "sja1000". The minimum and maximum values of the time segment 1
1289 and 2, the synchronisation jump width in units of tq, the
1290 bitrate pre-scaler and the CAN system clock frequency in Hz.
1291 These constants could be used for user-defined (non-standard)
1292 bit-timing calculation algorithms in user-space.
1293
1294 "re-started bus-errors arbit-lost error-warn error-pass bus-off"
1295 Shows the number of restarts, bus and arbitration lost errors,
1296 and the state changes to the error-warning, error-passive and
1297 bus-off state. RX overrun errors are listed in the "overrun"
1298 field of the standard network statistics.
1299
1300 Setting the CAN Bit-Timing
1301 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1302
1303 The CAN bit-timing parameters can always be defined in a hardware
1304 independent format as proposed in the Bosch CAN 2.0 specification
1305 specifying the arguments "tq", "prop_seg", "phase_seg1", "phase_seg2"
1306 and "sjw"::
1307
1308 $ ip link set canX type can tq 125 prop-seg 6 \
1309 phase-seg1 7 phase-seg2 2 sjw 1
1310
1311 If the kernel option CONFIG_CAN_CALC_BITTIMING is enabled, CIA
1312 recommended CAN bit-timing parameters will be calculated if the bit-
1313 rate is specified with the argument "bitrate"::
1314
1315 $ ip link set canX type can bitrate 125000
1316
1317 Note that this works fine for the most common CAN controllers with
1318 standard bit-rates but may *fail* for exotic bit-rates or CAN system
1319 clock frequencies. Disabling CONFIG_CAN_CALC_BITTIMING saves some
1320 space and allows user-space tools to solely determine and set the
1321 bit-timing parameters. The CAN controller specific bit-timing
1322 constants can be used for that purpose. They are listed by the
1323 following command::
1324
1325 $ ip -details link show can0
1326 ...
1327 sja1000: clock 8000000 tseg1 1..16 tseg2 1..8 sjw 1..4 brp 1..64 brp-inc 1
1328
1329
1330 Starting and Stopping the CAN Network Device
1331 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1332
1333 A CAN network device is started or stopped as usual with the command
1334 "ifconfig canX up/down" or "ip link set canX up/down". Be aware that
1335 you *must* define proper bit-timing parameters for real CAN devices
1336 before you can start it to avoid error-prone default settings::
1337
1338 $ ip link set canX up type can bitrate 125000
1339
1340 A device may enter the "bus-off" state if too many errors occurred on
1341 the CAN bus. Then no more messages are received or sent. An automatic
1342 bus-off recovery can be enabled by setting the "restart-ms" to a
1343 non-zero value, e.g.::
1344
1345 $ ip link set canX type can restart-ms 100
1346
1347 Alternatively, the application may realize the "bus-off" condition
1348 by monitoring CAN error message frames and do a restart when
1349 appropriate with the command::
1350
1351 $ ip link set canX type can restart
1352
1353 Note that a restart will also create a CAN error message frame (see
1354 also :ref:`socketcan-network-problem-notifications`).
1355
1356
1357 .. _socketcan-can-fd-driver:
1358
1359 CAN FD (Flexible Data Rate) Driver Support
1360 ------------------------------------------
1361
1362 CAN FD capable CAN controllers support two different bitrates for the
1363 arbitration phase and the payload phase of the CAN FD frame. Therefore a
1364 second bit timing has to be specified in order to enable the CAN FD bitrate.
1365
1366 Additionally CAN FD capable CAN controllers support up to 64 bytes of
1367 payload. The representation of this length in can_frame.len and
1368 canfd_frame.len for userspace applications and inside the Linux network
1369 layer is a plain value from 0 .. 64 instead of the CAN 'data length code'.
1370 The data length code was a 1:1 mapping to the payload length in the Classical
1371 CAN frames anyway. The payload length to the bus-relevant DLC mapping is
1372 only performed inside the CAN drivers, preferably with the helper
1373 functions can_fd_dlc2len() and can_fd_len2dlc().
1374
1375 The CAN netdevice driver capabilities can be distinguished by the network
1376 devices maximum transfer unit (MTU)::
1377
1378 MTU = 16 (CAN_MTU) => sizeof(struct can_frame) => Classical CAN device
1379 MTU = 72 (CANFD_MTU) => sizeof(struct canfd_frame) => CAN FD capable device
1380
1381 The CAN device MTU can be retrieved e.g. with a SIOCGIFMTU ioctl() syscall.
1382 N.B. CAN FD capable devices can also handle and send Classical CAN frames.
1383
1384 When configuring CAN FD capable CAN controllers an additional 'data' bitrate
1385 has to be set. This bitrate for the data phase of the CAN FD frame has to be
1386 at least the bitrate which was configured for the arbitration phase. This
1387 second bitrate is specified analogue to the first bitrate but the bitrate
1388 setting keywords for the 'data' bitrate start with 'd' e.g. dbitrate,
1389 dsample-point, dsjw or dtq and similar settings. When a data bitrate is set
1390 within the configuration process the controller option "fd on" can be
1391 specified to enable the CAN FD mode in the CAN controller. This controller
1392 option also switches the device MTU to 72 (CANFD_MTU).
1393
1394 The first CAN FD specification presented as whitepaper at the International
1395 CAN Conference 2012 needed to be improved for data integrity reasons.
1396 Therefore two CAN FD implementations have to be distinguished today:
1397
1398 - ISO compliant: The ISO 11898-1:2015 CAN FD implementation (default)
1399 - non-ISO compliant: The CAN FD implementation following the 2012 whitepaper
1400
1401 Finally there are three types of CAN FD controllers:
1402
1403 1. ISO compliant (fixed)
1404 2. non-ISO compliant (fixed, like the M_CAN IP core v3.0.1 in m_can.c)
1405 3. ISO/non-ISO CAN FD controllers (switchable, like the PEAK PCAN-USB FD)
1406
1407 The current ISO/non-ISO mode is announced by the CAN controller driver via
1408 netlink and displayed by the 'ip' tool (controller option FD-NON-ISO).
1409 The ISO/non-ISO-mode can be altered by setting 'fd-non-iso {on|off}' for
1410 switchable CAN FD controllers only.
1411
1412 Example configuring 500 kbit/s arbitration bitrate and 4 Mbit/s data bitrate::
1413
1414 $ ip link set can0 up type can bitrate 500000 sample-point 0.75 \
1415 dbitrate 4000000 dsample-point 0.8 fd on
1416 $ ip -details link show can0
1417 5: can0: <NOARP,UP,LOWER_UP,ECHO> mtu 72 qdisc pfifo_fast state UNKNOWN \
1418 mode DEFAULT group default qlen 10
1419 link/can promiscuity 0
1420 can <FD> state ERROR-ACTIVE (berr-counter tx 0 rx 0) restart-ms 0
1421 bitrate 500000 sample-point 0.750
1422 tq 50 prop-seg 14 phase-seg1 15 phase-seg2 10 sjw 1
1423 pcan_usb_pro_fd: tseg1 1..64 tseg2 1..16 sjw 1..16 brp 1..1024 \
1424 brp-inc 1
1425 dbitrate 4000000 dsample-point 0.800
1426 dtq 12 dprop-seg 7 dphase-seg1 8 dphase-seg2 4 dsjw 1
1427 pcan_usb_pro_fd: dtseg1 1..16 dtseg2 1..8 dsjw 1..4 dbrp 1..1024 \
1428 dbrp-inc 1
1429 clock 80000000
1430
1431 Example when 'fd-non-iso on' is added on this switchable CAN FD adapter::
1432
1433 can <FD,FD-NON-ISO> state ERROR-ACTIVE (berr-counter tx 0 rx 0) restart-ms 0
1434
1435
1436 Supported CAN Hardware
1437 ----------------------
1438
1439 Please check the "Kconfig" file in "drivers/net/can" to get an actual
1440 list of the support CAN hardware. On the SocketCAN project website
1441 (see :ref:`socketcan-resources`) there might be further drivers available, also for
1442 older kernel versions.
1443
1444
1445 .. _socketcan-resources:
1446
1447 SocketCAN Resources
1448 ===================
1449
1450 The Linux CAN / SocketCAN project resources (project site / mailing list)
1451 are referenced in the MAINTAINERS file in the Linux source tree.
1452 Search for CAN NETWORK [LAYERS|DRIVERS].
1453
1454 Credits
1455 =======
1456
1457 - Oliver Hartkopp (PF_CAN core, filters, drivers, bcm, SJA1000 driver)
1458 - Urs Thuermann (PF_CAN core, kernel integration, socket interfaces, raw, vcan)
1459 - Jan Kizka (RT-SocketCAN core, Socket-API reconciliation)
1460 - Wolfgang Grandegger (RT-SocketCAN core & drivers, Raw Socket-API reviews, CAN device driver interface, MSCAN driver)
1461 - Robert Schwebel (design reviews, PTXdist integration)
1462 - Marc Kleine-Budde (design reviews, Kernel 2.6 cleanups, drivers)
1463 - Benedikt Spranger (reviews)
1464 - Thomas Gleixner (LKML reviews, coding style, posting hints)
1465 - Andrey Volkov (kernel subtree structure, ioctls, MSCAN driver)
1466 - Matthias Brukner (first SJA1000 CAN netdevice implementation Q2/2003)
1467 - Klaus Hitschler (PEAK driver integration)
1468 - Uwe Koppe (CAN netdevices with PF_PACKET approach)
1469 - Michael Schulze (driver layer loopback requirement, RT CAN drivers review)
1470 - Pavel Pisa (Bit-timing calculation)
1471 - Sascha Hauer (SJA1000 platform driver)
1472 - Sebastian Haas (SJA1000 EMS PCI driver)
1473 - Markus Plessing (SJA1000 EMS PCI driver)
1474 - Per Dalen (SJA1000 Kvaser PCI driver)
1475 - Sam Ravnborg (reviews, coding style, kbuild help)