阿q 我手持钢鞭将你打:CAN Readme-linux

来源:百度文库 编辑:九乡新闻网 时间:2024/04/29 00:17:49
============================================================================can.txtReadme file for the Controller Area Network Protocol Family (aka Socket CAN)This file contains1 Overview / What is Socket CAN2 Motivation / Why using the socket API3 Socket CAN concept3.1 receive lists3.2 local loopback of sent frames3.3 network security issues (capabilities)3.4 network problem notifications4 How to use Socket CAN4.1 RAW protocol sockets with can_filters (SOCK_RAW)4.1.1 RAW socket option CAN_RAW_FILTER4.1.2 RAW socket option CAN_RAW_ERR_FILTER4.1.3 RAW socket option CAN_RAW_LOOPBACK4.1.4 RAW socket option CAN_RAW_RECV_OWN_MSGS4.2 Broadcast Manager protocol sockets (SOCK_DGRAM)4.3 connected transport protocols (SOCK_SEQPACKET)4.4 unconnected transport protocols (SOCK_DGRAM)5 Socket CAN core module5.1 can.ko module params5.2 procfs content5.3 writing own CAN protocol modules6 CAN network drivers6.1 general settings6.2 local loopback of sent frames6.3 CAN controller hardware filters6.4 The virtual CAN driver (vcan)6.5 The CAN network device driver interface6.5.1 Netlink interface to set/get devices properties6.5.2 Setting the CAN bit-timing6.5.3 Starting and stopping the CAN network device6.6 supported CAN hardware7 Socket CAN resources8 Credits============================================================================1. Overview / What is Socket CAN--------------------------------The socketcan package is an implementation of CAN protocols(Controller Area Network) for Linux.  CAN is a networking technologywhich has widespread use in automation, embedded devices, andautomotive fields.  While there have been other CAN implementationsfor Linux based on character devices, Socket CAN uses the Berkeleysocket API, the Linux network stack and implements the CAN devicedrivers as network interfaces.  The CAN socket API has been designedas similar as possible to the TCP/IP protocols to allow programmers,familiar with network programming, to easily learn how to use CANsockets.2. Motivation / Why using the socket API----------------------------------------There have been CAN implementations for Linux before Socket CAN so thequestion arises, why we have started another project.  Most existingimplementations come as a device driver for some CAN hardware, theyare based on character devices and provide comparatively littlefunctionality.  Usually, there is only a hardware-specific devicedriver which provides a character device interface to send andreceive raw CAN frames, directly to/from the controller hardware.Queueing of frames and higher-level transport protocols like ISO-TPhave to be implemented in user space applications.  Also, mostcharacter-device implementations support only one single process toopen the device at a time, similar to a serial interface.  Exchangingthe CAN controller requires employment of another device driver andoften the need for adaption of large parts of the application to thenew driver's API.Socket CAN was designed to overcome all of these limitations.  A newprotocol family has been implemented which provides a socket interfaceto user space applications and which builds upon the Linux networklayer, so to use all of the provided queueing functionality.  A devicedriver for CAN controller hardware registers itself with the Linuxnetwork layer as a network device, so that CAN frames from thecontroller can be passed up to the network layer and on to the CANprotocol family module and also vice-versa.  Also, the protocol familymodule provides an API for transport protocol modules to register, sothat any number of transport protocols can be loaded or unloadeddynamically.  In fact, the can core module alone does not provide anyprotocol and cannot be used without loading at least one additionalprotocol module.  Multiple sockets can be opened at the same time,on different or the same protocol module and they can listen/sendframes on different or the same CAN IDs.  Several sockets listening onthe same interface for frames with the same CAN ID are all passed thesame received matching CAN frames.  An application wishing tocommunicate using a specific transport protocol, e.g. ISO-TP, justselects that protocol when opening the socket, and then can read andwrite application data byte streams, without having to deal withCAN-IDs, frames, etc.Similar functionality visible from user-space could be provided by acharacter device, too, but this would lead to a technically inelegantsolution for a couple of reasons:* Intricate usage.  Instead of passing a protocol argument tosocket(2) and using bind(2) to select a CAN interface and CAN ID, anapplication would have to do all these operations using ioctl(2)s.* Code duplication.  A character device cannot make use of the Linuxnetwork queueing code, so all that code would have to be duplicatedfor CAN networking.* Abstraction.  In most existing character-device implementations, thehardware-specific device driver for a CAN controller directlyprovides the character device for the application to work with.This is at least very unusual in Unix systems for both, char andblock devices.  For example you don't have a character device for acertain UART of a serial interface, a certain sound chip in yourcomputer, a SCSI or IDE controller providing access to your harddisk or tape streamer device.  Instead, you have abstraction layerswhich provide a unified character or block device interface to theapplication on the one hand, and a interface for hardware-specificdevice drivers on the other hand.  These abstractions are providedby subsystems like the tty layer, the audio subsystem or the SCSIand IDE subsystems for the devices mentioned above.The easiest way to implement a CAN device driver is as a characterdevice without such a (complete) abstraction layer, as is done by mostexisting drivers.  The right way, however, would be to add such alayer with all the functionality like registering for certain CANIDs, supporting several open file descriptors and (de)multiplexingCAN frames between them, (sophisticated) queueing of CAN frames, andproviding an API for device drivers to register with.  However, thenit would be no more difficult, or may be even easier, to use thenetworking framework provided by the Linux kernel, and this is whatSocket CAN does.The use of the networking framework of the Linux kernel is just thenatural and most appropriate way to implement CAN for Linux.3. Socket CAN concept---------------------As described in chapter 2 it is the main goal of Socket CAN toprovide a socket interface to user space applications which buildsupon the Linux network layer. In contrast to the commonly knownTCP/IP and ethernet networking, the CAN bus is a broadcast-only(!)medium that has no MAC-layer addressing like ethernet. The CAN-identifier(can_id) is used for arbitration on the CAN-bus. Therefore the CAN-IDshave to be chosen uniquely on the bus. When designing a CAN-ECUnetwork the CAN-IDs are mapped to be sent by a specific ECU.For this reason a CAN-ID can be treated best as a kind of source address.3.1 receive listsThe network transparent access of multiple applications leads to theproblem that different applications may be interested in the sameCAN-IDs from the same CAN network interface. The Socket CAN coremodule - which implements the protocol family CAN - provides severalhigh efficient receive lists for this reason. If e.g. a user spaceapplication opens a CAN RAW socket, the raw protocol module itselfrequests the (range of) CAN-IDs from the Socket CAN core that arerequested by the user. The subscription and unsubscription ofCAN-IDs can be done for specific CAN interfaces or for all(!) knownCAN interfaces with the can_rx_(un)register() functions provided toCAN protocol modules by the SocketCAN core (see chapter 5).To optimize the CPU usage at runtime the receive lists are split upinto several specific lists per device that match the requestedfilter complexity for a given use-case.3.2 local loopback of sent framesAs known from other networking concepts the data exchangingapplications may run on the same or different nodes without anychange (except for the according addressing information):___   ___   ___                   _______   ___| _ | | _ | | _ |                 | _   _ | | _ |||A|| ||B|| ||C||                 ||A| |B|| ||C|||___| |___| |___|                 |_______| |___||     |     |                       |       |-----------------(1)- CAN bus -(2)---------------To ensure that application A receives the same information in theexample (2) as it would receive in example (1) there is need forsome kind of local loopback of the sent CAN frames on the appropriatenode.The Linux network devices (by default) just can handle thetransmission and reception of media dependent frames. Due to thearbitration on the CAN bus the transmission of a low prio CAN-IDmay be delayed by the reception of a high prio CAN frame. Toreflect the correct* traffic on the node the loopback of the sentdata has to be performed right after a successful transmission. Ifthe CAN network interface is not capable of performing the loopback forsome reason the SocketCAN core can do this task as a fallback solution.See chapter 6.2 for details (recommended).The loopback functionality is enabled by default to reflect standardnetworking behaviour for CAN applications. Due to some requests fromthe RT-SocketCAN group the loopback optionally may be disabled for eachseparate socket. See sockopts from the CAN RAW sockets in chapter 4.1.* = you really like to have this when you're running analyser toolslike 'candump' or 'cansniffer' on the (same) node.3.3 network security issues (capabilities)The Controller Area Network is a local field bus transmitting onlybroadcast messages without any routing and security concepts.In the majority of cases the user application has to deal withraw CAN frames. Therefore it might be reasonable NOT to restrictthe CAN access only to the user root, as known from other networks.Since the currently implemented CAN_RAW and CAN_BCM sockets can onlysend and receive frames to/from CAN interfaces it does not affectsecurity of others networks to allow all users to access the CAN.To enable non-root users to access CAN_RAW and CAN_BCM protocolsockets the Kconfig options CAN_RAW_USER and/or CAN_BCM_USER may beselected at kernel compile time.3.4 network problem notificationsThe use of the CAN bus may lead to several problems on the physicaland media access control layer. Detecting and logging of these lowerlayer problems is a vital requirement for CAN users to identifyhardware issues on the physical transceiver layer as well asarbitration problems and error frames caused by the differentECUs. The occurrence of detected errors are important for diagnosisand have to be logged together with the exact timestamp. For thisreason the CAN interface driver can generate so called Error Framesthat can optionally be passed to the user application in the sameway as other CAN frames. Whenever an error on the physical layeror the MAC layer is detected (e.g. by the CAN controller) the drivercreates an appropriate error frame. Error frames can be requested bythe user application using the common CAN filter mechanisms. Insidethis filter definition the (interested) type of errors may beselected. The reception of error frames is disabled by default.The format of the CAN error frame is briefly decribed in the Linuxheader file "include/linux/can/error.h".4. How to use Socket CAN------------------------Like TCP/IP, you first need to open a socket for communicating over aCAN network. Since Socket CAN implements a new protocol family, youneed to pass PF_CAN as the first argument to the socket(2) systemcall. Currently, there are two CAN protocols to choose from, the rawsocket protocol and the broadcast manager (BCM). So to open a socket,you would writes = socket(PF_CAN, SOCK_RAW, CAN_RAW);ands = socket(PF_CAN, SOCK_DGRAM, CAN_BCM);respectively.  After the successful creation of the socket, you wouldnormally use the bind(2) system call to bind the socket to a CANinterface (which is different from TCP/IP due to different addressing- see chapter 3). After binding (CAN_RAW) or connecting (CAN_BCM)the socket, you can read(2) and write(2) from/to the socket or usesend(2), sendto(2), sendmsg(2) and the recv* counterpart operationson the socket as usual. There are also CAN specific socket optionsdescribed below.The basic CAN frame structure and the sockaddr structure are definedin include/linux/can.h:struct can_frame {canid_t can_id;  /* 32 bit CAN_ID + EFF/RTR/ERR flags */__u8    can_dlc; /* data length code: 0 .. 8 */__u8    data[8] __attribute__((aligned(8)));};The alignment of the (linear) payload data[] to a 64bit boundaryallows the user to define own structs and unions to easily access theCAN payload. There is no given byteorder on the CAN bus bydefault. A read(2) system call on a CAN_RAW socket transfers astruct can_frame to the user space.The sockaddr_can structure has an interface index like thePF_PACKET socket, that also binds to a specific interface:struct sockaddr_can {sa_family_t can_family;int         can_ifindex;union {/* transport protocol class address info (e.g. ISOTP) */struct { canid_t rx_id, tx_id; } tp;/* reserved for future CAN protocols address information */} can_addr;};To determine the interface index an appropriate ioctl() has tobe used (example for CAN_RAW sockets without error checking):int s;struct sockaddr_can addr;struct ifreq ifr;s = socket(PF_CAN, SOCK_RAW, CAN_RAW);strcpy(ifr.ifr_name, "can0" );ioctl(s, SIOCGIFINDEX, &ifr);addr.can_family = AF_CAN;addr.can_ifindex = ifr.ifr_ifindex;bind(s, (struct sockaddr *)&addr, sizeof(addr));(..)To bind a socket to all(!) CAN interfaces the interface index mustbe 0 (zero). In this case the socket receives CAN frames from everyenabled CAN interface. To determine the originating CAN interfacethe system call recvfrom(2) may be used instead of read(2). To sendon a socket that is bound to 'any' interface sendto(2) is needed tospecify the outgoing interface.Reading CAN frames from a bound CAN_RAW socket (see above) consistsof reading a struct can_frame:struct can_frame frame;nbytes = read(s, &frame, sizeof(struct can_frame));if (nbytes < 0) {perror("can raw socket read");return 1;}/* paranoid check ... */if (nbytes < sizeof(struct can_frame)) {fprintf(stderr, "read: incomplete CAN frame\n");return 1;}/* do something with the received CAN frame */Writing CAN frames can be done similarly, with the write(2) system call:nbytes = write(s, &frame, sizeof(struct can_frame));When the CAN interface is bound to 'any' existing CAN interface(addr.can_ifindex = 0) it is recommended to use recvfrom(2) if theinformation about the originating CAN interface is needed:struct sockaddr_can addr;struct ifreq ifr;socklen_t len = sizeof(addr);struct can_frame frame;nbytes = recvfrom(s, &frame, sizeof(struct can_frame),0, (struct sockaddr*)&addr, &len);/* get interface name of the received CAN frame */ifr.ifr_ifindex = addr.can_ifindex;ioctl(s, SIOCGIFNAME, &ifr);printf("Received a CAN frame from interface %s", ifr.ifr_name);To write CAN frames on sockets bound to 'any' CAN interface theoutgoing interface has to be defined certainly.strcpy(ifr.ifr_name, "can0");ioctl(s, SIOCGIFINDEX, &ifr);addr.can_ifindex = ifr.ifr_ifindex;addr.can_family  = AF_CAN;nbytes = sendto(s, &frame, sizeof(struct can_frame),0, (struct sockaddr*)&addr, sizeof(addr));4.1 RAW protocol sockets with can_filters (SOCK_RAW)Using CAN_RAW sockets is extensively comparable to the commonlyknown access to CAN character devices. To meet the new possibilitiesprovided by the multi user SocketCAN approach, some reasonabledefaults are set at RAW socket binding time:- The filters are set to exactly one filter receiving everything- The socket only receives valid data frames (=> no error frames)- The loopback of sent CAN frames is enabled (see chapter 3.2)- The socket does not receive its own sent frames (in loopback mode)These default settings may be changed before or after binding the socket.To use the referenced definitions of the socket options for CAN_RAWsockets, include .4.1.1 RAW socket option CAN_RAW_FILTERThe reception of CAN frames using CAN_RAW sockets can be controlledby defining 0 .. n filters with the CAN_RAW_FILTER socket option.The CAN filter structure is defined in include/linux/can.h:struct can_filter {canid_t can_id;canid_t can_mask;};A filter matches, when & mask == can_id & maskwhich is analogous to known CAN controllers hardware filter semantics.The filter can be inverted in this semantic, when the CAN_INV_FILTERbit is set in can_id element of the can_filter structure. Incontrast to CAN controller hardware filters the user may set 0 .. nreceive filters for each open socket separately:struct can_filter rfilter[2];rfilter[0].can_id   = 0x123;rfilter[0].can_mask = CAN_SFF_MASK;rfilter[1].can_id   = 0x200;rfilter[1].can_mask = 0x700;setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter));To disable the reception of CAN frames on the selected CAN_RAW socket:setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);To set the filters to zero filters is quite obsolete as not readdata causes the raw socket to discard the received CAN frames. Buthaving this 'send only' use-case we may remove the receive list in theKernel to save a little (really a very little!) CPU usage.4.1.2 RAW socket option CAN_RAW_ERR_FILTERAs described in chapter 3.4 the CAN interface driver can generate socalled Error Frames that can optionally be passed to the userapplication in the same way as other CAN frames. The possibleerrors are divided into different error classes that may be filteredusing the appropriate error mask. To register for every possibleerror condition CAN_ERR_MASK can be used as value for the error mask.The values for the error mask are defined in linux/can/error.h .can_err_mask_t err_mask = ( CAN_ERR_TX_TIMEOUT | CAN_ERR_BUSOFF );setsockopt(s, SOL_CAN_RAW, CAN_RAW_ERR_FILTER,&err_mask, sizeof(err_mask));4.1.3 RAW socket option CAN_RAW_LOOPBACKTo meet multi user needs the local loopback is enabled by default(see chapter 3.2 for details). But in some embedded use-cases(e.g. when only one application uses the CAN bus) this loopbackfunctionality can be disabled (separately for each socket):int loopback = 0; /* 0 = disabled, 1 = enabled (default) */setsockopt(s, SOL_CAN_RAW, CAN_RAW_LOOPBACK, &loopback, sizeof(loopback));4.1.4 RAW socket option CAN_RAW_RECV_OWN_MSGSWhen the local loopback is enabled, all the sent CAN frames arelooped back to the open CAN sockets that registered for the CANframes' CAN-ID on this given interface to meet the multi userneeds. The reception of the CAN frames on the same socket that wassending the CAN frame is assumed to be unwanted and thereforedisabled by default. This default behaviour may be changed ondemand:int recv_own_msgs = 1; /* 0 = disabled (default), 1 = enabled */setsockopt(s, SOL_CAN_RAW, CAN_RAW_RECV_OWN_MSGS,&recv_own_msgs, sizeof(recv_own_msgs));4.2 Broadcast Manager protocol sockets (SOCK_DGRAM)4.3 connected transport protocols (SOCK_SEQPACKET)4.4 unconnected transport protocols (SOCK_DGRAM)5. Socket CAN core module-------------------------The Socket CAN core module implements the protocol familyPF_CAN. CAN protocol modules are loaded by the core module atruntime. The core module provides an interface for CAN protocolmodules to subscribe needed CAN IDs (see chapter 3.1).5.1 can.ko module params- stats_timer: To calculate the Socket CAN core statistics(e.g. current/maximum frames per second) this 1 second timer isinvoked at can.ko module start time by default. This timer can bedisabled by using stattimer=0 on the module commandline.- debug: (removed since SocketCAN SVN r546)5.2 procfs contentAs described in chapter 3.1 the Socket CAN core uses several filterlists to deliver received CAN frames to CAN protocol modules. Thesereceive lists, their filters and the count of filter matches can bechecked in the appropriate receive list. All entries contain thedevice and a protocol module identifier:foo@bar:~$ cat /proc/net/can/rcvlist_allreceive list 'rx_all':(vcan3: no entry)(vcan2: no entry)(vcan1: no entry)device   can_id   can_mask  function  userdata   matches  identvcan0     000    00000000  f88e6370  f6c6f400         0  raw(any: no entry)In this example an application requests any CAN traffic from vcan0.rcvlist_all - list for unfiltered entries (no filter operations)rcvlist_eff - list for single extended frame (EFF) entriesrcvlist_err - list for error frames masksrcvlist_fil - list for mask/value filtersrcvlist_inv - list for mask/value filters (inverse semantic)rcvlist_sff - list for single standard frame (SFF) entriesAdditional procfs files in /proc/net/canstats       - Socket CAN core statistics (rx/tx frames, match ratios, ...)reset_stats - manual statistic resetversion     - prints the Socket CAN core version and the ABI version5.3 writing own CAN protocol modulesTo implement a new protocol in the protocol family PF_CAN a newprotocol has to be defined in include/linux/can.h .The prototypes and definitions to use the Socket CAN core can beaccessed by including include/linux/can/core.h .In addition to functions that register the CAN protocol and theCAN device notifier chain there are functions to subscribe CANframes received by CAN interfaces and to send CAN frames:can_rx_register   - subscribe CAN frames from a specific interfacecan_rx_unregister - unsubscribe CAN frames from a specific interfacecan_send          - transmit a CAN frame (optional with local loopback)For details see the kerneldoc documentation in net/can/af_can.c orthe source code of net/can/raw.c or net/can/bcm.c .6. CAN network drivers----------------------Writing a CAN network device driver is much easier than writing aCAN character device driver. Similar to other known network devicedrivers you mainly have to deal with:- TX: Put the CAN frame from the socket buffer to the CAN controller.- RX: Put the CAN frame from the CAN controller to the socket buffer.See e.g. at Documentation/networking/netdevices.txt . The differencesfor writing CAN network device driver are described below:6.1 general settingsdev->type  = ARPHRD_CAN; /* the netdevice hardware type */dev->flags = IFF_NOARP;  /* CAN has no arp */dev->mtu   = sizeof(struct can_frame);The struct can_frame is the payload of each socket buffer in theprotocol family PF_CAN.6.2 local loopback of sent framesAs described in chapter 3.2 the CAN network device driver shouldsupport a local loopback functionality similar to the local echoe.g. of tty devices. In this case the driver flag IFF_ECHO has to beset to prevent the PF_CAN core from locally echoing sent frames(aka loopback) as fallback solution:dev->flags = (IFF_NOARP | IFF_ECHO);6.3 CAN controller hardware filtersTo reduce the interrupt load on deep embedded systems some CANcontrollers support the filtering of CAN IDs or ranges of CAN IDs.These hardware filter capabilities vary from controller tocontroller and have to be identified as not feasible in a multi-usernetworking approach. The use of the very controller specifichardware filters could make sense in a very dedicated use-case, as afilter on driver level would affect all users in the multi-usersystem. The high efficient filter sets inside the PF_CAN core allowto set different multiple filters for each socket separately.Therefore the use of hardware filters goes to the category 'handmadetuning on deep embedded systems'. The author is running a MPC603e@133MHz with four SJA1000 CAN controllers from 2002 under heavy busload without any problems ...6.4 The virtual CAN driver (vcan)Similar to the network loopback devices, vcan offers a virtual localCAN interface. A full qualified address on CAN consists of- a unique CAN Identifier (CAN ID)- the CAN bus this CAN ID is transmitted on (e.g. can0)so in common use cases more than one virtual CAN interface is needed.The virtual CAN interfaces allow the transmission and reception of CANframes without real CAN controller hardware. Virtual CAN networkdevices are usually named 'vcanX', like vcan0 vcan1 vcan2 ...When compiled as a module the virtual CAN driver module is called vcan.koSince Linux Kernel version 2.6.24 the vcan driver supports the Kernelnetlink interface to create vcan network devices. The creation andremoval of vcan network devices can be managed with the ip(8) tool:- Create a virtual CAN network interface:$ ip link add type vcan- Create a virtual CAN network interface with a specific name 'vcan42':$ ip link add dev vcan42 type vcan- Remove a (virtual CAN) network interface 'vcan42':$ ip link del vcan426.5 The CAN network device driver interfaceThe CAN network device driver interface provides a generic interfaceto setup, configure and monitor CAN network devices. The user can thenconfigure the CAN device, like setting the bit-timing parameters, viathe netlink interface using the program "ip" from the "IPROUTE2"utility suite. The following chapter describes briefly how to use it.Furthermore, the interface uses a common data structure and exports aset of common functions, which all real CAN network device driversshould use. Please have a look to the SJA1000 or MSCAN driver tounderstand how to use them. The name of the module is can-dev.ko.6.5.1 Netlink interface to set/get devices propertiesThe CAN device must be configured via netlink interface. The supportednetlink message types are defined and briefly described in"include/linux/can/netlink.h". CAN link support for the program "ip"of the IPROUTE2 utility suite is avaiable and it can be used as shownbelow:- Setting CAN device properties:$ ip link set can0 type can helpUsage: ip link set DEVICE type can[ bitrate BITRATE [ sample-point SAMPLE-POINT] ] |[ tq TQ prop-seg PROP_SEG phase-seg1 PHASE-SEG1phase-seg2 PHASE-SEG2 [ sjw SJW ] ][ loopback { on | off } ][ listen-only { on | off } ][ triple-sampling { on | off } ][ restart-ms TIME-MS ][ restart ]Where: BITRATE       := { 1..1000000 }SAMPLE-POINT  := { 0.000..0.999 }TQ            := { NUMBER }PROP-SEG      := { 1..8 }PHASE-SEG1    := { 1..8 }PHASE-SEG2    := { 1..8 }SJW           := { 1..4 }RESTART-MS    := { 0 | NUMBER }- Display CAN device details and statistics:$ ip -details -statistics link show can02: can0:  mtu 16 qdisc pfifo_fast state UP qlen 10link/cancan  state ERROR-ACTIVE restart-ms 100bitrate 125000 sample_point 0.875tq 125 prop-seg 6 phase-seg1 7 phase-seg2 2 sjw 1sja1000: tseg1 1..16 tseg2 1..8 sjw 1..4 brp 1..64 brp-inc 1clock 8000000re-started bus-errors arbit-lost error-warn error-pass bus-off41         17457      0          41         42         41RX: bytes  packets  errors  dropped overrun mcast140859     17608    17457   0       0       0TX: bytes  packets  errors  dropped carrier collsns861        112      0       41      0       0More info to the above output:""Shows the list of selected CAN controller modes: LOOPBACK,LISTEN-ONLY, or TRIPLE-SAMPLING."state ERROR-ACTIVE"The current state of the CAN controller: "ERROR-ACTIVE","ERROR-WARNING", "ERROR-PASSIVE", "BUS-OFF" or "STOPPED""restart-ms 100"Automatic restart delay time. If set to a non-zero value, arestart of the CAN controller will be triggered automaticallyin case of a bus-off condition after the specified delay timein milliseconds. By default it's off."bitrate 125000 sample_point 0.875"Shows the real bit-rate in bits/sec and the sample-point in therange 0.000..0.999. If the calculation of bit-timing parametersis enabled in the kernel (CONFIG_CAN_CALC_BITTIMING=y), thebit-timing can be defined by setting the "bitrate" argument.Optionally the "sample-point" can be specified. By default it's0.000 assuming CIA-recommended sample-points."tq 125 prop-seg 6 phase-seg1 7 phase-seg2 2 sjw 1"Shows the time quanta in ns, propagation segment, phase buffersegment 1 and 2 and the synchronisation jump width in units oftq. They allow to define the CAN bit-timing in a hardwareindependent format as proposed by the Bosch CAN 2.0 spec (seechapter 8 of http://www.semiconductors.bosch.de/pdf/can2spec.pdf)."sja1000: tseg1 1..16 tseg2 1..8 sjw 1..4 brp 1..64 brp-inc 1clock 8000000"Shows the bit-timing constants of the CAN controller, here the"sja1000". The minimum and maximum values of the time segment 1and 2, the synchronisation jump width in units of tq, thebitrate pre-scaler and the CAN system clock frequency in Hz.These constants could be used for user-defined (non-standard)bit-timing calculation algorithms in user-space."re-started bus-errors arbit-lost error-warn error-pass bus-off"Shows the number of restarts, bus and arbitration lost errors,and the state changes to the error-warning, error-passive andbus-off state. RX overrun errors are listed in the "overrun"field of the standard network statistics.6.5.2 Setting the CAN bit-timingThe CAN bit-timing parameters can always be defined in a hardwareindependent format as proposed in the Bosch CAN 2.0 specificationspecifying the arguments "tq", "prop_seg", "phase_seg1", "phase_seg2"and "sjw":$ ip link set canX type can tq 125 prop-seg 6 phase-seg1 7 phase-seg2 2 sjw 1If the kernel option CONFIG_CAN_CALC_BITTIMING is enabled, CIArecommended CAN bit-timing parameters will be calculated if the bit-rate is specified with the argument "bitrate":$ ip link set canX type can bitrate 125000Note that this works fine for the most common CAN controllers withstandard bit-rates but may *fail* for exotic bit-rates or CAN systemclock frequencies. Disabling CONFIG_CAN_CALC_BITTIMING saves somespace and allows user-space tools to solely determine and set thebit-timing parameters. The CAN controller specific bit-timingconstants can be used for that purpose. They are listed by thefollowing command:$ ip -details link show can0...sja1000: clock 8000000 tseg1 1..16 tseg2 1..8 sjw 1..4 brp 1..64 brp-inc 16.5.3 Starting and stopping the CAN network deviceA CAN network device is started or stopped as usual with the command"ifconfig canX up/down" or "ip link set canX up/down". Be aware thatyou *must* define proper bit-timing parameters for real CAN devicesbefore you can start it to avoid error-prone default settings:$ ip link set canX up type can bitrate 125000A device may enter the "bus-off" state if too much errors occurred onthe CAN bus. Then no more messages are received or sent. An automaticbus-off recovery can be enabled by setting the "restart-ms" to anon-zero value, e.g.:$ ip link set canX type can restart-ms 100Alternatively, the application may realize the "bus-off" conditionby monitoring CAN error frames and do a restart when appropriate withthe command:$ ip link set canX type can restartNote that a restart will also create a CAN error frame (see alsochapter 3.4).6.6 Supported CAN hardwarePlease check the "Kconfig" file in "drivers/net/can" to get an actuallist of the support CAN hardware. On the Socket CAN project website(see chapter 7) there might be further drivers available, also forolder kernel versions.7. Socket CAN resources-----------------------You can find further resources for Socket CAN like user space tools,support for old kernel versions, more drivers, mailing lists, etc.at the BerliOS OSS project website for Socket CAN:http://developer.berlios.de/projects/socketcanIf you have questions, bug fixes, etc., don't hesitate to post them tothe Socketcan-Users mailing list. But please search the archives first.8. Credits----------Oliver Hartkopp (PF_CAN core, filters, drivers, bcm, SJA1000 driver)Urs Thuermann (PF_CAN core, kernel integration, socket interfaces, raw, vcan)Jan Kizka (RT-SocketCAN core, Socket-API reconciliation)Wolfgang Grandegger (RT-SocketCAN core & drivers, Raw Socket-API reviews,CAN device driver interface, MSCAN driver)Robert Schwebel (design reviews, PTXdist integration)Marc Kleine-Budde (design reviews, Kernel 2.6 cleanups, drivers)Benedikt Spranger (reviews)Thomas Gleixner (LKML reviews, coding style, posting hints)Andrey Volkov (kernel subtree structure, ioctls, MSCAN driver)Matthias Brukner (first SJA1000 CAN netdevice implementation Q2/2003)Klaus Hitschler (PEAK driver integration)Uwe Koppe (CAN netdevices with PF_PACKET approach)Michael Schulze (driver layer loopback requirement, RT CAN drivers review)Pavel Pisa (Bit-timing calculation)Sascha Hauer (SJA1000 platform driver)Sebastian Haas (SJA1000 EMS PCI driver)Markus Plessing (SJA1000 EMS PCI driver)Per Dalen (SJA1000 Kvaser PCI driver)Sam Ravnborg (reviews, coding style, kbuild help)