1511 lines · plain
1===================================2SocketCAN - Controller Area Network3===================================4 5Overview / What is SocketCAN6============================7 8The socketcan package is an implementation of CAN protocols9(Controller Area Network) for Linux. CAN is a networking technology10which has widespread use in automation, embedded devices, and11automotive fields. While there have been other CAN implementations12for Linux based on character devices, SocketCAN uses the Berkeley13socket API, the Linux network stack and implements the CAN device14drivers as network interfaces. The CAN socket API has been designed15as similar as possible to the TCP/IP protocols to allow programmers,16familiar with network programming, to easily learn how to use CAN17sockets.18 19 20.. _socketcan-motivation:21 22Motivation / Why Using the Socket API23=====================================24 25There have been CAN implementations for Linux before SocketCAN so the26question arises, why we have started another project. Most existing27implementations come as a device driver for some CAN hardware, they28are based on character devices and provide comparatively little29functionality. Usually, there is only a hardware-specific device30driver which provides a character device interface to send and31receive raw CAN frames, directly to/from the controller hardware.32Queueing of frames and higher-level transport protocols like ISO-TP33have to be implemented in user space applications. Also, most34character-device implementations support only one single process to35open the device at a time, similar to a serial interface. Exchanging36the CAN controller requires employment of another device driver and37often the need for adaption of large parts of the application to the38new driver's API.39 40SocketCAN was designed to overcome all of these limitations. A new41protocol family has been implemented which provides a socket interface42to user space applications and which builds upon the Linux network43layer, enabling use all of the provided queueing functionality. A device44driver for CAN controller hardware registers itself with the Linux45network layer as a network device, so that CAN frames from the46controller can be passed up to the network layer and on to the CAN47protocol family module and also vice-versa. Also, the protocol family48module provides an API for transport protocol modules to register, so49that any number of transport protocols can be loaded or unloaded50dynamically. In fact, the can core module alone does not provide any51protocol and cannot be used without loading at least one additional52protocol module. Multiple sockets can be opened at the same time,53on different or the same protocol module and they can listen/send54frames on different or the same CAN IDs. Several sockets listening on55the same interface for frames with the same CAN ID are all passed the56same received matching CAN frames. An application wishing to57communicate using a specific transport protocol, e.g. ISO-TP, just58selects that protocol when opening the socket, and then can read and59write application data byte streams, without having to deal with60CAN-IDs, frames, etc.61 62Similar functionality visible from user-space could be provided by a63character device, too, but this would lead to a technically inelegant64solution for a couple of reasons:65 66* **Intricate usage:** Instead of passing a protocol argument to67 socket(2) and using bind(2) to select a CAN interface and CAN ID, an68 application would have to do all these operations using ioctl(2)s.69 70* **Code duplication:** A character device cannot make use of the Linux71 network queueing code, so all that code would have to be duplicated72 for CAN networking.73 74* **Abstraction:** In most existing character-device implementations, the75 hardware-specific device driver for a CAN controller directly76 provides the character device for the application to work with.77 This is at least very unusual in Unix systems for both, char and78 block devices. For example you don't have a character device for a79 certain UART of a serial interface, a certain sound chip in your80 computer, a SCSI or IDE controller providing access to your hard81 disk or tape streamer device. Instead, you have abstraction layers82 which provide a unified character or block device interface to the83 application on the one hand, and a interface for hardware-specific84 device drivers on the other hand. These abstractions are provided85 by subsystems like the tty layer, the audio subsystem or the SCSI86 and IDE subsystems for the devices mentioned above.87 88 The easiest way to implement a CAN device driver is as a character89 device without such a (complete) abstraction layer, as is done by most90 existing drivers. The right way, however, would be to add such a91 layer with all the functionality like registering for certain CAN92 IDs, supporting several open file descriptors and (de)multiplexing93 CAN frames between them, (sophisticated) queueing of CAN frames, and94 providing an API for device drivers to register with. However, then95 it would be no more difficult, or may be even easier, to use the96 networking framework provided by the Linux kernel, and this is what97 SocketCAN does.98 99The use of the networking framework of the Linux kernel is just the100natural and most appropriate way to implement CAN for Linux.101 102 103.. _socketcan-concept:104 105SocketCAN Concept106=================107 108As described in :ref:`socketcan-motivation` the main goal of SocketCAN is to109provide a socket interface to user space applications which builds110upon the Linux network layer. In contrast to the commonly known111TCP/IP and ethernet networking, the CAN bus is a broadcast-only(!)112medium that has no MAC-layer addressing like ethernet. The CAN-identifier113(can_id) is used for arbitration on the CAN-bus. Therefore the CAN-IDs114have to be chosen uniquely on the bus. When designing a CAN-ECU115network the CAN-IDs are mapped to be sent by a specific ECU.116For this reason a CAN-ID can be treated best as a kind of source address.117 118 119.. _socketcan-receive-lists:120 121Receive Lists122-------------123 124The network transparent access of multiple applications leads to the125problem that different applications may be interested in the same126CAN-IDs from the same CAN network interface. The SocketCAN core127module - which implements the protocol family CAN - provides several128high efficient receive lists for this reason. If e.g. a user space129application opens a CAN RAW socket, the raw protocol module itself130requests the (range of) CAN-IDs from the SocketCAN core that are131requested by the user. The subscription and unsubscription of132CAN-IDs can be done for specific CAN interfaces or for all(!) known133CAN interfaces with the can_rx_(un)register() functions provided to134CAN protocol modules by the SocketCAN core (see :ref:`socketcan-core-module`).135To optimize the CPU usage at runtime the receive lists are split up136into several specific lists per device that match the requested137filter complexity for a given use-case.138 139 140.. _socketcan-local-loopback1:141 142Local Loopback of Sent Frames143-----------------------------144 145As known from other networking concepts the data exchanging146applications may run on the same or different nodes without any147change (except for the according addressing information):148 149.. code::150 151 ___ ___ ___ _______ ___152 | _ | | _ | | _ | | _ _ | | _ |153 ||A|| ||B|| ||C|| ||A| |B|| ||C||154 |___| |___| |___| |_______| |___|155 | | | | |156 -----------------(1)- CAN bus -(2)---------------157 158To ensure that application A receives the same information in the159example (2) as it would receive in example (1) there is need for160some kind of local loopback of the sent CAN frames on the appropriate161node.162 163The Linux network devices (by default) just can handle the164transmission and reception of media dependent frames. Due to the165arbitration on the CAN bus the transmission of a low prio CAN-ID166may be delayed by the reception of a high prio CAN frame. To167reflect the correct [#f1]_ traffic on the node the loopback of the sent168data has to be performed right after a successful transmission. If169the CAN network interface is not capable of performing the loopback for170some reason the SocketCAN core can do this task as a fallback solution.171See :ref:`socketcan-local-loopback2` for details (recommended).172 173The loopback functionality is enabled by default to reflect standard174networking behaviour for CAN applications. Due to some requests from175the RT-SocketCAN group the loopback optionally may be disabled for each176separate socket. See sockopts from the CAN RAW sockets in :ref:`socketcan-raw-sockets`.177 178.. [#f1] you really like to have this when you're running analyser179 tools like 'candump' or 'cansniffer' on the (same) node.180 181 182.. _socketcan-network-problem-notifications:183 184Network Problem Notifications185-----------------------------186 187The use of the CAN bus may lead to several problems on the physical188and media access control layer. Detecting and logging of these lower189layer problems is a vital requirement for CAN users to identify190hardware issues on the physical transceiver layer as well as191arbitration problems and error frames caused by the different192ECUs. The occurrence of detected errors are important for diagnosis193and have to be logged together with the exact timestamp. For this194reason the CAN interface driver can generate so called Error Message195Frames that can optionally be passed to the user application in the196same way as other CAN frames. Whenever an error on the physical layer197or the MAC layer is detected (e.g. by the CAN controller) the driver198creates an appropriate error message frame. Error messages frames can199be requested by the user application using the common CAN filter200mechanisms. Inside this filter definition the (interested) type of201errors may be selected. The reception of error messages is disabled202by default. The format of the CAN error message frame is briefly203described in the Linux header file "include/uapi/linux/can/error.h".204 205 206How to use SocketCAN207====================208 209Like TCP/IP, you first need to open a socket for communicating over a210CAN network. Since SocketCAN implements a new protocol family, you211need to pass PF_CAN as the first argument to the socket(2) system212call. Currently, there are two CAN protocols to choose from, the raw213socket protocol and the broadcast manager (BCM). So to open a socket,214you would write::215 216 s = socket(PF_CAN, SOCK_RAW, CAN_RAW);217 218and::219 220 s = socket(PF_CAN, SOCK_DGRAM, CAN_BCM);221 222respectively. After the successful creation of the socket, you would223normally use the bind(2) system call to bind the socket to a CAN224interface (which is different from TCP/IP due to different addressing225- see :ref:`socketcan-concept`). After binding (CAN_RAW) or connecting (CAN_BCM)226the socket, you can read(2) and write(2) from/to the socket or use227send(2), sendto(2), sendmsg(2) and the recv* counterpart operations228on the socket as usual. There are also CAN specific socket options229described below.230 231The Classical CAN frame structure (aka CAN 2.0B), the CAN FD frame structure232and the sockaddr structure are defined in include/linux/can.h:233 234.. code-block:: C235 236 struct can_frame {237 canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */238 union {239 /* CAN frame payload length in byte (0 .. CAN_MAX_DLEN)240 * was previously named can_dlc so we need to carry that241 * name for legacy support242 */243 __u8 len;244 __u8 can_dlc; /* deprecated */245 };246 __u8 __pad; /* padding */247 __u8 __res0; /* reserved / padding */248 __u8 len8_dlc; /* optional DLC for 8 byte payload length (9 .. 15) */249 __u8 data[8] __attribute__((aligned(8)));250 };251 252Remark: The len element contains the payload length in bytes and should be253used instead of can_dlc. The deprecated can_dlc was misleadingly named as254it always contained the plain payload length in bytes and not the so called255'data length code' (DLC).256 257To pass the raw DLC from/to a Classical CAN network device the len8_dlc258element can contain values 9 .. 15 when the len element is 8 (the real259payload length for all DLC values greater or equal to 8).260 261The alignment of the (linear) payload data[] to a 64bit boundary262allows the user to define their own structs and unions to easily access263the CAN payload. There is no given byteorder on the CAN bus by264default. A read(2) system call on a CAN_RAW socket transfers a265struct can_frame to the user space.266 267The sockaddr_can structure has an interface index like the268PF_PACKET socket, that also binds to a specific interface:269 270.. code-block:: C271 272 struct sockaddr_can {273 sa_family_t can_family;274 int can_ifindex;275 union {276 /* transport protocol class address info (e.g. ISOTP) */277 struct { canid_t rx_id, tx_id; } tp;278 279 /* J1939 address information */280 struct {281 /* 8 byte name when using dynamic addressing */282 __u64 name;283 284 /* pgn:285 * 8 bit: PS in PDU2 case, else 0286 * 8 bit: PF287 * 1 bit: DP288 * 1 bit: reserved289 */290 __u32 pgn;291 292 /* 1 byte address */293 __u8 addr;294 } j1939;295 296 /* reserved for future CAN protocols address information */297 } can_addr;298 };299 300To determine the interface index an appropriate ioctl() has to301be used (example for CAN_RAW sockets without error checking):302 303.. code-block:: C304 305 int s;306 struct sockaddr_can addr;307 struct ifreq ifr;308 309 s = socket(PF_CAN, SOCK_RAW, CAN_RAW);310 311 strcpy(ifr.ifr_name, "can0" );312 ioctl(s, SIOCGIFINDEX, &ifr);313 314 addr.can_family = AF_CAN;315 addr.can_ifindex = ifr.ifr_ifindex;316 317 bind(s, (struct sockaddr *)&addr, sizeof(addr));318 319 (..)320 321To bind a socket to all(!) CAN interfaces the interface index must322be 0 (zero). In this case the socket receives CAN frames from every323enabled CAN interface. To determine the originating CAN interface324the system call recvfrom(2) may be used instead of read(2). To send325on a socket that is bound to 'any' interface sendto(2) is needed to326specify the outgoing interface.327 328Reading CAN frames from a bound CAN_RAW socket (see above) consists329of reading a struct can_frame:330 331.. code-block:: C332 333 struct can_frame frame;334 335 nbytes = read(s, &frame, sizeof(struct can_frame));336 337 if (nbytes < 0) {338 perror("can raw socket read");339 return 1;340 }341 342 /* paranoid check ... */343 if (nbytes < sizeof(struct can_frame)) {344 fprintf(stderr, "read: incomplete CAN frame\n");345 return 1;346 }347 348 /* do something with the received CAN frame */349 350Writing CAN frames can be done similarly, with the write(2) system call::351 352 nbytes = write(s, &frame, sizeof(struct can_frame));353 354When the CAN interface is bound to 'any' existing CAN interface355(addr.can_ifindex = 0) it is recommended to use recvfrom(2) if the356information about the originating CAN interface is needed:357 358.. code-block:: C359 360 struct sockaddr_can addr;361 struct ifreq ifr;362 socklen_t len = sizeof(addr);363 struct can_frame frame;364 365 nbytes = recvfrom(s, &frame, sizeof(struct can_frame),366 0, (struct sockaddr*)&addr, &len);367 368 /* get interface name of the received CAN frame */369 ifr.ifr_ifindex = addr.can_ifindex;370 ioctl(s, SIOCGIFNAME, &ifr);371 printf("Received a CAN frame from interface %s", ifr.ifr_name);372 373To write CAN frames on sockets bound to 'any' CAN interface the374outgoing interface has to be defined certainly:375 376.. code-block:: C377 378 strcpy(ifr.ifr_name, "can0");379 ioctl(s, SIOCGIFINDEX, &ifr);380 addr.can_ifindex = ifr.ifr_ifindex;381 addr.can_family = AF_CAN;382 383 nbytes = sendto(s, &frame, sizeof(struct can_frame),384 0, (struct sockaddr*)&addr, sizeof(addr));385 386An accurate timestamp can be obtained with an ioctl(2) call after reading387a message from the socket:388 389.. code-block:: C390 391 struct timeval tv;392 ioctl(s, SIOCGSTAMP, &tv);393 394The timestamp has a resolution of one microsecond and is set automatically395at the reception of a CAN frame.396 397Remark about CAN FD (flexible data rate) support:398 399Generally the handling of CAN FD is very similar to the formerly described400examples. The new CAN FD capable CAN controllers support two different401bitrates for the arbitration phase and the payload phase of the CAN FD frame402and up to 64 bytes of payload. This extended payload length breaks all the403kernel interfaces (ABI) which heavily rely on the CAN frame with fixed eight404bytes of payload (struct can_frame) like the CAN_RAW socket. Therefore e.g.405the CAN_RAW socket supports a new socket option CAN_RAW_FD_FRAMES that406switches the socket into a mode that allows the handling of CAN FD frames407and Classical CAN frames simultaneously (see :ref:`socketcan-rawfd`).408 409The struct canfd_frame is defined in include/linux/can.h:410 411.. code-block:: C412 413 struct canfd_frame {414 canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */415 __u8 len; /* frame payload length in byte (0 .. 64) */416 __u8 flags; /* additional flags for CAN FD */417 __u8 __res0; /* reserved / padding */418 __u8 __res1; /* reserved / padding */419 __u8 data[64] __attribute__((aligned(8)));420 };421 422The struct canfd_frame and the existing struct can_frame have the can_id,423the payload length and the payload data at the same offset inside their424structures. This allows to handle the different structures very similar.425When the content of a struct can_frame is copied into a struct canfd_frame426all structure elements can be used as-is - only the data[] becomes extended.427 428When introducing the struct canfd_frame it turned out that the data length429code (DLC) of the struct can_frame was used as a length information as the430length and the DLC has a 1:1 mapping in the range of 0 .. 8. To preserve431the easy handling of the length information the canfd_frame.len element432contains a plain length value from 0 .. 64. So both canfd_frame.len and433can_frame.len are equal and contain a length information and no DLC.434For details about the distinction of CAN and CAN FD capable devices and435the mapping to the bus-relevant data length code (DLC), see :ref:`socketcan-can-fd-driver`.436 437The length of the two CAN(FD) frame structures define the maximum transfer438unit (MTU) of the CAN(FD) network interface and skbuff data length. Two439definitions are specified for CAN specific MTUs in include/linux/can.h:440 441.. code-block:: C442 443 #define CAN_MTU (sizeof(struct can_frame)) == 16 => Classical CAN frame444 #define CANFD_MTU (sizeof(struct canfd_frame)) == 72 => CAN FD frame445 446 447Returned Message Flags448----------------------449 450When using the system call recvmsg(2) on a RAW or a BCM socket, the451msg->msg_flags field may contain the following flags:452 453MSG_DONTROUTE:454 set when the received frame was created on the local host.455 456MSG_CONFIRM:457 set when the frame was sent via the socket it is received on.458 This flag can be interpreted as a 'transmission confirmation' when the459 CAN driver supports the echo of frames on driver level, see460 :ref:`socketcan-local-loopback1` and :ref:`socketcan-local-loopback2`.461 (Note: In order to receive such messages on a RAW socket,462 CAN_RAW_RECV_OWN_MSGS must be set.)463 464 465.. _socketcan-raw-sockets:466 467RAW Protocol Sockets with can_filters (SOCK_RAW)468------------------------------------------------469 470Using CAN_RAW sockets is extensively comparable to the commonly471known access to CAN character devices. To meet the new possibilities472provided by the multi user SocketCAN approach, some reasonable473defaults are set at RAW socket binding time:474 475- The filters are set to exactly one filter receiving everything476- The socket only receives valid data frames (=> no error message frames)477- The loopback of sent CAN frames is enabled (see :ref:`socketcan-local-loopback2`)478- The socket does not receive its own sent frames (in loopback mode)479 480These default settings may be changed before or after binding the socket.481To use the referenced definitions of the socket options for CAN_RAW482sockets, include <linux/can/raw.h>.483 484 485.. _socketcan-rawfilter:486 487RAW socket option CAN_RAW_FILTER488~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~489 490The reception of CAN frames using CAN_RAW sockets can be controlled491by defining 0 .. n filters with the CAN_RAW_FILTER socket option.492 493The CAN filter structure is defined in include/linux/can.h:494 495.. code-block:: C496 497 struct can_filter {498 canid_t can_id;499 canid_t can_mask;500 };501 502A filter matches, when:503 504.. code-block:: C505 506 <received_can_id> & mask == can_id & mask507 508which is analogous to known CAN controllers hardware filter semantics.509The filter can be inverted in this semantic, when the CAN_INV_FILTER510bit is set in can_id element of the can_filter structure. In511contrast to CAN controller hardware filters the user may set 0 .. n512receive filters for each open socket separately:513 514.. code-block:: C515 516 struct can_filter rfilter[2];517 518 rfilter[0].can_id = 0x123;519 rfilter[0].can_mask = CAN_SFF_MASK;520 rfilter[1].can_id = 0x200;521 rfilter[1].can_mask = 0x700;522 523 setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter));524 525To disable the reception of CAN frames on the selected CAN_RAW socket:526 527.. code-block:: C528 529 setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);530 531To set the filters to zero filters is quite obsolete as to not read532data causes the raw socket to discard the received CAN frames. But533having this 'send only' use-case we may remove the receive list in the534Kernel to save a little (really a very little!) CPU usage.535 536CAN Filter Usage Optimisation537.............................538 539The CAN filters are processed in per-device filter lists at CAN frame540reception time. To reduce the number of checks that need to be performed541while walking through the filter lists the CAN core provides an optimized542filter handling when the filter subscription focusses on a single CAN ID.543 544For the possible 2048 SFF CAN identifiers the identifier is used as an index545to access the corresponding subscription list without any further checks.546For the 2^29 possible EFF CAN identifiers a 10 bit XOR folding is used as547hash function to retrieve the EFF table index.548 549To benefit from the optimized filters for single CAN identifiers the550CAN_SFF_MASK or CAN_EFF_MASK have to be set into can_filter.mask together551with set CAN_EFF_FLAG and CAN_RTR_FLAG bits. A set CAN_EFF_FLAG bit in the552can_filter.mask makes clear that it matters whether a SFF or EFF CAN ID is553subscribed. E.g. in the example from above:554 555.. code-block:: C556 557 rfilter[0].can_id = 0x123;558 rfilter[0].can_mask = CAN_SFF_MASK;559 560both SFF frames with CAN ID 0x123 and EFF frames with 0xXXXXX123 can pass.561 562To filter for only 0x123 (SFF) and 0x12345678 (EFF) CAN identifiers the563filter has to be defined in this way to benefit from the optimized filters:564 565.. code-block:: C566 567 struct can_filter rfilter[2];568 569 rfilter[0].can_id = 0x123;570 rfilter[0].can_mask = (CAN_EFF_FLAG | CAN_RTR_FLAG | CAN_SFF_MASK);571 rfilter[1].can_id = 0x12345678 | CAN_EFF_FLAG;572 rfilter[1].can_mask = (CAN_EFF_FLAG | CAN_RTR_FLAG | CAN_EFF_MASK);573 574 setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter));575 576 577RAW Socket Option CAN_RAW_ERR_FILTER578~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~579 580As described in :ref:`socketcan-network-problem-notifications` the CAN interface driver can generate so581called Error Message Frames that can optionally be passed to the user582application in the same way as other CAN frames. The possible583errors are divided into different error classes that may be filtered584using the appropriate error mask. To register for every possible585error condition CAN_ERR_MASK can be used as value for the error mask.586The values for the error mask are defined in linux/can/error.h:587 588.. code-block:: C589 590 can_err_mask_t err_mask = ( CAN_ERR_TX_TIMEOUT | CAN_ERR_BUSOFF );591 592 setsockopt(s, SOL_CAN_RAW, CAN_RAW_ERR_FILTER,593 &err_mask, sizeof(err_mask));594 595 596RAW Socket Option CAN_RAW_LOOPBACK597~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~598 599To meet multi user needs the local loopback is enabled by default600(see :ref:`socketcan-local-loopback1` for details). But in some embedded use-cases601(e.g. when only one application uses the CAN bus) this loopback602functionality can be disabled (separately for each socket):603 604.. code-block:: C605 606 int loopback = 0; /* 0 = disabled, 1 = enabled (default) */607 608 setsockopt(s, SOL_CAN_RAW, CAN_RAW_LOOPBACK, &loopback, sizeof(loopback));609 610 611RAW socket option CAN_RAW_RECV_OWN_MSGS612~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~613 614When the local loopback is enabled, all the sent CAN frames are615looped back to the open CAN sockets that registered for the CAN616frames' CAN-ID on this given interface to meet the multi user617needs. The reception of the CAN frames on the same socket that was618sending the CAN frame is assumed to be unwanted and therefore619disabled by default. This default behaviour may be changed on620demand:621 622.. code-block:: C623 624 int recv_own_msgs = 1; /* 0 = disabled (default), 1 = enabled */625 626 setsockopt(s, SOL_CAN_RAW, CAN_RAW_RECV_OWN_MSGS,627 &recv_own_msgs, sizeof(recv_own_msgs));628 629Note that reception of a socket's own CAN frames are subject to the same630filtering as other CAN frames (see :ref:`socketcan-rawfilter`).631 632.. _socketcan-rawfd:633 634RAW Socket Option CAN_RAW_FD_FRAMES635~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~636 637CAN FD support in CAN_RAW sockets can be enabled with a new socket option638CAN_RAW_FD_FRAMES which is off by default. When the new socket option is639not supported by the CAN_RAW socket (e.g. on older kernels), switching the640CAN_RAW_FD_FRAMES option returns the error -ENOPROTOOPT.641 642Once CAN_RAW_FD_FRAMES is enabled the application can send both CAN frames643and CAN FD frames. OTOH the application has to handle CAN and CAN FD frames644when reading from the socket:645 646.. code-block:: C647 648 CAN_RAW_FD_FRAMES enabled: CAN_MTU and CANFD_MTU are allowed649 CAN_RAW_FD_FRAMES disabled: only CAN_MTU is allowed (default)650 651Example:652 653.. code-block:: C654 655 [ remember: CANFD_MTU == sizeof(struct canfd_frame) ]656 657 struct canfd_frame cfd;658 659 nbytes = read(s, &cfd, CANFD_MTU);660 661 if (nbytes == CANFD_MTU) {662 printf("got CAN FD frame with length %d\n", cfd.len);663 /* cfd.flags contains valid data */664 } else if (nbytes == CAN_MTU) {665 printf("got Classical CAN frame with length %d\n", cfd.len);666 /* cfd.flags is undefined */667 } else {668 fprintf(stderr, "read: invalid CAN(FD) frame\n");669 return 1;670 }671 672 /* the content can be handled independently from the received MTU size */673 674 printf("can_id: %X data length: %d data: ", cfd.can_id, cfd.len);675 for (i = 0; i < cfd.len; i++)676 printf("%02X ", cfd.data[i]);677 678When reading with size CANFD_MTU only returns CAN_MTU bytes that have679been received from the socket a Classical CAN frame has been read into the680provided CAN FD structure. Note that the canfd_frame.flags data field is681not specified in the struct can_frame and therefore it is only valid in682CANFD_MTU sized CAN FD frames.683 684Implementation hint for new CAN applications:685 686To build a CAN FD aware application use struct canfd_frame as basic CAN687data structure for CAN_RAW based applications. When the application is688executed on an older Linux kernel and switching the CAN_RAW_FD_FRAMES689socket option returns an error: No problem. You'll get Classical CAN frames690or CAN FD frames and can process them the same way.691 692When sending to CAN devices make sure that the device is capable to handle693CAN FD frames by checking if the device maximum transfer unit is CANFD_MTU.694The CAN device MTU can be retrieved e.g. with a SIOCGIFMTU ioctl() syscall.695 696 697RAW socket option CAN_RAW_JOIN_FILTERS698~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~699 700The CAN_RAW socket can set multiple CAN identifier specific filters that701lead to multiple filters in the af_can.c filter processing. These filters702are indenpendent from each other which leads to logical OR'ed filters when703applied (see :ref:`socketcan-rawfilter`).704 705This socket option joines the given CAN filters in the way that only CAN706frames are passed to user space that matched *all* given CAN filters. The707semantic for the applied filters is therefore changed to a logical AND.708 709This is useful especially when the filterset is a combination of filters710where the CAN_INV_FILTER flag is set in order to notch single CAN IDs or711CAN ID ranges from the incoming traffic.712 713 714Broadcast Manager Protocol Sockets (SOCK_DGRAM)715-----------------------------------------------716 717The Broadcast Manager protocol provides a command based configuration718interface to filter and send (e.g. cyclic) CAN messages in kernel space.719 720Receive filters can be used to down sample frequent messages; detect events721such as message contents changes, packet length changes, and do time-out722monitoring of received messages.723 724Periodic transmission tasks of CAN frames or a sequence of CAN frames can be725created and modified at runtime; both the message content and the two726possible transmit intervals can be altered.727 728A BCM socket is not intended for sending individual CAN frames using the729struct can_frame as known from the CAN_RAW socket. Instead a special BCM730configuration message is defined. The basic BCM configuration message used731to communicate with the broadcast manager and the available operations are732defined in the linux/can/bcm.h include. The BCM message consists of a733message header with a command ('opcode') followed by zero or more CAN frames.734The broadcast manager sends responses to user space in the same form:735 736.. code-block:: C737 738 struct bcm_msg_head {739 __u32 opcode; /* command */740 __u32 flags; /* special flags */741 __u32 count; /* run 'count' times with ival1 */742 struct timeval ival1, ival2; /* count and subsequent interval */743 canid_t can_id; /* unique can_id for task */744 __u32 nframes; /* number of can_frames following */745 struct can_frame frames[0];746 };747 748The aligned payload 'frames' uses the same basic CAN frame structure defined749at the beginning of :ref:`socketcan-rawfd` and in the include/linux/can.h include. All750messages to the broadcast manager from user space have this structure.751 752Note a CAN_BCM socket must be connected instead of bound after socket753creation (example without error checking):754 755.. code-block:: C756 757 int s;758 struct sockaddr_can addr;759 struct ifreq ifr;760 761 s = socket(PF_CAN, SOCK_DGRAM, CAN_BCM);762 763 strcpy(ifr.ifr_name, "can0");764 ioctl(s, SIOCGIFINDEX, &ifr);765 766 addr.can_family = AF_CAN;767 addr.can_ifindex = ifr.ifr_ifindex;768 769 connect(s, (struct sockaddr *)&addr, sizeof(addr));770 771 (..)772 773The broadcast manager socket is able to handle any number of in flight774transmissions or receive filters concurrently. The different RX/TX jobs are775distinguished by the unique can_id in each BCM message. However additional776CAN_BCM sockets are recommended to communicate on multiple CAN interfaces.777When the broadcast manager socket is bound to 'any' CAN interface (=> the778interface index is set to zero) the configured receive filters apply to any779CAN interface unless the sendto() syscall is used to overrule the 'any' CAN780interface index. When using recvfrom() instead of read() to retrieve BCM781socket messages the originating CAN interface is provided in can_ifindex.782 783 784Broadcast Manager Operations785~~~~~~~~~~~~~~~~~~~~~~~~~~~~786 787The opcode defines the operation for the broadcast manager to carry out,788or details the broadcast managers response to several events, including789user requests.790 791Transmit Operations (user space to broadcast manager):792 793TX_SETUP:794 Create (cyclic) transmission task.795 796TX_DELETE:797 Remove (cyclic) transmission task, requires only can_id.798 799TX_READ:800 Read properties of (cyclic) transmission task for can_id.801 802TX_SEND:803 Send one CAN frame.804 805Transmit Responses (broadcast manager to user space):806 807TX_STATUS:808 Reply to TX_READ request (transmission task configuration).809 810TX_EXPIRED:811 Notification when counter finishes sending at initial interval812 'ival1'. Requires the TX_COUNTEVT flag to be set at TX_SETUP.813 814Receive Operations (user space to broadcast manager):815 816RX_SETUP:817 Create RX content filter subscription.818 819RX_DELETE:820 Remove RX content filter subscription, requires only can_id.821 822RX_READ:823 Read properties of RX content filter subscription for can_id.824 825Receive Responses (broadcast manager to user space):826 827RX_STATUS:828 Reply to RX_READ request (filter task configuration).829 830RX_TIMEOUT:831 Cyclic message is detected to be absent (timer ival1 expired).832 833RX_CHANGED:834 BCM message with updated CAN frame (detected content change).835 Sent on first message received or on receipt of revised CAN messages.836 837 838Broadcast Manager Message Flags839~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~840 841When sending a message to the broadcast manager the 'flags' element may842contain the following flag definitions which influence the behaviour:843 844SETTIMER:845 Set the values of ival1, ival2 and count846 847STARTTIMER:848 Start the timer with the actual values of ival1, ival2849 and count. Starting the timer leads simultaneously to emit a CAN frame.850 851TX_COUNTEVT:852 Create the message TX_EXPIRED when count expires853 854TX_ANNOUNCE:855 A change of data by the process is emitted immediately.856 857TX_CP_CAN_ID:858 Copies the can_id from the message header to each859 subsequent frame in frames. This is intended as usage simplification. For860 TX tasks the unique can_id from the message header may differ from the861 can_id(s) stored for transmission in the subsequent struct can_frame(s).862 863RX_FILTER_ID:864 Filter by can_id alone, no frames required (nframes=0).865 866RX_CHECK_DLC:867 A change of the DLC leads to an RX_CHANGED.868 869RX_NO_AUTOTIMER:870 Prevent automatically starting the timeout monitor.871 872RX_ANNOUNCE_RESUME:873 If passed at RX_SETUP and a receive timeout occurred, a874 RX_CHANGED message will be generated when the (cyclic) receive restarts.875 876TX_RESET_MULTI_IDX:877 Reset the index for the multiple frame transmission.878 879RX_RTR_FRAME:880 Send reply for RTR-request (placed in op->frames[0]).881 882CAN_FD_FRAME:883 The CAN frames following the bcm_msg_head are struct canfd_frame's884 885Broadcast Manager Transmission Timers886~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~887 888Periodic transmission configurations may use up to two interval timers.889In this case the BCM sends a number of messages ('count') at an interval890'ival1', then continuing to send at another given interval 'ival2'. When891only one timer is needed 'count' is set to zero and only 'ival2' is used.892When SET_TIMER and START_TIMER flag were set the timers are activated.893The timer values can be altered at runtime when only SET_TIMER is set.894 895 896Broadcast Manager message sequence transmission897~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~898 899Up to 256 CAN frames can be transmitted in a sequence in the case of a cyclic900TX task configuration. The number of CAN frames is provided in the 'nframes'901element of the BCM message head. The defined number of CAN frames are added902as array to the TX_SETUP BCM configuration message:903 904.. code-block:: C905 906 /* create a struct to set up a sequence of four CAN frames */907 struct {908 struct bcm_msg_head msg_head;909 struct can_frame frame[4];910 } mytxmsg;911 912 (..)913 mytxmsg.msg_head.nframes = 4;914 (..)915 916 write(s, &mytxmsg, sizeof(mytxmsg));917 918With every transmission the index in the array of CAN frames is increased919and set to zero at index overflow.920 921 922Broadcast Manager Receive Filter Timers923~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~924 925The timer values ival1 or ival2 may be set to non-zero values at RX_SETUP.926When the SET_TIMER flag is set the timers are enabled:927 928ival1:929 Send RX_TIMEOUT when a received message is not received again within930 the given time. When START_TIMER is set at RX_SETUP the timeout detection931 is activated directly - even without a former CAN frame reception.932 933ival2:934 Throttle the received message rate down to the value of ival2. This935 is useful to reduce messages for the application when the signal inside the936 CAN frame is stateless as state changes within the ival2 period may get937 lost.938 939Broadcast Manager Multiplex Message Receive Filter940~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~941 942To filter for content changes in multiplex message sequences an array of more943than one CAN frames can be passed in a RX_SETUP configuration message. The944data bytes of the first CAN frame contain the mask of relevant bits that945have to match in the subsequent CAN frames with the received CAN frame.946If one of the subsequent CAN frames is matching the bits in that frame data947mark the relevant content to be compared with the previous received content.948Up to 257 CAN frames (multiplex filter bit mask CAN frame plus 256 CAN949filters) can be added as array to the TX_SETUP BCM configuration message:950 951.. code-block:: C952 953 /* usually used to clear CAN frame data[] - beware of endian problems! */954 #define U64_DATA(p) (*(unsigned long long*)(p)->data)955 956 struct {957 struct bcm_msg_head msg_head;958 struct can_frame frame[5];959 } msg;960 961 msg.msg_head.opcode = RX_SETUP;962 msg.msg_head.can_id = 0x42;963 msg.msg_head.flags = 0;964 msg.msg_head.nframes = 5;965 U64_DATA(&msg.frame[0]) = 0xFF00000000000000ULL; /* MUX mask */966 U64_DATA(&msg.frame[1]) = 0x01000000000000FFULL; /* data mask (MUX 0x01) */967 U64_DATA(&msg.frame[2]) = 0x0200FFFF000000FFULL; /* data mask (MUX 0x02) */968 U64_DATA(&msg.frame[3]) = 0x330000FFFFFF0003ULL; /* data mask (MUX 0x33) */969 U64_DATA(&msg.frame[4]) = 0x4F07FC0FF0000000ULL; /* data mask (MUX 0x4F) */970 971 write(s, &msg, sizeof(msg));972 973 974Broadcast Manager CAN FD Support975~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~976 977The programming API of the CAN_BCM depends on struct can_frame which is978given as array directly behind the bcm_msg_head structure. To follow this979schema for the CAN FD frames a new flag 'CAN_FD_FRAME' in the bcm_msg_head980flags indicates that the concatenated CAN frame structures behind the981bcm_msg_head are defined as struct canfd_frame:982 983.. code-block:: C984 985 struct {986 struct bcm_msg_head msg_head;987 struct canfd_frame frame[5];988 } msg;989 990 msg.msg_head.opcode = RX_SETUP;991 msg.msg_head.can_id = 0x42;992 msg.msg_head.flags = CAN_FD_FRAME;993 msg.msg_head.nframes = 5;994 (..)995 996When using CAN FD frames for multiplex filtering the MUX mask is still997expected in the first 64 bit of the struct canfd_frame data section.998 999 1000Connected Transport Protocols (SOCK_SEQPACKET)1001----------------------------------------------1002 1003(to be written)1004 1005 1006Unconnected Transport Protocols (SOCK_DGRAM)1007--------------------------------------------1008 1009(to be written)1010 1011 1012.. _socketcan-core-module:1013 1014SocketCAN Core Module1015=====================1016 1017The SocketCAN core module implements the protocol family1018PF_CAN. CAN protocol modules are loaded by the core module at1019runtime. The core module provides an interface for CAN protocol1020modules to subscribe needed CAN IDs (see :ref:`socketcan-receive-lists`).1021 1022 1023can.ko Module Params1024--------------------1025 1026- **stats_timer**:1027 To calculate the SocketCAN core statistics1028 (e.g. current/maximum frames per second) this 1 second timer is1029 invoked at can.ko module start time by default. This timer can be1030 disabled by using stattimer=0 on the module commandline.1031 1032- **debug**:1033 (removed since SocketCAN SVN r546)1034 1035 1036procfs content1037--------------1038 1039As described in :ref:`socketcan-receive-lists` the SocketCAN core uses several filter1040lists to deliver received CAN frames to CAN protocol modules. These1041receive lists, their filters and the count of filter matches can be1042checked in the appropriate receive list. All entries contain the1043device and a protocol module identifier::1044 1045 foo@bar:~$ cat /proc/net/can/rcvlist_all1046 1047 receive list 'rx_all':1048 (vcan3: no entry)1049 (vcan2: no entry)1050 (vcan1: no entry)1051 device can_id can_mask function userdata matches ident1052 vcan0 000 00000000 f88e6370 f6c6f400 0 raw1053 (any: no entry)1054 1055In this example an application requests any CAN traffic from vcan0::1056 1057 rcvlist_all - list for unfiltered entries (no filter operations)1058 rcvlist_eff - list for single extended frame (EFF) entries1059 rcvlist_err - list for error message frames masks1060 rcvlist_fil - list for mask/value filters1061 rcvlist_inv - list for mask/value filters (inverse semantic)1062 rcvlist_sff - list for single standard frame (SFF) entries1063 1064Additional procfs files in /proc/net/can::1065 1066 stats - SocketCAN core statistics (rx/tx frames, match ratios, ...)1067 reset_stats - manual statistic reset1068 version - prints SocketCAN core and ABI version (removed in Linux 5.10)1069 1070 1071Writing Own CAN Protocol Modules1072--------------------------------1073 1074To implement a new protocol in the protocol family PF_CAN a new1075protocol has to be defined in include/linux/can.h .1076The prototypes and definitions to use the SocketCAN core can be1077accessed by including include/linux/can/core.h .1078In addition to functions that register the CAN protocol and the1079CAN device notifier chain there are functions to subscribe CAN1080frames received by CAN interfaces and to send CAN frames::1081 1082 can_rx_register - subscribe CAN frames from a specific interface1083 can_rx_unregister - unsubscribe CAN frames from a specific interface1084 can_send - transmit a CAN frame (optional with local loopback)1085 1086For details see the kerneldoc documentation in net/can/af_can.c or1087the source code of net/can/raw.c or net/can/bcm.c .1088 1089 1090CAN Network Drivers1091===================1092 1093Writing a CAN network device driver is much easier than writing a1094CAN character device driver. Similar to other known network device1095drivers you mainly have to deal with:1096 1097- TX: Put the CAN frame from the socket buffer to the CAN controller.1098- RX: Put the CAN frame from the CAN controller to the socket buffer.1099 1100See e.g. at Documentation/networking/netdevices.rst . The differences1101for writing CAN network device driver are described below:1102 1103 1104General Settings1105----------------1106 1107.. code-block:: C1108 1109 dev->type = ARPHRD_CAN; /* the netdevice hardware type */1110 dev->flags = IFF_NOARP; /* CAN has no arp */1111 1112 dev->mtu = CAN_MTU; /* sizeof(struct can_frame) -> Classical CAN interface */1113 1114 or alternative, when the controller supports CAN with flexible data rate:1115 dev->mtu = CANFD_MTU; /* sizeof(struct canfd_frame) -> CAN FD interface */1116 1117The struct can_frame or struct canfd_frame is the payload of each socket1118buffer (skbuff) in the protocol family PF_CAN.1119 1120 1121.. _socketcan-local-loopback2:1122 1123Local Loopback of Sent Frames1124-----------------------------1125 1126As described in :ref:`socketcan-local-loopback1` the CAN network device driver should1127support a local loopback functionality similar to the local echo1128e.g. of tty devices. In this case the driver flag IFF_ECHO has to be1129set to prevent the PF_CAN core from locally echoing sent frames1130(aka loopback) as fallback solution::1131 1132 dev->flags = (IFF_NOARP | IFF_ECHO);1133 1134 1135CAN Controller Hardware Filters1136-------------------------------1137 1138To reduce the interrupt load on deep embedded systems some CAN1139controllers support the filtering of CAN IDs or ranges of CAN IDs.1140These hardware filter capabilities vary from controller to1141controller and have to be identified as not feasible in a multi-user1142networking approach. The use of the very controller specific1143hardware filters could make sense in a very dedicated use-case, as a1144filter on driver level would affect all users in the multi-user1145system. The high efficient filter sets inside the PF_CAN core allow1146to set different multiple filters for each socket separately.1147Therefore the use of hardware filters goes to the category 'handmade1148tuning on deep embedded systems'. The author is running a MPC603e1149@133MHz with four SJA1000 CAN controllers from 2002 under heavy bus1150load without any problems ...1151 1152 1153Switchable Termination Resistors1154--------------------------------1155 1156CAN bus requires a specific impedance across the differential pair,1157typically provided by two 120Ohm resistors on the farthest nodes of1158the bus. Some CAN controllers support activating / deactivating a1159termination resistor(s) to provide the correct impedance.1160 1161Query the available resistances::1162 1163 $ ip -details link show can01164 ...1165 termination 120 [ 0, 120 ]1166 1167Activate the terminating resistor::1168 1169 $ ip link set dev can0 type can termination 1201170 1171Deactivate the terminating resistor::1172 1173 $ ip link set dev can0 type can termination 01174 1175To enable termination resistor support to a can-controller, either1176implement in the controller's struct can-priv::1177 1178 termination_const1179 termination_const_cnt1180 do_set_termination1181 1182or add gpio control with the device tree entries from1183Documentation/devicetree/bindings/net/can/can-controller.yaml1184 1185 1186The Virtual CAN Driver (vcan)1187-----------------------------1188 1189Similar to the network loopback devices, vcan offers a virtual local1190CAN interface. A full qualified address on CAN consists of1191 1192- a unique CAN Identifier (CAN ID)1193- the CAN bus this CAN ID is transmitted on (e.g. can0)1194 1195so in common use cases more than one virtual CAN interface is needed.1196 1197The virtual CAN interfaces allow the transmission and reception of CAN1198frames without real CAN controller hardware. Virtual CAN network1199devices are usually named 'vcanX', like vcan0 vcan1 vcan2 ...1200When compiled as a module the virtual CAN driver module is called vcan.ko1201 1202Since Linux Kernel version 2.6.24 the vcan driver supports the Kernel1203netlink interface to create vcan network devices. The creation and1204removal of vcan network devices can be managed with the ip(8) tool::1205 1206 - Create a virtual CAN network interface:1207 $ ip link add type vcan1208 1209 - Create a virtual CAN network interface with a specific name 'vcan42':1210 $ ip link add dev vcan42 type vcan1211 1212 - Remove a (virtual CAN) network interface 'vcan42':1213 $ ip link del vcan421214 1215 1216The CAN Network Device Driver Interface1217---------------------------------------1218 1219The CAN network device driver interface provides a generic interface1220to setup, configure and monitor CAN network devices. The user can then1221configure the CAN device, like setting the bit-timing parameters, via1222the netlink interface using the program "ip" from the "IPROUTE2"1223utility suite. The following chapter describes briefly how to use it.1224Furthermore, the interface uses a common data structure and exports a1225set of common functions, which all real CAN network device drivers1226should use. Please have a look to the SJA1000 or MSCAN driver to1227understand how to use them. The name of the module is can-dev.ko.1228 1229 1230Netlink interface to set/get devices properties1231~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~1232 1233The CAN device must be configured via netlink interface. The supported1234netlink message types are defined and briefly described in1235"include/linux/can/netlink.h". CAN link support for the program "ip"1236of the IPROUTE2 utility suite is available and it can be used as shown1237below:1238 1239Setting CAN device properties::1240 1241 $ ip link set can0 type can help1242 Usage: ip link set DEVICE type can1243 [ bitrate BITRATE [ sample-point SAMPLE-POINT] ] |1244 [ tq TQ prop-seg PROP_SEG phase-seg1 PHASE-SEG11245 phase-seg2 PHASE-SEG2 [ sjw SJW ] ]1246 1247 [ dbitrate BITRATE [ dsample-point SAMPLE-POINT] ] |1248 [ dtq TQ dprop-seg PROP_SEG dphase-seg1 PHASE-SEG11249 dphase-seg2 PHASE-SEG2 [ dsjw SJW ] ]1250 1251 [ loopback { on | off } ]1252 [ listen-only { on | off } ]1253 [ triple-sampling { on | off } ]1254 [ one-shot { on | off } ]1255 [ berr-reporting { on | off } ]1256 [ fd { on | off } ]1257 [ fd-non-iso { on | off } ]1258 [ presume-ack { on | off } ]1259 [ cc-len8-dlc { on | off } ]1260 1261 [ restart-ms TIME-MS ]1262 [ restart ]1263 1264 Where: BITRATE := { 1..1000000 }1265 SAMPLE-POINT := { 0.000..0.999 }1266 TQ := { NUMBER }1267 PROP-SEG := { 1..8 }1268 PHASE-SEG1 := { 1..8 }1269 PHASE-SEG2 := { 1..8 }1270 SJW := { 1..4 }1271 RESTART-MS := { 0 | NUMBER }1272 1273Display CAN device details and statistics::1274 1275 $ ip -details -statistics link show can01276 2: can0: <NOARP,UP,LOWER_UP,ECHO> mtu 16 qdisc pfifo_fast state UP qlen 101277 link/can1278 can <TRIPLE-SAMPLING> state ERROR-ACTIVE restart-ms 1001279 bitrate 125000 sample_point 0.8751280 tq 125 prop-seg 6 phase-seg1 7 phase-seg2 2 sjw 11281 sja1000: tseg1 1..16 tseg2 1..8 sjw 1..4 brp 1..64 brp-inc 11282 clock 80000001283 re-started bus-errors arbit-lost error-warn error-pass bus-off1284 41 17457 0 41 42 411285 RX: bytes packets errors dropped overrun mcast1286 140859 17608 17457 0 0 01287 TX: bytes packets errors dropped carrier collsns1288 861 112 0 41 0 01289 1290More info to the above output:1291 1292"<TRIPLE-SAMPLING>"1293 Shows the list of selected CAN controller modes: LOOPBACK,1294 LISTEN-ONLY, or TRIPLE-SAMPLING.1295 1296"state ERROR-ACTIVE"1297 The current state of the CAN controller: "ERROR-ACTIVE",1298 "ERROR-WARNING", "ERROR-PASSIVE", "BUS-OFF" or "STOPPED"1299 1300"restart-ms 100"1301 Automatic restart delay time. If set to a non-zero value, a1302 restart of the CAN controller will be triggered automatically1303 in case of a bus-off condition after the specified delay time1304 in milliseconds. By default it's off.1305 1306"bitrate 125000 sample-point 0.875"1307 Shows the real bit-rate in bits/sec and the sample-point in the1308 range 0.000..0.999. If the calculation of bit-timing parameters1309 is enabled in the kernel (CONFIG_CAN_CALC_BITTIMING=y), the1310 bit-timing can be defined by setting the "bitrate" argument.1311 Optionally the "sample-point" can be specified. By default it's1312 0.000 assuming CIA-recommended sample-points.1313 1314"tq 125 prop-seg 6 phase-seg1 7 phase-seg2 2 sjw 1"1315 Shows the time quanta in ns, propagation segment, phase buffer1316 segment 1 and 2 and the synchronisation jump width in units of1317 tq. They allow to define the CAN bit-timing in a hardware1318 independent format as proposed by the Bosch CAN 2.0 spec (see1319 chapter 8 of http://www.semiconductors.bosch.de/pdf/can2spec.pdf).1320 1321"sja1000: tseg1 1..16 tseg2 1..8 sjw 1..4 brp 1..64 brp-inc 1 clock 8000000"1322 Shows the bit-timing constants of the CAN controller, here the1323 "sja1000". The minimum and maximum values of the time segment 11324 and 2, the synchronisation jump width in units of tq, the1325 bitrate pre-scaler and the CAN system clock frequency in Hz.1326 These constants could be used for user-defined (non-standard)1327 bit-timing calculation algorithms in user-space.1328 1329"re-started bus-errors arbit-lost error-warn error-pass bus-off"1330 Shows the number of restarts, bus and arbitration lost errors,1331 and the state changes to the error-warning, error-passive and1332 bus-off state. RX overrun errors are listed in the "overrun"1333 field of the standard network statistics.1334 1335Setting the CAN Bit-Timing1336~~~~~~~~~~~~~~~~~~~~~~~~~~1337 1338The CAN bit-timing parameters can always be defined in a hardware1339independent format as proposed in the Bosch CAN 2.0 specification1340specifying the arguments "tq", "prop_seg", "phase_seg1", "phase_seg2"1341and "sjw"::1342 1343 $ ip link set canX type can tq 125 prop-seg 6 \1344 phase-seg1 7 phase-seg2 2 sjw 11345 1346If the kernel option CONFIG_CAN_CALC_BITTIMING is enabled, CIA1347recommended CAN bit-timing parameters will be calculated if the bit-1348rate is specified with the argument "bitrate"::1349 1350 $ ip link set canX type can bitrate 1250001351 1352Note that this works fine for the most common CAN controllers with1353standard bit-rates but may *fail* for exotic bit-rates or CAN system1354clock frequencies. Disabling CONFIG_CAN_CALC_BITTIMING saves some1355space and allows user-space tools to solely determine and set the1356bit-timing parameters. The CAN controller specific bit-timing1357constants can be used for that purpose. They are listed by the1358following command::1359 1360 $ ip -details link show can01361 ...1362 sja1000: clock 8000000 tseg1 1..16 tseg2 1..8 sjw 1..4 brp 1..64 brp-inc 11363 1364 1365Starting and Stopping the CAN Network Device1366~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~1367 1368A CAN network device is started or stopped as usual with the command1369"ifconfig canX up/down" or "ip link set canX up/down". Be aware that1370you *must* define proper bit-timing parameters for real CAN devices1371before you can start it to avoid error-prone default settings::1372 1373 $ ip link set canX up type can bitrate 1250001374 1375A device may enter the "bus-off" state if too many errors occurred on1376the CAN bus. Then no more messages are received or sent. An automatic1377bus-off recovery can be enabled by setting the "restart-ms" to a1378non-zero value, e.g.::1379 1380 $ ip link set canX type can restart-ms 1001381 1382Alternatively, the application may realize the "bus-off" condition1383by monitoring CAN error message frames and do a restart when1384appropriate with the command::1385 1386 $ ip link set canX type can restart1387 1388Note that a restart will also create a CAN error message frame (see1389also :ref:`socketcan-network-problem-notifications`).1390 1391 1392.. _socketcan-can-fd-driver:1393 1394CAN FD (Flexible Data Rate) Driver Support1395------------------------------------------1396 1397CAN FD capable CAN controllers support two different bitrates for the1398arbitration phase and the payload phase of the CAN FD frame. Therefore a1399second bit timing has to be specified in order to enable the CAN FD bitrate.1400 1401Additionally CAN FD capable CAN controllers support up to 64 bytes of1402payload. The representation of this length in can_frame.len and1403canfd_frame.len for userspace applications and inside the Linux network1404layer is a plain value from 0 .. 64 instead of the CAN 'data length code'.1405The data length code was a 1:1 mapping to the payload length in the Classical1406CAN frames anyway. The payload length to the bus-relevant DLC mapping is1407only performed inside the CAN drivers, preferably with the helper1408functions can_fd_dlc2len() and can_fd_len2dlc().1409 1410The CAN netdevice driver capabilities can be distinguished by the network1411devices maximum transfer unit (MTU)::1412 1413 MTU = 16 (CAN_MTU) => sizeof(struct can_frame) => Classical CAN device1414 MTU = 72 (CANFD_MTU) => sizeof(struct canfd_frame) => CAN FD capable device1415 1416The CAN device MTU can be retrieved e.g. with a SIOCGIFMTU ioctl() syscall.1417N.B. CAN FD capable devices can also handle and send Classical CAN frames.1418 1419When configuring CAN FD capable CAN controllers an additional 'data' bitrate1420has to be set. This bitrate for the data phase of the CAN FD frame has to be1421at least the bitrate which was configured for the arbitration phase. This1422second bitrate is specified analogue to the first bitrate but the bitrate1423setting keywords for the 'data' bitrate start with 'd' e.g. dbitrate,1424dsample-point, dsjw or dtq and similar settings. When a data bitrate is set1425within the configuration process the controller option "fd on" can be1426specified to enable the CAN FD mode in the CAN controller. This controller1427option also switches the device MTU to 72 (CANFD_MTU).1428 1429The first CAN FD specification presented as whitepaper at the International1430CAN Conference 2012 needed to be improved for data integrity reasons.1431Therefore two CAN FD implementations have to be distinguished today:1432 1433- ISO compliant: The ISO 11898-1:2015 CAN FD implementation (default)1434- non-ISO compliant: The CAN FD implementation following the 2012 whitepaper1435 1436Finally there are three types of CAN FD controllers:1437 14381. ISO compliant (fixed)14392. non-ISO compliant (fixed, like the M_CAN IP core v3.0.1 in m_can.c)14403. ISO/non-ISO CAN FD controllers (switchable, like the PEAK PCAN-USB FD)1441 1442The current ISO/non-ISO mode is announced by the CAN controller driver via1443netlink and displayed by the 'ip' tool (controller option FD-NON-ISO).1444The ISO/non-ISO-mode can be altered by setting 'fd-non-iso {on|off}' for1445switchable CAN FD controllers only.1446 1447Example configuring 500 kbit/s arbitration bitrate and 4 Mbit/s data bitrate::1448 1449 $ ip link set can0 up type can bitrate 500000 sample-point 0.75 \1450 dbitrate 4000000 dsample-point 0.8 fd on1451 $ ip -details link show can01452 5: can0: <NOARP,UP,LOWER_UP,ECHO> mtu 72 qdisc pfifo_fast state UNKNOWN \1453 mode DEFAULT group default qlen 101454 link/can promiscuity 01455 can <FD> state ERROR-ACTIVE (berr-counter tx 0 rx 0) restart-ms 01456 bitrate 500000 sample-point 0.7501457 tq 50 prop-seg 14 phase-seg1 15 phase-seg2 10 sjw 11458 pcan_usb_pro_fd: tseg1 1..64 tseg2 1..16 sjw 1..16 brp 1..1024 \1459 brp-inc 11460 dbitrate 4000000 dsample-point 0.8001461 dtq 12 dprop-seg 7 dphase-seg1 8 dphase-seg2 4 dsjw 11462 pcan_usb_pro_fd: dtseg1 1..16 dtseg2 1..8 dsjw 1..4 dbrp 1..1024 \1463 dbrp-inc 11464 clock 800000001465 1466Example when 'fd-non-iso on' is added on this switchable CAN FD adapter::1467 1468 can <FD,FD-NON-ISO> state ERROR-ACTIVE (berr-counter tx 0 rx 0) restart-ms 01469 1470 1471Supported CAN Hardware1472----------------------1473 1474Please check the "Kconfig" file in "drivers/net/can" to get an actual1475list of the support CAN hardware. On the SocketCAN project website1476(see :ref:`socketcan-resources`) there might be further drivers available, also for1477older kernel versions.1478 1479 1480.. _socketcan-resources:1481 1482SocketCAN Resources1483===================1484 1485The Linux CAN / SocketCAN project resources (project site / mailing list)1486are referenced in the MAINTAINERS file in the Linux source tree.1487Search for CAN NETWORK [LAYERS|DRIVERS].1488 1489Credits1490=======1491 1492- Oliver Hartkopp (PF_CAN core, filters, drivers, bcm, SJA1000 driver)1493- Urs Thuermann (PF_CAN core, kernel integration, socket interfaces, raw, vcan)1494- Jan Kizka (RT-SocketCAN core, Socket-API reconciliation)1495- Wolfgang Grandegger (RT-SocketCAN core & drivers, Raw Socket-API reviews, CAN device driver interface, MSCAN driver)1496- Robert Schwebel (design reviews, PTXdist integration)1497- Marc Kleine-Budde (design reviews, Kernel 2.6 cleanups, drivers)1498- Benedikt Spranger (reviews)1499- Thomas Gleixner (LKML reviews, coding style, posting hints)1500- Andrey Volkov (kernel subtree structure, ioctls, MSCAN driver)1501- Matthias Brukner (first SJA1000 CAN netdevice implementation Q2/2003)1502- Klaus Hitschler (PEAK driver integration)1503- Uwe Koppe (CAN netdevices with PF_PACKET approach)1504- Michael Schulze (driver layer loopback requirement, RT CAN drivers review)1505- Pavel Pisa (Bit-timing calculation)1506- Sascha Hauer (SJA1000 platform driver)1507- Sebastian Haas (SJA1000 EMS PCI driver)1508- Markus Plessing (SJA1000 EMS PCI driver)1509- Per Dalen (SJA1000 Kvaser PCI driver)1510- Sam Ravnborg (reviews, coding style, kbuild help)1511