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

Linux 6.18.37 · Networking

The UCAN Protocol

UCAN USB-CAN protocol의 endpoint, control command, 4-byte message alignment, flow control와 Bus OFF 복구를 설명합니다.

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

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

1. 요약·해설

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

요약·해설

can_ucan_protocol.rst:1-332

UCAN은 Linux CAN 표현과 유사하게 설계된 little-endian USB protocol입니다. CONTROL endpoint는 구성과 상태 명령을, IN endpoint는 수신·완료·error frame을, OUT endpoint는 송신 frame을 담당합니다. Batch message의 `len`과 4-byte alignment, echo-id 기반 완료 응답, NAK 기반 backpressure가 구현의 핵심입니다.

UCAN endpoint 방향
Host driverCONTROL vendor requestUCAN device management
Host driverOUT: CAN TX frameUCAN device → CAN bus
Host driverIN: CAN RX·TX complete·errorUCAN device

Host driver와 USB-CAN device 사이의 세 endpoint 역할입니다.

UCAN command 지원
Command방향지원Payload·효과
GET_FW_STRINGDev→Host선택Firmware string
STARTHost→Dev필수`cmd_start`, mode mask
STOPHost→Dev필수빈 payload, interface 중지
RESETHost→Dev필수Controller·error counter reset
GETHost→Dev필수Device info·protocol version
SET_BITTIMINGHost→Dev필수`cmd_set_bittiming`
SLEEP/WAKEHost→Dev선택Driver 미지원
FILTERHost→Dev선택Driver 미지원

방향과 필수 여부, 주요 payload를 한눈에 정리합니다.

IN·OUT batch 공통 layout
단계Offset검증
첫 message0`len`이 실제 data 범위 안인지 확인
Message 끝`len`필요하면 padding 존재
다음 message`round_up(len, 4)`4-byte boundary
반복다음 `len`Packet 끝까지 sanity-check

원문의 두 ASCII layout은 같은 4-byte 정렬 규칙을 사용합니다.

TX echo 완료 흐름
Host: `UCAN_OUT_TX` + echo-idDevice가 CAN bus에 frame 송신`UCAN_IN_TX_COMPLETE`<echo-id, flags>Bit 0으로 성공 판정

Echo-id가 host 송신 요청과 device 완료 결과를 연결합니다.

UCAN flow control
방향Device 동작Driver 책임
CAN→USB INFlow control 없음, overflow 시 error frame충분히 빠르게 처리해 drop 방지
USB OUT→CANBuffer full이면 OUT pipe에 NAK미완료 packet threshold에서 queue 중지

수신과 송신 방향은 서로 다른 과부하 신호를 사용합니다.

Bus OFF 복구
CAN error frame으로 Bus OFF 통지TX 중지·요청 즉시 실패 완료`UCAN_COMMAND_RESTART`복구ERROR-ACTIVE error frame

자동 복구가 없으므로 명시적인 RESTART와 상태 확인이 필요합니다.

2. 영어 원문 전체

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

