← Documents Documentation/networking/can.rst GitHub 원문 ↗

Linux 6.18.37 · Networking

SocketCAN - Controller Area Network

SocketCAN의 protocol family, RAW·BCM socket, filter·loopback, CAN FD, netlink driver 설정과 TDC를 종합 설명합니다.

Source pathDocumentation/networking/can.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

요약·해설

can.rst:1-1570

SocketCAN은 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까지 함께 구성해야 합니다.

Character CAN과 SocketCAN
관점Character device 방식SocketCAN
Hardware 교체Driver API에 application 종속Network interface 추상화
동시 사용자종종 process 하나여러 socket 동시 구독
QueueUser space 재구현Linux network queue 재사용
TransportApplication이 직접 구현Protocol module 동적 등록
FilterDevice 또는 driver 전역Socket별 여러 filter

SocketCAN을 별도 Linux networking subsystem으로 만든 핵심 이유입니다.

SocketCAN data path
CAN controllerCAN network driverLinux network layerPF_CAN core receive listRAW·BCM·ISO-TP moduleUser socket
User socketProtocol module`can_send` / skbuffCAN network driverCAN controller

Controller frame이 protocol module과 application으로 오가는 경로입니다.

Local loopback topology
Node ACAN busNode BCAN busNode C
Node AB: App A + App BLocal echo + CAN busNode C: App C
성공 송신 직후 loopback실제 arbitration 순서 반영Analyzer도 동일 traffic 관측

원문 L151-156은 application 배치가 달라도 같은 관측 결과를 제공해야 함을 보여 줍니다.

CAN frame 구조 비교
항목`can_frame``canfd_frame`
Payload0..8 byte0..64 byte
MTU`CAN_MTU` = 16`CANFD_MTU` = 72
Length`len``len`
추가 flag없음`flags`
Data alignment64 bit64 bit

공통 offset을 유지해 Classical CAN과 CAN FD를 비슷하게 처리합니다.

CAN_RAW option 지도
Option효과
`CAN_RAW_FILTER`CAN ID mask filter 0..n개
`CAN_RAW_ERR_FILTER`선택한 error class 수신
`CAN_RAW_LOOPBACK`Local loopback on/off
`CAN_RAW_RECV_OWN_MSGS`자신이 보낸 echo 수신
`CAN_RAW_FD_FRAMES`Classical CAN + CAN FD 허용
`CAN_RAW_JOIN_FILTERS`여러 filter를 AND로 결합

Socket별 수신·echo·FD 동작을 독립적으로 조정합니다.

BCM 주기 송신
`TX_SETUP``ival1` 간격으로 `count`회`TX_EXPIRED` 선택 알림`ival2` 간격으로 계속
`SETTIMER`Runtime interval 변경
`TX_DELETE`Task 제거

두 interval과 count를 사용해 초기 burst와 지속 주기를 분리합니다.

BCM receive monitor
기능설정결과
Content 변화`RX_SETUP` + frame mask`RX_CHANGED`
DLC 변화`RX_CHECK_DLC``RX_CHANGED`
수신 누락`ival1``RX_TIMEOUT`
Rate throttle`ival2`Application message 감소
Multiplex첫 frame MUX mask + 최대 256 filter선택 field 비교

Content 변화, timeout, rate 제어를 kernel task로 처리합니다.

CAN device 생명주기
Controller capability·clock 확인Bit timing 설정`ip link set canX up`ERROR-ACTIVE
Error 누적BUS-OFF`restart-ms` 자동 또는 `restart` 수동복구 error frame

실제 device는 timing을 먼저 설정하고 bus-off 복구 정책을 정해야 합니다.

Classical CAN과 CAN FD driver
구분Classical CANCAN FD
Arbitration bitrate1개1개
Data bitrate동일`dbitrate` 별도, arbitration 이상
Payload최대 8최대 64
MTU1672
DLC mappingDriver`can_fd_dlc2len` / `can_fd_len2dlc`
Mode기본ISO 또는 non-ISO

CAN FD는 별도 data-phase timing과 더 큰 MTU가 필요합니다.

TDC sample point
TX bit 시작Transceiver propagation delayRX 실제 측정
`TDCV` device 측정값+ `TDCO` offsetSSP(Secondary Sample Point)
권장: tdc-mode 생략Kernel 자동 판단·TDCO 계산Device 측정 TDCV 사용

High data bitrate에서 TX→RX propagation delay를 보상합니다.

vcan 활용
명령결과
`ip link add type vcan`자동 이름의 virtual CAN 생성
`ip link add dev vcan42 type vcan``vcan42` 생성
`ip link del vcan42`Virtual CAN 제거
여러 vcan 사용CAN ID + bus 조합별 독립 test

실제 hardware 없이 SocketCAN application과 protocol을 검증합니다.

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

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

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

SocketCAN 개요와 socket API를 택한 이유

1-104

SocketCAN - 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-205

SocketCAN 개념

: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-396

SocketCAN 사용법

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-466

CAN 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-713

RAW 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-837

Broadcast 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-999

Broadcast 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-1089

Connected 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-1182

CAN 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-1226

Virtual 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.

CAN bit timing과 device 시작·중지

1332-1390

CAN 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-1466

CAN 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-1530

Transmitter 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)