요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
===================================
SocketCAN - Controller Area Network
===================================
Overview / What is SocketCAN
============================
The socketcan package is an implementation of CAN protocols
(Controller Area Network) for Linux. CAN is a networking technology
which has widespread use in automation, embedded devices, and
automotive fields. While there have been other CAN implementations
for Linux based on character devices, SocketCAN uses the Berkeley
socket API, the Linux network stack and implements the CAN device
drivers as network interfaces. The CAN socket API has been designed
as similar as possible to the TCP/IP protocols to allow programmers,
familiar with network programming, to easily learn how to use CAN
sockets.
.. _socketcan-motivation:
Motivation / Why Using the Socket API
=====================================
There have been CAN implementations for Linux before SocketCAN so the
question arises, why we have started another project. Most existing
implementations come as a device driver for some CAN hardware, they
are based on character devices and provide comparatively little
functionality. Usually, there is only a hardware-specific device
driver which provides a character device interface to send and
receive raw CAN frames, directly to/from the controller hardware.
Queueing of frames and higher-level transport protocols like ISO-TP
have to be implemented in user space applications. Also, most
character-device implementations support only one single process to
open the device at a time, similar to a serial interface. Exchanging
the CAN controller requires employment of another device driver and
often the need for adaption of large parts of the application to the
new driver's API.
SocketCAN was designed to overcome all of these limitations. A new
protocol family has been implemented which provides a socket interface
to user space applications and which builds upon the Linux network
layer, enabling use all of the provided queueing functionality. A device
driver for CAN controller hardware registers itself with the Linux
network layer as a network device, so that CAN frames from the
controller can be passed up to the network layer and on to the CAN
protocol family module and also vice-versa. Also, the protocol family
module provides an API for transport protocol modules to register, so
that any number of transport protocols can be loaded or unloaded
dynamically. In fact, the can core module alone does not provide any
protocol and cannot be used without loading at least one additional
protocol module. Multiple sockets can be opened at the same time,
on different or the same protocol module and they can listen/send
frames on different or the same CAN IDs. Several sockets listening on
the same interface for frames with the same CAN ID are all passed the
same received matching CAN frames. An application wishing to
communicate using a specific transport protocol, e.g. ISO-TP, just
selects that protocol when opening the socket, and then can read and
write application data byte streams, without having to deal with
CAN-IDs, frames, etc.
Similar functionality visible from user-space could be provided by a
character device, too, but this would lead to a technically inelegant
solution for a couple of reasons:
* **Intricate usage:** Instead of passing a protocol argument to
socket(2) and using bind(2) to select a CAN interface and CAN ID, an
application would have to do all these operations using ioctl(2)s.
* **Code duplication:** A character device cannot make use of the Linux
network queueing code, so all that code would have to be duplicated
for CAN networking.
* **Abstraction:** In most existing character-device implementations, the
hardware-specific device driver for a CAN controller directly
provides the character device for the application to work with.
This is at least very unusual in Unix systems for both, char and
block devices. For example you don't have a character device for a
certain UART of a serial interface, a certain sound chip in your
computer, a SCSI or IDE controller providing access to your hard
disk or tape streamer device. Instead, you have abstraction layers
which provide a unified character or block device interface to the
application on the one hand, and a interface for hardware-specific
device drivers on the other hand. These abstractions are provided
by subsystems like the tty layer, the audio subsystem or the SCSI
and IDE subsystems for the devices mentioned above.
The easiest way to implement a CAN device driver is as a character
device without such a (complete) abstraction layer, as is done by most
existing drivers. The right way, however, would be to add such a
layer with all the functionality like registering for certain CAN
IDs, supporting several open file descriptors and (de)multiplexing
CAN frames between them, (sophisticated) queueing of CAN frames, and
providing an API for device drivers to register with. However, then
it would be no more difficult, or may be even easier, to use the
networking framework provided by the Linux kernel, and this is what
SocketCAN does.
The use of the networking framework of the Linux kernel is just the
natural and most appropriate way to implement CAN for Linux.
.. _socketcan-concept:
SocketCAN Concept
=================
As described in :ref:`socketcan-motivation` the main goal of SocketCAN is to
provide a socket interface to user space applications which builds
upon the Linux network layer. In contrast to the commonly known
TCP/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-IDs
have to be chosen uniquely on the bus. When designing a CAN-ECU
network 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.
.. _socketcan-receive-lists:
Receive Lists
-------------
The network transparent access of multiple applications leads to the
problem that different applications may be interested in the same
CAN-IDs from the same CAN network interface. The SocketCAN core
module - which implements the protocol family CAN - provides several
high efficient receive lists for this reason. If e.g. a user space
application opens a CAN RAW socket, the raw protocol module itself
requests the (range of) CAN-IDs from the SocketCAN core that are
requested by the user. The subscription and unsubscription of
CAN-IDs can be done for specific CAN interfaces or for all(!) known
CAN interfaces with the can_rx_(un)register() functions provided to
CAN protocol modules by the SocketCAN core (see :ref:`socketcan-core-module`).
To optimize the CPU usage at runtime the receive lists are split up
into several specific lists per device that match the requested
filter complexity for a given use-case.
.. _socketcan-local-loopback1:
Local Loopback of Sent Frames
-----------------------------
As known from other networking concepts the data exchanging
applications may run on the same or different nodes without any
change (except for the according addressing information):
.. code::
___ ___ ___ _______ ___
| _ | | _ | | _ | | _ _ | | _ |
||A|| ||B|| ||C|| ||A| |B|| ||C||
|___| |___| |___| |_______| |___|
| | | | |
-----------------(1)- CAN bus -(2)---------------
To ensure that application A receives the same information in the
example (2) as it would receive in example (1) there is need for
some kind of local loopback of the sent CAN frames on the appropriate
node.
The Linux network devices (by default) just can handle the
transmission and reception of media dependent frames. Due to the
arbitration on the CAN bus the transmission of a low prio CAN-ID
may be delayed by the reception of a high prio CAN frame. To
reflect the correct [#f1]_ traffic on the node the loopback of the sent
data has to be performed right after a successful transmission. If
the CAN network interface is not capable of performing the loopback for
some reason the SocketCAN core can do this task as a fallback solution.
See :ref:`socketcan-local-loopback2` for details (recommended).
The loopback functionality is enabled by default to reflect standard
networking behaviour for CAN applications. Due to some requests from
the RT-SocketCAN group the loopback optionally may be disabled for each
separate socket. See sockopts from the CAN RAW sockets in :ref:`socketcan-raw-sockets`.
.. [#f1] you really like to have this when you're running analyser
tools like 'candump' or 'cansniffer' on the (same) node.
.. _socketcan-network-problem-notifications:
Network Problem Notifications
-----------------------------
The use of the CAN bus may lead to several problems on the physical
and media access control layer. Detecting and logging of these lower
layer problems is a vital requirement for CAN users to identify
hardware issues on the physical transceiver layer as well as
arbitration problems and error frames caused by the different
ECUs. The occurrence of detected errors are important for diagnosis
and have to be logged together with the exact timestamp. For this
reason the CAN interface driver can generate so called Error Message
Frames that can optionally be passed to the user application in the
same way as other CAN frames. Whenever an error on the physical layer
or the MAC layer is detected (e.g. by the CAN controller) the driver
creates an appropriate error message frame. Error messages frames can
be requested by the user application using the common CAN filter
mechanisms. Inside this filter definition the (interested) type of
errors may be selected. The reception of error messages is disabled
by default. The format of the CAN error message frame is briefly
described in the Linux header file "include/uapi/linux/can/error.h".
How to use SocketCAN
====================
Like TCP/IP, you first need to open a socket for communicating over a
CAN network. Since SocketCAN implements a new protocol family, you
need to pass PF_CAN as the first argument to the socket(2) system
call. Currently, there are two CAN protocols to choose from, the raw
socket protocol and the broadcast manager (BCM). So to open a socket,
you would write::
s = socket(PF_CAN, SOCK_RAW, CAN_RAW);
and::
s = socket(PF_CAN, SOCK_DGRAM, CAN_BCM);
respectively. After the successful creation of the socket, you would
normally use the bind(2) system call to bind the socket to a CAN
interface (which is different from TCP/IP due to different addressing
- see :ref:`socketcan-concept`). After binding (CAN_RAW) or connecting (CAN_BCM)
the socket, you can read(2) and write(2) from/to the socket or use
send(2), sendto(2), sendmsg(2) and the recv* counterpart operations
on the socket as usual. There are also CAN specific socket options
described below.
The Classical CAN frame structure (aka CAN 2.0B), the CAN FD frame structure
and the sockaddr structure are defined in include/linux/can.h:
.. code-block:: C
struct can_frame {
canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */
union {
/* CAN frame payload length in byte (0 .. CAN_MAX_DLEN)
* was previously named can_dlc so we need to carry that
* name for legacy support
*/
__u8 len;
__u8 can_dlc; /* deprecated */
};
__u8 __pad; /* padding */
__u8 __res0; /* reserved / padding */
__u8 len8_dlc; /* optional DLC for 8 byte payload length (9 .. 15) */
__u8 data[8] __attribute__((aligned(8)));
};
Remark: The len element contains the payload length in bytes and should be
used instead of can_dlc. The deprecated can_dlc was misleadingly named as
it always contained the plain payload length in bytes and not the so called
'data length code' (DLC).
To pass the raw DLC from/to a Classical CAN network device the len8_dlc
element can contain values 9 .. 15 when the len element is 8 (the real
payload length for all DLC values greater or equal to 8).
The alignment of the (linear) payload data[] to a 64bit boundary
allows the user to define their own structs and unions to easily access
the CAN payload. There is no given byteorder on the CAN bus by
default. A read(2) system call on a CAN_RAW socket transfers a
struct can_frame to the user space.
The sockaddr_can structure has an interface index like the
PF_PACKET socket, that also binds to a specific interface:
.. code-block:: C
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;
/* J1939 address information */
struct {
/* 8 byte name when using dynamic addressing */
__u64 name;
/* pgn:
* 8 bit: PS in PDU2 case, else 0
* 8 bit: PF
* 1 bit: DP
* 1 bit: reserved
*/
__u32 pgn;
/* 1 byte address */
__u8 addr;
} j1939;
/* reserved for future CAN protocols address information */
} can_addr;
};
To determine the interface index an appropriate ioctl() has to
be used (example for CAN_RAW sockets without error checking):
.. code-block:: C
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 must
be 0 (zero). In this case the socket receives CAN frames from every
enabled CAN interface. To determine the originating CAN interface
the system call recvfrom(2) may be used instead of read(2). To send
on a socket that is bound to 'any' interface sendto(2) is needed to
specify the outgoing interface.
Reading CAN frames from a bound CAN_RAW socket (see above) consists
of reading a struct can_frame:
.. code-block:: C
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 the
information about the originating CAN interface is needed:
.. code-block:: C
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 the
outgoing interface has to be defined certainly:
.. code-block:: C
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));
An accurate timestamp can be obtained with an ioctl(2) call after reading
a message from the socket:
.. code-block:: C
struct timeval tv;
ioctl(s, SIOCGSTAMP, &tv);
The timestamp has a resolution of one microsecond and is set automatically
at the reception of a CAN frame.
Remark about CAN FD (flexible data rate) support:
Generally the handling of CAN FD is very similar to the formerly described
examples. The new CAN FD capable CAN controllers support two different
bitrates for the arbitration phase and the payload phase of the CAN FD frame
and up to 64 bytes of payload. This extended payload length breaks all the
kernel interfaces (ABI) which heavily rely on the CAN frame with fixed eight
bytes of payload (struct can_frame) like the CAN_RAW socket. Therefore e.g.
the CAN_RAW socket supports a new socket option CAN_RAW_FD_FRAMES that
switches the socket into a mode that allows the handling of CAN FD frames
and Classical CAN frames simultaneously (see :ref:`socketcan-rawfd`).
The struct canfd_frame is defined in include/linux/can.h:
.. code-block:: C
struct canfd_frame {
canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */
__u8 len; /* frame payload length in byte (0 .. 64) */
__u8 flags; /* additional flags for CAN FD */
__u8 __res0; /* reserved / padding */
__u8 __res1; /* reserved / padding */
__u8 data[64] __attribute__((aligned(8)));
};
The struct canfd_frame and the existing struct can_frame have the can_id,
the payload length and the payload data at the same offset inside their
structures. This allows to handle the different structures very similar.
When the content of a struct can_frame is copied into a struct canfd_frame
all structure elements can be used as-is - only the data[] becomes extended.
When introducing the struct canfd_frame it turned out that the data length
code (DLC) of the struct can_frame was used as a length information as the
length and the DLC has a 1:1 mapping in the range of 0 .. 8. To preserve
the easy handling of the length information the canfd_frame.len element
contains a plain length value from 0 .. 64. So both canfd_frame.len and
can_frame.len are equal and contain a length information and no DLC.
For details about the distinction of CAN and CAN FD capable devices and
the mapping to the bus-relevant data length code (DLC), see :ref:`socketcan-can-fd-driver`.
The length of the two CAN(FD) frame structures define the maximum transfer
unit (MTU) of the CAN(FD) network interface and skbuff data length. Two
definitions are specified for CAN specific MTUs in include/linux/can.h:
.. code-block:: C
#define CAN_MTU (sizeof(struct can_frame)) == 16 => Classical CAN frame
#define CANFD_MTU (sizeof(struct canfd_frame)) == 72 => CAN FD frame
Returned Message Flags
----------------------
When using the system call recvmsg(2) on a RAW or a BCM socket, the
msg->msg_flags field may contain the following flags:
MSG_DONTROUTE:
set when the received frame was created on the local host.
MSG_CONFIRM:
set when the frame was sent via the socket it is received on.
This flag can be interpreted as a 'transmission confirmation' when the
CAN driver supports the echo of frames on driver level, see
:ref:`socketcan-local-loopback1` and :ref:`socketcan-local-loopback2`.
(Note: In order to receive such messages on a RAW socket,
CAN_RAW_RECV_OWN_MSGS must be set.)
.. _socketcan-raw-sockets:
RAW Protocol Sockets with can_filters (SOCK_RAW)
------------------------------------------------
Using CAN_RAW sockets is extensively comparable to the commonly
known access to CAN character devices. To meet the new possibilities
provided by the multi user SocketCAN approach, some reasonable
defaults 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 message frames)
- The loopback of sent CAN frames is enabled (see :ref:`socketcan-local-loopback2`)
- 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_RAW
sockets, include <linux/can/raw.h>.
.. _socketcan-rawfilter:
RAW socket option CAN_RAW_FILTER
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The reception of CAN frames using CAN_RAW sockets can be controlled
by defining 0 .. n filters with the CAN_RAW_FILTER socket option.
The CAN filter structure is defined in include/linux/can.h:
.. code-block:: C
struct can_filter {
canid_t can_id;
canid_t can_mask;
};
A filter matches, when:
.. code-block:: C
<received_can_id> & mask == can_id & mask
which is analogous to known CAN controllers hardware filter semantics.
The filter can be inverted in this semantic, when the CAN_INV_FILTER
bit is set in can_id element of the can_filter structure. In
contrast to CAN controller hardware filters the user may set 0 .. n
receive filters for each open socket separately:
.. code-block:: C
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:
.. code-block:: C
setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);
To set the filters to zero filters is quite obsolete as to not read
data causes the raw socket to discard the received CAN frames. But
having this 'send only' use-case we may remove the receive list in the
Kernel to save a little (really a very little!) CPU usage.
CAN Filter Usage Optimisation
.............................
The CAN filters are processed in per-device filter lists at CAN frame
reception time. To reduce the number of checks that need to be performed
while walking through the filter lists the CAN core provides an optimized
filter handling when the filter subscription focuses on a single CAN ID.
For the possible 2048 SFF CAN identifiers the identifier is used as an index
to access the corresponding subscription list without any further checks.
For the 2^29 possible EFF CAN identifiers a 10 bit XOR folding is used as
hash function to retrieve the EFF table index.
To benefit from the optimized filters for single CAN identifiers the
CAN_SFF_MASK or CAN_EFF_MASK have to be set into can_filter.mask together
with set CAN_EFF_FLAG and CAN_RTR_FLAG bits. A set CAN_EFF_FLAG bit in the
can_filter.mask makes clear that it matters whether a SFF or EFF CAN ID is
subscribed. E.g. in the example from above:
.. code-block:: C
rfilter[0].can_id = 0x123;
rfilter[0].can_mask = CAN_SFF_MASK;
both SFF frames with CAN ID 0x123 and EFF frames with 0xXXXXX123 can pass.
To filter for only 0x123 (SFF) and 0x12345678 (EFF) CAN identifiers the
filter has to be defined in this way to benefit from the optimized filters:
.. code-block:: C
struct can_filter rfilter[2];
rfilter[0].can_id = 0x123;
rfilter[0].can_mask = (CAN_EFF_FLAG | CAN_RTR_FLAG | CAN_SFF_MASK);
rfilter[1].can_id = 0x12345678 | CAN_EFF_FLAG;
rfilter[1].can_mask = (CAN_EFF_FLAG | CAN_RTR_FLAG | CAN_EFF_MASK);
setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter));
RAW Socket Option CAN_RAW_ERR_FILTER
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
As described in :ref:`socketcan-network-problem-notifications` the CAN interface driver can generate so
called Error Message Frames that can optionally be passed to the user
application in the same way as other CAN frames. The possible
errors are divided into different error classes that may be filtered
using the appropriate error mask. To register for every possible
error 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:
.. code-block:: C
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));
RAW Socket Option CAN_RAW_LOOPBACK
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To meet multi user needs the local loopback is enabled by default
(see :ref:`socketcan-local-loopback1` for details). But in some embedded use-cases
(e.g. when only one application uses the CAN bus) this loopback
functionality can be disabled (separately for each socket):
.. code-block:: C
int loopback = 0; /* 0 = disabled, 1 = enabled (default) */
setsockopt(s, SOL_CAN_RAW, CAN_RAW_LOOPBACK, &loopback, sizeof(loopback));
RAW socket option CAN_RAW_RECV_OWN_MSGS
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When the local loopback is enabled, all the sent CAN frames are
looped back to the open CAN sockets that registered for the CAN
frames' CAN-ID on this given interface to meet the multi user
needs. The reception of the CAN frames on the same socket that was
sending the CAN frame is assumed to be unwanted and therefore
disabled by default. This default behaviour may be changed on
demand:
.. code-block:: C
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));
Note that reception of a socket's own CAN frames are subject to the same
filtering as other CAN frames (see :ref:`socketcan-rawfilter`).
.. _socketcan-rawfd:
RAW Socket Option CAN_RAW_FD_FRAMES
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CAN FD support in CAN_RAW sockets can be enabled with a new socket option
CAN_RAW_FD_FRAMES which is off by default. When the new socket option is
not supported by the CAN_RAW socket (e.g. on older kernels), switching the
CAN_RAW_FD_FRAMES option returns the error -ENOPROTOOPT.
Once CAN_RAW_FD_FRAMES is enabled the application can send both CAN frames
and CAN FD frames. OTOH the application has to handle CAN and CAN FD frames
when reading from the socket:
.. code-block:: C
CAN_RAW_FD_FRAMES enabled: CAN_MTU and CANFD_MTU are allowed
CAN_RAW_FD_FRAMES disabled: only CAN_MTU is allowed (default)
Example:
.. code-block:: C
[ remember: CANFD_MTU == sizeof(struct canfd_frame) ]
struct canfd_frame cfd;
nbytes = read(s, &cfd, CANFD_MTU);
if (nbytes == CANFD_MTU) {
printf("got CAN FD frame with length %d\n", cfd.len);
/* cfd.flags contains valid data */
} else if (nbytes == CAN_MTU) {
printf("got Classical CAN frame with length %d\n", cfd.len);
/* cfd.flags is undefined */
} else {
fprintf(stderr, "read: invalid CAN(FD) frame\n");
return 1;
}
/* the content can be handled independently from the received MTU size */
printf("can_id: %X data length: %d data: ", cfd.can_id, cfd.len);
for (i = 0; i < cfd.len; i++)
printf("%02X ", cfd.data[i]);
When reading with size CANFD_MTU only returns CAN_MTU bytes that have
been received from the socket a Classical CAN frame has been read into the
provided CAN FD structure. Note that the canfd_frame.flags data field is
not specified in the struct can_frame and therefore it is only valid in
CANFD_MTU sized CAN FD frames.
Implementation hint for new CAN applications:
To build a CAN FD aware application use struct canfd_frame as basic CAN
data structure for CAN_RAW based applications. When the application is
executed on an older Linux kernel and switching the CAN_RAW_FD_FRAMES
socket option returns an error: No problem. You'll get Classical CAN frames
or CAN FD frames and can process them the same way.
When sending to CAN devices make sure that the device is capable to handle
CAN FD frames by checking if the device maximum transfer unit is CANFD_MTU.
The CAN device MTU can be retrieved e.g. with a SIOCGIFMTU ioctl() syscall.
RAW socket option CAN_RAW_JOIN_FILTERS
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The CAN_RAW socket can set multiple CAN identifier specific filters that
lead to multiple filters in the af_can.c filter processing. These filters
are independent from each other which leads to logical OR'ed filters when
applied (see :ref:`socketcan-rawfilter`).
This socket option joins the given CAN filters in the way that only CAN
frames are passed to user space that matched *all* given CAN filters. The
semantic for the applied filters is therefore changed to a logical AND.
This is useful especially when the filterset is a combination of filters
where the CAN_INV_FILTER flag is set in order to notch single CAN IDs or
CAN ID ranges from the incoming traffic.
Broadcast Manager Protocol Sockets (SOCK_DGRAM)
-----------------------------------------------
The Broadcast Manager protocol provides a command based configuration
interface to filter and send (e.g. cyclic) CAN messages in kernel space.
Receive filters can be used to down sample frequent messages; detect events
such as message contents changes, packet length changes, and do time-out
monitoring of received messages.
Periodic transmission tasks of CAN frames or a sequence of CAN frames can be
created and modified at runtime; both the message content and the two
possible transmit intervals can be altered.
A BCM socket is not intended for sending individual CAN frames using the
struct can_frame as known from the CAN_RAW socket. Instead a special BCM
configuration message is defined. The basic BCM configuration message used
to communicate with the broadcast manager and the available operations are
defined in the linux/can/bcm.h include. The BCM message consists of a
message header with a command ('opcode') followed by zero or more CAN frames.
The broadcast manager sends responses to user space in the same form:
.. code-block:: C
struct bcm_msg_head {
__u32 opcode; /* command */
__u32 flags; /* special flags */
__u32 count; /* run 'count' times with ival1 */
struct timeval ival1, ival2; /* count and subsequent interval */
canid_t can_id; /* unique can_id for task */
__u32 nframes; /* number of can_frames following */
struct can_frame frames[];
};
The aligned payload 'frames' uses the same basic CAN frame structure defined
at the beginning of :ref:`socketcan-rawfd` and in the include/linux/can.h include. All
messages to the broadcast manager from user space have this structure.
Note a CAN_BCM socket must be connected instead of bound after socket
creation (example without error checking):
.. code-block:: C
int s;
struct sockaddr_can addr;
struct ifreq ifr;
s = socket(PF_CAN, SOCK_DGRAM, CAN_BCM);
strcpy(ifr.ifr_name, "can0");
ioctl(s, SIOCGIFINDEX, &ifr);
addr.can_family = AF_CAN;
addr.can_ifindex = ifr.ifr_ifindex;
connect(s, (struct sockaddr *)&addr, sizeof(addr));
(..)
The broadcast manager socket is able to handle any number of in flight
transmissions or receive filters concurrently. The different RX/TX jobs are
distinguished by the unique can_id in each BCM message. However additional
CAN_BCM sockets are recommended to communicate on multiple CAN interfaces.
When the broadcast manager socket is bound to 'any' CAN interface (=> the
interface index is set to zero) the configured receive filters apply to any
CAN interface unless the sendto() syscall is used to overrule the 'any' CAN
interface index. When using recvfrom() instead of read() to retrieve BCM
socket messages the originating CAN interface is provided in can_ifindex.
Broadcast Manager Operations
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The opcode defines the operation for the broadcast manager to carry out,
or details the broadcast managers response to several events, including
user requests.
Transmit Operations (user space to broadcast manager):
TX_SETUP:
Create (cyclic) transmission task.
TX_DELETE:
Remove (cyclic) transmission task, requires only can_id.
TX_READ:
Read properties of (cyclic) transmission task for can_id.
TX_SEND:
Send one CAN frame.
Transmit Responses (broadcast manager to user space):
TX_STATUS:
Reply to TX_READ request (transmission task configuration).
TX_EXPIRED:
Notification when counter finishes sending at initial interval
'ival1'. Requires the TX_COUNTEVT flag to be set at TX_SETUP.
Receive Operations (user space to broadcast manager):
RX_SETUP:
Create RX content filter subscription.
RX_DELETE:
Remove RX content filter subscription, requires only can_id.
RX_READ:
Read properties of RX content filter subscription for can_id.
Receive Responses (broadcast manager to user space):
RX_STATUS:
Reply to RX_READ request (filter task configuration).
RX_TIMEOUT:
Cyclic message is detected to be absent (timer ival1 expired).
RX_CHANGED:
BCM message with updated CAN frame (detected content change).
Sent on first message received or on receipt of revised CAN messages.
Broadcast Manager Message Flags
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When sending a message to the broadcast manager the 'flags' element may
contain the following flag definitions which influence the behaviour:
SETTIMER:
Set the values of ival1, ival2 and count
STARTTIMER:
Start the timer with the actual values of ival1, ival2
and count. Starting the timer leads simultaneously to emit a CAN frame.
TX_COUNTEVT:
Create the message TX_EXPIRED when count expires
TX_ANNOUNCE:
A change of data by the process is emitted immediately.
TX_CP_CAN_ID:
Copies the can_id from the message header to each
subsequent frame in frames. This is intended as usage simplification. For
TX tasks the unique can_id from the message header may differ from the
can_id(s) stored for transmission in the subsequent struct can_frame(s).
RX_FILTER_ID:
Filter by can_id alone, no frames required (nframes=0).
RX_CHECK_DLC:
A change of the DLC leads to an RX_CHANGED.
RX_NO_AUTOTIMER:
Prevent automatically starting the timeout monitor.
RX_ANNOUNCE_RESUME:
If passed at RX_SETUP and a receive timeout occurred, a
RX_CHANGED message will be generated when the (cyclic) receive restarts.
TX_RESET_MULTI_IDX:
Reset the index for the multiple frame transmission.
RX_RTR_FRAME:
Send reply for RTR-request (placed in op->frames[0]).
CAN_FD_FRAME:
The CAN frames following the bcm_msg_head are struct canfd_frame's
Broadcast Manager Transmission Timers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Periodic transmission configurations may use up to two interval timers.
In this case the BCM sends a number of messages ('count') at an interval
'ival1', then continuing to send at another given interval 'ival2'. When
only one timer is needed 'count' is set to zero and only 'ival2' is used.
When SET_TIMER and START_TIMER flag were set the timers are activated.
The timer values can be altered at runtime when only SET_TIMER is set.
Broadcast Manager message sequence transmission
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Up to 256 CAN frames can be transmitted in a sequence in the case of a cyclic
TX task configuration. The number of CAN frames is provided in the 'nframes'
element of the BCM message head. The defined number of CAN frames are added
as array to the TX_SETUP BCM configuration message:
.. code-block:: C
/* create a struct to set up a sequence of four CAN frames */
struct {
struct bcm_msg_head msg_head;
struct can_frame frame[4];
} mytxmsg;
(..)
mytxmsg.msg_head.nframes = 4;
(..)
write(s, &mytxmsg, sizeof(mytxmsg));
With every transmission the index in the array of CAN frames is increased
and set to zero at index overflow.
Broadcast Manager Receive Filter Timers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The timer values ival1 or ival2 may be set to non-zero values at RX_SETUP.
When the SET_TIMER flag is set the timers are enabled:
ival1:
Send RX_TIMEOUT when a received message is not received again within
the given time. When START_TIMER is set at RX_SETUP the timeout detection
is activated directly - even without a former CAN frame reception.
ival2:
Throttle the received message rate down to the value of ival2. This
is useful to reduce messages for the application when the signal inside the
CAN frame is stateless as state changes within the ival2 period may get
lost.
Broadcast Manager Multiplex Message Receive Filter
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To filter for content changes in multiplex message sequences an array of more
than one CAN frames can be passed in a RX_SETUP configuration message. The
data bytes of the first CAN frame contain the mask of relevant bits that
have to match in the subsequent CAN frames with the received CAN frame.
If one of the subsequent CAN frames is matching the bits in that frame data
mark the relevant content to be compared with the previous received content.
Up to 257 CAN frames (multiplex filter bit mask CAN frame plus 256 CAN
filters) can be added as array to the TX_SETUP BCM configuration message:
.. code-block:: C
/* usually used to clear CAN frame data[] - beware of endian problems! */
#define U64_DATA(p) (*(unsigned long long*)(p)->data)
struct {
struct bcm_msg_head msg_head;
struct can_frame frame[5];
} msg;
msg.msg_head.opcode = RX_SETUP;
msg.msg_head.can_id = 0x42;
msg.msg_head.flags = 0;
msg.msg_head.nframes = 5;
U64_DATA(&msg.frame[0]) = 0xFF00000000000000ULL; /* MUX mask */
U64_DATA(&msg.frame[1]) = 0x01000000000000FFULL; /* data mask (MUX 0x01) */
U64_DATA(&msg.frame[2]) = 0x0200FFFF000000FFULL; /* data mask (MUX 0x02) */
U64_DATA(&msg.frame[3]) = 0x330000FFFFFF0003ULL; /* data mask (MUX 0x33) */
U64_DATA(&msg.frame[4]) = 0x4F07FC0FF0000000ULL; /* data mask (MUX 0x4F) */
write(s, &msg, sizeof(msg));
Broadcast Manager CAN FD Support
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The programming API of the CAN_BCM depends on struct can_frame which is
given as array directly behind the bcm_msg_head structure. To follow this
schema for the CAN FD frames a new flag 'CAN_FD_FRAME' in the bcm_msg_head
flags indicates that the concatenated CAN frame structures behind the
bcm_msg_head are defined as struct canfd_frame:
.. code-block:: C
struct {
struct bcm_msg_head msg_head;
struct canfd_frame frame[5];
} msg;
msg.msg_head.opcode = RX_SETUP;
msg.msg_head.can_id = 0x42;
msg.msg_head.flags = CAN_FD_FRAME;
msg.msg_head.nframes = 5;
(..)
When using CAN FD frames for multiplex filtering the MUX mask is still
expected in the first 64 bit of the struct canfd_frame data section.
Connected Transport Protocols (SOCK_SEQPACKET)
----------------------------------------------
(to be written)
Unconnected Transport Protocols (SOCK_DGRAM)
--------------------------------------------
(to be written)
.. _socketcan-core-module:
SocketCAN Core Module
=====================
The SocketCAN core module implements the protocol family
PF_CAN. CAN protocol modules are loaded by the core module at
runtime. The core module provides an interface for CAN protocol
modules to subscribe needed CAN IDs (see :ref:`socketcan-receive-lists`).
can.ko Module Params
--------------------
- **stats_timer**:
To calculate the SocketCAN core statistics
(e.g. current/maximum frames per second) this 1 second timer is
invoked at can.ko module start time by default. This timer can be
disabled by using stattimer=0 on the module commandline.
- **debug**:
(removed since SocketCAN SVN r546)
procfs content
--------------
As described in :ref:`socketcan-receive-lists` the SocketCAN core uses several filter
lists to deliver received CAN frames to CAN protocol modules. These
receive lists, their filters and the count of filter matches can be
checked in the appropriate receive list. All entries contain the
device and a protocol module identifier::
foo@bar:~$ cat /proc/net/can/rcvlist_all
receive list 'rx_all':
(vcan3: no entry)
(vcan2: no entry)
(vcan1: no entry)
device can_id can_mask function userdata matches ident
vcan0 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) entries
rcvlist_err - list for error message frames masks
rcvlist_fil - list for mask/value filters
rcvlist_inv - list for mask/value filters (inverse semantic)
rcvlist_sff - list for single standard frame (SFF) entries
Additional procfs files in /proc/net/can::
stats - SocketCAN core statistics (rx/tx frames, match ratios, ...)
reset_stats - manual statistic reset
version - prints SocketCAN core and ABI version (removed in Linux 5.10)
Writing Own CAN Protocol Modules
--------------------------------
To implement a new protocol in the protocol family PF_CAN a new
protocol has to be defined in include/linux/can.h .
The prototypes and definitions to use the SocketCAN core can be
accessed by including include/linux/can/core.h .
In addition to functions that register the CAN protocol and the
CAN device notifier chain there are functions to subscribe CAN
frames received by CAN interfaces and to send CAN frames::
can_rx_register - subscribe CAN frames from a specific interface
can_rx_unregister - unsubscribe CAN frames from a specific interface
can_send - transmit a CAN frame (optional with local loopback)
For details see the kerneldoc documentation in net/can/af_can.c or
the source code of net/can/raw.c or net/can/bcm.c .
CAN Network Drivers
===================
Writing a CAN network device driver is much easier than writing a
CAN character device driver. Similar to other known network device
drivers 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.rst . The differences
for writing CAN network device driver are described below:
General Settings
----------------
CAN network device drivers can use alloc_candev_mqs() and friends instead of
alloc_netdev_mqs(), to automatically take care of CAN-specific setup:
.. code-block:: C
dev = alloc_candev_mqs(...);
The struct can_frame or struct canfd_frame is the payload of each socket
buffer (skbuff) in the protocol family PF_CAN.
.. _socketcan-local-loopback2:
Local Loopback of Sent Frames
-----------------------------
As described in :ref:`socketcan-local-loopback1` the CAN network device driver should
support a local loopback functionality similar to the local echo
e.g. of tty devices. In this case the driver flag IFF_ECHO has to be
set to prevent the PF_CAN core from locally echoing sent frames
(aka loopback) as fallback solution::
dev->flags = (IFF_NOARP | IFF_ECHO);
CAN Controller Hardware Filters
-------------------------------
To reduce the interrupt load on deep embedded systems some CAN
controllers support the filtering of CAN IDs or ranges of CAN IDs.
These hardware filter capabilities vary from controller to
controller and have to be identified as not feasible in a multi-user
networking approach. The use of the very controller specific
hardware filters could make sense in a very dedicated use-case, as a
filter on driver level would affect all users in the multi-user
system. The high efficient filter sets inside the PF_CAN core allow
to set different multiple filters for each socket separately.
Therefore the use of hardware filters goes to the category 'handmade
tuning on deep embedded systems'. The author is running a MPC603e
@133MHz with four SJA1000 CAN controllers from 2002 under heavy bus
load without any problems ...
Switchable Termination Resistors
--------------------------------
CAN bus requires a specific impedance across the differential pair,
typically provided by two 120Ohm resistors on the farthest nodes of
the bus. Some CAN controllers support activating / deactivating a
termination resistor(s) to provide the correct impedance.
Query the available resistances::
$ ip -details link show can0
...
termination 120 [ 0, 120 ]
Activate the terminating resistor::
$ ip link set dev can0 type can termination 120
Deactivate the terminating resistor::
$ ip link set dev can0 type can termination 0
To enable termination resistor support to a can-controller, either
implement in the controller's struct can-priv::
termination_const
termination_const_cnt
do_set_termination
or add gpio control with the device tree entries from
Documentation/devicetree/bindings/net/can/can-controller.yaml
The Virtual CAN Driver (vcan)
-----------------------------
Similar to the network loopback devices, vcan offers a virtual local
CAN 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 CAN
frames without real CAN controller hardware. Virtual CAN network
devices are usually named 'vcanX', like vcan0 vcan1 vcan2 ...
When compiled as a module the virtual CAN driver module is called vcan.ko
Since Linux Kernel version 2.6.24 the vcan driver supports the Kernel
netlink interface to create vcan network devices. The creation and
removal 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 vcan42
The CAN Network Device Driver Interface
---------------------------------------
The CAN network device driver interface provides a generic interface
to setup, configure and monitor CAN network devices. The user can then
configure the CAN device, like setting the bit-timing parameters, via
the 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 a
set of common functions, which all real CAN network device drivers
should use. Please have a look to the SJA1000 or MSCAN driver to
understand how to use them. The name of the module is can-dev.ko.
Netlink interface to set/get devices properties
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The CAN device must be configured via netlink interface. The supported
netlink 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 available and it can be used as shown
below:
Setting CAN device properties::
$ ip link set can0 type can help
Usage: ip link set DEVICE type can
[ bitrate BITRATE [ sample-point SAMPLE-POINT] ] |
[ tq TQ prop-seg PROP_SEG phase-seg1 PHASE-SEG1
phase-seg2 PHASE-SEG2 [ sjw SJW ] ]
[ dbitrate BITRATE [ dsample-point SAMPLE-POINT] ] |
[ dtq TQ dprop-seg PROP_SEG dphase-seg1 PHASE-SEG1
dphase-seg2 PHASE-SEG2 [ dsjw SJW ] ]
[ loopback { on | off } ]
[ listen-only { on | off } ]
[ triple-sampling { on | off } ]
[ one-shot { on | off } ]
[ berr-reporting { on | off } ]
[ fd { on | off } ]
[ fd-non-iso { on | off } ]
[ presume-ack { on | off } ]
[ cc-len8-dlc { 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 can0
2: can0: <NOARP,UP,LOWER_UP,ECHO> mtu 16 qdisc pfifo_fast state UP qlen 10
link/can
can <TRIPLE-SAMPLING> state ERROR-ACTIVE restart-ms 100
bitrate 125000 sample_point 0.875
tq 125 prop-seg 6 phase-seg1 7 phase-seg2 2 sjw 1
sja1000: tseg1 1..16 tseg2 1..8 sjw 1..4 brp 1..64 brp-inc 1
clock 8000000
re-started bus-errors arbit-lost error-warn error-pass bus-off
41 17457 0 41 42 41
RX: bytes packets errors dropped overrun mcast
140859 17608 17457 0 0 0
TX: bytes packets errors dropped carrier collsns
861 112 0 41 0 0
More info to the above output:
"<TRIPLE-SAMPLING>"
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, a
restart of the CAN controller will be triggered automatically
in case of a bus-off condition after the specified delay time
in 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 the
range 0.000..0.999. If the calculation of bit-timing parameters
is enabled in the kernel (CONFIG_CAN_CALC_BITTIMING=y), the
bit-timing can be defined by setting the "bitrate" argument.
Optionally the "sample-point" can be specified. By default it's
0.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 buffer
segment 1 and 2 and the synchronisation jump width in units of
tq. They allow to define the CAN bit-timing in a hardware
independent format as proposed by the Bosch CAN 2.0 spec (see
chapter 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 1 clock 8000000"
Shows the bit-timing constants of the CAN controller, here the
"sja1000". The minimum and maximum values of the time segment 1
and 2, the synchronisation jump width in units of tq, the
bitrate 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 and
bus-off state. RX overrun errors are listed in the "overrun"
field of the standard network statistics.
Setting the CAN Bit-Timing
~~~~~~~~~~~~~~~~~~~~~~~~~~
The CAN bit-timing parameters can always be defined in a hardware
independent format as proposed in the Bosch CAN 2.0 specification
specifying 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 1
If the kernel option CONFIG_CAN_CALC_BITTIMING is enabled, CIA
recommended CAN bit-timing parameters will be calculated if the bit-
rate is specified with the argument "bitrate"::
$ ip link set canX type can bitrate 125000
Note that this works fine for the most common CAN controllers with
standard bit-rates but may *fail* for exotic bit-rates or CAN system
clock frequencies. Disabling CONFIG_CAN_CALC_BITTIMING saves some
space and allows user-space tools to solely determine and set the
bit-timing parameters. The CAN controller specific bit-timing
constants can be used for that purpose. They are listed by the
following command::
$ ip -details link show can0
...
sja1000: clock 8000000 tseg1 1..16 tseg2 1..8 sjw 1..4 brp 1..64 brp-inc 1
Starting and Stopping the CAN Network Device
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A 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 that
you *must* define proper bit-timing parameters for real CAN devices
before you can start it to avoid error-prone default settings::
$ ip link set canX up type can bitrate 125000
A device may enter the "bus-off" state if too many errors occurred on
the CAN bus. Then no more messages are received or sent. An automatic
bus-off recovery can be enabled by setting the "restart-ms" to a
non-zero value, e.g.::
$ ip link set canX type can restart-ms 100
Alternatively, the application may realize the "bus-off" condition
by monitoring CAN error message frames and do a restart when
appropriate with the command::
$ ip link set canX type can restart
Note that a restart will also create a CAN error message frame (see
also :ref:`socketcan-network-problem-notifications`).
.. _socketcan-can-fd-driver:
CAN FD (Flexible Data Rate) Driver Support
------------------------------------------
CAN FD capable CAN controllers support two different bitrates for the
arbitration phase and the payload phase of the CAN FD frame. Therefore a
second bit timing has to be specified in order to enable the CAN FD bitrate.
Additionally CAN FD capable CAN controllers support up to 64 bytes of
payload. The representation of this length in can_frame.len and
canfd_frame.len for userspace applications and inside the Linux network
layer is a plain value from 0 .. 64 instead of the Classical CAN length
which ranges from 0 to 8. The payload length to the bus-relevant DLC mapping
is only performed inside the CAN drivers, preferably with the helper
functions can_fd_dlc2len() and can_fd_len2dlc().
The CAN netdevice driver capabilities can be distinguished by the network
devices maximum transfer unit (MTU)::
MTU = 16 (CAN_MTU) => sizeof(struct can_frame) => Classical CAN device
MTU = 72 (CANFD_MTU) => sizeof(struct canfd_frame) => CAN FD capable device
The CAN device MTU can be retrieved e.g. with a SIOCGIFMTU ioctl() syscall.
N.B. CAN FD capable devices can also handle and send Classical CAN frames.
When configuring CAN FD capable CAN controllers an additional 'data' bitrate
has to be set. This bitrate for the data phase of the CAN FD frame has to be
at least the bitrate which was configured for the arbitration phase. This
second bitrate is specified analogue to the first bitrate but the bitrate
setting keywords for the 'data' bitrate start with 'd' e.g. dbitrate,
dsample-point, dsjw or dtq and similar settings. When a data bitrate is set
within the configuration process the controller option "fd on" can be
specified to enable the CAN FD mode in the CAN controller. This controller
option also switches the device MTU to 72 (CANFD_MTU).
The first CAN FD specification presented as whitepaper at the International
CAN Conference 2012 needed to be improved for data integrity reasons.
Therefore two CAN FD implementations have to be distinguished today:
- ISO compliant: The ISO 11898-1:2015 CAN FD implementation (default)
- non-ISO compliant: The CAN FD implementation following the 2012 whitepaper
Finally there are three types of CAN FD controllers:
1. ISO compliant (fixed)
2. non-ISO compliant (fixed, like the M_CAN IP core v3.0.1 in m_can.c)
3. ISO/non-ISO CAN FD controllers (switchable, like the PEAK PCAN-USB FD)
The current ISO/non-ISO mode is announced by the CAN controller driver via
netlink and displayed by the 'ip' tool (controller option FD-NON-ISO).
The ISO/non-ISO-mode can be altered by setting 'fd-non-iso {on|off}' for
switchable CAN FD controllers only.
Example configuring 500 kbit/s arbitration bitrate and 4 Mbit/s data bitrate::
$ ip link set can0 up type can bitrate 500000 sample-point 0.75 \
dbitrate 4000000 dsample-point 0.8 fd on
$ ip -details link show can0
5: can0: <NOARP,UP,LOWER_UP,ECHO> mtu 72 qdisc pfifo_fast state UNKNOWN \
mode DEFAULT group default qlen 10
link/can promiscuity 0
can <FD> state ERROR-ACTIVE (berr-counter tx 0 rx 0) restart-ms 0
bitrate 500000 sample-point 0.750
tq 50 prop-seg 14 phase-seg1 15 phase-seg2 10 sjw 1
pcan_usb_pro_fd: tseg1 1..64 tseg2 1..16 sjw 1..16 brp 1..1024 \
brp-inc 1
dbitrate 4000000 dsample-point 0.800
dtq 12 dprop-seg 7 dphase-seg1 8 dphase-seg2 4 dsjw 1
pcan_usb_pro_fd: dtseg1 1..16 dtseg2 1..8 dsjw 1..4 dbrp 1..1024 \
dbrp-inc 1
clock 80000000
Example when 'fd-non-iso on' is added on this switchable CAN FD adapter::
can <FD,FD-NON-ISO> state ERROR-ACTIVE (berr-counter tx 0 rx 0) restart-ms 0
Transmitter Delay Compensation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
At high bit rates, the propagation delay from the TX pin to the RX pin of
the transceiver might become greater than the actual bit time causing
measurement errors: the RX pin would still be measuring the previous bit.
The Transmitter Delay Compensation (thereafter, TDC) resolves this problem
by introducing a Secondary Sample Point (SSP) equal to the distance, in
minimum time quantum, from the start of the bit time on the TX pin to the
actual measurement on the RX pin. The SSP is calculated as the sum of two
configurable values: the TDC Value (TDCV) and the TDC offset (TDCO).
TDC, if supported by the device, can be configured together with CAN-FD
using the ip tool's "tdc-mode" argument as follow:
**omitted**
When no "tdc-mode" option is provided, the kernel will automatically
decide whether TDC should be turned on, in which case it will
calculate a default TDCO and use the TDCV as measured by the
device. This is the recommended method to use TDC.
**"tdc-mode off"**
TDC is explicitly disabled.
**"tdc-mode auto"**
The user must provide the "tdco" argument. The TDCV will be
automatically calculated by the device. This option is only
available if the device supports the TDC-AUTO CAN controller mode.
**"tdc-mode manual"**
The user must provide both the "tdco" and "tdcv" arguments. This
option is only available if the device supports the TDC-MANUAL CAN
controller mode.
Note that some devices may offer an additional parameter: "tdcf" (TDC Filter
window). If supported by your device, this can be added as an optional
argument to either "tdc-mode auto" or "tdc-mode manual".
Example configuring a 500 kbit/s arbitration bitrate, a 5 Mbit/s data
bitrate, a TDCO of 15 minimum time quantum and a TDCV automatically measured
by the device::
$ ip link set can0 up type can bitrate 500000 \
fd on dbitrate 4000000 \
tdc-mode auto tdco 15
$ ip -details link show can0
5: can0: <NOARP,UP,LOWER_UP,ECHO> mtu 72 qdisc pfifo_fast state UP \
mode DEFAULT group default qlen 10
link/can promiscuity 0 allmulti 0 minmtu 72 maxmtu 72
can <FD,TDC-AUTO> state ERROR-ACTIVE restart-ms 0
bitrate 500000 sample-point 0.875
tq 12 prop-seg 69 phase-seg1 70 phase-seg2 20 sjw 10 brp 1
ES582.1/ES584.1: tseg1 2..256 tseg2 2..128 sjw 1..128 brp 1..512 \
brp_inc 1
dbitrate 4000000 dsample-point 0.750
dtq 12 dprop-seg 7 dphase-seg1 7 dphase-seg2 5 dsjw 2 dbrp 1
tdco 15 tdcf 0
ES582.1/ES584.1: dtseg1 2..32 dtseg2 1..16 dsjw 1..8 dbrp 1..32 \
dbrp_inc 1
tdco 0..127 tdcf 0..127
clock 80000000
Supported CAN Hardware
----------------------
Please check the "Kconfig" file in "drivers/net/can" to get an actual
list of the support CAN hardware. On the SocketCAN project website
(see :ref:`socketcan-resources`) there might be further drivers available, also for
older kernel versions.
.. _socketcan-resources:
SocketCAN Resources
===================
The Linux CAN / SocketCAN project resources (project site / mailing list)
are referenced in the MAINTAINERS file in the Linux source tree.
Search for CAN NETWORK [LAYERS|DRIVERS].
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)
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
SocketCAN 개요와 socket API를 택한 이유
1-104SocketCAN - Controller Area Network
개요 / SocketCAN이란 무엇인가
socketcan package는 Linux용 CAN(Controller Area Network) protocol 구현입니다. CAN은 automation, embedded device, automotive 분야에서 널리 쓰이는 networking 기술입니다. Linux에는 character device 기반 CAN 구현도 있었지만, SocketCAN은 Berkeley socket API와 Linux network stack을 사용하고 CAN device driver를 network interface로 구현합니다. CAN socket API는 network programming에 익숙한 programmer가 쉽게 배울 수 있도록 TCP/IP protocol과 최대한 비슷하게 설계되었습니다.
동기 / socket API를 사용하는 이유
SocketCAN 이전에도 Linux CAN 구현이 있었으므로 또 다른 project를 시작한 이유를 물을 수 있습니다. 기존 구현 대부분은 특정 CAN hardware의 character device driver이며 기능이 비교적 적었습니다. 보통 controller hardware와 직접 raw CAN frame을 주고받는 hardware-specific character interface만 제공했습니다. Frame queue와 ISO-TP 같은 상위 transport protocol은 user-space application이 구현해야 했습니다. Serial interface처럼 한 번에 process 하나만 device를 열 수 있는 구현도 많았습니다. CAN controller를 바꾸면 다른 driver를 사용하고 application 상당 부분을 새 API에 맞춰야 했습니다.
SocketCAN은 이 제약을 해결하도록 설계되었습니다. 새 protocol family가 Linux network layer 위에 user-space socket interface를 제공하므로 기존 queue 기능을 활용할 수 있습니다. CAN controller driver는 Linux network layer에 network device로 등록하고 controller의 CAN frame을 network layer와 CAN protocol family module로 올리거나 반대 방향으로 내립니다.
Protocol family module은 transport protocol module 등록 API도 제공하므로 여러 transport protocol을 동적으로 load·unload할 수 있습니다. CAN core module만으로는 protocol을 제공하지 않으므로 적어도 하나의 추가 protocol module을 load해야 사용할 수 있습니다. 서로 같거나 다른 protocol module과 CAN ID에 socket 여러 개를 동시에 열 수 있고, 같은 interface의 같은 CAN ID를 구독하는 socket 모두가 일치하는 수신 frame을 받습니다. ISO-TP 같은 특정 transport protocol을 사용할 application은 socket을 열 때 해당 protocol을 선택한 뒤 CAN ID나 frame을 직접 다루지 않고 application data byte stream을 읽고 쓸 수 있습니다.
User space에서 보이는 비슷한 기능을 character device로도 만들 수 있지만 다음 이유로 기술적으로 깔끔하지 않습니다.
- 복잡한 사용법: `socket(2)`에 protocol argument를 전달하고 `bind(2)`로 CAN interface와 CAN ID를 고르는 대신 모든 작업을 `ioctl(2)`로 수행해야 합니다.
- Code 중복: character device는 Linux network queue code를 사용할 수 없으므로 CAN networking용으로 같은 code를 다시 구현해야 합니다.
- 추상화 부족: 기존 character-device 구현에서는 hardware-specific CAN controller driver가 application용 character device를 직접 제공합니다. Unix의 다른 char·block device와 비교하면 이례적입니다. UART, sound chip, SCSI·IDE controller를 직접 드러내는 대신 tty, audio, SCSI, IDE subsystem이 application용 공통 interface와 hardware driver용 interface를 나눕니다.
완전한 abstraction layer 없이 CAN driver를 character device로 구현하는 것이 가장 쉽지만, 올바른 abstraction이라면 CAN ID 등록, 여러 open file descriptor, frame (de)multiplexing, 정교한 queue, driver 등록 API를 제공해야 합니다. 이 정도를 만들 바에는 Linux kernel의 networking framework를 사용하는 편이 어렵지 않고 오히려 더 쉽습니다. SocketCAN이 바로 이 방식을 택합니다.
Linux kernel networking framework를 사용하는 것이 Linux에서 CAN을 구현하는 자연스럽고 가장 적절한 방법입니다.
===================================
SocketCAN - Controller Area Network
===================================
Overview / What is SocketCAN
============================
The socketcan package is an implementation of CAN protocols
(Controller Area Network) for Linux. CAN is a networking technology
which has widespread use in automation, embedded devices, and
automotive fields. While there have been other CAN implementations
for Linux based on character devices, SocketCAN uses the Berkeley
socket API, the Linux network stack and implements the CAN device
drivers as network interfaces. The CAN socket API has been designed
as similar as possible to the TCP/IP protocols to allow programmers,
familiar with network programming, to easily learn how to use CAN
sockets.
.. _socketcan-motivation:
Motivation / Why Using the Socket API
=====================================
There have been CAN implementations for Linux before SocketCAN so the
question arises, why we have started another project. Most existing
implementations come as a device driver for some CAN hardware, they
are based on character devices and provide comparatively little
functionality. Usually, there is only a hardware-specific device
driver which provides a character device interface to send and
receive raw CAN frames, directly to/from the controller hardware.
Queueing of frames and higher-level transport protocols like ISO-TP
have to be implemented in user space applications. Also, most
character-device implementations support only one single process to
open the device at a time, similar to a serial interface. Exchanging
the CAN controller requires employment of another device driver and
often the need for adaption of large parts of the application to the
new driver's API.
SocketCAN was designed to overcome all of these limitations. A new
protocol family has been implemented which provides a socket interface
to user space applications and which builds upon the Linux network
layer, enabling use all of the provided queueing functionality. A device
driver for CAN controller hardware registers itself with the Linux
network layer as a network device, so that CAN frames from the
controller can be passed up to the network layer and on to the CAN
protocol family module and also vice-versa. Also, the protocol family
module provides an API for transport protocol modules to register, so
that any number of transport protocols can be loaded or unloaded
dynamically. In fact, the can core module alone does not provide any
protocol and cannot be used without loading at least one additional
protocol module. Multiple sockets can be opened at the same time,
on different or the same protocol module and they can listen/send
frames on different or the same CAN IDs. Several sockets listening on
the same interface for frames with the same CAN ID are all passed the
same received matching CAN frames. An application wishing to
communicate using a specific transport protocol, e.g. ISO-TP, just
selects that protocol when opening the socket, and then can read and
write application data byte streams, without having to deal with
CAN-IDs, frames, etc.
Similar functionality visible from user-space could be provided by a
character device, too, but this would lead to a technically inelegant
solution for a couple of reasons:
* **Intricate usage:** Instead of passing a protocol argument to
socket(2) and using bind(2) to select a CAN interface and CAN ID, an
application would have to do all these operations using ioctl(2)s.
* **Code duplication:** A character device cannot make use of the Linux
network queueing code, so all that code would have to be duplicated
for CAN networking.
* **Abstraction:** In most existing character-device implementations, the
hardware-specific device driver for a CAN controller directly
provides the character device for the application to work with.
This is at least very unusual in Unix systems for both, char and
block devices. For example you don't have a character device for a
certain UART of a serial interface, a certain sound chip in your
computer, a SCSI or IDE controller providing access to your hard
disk or tape streamer device. Instead, you have abstraction layers
which provide a unified character or block device interface to the
application on the one hand, and a interface for hardware-specific
device drivers on the other hand. These abstractions are provided
by subsystems like the tty layer, the audio subsystem or the SCSI
and IDE subsystems for the devices mentioned above.
The easiest way to implement a CAN device driver is as a character
device without such a (complete) abstraction layer, as is done by most
existing drivers. The right way, however, would be to add such a
layer with all the functionality like registering for certain CAN
IDs, supporting several open file descriptors and (de)multiplexing
CAN frames between them, (sophisticated) queueing of CAN frames, and
providing an API for device drivers to register with. However, then
it would be no more difficult, or may be even easier, to use the
networking framework provided by the Linux kernel, and this is what
SocketCAN does.
The use of the networking framework of the Linux kernel is just the
natural and most appropriate way to implement CAN for Linux.
.. _socketcan-concept:
SocketCAN 개념, receive list, loopback과 오류 알림
105-205SocketCAN 개념
:ref:`socketcan-motivation`에서 설명했듯 SocketCAN의 주된 목표는 Linux network layer 위에 user-space socket interface를 제공하는 것입니다. 일반적인 TCP/IP·Ethernet과 달리 CAN bus는 broadcast-only medium이며 Ethernet 같은 MAC-layer address가 없습니다. CAN identifier(`can_id`)는 CAN bus arbitration에 쓰이므로 bus에서 고유하게 선택해야 합니다. CAN-ECU network를 설계할 때 특정 ECU가 보낼 CAN ID를 할당하며, 이런 이유로 CAN ID는 source address에 가까운 값으로 보는 것이 가장 적절합니다.
Receive List
여러 application이 network를 투명하게 공유하면 같은 CAN network interface의 같은 CAN ID에 관심을 가질 수 있습니다. Protocol family CAN을 구현하는 SocketCAN core module은 이를 위해 효율적인 receive list 여러 개를 제공합니다. 예를 들어 user-space application이 CAN RAW socket을 열면 raw protocol module은 사용자가 요청한 CAN ID 또는 범위를 SocketCAN core에 요청합니다.
CAN protocol module은 core가 제공하는 `can_rx_(un)register()` function으로 특정 CAN interface 또는 알려진 모든 CAN interface에 CAN ID를 subscribe·unsubscribe할 수 있습니다. Runtime CPU 사용을 최적화하도록 device마다 filter 복잡도에 맞춘 여러 전용 receive list로 나눕니다.
송신 frame의 local loopback
다른 network와 마찬가지로 data를 교환하는 application은 addressing 정보만 맞추면 같은 node나 다른 node에서 code 변경 없이 실행할 수 있습니다. 원문의 두 topology에서 첫 번째는 A·B·C가 각각 별도 node이고, 두 번째는 A와 B가 같은 node에 있으며 C는 별도 node입니다. 두 번째의 A가 첫 번째와 같은 정보를 받으려면 해당 node에서 보낸 CAN frame을 local loopback해야 합니다.
Linux network device는 기본적으로 medium 종속 frame의 송수신만 처리합니다. CAN bus arbitration 때문에 낮은 priority CAN ID의 송신이 높은 priority frame 수신으로 지연될 수 있습니다. Node에서 실제 traffic 순서를 정확히 반영하려면 성공적으로 송신한 직후 frame을 loopback해야 합니다. CAN network interface가 이를 수행하지 못하면 SocketCAN core가 fallback으로 처리할 수 있습니다. 자세한 내용은 :ref:`socketcan-local-loopback2`를 참조하십시오.
CAN application에 표준 network 동작을 제공하기 위해 loopback은 기본적으로 활성화됩니다. RT-SocketCAN group 요청에 따라 socket별로 비활성화할 수도 있습니다. :ref:`socketcan-raw-sockets`의 CAN RAW socket option을 참조하십시오. 같은 node에서 `candump`나 `cansniffer` 같은 analyzer를 실행할 때 정확한 loopback이 특히 필요합니다.
Network 문제 알림
CAN bus에서는 physical layer와 media access control layer에 여러 문제가 생길 수 있습니다. CAN 사용자는 physical transceiver hardware 문제, ECU 사이 arbitration 문제, error frame을 식별하기 위해 하위 계층 문제를 탐지하고 정확한 timestamp와 함께 기록해야 합니다.
CAN interface driver는 Error Message Frame을 생성하여 다른 CAN frame과 같은 방식으로 선택적으로 user application에 전달할 수 있습니다. Physical layer 또는 MAC layer error를 감지하면 driver가 해당 error message frame을 만들며, application은 일반 CAN filter mechanism으로 원하는 error 종류를 요청할 수 있습니다. Error message 수신은 기본적으로 비활성화되어 있습니다. 형식은 `include/uapi/linux/can/error.h`에 간단히 정의되어 있습니다.
SocketCAN Concept
=================
As described in :ref:`socketcan-motivation` the main goal of SocketCAN is to
provide a socket interface to user space applications which builds
upon the Linux network layer. In contrast to the commonly known
TCP/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-IDs
have to be chosen uniquely on the bus. When designing a CAN-ECU
network 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.
.. _socketcan-receive-lists:
Receive Lists
-------------
The network transparent access of multiple applications leads to the
problem that different applications may be interested in the same
CAN-IDs from the same CAN network interface. The SocketCAN core
module - which implements the protocol family CAN - provides several
high efficient receive lists for this reason. If e.g. a user space
application opens a CAN RAW socket, the raw protocol module itself
requests the (range of) CAN-IDs from the SocketCAN core that are
requested by the user. The subscription and unsubscription of
CAN-IDs can be done for specific CAN interfaces or for all(!) known
CAN interfaces with the can_rx_(un)register() functions provided to
CAN protocol modules by the SocketCAN core (see :ref:`socketcan-core-module`).
To optimize the CPU usage at runtime the receive lists are split up
into several specific lists per device that match the requested
filter complexity for a given use-case.
.. _socketcan-local-loopback1:
Local Loopback of Sent Frames
-----------------------------
As known from other networking concepts the data exchanging
applications may run on the same or different nodes without any
change (except for the according addressing information):
.. code::
___ ___ ___ _______ ___
| _ | | _ | | _ | | _ _ | | _ |
||A|| ||B|| ||C|| ||A| |B|| ||C||
|___| |___| |___| |_______| |___|
| | | | |
-----------------(1)- CAN bus -(2)---------------
To ensure that application A receives the same information in the
example (2) as it would receive in example (1) there is need for
some kind of local loopback of the sent CAN frames on the appropriate
node.
The Linux network devices (by default) just can handle the
transmission and reception of media dependent frames. Due to the
arbitration on the CAN bus the transmission of a low prio CAN-ID
may be delayed by the reception of a high prio CAN frame. To
reflect the correct [#f1]_ traffic on the node the loopback of the sent
data has to be performed right after a successful transmission. If
the CAN network interface is not capable of performing the loopback for
some reason the SocketCAN core can do this task as a fallback solution.
See :ref:`socketcan-local-loopback2` for details (recommended).
The loopback functionality is enabled by default to reflect standard
networking behaviour for CAN applications. Due to some requests from
the RT-SocketCAN group the loopback optionally may be disabled for each
separate socket. See sockopts from the CAN RAW sockets in :ref:`socketcan-raw-sockets`.
.. [#f1] you really like to have this when you're running analyser
tools like 'candump' or 'cansniffer' on the (same) node.
.. _socketcan-network-problem-notifications:
Network Problem Notifications
-----------------------------
The use of the CAN bus may lead to several problems on the physical
and media access control layer. Detecting and logging of these lower
layer problems is a vital requirement for CAN users to identify
hardware issues on the physical transceiver layer as well as
arbitration problems and error frames caused by the different
ECUs. The occurrence of detected errors are important for diagnosis
and have to be logged together with the exact timestamp. For this
reason the CAN interface driver can generate so called Error Message
Frames that can optionally be passed to the user application in the
same way as other CAN frames. Whenever an error on the physical layer
or the MAC layer is detected (e.g. by the CAN controller) the driver
creates an appropriate error message frame. Error messages frames can
be requested by the user application using the common CAN filter
mechanisms. Inside this filter definition the (interested) type of
errors may be selected. The reception of error messages is disabled
by default. The format of the CAN error message frame is briefly
described in the Linux header file "include/uapi/linux/can/error.h".
SocketCAN API와 Classical CAN frame
206-396SocketCAN 사용법
TCP/IP와 마찬가지로 CAN network 통신을 위해 먼저 socket을 엽니다. SocketCAN은 새 protocol family를 구현하므로 `socket(2)` 첫 argument로 `PF_CAN`을 전달합니다. 현재 raw socket protocol과 BCM(Broadcast Manager) 가운데 선택할 수 있습니다.
s = socket(PF_CAN, SOCK_RAW, CAN_RAW);
s = socket(PF_CAN, SOCK_DGRAM, CAN_BCM);
Socket을 만든 뒤 보통 `bind(2)`로 CAN interface에 bind합니다. Address 방식이 다르므로 TCP/IP와는 차이가 있습니다. CAN_RAW는 bind하고 CAN_BCM은 connect한 뒤 `read(2)`, `write(2)`, `send(2)`, `sendto(2)`, `sendmsg(2)`와 대응하는 `recv*` operation을 사용할 수 있습니다. 아래에는 CAN 전용 socket option도 있습니다.
Classical CAN frame(CAN 2.0B), CAN FD frame, sockaddr structure는 `include/linux/can.h`에 정의됩니다.
struct can_frame {
canid_t can_id;
union { __u8 len; __u8 can_dlc; };
__u8 __pad;
__u8 __res0;
__u8 len8_dlc;
__u8 data[8] __attribute__((aligned(8)));
};
`len`은 byte 단위 payload length이며 `can_dlc` 대신 사용해야 합니다. Deprecated `can_dlc`는 이름과 달리 DLC가 아니라 늘 평범한 byte length를 담았으므로 오해를 불렀습니다. Classical CAN network device에서 raw DLC를 전달하려면 `len`이 8일 때 `len8_dlc`에 9..15를 넣을 수 있습니다. DLC 8 이상에서 실제 payload length는 모두 8입니다.
Linear `data[]` payload를 64-bit boundary에 align하므로 사용자는 CAN payload에 쉽게 접근할 struct·union을 정의할 수 있습니다. CAN bus 자체에는 기본 byte order가 없습니다. CAN_RAW socket의 `read(2)`는 `struct can_frame`을 user space로 전달합니다.
`sockaddr_can`은 특정 interface에 bind하는 PF_PACKET socket처럼 interface index를 가집니다. `can_addr.tp`는 ISO-TP 같은 transport protocol의 `rx_id`, `tx_id`를 담고, `can_addr.j1939`는 dynamic address용 8-byte `name`, PGN, 1-byte address를 담습니다. Union의 나머지는 향후 CAN protocol address 정보용으로 예약됩니다.
Interface index는 적절한 `ioctl()`로 구합니다. CAN_RAW socket을 만들고 `ifr.ifr_name`을 `can0`로 설정한 뒤 `SIOCGIFINDEX`를 호출하여 `addr.can_ifindex`에 넣고 `AF_CAN` family로 bind합니다.
모든 CAN interface에 bind하려면 interface index를 0으로 설정합니다. 이 socket은 활성화된 모든 CAN interface의 frame을 받습니다. 어느 interface에서 왔는지 확인하려면 `read(2)` 대신 `recvfrom(2)`을 사용합니다. `any` interface에 bind한 socket에서 송신할 때는 `sendto(2)`로 outgoing interface를 지정해야 합니다.
Bound CAN_RAW socket에서 frame을 읽을 때는 `struct can_frame` 크기로 `read()`하고 음수 오류와 불완전한 frame을 검사합니다. 송신은 같은 크기로 `write()`합니다. `any` socket에서는 `recvfrom()`이 채운 `addr.can_ifindex`를 `SIOCGIFNAME`으로 interface name으로 변환할 수 있고, 송신 시 `SIOCGIFINDEX`로 target index를 구해 `sendto()`에 전달합니다.
Message를 읽은 직후 `SIOCGSTAMP` ioctl로 정확한 timestamp를 얻을 수 있습니다. Timestamp는 1 microsecond resolution이며 CAN frame 수신 시 자동으로 설정됩니다.
How to use SocketCAN
====================
Like TCP/IP, you first need to open a socket for communicating over a
CAN network. Since SocketCAN implements a new protocol family, you
need to pass PF_CAN as the first argument to the socket(2) system
call. Currently, there are two CAN protocols to choose from, the raw
socket protocol and the broadcast manager (BCM). So to open a socket,
you would write::
s = socket(PF_CAN, SOCK_RAW, CAN_RAW);
and::
s = socket(PF_CAN, SOCK_DGRAM, CAN_BCM);
respectively. After the successful creation of the socket, you would
normally use the bind(2) system call to bind the socket to a CAN
interface (which is different from TCP/IP due to different addressing
- see :ref:`socketcan-concept`). After binding (CAN_RAW) or connecting (CAN_BCM)
the socket, you can read(2) and write(2) from/to the socket or use
send(2), sendto(2), sendmsg(2) and the recv* counterpart operations
on the socket as usual. There are also CAN specific socket options
described below.
The Classical CAN frame structure (aka CAN 2.0B), the CAN FD frame structure
and the sockaddr structure are defined in include/linux/can.h:
.. code-block:: C
struct can_frame {
canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */
union {
/* CAN frame payload length in byte (0 .. CAN_MAX_DLEN)
* was previously named can_dlc so we need to carry that
* name for legacy support
*/
__u8 len;
__u8 can_dlc; /* deprecated */
};
__u8 __pad; /* padding */
__u8 __res0; /* reserved / padding */
__u8 len8_dlc; /* optional DLC for 8 byte payload length (9 .. 15) */
__u8 data[8] __attribute__((aligned(8)));
};
Remark: The len element contains the payload length in bytes and should be
used instead of can_dlc. The deprecated can_dlc was misleadingly named as
it always contained the plain payload length in bytes and not the so called
'data length code' (DLC).
To pass the raw DLC from/to a Classical CAN network device the len8_dlc
element can contain values 9 .. 15 when the len element is 8 (the real
payload length for all DLC values greater or equal to 8).
The alignment of the (linear) payload data[] to a 64bit boundary
allows the user to define their own structs and unions to easily access
the CAN payload. There is no given byteorder on the CAN bus by
default. A read(2) system call on a CAN_RAW socket transfers a
struct can_frame to the user space.
The sockaddr_can structure has an interface index like the
PF_PACKET socket, that also binds to a specific interface:
.. code-block:: C
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;
/* J1939 address information */
struct {
/* 8 byte name when using dynamic addressing */
__u64 name;
/* pgn:
* 8 bit: PS in PDU2 case, else 0
* 8 bit: PF
* 1 bit: DP
* 1 bit: reserved
*/
__u32 pgn;
/* 1 byte address */
__u8 addr;
} j1939;
/* reserved for future CAN protocols address information */
} can_addr;
};
To determine the interface index an appropriate ioctl() has to
be used (example for CAN_RAW sockets without error checking):
.. code-block:: C
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 must
be 0 (zero). In this case the socket receives CAN frames from every
enabled CAN interface. To determine the originating CAN interface
the system call recvfrom(2) may be used instead of read(2). To send
on a socket that is bound to 'any' interface sendto(2) is needed to
specify the outgoing interface.
Reading CAN frames from a bound CAN_RAW socket (see above) consists
of reading a struct can_frame:
.. code-block:: C
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 the
information about the originating CAN interface is needed:
.. code-block:: C
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 the
outgoing interface has to be defined certainly:
.. code-block:: C
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));
An accurate timestamp can be obtained with an ioctl(2) call after reading
a message from the socket:
.. code-block:: C
struct timeval tv;
ioctl(s, SIOCGSTAMP, &tv);
The timestamp has a resolution of one microsecond and is set automatically
at the reception of a CAN frame.
CAN FD structure, MTU와 반환 flag
397-466CAN FD(flexible data rate) 지원 참고
CAN FD controller는 arbitration phase와 payload phase에 서로 다른 두 bitrate를 지원하고 최대 64 byte payload를 제공합니다. 이 확장 길이는 8-byte 고정 payload인 `struct can_frame`에 의존하던 CAN_RAW 같은 kernel ABI와 호환되지 않습니다. 따라서 CAN_RAW socket은 `CAN_RAW_FD_FRAMES` option으로 CAN FD와 Classical CAN frame을 동시에 처리하는 mode를 제공합니다.
`struct canfd_frame`은 `include/linux/can.h`에 정의됩니다.
struct canfd_frame {
canid_t can_id;
__u8 len;
__u8 flags;
__u8 __res0;
__u8 __res1;
__u8 data[64] __attribute__((aligned(8)));
};
`struct canfd_frame`과 `struct can_frame`은 내부에서 `can_id`, payload length, payload data가 같은 offset에 있습니다. 따라서 두 structure를 비슷하게 처리할 수 있으며 `can_frame`을 `canfd_frame`에 복사해도 `data[]`가 확장될 뿐 기존 element를 그대로 사용할 수 있습니다.
Classical CAN의 DLC는 0..8에서 length와 1:1이어서 length 정보처럼 사용되었습니다. 단순한 처리를 유지하기 위해 `canfd_frame.len`은 0..64의 실제 length를 담습니다. `can_frame.len`도 DLC가 아니라 length입니다. CAN/CAN FD device 구분과 bus DLC mapping은 :ref:`socketcan-can-fd-driver`를 참조하십시오.
두 CAN(FD) frame structure의 길이는 CAN(FD) network interface MTU와 skbuff data length를 정의합니다. `CAN_MTU = sizeof(struct can_frame) = 16`은 Classical CAN, `CANFD_MTU = sizeof(struct canfd_frame) = 72`는 CAN FD입니다.
반환 message flag
RAW 또는 BCM socket에서 `recvmsg(2)`를 사용하면 `msg->msg_flags`에 다음 flag가 들어올 수 있습니다.
- `MSG_DONTROUTE`: 수신 frame이 local host에서 생성되었을 때 설정됩니다.
- `MSG_CONFIRM`: frame을 수신한 바로 그 socket을 통해 송신했을 때 설정됩니다. Driver가 frame echo를 지원하면 transmission confirmation으로 해석할 수 있습니다. RAW socket에서 이 message를 받으려면 `CAN_RAW_RECV_OWN_MSGS`를 설정해야 합니다.
Remark about CAN FD (flexible data rate) support:
Generally the handling of CAN FD is very similar to the formerly described
examples. The new CAN FD capable CAN controllers support two different
bitrates for the arbitration phase and the payload phase of the CAN FD frame
and up to 64 bytes of payload. This extended payload length breaks all the
kernel interfaces (ABI) which heavily rely on the CAN frame with fixed eight
bytes of payload (struct can_frame) like the CAN_RAW socket. Therefore e.g.
the CAN_RAW socket supports a new socket option CAN_RAW_FD_FRAMES that
switches the socket into a mode that allows the handling of CAN FD frames
and Classical CAN frames simultaneously (see :ref:`socketcan-rawfd`).
The struct canfd_frame is defined in include/linux/can.h:
.. code-block:: C
struct canfd_frame {
canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */
__u8 len; /* frame payload length in byte (0 .. 64) */
__u8 flags; /* additional flags for CAN FD */
__u8 __res0; /* reserved / padding */
__u8 __res1; /* reserved / padding */
__u8 data[64] __attribute__((aligned(8)));
};
The struct canfd_frame and the existing struct can_frame have the can_id,
the payload length and the payload data at the same offset inside their
structures. This allows to handle the different structures very similar.
When the content of a struct can_frame is copied into a struct canfd_frame
all structure elements can be used as-is - only the data[] becomes extended.
When introducing the struct canfd_frame it turned out that the data length
code (DLC) of the struct can_frame was used as a length information as the
length and the DLC has a 1:1 mapping in the range of 0 .. 8. To preserve
the easy handling of the length information the canfd_frame.len element
contains a plain length value from 0 .. 64. So both canfd_frame.len and
can_frame.len are equal and contain a length information and no DLC.
For details about the distinction of CAN and CAN FD capable devices and
the mapping to the bus-relevant data length code (DLC), see :ref:`socketcan-can-fd-driver`.
The length of the two CAN(FD) frame structures define the maximum transfer
unit (MTU) of the CAN(FD) network interface and skbuff data length. Two
definitions are specified for CAN specific MTUs in include/linux/can.h:
.. code-block:: C
#define CAN_MTU (sizeof(struct can_frame)) == 16 => Classical CAN frame
#define CANFD_MTU (sizeof(struct canfd_frame)) == 72 => CAN FD frame
Returned Message Flags
----------------------
When using the system call recvmsg(2) on a RAW or a BCM socket, the
msg->msg_flags field may contain the following flags:
MSG_DONTROUTE:
set when the received frame was created on the local host.
MSG_CONFIRM:
set when the frame was sent via the socket it is received on.
This flag can be interpreted as a 'transmission confirmation' when the
CAN driver supports the echo of frames on driver level, see
:ref:`socketcan-local-loopback1` and :ref:`socketcan-local-loopback2`.
(Note: In order to receive such messages on a RAW socket,
CAN_RAW_RECV_OWN_MSGS must be set.)
.. _socketcan-raw-sockets:
CAN_RAW 기본값과 filter 최적화
467-576`can_filter`를 사용하는 RAW protocol socket(`SOCK_RAW`)
CAN_RAW socket 사용법은 기존 CAN character device 접근과 상당히 비슷하지만, multi-user SocketCAN에 맞춰 bind 시 다음 기본값을 적용합니다.
- 모든 frame을 받는 filter 하나를 설정합니다.
- Valid data frame만 받고 error message frame은 받지 않습니다.
- 송신 CAN frame의 loopback을 활성화합니다.
- Loopback mode에서도 자신이 보낸 frame을 같은 socket으로 받지는 않습니다.
이 기본값은 bind 전후에 변경할 수 있습니다. CAN_RAW socket option 정의를 사용하려면 `<linux/can/raw.h>`를 include하십시오.
RAW socket option `CAN_RAW_FILTER`
CAN_RAW frame 수신은 `CAN_RAW_FILTER` socket option에 filter 0..n개를 지정해 제어합니다. `struct can_filter`는 `can_id`와 `can_mask`로 구성됩니다.
struct can_filter {
canid_t can_id;
canid_t can_mask;
};
<received_can_id> & mask == can_id & mask
Match semantics는 CAN controller hardware filter와 같습니다. `can_filter.can_id`에 `CAN_INV_FILTER` bit를 설정하면 의미를 반전할 수 있습니다. Hardware filter와 달리 open socket마다 receive filter 0..n개를 독립적으로 설정할 수 있습니다.
예에서는 `0x123`과 `0x200/0x700` 범위 filter 두 개를 `setsockopt(SOL_CAN_RAW, CAN_RAW_FILTER, ...)`로 설정합니다. `NULL, 0`을 전달하면 선택한 CAN_RAW socket의 frame 수신을 비활성화합니다. 읽지 않아도 raw socket이 frame을 버리므로 zero filter는 보통 필요 없지만, send-only 용도에서는 kernel receive list를 제거해 아주 적은 CPU를 절약합니다.
CAN filter 사용 최적화
CAN core는 수신 시 device별 filter list를 순회합니다. 단일 CAN ID 구독은 최적화된 처리를 사용합니다. 2048개 SFF identifier는 identifier를 subscription list index로 직접 사용하고, 2^29개 EFF identifier는 10-bit XOR folding hash로 EFF table index를 구합니다.
단일 ID 최적화를 사용하려면 `can_filter.mask`에 `CAN_SFF_MASK` 또는 `CAN_EFF_MASK`와 함께 `CAN_EFF_FLAG`, `CAN_RTR_FLAG` bit를 설정해야 합니다. `CAN_EFF_FLAG`가 mask에 있으면 SFF와 EFF 중 어느 형식을 구독하는지가 중요하다는 뜻입니다.
Mask가 `CAN_SFF_MASK`뿐이면 SFF `0x123`뿐 아니라 하위 bit가 같은 EFF `0xXXXXX123`도 통과할 수 있습니다. SFF `0x123`과 EFF `0x12345678`만 받으려면 첫 filter mask를 `CAN_EFF_FLAG | CAN_RTR_FLAG | CAN_SFF_MASK`, 두 번째를 `CAN_EFF_FLAG | CAN_RTR_FLAG | CAN_EFF_MASK`로 지정하고 EFF can_id에는 `CAN_EFF_FLAG`를 더합니다.
RAW Protocol Sockets with can_filters (SOCK_RAW)
------------------------------------------------
Using CAN_RAW sockets is extensively comparable to the commonly
known access to CAN character devices. To meet the new possibilities
provided by the multi user SocketCAN approach, some reasonable
defaults 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 message frames)
- The loopback of sent CAN frames is enabled (see :ref:`socketcan-local-loopback2`)
- 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_RAW
sockets, include <linux/can/raw.h>.
.. _socketcan-rawfilter:
RAW socket option CAN_RAW_FILTER
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The reception of CAN frames using CAN_RAW sockets can be controlled
by defining 0 .. n filters with the CAN_RAW_FILTER socket option.
The CAN filter structure is defined in include/linux/can.h:
.. code-block:: C
struct can_filter {
canid_t can_id;
canid_t can_mask;
};
A filter matches, when:
.. code-block:: C
<received_can_id> & mask == can_id & mask
which is analogous to known CAN controllers hardware filter semantics.
The filter can be inverted in this semantic, when the CAN_INV_FILTER
bit is set in can_id element of the can_filter structure. In
contrast to CAN controller hardware filters the user may set 0 .. n
receive filters for each open socket separately:
.. code-block:: C
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:
.. code-block:: C
setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);
To set the filters to zero filters is quite obsolete as to not read
data causes the raw socket to discard the received CAN frames. But
having this 'send only' use-case we may remove the receive list in the
Kernel to save a little (really a very little!) CPU usage.
CAN Filter Usage Optimisation
.............................
The CAN filters are processed in per-device filter lists at CAN frame
reception time. To reduce the number of checks that need to be performed
while walking through the filter lists the CAN core provides an optimized
filter handling when the filter subscription focuses on a single CAN ID.
For the possible 2048 SFF CAN identifiers the identifier is used as an index
to access the corresponding subscription list without any further checks.
For the 2^29 possible EFF CAN identifiers a 10 bit XOR folding is used as
hash function to retrieve the EFF table index.
To benefit from the optimized filters for single CAN identifiers the
CAN_SFF_MASK or CAN_EFF_MASK have to be set into can_filter.mask together
with set CAN_EFF_FLAG and CAN_RTR_FLAG bits. A set CAN_EFF_FLAG bit in the
can_filter.mask makes clear that it matters whether a SFF or EFF CAN ID is
subscribed. E.g. in the example from above:
.. code-block:: C
rfilter[0].can_id = 0x123;
rfilter[0].can_mask = CAN_SFF_MASK;
both SFF frames with CAN ID 0x123 and EFF frames with 0xXXXXX123 can pass.
To filter for only 0x123 (SFF) and 0x12345678 (EFF) CAN identifiers the
filter has to be defined in this way to benefit from the optimized filters:
.. code-block:: C
struct can_filter rfilter[2];
rfilter[0].can_id = 0x123;
rfilter[0].can_mask = (CAN_EFF_FLAG | CAN_RTR_FLAG | CAN_SFF_MASK);
rfilter[1].can_id = 0x12345678 | CAN_EFF_FLAG;
rfilter[1].can_mask = (CAN_EFF_FLAG | CAN_RTR_FLAG | CAN_EFF_MASK);
setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter));
CAN_RAW error, loopback, FD와 JOIN_FILTERS option
577-713RAW socket option `CAN_RAW_ERR_FILTER`
CAN interface driver가 만드는 Error Message Frame은 다른 CAN frame처럼 선택적으로 application에 전달할 수 있습니다. Error class별 mask로 filter하며 모든 error condition을 구독하려면 `CAN_ERR_MASK`를 사용합니다. 값은 `linux/can/error.h`에 정의됩니다. 예에서는 `CAN_ERR_TX_TIMEOUT | CAN_ERR_BUSOFF`를 `CAN_RAW_ERR_FILTER`로 설정합니다.
RAW socket option `CAN_RAW_LOOPBACK`
Multi-user 요구를 위해 local loopback은 기본 활성화됩니다. Application 하나만 CAN bus를 쓰는 embedded 용도 등에서는 socket별로 `CAN_RAW_LOOPBACK`을 0으로 설정해 끌 수 있습니다.
RAW socket option `CAN_RAW_RECV_OWN_MSGS`
Local loopback이 켜지면 송신 frame의 CAN ID를 등록한 같은 interface의 모든 open CAN socket으로 frame을 돌려보냅니다. 다만 보낸 socket 자신이 다시 받는 것은 원하지 않는다고 보아 기본 비활성화합니다. 필요하면 `CAN_RAW_RECV_OWN_MSGS`를 1로 설정합니다. Own frame도 다른 frame과 같은 filter를 적용받습니다.
RAW socket option `CAN_RAW_FD_FRAMES`
CAN_RAW socket의 CAN FD 지원은 기본적으로 꺼진 `CAN_RAW_FD_FRAMES` option으로 활성화합니다. 오래된 kernel처럼 지원하지 않으면 설정 시 `-ENOPROTOOPT`를 반환합니다. 활성화하면 application은 CAN과 CAN FD frame을 모두 송수신하고 두 형식을 모두 처리해야 합니다. 활성화 시 `CAN_MTU`와 `CANFD_MTU`가 허용되고, 비활성화 시 `CAN_MTU`만 허용됩니다.
`struct canfd_frame` buffer를 `CANFD_MTU` 크기로 읽고 반환값이 `CANFD_MTU`면 CAN FD frame, `CAN_MTU`면 Classical CAN frame입니다. 후자의 경우 `cfd.flags`는 정의되지 않습니다. 공통 offset 덕분에 `can_id`, `len`, `data[]`는 MTU와 무관하게 처리할 수 있습니다.
새 CAN application은 CAN_RAW 기본 data structure로 `struct canfd_frame`을 사용하는 것이 좋습니다. 오래된 kernel에서 FD option 설정이 실패해도 Classical CAN frame을 같은 방식으로 받을 수 있습니다. 송신 전에는 `SIOCGIFMTU` 등으로 device MTU가 `CANFD_MTU`인지 확인하여 CAN FD 지원 여부를 검증하십시오.
RAW socket option `CAN_RAW_JOIN_FILTERS`
기본적으로 여러 CAN filter는 서로 독립적이어서 논리 OR로 적용됩니다. 이 option은 모든 filter에 일치한 frame만 user space로 전달하도록 의미를 논리 AND로 바꿉니다. `CAN_INV_FILTER`를 사용해 incoming traffic에서 특정 CAN ID 또는 범위를 제외하는 filter 조합에 특히 유용합니다.
RAW Socket Option CAN_RAW_ERR_FILTER
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
As described in :ref:`socketcan-network-problem-notifications` the CAN interface driver can generate so
called Error Message Frames that can optionally be passed to the user
application in the same way as other CAN frames. The possible
errors are divided into different error classes that may be filtered
using the appropriate error mask. To register for every possible
error 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:
.. code-block:: C
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));
RAW Socket Option CAN_RAW_LOOPBACK
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To meet multi user needs the local loopback is enabled by default
(see :ref:`socketcan-local-loopback1` for details). But in some embedded use-cases
(e.g. when only one application uses the CAN bus) this loopback
functionality can be disabled (separately for each socket):
.. code-block:: C
int loopback = 0; /* 0 = disabled, 1 = enabled (default) */
setsockopt(s, SOL_CAN_RAW, CAN_RAW_LOOPBACK, &loopback, sizeof(loopback));
RAW socket option CAN_RAW_RECV_OWN_MSGS
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When the local loopback is enabled, all the sent CAN frames are
looped back to the open CAN sockets that registered for the CAN
frames' CAN-ID on this given interface to meet the multi user
needs. The reception of the CAN frames on the same socket that was
sending the CAN frame is assumed to be unwanted and therefore
disabled by default. This default behaviour may be changed on
demand:
.. code-block:: C
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));
Note that reception of a socket's own CAN frames are subject to the same
filtering as other CAN frames (see :ref:`socketcan-rawfilter`).
.. _socketcan-rawfd:
RAW Socket Option CAN_RAW_FD_FRAMES
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CAN FD support in CAN_RAW sockets can be enabled with a new socket option
CAN_RAW_FD_FRAMES which is off by default. When the new socket option is
not supported by the CAN_RAW socket (e.g. on older kernels), switching the
CAN_RAW_FD_FRAMES option returns the error -ENOPROTOOPT.
Once CAN_RAW_FD_FRAMES is enabled the application can send both CAN frames
and CAN FD frames. OTOH the application has to handle CAN and CAN FD frames
when reading from the socket:
.. code-block:: C
CAN_RAW_FD_FRAMES enabled: CAN_MTU and CANFD_MTU are allowed
CAN_RAW_FD_FRAMES disabled: only CAN_MTU is allowed (default)
Example:
.. code-block:: C
[ remember: CANFD_MTU == sizeof(struct canfd_frame) ]
struct canfd_frame cfd;
nbytes = read(s, &cfd, CANFD_MTU);
if (nbytes == CANFD_MTU) {
printf("got CAN FD frame with length %d\n", cfd.len);
/* cfd.flags contains valid data */
} else if (nbytes == CAN_MTU) {
printf("got Classical CAN frame with length %d\n", cfd.len);
/* cfd.flags is undefined */
} else {
fprintf(stderr, "read: invalid CAN(FD) frame\n");
return 1;
}
/* the content can be handled independently from the received MTU size */
printf("can_id: %X data length: %d data: ", cfd.can_id, cfd.len);
for (i = 0; i < cfd.len; i++)
printf("%02X ", cfd.data[i]);
When reading with size CANFD_MTU only returns CAN_MTU bytes that have
been received from the socket a Classical CAN frame has been read into the
provided CAN FD structure. Note that the canfd_frame.flags data field is
not specified in the struct can_frame and therefore it is only valid in
CANFD_MTU sized CAN FD frames.
Implementation hint for new CAN applications:
To build a CAN FD aware application use struct canfd_frame as basic CAN
data structure for CAN_RAW based applications. When the application is
executed on an older Linux kernel and switching the CAN_RAW_FD_FRAMES
socket option returns an error: No problem. You'll get Classical CAN frames
or CAN FD frames and can process them the same way.
When sending to CAN devices make sure that the device is capable to handle
CAN FD frames by checking if the device maximum transfer unit is CANFD_MTU.
The CAN device MTU can be retrieved e.g. with a SIOCGIFMTU ioctl() syscall.
RAW socket option CAN_RAW_JOIN_FILTERS
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The CAN_RAW socket can set multiple CAN identifier specific filters that
lead to multiple filters in the af_can.c filter processing. These filters
are independent from each other which leads to logical OR'ed filters when
applied (see :ref:`socketcan-rawfilter`).
This socket option joins the given CAN filters in the way that only CAN
frames are passed to user space that matched *all* given CAN filters. The
semantic for the applied filters is therefore changed to a logical AND.
This is useful especially when the filterset is a combination of filters
where the CAN_INV_FILTER flag is set in order to notch single CAN IDs or
CAN ID ranges from the incoming traffic.
Broadcast Manager socket과 operation
714-837Broadcast Manager Protocol Socket(`SOCK_DGRAM`)
BCM protocol은 kernel space에서 CAN message를 filter하고 주기적으로 송신하는 command 기반 configuration interface를 제공합니다. Receive filter는 빈번한 message를 down-sample하고 content·packet length 변화 같은 event를 감지하며 수신 timeout을 monitor할 수 있습니다.
CAN frame 하나 또는 frame sequence의 periodic transmission task를 runtime에 생성·수정할 수 있습니다. Message content와 가능한 두 transmit interval 모두 바꿀 수 있습니다.
BCM socket은 CAN_RAW처럼 개별 `struct can_frame`을 보내기 위한 것이 아닙니다. `linux/can/bcm.h`의 특별한 BCM configuration message를 사용합니다. Message는 command인 `opcode`를 담은 header와 뒤따르는 0개 이상의 CAN frame으로 구성되며 response도 같은 형식입니다.
struct bcm_msg_head {
__u32 opcode;
__u32 flags;
__u32 count;
struct timeval ival1, ival2;
canid_t can_id;
__u32 nframes;
struct can_frame frames[];
};
Aligned `frames` payload는 `include/linux/can.h`의 기본 CAN frame structure를 사용합니다. CAN_BCM socket은 생성 후 bind가 아니라 connect해야 합니다. `PF_CAN`, `SOCK_DGRAM`, `CAN_BCM`으로 열고 interface index와 `AF_CAN`을 설정해 `connect()`합니다.
BCM socket 하나는 진행 중인 transmission과 receive filter를 여러 개 동시에 처리할 수 있으며 BCM message의 고유 `can_id`로 RX/TX job을 구분합니다. 여러 CAN interface와 통신하려면 추가 CAN_BCM socket 사용을 권장합니다. Interface index 0인 `any`에 연결하면 receive filter가 모든 interface에 적용되며, `sendto()`로 이를 override할 수 있습니다. `recvfrom()`을 사용하면 originating `can_ifindex`를 얻습니다.
Broadcast Manager operation
Transmit operation(user space → BCM)
- `TX_SETUP`: 주기적 transmission task를 생성합니다.
- `TX_DELETE`: `can_id`에 해당하는 주기적 task를 제거합니다.
- `TX_READ`: `can_id` task의 속성을 읽습니다.
- `TX_SEND`: CAN frame 하나를 보냅니다.
Transmit response(BCM → user space)
- `TX_STATUS`: `TX_READ` 요청에 transmission task configuration으로 응답합니다.
- `TX_EXPIRED`: 초기 interval `ival1`에서 `count`회 송신이 끝났음을 알립니다. `TX_SETUP`에서 `TX_COUNTEVT`가 필요합니다.
Receive operation(user space → BCM)
- `RX_SETUP`: RX content filter subscription을 생성합니다.
- `RX_DELETE`: `can_id`에 해당하는 RX subscription을 제거합니다.
- `RX_READ`: `can_id` RX filter 속성을 읽습니다.
Receive response(BCM → user space)
- `RX_STATUS`: `RX_READ`에 filter task configuration으로 응답합니다.
- `RX_TIMEOUT`: `ival1` timer가 만료되어 cyclic message가 없음을 알립니다.
- `RX_CHANGED`: 처음 수신했거나 CAN frame content 변화가 감지되면 갱신 frame을 담아 보냅니다.
Broadcast Manager Protocol Sockets (SOCK_DGRAM)
-----------------------------------------------
The Broadcast Manager protocol provides a command based configuration
interface to filter and send (e.g. cyclic) CAN messages in kernel space.
Receive filters can be used to down sample frequent messages; detect events
such as message contents changes, packet length changes, and do time-out
monitoring of received messages.
Periodic transmission tasks of CAN frames or a sequence of CAN frames can be
created and modified at runtime; both the message content and the two
possible transmit intervals can be altered.
A BCM socket is not intended for sending individual CAN frames using the
struct can_frame as known from the CAN_RAW socket. Instead a special BCM
configuration message is defined. The basic BCM configuration message used
to communicate with the broadcast manager and the available operations are
defined in the linux/can/bcm.h include. The BCM message consists of a
message header with a command ('opcode') followed by zero or more CAN frames.
The broadcast manager sends responses to user space in the same form:
.. code-block:: C
struct bcm_msg_head {
__u32 opcode; /* command */
__u32 flags; /* special flags */
__u32 count; /* run 'count' times with ival1 */
struct timeval ival1, ival2; /* count and subsequent interval */
canid_t can_id; /* unique can_id for task */
__u32 nframes; /* number of can_frames following */
struct can_frame frames[];
};
The aligned payload 'frames' uses the same basic CAN frame structure defined
at the beginning of :ref:`socketcan-rawfd` and in the include/linux/can.h include. All
messages to the broadcast manager from user space have this structure.
Note a CAN_BCM socket must be connected instead of bound after socket
creation (example without error checking):
.. code-block:: C
int s;
struct sockaddr_can addr;
struct ifreq ifr;
s = socket(PF_CAN, SOCK_DGRAM, CAN_BCM);
strcpy(ifr.ifr_name, "can0");
ioctl(s, SIOCGIFINDEX, &ifr);
addr.can_family = AF_CAN;
addr.can_ifindex = ifr.ifr_ifindex;
connect(s, (struct sockaddr *)&addr, sizeof(addr));
(..)
The broadcast manager socket is able to handle any number of in flight
transmissions or receive filters concurrently. The different RX/TX jobs are
distinguished by the unique can_id in each BCM message. However additional
CAN_BCM sockets are recommended to communicate on multiple CAN interfaces.
When the broadcast manager socket is bound to 'any' CAN interface (=> the
interface index is set to zero) the configured receive filters apply to any
CAN interface unless the sendto() syscall is used to overrule the 'any' CAN
interface index. When using recvfrom() instead of read() to retrieve BCM
socket messages the originating CAN interface is provided in can_ifindex.
Broadcast Manager Operations
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The opcode defines the operation for the broadcast manager to carry out,
or details the broadcast managers response to several events, including
user requests.
Transmit Operations (user space to broadcast manager):
TX_SETUP:
Create (cyclic) transmission task.
TX_DELETE:
Remove (cyclic) transmission task, requires only can_id.
TX_READ:
Read properties of (cyclic) transmission task for can_id.
TX_SEND:
Send one CAN frame.
Transmit Responses (broadcast manager to user space):
TX_STATUS:
Reply to TX_READ request (transmission task configuration).
TX_EXPIRED:
Notification when counter finishes sending at initial interval
'ival1'. Requires the TX_COUNTEVT flag to be set at TX_SETUP.
Receive Operations (user space to broadcast manager):
RX_SETUP:
Create RX content filter subscription.
RX_DELETE:
Remove RX content filter subscription, requires only can_id.
RX_READ:
Read properties of RX content filter subscription for can_id.
Receive Responses (broadcast manager to user space):
RX_STATUS:
Reply to RX_READ request (filter task configuration).
RX_TIMEOUT:
Cyclic message is detected to be absent (timer ival1 expired).
RX_CHANGED:
BCM message with updated CAN frame (detected content change).
Sent on first message received or on receipt of revised CAN messages.
BCM flag, timer, sequence, multiplex filter와 CAN FD
838-999Broadcast Manager message flag
BCM에 보내는 message의 `flags`는 다음 동작을 제어합니다.
- `SETTIMER`: `ival1`, `ival2`, `count` 값을 설정합니다.
- `STARTTIMER`: 현재 `ival1`, `ival2`, `count`로 timer를 시작하고 동시에 CAN frame 하나를 내보냅니다.
- `TX_COUNTEVT`: `count`가 끝나면 `TX_EXPIRED`를 생성합니다.
- `TX_ANNOUNCE`: process가 data를 바꾸면 즉시 내보냅니다.
- `TX_CP_CAN_ID`: message header의 `can_id`를 뒤따르는 모든 frame에 복사합니다. TX task의 고유 task ID와 실제 송신 frame ID는 달라도 됩니다.
- `RX_FILTER_ID`: frame 없이(`nframes=0`) `can_id`만으로 filter합니다.
- `RX_CHECK_DLC`: DLC 변화도 `RX_CHANGED`를 발생시킵니다.
- `RX_NO_AUTOTIMER`: timeout monitor 자동 시작을 막습니다.
- `RX_ANNOUNCE_RESUME`: `RX_SETUP`에 설정하고 timeout이 발생했다면 cyclic receive가 재개될 때 `RX_CHANGED`를 만듭니다.
- `TX_RESET_MULTI_IDX`: multiple-frame transmission index를 reset합니다.
- `RX_RTR_FRAME`: `op->frames[0]`에 둔 RTR request 응답을 보냅니다.
- `CAN_FD_FRAME`: `bcm_msg_head` 뒤 frame이 `struct canfd_frame`임을 뜻합니다.
BCM transmission timer
Periodic transmission은 timer 두 개까지 사용할 수 있습니다. `ival1` 간격으로 `count`개 message를 보낸 뒤 `ival2` 간격으로 계속 송신합니다. Timer 하나만 필요하면 `count=0`으로 두고 `ival2`만 사용합니다. `SET_TIMER`와 `START_TIMER`를 설정하면 timer가 활성화되고, runtime에 값만 바꾸려면 `SET_TIMER`만 설정합니다.
BCM message sequence transmission
Cyclic TX task는 최대 256개 CAN frame을 sequence로 보낼 수 있습니다. Frame 수는 header `nframes`에 넣고 해당 개수의 array를 `TX_SETUP` message 뒤에 붙입니다. 송신할 때마다 array index가 증가하며 끝을 넘으면 0으로 돌아갑니다.
BCM receive filter timer
- `ival1`: 주어진 시간 안에 같은 message가 다시 오지 않으면 `RX_TIMEOUT`을 보냅니다. `RX_SETUP`에 `START_TIMER`도 설정하면 이전 CAN frame을 받기 전부터 timeout 감지를 시작합니다.
- `ival2`: 수신 message rate를 이 값으로 throttle합니다. CAN frame 안 signal이 stateless일 때 application message를 줄이는 데 유용하지만 interval 안의 state change가 사라질 수 있습니다.
BCM multiplex message receive filter
Multiplex message sequence의 content 변화를 filter하려면 `RX_SETUP`에 CAN frame array를 둘 이상 전달합니다. 첫 frame의 data byte는 이후 filter frame과 수신 CAN frame에서 일치해야 하는 relevant bit mask입니다. 이후 frame 하나가 multiplex bit에 일치하면 그 frame의 data mark가 이전 수신 content와 비교할 relevant content를 정합니다.
Multiplex filter mask frame 1개와 CAN filter 최대 256개, 총 257개 frame을 array로 추가할 수 있습니다. 예제는 `U64_DATA` macro로 data를 다루며 endian 문제를 경고하고, CAN ID `0x42`에 MUX mask와 MUX `0x01`, `0x02`, `0x33`, `0x4F`별 data mask를 설정합니다.
BCM CAN FD 지원
CAN_BCM API는 `bcm_msg_head` 바로 뒤의 `struct can_frame` array를 전제로 합니다. CAN FD도 같은 schema를 사용하기 위해 header flag `CAN_FD_FRAME`으로 뒤따르는 structure가 `struct canfd_frame`임을 표시합니다. CAN FD multiplex filtering에서도 MUX mask는 `canfd_frame.data`의 첫 64 bit에 있어야 합니다.
Broadcast Manager Message Flags
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When sending a message to the broadcast manager the 'flags' element may
contain the following flag definitions which influence the behaviour:
SETTIMER:
Set the values of ival1, ival2 and count
STARTTIMER:
Start the timer with the actual values of ival1, ival2
and count. Starting the timer leads simultaneously to emit a CAN frame.
TX_COUNTEVT:
Create the message TX_EXPIRED when count expires
TX_ANNOUNCE:
A change of data by the process is emitted immediately.
TX_CP_CAN_ID:
Copies the can_id from the message header to each
subsequent frame in frames. This is intended as usage simplification. For
TX tasks the unique can_id from the message header may differ from the
can_id(s) stored for transmission in the subsequent struct can_frame(s).
RX_FILTER_ID:
Filter by can_id alone, no frames required (nframes=0).
RX_CHECK_DLC:
A change of the DLC leads to an RX_CHANGED.
RX_NO_AUTOTIMER:
Prevent automatically starting the timeout monitor.
RX_ANNOUNCE_RESUME:
If passed at RX_SETUP and a receive timeout occurred, a
RX_CHANGED message will be generated when the (cyclic) receive restarts.
TX_RESET_MULTI_IDX:
Reset the index for the multiple frame transmission.
RX_RTR_FRAME:
Send reply for RTR-request (placed in op->frames[0]).
CAN_FD_FRAME:
The CAN frames following the bcm_msg_head are struct canfd_frame's
Broadcast Manager Transmission Timers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Periodic transmission configurations may use up to two interval timers.
In this case the BCM sends a number of messages ('count') at an interval
'ival1', then continuing to send at another given interval 'ival2'. When
only one timer is needed 'count' is set to zero and only 'ival2' is used.
When SET_TIMER and START_TIMER flag were set the timers are activated.
The timer values can be altered at runtime when only SET_TIMER is set.
Broadcast Manager message sequence transmission
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Up to 256 CAN frames can be transmitted in a sequence in the case of a cyclic
TX task configuration. The number of CAN frames is provided in the 'nframes'
element of the BCM message head. The defined number of CAN frames are added
as array to the TX_SETUP BCM configuration message:
.. code-block:: C
/* create a struct to set up a sequence of four CAN frames */
struct {
struct bcm_msg_head msg_head;
struct can_frame frame[4];
} mytxmsg;
(..)
mytxmsg.msg_head.nframes = 4;
(..)
write(s, &mytxmsg, sizeof(mytxmsg));
With every transmission the index in the array of CAN frames is increased
and set to zero at index overflow.
Broadcast Manager Receive Filter Timers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The timer values ival1 or ival2 may be set to non-zero values at RX_SETUP.
When the SET_TIMER flag is set the timers are enabled:
ival1:
Send RX_TIMEOUT when a received message is not received again within
the given time. When START_TIMER is set at RX_SETUP the timeout detection
is activated directly - even without a former CAN frame reception.
ival2:
Throttle the received message rate down to the value of ival2. This
is useful to reduce messages for the application when the signal inside the
CAN frame is stateless as state changes within the ival2 period may get
lost.
Broadcast Manager Multiplex Message Receive Filter
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To filter for content changes in multiplex message sequences an array of more
than one CAN frames can be passed in a RX_SETUP configuration message. The
data bytes of the first CAN frame contain the mask of relevant bits that
have to match in the subsequent CAN frames with the received CAN frame.
If one of the subsequent CAN frames is matching the bits in that frame data
mark the relevant content to be compared with the previous received content.
Up to 257 CAN frames (multiplex filter bit mask CAN frame plus 256 CAN
filters) can be added as array to the TX_SETUP BCM configuration message:
.. code-block:: C
/* usually used to clear CAN frame data[] - beware of endian problems! */
#define U64_DATA(p) (*(unsigned long long*)(p)->data)
struct {
struct bcm_msg_head msg_head;
struct can_frame frame[5];
} msg;
msg.msg_head.opcode = RX_SETUP;
msg.msg_head.can_id = 0x42;
msg.msg_head.flags = 0;
msg.msg_head.nframes = 5;
U64_DATA(&msg.frame[0]) = 0xFF00000000000000ULL; /* MUX mask */
U64_DATA(&msg.frame[1]) = 0x01000000000000FFULL; /* data mask (MUX 0x01) */
U64_DATA(&msg.frame[2]) = 0x0200FFFF000000FFULL; /* data mask (MUX 0x02) */
U64_DATA(&msg.frame[3]) = 0x330000FFFFFF0003ULL; /* data mask (MUX 0x33) */
U64_DATA(&msg.frame[4]) = 0x4F07FC0FF0000000ULL; /* data mask (MUX 0x4F) */
write(s, &msg, sizeof(msg));
Broadcast Manager CAN FD Support
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The programming API of the CAN_BCM depends on struct can_frame which is
given as array directly behind the bcm_msg_head structure. To follow this
schema for the CAN FD frames a new flag 'CAN_FD_FRAME' in the bcm_msg_head
flags indicates that the concatenated CAN frame structures behind the
bcm_msg_head are defined as struct canfd_frame:
.. code-block:: C
struct {
struct bcm_msg_head msg_head;
struct canfd_frame frame[5];
} msg;
msg.msg_head.opcode = RX_SETUP;
msg.msg_head.can_id = 0x42;
msg.msg_head.flags = CAN_FD_FRAME;
msg.msg_head.nframes = 5;
(..)
When using CAN FD frames for multiplex filtering the MUX mask is still
expected in the first 64 bit of the struct canfd_frame data section.
Transport placeholder, SocketCAN core와 protocol module
1000-1089Connected Transport Protocol(`SOCK_SEQPACKET`)
(작성 예정)
Unconnected Transport Protocol(`SOCK_DGRAM`)
(작성 예정)
SocketCAN Core Module
SocketCAN core module은 protocol family `PF_CAN`을 구현합니다. CAN protocol module은 runtime에 core가 load하며, core는 필요한 CAN ID를 subscribe하는 interface를 제공합니다.
`can.ko` module parameter
- `stats_timer`: 현재·최대 frames/sec 같은 SocketCAN core statistic을 계산하는 1-second timer입니다. 기본적으로 `can.ko` 시작 때 실행되며 module command line에서 `stattimer=0`으로 비활성화할 수 있습니다.
- `debug`: SocketCAN SVN r546 이후 제거되었습니다.
procfs 내용
SocketCAN core는 수신 CAN frame을 protocol module에 전달하기 위해 여러 filter list를 사용합니다. 해당 receive list에서 filter와 match count를 볼 수 있으며 모든 entry에 device와 protocol module identifier가 있습니다. 예제 `/proc/net/can/rcvlist_all`은 `vcan0`의 모든 CAN traffic을 요청한 raw application을 보여 줍니다.
- `rcvlist_all`: filter operation 없는 unfiltered entry
- `rcvlist_eff`: 단일 extended frame(EFF) entry
- `rcvlist_err`: error message frame mask
- `rcvlist_fil`: mask/value filter
- `rcvlist_inv`: 반전 semantics의 mask/value filter
- `rcvlist_sff`: 단일 standard frame(SFF) entry
`/proc/net/can`의 추가 file은 `stats`(RX/TX frame, match ratio 등), `reset_stats`(수동 통계 reset), `version`(SocketCAN core와 ABI version, Linux 5.10에서 제거)입니다.
자체 CAN protocol module 작성
`PF_CAN` family에 새 protocol을 구현하려면 `include/linux/can.h`에 protocol을 정의합니다. SocketCAN core prototype과 정의는 `include/linux/can/core.h`를 include해 사용합니다. Protocol 등록과 CAN device notifier chain 외에 다음 function을 제공합니다.
- `can_rx_register`: 특정 interface의 CAN frame을 subscribe합니다.
- `can_rx_unregister`: 특정 interface의 CAN frame subscription을 해제합니다.
- `can_send`: local loopback을 선택적으로 사용해 CAN frame을 전송합니다.
자세한 내용은 `net/can/af_can.c`의 kerneldoc 또는 `net/can/raw.c`, `net/can/bcm.c` source를 참조하십시오.
Connected Transport Protocols (SOCK_SEQPACKET)
----------------------------------------------
(to be written)
Unconnected Transport Protocols (SOCK_DGRAM)
--------------------------------------------
(to be written)
.. _socketcan-core-module:
SocketCAN Core Module
=====================
The SocketCAN core module implements the protocol family
PF_CAN. CAN protocol modules are loaded by the core module at
runtime. The core module provides an interface for CAN protocol
modules to subscribe needed CAN IDs (see :ref:`socketcan-receive-lists`).
can.ko Module Params
--------------------
- **stats_timer**:
To calculate the SocketCAN core statistics
(e.g. current/maximum frames per second) this 1 second timer is
invoked at can.ko module start time by default. This timer can be
disabled by using stattimer=0 on the module commandline.
- **debug**:
(removed since SocketCAN SVN r546)
procfs content
--------------
As described in :ref:`socketcan-receive-lists` the SocketCAN core uses several filter
lists to deliver received CAN frames to CAN protocol modules. These
receive lists, their filters and the count of filter matches can be
checked in the appropriate receive list. All entries contain the
device and a protocol module identifier::
foo@bar:~$ cat /proc/net/can/rcvlist_all
receive list 'rx_all':
(vcan3: no entry)
(vcan2: no entry)
(vcan1: no entry)
device can_id can_mask function userdata matches ident
vcan0 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) entries
rcvlist_err - list for error message frames masks
rcvlist_fil - list for mask/value filters
rcvlist_inv - list for mask/value filters (inverse semantic)
rcvlist_sff - list for single standard frame (SFF) entries
Additional procfs files in /proc/net/can::
stats - SocketCAN core statistics (rx/tx frames, match ratios, ...)
reset_stats - manual statistic reset
version - prints SocketCAN core and ABI version (removed in Linux 5.10)
Writing Own CAN Protocol Modules
--------------------------------
To implement a new protocol in the protocol family PF_CAN a new
protocol has to be defined in include/linux/can.h .
The prototypes and definitions to use the SocketCAN core can be
accessed by including include/linux/can/core.h .
In addition to functions that register the CAN protocol and the
CAN device notifier chain there are functions to subscribe CAN
frames received by CAN interfaces and to send CAN frames::
can_rx_register - subscribe CAN frames from a specific interface
can_rx_unregister - unsubscribe CAN frames from a specific interface
can_send - transmit a CAN frame (optional with local loopback)
For details see the kerneldoc documentation in net/can/af_can.c or
the source code of net/can/raw.c or net/can/bcm.c .
CAN network driver, loopback, hardware filter와 termination
1090-1182CAN Network Driver
CAN network device driver는 CAN character device driver보다 작성하기 쉽습니다. 일반 network driver처럼 주로 TX에서 socket buffer의 CAN frame을 controller에 넣고, RX에서 controller frame을 socket buffer에 넣습니다. 일반 내용은 `Documentation/networking/netdevices.rst`를 참조하십시오.
일반 설정
CAN network driver는 `alloc_netdev_mqs()` 대신 `alloc_candev_mqs()`와 관련 helper를 사용해 CAN 전용 설정을 자동 처리할 수 있습니다. `PF_CAN`의 각 skbuff payload는 `struct can_frame` 또는 `struct canfd_frame`입니다.
송신 frame local loopback
CAN network driver는 TTY local echo와 유사한 local loopback을 지원해야 합니다. Driver가 echo를 수행한다면 `IFF_ECHO`를 설정해 PF_CAN core fallback loopback이 중복으로 실행되지 않게 합니다.
dev->flags = (IFF_NOARP | IFF_ECHO);
CAN controller hardware filter
일부 CAN controller는 깊은 embedded system의 interrupt 부하를 줄이기 위해 CAN ID 또는 범위를 hardware로 filter합니다. Controller마다 기능이 달라 multi-user networking의 일반 기능으로 쓰기에는 적합하지 않습니다. Driver-level filter는 모든 사용자에게 영향을 주므로 매우 전용인 용도에서만 의미가 있습니다.
PF_CAN core의 효율적인 filter set은 socket마다 서로 다른 여러 filter를 설정할 수 있습니다. 따라서 hardware filter는 깊은 embedded system을 위한 수작업 tuning 범주입니다. 문서 저자는 2002년식 SJA1000 controller 네 개를 연결한 133 MHz MPC603e에서도 높은 bus load를 문제없이 처리했다고 설명합니다.
전환 가능한 termination resistor
CAN bus differential pair에는 정해진 impedance가 필요하며 보통 bus 양 끝 node의 120 Ohm resistor 두 개로 제공합니다. 일부 CAN controller는 올바른 impedance를 위해 termination resistor를 켜거나 끌 수 있습니다.
$ ip -details link show can0
termination 120 [ 0, 120 ]
$ ip link set dev can0 type can termination 120
$ ip link set dev can0 type can termination 0
CAN controller에 termination 지원을 추가하려면 controller의 `struct can_priv`에 `termination_const`, `termination_const_cnt`, `do_set_termination`을 구현하거나 `Documentation/devicetree/bindings/net/can/can-controller.yaml`의 device tree entry로 GPIO control을 추가합니다.
CAN Network Drivers
===================
Writing a CAN network device driver is much easier than writing a
CAN character device driver. Similar to other known network device
drivers 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.rst . The differences
for writing CAN network device driver are described below:
General Settings
----------------
CAN network device drivers can use alloc_candev_mqs() and friends instead of
alloc_netdev_mqs(), to automatically take care of CAN-specific setup:
.. code-block:: C
dev = alloc_candev_mqs(...);
The struct can_frame or struct canfd_frame is the payload of each socket
buffer (skbuff) in the protocol family PF_CAN.
.. _socketcan-local-loopback2:
Local Loopback of Sent Frames
-----------------------------
As described in :ref:`socketcan-local-loopback1` the CAN network device driver should
support a local loopback functionality similar to the local echo
e.g. of tty devices. In this case the driver flag IFF_ECHO has to be
set to prevent the PF_CAN core from locally echoing sent frames
(aka loopback) as fallback solution::
dev->flags = (IFF_NOARP | IFF_ECHO);
CAN Controller Hardware Filters
-------------------------------
To reduce the interrupt load on deep embedded systems some CAN
controllers support the filtering of CAN IDs or ranges of CAN IDs.
These hardware filter capabilities vary from controller to
controller and have to be identified as not feasible in a multi-user
networking approach. The use of the very controller specific
hardware filters could make sense in a very dedicated use-case, as a
filter on driver level would affect all users in the multi-user
system. The high efficient filter sets inside the PF_CAN core allow
to set different multiple filters for each socket separately.
Therefore the use of hardware filters goes to the category 'handmade
tuning on deep embedded systems'. The author is running a MPC603e
@133MHz with four SJA1000 CAN controllers from 2002 under heavy bus
load without any problems ...
Switchable Termination Resistors
--------------------------------
CAN bus requires a specific impedance across the differential pair,
typically provided by two 120Ohm resistors on the farthest nodes of
the bus. Some CAN controllers support activating / deactivating a
termination resistor(s) to provide the correct impedance.
Query the available resistances::
$ ip -details link show can0
...
termination 120 [ 0, 120 ]
Activate the terminating resistor::
$ ip link set dev can0 type can termination 120
Deactivate the terminating resistor::
$ ip link set dev can0 type can termination 0
To enable termination resistor support to a can-controller, either
implement in the controller's struct can-priv::
termination_const
termination_const_cnt
do_set_termination
or add gpio control with the device tree entries from
Documentation/devicetree/bindings/net/can/can-controller.yaml
vcan과 CAN network device interface
1183-1226Virtual CAN driver(`vcan`)
Network loopback device와 비슷하게 vcan은 virtual local CAN interface를 제공합니다. CAN의 완전한 address는 고유 CAN ID와 그 ID를 전송하는 CAN bus(예: `can0`)로 구성되므로 일반적인 용도에서는 virtual CAN interface가 여러 개 필요합니다.
Virtual CAN interface를 사용하면 실제 CAN controller hardware 없이 frame을 송수신할 수 있습니다. 보통 `vcan0`, `vcan1`, `vcan2`처럼 이름을 붙이며 module 이름은 `vcan.ko`입니다. Linux 2.6.24부터 netlink로 vcan device를 생성하고 제거할 수 있습니다.
$ ip link add type vcan
$ ip link add dev vcan42 type vcan
$ ip link del vcan42
CAN Network Device Driver Interface
이 interface는 CAN network device를 setup·configure·monitor하는 공통 interface를 제공합니다. 사용자는 IPROUTE2의 `ip` program으로 netlink를 통해 bit-timing parameter 등을 설정합니다. 모든 실제 CAN network driver가 사용해야 할 공통 data structure와 function도 제공합니다. 사용 예는 SJA1000 또는 MSCAN driver를 참조하십시오. Module 이름은 `can-dev.ko`입니다.
The Virtual CAN Driver (vcan)
-----------------------------
Similar to the network loopback devices, vcan offers a virtual local
CAN 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 CAN
frames without real CAN controller hardware. Virtual CAN network
devices are usually named 'vcanX', like vcan0 vcan1 vcan2 ...
When compiled as a module the virtual CAN driver module is called vcan.ko
Since Linux Kernel version 2.6.24 the vcan driver supports the Kernel
netlink interface to create vcan network devices. The creation and
removal 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 vcan42
The CAN Network Device Driver Interface
---------------------------------------
The CAN network device driver interface provides a generic interface
to setup, configure and monitor CAN network devices. The user can then
configure the CAN device, like setting the bit-timing parameters, via
the 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 a
set of common functions, which all real CAN network device drivers
should use. Please have a look to the SJA1000 or MSCAN driver to
understand how to use them. The name of the module is can-dev.ko.
Netlink property 설정과 통계 해석
1227-1331Device property set/get용 netlink interface
CAN device는 netlink interface로 구성해야 합니다. 지원 message type은 `include/linux/can/netlink.h`에 정의됩니다. IPROUTE2의 `ip`는 CAN link를 지원합니다.
`ip link set can0 type can help`는 arbitration bit timing의 `bitrate`, `sample-point`, `tq`, `prop-seg`, `phase-seg1`, `phase-seg2`, `sjw`, CAN FD data timing의 `dbitrate`, `dsample-point`, `dtq`, `dprop-seg`, `dphase-seg1`, `dphase-seg2`, `dsjw`, 그리고 controller mode를 설정하는 option을 보여 줍니다.
- `loopback`, `listen-only`, `triple-sampling`, `one-shot`
- `berr-reporting`, `fd`, `fd-non-iso`, `presume-ack`, `cc-len8-dlc`
- `restart-ms TIME-MS`, `restart`
상세 정보와 통계는 `ip -details -statistics link show can0`으로 표시합니다.
`<TRIPLE-SAMPLING>` 같은 angle bracket에는 선택된 controller mode인 LOOPBACK, LISTEN-ONLY, TRIPLE-SAMPLING이 나옵니다.
`state ERROR-ACTIVE`는 현재 CAN controller 상태입니다. 가능한 값은 ERROR-ACTIVE, ERROR-WARNING, ERROR-PASSIVE, BUS-OFF, STOPPED입니다.
`restart-ms 100`은 자동 restart delay입니다. 0이 아니면 bus-off 발생 후 지정한 millisecond가 지나 controller를 자동 restart합니다. 기본값은 off입니다.
`bitrate 125000 sample-point 0.875`는 실제 bit/s와 0.000..0.999 범위 sample point입니다. Kernel에 `CONFIG_CAN_CALC_BITTIMING=y`가 있으면 `bitrate`만 설정해 timing을 계산할 수 있고 sample point는 선택 사항입니다. 기본 0.000은 CiA 권장 sample point를 사용한다는 뜻입니다.
`tq 125 prop-seg 6 phase-seg1 7 phase-seg2 2 sjw 1`은 nanosecond 단위 time quantum, propagation segment, phase buffer segment 1·2, tq 단위 synchronization jump width입니다. Bosch CAN 2.0 specification이 제안한 hardware-independent bit timing 표현입니다.
`sja1000: tseg1 ... clock 8000000`은 controller의 timing constant입니다. Time segment 1·2, tq 단위 SJW, bitrate prescaler, CAN system clock frequency를 보여 주며 user space의 비표준 timing 계산 algorithm에 사용할 수 있습니다.
`re-started bus-errors arbit-lost error-warn error-pass bus-off`는 restart 수, bus error와 arbitration loss, error-warning·error-passive·bus-off 상태 전이 횟수를 보여 줍니다. RX overrun은 표준 network statistic의 `overrun` field에 기록됩니다.
Netlink interface to set/get devices properties
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The CAN device must be configured via netlink interface. The supported
netlink 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 available and it can be used as shown
below:
Setting CAN device properties::
$ ip link set can0 type can help
Usage: ip link set DEVICE type can
[ bitrate BITRATE [ sample-point SAMPLE-POINT] ] |
[ tq TQ prop-seg PROP_SEG phase-seg1 PHASE-SEG1
phase-seg2 PHASE-SEG2 [ sjw SJW ] ]
[ dbitrate BITRATE [ dsample-point SAMPLE-POINT] ] |
[ dtq TQ dprop-seg PROP_SEG dphase-seg1 PHASE-SEG1
dphase-seg2 PHASE-SEG2 [ dsjw SJW ] ]
[ loopback { on | off } ]
[ listen-only { on | off } ]
[ triple-sampling { on | off } ]
[ one-shot { on | off } ]
[ berr-reporting { on | off } ]
[ fd { on | off } ]
[ fd-non-iso { on | off } ]
[ presume-ack { on | off } ]
[ cc-len8-dlc { 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 can0
2: can0: <NOARP,UP,LOWER_UP,ECHO> mtu 16 qdisc pfifo_fast state UP qlen 10
link/can
can <TRIPLE-SAMPLING> state ERROR-ACTIVE restart-ms 100
bitrate 125000 sample_point 0.875
tq 125 prop-seg 6 phase-seg1 7 phase-seg2 2 sjw 1
sja1000: tseg1 1..16 tseg2 1..8 sjw 1..4 brp 1..64 brp-inc 1
clock 8000000
re-started bus-errors arbit-lost error-warn error-pass bus-off
41 17457 0 41 42 41
RX: bytes packets errors dropped overrun mcast
140859 17608 17457 0 0 0
TX: bytes packets errors dropped carrier collsns
861 112 0 41 0 0
More info to the above output:
"<TRIPLE-SAMPLING>"
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, a
restart of the CAN controller will be triggered automatically
in case of a bus-off condition after the specified delay time
in 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 the
range 0.000..0.999. If the calculation of bit-timing parameters
is enabled in the kernel (CONFIG_CAN_CALC_BITTIMING=y), the
bit-timing can be defined by setting the "bitrate" argument.
Optionally the "sample-point" can be specified. By default it's
0.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 buffer
segment 1 and 2 and the synchronisation jump width in units of
tq. They allow to define the CAN bit-timing in a hardware
independent format as proposed by the Bosch CAN 2.0 spec (see
chapter 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 1 clock 8000000"
Shows the bit-timing constants of the CAN controller, here the
"sja1000". The minimum and maximum values of the time segment 1
and 2, the synchronisation jump width in units of tq, the
bitrate 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 and
bus-off state. RX overrun errors are listed in the "overrun"
field of the standard network statistics.
CAN bit timing과 device 시작·중지
1332-1390CAN Bit-Timing 설정
Bosch CAN 2.0 specification이 제안한 hardware-independent 형식으로 `tq`, `prop_seg`, `phase_seg1`, `phase_seg2`, `sjw`를 직접 지정할 수 있습니다.
$ ip link set canX type can tq 125 prop-seg 6 \
phase-seg1 7 phase-seg2 2 sjw 1
`CONFIG_CAN_CALC_BITTIMING`을 활성화했다면 `bitrate`를 지정할 때 CiA 권장 timing을 계산합니다.
$ ip link set canX type can bitrate 125000
일반 controller와 표준 bitrate에는 잘 동작하지만 특이한 bitrate나 CAN clock frequency에서는 실패할 수 있습니다. `CONFIG_CAN_CALC_BITTIMING`을 끄면 공간을 절약하고 user-space tool이 timing을 전적으로 계산·설정하게 할 수 있습니다. Controller별 constant는 `ip -details link show can0`으로 확인합니다.
CAN Network Device 시작과 중지
`ifconfig canX up/down` 또는 `ip link set canX up/down`으로 시작·중지합니다. 실제 CAN device는 오류가 많은 기본 설정을 피하려면 시작 전에 반드시 올바른 bit timing을 정의해야 합니다.
$ ip link set canX up type can bitrate 125000
CAN bus에서 error가 너무 많이 발생하면 device가 `bus-off` 상태에 들어가 송수신을 중단할 수 있습니다. `restart-ms`를 0이 아닌 값으로 설정하면 자동 복구할 수 있습니다.
$ ip link set canX type can restart-ms 100
$ ip link set canX type can restart
또는 application이 CAN error message frame을 monitor하여 bus-off를 감지한 뒤 적절한 때 수동 restart할 수 있습니다. Restart 자체도 CAN error message frame을 생성합니다.
Setting the CAN Bit-Timing
~~~~~~~~~~~~~~~~~~~~~~~~~~
The CAN bit-timing parameters can always be defined in a hardware
independent format as proposed in the Bosch CAN 2.0 specification
specifying 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 1
If the kernel option CONFIG_CAN_CALC_BITTIMING is enabled, CIA
recommended CAN bit-timing parameters will be calculated if the bit-
rate is specified with the argument "bitrate"::
$ ip link set canX type can bitrate 125000
Note that this works fine for the most common CAN controllers with
standard bit-rates but may *fail* for exotic bit-rates or CAN system
clock frequencies. Disabling CONFIG_CAN_CALC_BITTIMING saves some
space and allows user-space tools to solely determine and set the
bit-timing parameters. The CAN controller specific bit-timing
constants can be used for that purpose. They are listed by the
following command::
$ ip -details link show can0
...
sja1000: clock 8000000 tseg1 1..16 tseg2 1..8 sjw 1..4 brp 1..64 brp-inc 1
Starting and Stopping the CAN Network Device
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A 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 that
you *must* define proper bit-timing parameters for real CAN devices
before you can start it to avoid error-prone default settings::
$ ip link set canX up type can bitrate 125000
A device may enter the "bus-off" state if too many errors occurred on
the CAN bus. Then no more messages are received or sent. An automatic
bus-off recovery can be enabled by setting the "restart-ms" to a
non-zero value, e.g.::
$ ip link set canX type can restart-ms 100
Alternatively, the application may realize the "bus-off" condition
by monitoring CAN error message frames and do a restart when
appropriate with the command::
$ ip link set canX type can restart
Note that a restart will also create a CAN error message frame (see
also :ref:`socketcan-network-problem-notifications`).
.. _socketcan-can-fd-driver:
CAN FD driver 지원과 ISO mode
1391-1466CAN FD(Flexible Data Rate) Driver 지원
CAN FD controller는 arbitration phase와 payload phase에 서로 다른 bitrate를 지원하므로 CAN FD를 활성화하려면 두 번째 bit timing을 지정해야 합니다. 또한 최대 64-byte payload를 지원합니다.
User space와 Linux network layer에서 `can_frame.len`, `canfd_frame.len`은 CAN FD 0..64를 실제 length로 표현합니다. Bus에 쓰는 DLC mapping은 CAN driver 내부에서만 수행하며 `can_fd_dlc2len()`, `can_fd_len2dlc()` helper 사용을 권장합니다.
Netdevice capability는 MTU로 구분합니다. `MTU=16(CAN_MTU)`은 Classical CAN device, `MTU=72(CANFD_MTU)`는 CAN FD capable device입니다. `SIOCGIFMTU`로 확인할 수 있으며 CAN FD device도 Classical CAN frame을 처리·송신할 수 있습니다.
CAN FD controller를 구성할 때 data phase용 `dbitrate`는 arbitration `bitrate` 이상이어야 합니다. Data timing keyword는 `dbitrate`, `dsample-point`, `dsjw`, `dtq`처럼 `d`로 시작합니다. Data bitrate 설정과 함께 `fd on`을 지정하면 controller의 CAN FD mode를 켜고 device MTU를 72로 전환합니다.
2012 International CAN Conference whitepaper의 첫 CAN FD specification은 data integrity 문제로 개선되었습니다. 오늘날에는 기본인 ISO 11898-1:2015 compliant 구현과 2012 whitepaper를 따르는 non-ISO 구현을 구분합니다.
- ISO compliant로 고정된 controller
- Non-ISO compliant로 고정된 controller(예: `m_can.c`의 M_CAN IP core v3.0.1)
- ISO/non-ISO 전환 가능 controller(예: PEAK PCAN-USB FD)
현재 mode는 driver가 netlink로 알리고 `ip`가 `FD-NON-ISO` option으로 표시합니다. 전환 가능한 controller에서만 `fd-non-iso {on|off}`로 변경할 수 있습니다.
예제는 arbitration bitrate 500 kbit/s, sample point 0.75, data bitrate 4 Mbit/s, data sample point 0.8, `fd on`을 설정합니다. 결과에서 MTU 72, `<FD>`, arbitration timing, data timing, controller constant와 80 MHz clock을 확인합니다. `fd-non-iso on`을 추가하면 `<FD,FD-NON-ISO>`로 표시됩니다.
CAN FD (Flexible Data Rate) Driver Support
------------------------------------------
CAN FD capable CAN controllers support two different bitrates for the
arbitration phase and the payload phase of the CAN FD frame. Therefore a
second bit timing has to be specified in order to enable the CAN FD bitrate.
Additionally CAN FD capable CAN controllers support up to 64 bytes of
payload. The representation of this length in can_frame.len and
canfd_frame.len for userspace applications and inside the Linux network
layer is a plain value from 0 .. 64 instead of the Classical CAN length
which ranges from 0 to 8. The payload length to the bus-relevant DLC mapping
is only performed inside the CAN drivers, preferably with the helper
functions can_fd_dlc2len() and can_fd_len2dlc().
The CAN netdevice driver capabilities can be distinguished by the network
devices maximum transfer unit (MTU)::
MTU = 16 (CAN_MTU) => sizeof(struct can_frame) => Classical CAN device
MTU = 72 (CANFD_MTU) => sizeof(struct canfd_frame) => CAN FD capable device
The CAN device MTU can be retrieved e.g. with a SIOCGIFMTU ioctl() syscall.
N.B. CAN FD capable devices can also handle and send Classical CAN frames.
When configuring CAN FD capable CAN controllers an additional 'data' bitrate
has to be set. This bitrate for the data phase of the CAN FD frame has to be
at least the bitrate which was configured for the arbitration phase. This
second bitrate is specified analogue to the first bitrate but the bitrate
setting keywords for the 'data' bitrate start with 'd' e.g. dbitrate,
dsample-point, dsjw or dtq and similar settings. When a data bitrate is set
within the configuration process the controller option "fd on" can be
specified to enable the CAN FD mode in the CAN controller. This controller
option also switches the device MTU to 72 (CANFD_MTU).
The first CAN FD specification presented as whitepaper at the International
CAN Conference 2012 needed to be improved for data integrity reasons.
Therefore two CAN FD implementations have to be distinguished today:
- ISO compliant: The ISO 11898-1:2015 CAN FD implementation (default)
- non-ISO compliant: The CAN FD implementation following the 2012 whitepaper
Finally there are three types of CAN FD controllers:
1. ISO compliant (fixed)
2. non-ISO compliant (fixed, like the M_CAN IP core v3.0.1 in m_can.c)
3. ISO/non-ISO CAN FD controllers (switchable, like the PEAK PCAN-USB FD)
The current ISO/non-ISO mode is announced by the CAN controller driver via
netlink and displayed by the 'ip' tool (controller option FD-NON-ISO).
The ISO/non-ISO-mode can be altered by setting 'fd-non-iso {on|off}' for
switchable CAN FD controllers only.
Example configuring 500 kbit/s arbitration bitrate and 4 Mbit/s data bitrate::
$ ip link set can0 up type can bitrate 500000 sample-point 0.75 \
dbitrate 4000000 dsample-point 0.8 fd on
$ ip -details link show can0
5: can0: <NOARP,UP,LOWER_UP,ECHO> mtu 72 qdisc pfifo_fast state UNKNOWN \
mode DEFAULT group default qlen 10
link/can promiscuity 0
can <FD> state ERROR-ACTIVE (berr-counter tx 0 rx 0) restart-ms 0
bitrate 500000 sample-point 0.750
tq 50 prop-seg 14 phase-seg1 15 phase-seg2 10 sjw 1
pcan_usb_pro_fd: tseg1 1..64 tseg2 1..16 sjw 1..16 brp 1..1024 \
brp-inc 1
dbitrate 4000000 dsample-point 0.800
dtq 12 dprop-seg 7 dphase-seg1 8 dphase-seg2 4 dsjw 1
pcan_usb_pro_fd: dtseg1 1..16 dtseg2 1..8 dsjw 1..4 dbrp 1..1024 \
dbrp-inc 1
clock 80000000
Example when 'fd-non-iso on' is added on this switchable CAN FD adapter::
can <FD,FD-NON-ISO> state ERROR-ACTIVE (berr-counter tx 0 rx 0) restart-ms 0
Transmitter Delay Compensation
1467-1530Transmitter Delay Compensation
높은 bitrate에서는 transceiver TX pin에서 RX pin까지의 propagation delay가 실제 bit time보다 길어져 RX pin이 이전 bit를 측정하는 오류가 생길 수 있습니다.
TDC(Transmitter Delay Compensation)는 TX pin의 bit time 시작부터 RX pin의 실제 측정점까지 거리를 minimum time quantum 단위로 나타내는 SSP(Secondary Sample Point)를 도입해 이를 해결합니다. SSP는 설정 가능한 TDC Value(`TDCV`)와 TDC offset(`TDCO`)의 합입니다.
Device가 지원하면 CAN FD 설정과 함께 `ip`의 `tdc-mode` argument로 구성합니다.
- 생략: kernel이 TDC 활성화 여부를 자동 결정하고, 켜면 기본 TDCO를 계산하며 device가 측정한 TDCV를 사용합니다. 권장 방식입니다.
- `tdc-mode off`: TDC를 명시적으로 비활성화합니다.
- `tdc-mode auto`: 사용자가 `tdco`를 제공하고 device가 TDCV를 자동 계산합니다. TDC-AUTO controller mode 지원 device에서만 가능합니다.
- `tdc-mode manual`: 사용자가 `tdco`와 `tdcv`를 모두 제공합니다. TDC-MANUAL controller mode 지원 device에서만 가능합니다.
일부 device는 `tdcf`(TDC Filter window)도 제공합니다. 지원한다면 `tdc-mode auto` 또는 `manual`에 선택 argument로 추가할 수 있습니다.
예제는 arbitration 500 kbit/s, data 4 Mbit/s, `tdc-mode auto`, minimum time quantum 15의 TDCO를 설정합니다. 상세 출력은 `<FD,TDC-AUTO>`, arbitration·data timing, `tdco 15`, `tdcf 0`, controller별 허용 범위와 80 MHz clock을 보여 줍니다.
Transmitter Delay Compensation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
At high bit rates, the propagation delay from the TX pin to the RX pin of
the transceiver might become greater than the actual bit time causing
measurement errors: the RX pin would still be measuring the previous bit.
The Transmitter Delay Compensation (thereafter, TDC) resolves this problem
by introducing a Secondary Sample Point (SSP) equal to the distance, in
minimum time quantum, from the start of the bit time on the TX pin to the
actual measurement on the RX pin. The SSP is calculated as the sum of two
configurable values: the TDC Value (TDCV) and the TDC offset (TDCO).
TDC, if supported by the device, can be configured together with CAN-FD
using the ip tool's "tdc-mode" argument as follow:
**omitted**
When no "tdc-mode" option is provided, the kernel will automatically
decide whether TDC should be turned on, in which case it will
calculate a default TDCO and use the TDCV as measured by the
device. This is the recommended method to use TDC.
**"tdc-mode off"**
TDC is explicitly disabled.
**"tdc-mode auto"**
The user must provide the "tdco" argument. The TDCV will be
automatically calculated by the device. This option is only
available if the device supports the TDC-AUTO CAN controller mode.
**"tdc-mode manual"**
The user must provide both the "tdco" and "tdcv" arguments. This
option is only available if the device supports the TDC-MANUAL CAN
controller mode.
Note that some devices may offer an additional parameter: "tdcf" (TDC Filter
window). If supported by your device, this can be added as an optional
argument to either "tdc-mode auto" or "tdc-mode manual".
Example configuring a 500 kbit/s arbitration bitrate, a 5 Mbit/s data
bitrate, a TDCO of 15 minimum time quantum and a TDCV automatically measured
by the device::
$ ip link set can0 up type can bitrate 500000 \
fd on dbitrate 4000000 \
tdc-mode auto tdco 15
$ ip -details link show can0
5: can0: <NOARP,UP,LOWER_UP,ECHO> mtu 72 qdisc pfifo_fast state UP \
mode DEFAULT group default qlen 10
link/can promiscuity 0 allmulti 0 minmtu 72 maxmtu 72
can <FD,TDC-AUTO> state ERROR-ACTIVE restart-ms 0
bitrate 500000 sample-point 0.875
tq 12 prop-seg 69 phase-seg1 70 phase-seg2 20 sjw 10 brp 1
ES582.1/ES584.1: tseg1 2..256 tseg2 2..128 sjw 1..128 brp 1..512 \
brp_inc 1
dbitrate 4000000 dsample-point 0.750
dtq 12 dprop-seg 7 dphase-seg1 7 dphase-seg2 5 dsjw 2 dbrp 1
tdco 15 tdcf 0
ES582.1/ES584.1: dtseg1 2..32 dtseg2 1..16 dsjw 1..8 dbrp 1..32 \
dbrp_inc 1
tdco 0..127 tdcf 0..127
clock 80000000
지원 hardware, 자료와 기여자
1531-1570지원 CAN hardware
현재 지원 hardware 목록은 `drivers/net/can`의 `Kconfig`를 확인하십시오. :ref:`socketcan-resources`의 SocketCAN project website에는 오래된 kernel version용을 포함한 추가 driver가 있을 수 있습니다.
SocketCAN 자료
Linux CAN / SocketCAN project site와 mailing list는 Linux source tree의 `MAINTAINERS` file에 있습니다. `CAN NETWORK LAYERS` 또는 `CAN NETWORK DRIVERS`를 검색하십시오.
기여자
- Oliver Hartkopp: PF_CAN core, filter, driver, BCM, SJA1000 driver
- Urs Thuermann: PF_CAN core, kernel 통합, socket interface, raw, vcan
- Jan Kizka: RT-SocketCAN core, Socket API 조정
- Wolfgang Grandegger: RT-SocketCAN core·driver, Raw Socket API review, CAN driver interface, MSCAN driver
- Robert Schwebel: design review, PTXdist 통합
- Marc Kleine-Budde: design review, Kernel 2.6 cleanup, driver
- Benedikt Spranger: review
- Thomas Gleixner: LKML review, coding style, posting 조언
- Andrey Volkov: kernel subtree 구조, ioctl, MSCAN driver
- Matthias Brukner: 최초 SJA1000 CAN netdevice 구현(Q2/2003)
- Klaus Hitschler: PEAK driver 통합
- Uwe Koppe: PF_PACKET 접근의 CAN netdevice
- Michael Schulze: driver layer loopback 요구사항, RT CAN driver review
- Pavel Pisa: bit-timing 계산
- 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: review, coding style, kbuild 지원
Supported CAN Hardware
----------------------
Please check the "Kconfig" file in "drivers/net/can" to get an actual
list of the support CAN hardware. On the SocketCAN project website
(see :ref:`socketcan-resources`) there might be further drivers available, also for
older kernel versions.
.. _socketcan-resources:
SocketCAN Resources
===================
The Linux CAN / SocketCAN project resources (project site / mailing list)
are referenced in the MAINTAINERS file in the Linux source tree.
Search for CAN NETWORK [LAYERS|DRIVERS].
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)
요약·해설
can.rst:1-1570SocketCAN은 CAN controller를 Linux network device로 추상화하고 `PF_CAN` socket family를 통해 여러 process와 protocol이 같은 bus를 안전하게 공유하게 합니다. RAW socket은 frame·filter 중심 접근을, BCM socket은 kernel 안의 주기 송신·변화 감지·timeout 작업을 제공합니다. CAN FD에서는 MTU, 두 bitrate, ISO mode와 TDC까지 함께 구성해야 합니다.
SocketCAN을 별도 Linux networking subsystem으로 만든 핵심 이유입니다.
Controller frame이 protocol module과 application으로 오가는 경로입니다.
원문 L151-156은 application 배치가 달라도 같은 관측 결과를 제공해야 함을 보여 줍니다.
공통 offset을 유지해 Classical CAN과 CAN FD를 비슷하게 처리합니다.
Socket별 수신·echo·FD 동작을 독립적으로 조정합니다.
두 interval과 count를 사용해 초기 burst와 지속 주기를 분리합니다.
Content 변화, timeout, rate 제어를 kernel task로 처리합니다.
실제 device는 timing을 먼저 설정하고 bus-off 복구 정책을 정해야 합니다.
CAN FD는 별도 data-phase timing과 더 큰 MTU가 필요합니다.
High data bitrate에서 TX→RX propagation delay를 보상합니다.
실제 hardware 없이 SocketCAN application과 protocol을 검증합니다.