원문 전체 펼치기
1 =================
2 The UCAN Protocol
3 =================
4
5 UCAN is the protocol used by the microcontroller-based USB-CAN
6 adapter that is integrated on System-on-Modules from Theobroma Systems
7 and that is also available as a standalone USB stick.
8
9 The UCAN protocol has been designed to be hardware-independent.
10 It is modeled closely after how Linux represents CAN devices
11 internally. All multi-byte integers are encoded as Little Endian.
12
13 All structures mentioned in this document are defined in
14 ``drivers/net/can/usb/ucan.c``.
15
16 USB Endpoints
17 =============
18
19 UCAN devices use three USB endpoints:
20
21 CONTROL endpoint
22 The driver sends device management commands on this endpoint
23
24 IN endpoint
25 The device sends CAN data frames and CAN error frames
26
27 OUT endpoint
28 The driver sends CAN data frames on the out endpoint
29
30
31 CONTROL Messages
32 ================
33
34 UCAN devices are configured using vendor requests on the control pipe.
35
36 To support multiple CAN interfaces in a single USB device all
37 configuration commands target the corresponding interface in the USB
38 descriptor.
39
40 The driver uses ``ucan_ctrl_command_in/out`` and
41 ``ucan_device_request_in`` to deliver commands to the device.
42
43 Setup Packet
44 ------------
45
46 ================= =====================================================
47 ``bmRequestType`` Direction | Vendor | (Interface or Device)
48 ``bRequest`` Command Number
49 ``wValue`` Subcommand Number (16 Bit) or 0 if not used
50 ``wIndex`` USB Interface Index (0 for device commands)
51 ``wLength`` * Host to Device - Number of bytes to transmit
52 * Device to Host - Maximum Number of bytes to
53 receive. If the device send less. Common ZLP
54 semantics are used.
55 ================= =====================================================
56
57 Error Handling
58 --------------
59
60 The device indicates failed control commands by stalling the
61 pipe.
62
63 Device Commands
64 ---------------
65
66 UCAN_DEVICE_GET_FW_STRING
67 ~~~~~~~~~~~~~~~~~~~~~~~~~
68
69 *Dev2Host; optional*
70
71 Request the device firmware string.
72
73
74 Interface Commands
75 ------------------
76
77 UCAN_COMMAND_START
78 ~~~~~~~~~~~~~~~~~~
79
80 *Host2Dev; mandatory*
81
82 Bring the CAN interface up.
83
84 Payload Format
85 ``ucan_ctl_payload_t.cmd_start``
86
87 ==== ============================
88 mode or mask of ``UCAN_MODE_*``
89 ==== ============================
90
91 UCAN_COMMAND_STOP
92 ~~~~~~~~~~~~~~~~~~
93
94 *Host2Dev; mandatory*
95
96 Stop the CAN interface
97
98 Payload Format
99 *empty*
100
101 UCAN_COMMAND_RESET
102 ~~~~~~~~~~~~~~~~~~
103
104 *Host2Dev; mandatory*
105
106 Reset the CAN controller (including error counters)
107
108 Payload Format
109 *empty*
110
111 UCAN_COMMAND_GET
112 ~~~~~~~~~~~~~~~~
113
114 *Host2Dev; mandatory*
115
116 Get Information from the Device
117
118 Subcommands
119 ^^^^^^^^^^^
120
121 UCAN_COMMAND_GET_INFO
122 Request the device information structure ``ucan_ctl_payload_t.device_info``.
123
124 See the ``device_info`` field for details, and
125 ``uapi/linux/can/netlink.h`` for an explanation of the
126 ``can_bittiming fields``.
127
128 Payload Format
129 ``ucan_ctl_payload_t.device_info``
130
131 UCAN_COMMAND_GET_PROTOCOL_VERSION
132
133 Request the device protocol version
134 ``ucan_ctl_payload_t.protocol_version``. The current protocol version is 3.
135
136 Payload Format
137 ``ucan_ctl_payload_t.protocol_version``
138
139 .. note:: Devices that do not implement this command use the old
140 protocol version 1
141
142 UCAN_COMMAND_SET_BITTIMING
143 ~~~~~~~~~~~~~~~~~~~~~~~~~~
144
145 *Host2Dev; mandatory*
146
147 Setup bittiming by sending the structure
148 ``ucan_ctl_payload_t.cmd_set_bittiming`` (see ``struct bittiming`` for
149 details)
150
151 Payload Format
152 ``ucan_ctl_payload_t.cmd_set_bittiming``.
153
154 UCAN_SLEEP/WAKE
155 ~~~~~~~~~~~~~~~
156
157 *Host2Dev; optional*
158
159 Configure sleep and wake modes. Not yet supported by the driver.
160
161 UCAN_FILTER
162 ~~~~~~~~~~~
163
164 *Host2Dev; optional*
165
166 Setup hardware CAN filters. Not yet supported by the driver.
167
168 Allowed interface commands
169 --------------------------
170
171 ================== =================== ==================
172 Legal Device State Command New Device State
173 ================== =================== ==================
174 stopped SET_BITTIMING stopped
175 stopped START started
176 started STOP or RESET stopped
177 stopped STOP or RESET stopped
178 started RESTART started
179 any GET *no change*
180 ================== =================== ==================
181
182 IN Message Format
183 =================
184
185 A data packet on the USB IN endpoint contains one or more
186 ``ucan_message_in`` values. If multiple messages are batched in a USB
187 data packet, the ``len`` field can be used to jump to the next
188 ``ucan_message_in`` value (take care to sanity-check the ``len`` value
189 against the actual data size).
190
191 .. _can_ucan_in_message_len:
192
193 ``len`` field
194 -------------
195
196 Each ``ucan_message_in`` must be aligned to a 4-byte boundary (relative
197 to the start of the start of the data buffer). That means that there
198 may be padding bytes between multiple ``ucan_message_in`` values:
199
200 .. code::
201
202 +----------------------------+ < 0
203 | |
204 | struct ucan_message_in |
205 | |
206 +----------------------------+ < len
207 [padding]
208 +----------------------------+ < round_up(len, 4)
209 | |
210 | struct ucan_message_in |
211 | |
212 +----------------------------+
213 [...]
214
215 ``type`` field
216 --------------
217
218 The ``type`` field specifies the type of the message.
219
220 UCAN_IN_RX
221 ~~~~~~~~~~
222
223 ``subtype``
224 zero
225
226 Data received from the CAN bus (ID + payload).
227
228 UCAN_IN_TX_COMPLETE
229 ~~~~~~~~~~~~~~~~~~~
230
231 ``subtype``
232 zero
233
234 The CAN device has sent a message to the CAN bus. It answers with a
235 list of tuples <echo-ids, flags>.
236
237 The echo-id identifies the frame from (echos the id from a previous
238 UCAN_OUT_TX message). The flag indicates the result of the
239 transmission. Whereas a set Bit 0 indicates success. All other bits
240 are reserved and set to zero.
241
242 Flow Control
243 ------------
244
245 When receiving CAN messages there is no flow control on the USB
246 buffer. The driver has to handle inbound message quickly enough to
247 avoid drops. I case the device buffer overflow the condition is
248 reported by sending corresponding error frames (see
249 :ref:`can_ucan_error_handling`)
250
251
252 OUT Message Format
253 ==================
254
255 A data packet on the USB OUT endpoint contains one or more ``struct
256 ucan_message_out`` values. If multiple messages are batched into one
257 data packet, the device uses the ``len`` field to jump to the next
258 ucan_message_out value. Each ucan_message_out must be aligned to 4
259 bytes (relative to the start of the data buffer). The mechanism is
260 same as described in :ref:`can_ucan_in_message_len`.
261
262 .. code::
263
264 +----------------------------+ < 0
265 | |
266 | struct ucan_message_out |
267 | |
268 +----------------------------+ < len
269 [padding]
270 +----------------------------+ < round_up(len, 4)
271 | |
272 | struct ucan_message_out |
273 | |
274 +----------------------------+
275 [...]
276
277 ``type`` field
278 --------------
279
280 In protocol version 3 only ``UCAN_OUT_TX`` is defined, others are used
281 only by legacy devices (protocol version 1).
282
283 UCAN_OUT_TX
284 ~~~~~~~~~~~
285 ``subtype``
286 echo id to be replied within a CAN_IN_TX_COMPLETE message
287
288 Transmit a CAN frame. (parameters: ``id``, ``data``)
289
290 Flow Control
291 ------------
292
293 When the device outbound buffers are full it starts sending *NAKs* on
294 the *OUT* pipe until more buffers are available. The driver stops the
295 queue when a certain threshold of out packets are incomplete.
296
297 .. _can_ucan_error_handling:
298
299 CAN Error Handling
300 ==================
301
302 If error reporting is turned on the device encodes errors into CAN
303 error frames (see ``uapi/linux/can/error.h``) and sends it using the
304 IN endpoint. The driver updates its error statistics and forwards
305 it.
306
307 Although UCAN devices can suppress error frames completely, in Linux
308 the driver is always interested. Hence, the device is always started with
309 the ``UCAN_MODE_BERR_REPORT`` set. Filtering those messages for the
310 user space is done by the driver.
311
312 Bus OFF
313 -------
314
315 - The device does not recover from bus of automatically.
316 - Bus OFF is indicated by an error frame (see ``uapi/linux/can/error.h``)
317 - Bus OFF recovery is started by ``UCAN_COMMAND_RESTART``
318 - Once Bus OFF recover is completed the device sends an error frame
319 indicating that it is on ERROR-ACTIVE state.
320 - During Bus OFF no frames are sent by the device.
321 - During Bus OFF transmission requests from the host are completed
322 immediately with the success bit left unset.
323
324 Example Conversation
325 ====================
326
327 #) Device is connected to USB
328 #) Host sends command ``UCAN_COMMAND_RESET``, subcmd 0
329 #) Host sends command ``UCAN_COMMAND_GET``, subcmd ``UCAN_COMMAND_GET_INFO``
330 #) Device sends ``UCAN_IN_DEVICE_INFO``
331 #) Host sends command ``UCAN_OUT_SET_BITTIMING``
332 #) Host sends command ``UCAN_COMMAND_START``, subcmd 0, mode ``UCAN_MODE_BERR_REPORT``
333

