1=================================== 2SocketCAN - Controller Area Network 3=================================== 4 5Overview / What is SocketCAN 6============================ 7 8The socketcan package is an implementation of CAN protocols 9(Controller Area Network) for Linux. CAN is a networking technology 10which has widespread use in automation, embedded devices, and 11automotive fields. While there have been other CAN implementations 12for Linux based on character devices, SocketCAN uses the Berkeley 13socket API, the Linux network stack and implements the CAN device 14drivers as network interfaces. The CAN socket API has been designed 15as similar as possible to the TCP/IP protocols to allow programmers, 16familiar with network programming, to easily learn how to use CAN 17sockets. 18 19 20.. _socketcan-motivation: 21 22Motivation / Why Using the Socket API 23===================================== 24 25There have been CAN implementations for Linux before SocketCAN so the 26question arises, why we have started another project. Most existing 27implementations come as a device driver for some CAN hardware, they 28are based on character devices and provide comparatively little 29functionality. Usually, there is only a hardware-specific device 30driver which provides a character device interface to send and 31receive raw CAN frames, directly to/from the controller hardware. 32Queueing of frames and higher-level transport protocols like ISO-TP 33have to be implemented in user space applications. Also, most 34character-device implementations support only one single process to 35open the device at a time, similar to a serial interface. Exchanging 36the CAN controller requires employment of another device driver and 37often the need for adaption of large parts of the application to the 38new driver's API. 39 40SocketCAN was designed to overcome all of these limitations. A new 41protocol family has been implemented which provides a socket interface 42to user space applications and which builds upon the Linux network 43layer, enabling use all of the provided queueing functionality. A device 44driver for CAN controller hardware registers itself with the Linux 45network layer as a network device, so that CAN frames from the 46controller can be passed up to the network layer and on to the CAN 47protocol family module and also vice-versa. Also, the protocol family 48module provides an API for transport protocol modules to register, so 49that any number of transport protocols can be loaded or unloaded 50dynamically. In fact, the can core module alone does not provide any 51protocol and cannot be used without loading at least one additional 52protocol module. Multiple sockets can be opened at the same time, 53on different or the same protocol module and they can listen/send 54frames on different or the same CAN IDs. Several sockets listening on 55the same interface for frames with the same CAN ID are all passed the 56same received matching CAN frames. An application wishing to 57communicate using a specific transport protocol, e.g. ISO-TP, just 58selects that protocol when opening the socket, and then can read and 59write application data byte streams, without having to deal with 60CAN-IDs, frames, etc. 61 62Similar functionality visible from user-space could be provided by a 63character device, too, but this would lead to a technically inelegant 64solution for a couple of reasons: 65 66* **Intricate usage:** Instead of passing a protocol argument to 67 socket(2) and using bind(2) to select a CAN interface and CAN ID, an 68 application would have to do all these operations using ioctl(2)s. 69 70* **Code duplication:** A character device cannot make use of the Linux 71 network queueing code, so all that code would have to be duplicated 72 for CAN networking. 73 74* **Abstraction:** In most existing character-device implementations, the 75 hardware-specific device driver for a CAN controller directly 76 provides the character device for the application to work with. 77 This is at least very unusual in Unix systems for both, char and 78 block devices. For example you don't have a character device for a 79 certain UART of a serial interface, a certain sound chip in your 80 computer, a SCSI or IDE controller providing access to your hard 81 disk or tape streamer device. Instead, you have abstraction layers 82 which provide a unified character or block device interface to the 83 application on the one hand, and a interface for hardware-specific 84 device drivers on the other hand. These abstractions are provided 85 by subsystems like the tty layer, the audio subsystem or the SCSI 86 and IDE subsystems for the devices mentioned above. 87 88 The easiest way to implement a CAN device driver is as a character 89 device without such a (complete) abstraction layer, as is done by most 90 existing drivers. The right way, however, would be to add such a 91 layer with all the functionality like registering for certain CAN 92 IDs, supporting several open file descriptors and (de)multiplexing 93 CAN frames between them, (sophisticated) queueing of CAN frames, and 94 providing an API for device drivers to register with. However, then 95 it would be no more difficult, or may be even easier, to use the 96 networking framework provided by the Linux kernel, and this is what 97 SocketCAN does. 98 99The use of the networking framework of the Linux kernel is just the 100natural and most appropriate way to implement CAN for Linux. 101 102 103.. _socketcan-concept: 104 105SocketCAN Concept 106================= 107 108As described in :ref:`socketcan-motivation` the main goal of SocketCAN is to 109provide a socket interface to user space applications which builds 110upon the Linux network layer. In contrast to the commonly known 111TCP/IP and ethernet networking, the CAN bus is a broadcast-only(!) 112medium that has no MAC-layer addressing like ethernet. The CAN-identifier 113(can_id) is used for arbitration on the CAN-bus. Therefore the CAN-IDs 114have to be chosen uniquely on the bus. When designing a CAN-ECU 115network 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 Lists 122------------- 123 124The network transparent access of multiple applications leads to the 125problem that different applications may be interested in the same 126CAN-IDs from the same CAN network interface. The SocketCAN core 127module - which implements the protocol family CAN - provides several 128high efficient receive lists for this reason. If e.g. a user space 129application opens a CAN RAW socket, the raw protocol module itself 130requests the (range of) CAN-IDs from the SocketCAN core that are 131requested by the user. The subscription and unsubscription of 132CAN-IDs can be done for specific CAN interfaces or for all(!) known 133CAN interfaces with the can_rx_(un)register() functions provided to 134CAN protocol modules by the SocketCAN core (see :ref:`socketcan-core-module`). 135To optimize the CPU usage at runtime the receive lists are split up 136into several specific lists per device that match the requested 137filter complexity for a given use-case. 138 139 140.. _socketcan-local-loopback1: 141 142Local Loopback of Sent Frames 143----------------------------- 144 145As known from other networking concepts the data exchanging 146applications may run on the same or different nodes without any 147change (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 the 159example (2) as it would receive in example (1) there is need for 160some kind of local loopback of the sent CAN frames on the appropriate 161node. 162 163The Linux network devices (by default) just can handle the 164transmission and reception of media dependent frames. Due to the 165arbitration on the CAN bus the transmission of a low prio CAN-ID 166may be delayed by the reception of a high prio CAN frame. To 167reflect the correct [#f1]_ traffic on the node the loopback of the sent 168data has to be performed right after a successful transmission. If 169the CAN network interface is not capable of performing the loopback for 170some reason the SocketCAN core can do this task as a fallback solution. 171See :ref:`socketcan-local-loopback1` for details (recommended). 172 173The loopback functionality is enabled by default to reflect standard 174networking behaviour for CAN applications. Due to some requests from 175the RT-SocketCAN group the loopback optionally may be disabled for each 176separate 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 analyser 179 tools like 'candump' or 'cansniffer' on the (same) node. 180 181 182.. _socketcan-network-problem-notifications: 183 184Network Problem Notifications 185----------------------------- 186 187The use of the CAN bus may lead to several problems on the physical 188and media access control layer. Detecting and logging of these lower 189layer problems is a vital requirement for CAN users to identify 190hardware issues on the physical transceiver layer as well as 191arbitration problems and error frames caused by the different 192ECUs. The occurrence of detected errors are important for diagnosis 193and have to be logged together with the exact timestamp. For this 194reason the CAN interface driver can generate so called Error Message 195Frames that can optionally be passed to the user application in the 196same way as other CAN frames. Whenever an error on the physical layer 197or the MAC layer is detected (e.g. by the CAN controller) the driver 198creates an appropriate error message frame. Error messages frames can 199be requested by the user application using the common CAN filter 200mechanisms. Inside this filter definition the (interested) type of 201errors may be selected. The reception of error messages is disabled 202by default. The format of the CAN error message frame is briefly 203described in the Linux header file "include/uapi/linux/can/error.h". 204 205 206How to use SocketCAN 207==================== 208 209Like TCP/IP, you first need to open a socket for communicating over a 210CAN network. Since SocketCAN implements a new protocol family, you 211need to pass PF_CAN as the first argument to the socket(2) system 212call. Currently, there are two CAN protocols to choose from, the raw 213socket 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 would 223normally use the bind(2) system call to bind the socket to a CAN 224interface (which is different from TCP/IP due to different addressing 225- 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 use 227send(2), sendto(2), sendmsg(2) and the recv* counterpart operations 228on the socket as usual. There are also CAN specific socket options 229described below. 230 231The Classical CAN frame structure (aka CAN 2.0B), the CAN FD frame structure 232and the sockaddr structure are defined in include/linux/can.h: 233 234.. code-block:: C 235 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 that 241 * name for legacy support 242 */ 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 be 253used instead of can_dlc. The deprecated can_dlc was misleadingly named as 254it always contained the plain payload length in bytes and not the so called 255'data length code' (DLC). 256 257To pass the raw DLC from/to a Classical CAN network device the len8_dlc 258element can contain values 9 .. 15 when the len element is 8 (the real 259payload length for all DLC values greater or equal to 8). 260 261The alignment of the (linear) payload data[] to a 64bit boundary 262allows the user to define their own structs and unions to easily access 263the CAN payload. There is no given byteorder on the CAN bus by 264default. A read(2) system call on a CAN_RAW socket transfers a 265struct can_frame to the user space. 266 267The sockaddr_can structure has an interface index like the 268PF_PACKET socket, that also binds to a specific interface: 269 270.. code-block:: C 271 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 0 286 * 8 bit: PF 287 * 1 bit: DP 288 * 1 bit: reserved 289 */ 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 to 301be used (example for CAN_RAW sockets without error checking): 302 303.. code-block:: C 304 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 must 322be 0 (zero). In this case the socket receives CAN frames from every 323enabled CAN interface. To determine the originating CAN interface 324the system call recvfrom(2) may be used instead of read(2). To send 325on a socket that is bound to 'any' interface sendto(2) is needed to 326specify the outgoing interface. 327 328Reading CAN frames from a bound CAN_RAW socket (see above) consists 329of reading a struct can_frame: 330 331.. code-block:: C 332 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 interface 355(addr.can_ifindex = 0) it is recommended to use recvfrom(2) if the 356information about the originating CAN interface is needed: 357 358.. code-block:: C 359 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 the 374outgoing interface has to be defined certainly: 375 376.. code-block:: C 377 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 reading 387a message from the socket: 388 389.. code-block:: C 390 391 struct timeval tv; 392 ioctl(s, SIOCGSTAMP, &tv); 393 394The timestamp has a resolution of one microsecond and is set automatically 395at 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 described 400examples. The new CAN FD capable CAN controllers support two different 401bitrates for the arbitration phase and the payload phase of the CAN FD frame 402and up to 64 bytes of payload. This extended payload length breaks all the 403kernel interfaces (ABI) which heavily rely on the CAN frame with fixed eight 404bytes 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 that 406switches the socket into a mode that allows the handling of CAN FD frames 407and Classical CAN frames simultaneously (see :ref:`socketcan-rawfd`). 408 409The struct canfd_frame is defined in include/linux/can.h: 410 411.. code-block:: C 412 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 their 424structures. This allows to handle the different structures very similar. 425When the content of a struct can_frame is copied into a struct canfd_frame 426all 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 length 429code (DLC) of the struct can_frame was used as a length information as the 430length and the DLC has a 1:1 mapping in the range of 0 .. 8. To preserve 431the easy handling of the length information the canfd_frame.len element 432contains a plain length value from 0 .. 64. So both canfd_frame.len and 433can_frame.len are equal and contain a length information and no DLC. 434For details about the distinction of CAN and CAN FD capable devices and 435the 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 transfer 438unit (MTU) of the CAN(FD) network interface and skbuff data length. Two 439definitions are specified for CAN specific MTUs in include/linux/can.h: 440 441.. code-block:: C 442 443 #define CAN_MTU (sizeof(struct can_frame)) == 16 => Classical CAN frame 444 #define CANFD_MTU (sizeof(struct canfd_frame)) == 72 => CAN FD frame 445 446 447.. _socketcan-raw-sockets: 448 449RAW Protocol Sockets with can_filters (SOCK_RAW) 450------------------------------------------------ 451 452Using CAN_RAW sockets is extensively comparable to the commonly 453known access to CAN character devices. To meet the new possibilities 454provided by the multi user SocketCAN approach, some reasonable 455defaults are set at RAW socket binding time: 456 457- The filters are set to exactly one filter receiving everything 458- The socket only receives valid data frames (=> no error message frames) 459- The loopback of sent CAN frames is enabled (see :ref:`socketcan-local-loopback2`) 460- The socket does not receive its own sent frames (in loopback mode) 461 462These default settings may be changed before or after binding the socket. 463To use the referenced definitions of the socket options for CAN_RAW 464sockets, include <linux/can/raw.h>. 465 466 467.. _socketcan-rawfilter: 468 469RAW socket option CAN_RAW_FILTER 470~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 471 472The reception of CAN frames using CAN_RAW sockets can be controlled 473by defining 0 .. n filters with the CAN_RAW_FILTER socket option. 474 475The CAN filter structure is defined in include/linux/can.h: 476 477.. code-block:: C 478 479 struct can_filter { 480 canid_t can_id; 481 canid_t can_mask; 482 }; 483 484A filter matches, when: 485 486.. code-block:: C 487 488 <received_can_id> & mask == can_id & mask 489 490which is analogous to known CAN controllers hardware filter semantics. 491The filter can be inverted in this semantic, when the CAN_INV_FILTER 492bit is set in can_id element of the can_filter structure. In 493contrast to CAN controller hardware filters the user may set 0 .. n 494receive filters for each open socket separately: 495 496.. code-block:: C 497 498 struct can_filter rfilter[2]; 499 500 rfilter[0].can_id = 0x123; 501 rfilter[0].can_mask = CAN_SFF_MASK; 502 rfilter[1].can_id = 0x200; 503 rfilter[1].can_mask = 0x700; 504 505 setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter)); 506 507To disable the reception of CAN frames on the selected CAN_RAW socket: 508 509.. code-block:: C 510 511 setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0); 512 513To set the filters to zero filters is quite obsolete as to not read 514data causes the raw socket to discard the received CAN frames. But 515having this 'send only' use-case we may remove the receive list in the 516Kernel to save a little (really a very little!) CPU usage. 517 518CAN Filter Usage Optimisation 519............................. 520 521The CAN filters are processed in per-device filter lists at CAN frame 522reception time. To reduce the number of checks that need to be performed 523while walking through the filter lists the CAN core provides an optimized 524filter handling when the filter subscription focusses on a single CAN ID. 525 526For the possible 2048 SFF CAN identifiers the identifier is used as an index 527to access the corresponding subscription list without any further checks. 528For the 2^29 possible EFF CAN identifiers a 10 bit XOR folding is used as 529hash function to retrieve the EFF table index. 530 531To benefit from the optimized filters for single CAN identifiers the 532CAN_SFF_MASK or CAN_EFF_MASK have to be set into can_filter.mask together 533with set CAN_EFF_FLAG and CAN_RTR_FLAG bits. A set CAN_EFF_FLAG bit in the 534can_filter.mask makes clear that it matters whether a SFF or EFF CAN ID is 535subscribed. E.g. in the example from above: 536 537.. code-block:: C 538 539 rfilter[0].can_id = 0x123; 540 rfilter[0].can_mask = CAN_SFF_MASK; 541 542both SFF frames with CAN ID 0x123 and EFF frames with 0xXXXXX123 can pass. 543 544To filter for only 0x123 (SFF) and 0x12345678 (EFF) CAN identifiers the 545filter has to be defined in this way to benefit from the optimized filters: 546 547.. code-block:: C 548 549 struct can_filter rfilter[2]; 550 551 rfilter[0].can_id = 0x123; 552 rfilter[0].can_mask = (CAN_EFF_FLAG | CAN_RTR_FLAG | CAN_SFF_MASK); 553 rfilter[1].can_id = 0x12345678 | CAN_EFF_FLAG; 554 rfilter[1].can_mask = (CAN_EFF_FLAG | CAN_RTR_FLAG | CAN_EFF_MASK); 555 556 setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter)); 557 558 559RAW Socket Option CAN_RAW_ERR_FILTER 560~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 561 562As described in :ref:`socketcan-network-problem-notifications` the CAN interface driver can generate so 563called Error Message Frames that can optionally be passed to the user 564application in the same way as other CAN frames. The possible 565errors are divided into different error classes that may be filtered 566using the appropriate error mask. To register for every possible 567error condition CAN_ERR_MASK can be used as value for the error mask. 568The values for the error mask are defined in linux/can/error.h: 569 570.. code-block:: C 571 572 can_err_mask_t err_mask = ( CAN_ERR_TX_TIMEOUT | CAN_ERR_BUSOFF ); 573 574 setsockopt(s, SOL_CAN_RAW, CAN_RAW_ERR_FILTER, 575 &err_mask, sizeof(err_mask)); 576 577 578RAW Socket Option CAN_RAW_LOOPBACK 579~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 580 581To meet multi user needs the local loopback is enabled by default 582(see :ref:`socketcan-local-loopback1` for details). But in some embedded use-cases 583(e.g. when only one application uses the CAN bus) this loopback 584functionality can be disabled (separately for each socket): 585 586.. code-block:: C 587 588 int loopback = 0; /* 0 = disabled, 1 = enabled (default) */ 589 590 setsockopt(s, SOL_CAN_RAW, CAN_RAW_LOOPBACK, &loopback, sizeof(loopback)); 591 592 593RAW socket option CAN_RAW_RECV_OWN_MSGS 594~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 595 596When the local loopback is enabled, all the sent CAN frames are 597looped back to the open CAN sockets that registered for the CAN 598frames' CAN-ID on this given interface to meet the multi user 599needs. The reception of the CAN frames on the same socket that was 600sending the CAN frame is assumed to be unwanted and therefore 601disabled by default. This default behaviour may be changed on 602demand: 603 604.. code-block:: C 605 606 int recv_own_msgs = 1; /* 0 = disabled (default), 1 = enabled */ 607 608 setsockopt(s, SOL_CAN_RAW, CAN_RAW_RECV_OWN_MSGS, 609 &recv_own_msgs, sizeof(recv_own_msgs)); 610 611 612.. _socketcan-rawfd: 613 614RAW Socket Option CAN_RAW_FD_FRAMES 615~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 616 617CAN FD support in CAN_RAW sockets can be enabled with a new socket option 618CAN_RAW_FD_FRAMES which is off by default. When the new socket option is 619not supported by the CAN_RAW socket (e.g. on older kernels), switching the 620CAN_RAW_FD_FRAMES option returns the error -ENOPROTOOPT. 621 622Once CAN_RAW_FD_FRAMES is enabled the application can send both CAN frames 623and CAN FD frames. OTOH the application has to handle CAN and CAN FD frames 624when reading from the socket: 625 626.. code-block:: C 627 628 CAN_RAW_FD_FRAMES enabled: CAN_MTU and CANFD_MTU are allowed 629 CAN_RAW_FD_FRAMES disabled: only CAN_MTU is allowed (default) 630 631Example: 632 633.. code-block:: C 634 635 [ remember: CANFD_MTU == sizeof(struct canfd_frame) ] 636 637 struct canfd_frame cfd; 638 639 nbytes = read(s, &cfd, CANFD_MTU); 640 641 if (nbytes == CANFD_MTU) { 642 printf("got CAN FD frame with length %d\n", cfd.len); 643 /* cfd.flags contains valid data */ 644 } else if (nbytes == CAN_MTU) { 645 printf("got Classical CAN frame with length %d\n", cfd.len); 646 /* cfd.flags is undefined */ 647 } else { 648 fprintf(stderr, "read: invalid CAN(FD) frame\n"); 649 return 1; 650 } 651 652 /* the content can be handled independently from the received MTU size */ 653 654 printf("can_id: %X data length: %d data: ", cfd.can_id, cfd.len); 655 for (i = 0; i < cfd.len; i++) 656 printf("%02X ", cfd.data[i]); 657 658When reading with size CANFD_MTU only returns CAN_MTU bytes that have 659been received from the socket a Classical CAN frame has been read into the 660provided CAN FD structure. Note that the canfd_frame.flags data field is 661not specified in the struct can_frame and therefore it is only valid in 662CANFD_MTU sized CAN FD frames. 663 664Implementation hint for new CAN applications: 665 666To build a CAN FD aware application use struct canfd_frame as basic CAN 667data structure for CAN_RAW based applications. When the application is 668executed on an older Linux kernel and switching the CAN_RAW_FD_FRAMES 669socket option returns an error: No problem. You'll get Classical CAN frames 670or CAN FD frames and can process them the same way. 671 672When sending to CAN devices make sure that the device is capable to handle 673CAN FD frames by checking if the device maximum transfer unit is CANFD_MTU. 674The CAN device MTU can be retrieved e.g. with a SIOCGIFMTU ioctl() syscall. 675 676 677RAW socket option CAN_RAW_JOIN_FILTERS 678~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 679 680The CAN_RAW socket can set multiple CAN identifier specific filters that 681lead to multiple filters in the af_can.c filter processing. These filters 682are indenpendent from each other which leads to logical OR'ed filters when 683applied (see :ref:`socketcan-rawfilter`). 684 685This socket option joines the given CAN filters in the way that only CAN 686frames are passed to user space that matched *all* given CAN filters. The 687semantic for the applied filters is therefore changed to a logical AND. 688 689This is useful especially when the filterset is a combination of filters 690where the CAN_INV_FILTER flag is set in order to notch single CAN IDs or 691CAN ID ranges from the incoming traffic. 692 693 694RAW Socket Returned Message Flags 695~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 696 697When using recvmsg() call, the msg->msg_flags may contain following flags: 698 699MSG_DONTROUTE: 700 set when the received frame was created on the local host. 701 702MSG_CONFIRM: 703 set when the frame was sent via the socket it is received on. 704 This flag can be interpreted as a 'transmission confirmation' when the 705 CAN driver supports the echo of frames on driver level, see 706 :ref:`socketcan-local-loopback1` and :ref:`socketcan-local-loopback2`. 707 In order to receive such messages, CAN_RAW_RECV_OWN_MSGS must be set. 708 709 710Broadcast Manager Protocol Sockets (SOCK_DGRAM) 711----------------------------------------------- 712 713The Broadcast Manager protocol provides a command based configuration 714interface to filter and send (e.g. cyclic) CAN messages in kernel space. 715 716Receive filters can be used to down sample frequent messages; detect events 717such as message contents changes, packet length changes, and do time-out 718monitoring of received messages. 719 720Periodic transmission tasks of CAN frames or a sequence of CAN frames can be 721created and modified at runtime; both the message content and the two 722possible transmit intervals can be altered. 723 724A BCM socket is not intended for sending individual CAN frames using the 725struct can_frame as known from the CAN_RAW socket. Instead a special BCM 726configuration message is defined. The basic BCM configuration message used 727to communicate with the broadcast manager and the available operations are 728defined in the linux/can/bcm.h include. The BCM message consists of a 729message header with a command ('opcode') followed by zero or more CAN frames. 730The broadcast manager sends responses to user space in the same form: 731 732.. code-block:: C 733 734 struct bcm_msg_head { 735 __u32 opcode; /* command */ 736 __u32 flags; /* special flags */ 737 __u32 count; /* run 'count' times with ival1 */ 738 struct timeval ival1, ival2; /* count and subsequent interval */ 739 canid_t can_id; /* unique can_id for task */ 740 __u32 nframes; /* number of can_frames following */ 741 struct can_frame frames[0]; 742 }; 743 744The aligned payload 'frames' uses the same basic CAN frame structure defined 745at the beginning of :ref:`socketcan-rawfd` and in the include/linux/can.h include. All 746messages to the broadcast manager from user space have this structure. 747 748Note a CAN_BCM socket must be connected instead of bound after socket 749creation (example without error checking): 750 751.. code-block:: C 752 753 int s; 754 struct sockaddr_can addr; 755 struct ifreq ifr; 756 757 s = socket(PF_CAN, SOCK_DGRAM, CAN_BCM); 758 759 strcpy(ifr.ifr_name, "can0"); 760 ioctl(s, SIOCGIFINDEX, &ifr); 761 762 addr.can_family = AF_CAN; 763 addr.can_ifindex = ifr.ifr_ifindex; 764 765 connect(s, (struct sockaddr *)&addr, sizeof(addr)); 766 767 (..) 768 769The broadcast manager socket is able to handle any number of in flight 770transmissions or receive filters concurrently. The different RX/TX jobs are 771distinguished by the unique can_id in each BCM message. However additional 772CAN_BCM sockets are recommended to communicate on multiple CAN interfaces. 773When the broadcast manager socket is bound to 'any' CAN interface (=> the 774interface index is set to zero) the configured receive filters apply to any 775CAN interface unless the sendto() syscall is used to overrule the 'any' CAN 776interface index. When using recvfrom() instead of read() to retrieve BCM 777socket messages the originating CAN interface is provided in can_ifindex. 778 779 780Broadcast Manager Operations 781~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 782 783The opcode defines the operation for the broadcast manager to carry out, 784or details the broadcast managers response to several events, including 785user requests. 786 787Transmit Operations (user space to broadcast manager): 788 789TX_SETUP: 790 Create (cyclic) transmission task. 791 792TX_DELETE: 793 Remove (cyclic) transmission task, requires only can_id. 794 795TX_READ: 796 Read properties of (cyclic) transmission task for can_id. 797 798TX_SEND: 799 Send one CAN frame. 800 801Transmit Responses (broadcast manager to user space): 802 803TX_STATUS: 804 Reply to TX_READ request (transmission task configuration). 805 806TX_EXPIRED: 807 Notification when counter finishes sending at initial interval 808 'ival1'. Requires the TX_COUNTEVT flag to be set at TX_SETUP. 809 810Receive Operations (user space to broadcast manager): 811 812RX_SETUP: 813 Create RX content filter subscription. 814 815RX_DELETE: 816 Remove RX content filter subscription, requires only can_id. 817 818RX_READ: 819 Read properties of RX content filter subscription for can_id. 820 821Receive Responses (broadcast manager to user space): 822 823RX_STATUS: 824 Reply to RX_READ request (filter task configuration). 825 826RX_TIMEOUT: 827 Cyclic message is detected to be absent (timer ival1 expired). 828 829RX_CHANGED: 830 BCM message with updated CAN frame (detected content change). 831 Sent on first message received or on receipt of revised CAN messages. 832 833 834Broadcast Manager Message Flags 835~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 836 837When sending a message to the broadcast manager the 'flags' element may 838contain the following flag definitions which influence the behaviour: 839 840SETTIMER: 841 Set the values of ival1, ival2 and count 842 843STARTTIMER: 844 Start the timer with the actual values of ival1, ival2 845 and count. Starting the timer leads simultaneously to emit a CAN frame. 846 847TX_COUNTEVT: 848 Create the message TX_EXPIRED when count expires 849 850TX_ANNOUNCE: 851 A change of data by the process is emitted immediately. 852 853TX_CP_CAN_ID: 854 Copies the can_id from the message header to each 855 subsequent frame in frames. This is intended as usage simplification. For 856 TX tasks the unique can_id from the message header may differ from the 857 can_id(s) stored for transmission in the subsequent struct can_frame(s). 858 859RX_FILTER_ID: 860 Filter by can_id alone, no frames required (nframes=0). 861 862RX_CHECK_DLC: 863 A change of the DLC leads to an RX_CHANGED. 864 865RX_NO_AUTOTIMER: 866 Prevent automatically starting the timeout monitor. 867 868RX_ANNOUNCE_RESUME: 869 If passed at RX_SETUP and a receive timeout occurred, a 870 RX_CHANGED message will be generated when the (cyclic) receive restarts. 871 872TX_RESET_MULTI_IDX: 873 Reset the index for the multiple frame transmission. 874 875RX_RTR_FRAME: 876 Send reply for RTR-request (placed in op->frames[0]). 877 878CAN_FD_FRAME: 879 The CAN frames following the bcm_msg_head are struct canfd_frame's 880 881Broadcast Manager Transmission Timers 882~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 883 884Periodic transmission configurations may use up to two interval timers. 885In this case the BCM sends a number of messages ('count') at an interval 886'ival1', then continuing to send at another given interval 'ival2'. When 887only one timer is needed 'count' is set to zero and only 'ival2' is used. 888When SET_TIMER and START_TIMER flag were set the timers are activated. 889The timer values can be altered at runtime when only SET_TIMER is set. 890 891 892Broadcast Manager message sequence transmission 893~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 894 895Up to 256 CAN frames can be transmitted in a sequence in the case of a cyclic 896TX task configuration. The number of CAN frames is provided in the 'nframes' 897element of the BCM message head. The defined number of CAN frames are added 898as array to the TX_SETUP BCM configuration message: 899 900.. code-block:: C 901 902 /* create a struct to set up a sequence of four CAN frames */ 903 struct { 904 struct bcm_msg_head msg_head; 905 struct can_frame frame[4]; 906 } mytxmsg; 907 908 (..) 909 mytxmsg.msg_head.nframes = 4; 910 (..) 911 912 write(s, &mytxmsg, sizeof(mytxmsg)); 913 914With every transmission the index in the array of CAN frames is increased 915and set to zero at index overflow. 916 917 918Broadcast Manager Receive Filter Timers 919~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 920 921The timer values ival1 or ival2 may be set to non-zero values at RX_SETUP. 922When the SET_TIMER flag is set the timers are enabled: 923 924ival1: 925 Send RX_TIMEOUT when a received message is not received again within 926 the given time. When START_TIMER is set at RX_SETUP the timeout detection 927 is activated directly - even without a former CAN frame reception. 928 929ival2: 930 Throttle the received message rate down to the value of ival2. This 931 is useful to reduce messages for the application when the signal inside the 932 CAN frame is stateless as state changes within the ival2 periode may get 933 lost. 934 935Broadcast Manager Multiplex Message Receive Filter 936~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 937 938To filter for content changes in multiplex message sequences an array of more 939than one CAN frames can be passed in a RX_SETUP configuration message. The 940data bytes of the first CAN frame contain the mask of relevant bits that 941have to match in the subsequent CAN frames with the received CAN frame. 942If one of the subsequent CAN frames is matching the bits in that frame data 943mark the relevant content to be compared with the previous received content. 944Up to 257 CAN frames (multiplex filter bit mask CAN frame plus 256 CAN 945filters) can be added as array to the TX_SETUP BCM configuration message: 946 947.. code-block:: C 948 949 /* usually used to clear CAN frame data[] - beware of endian problems! */ 950 #define U64_DATA(p) (*(unsigned long long*)(p)->data) 951 952 struct { 953 struct bcm_msg_head msg_head; 954 struct can_frame frame[5]; 955 } msg; 956 957 msg.msg_head.opcode = RX_SETUP; 958 msg.msg_head.can_id = 0x42; 959 msg.msg_head.flags = 0; 960 msg.msg_head.nframes = 5; 961 U64_DATA(&msg.frame[0]) = 0xFF00000000000000ULL; /* MUX mask */ 962 U64_DATA(&msg.frame[1]) = 0x01000000000000FFULL; /* data mask (MUX 0x01) */ 963 U64_DATA(&msg.frame[2]) = 0x0200FFFF000000FFULL; /* data mask (MUX 0x02) */ 964 U64_DATA(&msg.frame[3]) = 0x330000FFFFFF0003ULL; /* data mask (MUX 0x33) */ 965 U64_DATA(&msg.frame[4]) = 0x4F07FC0FF0000000ULL; /* data mask (MUX 0x4F) */ 966 967 write(s, &msg, sizeof(msg)); 968 969 970Broadcast Manager CAN FD Support 971~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 972 973The programming API of the CAN_BCM depends on struct can_frame which is 974given as array directly behind the bcm_msg_head structure. To follow this 975schema for the CAN FD frames a new flag 'CAN_FD_FRAME' in the bcm_msg_head 976flags indicates that the concatenated CAN frame structures behind the 977bcm_msg_head are defined as struct canfd_frame: 978 979.. code-block:: C 980 981 struct { 982 struct bcm_msg_head msg_head; 983 struct canfd_frame frame[5]; 984 } msg; 985 986 msg.msg_head.opcode = RX_SETUP; 987 msg.msg_head.can_id = 0x42; 988 msg.msg_head.flags = CAN_FD_FRAME; 989 msg.msg_head.nframes = 5; 990 (..) 991 992When using CAN FD frames for multiplex filtering the MUX mask is still 993expected in the first 64 bit of the struct canfd_frame data section. 994 995 996Connected Transport Protocols (SOCK_SEQPACKET) 997---------------------------------------------- 998 999(to be written) 1000 1001 1002Unconnected Transport Protocols (SOCK_DGRAM) 1003-------------------------------------------- 1004 1005(to be written) 1006 1007 1008.. _socketcan-core-module: 1009 1010SocketCAN Core Module 1011===================== 1012 1013The SocketCAN core module implements the protocol family 1014PF_CAN. CAN protocol modules are loaded by the core module at 1015runtime. The core module provides an interface for CAN protocol 1016modules to subscribe needed CAN IDs (see :ref:`socketcan-receive-lists`). 1017 1018 1019can.ko Module Params 1020-------------------- 1021 1022- **stats_timer**: 1023 To calculate the SocketCAN core statistics 1024 (e.g. current/maximum frames per second) this 1 second timer is 1025 invoked at can.ko module start time by default. This timer can be 1026 disabled by using stattimer=0 on the module commandline. 1027 1028- **debug**: 1029 (removed since SocketCAN SVN r546) 1030 1031 1032procfs content 1033-------------- 1034 1035As described in :ref:`socketcan-receive-lists` the SocketCAN core uses several filter 1036lists to deliver received CAN frames to CAN protocol modules. These 1037receive lists, their filters and the count of filter matches can be 1038checked in the appropriate receive list. All entries contain the 1039device and a protocol module identifier:: 1040 1041 foo@bar:~$ cat /proc/net/can/rcvlist_all 1042 1043 receive list 'rx_all': 1044 (vcan3: no entry) 1045 (vcan2: no entry) 1046 (vcan1: no entry) 1047 device can_id can_mask function userdata matches ident 1048 vcan0 000 00000000 f88e6370 f6c6f400 0 raw 1049 (any: no entry) 1050 1051In this example an application requests any CAN traffic from vcan0:: 1052 1053 rcvlist_all - list for unfiltered entries (no filter operations) 1054 rcvlist_eff - list for single extended frame (EFF) entries 1055 rcvlist_err - list for error message frames masks 1056 rcvlist_fil - list for mask/value filters 1057 rcvlist_inv - list for mask/value filters (inverse semantic) 1058 rcvlist_sff - list for single standard frame (SFF) entries 1059 1060Additional procfs files in /proc/net/can:: 1061 1062 stats - SocketCAN core statistics (rx/tx frames, match ratios, ...) 1063 reset_stats - manual statistic reset 1064 version - prints SocketCAN core and ABI version (removed in Linux 5.10) 1065 1066 1067Writing Own CAN Protocol Modules 1068-------------------------------- 1069 1070To implement a new protocol in the protocol family PF_CAN a new 1071protocol has to be defined in include/linux/can.h . 1072The prototypes and definitions to use the SocketCAN core can be 1073accessed by including include/linux/can/core.h . 1074In addition to functions that register the CAN protocol and the 1075CAN device notifier chain there are functions to subscribe CAN 1076frames received by CAN interfaces and to send CAN frames:: 1077 1078 can_rx_register - subscribe CAN frames from a specific interface 1079 can_rx_unregister - unsubscribe CAN frames from a specific interface 1080 can_send - transmit a CAN frame (optional with local loopback) 1081 1082For details see the kerneldoc documentation in net/can/af_can.c or 1083the source code of net/can/raw.c or net/can/bcm.c . 1084 1085 1086CAN Network Drivers 1087=================== 1088 1089Writing a CAN network device driver is much easier than writing a 1090CAN character device driver. Similar to other known network device 1091drivers you mainly have to deal with: 1092 1093- TX: Put the CAN frame from the socket buffer to the CAN controller. 1094- RX: Put the CAN frame from the CAN controller to the socket buffer. 1095 1096See e.g. at Documentation/networking/netdevices.rst . The differences 1097for writing CAN network device driver are described below: 1098 1099 1100General Settings 1101---------------- 1102 1103.. code-block:: C 1104 1105 dev->type = ARPHRD_CAN; /* the netdevice hardware type */ 1106 dev->flags = IFF_NOARP; /* CAN has no arp */ 1107 1108 dev->mtu = CAN_MTU; /* sizeof(struct can_frame) -> Classical CAN interface */ 1109 1110 or alternative, when the controller supports CAN with flexible data rate: 1111 dev->mtu = CANFD_MTU; /* sizeof(struct canfd_frame) -> CAN FD interface */ 1112 1113The struct can_frame or struct canfd_frame is the payload of each socket 1114buffer (skbuff) in the protocol family PF_CAN. 1115 1116 1117.. _socketcan-local-loopback2: 1118 1119Local Loopback of Sent Frames 1120----------------------------- 1121 1122As described in :ref:`socketcan-local-loopback1` the CAN network device driver should 1123support a local loopback functionality similar to the local echo 1124e.g. of tty devices. In this case the driver flag IFF_ECHO has to be 1125set to prevent the PF_CAN core from locally echoing sent frames 1126(aka loopback) as fallback solution:: 1127 1128 dev->flags = (IFF_NOARP | IFF_ECHO); 1129 1130 1131CAN Controller Hardware Filters 1132------------------------------- 1133 1134To reduce the interrupt load on deep embedded systems some CAN 1135controllers support the filtering of CAN IDs or ranges of CAN IDs. 1136These hardware filter capabilities vary from controller to 1137controller and have to be identified as not feasible in a multi-user 1138networking approach. The use of the very controller specific 1139hardware filters could make sense in a very dedicated use-case, as a 1140filter on driver level would affect all users in the multi-user 1141system. The high efficient filter sets inside the PF_CAN core allow 1142to set different multiple filters for each socket separately. 1143Therefore the use of hardware filters goes to the category 'handmade 1144tuning on deep embedded systems'. The author is running a MPC603e 1145@133MHz with four SJA1000 CAN controllers from 2002 under heavy bus 1146load without any problems ... 1147 1148 1149The Virtual CAN Driver (vcan) 1150----------------------------- 1151 1152Similar to the network loopback devices, vcan offers a virtual local 1153CAN interface. A full qualified address on CAN consists of 1154 1155- a unique CAN Identifier (CAN ID) 1156- the CAN bus this CAN ID is transmitted on (e.g. can0) 1157 1158so in common use cases more than one virtual CAN interface is needed. 1159 1160The virtual CAN interfaces allow the transmission and reception of CAN 1161frames without real CAN controller hardware. Virtual CAN network 1162devices are usually named 'vcanX', like vcan0 vcan1 vcan2 ... 1163When compiled as a module the virtual CAN driver module is called vcan.ko 1164 1165Since Linux Kernel version 2.6.24 the vcan driver supports the Kernel 1166netlink interface to create vcan network devices. The creation and 1167removal of vcan network devices can be managed with the ip(8) tool:: 1168 1169 - Create a virtual CAN network interface: 1170 $ ip link add type vcan 1171 1172 - Create a virtual CAN network interface with a specific name 'vcan42': 1173 $ ip link add dev vcan42 type vcan 1174 1175 - Remove a (virtual CAN) network interface 'vcan42': 1176 $ ip link del vcan42 1177 1178 1179The CAN Network Device Driver Interface 1180--------------------------------------- 1181 1182The CAN network device driver interface provides a generic interface 1183to setup, configure and monitor CAN network devices. The user can then 1184configure the CAN device, like setting the bit-timing parameters, via 1185the netlink interface using the program "ip" from the "IPROUTE2" 1186utility suite. The following chapter describes briefly how to use it. 1187Furthermore, the interface uses a common data structure and exports a 1188set of common functions, which all real CAN network device drivers 1189should use. Please have a look to the SJA1000 or MSCAN driver to 1190understand how to use them. The name of the module is can-dev.ko. 1191 1192 1193Netlink interface to set/get devices properties 1194~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1195 1196The CAN device must be configured via netlink interface. The supported 1197netlink message types are defined and briefly described in 1198"include/linux/can/netlink.h". CAN link support for the program "ip" 1199of the IPROUTE2 utility suite is available and it can be used as shown 1200below: 1201 1202Setting CAN device properties:: 1203 1204 $ ip link set can0 type can help 1205 Usage: ip link set DEVICE type can 1206 [ bitrate BITRATE [ sample-point SAMPLE-POINT] ] | 1207 [ tq TQ prop-seg PROP_SEG phase-seg1 PHASE-SEG1 1208 phase-seg2 PHASE-SEG2 [ sjw SJW ] ] 1209 1210 [ dbitrate BITRATE [ dsample-point SAMPLE-POINT] ] | 1211 [ dtq TQ dprop-seg PROP_SEG dphase-seg1 PHASE-SEG1 1212 dphase-seg2 PHASE-SEG2 [ dsjw SJW ] ] 1213 1214 [ loopback { on | off } ] 1215 [ listen-only { on | off } ] 1216 [ triple-sampling { on | off } ] 1217 [ one-shot { on | off } ] 1218 [ berr-reporting { on | off } ] 1219 [ fd { on | off } ] 1220 [ fd-non-iso { on | off } ] 1221 [ presume-ack { on | off } ] 1222 [ cc-len8-dlc { on | off } ] 1223 1224 [ restart-ms TIME-MS ] 1225 [ restart ] 1226 1227 Where: BITRATE := { 1..1000000 } 1228 SAMPLE-POINT := { 0.000..0.999 } 1229 TQ := { NUMBER } 1230 PROP-SEG := { 1..8 } 1231 PHASE-SEG1 := { 1..8 } 1232 PHASE-SEG2 := { 1..8 } 1233 SJW := { 1..4 } 1234 RESTART-MS := { 0 | NUMBER } 1235 1236Display CAN device details and statistics:: 1237 1238 $ ip -details -statistics link show can0 1239 2: can0: <NOARP,UP,LOWER_UP,ECHO> mtu 16 qdisc pfifo_fast state UP qlen 10 1240 link/can 1241 can <TRIPLE-SAMPLING> state ERROR-ACTIVE restart-ms 100 1242 bitrate 125000 sample_point 0.875 1243 tq 125 prop-seg 6 phase-seg1 7 phase-seg2 2 sjw 1 1244 sja1000: tseg1 1..16 tseg2 1..8 sjw 1..4 brp 1..64 brp-inc 1 1245 clock 8000000 1246 re-started bus-errors arbit-lost error-warn error-pass bus-off 1247 41 17457 0 41 42 41 1248 RX: bytes packets errors dropped overrun mcast 1249 140859 17608 17457 0 0 0 1250 TX: bytes packets errors dropped carrier collsns 1251 861 112 0 41 0 0 1252 1253More info to the above output: 1254 1255"<TRIPLE-SAMPLING>" 1256 Shows the list of selected CAN controller modes: LOOPBACK, 1257 LISTEN-ONLY, or TRIPLE-SAMPLING. 1258 1259"state ERROR-ACTIVE" 1260 The current state of the CAN controller: "ERROR-ACTIVE", 1261 "ERROR-WARNING", "ERROR-PASSIVE", "BUS-OFF" or "STOPPED" 1262 1263"restart-ms 100" 1264 Automatic restart delay time. If set to a non-zero value, a 1265 restart of the CAN controller will be triggered automatically 1266 in case of a bus-off condition after the specified delay time 1267 in milliseconds. By default it's off. 1268 1269"bitrate 125000 sample-point 0.875" 1270 Shows the real bit-rate in bits/sec and the sample-point in the 1271 range 0.000..0.999. If the calculation of bit-timing parameters 1272 is enabled in the kernel (CONFIG_CAN_CALC_BITTIMING=y), the 1273 bit-timing can be defined by setting the "bitrate" argument. 1274 Optionally the "sample-point" can be specified. By default it's 1275 0.000 assuming CIA-recommended sample-points. 1276 1277"tq 125 prop-seg 6 phase-seg1 7 phase-seg2 2 sjw 1" 1278 Shows the time quanta in ns, propagation segment, phase buffer 1279 segment 1 and 2 and the synchronisation jump width in units of 1280 tq. They allow to define the CAN bit-timing in a hardware 1281 independent format as proposed by the Bosch CAN 2.0 spec (see 1282 chapter 8 of http://www.semiconductors.bosch.de/pdf/can2spec.pdf). 1283 1284"sja1000: tseg1 1..16 tseg2 1..8 sjw 1..4 brp 1..64 brp-inc 1 clock 8000000" 1285 Shows the bit-timing constants of the CAN controller, here the 1286 "sja1000". The minimum and maximum values of the time segment 1 1287 and 2, the synchronisation jump width in units of tq, the 1288 bitrate pre-scaler and the CAN system clock frequency in Hz. 1289 These constants could be used for user-defined (non-standard) 1290 bit-timing calculation algorithms in user-space. 1291 1292"re-started bus-errors arbit-lost error-warn error-pass bus-off" 1293 Shows the number of restarts, bus and arbitration lost errors, 1294 and the state changes to the error-warning, error-passive and 1295 bus-off state. RX overrun errors are listed in the "overrun" 1296 field of the standard network statistics. 1297 1298Setting the CAN Bit-Timing 1299~~~~~~~~~~~~~~~~~~~~~~~~~~ 1300 1301The CAN bit-timing parameters can always be defined in a hardware 1302independent format as proposed in the Bosch CAN 2.0 specification 1303specifying the arguments "tq", "prop_seg", "phase_seg1", "phase_seg2" 1304and "sjw":: 1305 1306 $ ip link set canX type can tq 125 prop-seg 6 \ 1307 phase-seg1 7 phase-seg2 2 sjw 1 1308 1309If the kernel option CONFIG_CAN_CALC_BITTIMING is enabled, CIA 1310recommended CAN bit-timing parameters will be calculated if the bit- 1311rate is specified with the argument "bitrate":: 1312 1313 $ ip link set canX type can bitrate 125000 1314 1315Note that this works fine for the most common CAN controllers with 1316standard bit-rates but may *fail* for exotic bit-rates or CAN system 1317clock frequencies. Disabling CONFIG_CAN_CALC_BITTIMING saves some 1318space and allows user-space tools to solely determine and set the 1319bit-timing parameters. The CAN controller specific bit-timing 1320constants can be used for that purpose. They are listed by the 1321following command:: 1322 1323 $ ip -details link show can0 1324 ... 1325 sja1000: clock 8000000 tseg1 1..16 tseg2 1..8 sjw 1..4 brp 1..64 brp-inc 1 1326 1327 1328Starting and Stopping the CAN Network Device 1329~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1330 1331A CAN network device is started or stopped as usual with the command 1332"ifconfig canX up/down" or "ip link set canX up/down". Be aware that 1333you *must* define proper bit-timing parameters for real CAN devices 1334before you can start it to avoid error-prone default settings:: 1335 1336 $ ip link set canX up type can bitrate 125000 1337 1338A device may enter the "bus-off" state if too many errors occurred on 1339the CAN bus. Then no more messages are received or sent. An automatic 1340bus-off recovery can be enabled by setting the "restart-ms" to a 1341non-zero value, e.g.:: 1342 1343 $ ip link set canX type can restart-ms 100 1344 1345Alternatively, the application may realize the "bus-off" condition 1346by monitoring CAN error message frames and do a restart when 1347appropriate with the command:: 1348 1349 $ ip link set canX type can restart 1350 1351Note that a restart will also create a CAN error message frame (see 1352also :ref:`socketcan-network-problem-notifications`). 1353 1354 1355.. _socketcan-can-fd-driver: 1356 1357CAN FD (Flexible Data Rate) Driver Support 1358------------------------------------------ 1359 1360CAN FD capable CAN controllers support two different bitrates for the 1361arbitration phase and the payload phase of the CAN FD frame. Therefore a 1362second bit timing has to be specified in order to enable the CAN FD bitrate. 1363 1364Additionally CAN FD capable CAN controllers support up to 64 bytes of 1365payload. The representation of this length in can_frame.len and 1366canfd_frame.len for userspace applications and inside the Linux network 1367layer is a plain value from 0 .. 64 instead of the CAN 'data length code'. 1368The data length code was a 1:1 mapping to the payload length in the Classical 1369CAN frames anyway. The payload length to the bus-relevant DLC mapping is 1370only performed inside the CAN drivers, preferably with the helper 1371functions can_fd_dlc2len() and can_fd_len2dlc(). 1372 1373The CAN netdevice driver capabilities can be distinguished by the network 1374devices maximum transfer unit (MTU):: 1375 1376 MTU = 16 (CAN_MTU) => sizeof(struct can_frame) => Classical CAN device 1377 MTU = 72 (CANFD_MTU) => sizeof(struct canfd_frame) => CAN FD capable device 1378 1379The CAN device MTU can be retrieved e.g. with a SIOCGIFMTU ioctl() syscall. 1380N.B. CAN FD capable devices can also handle and send Classical CAN frames. 1381 1382When configuring CAN FD capable CAN controllers an additional 'data' bitrate 1383has to be set. This bitrate for the data phase of the CAN FD frame has to be 1384at least the bitrate which was configured for the arbitration phase. This 1385second bitrate is specified analogue to the first bitrate but the bitrate 1386setting keywords for the 'data' bitrate start with 'd' e.g. dbitrate, 1387dsample-point, dsjw or dtq and similar settings. When a data bitrate is set 1388within the configuration process the controller option "fd on" can be 1389specified to enable the CAN FD mode in the CAN controller. This controller 1390option also switches the device MTU to 72 (CANFD_MTU). 1391 1392The first CAN FD specification presented as whitepaper at the International 1393CAN Conference 2012 needed to be improved for data integrity reasons. 1394Therefore two CAN FD implementations have to be distinguished today: 1395 1396- ISO compliant: The ISO 11898-1:2015 CAN FD implementation (default) 1397- non-ISO compliant: The CAN FD implementation following the 2012 whitepaper 1398 1399Finally there are three types of CAN FD controllers: 1400 14011. ISO compliant (fixed) 14022. non-ISO compliant (fixed, like the M_CAN IP core v3.0.1 in m_can.c) 14033. ISO/non-ISO CAN FD controllers (switchable, like the PEAK PCAN-USB FD) 1404 1405The current ISO/non-ISO mode is announced by the CAN controller driver via 1406netlink and displayed by the 'ip' tool (controller option FD-NON-ISO). 1407The ISO/non-ISO-mode can be altered by setting 'fd-non-iso {on|off}' for 1408switchable CAN FD controllers only. 1409 1410Example configuring 500 kbit/s arbitration bitrate and 4 Mbit/s data bitrate:: 1411 1412 $ ip link set can0 up type can bitrate 500000 sample-point 0.75 \ 1413 dbitrate 4000000 dsample-point 0.8 fd on 1414 $ ip -details link show can0 1415 5: can0: <NOARP,UP,LOWER_UP,ECHO> mtu 72 qdisc pfifo_fast state UNKNOWN \ 1416 mode DEFAULT group default qlen 10 1417 link/can promiscuity 0 1418 can <FD> state ERROR-ACTIVE (berr-counter tx 0 rx 0) restart-ms 0 1419 bitrate 500000 sample-point 0.750 1420 tq 50 prop-seg 14 phase-seg1 15 phase-seg2 10 sjw 1 1421 pcan_usb_pro_fd: tseg1 1..64 tseg2 1..16 sjw 1..16 brp 1..1024 \ 1422 brp-inc 1 1423 dbitrate 4000000 dsample-point 0.800 1424 dtq 12 dprop-seg 7 dphase-seg1 8 dphase-seg2 4 dsjw 1 1425 pcan_usb_pro_fd: dtseg1 1..16 dtseg2 1..8 dsjw 1..4 dbrp 1..1024 \ 1426 dbrp-inc 1 1427 clock 80000000 1428 1429Example when 'fd-non-iso on' is added on this switchable CAN FD adapter:: 1430 1431 can <FD,FD-NON-ISO> state ERROR-ACTIVE (berr-counter tx 0 rx 0) restart-ms 0 1432 1433 1434Supported CAN Hardware 1435---------------------- 1436 1437Please check the "Kconfig" file in "drivers/net/can" to get an actual 1438list of the support CAN hardware. On the SocketCAN project website 1439(see :ref:`socketcan-resources`) there might be further drivers available, also for 1440older kernel versions. 1441 1442 1443.. _socketcan-resources: 1444 1445SocketCAN Resources 1446=================== 1447 1448The Linux CAN / SocketCAN project resources (project site / mailing list) 1449are referenced in the MAINTAINERS file in the Linux source tree. 1450Search for CAN NETWORK [LAYERS|DRIVERS]. 1451 1452Credits 1453======= 1454 1455- Oliver Hartkopp (PF_CAN core, filters, drivers, bcm, SJA1000 driver) 1456- Urs Thuermann (PF_CAN core, kernel integration, socket interfaces, raw, vcan) 1457- Jan Kizka (RT-SocketCAN core, Socket-API reconciliation) 1458- Wolfgang Grandegger (RT-SocketCAN core & drivers, Raw Socket-API reviews, CAN device driver interface, MSCAN driver) 1459- Robert Schwebel (design reviews, PTXdist integration) 1460- Marc Kleine-Budde (design reviews, Kernel 2.6 cleanups, drivers) 1461- Benedikt Spranger (reviews) 1462- Thomas Gleixner (LKML reviews, coding style, posting hints) 1463- Andrey Volkov (kernel subtree structure, ioctls, MSCAN driver) 1464- Matthias Brukner (first SJA1000 CAN netdevice implementation Q2/2003) 1465- Klaus Hitschler (PEAK driver integration) 1466- Uwe Koppe (CAN netdevices with PF_PACKET approach) 1467- Michael Schulze (driver layer loopback requirement, RT CAN drivers review) 1468- Pavel Pisa (Bit-timing calculation) 1469- Sascha Hauer (SJA1000 platform driver) 1470- Sebastian Haas (SJA1000 EMS PCI driver) 1471- Markus Plessing (SJA1000 EMS PCI driver) 1472- Per Dalen (SJA1000 Kvaser PCI driver) 1473- Sam Ravnborg (reviews, coding style, kbuild help) 1474