3. 한국어 전문 번역

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

UCAN 개요, endpoint와 control setup

1-62

UCAN Protocol

UCAN은 Theobroma Systems의 System-on-Module에 통합되어 있고 독립형 USB stick으로도 제공되는 microcontroller 기반 USB-CAN adapter가 사용하는 protocol입니다.

UCAN protocol은 hardware와 독립적으로 설계되었습니다. Linux가 내부적으로 CAN device를 표현하는 방식과 밀접하게 맞춰져 있으며, 모든 multi-byte integer는 Little Endian으로 encode합니다.

이 문서에서 언급하는 모든 structure는 `drivers/net/can/usb/ucan.c`에 정의되어 있습니다.

USB Endpoint

UCAN device는 USB endpoint 세 개를 사용합니다.

  • CONTROL endpoint: driver가 device management command를 보냅니다.
  • IN endpoint: device가 CAN data frame과 CAN error frame을 보냅니다.
  • OUT endpoint: driver가 CAN data frame을 보냅니다.

CONTROL message

UCAN device는 control pipe의 vendor request로 구성합니다. 하나의 USB device에서 여러 CAN interface를 지원할 수 있도록 모든 configuration command는 USB descriptor에 있는 해당 interface를 대상으로 합니다.

Driver는 `ucan_ctrl_command_in/out`과 `ucan_device_request_in`을 사용해 command를 device에 전달합니다.

Setup Packet

USB control setup packet
Field내용
`bmRequestType`Direction | Vendor | (Interface 또는 Device)
`bRequest`Command Number
`wValue`16-bit Subcommand Number, 사용하지 않으면 0
`wIndex`USB Interface Index, device command는 0
`wLength` Host→Device전송할 byte 수
`wLength` Device→Host최대 수신 byte 수, 짧으면 일반 ZLP semantics 사용

UCAN vendor request의 setup field 의미입니다.

오류 처리

Device는 실패한 control command를 pipe stall로 표시합니다.

=================
The UCAN Protocol
=================

UCAN is the protocol used by the microcontroller-based USB-CAN
adapter that is integrated on System-on-Modules from Theobroma Systems
and that is also available as a standalone USB stick.

The UCAN protocol has been designed to be hardware-independent.
It is modeled closely after how Linux represents CAN devices
internally. All multi-byte integers are encoded as Little Endian.

All structures mentioned in this document are defined in
``drivers/net/can/usb/ucan.c``.

USB Endpoints
=============

UCAN devices use three USB endpoints:

CONTROL endpoint
  The driver sends device management commands on this endpoint

IN endpoint
  The device sends CAN data frames and CAN error frames

OUT endpoint
  The driver sends CAN data frames on the out endpoint


CONTROL Messages
================

UCAN devices are configured using vendor requests on the control pipe.

To support multiple CAN interfaces in a single USB device all
configuration commands target the corresponding interface in the USB
descriptor.

The driver uses ``ucan_ctrl_command_in/out`` and
``ucan_device_request_in`` to deliver commands to the device.

Setup Packet
------------

=================  =====================================================
``bmRequestType``  Direction | Vendor | (Interface or Device)
``bRequest``       Command Number
``wValue``         Subcommand Number (16 Bit) or 0 if not used
``wIndex``         USB Interface Index (0 for device commands)
``wLength``        * Host to Device - Number of bytes to transmit
                   * Device to Host - Maximum Number of bytes to
                     receive. If the device send less. Common ZLP
                     semantics are used.
=================  =====================================================

Error Handling
--------------

The device indicates failed control commands by stalling the
pipe.

Device·interface command와 정보 조회

63-141

Device command

`UCAN_DEVICE_GET_FW_STRING`

*Dev2Host; optional*

Device firmware string을 요청합니다.

Interface command

`UCAN_COMMAND_START`

*Host2Dev; mandatory*

CAN interface를 활성화합니다.

Payload format은 `ucan_ctl_payload_t.cmd_start`이며 `mode`에는 `UCAN_MODE_*` 값의 OR mask를 넣습니다.

`UCAN_COMMAND_STOP`

*Host2Dev; mandatory*

CAN interface를 중지합니다. Payload는 비어 있습니다.

`UCAN_COMMAND_RESET`

*Host2Dev; mandatory*

Error counter를 포함해 CAN controller를 reset합니다. Payload는 비어 있습니다.

`UCAN_COMMAND_GET`

*Host2Dev; mandatory*

Device에서 정보를 가져옵니다.

Subcommand

`UCAN_COMMAND_GET_INFO`

Device information structure인 `ucan_ctl_payload_t.device_info`를 요청합니다. 자세한 내용은 `device_info` field를, `can_bittiming` field 설명은 `uapi/linux/can/netlink.h`를 참조하십시오. Payload format은 `ucan_ctl_payload_t.device_info`입니다.

`UCAN_COMMAND_GET_PROTOCOL_VERSION`

Device protocol version을 `ucan_ctl_payload_t.protocol_version` 형식으로 요청합니다. 현재 protocol version은 3입니다.

참고: 이 command를 구현하지 않은 device는 이전 protocol version 1을 사용합니다.

Device Commands
---------------

UCAN_DEVICE_GET_FW_STRING
~~~~~~~~~~~~~~~~~~~~~~~~~

*Dev2Host; optional*

Request the device firmware string.


Interface Commands
------------------

UCAN_COMMAND_START
~~~~~~~~~~~~~~~~~~

*Host2Dev; mandatory*

Bring the CAN interface up.

Payload Format
  ``ucan_ctl_payload_t.cmd_start``

====  ============================
mode  or mask of ``UCAN_MODE_*``
====  ============================

UCAN_COMMAND_STOP
~~~~~~~~~~~~~~~~~~

*Host2Dev; mandatory*

Stop the CAN interface

Payload Format
  *empty*

UCAN_COMMAND_RESET
~~~~~~~~~~~~~~~~~~

*Host2Dev; mandatory*

Reset the CAN controller (including error counters)

Payload Format
  *empty*

UCAN_COMMAND_GET
~~~~~~~~~~~~~~~~

*Host2Dev; mandatory*

Get Information from the Device

Subcommands
^^^^^^^^^^^

UCAN_COMMAND_GET_INFO
  Request the device information structure ``ucan_ctl_payload_t.device_info``.

  See the ``device_info`` field for details, and
  ``uapi/linux/can/netlink.h`` for an explanation of the
  ``can_bittiming fields``.

  Payload Format
    ``ucan_ctl_payload_t.device_info``

UCAN_COMMAND_GET_PROTOCOL_VERSION

  Request the device protocol version
  ``ucan_ctl_payload_t.protocol_version``. The current protocol version is 3.

  Payload Format
    ``ucan_ctl_payload_t.protocol_version``

.. note:: Devices that do not implement this command use the old
          protocol version 1

Bit timing, optional command와 상태 전이

142-181

`UCAN_COMMAND_SET_BITTIMING`

*Host2Dev; mandatory*

`ucan_ctl_payload_t.cmd_set_bittiming` structure를 보내 bit timing을 설정합니다. 자세한 내용은 `struct bittiming`을 참조하십시오. Payload format은 `ucan_ctl_payload_t.cmd_set_bittiming`입니다.

`UCAN_SLEEP/WAKE`

*Host2Dev; optional*

Sleep과 wake mode를 구성합니다. 아직 driver가 지원하지 않습니다.

`UCAN_FILTER`

*Host2Dev; optional*

Hardware CAN filter를 설정합니다. 아직 driver가 지원하지 않습니다.

허용되는 interface command

UCAN interface 상태 전이
현재 상태Command새 상태
stoppedSET_BITTIMINGstopped
stoppedSTARTstarted
startedSTOP 또는 RESETstopped
stoppedSTOP 또는 RESETstopped
startedRESTARTstarted
anyGET변화 없음

Command가 허용되는 현재 상태와 실행 후 상태입니다.

UCAN_COMMAND_SET_BITTIMING
~~~~~~~~~~~~~~~~~~~~~~~~~~

*Host2Dev; mandatory*

Setup bittiming by sending the structure
``ucan_ctl_payload_t.cmd_set_bittiming`` (see ``struct bittiming`` for
details)

Payload Format
  ``ucan_ctl_payload_t.cmd_set_bittiming``.

UCAN_SLEEP/WAKE
~~~~~~~~~~~~~~~

*Host2Dev; optional*

Configure sleep and wake modes. Not yet supported by the driver.

UCAN_FILTER
~~~~~~~~~~~

*Host2Dev; optional*

Setup hardware CAN filters. Not yet supported by the driver.

Allowed interface commands
--------------------------

==================  ===================  ==================
Legal Device State  Command              New Device State
==================  ===================  ==================
stopped             SET_BITTIMING        stopped
stopped             START                started
started             STOP or RESET        stopped
stopped             STOP or RESET        stopped
started             RESTART              started
any                 GET                  *no change*
==================  ===================  ==================

USB IN message와 수신 flow control

182-251

IN Message Format

USB IN endpoint의 data packet은 하나 이상의 `ucan_message_in` 값을 담습니다. USB data packet 하나에 여러 message를 batch했다면 `len` field로 다음 `ucan_message_in` 값으로 이동할 수 있습니다. 이때 실제 data size와 비교하여 `len` 값을 반드시 sanity-check해야 합니다.

`len` field

각 `ucan_message_in`은 data buffer 시작점을 기준으로 4-byte boundary에 정렬되어야 합니다. 따라서 여러 `ucan_message_in` 값 사이에 padding byte가 있을 수 있습니다.

UCAN IN batch layout
Offset영역다음 위치
0`struct ucan_message_in``len`
`len`padding 가능`round_up(len, 4)`
`round_up(len, 4)`다음 `struct ucan_message_in`다음 `len`
반복추가 messagepacket 끝

원문 L202-213의 4-byte alignment 구조를 offset 기준으로 재구성했습니다.

`type` field

`type` field는 message 종류를 지정합니다.

`UCAN_IN_RX`

`subtype`은 0입니다. CAN bus에서 수신한 data(ID + payload)입니다.

`UCAN_IN_TX_COMPLETE`

`subtype`은 0입니다. CAN device가 CAN bus에 message를 보냈다는 응답이며 `<echo-id, flags>` tuple 목록을 전달합니다.

Echo-id는 이전 `UCAN_OUT_TX` message에서 가져온 ID를 echo하여 frame을 식별합니다. Flag는 전송 결과를 나타냅니다. Bit 0이 설정되면 성공이며 나머지 bit는 reserved이므로 0으로 설정합니다.

Flow Control

CAN message를 수신할 때 USB buffer에는 flow control이 없습니다. Driver는 drop을 피할 만큼 빠르게 inbound message를 처리해야 합니다. Device buffer가 overflow하면 해당 상태를 대응하는 error frame으로 보고합니다. :ref:`can_ucan_error_handling`을 참조하십시오.

IN Message Format
=================

A data packet on the USB IN endpoint contains one or more
``ucan_message_in`` values. If multiple messages are batched in a USB
data packet, the ``len`` field can be used to jump to the next
``ucan_message_in`` value (take care to sanity-check the ``len`` value
against the actual data size).

.. _can_ucan_in_message_len:

``len`` field
-------------

Each ``ucan_message_in`` must be aligned to a 4-byte boundary (relative
to the start of the start of the data buffer). That means that there
may be padding bytes between multiple ``ucan_message_in`` values:

.. code::

    +----------------------------+ < 0
    |                            |
    |   struct ucan_message_in   |
    |                            |
    +----------------------------+ < len
              [padding]
    +----------------------------+ < round_up(len, 4)
    |                            |
    |   struct ucan_message_in   |
    |                            |
    +----------------------------+
                [...]

``type`` field
--------------

The ``type`` field specifies the type of the message.

UCAN_IN_RX
~~~~~~~~~~

``subtype``
  zero

Data received from the CAN bus (ID + payload).

UCAN_IN_TX_COMPLETE
~~~~~~~~~~~~~~~~~~~

``subtype``
  zero

The CAN device has sent a message to the CAN bus. It answers with a
list of tuples <echo-ids, flags>.

The echo-id identifies the frame from (echos the id from a previous
UCAN_OUT_TX message). The flag indicates the result of the
transmission. Whereas a set Bit 0 indicates success. All other bits
are reserved and set to zero.

Flow Control
------------

When receiving CAN messages there is no flow control on the USB
buffer. The driver has to handle inbound message quickly enough to
avoid drops. I case the device buffer overflow the condition is
reported by sending corresponding error frames (see
:ref:`can_ucan_error_handling`)

USB OUT message와 송신 flow control

252-296

OUT Message Format

USB OUT endpoint의 data packet은 하나 이상의 `struct ucan_message_out` 값을 담습니다. Data packet 하나에 여러 message를 batch하면 device는 `len` field를 사용해 다음 `ucan_message_out` 값으로 이동합니다. 각 `ucan_message_out`은 data buffer 시작점을 기준으로 4 byte에 정렬해야 합니다. 동작은 :ref:`can_ucan_in_message_len`에서 설명한 것과 같습니다.

UCAN OUT batch layout
Offset영역다음 위치
0`struct ucan_message_out``len`
`len`padding 가능`round_up(len, 4)`
`round_up(len, 4)`다음 `struct ucan_message_out`다음 `len`
반복추가 messagepacket 끝

원문 L264-275의 송신 message 정렬과 padding을 구조화했습니다.

`type` field

Protocol version 3에서는 `UCAN_OUT_TX`만 정의됩니다. 다른 type은 legacy device(protocol version 1)에서만 사용합니다.

`UCAN_OUT_TX`

`subtype`은 `CAN_IN_TX_COMPLETE` message로 응답받을 echo id입니다. `id`와 `data` parameter를 사용해 CAN frame을 전송합니다.

Flow Control

Device의 outbound buffer가 가득 차면 buffer 여유가 생길 때까지 OUT pipe에서 *NAK*를 보내기 시작합니다. 완료되지 않은 OUT packet 수가 일정 threshold에 도달하면 driver는 queue를 중지합니다.

OUT Message Format
==================

A data packet on the USB OUT endpoint contains one or more ``struct
ucan_message_out`` values. If multiple messages are batched into one
data packet, the device uses the ``len`` field to jump to the next
ucan_message_out value. Each ucan_message_out must be aligned to 4
bytes (relative to the start of the data buffer). The mechanism is
same as described in :ref:`can_ucan_in_message_len`.

.. code::

    +----------------------------+ < 0
    |                            |
    |   struct ucan_message_out  |
    |                            |
    +----------------------------+ < len
              [padding]
    +----------------------------+ < round_up(len, 4)
    |                            |
    |   struct ucan_message_out  |
    |                            |
    +----------------------------+
                [...]

``type`` field
--------------

In protocol version 3 only ``UCAN_OUT_TX`` is defined, others are used
only by legacy devices (protocol version 1).

UCAN_OUT_TX
~~~~~~~~~~~
``subtype``
  echo id to be replied within a CAN_IN_TX_COMPLETE message

Transmit a CAN frame. (parameters: ``id``, ``data``)

Flow Control
------------

When the device outbound buffers are full it starts sending *NAKs* on
the *OUT* pipe until more buffers are available. The driver stops the
queue when a certain threshold of out packets are incomplete.

CAN error, Bus OFF와 예시 대화

297-332

CAN Error Handling

Error reporting을 켜면 device는 error를 CAN error frame으로 encode하고(`uapi/linux/can/error.h` 참조) IN endpoint로 보냅니다. Driver는 error statistic을 갱신한 뒤 frame을 forwarding합니다.

UCAN device는 error frame을 완전히 억제할 수 있지만 Linux driver는 항상 이 정보에 관심이 있습니다. 따라서 device를 시작할 때 항상 `UCAN_MODE_BERR_REPORT`를 설정합니다. User space로 전달할 message를 filtering하는 작업은 driver가 수행합니다.

Bus OFF

  • Device는 Bus OFF 상태에서 자동으로 복구하지 않습니다.
  • Bus OFF는 error frame으로 표시합니다. `uapi/linux/can/error.h`를 참조하십시오.
  • `UCAN_COMMAND_RESTART`로 Bus OFF 복구를 시작합니다.
  • Bus OFF 복구가 끝나면 device는 ERROR-ACTIVE 상태임을 나타내는 error frame을 보냅니다.
  • Bus OFF 동안 device는 frame을 전송하지 않습니다.
  • Bus OFF 동안 host가 보낸 transmission request는 success bit를 설정하지 않은 채 즉시 완료됩니다.

대화 예시

  • 1. Device가 USB에 연결됩니다.
  • 2. Host가 subcommand 0으로 `UCAN_COMMAND_RESET`을 보냅니다.
  • 3. Host가 subcommand `UCAN_COMMAND_GET_INFO`로 `UCAN_COMMAND_GET`을 보냅니다.
  • 4. Device가 `UCAN_IN_DEVICE_INFO`를 보냅니다.
  • 5. Host가 `UCAN_OUT_SET_BITTIMING`을 보냅니다.
  • 6. Host가 subcommand 0, mode `UCAN_MODE_BERR_REPORT`로 `UCAN_COMMAND_START`를 보냅니다.
.. _can_ucan_error_handling:

CAN Error Handling
==================

If error reporting is turned on the device encodes errors into CAN
error frames (see ``uapi/linux/can/error.h``) and sends it using the
IN endpoint. The driver updates its error statistics and forwards
it.

Although UCAN devices can suppress error frames completely, in Linux
the driver is always interested. Hence, the device is always started with
the ``UCAN_MODE_BERR_REPORT`` set. Filtering those messages for the
user space is done by the driver.

Bus OFF
-------

- The device does not recover from bus of automatically.
- Bus OFF is indicated by an error frame (see ``uapi/linux/can/error.h``)
- Bus OFF recovery is started by ``UCAN_COMMAND_RESTART``
- Once Bus OFF recover is completed the device sends an error frame
  indicating that it is on ERROR-ACTIVE state.
- During Bus OFF no frames are sent by the device.
- During Bus OFF transmission requests from the host are completed
  immediately with the success bit left unset.

Example Conversation
====================

#) Device is connected to USB
#) Host sends command ``UCAN_COMMAND_RESET``, subcmd 0
#) Host sends command ``UCAN_COMMAND_GET``, subcmd ``UCAN_COMMAND_GET_INFO``
#) Device sends ``UCAN_IN_DEVICE_INFO``
#) Host sends command ``UCAN_OUT_SET_BITTIMING``
#) Host sends command ``UCAN_COMMAND_START``, subcmd 0, mode ``UCAN_MODE_BERR_REPORT``