← Documents Documentation/networking/device_drivers/ethernet/amazon/ena.rst GitHub 원문 ↗

Linux 6.18.37 · Networking

Linux kernel driver for Elastic Network Adapter family

Amazon ENA의 Admin Queue, multi-queue, LLQ, interrupt moderation, PHC, RSS, Tx/Rx와 Dynamic RX Buffer를 설명합니다.

Source pathDocumentation/networking/device_drivers/ethernet/amazon/ena.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

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

1. 요약·해설

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

요약·해설

ena.rst:1-471

ENA는 link speed와 PF·VF 형태에 독립적인 고성능 network device interface입니다. Management traffic은 AQ·ACQ·AENQ로, packet traffic은 여러 Tx/Rx descriptor ring으로 분리하며 queue마다 MSI-X와 NAPI를 결합합니다.

ENA architecture
Plane구성 요소역할
ManagementAQ·ACQ·AENQCommand, completion, async event
DataTx/Rx SQ·CQPacket descriptor 처리
InterruptMSI-XQueue pair별 vector
ScalingRSS·multi-queueCPU별 traffic 분산
HealthKeep-Alive·watchdog자동 reset과 복구

Management plane과 data plane을 분리해 확장성과 낮은 overhead를 얻습니다.

Management command
DriverAQ command 제출ENA deviceACQ completionDriver

AQ의 command 결과는 ACQ에서 비동기로 돌아옵니다.

AENQ event
GroupSyndrome·의미
Link state changeLink 변경
Fatal error치명적 device error
NotificationSuspend·Resume traffic
Keep-Alive1초 주기 health 신호

ACQ로 표현할 수 없는 비동기 상태를 별도 queue로 전달합니다.

Tx queue mode
항목RegularLLQ·push-mode
Tx SQ 위치Host memoryDevice memory BAR 사용
DescriptorDevice가 fetchDriver가 직접 push
Packet dataHost에서 fetch첫 96 byte push, 나머지 fetch
지원모든 device협상 후 지원 device만
Fallback해당 없음미지원 시 Regular

LLQ는 packet 앞부분을 device memory에 직접 push합니다.

MSI-X와 NAPI
Queue completionMSI-X 전달Cause clear·auto-maskNAPI 처리Driver unmask

Interrupt는 자동 mask되고 NAPI 처리가 끝난 뒤 다시 활성화됩니다.

Interrupt moderation
Mode조절 방식설정
Conventional정적 delay`tx-usecs`, `rx-usecs`
AdaptiveNAPI cycle마다 동적 조절`adaptive_rx on|off`

고정 delay와 traffic 적응형 delay 중 선택할 수 있습니다.

RX copybreak
Packet < rx_copybreak새 buffer로 복사RX descriptor 즉시 재사용
Packet >= rx_copybreakRX buffer를 SKB에 연결복사 회피

작은 packet은 복사 비용과 descriptor 재사용 이득을 교환합니다.

PHC 운영 한계
항목기준
Get time 빈도초당 최대 125회
허용 PHC error전체 요청의 1% 미만
상태 확인`ethtool -T <interface>`
통계`debugfs/.../phc_stats`
활성화devlink `enable_phc=true` 후 reload

PHC 요청 제한과 error 비율을 함께 감시해야 합니다.

Tx data path
`ena_start_xmit()`Buffer mapping`req_id` 할당ENA descriptor 생성DoorbellCompletion MSI-XNAPI cleanup

Request ID로 순서가 뒤바뀐 completion도 올바른 packet에 연결합니다.

Rx data path
Rx completion`ena_com_rx_pkt()``ena_rx_skb()`작으면 copy크면 linear·frags 연결`napi_gro_receive()`

Packet 크기에 따라 copybreak 경로와 fragment 연결 경로가 갈립니다.

Dynamic RX Buffer
4KB page RX buffer300 byte 수신Page refcount 증가300 byte 사용 영역3796 byte 잔여 영역을 HW에 반환

원문의 ASCII buffer 그림을 page 잔여 공간 재사용 흐름으로 구조화했습니다.

DRB 적용 조건
조건동작
잔여 공간 > 2KB같은 page의 나머지 공간 재사용
XDP program loadDRB 사용 안 함
Packet < rx_copybreak새 skb로 복사, buffer 크기 유지
System page4KB 또는 16KB

잔여 공간과 XDP·copybreak 상태에 따라 재사용 여부가 달라집니다.

Feature 설정 경로
기능Interface·property
MTUAQ SetFeature `ENA_ADMIN_MTU`
RSSAQ SetFeature RSS property 3종
Coalescing`ethtool(8)`
PHC`devlink` driverinit parameter
Driver 재협상`devlink dev reload`

운영자가 자주 만지는 기능과 관리 interface를 묶었습니다.

2. 영어 원문 전체

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

원문 전체 펼치기
1 .. SPDX-License-Identifier: GPL-2.0
2
3 ============================================================
4 Linux kernel driver for Elastic Network Adapter (ENA) family
5 ============================================================
6
7 Overview
8 ========
9
10 ENA is a networking interface designed to make good use of modern CPU
11 features and system architectures.
12
13 The ENA device exposes a lightweight management interface with a
14 minimal set of memory mapped registers and extendible command set
15 through an Admin Queue.
16
17 The driver supports a range of ENA devices, is link-speed independent
18 (i.e., the same driver is used for 10GbE, 25GbE, 40GbE, etc), and has
19 a negotiated and extendible feature set.
20
21 Some ENA devices support SR-IOV. This driver is used for both the
22 SR-IOV Physical Function (PF) and Virtual Function (VF) devices.
23
24 ENA devices enable high speed and low overhead network traffic
25 processing by providing multiple Tx/Rx queue pairs (the maximum number
26 is advertised by the device via the Admin Queue), a dedicated MSI-X
27 interrupt vector per Tx/Rx queue pair, adaptive interrupt moderation,
28 and CPU cacheline optimized data placement.
29
30 The ENA driver supports industry standard TCP/IP offload features such as
31 checksum offload. Receive-side scaling (RSS) is supported for multi-core
32 scaling.
33
34 The ENA driver and its corresponding devices implement health
35 monitoring mechanisms such as watchdog, enabling the device and driver
36 to recover in a manner transparent to the application, as well as
37 debug logs.
38
39 Some of the ENA devices support a working mode called Low-latency
40 Queue (LLQ), which saves several more microseconds.
41
42 ENA Source Code Directory Structure
43 ===================================
44
45 ================= ======================================================
46 ena_com.[ch] Management communication layer. This layer is
47 responsible for the handling all the management
48 (admin) communication between the device and the
49 driver.
50 ena_eth_com.[ch] Tx/Rx data path.
51 ena_admin_defs.h Definition of ENA management interface.
52 ena_eth_io_defs.h Definition of ENA data path interface.
53 ena_common_defs.h Common definitions for ena_com layer.
54 ena_regs_defs.h Definition of ENA PCI memory-mapped (MMIO) registers.
55 ena_netdev.[ch] Main Linux kernel driver.
56 ena_ethtool.c ethtool callbacks.
57 ena_xdp.[ch] XDP files
58 ena_pci_id_tbl.h Supported device IDs.
59 ena_phc.[ch] PTP hardware clock infrastructure (see `PHC`_ for more info)
60 ena_devlink.[ch] devlink files.
61 ena_debugfs.[ch] debugfs files.
62 ================= ======================================================
63
64 Management Interface:
65 =====================
66
67 ENA management interface is exposed by means of:
68
69 - PCIe Configuration Space
70 - Device Registers
71 - Admin Queue (AQ) and Admin Completion Queue (ACQ)
72 - Asynchronous Event Notification Queue (AENQ)
73
74 ENA device MMIO Registers are accessed only during driver
75 initialization and are not used during further normal device
76 operation.
77
78 AQ is used for submitting management commands, and the
79 results/responses are reported asynchronously through ACQ.
80
81 ENA introduces a small set of management commands with room for
82 vendor-specific extensions. Most of the management operations are
83 framed in a generic Get/Set feature command.
84
85 The following admin queue commands are supported:
86
87 - Create I/O submission queue
88 - Create I/O completion queue
89 - Destroy I/O submission queue
90 - Destroy I/O completion queue
91 - Get feature
92 - Set feature
93 - Configure AENQ
94 - Get statistics
95
96 Refer to ena_admin_defs.h for the list of supported Get/Set Feature
97 properties.
98
99 The Asynchronous Event Notification Queue (AENQ) is a uni-directional
100 queue used by the ENA device to send to the driver events that cannot
101 be reported using ACQ. AENQ events are subdivided into groups. Each
102 group may have multiple syndromes, as shown below
103
104 The events are:
105
106 ==================== ===============
107 Group Syndrome
108 ==================== ===============
109 Link state change **X**
110 Fatal error **X**
111 Notification Suspend traffic
112 Notification Resume traffic
113 Keep-Alive **X**
114 ==================== ===============
115
116 ACQ and AENQ share the same MSI-X vector.
117
118 Keep-Alive is a special mechanism that allows monitoring the device's health.
119 A Keep-Alive event is delivered by the device every second.
120 The driver maintains a watchdog (WD) handler which logs the current state and
121 statistics. If the keep-alive events aren't delivered as expected the WD resets
122 the device and the driver.
123
124 Data Path Interface
125 ===================
126
127 I/O operations are based on Tx and Rx Submission Queues (Tx SQ and Rx
128 SQ correspondingly). Each SQ has a completion queue (CQ) associated
129 with it.
130
131 The SQs and CQs are implemented as descriptor rings in contiguous
132 physical memory.
133
134 The ENA driver supports two Queue Operation modes for Tx SQs:
135
136 - **Regular mode:**
137 In this mode the Tx SQs reside in the host's memory. The ENA
138 device fetches the ENA Tx descriptors and packet data from host
139 memory.
140
141 - **Low Latency Queue (LLQ) mode or "push-mode":**
142 In this mode the driver pushes the transmit descriptors and the
143 first 96 bytes of the packet directly to the ENA device memory
144 space. The rest of the packet payload is fetched by the
145 device. For this operation mode, the driver uses a dedicated PCI
146 device memory BAR, which is mapped with write-combine capability.
147
148 **Note that** not all ENA devices support LLQ, and this feature is negotiated
149 with the device upon initialization. If the ENA device does not
150 support LLQ mode, the driver falls back to the regular mode.
151
152 The Rx SQs support only the regular mode.
153
154 The driver supports multi-queue for both Tx and Rx. This has various
155 benefits:
156
157 - Reduced CPU/thread/process contention on a given Ethernet interface.
158 - Cache miss rate on completion is reduced, particularly for data
159 cache lines that hold the sk_buff structures.
160 - Increased process-level parallelism when handling received packets.
161 - Increased data cache hit rate, by steering kernel processing of
162 packets to the CPU, where the application thread consuming the
163 packet is running.
164 - In hardware interrupt re-direction.
165
166 Interrupt Modes
167 ===============
168
169 The driver assigns a single MSI-X vector per queue pair (for both Tx
170 and Rx directions). The driver assigns an additional dedicated MSI-X vector
171 for management (for ACQ and AENQ).
172
173 Management interrupt registration is performed when the Linux kernel
174 probes the adapter, and it is de-registered when the adapter is
175 removed. I/O queue interrupt registration is performed when the Linux
176 interface of the adapter is opened, and it is de-registered when the
177 interface is closed.
178
179 The management interrupt is named::
180
181 ena-mgmnt@pci:<PCI domain:bus:slot.function>
182
183 and for each queue pair, an interrupt is named::
184
185 <interface name>-Tx-Rx-<queue index>
186
187 The ENA device operates in auto-mask and auto-clear interrupt
188 modes. That is, once MSI-X is delivered to the host, its Cause bit is
189 automatically cleared and the interrupt is masked. The interrupt is
190 unmasked by the driver after NAPI processing is complete.
191
192 Interrupt Moderation
193 ====================
194
195 ENA driver and device can operate in conventional or adaptive interrupt
196 moderation mode.
197
198 **In conventional mode** the driver instructs device to postpone interrupt
199 posting according to static interrupt delay value. The interrupt delay
200 value can be configured through `ethtool(8)`. The following `ethtool`
201 parameters are supported by the driver: ``tx-usecs``, ``rx-usecs``
202
203 **In adaptive interrupt** moderation mode the interrupt delay value is
204 updated by the driver dynamically and adjusted every NAPI cycle
205 according to the traffic nature.
206
207 Adaptive coalescing can be switched on/off through `ethtool(8)`'s
208 :code:`adaptive_rx on|off` parameter.
209
210 More information about Adaptive Interrupt Moderation (DIM) can be found in
211 Documentation/networking/net_dim.rst
212
213 .. _`RX copybreak`:
214
215 RX copybreak
216 ============
217
218 The rx_copybreak is initialized by default to ENA_DEFAULT_RX_COPYBREAK
219 and can be configured by the ETHTOOL_STUNABLE command of the
220 SIOCETHTOOL ioctl.
221
222 This option controls the maximum packet length for which the RX
223 descriptor it was received on would be recycled. When a packet smaller
224 than RX copybreak bytes is received, it is copied into a new memory
225 buffer and the RX descriptor is returned to HW.
226
227 .. _`PHC`:
228
229 PTP Hardware Clock (PHC)
230 ========================
231 .. _`ptp-userspace-api`: https://docs.kernel.org/driver-api/ptp.html#ptp-hardware-clock-user-space-api
232 .. _`testptp`: https://elixir.bootlin.com/linux/latest/source/tools/testing/selftests/ptp/testptp.c
233
234 ENA Linux driver supports PTP hardware clock providing timestamp reference to achieve nanosecond resolution.
235
236 **PHC support**
237
238 PHC depends on the PTP module, which needs to be either loaded as a module or compiled into the kernel.
239
240 Verify if the PTP module is present:
241
242 .. code-block:: shell
243
244 grep -w '^CONFIG_PTP_1588_CLOCK=[ym]' /boot/config-`uname -r`
245
246 - If no output is provided, the ENA driver cannot be loaded with PHC support.
247
248 **PHC activation**
249
250 The feature is turned off by default, in order to turn the feature on, the ENA driver
251 can be loaded in the following way:
252
253 - devlink:
254
255 .. code-block:: shell
256
257 sudo devlink dev param set pci/<domain:bus:slot.function> name enable_phc value true cmode driverinit
258 sudo devlink dev reload pci/<domain:bus:slot.function>
259 # for example:
260 sudo devlink dev param set pci/0000:00:06.0 name enable_phc value true cmode driverinit
261 sudo devlink dev reload pci/0000:00:06.0
262
263 All available PTP clock sources can be tracked here:
264
265 .. code-block:: shell
266
267 ls /sys/class/ptp
268
269 PHC support and capabilities can be verified using ethtool:
270
271 .. code-block:: shell
272
273 ethtool -T <interface>
274
275 **PHC timestamp**
276
277 To retrieve PHC timestamp, use `ptp-userspace-api`_, usage example using `testptp`_:
278
279 .. code-block:: shell
280
281 testptp -d /dev/ptp$(ethtool -T <interface> | awk '/PTP Hardware Clock:/ {print $NF}') -k 1
282
283 PHC get time requests should be within reasonable bounds,
284 avoid excessive utilization to ensure optimal performance and efficiency.
285 The ENA device restricts the frequency of PHC get time requests to a maximum
286 of 125 requests per second. If this limit is surpassed, the get time request
287 will fail, leading to an increment in the phc_err_ts statistic.
288
289 **PHC statistics**
290
291 PHC can be monitored using debugfs (if mounted):
292
293 .. code-block:: shell
294
295 sudo cat /sys/kernel/debug/<domain:bus:slot.function>/phc_stats
296
297 # for example:
298 sudo cat /sys/kernel/debug/0000:00:06.0/phc_stats
299
300 PHC errors must remain below 1% of all PHC requests to maintain the desired level of accuracy and reliability
301
302 ================= ======================================================
303 **phc_cnt** | Number of successful retrieved timestamps (below expire timeout).
304 **phc_exp** | Number of expired retrieved timestamps (above expire timeout).
305 **phc_skp** | Number of skipped get time attempts (during block period).
306 **phc_err_dv** | Number of failed get time attempts due to device errors (entering into block state).
307 **phc_err_ts** | Number of failed get time attempts due to timestamp errors (entering into block state),
308 | This occurs if driver exceeded the request limit or device received an invalid timestamp.
309 ================= ======================================================
310
311 PHC timeouts:
312
313 ================= ======================================================
314 **expire** | Max time for a valid timestamp retrieval, passing this threshold will fail
315 | the get time request and block new requests until block timeout.
316 **block** | Blocking period starts once get time request expires or fails,
317 | all get time requests during block period will be skipped.
318 ================= ======================================================
319
320 Statistics
321 ==========
322
323 The user can obtain ENA device and driver statistics using `ethtool`.
324 The driver can collect regular or extended statistics (including
325 per-queue stats) from the device.
326
327 In addition the driver logs the stats to syslog upon device reset.
328
329 On supported instance types, the statistics will also include the
330 ENA Express data (fields prefixed with `ena_srd`). For a complete
331 documentation of ENA Express data refer to
332 https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ena-express.html#ena-express-monitor
333
334 MTU
335 ===
336
337 The driver supports an arbitrarily large MTU with a maximum that is
338 negotiated with the device. The driver configures MTU using the
339 SetFeature command (ENA_ADMIN_MTU property). The user can change MTU
340 via `ip(8)` and similar legacy tools.
341
342 Stateless Offloads
343 ==================
344
345 The ENA driver supports:
346
347 - IPv4 header checksum offload
348 - TCP/UDP over IPv4/IPv6 checksum offloads
349
350 RSS
351 ===
352
353 - The ENA device supports RSS that allows flexible Rx traffic
354 steering.
355 - Toeplitz and CRC32 hash functions are supported.
356 - Different combinations of L2/L3/L4 fields can be configured as
357 inputs for hash functions.
358 - The driver configures RSS settings using the AQ SetFeature command
359 (ENA_ADMIN_RSS_HASH_FUNCTION, ENA_ADMIN_RSS_HASH_INPUT and
360 ENA_ADMIN_RSS_INDIRECTION_TABLE_CONFIG properties).
361 - If the NETIF_F_RXHASH flag is set, the 32-bit result of the hash
362 function delivered in the Rx CQ descriptor is set in the received
363 SKB.
364 - The user can provide a hash key, hash function, and configure the
365 indirection table through `ethtool(8)`.
366
367 DEVLINK SUPPORT
368 ===============
369 .. _`devlink`: https://www.kernel.org/doc/html/latest/networking/devlink/index.html
370
371 `devlink`_ supports reloading the driver and initiating re-negotiation with the ENA device
372
373 .. code-block:: shell
374
375 sudo devlink dev reload pci/<domain:bus:slot.function>
376 # for example:
377 sudo devlink dev reload pci/0000:00:06.0
378
379 DATA PATH
380 =========
381
382 Tx
383 --
384
385 :code:`ena_start_xmit()` is called by the stack. This function does the following:
386
387 - Maps data buffers (``skb->data`` and frags).
388 - Populates ``ena_buf`` for the push buffer (if the driver and device are
389 in push mode).
390 - Prepares ENA bufs for the remaining frags.
391 - Allocates a new request ID from the empty ``req_id`` ring. The request
392 ID is the index of the packet in the Tx info. This is used for
393 out-of-order Tx completions.
394 - Adds the packet to the proper place in the Tx ring.
395 - Calls :code:`ena_com_prepare_tx()`, an ENA communication layer that converts
396 the ``ena_bufs`` to ENA descriptors (and adds meta ENA descriptors as
397 needed).
398
399 * This function also copies the ENA descriptors and the push buffer
400 to the Device memory space (if in push mode).
401
402 - Writes a doorbell to the ENA device.
403 - When the ENA device finishes sending the packet, a completion
404 interrupt is raised.
405 - The interrupt handler schedules NAPI.
406 - The :code:`ena_clean_tx_irq()` function is called. This function handles the
407 completion descriptors generated by the ENA, with a single
408 completion descriptor per completed packet.
409
410 * ``req_id`` is retrieved from the completion descriptor. The ``tx_info`` of
411 the packet is retrieved via the ``req_id``. The data buffers are
412 unmapped and ``req_id`` is returned to the empty ``req_id`` ring.
413 * The function stops when the completion descriptors are completed or
414 the budget is reached.
415
416 Rx
417 --
418
419 - When a packet is received from the ENA device.
420 - The interrupt handler schedules NAPI.
421 - The :code:`ena_clean_rx_irq()` function is called. This function calls
422 :code:`ena_com_rx_pkt()`, an ENA communication layer function, which returns the
423 number of descriptors used for a new packet, and zero if
424 no new packet is found.
425 - :code:`ena_rx_skb()` checks packet length:
426
427 * If the packet is small (len < rx_copybreak), the driver allocates
428 a SKB for the new packet, and copies the packet payload into the
429 SKB data buffer.
430
431 - In this way the original data buffer is not passed to the stack
432 and is reused for future Rx packets.
433
434 * Otherwise the function unmaps the Rx buffer, sets the first
435 descriptor as `skb`'s linear part and the other descriptors as the
436 `skb`'s frags.
437
438 - The new SKB is updated with the necessary information (protocol,
439 checksum hw verify result, etc), and then passed to the network
440 stack, using the NAPI interface function :code:`napi_gro_receive()`.
441
442 Dynamic RX Buffers (DRB)
443 ------------------------
444
445 Each RX descriptor in the RX ring is a single memory page (which is either 4KB
446 or 16KB long depending on system's configurations).
447 To reduce the memory allocations required when dealing with a high rate of small
448 packets, the driver tries to reuse the remaining RX descriptor's space if more
449 than 2KB of this page remain unused.
450
451 A simple example of this mechanism is the following sequence of events:
452
453 ::
454
455 1. Driver allocates page-sized RX buffer and passes it to hardware
456 +----------------------+
457 |4KB RX Buffer |
458 +----------------------+
459
460 2. A 300Bytes packet is received on this buffer
461
462 3. The driver increases the ref count on this page and returns it back to
463 HW as an RX buffer of size 4KB - 300Bytes = 3796 Bytes
464 +----+--------------------+
465 |****|3796 Bytes RX Buffer|
466 +----+--------------------+
467
468 This mechanism isn't used when an XDP program is loaded, or when the
469 RX packet is less than rx_copybreak bytes (in which case the packet is
470 copied out of the RX buffer into the linear part of a new skb allocated
471 for it and the RX buffer remains the same size, see `RX copybreak`_).
472

3. 한국어 전문 번역

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

ENA family 개요

1-41

Elastic Network Adapter(ENA) family용 Linux kernel driver

개요

ENA는 최신 CPU 기능과 system architecture를 효율적으로 활용하도록 설계된 network interface입니다.

ENA device는 최소한의 memory-mapped register와 Admin Queue를 통한 확장 가능한 command set으로 구성된 가벼운 management interface를 제공합니다.

Driver는 여러 ENA device를 지원하며 link speed에 독립적입니다. 즉 10GbE, 25GbE, 40GbE 등에 같은 driver를 사용합니다. 기능 set은 device와 협상하며 확장할 수 있습니다.

일부 ENA device는 SR-IOV를 지원합니다. 이 driver는 SR-IOV Physical Function(`PF`)과 Virtual Function(`VF`) device 모두에 사용됩니다.

ENA device는 여러 Tx/Rx queue pair, queue pair마다 전용 MSI-X interrupt vector, adaptive interrupt moderation, CPU cacheline에 최적화된 data 배치를 제공하여 빠르고 overhead가 낮은 network traffic 처리를 가능하게 합니다. 최대 queue pair 수는 device가 Admin Queue를 통해 알립니다.

ENA driver는 checksum offload 같은 표준 TCP/IP offload 기능을 지원합니다. Multi-core 확장을 위해 receive-side scaling(`RSS`)도 지원합니다.

ENA driver와 device는 watchdog 같은 health monitoring mechanism과 debug log를 구현합니다. 이를 통해 application에 투명한 방식으로 device와 driver를 복구할 수 있습니다.

일부 ENA device는 몇 microsecond를 더 절약하는 Low-latency Queue(`LLQ`) mode를 지원합니다.

.. SPDX-License-Identifier: GPL-2.0

============================================================
Linux kernel driver for Elastic Network Adapter (ENA) family
============================================================

Overview
========

ENA is a networking interface designed to make good use of modern CPU
features and system architectures.

The ENA device exposes a lightweight management interface with a
minimal set of memory mapped registers and extendible command set
through an Admin Queue.

The driver supports a range of ENA devices, is link-speed independent
(i.e., the same driver is used for 10GbE, 25GbE, 40GbE, etc), and has
a negotiated and extendible feature set.

Some ENA devices support SR-IOV. This driver is used for both the
SR-IOV Physical Function (PF) and Virtual Function (VF) devices.

ENA devices enable high speed and low overhead network traffic
processing by providing multiple Tx/Rx queue pairs (the maximum number
is advertised by the device via the Admin Queue), a dedicated MSI-X
interrupt vector per Tx/Rx queue pair, adaptive interrupt moderation,
and CPU cacheline optimized data placement.

The ENA driver supports industry standard TCP/IP offload features such as
checksum offload. Receive-side scaling (RSS) is supported for multi-core
scaling.

The ENA driver and its corresponding devices implement health
monitoring mechanisms such as watchdog, enabling the device and driver
to recover in a manner transparent to the application, as well as
debug logs.

Some of the ENA devices support a working mode called Low-latency
Queue (LLQ), which saves several more microseconds.

Source 구조와 management interface

42-123

ENA source code directory 구조

  • `ena_com.[ch]`: management communication layer입니다. Device와 driver 사이의 모든 management(admin) 통신을 처리합니다.
  • `ena_eth_com.[ch]`: Tx/Rx data path입니다.
  • `ena_admin_defs.h`: ENA management interface 정의입니다.
  • `ena_eth_io_defs.h`: ENA data path interface 정의입니다.
  • `ena_common_defs.h`: `ena_com` layer의 공통 정의입니다.
  • `ena_regs_defs.h`: ENA PCI memory-mapped(`MMIO`) register 정의입니다.
  • `ena_netdev.[ch]`: 주 Linux kernel driver입니다.
  • `ena_ethtool.c`: ethtool callback입니다.
  • `ena_xdp.[ch]`: XDP file입니다.
  • `ena_pci_id_tbl.h`: 지원 device ID입니다.
  • `ena_phc.[ch]`: PTP hardware clock infrastructure입니다. 자세한 내용은 `PHC` 절을 참조하십시오.
  • `ena_devlink.[ch]`: devlink file입니다.
  • `ena_debugfs.[ch]`: debugfs file입니다.

Management interface

ENA management interface는 다음 수단으로 노출됩니다.

  • PCIe Configuration Space
  • Device Register
  • Admin Queue(`AQ`)와 Admin Completion Queue(`ACQ`)
  • Asynchronous Event Notification Queue(`AENQ`)

ENA device MMIO register는 driver 초기화 중에만 접근하며 이후 정상 device 동작에서는 사용하지 않습니다.

AQ는 management command 제출에 사용하고, 결과와 응답은 ACQ를 통해 비동기로 보고됩니다.

ENA는 vendor별 확장 공간을 둔 작은 management command set을 제공합니다. 대부분의 management operation은 일반적인 Get/Set feature command 형식으로 구성됩니다.

지원하는 Admin Queue command는 다음과 같습니다.

  • I/O submission queue 생성
  • I/O completion queue 생성
  • I/O submission queue 제거
  • I/O completion queue 제거
  • Feature 조회
  • Feature 설정
  • AENQ 설정
  • 통계 조회

지원하는 Get/Set Feature property 목록은 `ena_admin_defs.h`를 참조하십시오.

AENQ는 ACQ로 보고할 수 없는 event를 ENA device가 driver에 보내는 단방향 queue입니다. AENQ event는 group으로 나뉘며 각 group은 여러 syndrome을 가질 수 있습니다.

Event는 다음과 같습니다.

  • Link state change: 고유 syndrome
  • Fatal error: 고유 syndrome
  • Notification: Suspend traffic
  • Notification: Resume traffic
  • Keep-Alive: 고유 syndrome

ACQ와 AENQ는 같은 MSI-X vector를 공유합니다.

Keep-Alive는 device health를 감시하는 특수 mechanism입니다. Device가 1초마다 Keep-Alive event를 전달합니다. Driver의 watchdog(`WD`) handler는 현재 상태와 통계를 log합니다. Keep-Alive event가 예상대로 오지 않으면 WD가 device와 driver를 reset합니다.

ENA Source Code Directory Structure
===================================

=================   ======================================================
ena_com.[ch]        Management communication layer. This layer is
                    responsible for the handling all the management
                    (admin) communication between the device and the
                    driver.
ena_eth_com.[ch]    Tx/Rx data path.
ena_admin_defs.h    Definition of ENA management interface.
ena_eth_io_defs.h   Definition of ENA data path interface.
ena_common_defs.h   Common definitions for ena_com layer.
ena_regs_defs.h     Definition of ENA PCI memory-mapped (MMIO) registers.
ena_netdev.[ch]     Main Linux kernel driver.
ena_ethtool.c       ethtool callbacks.
ena_xdp.[ch]        XDP files
ena_pci_id_tbl.h    Supported device IDs.
ena_phc.[ch]        PTP hardware clock infrastructure (see `PHC`_ for more info)
ena_devlink.[ch]    devlink files.
ena_debugfs.[ch]    debugfs files.
=================   ======================================================

Management Interface:
=====================

ENA management interface is exposed by means of:

- PCIe Configuration Space
- Device Registers
- Admin Queue (AQ) and Admin Completion Queue (ACQ)
- Asynchronous Event Notification Queue (AENQ)

ENA device MMIO Registers are accessed only during driver
initialization and are not used during further normal device
operation.

AQ is used for submitting management commands, and the
results/responses are reported asynchronously through ACQ.

ENA introduces a small set of management commands with room for
vendor-specific extensions. Most of the management operations are
framed in a generic Get/Set feature command.

The following admin queue commands are supported:

- Create I/O submission queue
- Create I/O completion queue
- Destroy I/O submission queue
- Destroy I/O completion queue
- Get feature
- Set feature
- Configure AENQ
- Get statistics

Refer to ena_admin_defs.h for the list of supported Get/Set Feature
properties.

The Asynchronous Event Notification Queue (AENQ) is a uni-directional
queue used by the ENA device to send to the driver events that cannot
be reported using ACQ. AENQ events are subdivided into groups. Each
group may have multiple syndromes, as shown below

The events are:

====================    ===============
Group                   Syndrome
====================    ===============
Link state change       **X**
Fatal error             **X**
Notification            Suspend traffic
Notification            Resume traffic
Keep-Alive              **X**
====================    ===============

ACQ and AENQ share the same MSI-X vector.

Keep-Alive is a special mechanism that allows monitoring the device's health.
A Keep-Alive event is delivered by the device every second.
The driver maintains a watchdog (WD) handler which logs the current state and
statistics. If the keep-alive events aren't delivered as expected the WD resets
the device and the driver.

Queue mode, multi-queue와 interrupt

124-191

Data path interface

I/O operation은 Tx 및 Rx Submission Queue(`Tx SQ`, `Rx SQ`)를 기반으로 합니다. 각 SQ에는 연관된 completion queue(`CQ`)가 있습니다.

SQ와 CQ는 연속된 physical memory의 descriptor ring으로 구현됩니다.

ENA driver는 Tx SQ에 두 가지 Queue Operation mode를 지원합니다.

Regular mode에서는 Tx SQ가 host memory에 있습니다. ENA device는 ENA Tx descriptor와 packet data를 host memory에서 가져옵니다.

Low Latency Queue(`LLQ`) mode 또는 push-mode에서는 driver가 transmit descriptor와 packet의 첫 96 byte를 ENA device memory 공간에 직접 push합니다. 나머지 packet payload는 device가 가져옵니다. Driver는 이 mode에서 write-combine capability로 mapping한 전용 PCI device memory BAR를 사용합니다.

모든 ENA device가 LLQ를 지원하는 것은 아니며 초기화 중 device와 기능을 협상합니다. Device가 LLQ mode를 지원하지 않으면 driver는 regular mode로 fallback합니다.

Rx SQ는 regular mode만 지원합니다.

Driver는 Tx와 Rx 모두 multi-queue를 지원하며 다음 이점이 있습니다.

  • 하나의 Ethernet interface에서 CPU, thread, process contention이 줄어듭니다.
  • Completion 시 cache miss rate가 줄어듭니다. 특히 `sk_buff` structure를 담는 data cacheline에서 효과가 큽니다.
  • 수신 packet을 처리할 때 process level parallelism이 증가합니다.
  • Packet을 소비하는 application thread가 실행 중인 CPU로 kernel packet 처리를 steering하여 data cache hit rate가 증가합니다.
  • Hardware interrupt redirection을 사용할 수 있습니다.

Interrupt mode

Driver는 각 queue pair의 Tx/Rx 방향에 MSI-X vector 하나를 할당하고, ACQ와 AENQ를 위한 별도의 전용 management MSI-X vector를 추가로 할당합니다.

Linux kernel이 adapter를 probe할 때 management interrupt를 등록하고 adapter를 제거할 때 해제합니다. Adapter의 Linux interface를 열 때 I/O queue interrupt를 등록하고 interface를 닫을 때 해제합니다.

Management interrupt 이름은 다음 형식입니다.

ena-mgmnt@pci:<PCI domain:bus:slot.function>

각 queue pair interrupt 이름은 다음 형식입니다.

<interface name>-Tx-Rx-<queue index>

ENA device는 auto-mask 및 auto-clear interrupt mode로 동작합니다. MSI-X가 host에 전달되면 Cause bit가 자동으로 clear되고 interrupt가 mask됩니다. NAPI 처리가 끝난 뒤 driver가 interrupt mask를 해제합니다.

Data Path Interface
===================

I/O operations are based on Tx and Rx Submission Queues (Tx SQ and Rx
SQ correspondingly). Each SQ has a completion queue (CQ) associated
with it.

The SQs and CQs are implemented as descriptor rings in contiguous
physical memory.

The ENA driver supports two Queue Operation modes for Tx SQs:

- **Regular mode:**
  In this mode the Tx SQs reside in the host's memory. The ENA
  device fetches the ENA Tx descriptors and packet data from host
  memory.

- **Low Latency Queue (LLQ) mode or "push-mode":**
  In this mode the driver pushes the transmit descriptors and the
  first 96 bytes of the packet directly to the ENA device memory
  space. The rest of the packet payload is fetched by the
  device. For this operation mode, the driver uses a dedicated PCI
  device memory BAR, which is mapped with write-combine capability.

  **Note that** not all ENA devices support LLQ, and this feature is negotiated
  with the device upon initialization. If the ENA device does not
  support LLQ mode, the driver falls back to the regular mode.

The Rx SQs support only the regular mode.

The driver supports multi-queue for both Tx and Rx. This has various
benefits:

- Reduced CPU/thread/process contention on a given Ethernet interface.
- Cache miss rate on completion is reduced, particularly for data
  cache lines that hold the sk_buff structures.
- Increased process-level parallelism when handling received packets.
- Increased data cache hit rate, by steering kernel processing of
  packets to the CPU, where the application thread consuming the
  packet is running.
- In hardware interrupt re-direction.

Interrupt Modes
===============

The driver assigns a single MSI-X vector per queue pair (for both Tx
and Rx directions). The driver assigns an additional dedicated MSI-X vector
for management (for ACQ and AENQ).

Management interrupt registration is performed when the Linux kernel
probes the adapter, and it is de-registered when the adapter is
removed. I/O queue interrupt registration is performed when the Linux
interface of the adapter is opened, and it is de-registered when the
interface is closed.

The management interrupt is named::

   ena-mgmnt@pci:<PCI domain:bus:slot.function>

and for each queue pair, an interrupt is named::

   <interface name>-Tx-Rx-<queue index>

The ENA device operates in auto-mask and auto-clear interrupt
modes. That is, once MSI-X is delivered to the host, its Cause bit is
automatically cleared and the interrupt is masked. The interrupt is
unmasked by the driver after NAPI processing is complete.

Interrupt moderation과 RX copybreak

192-226

Interrupt moderation

ENA driver와 device는 conventional 또는 adaptive interrupt moderation mode로 동작할 수 있습니다.

Conventional mode에서 driver는 정적인 interrupt delay 값에 따라 interrupt 게시를 늦추도록 device에 지시합니다. Interrupt delay는 `ethtool(8)`로 설정할 수 있으며 driver는 `tx-usecs`와 `rx-usecs` parameter를 지원합니다.

Adaptive interrupt moderation mode에서는 driver가 traffic 특성에 따라 매 NAPI cycle마다 interrupt delay 값을 동적으로 갱신하고 조절합니다.

Adaptive coalescing은 `ethtool(8)`의 `adaptive_rx on|off` parameter로 켜거나 끌 수 있습니다.

Dynamic Interrupt Moderation(`DIM`)에 관한 자세한 내용은 `Documentation/networking/net_dim.rst`를 참조하십시오.

RX copybreak

`rx_copybreak`는 기본적으로 `ENA_DEFAULT_RX_COPYBREAK`로 초기화되며 `SIOCETHTOOL` ioctl의 `ETHTOOL_STUNABLE` command로 설정할 수 있습니다.

이 option은 수신에 사용한 RX descriptor를 재활용할 최대 packet 길이를 제어합니다. RX copybreak보다 작은 packet을 받으면 새 memory buffer로 복사하고 RX descriptor는 hardware에 반환합니다.

Interrupt Moderation
====================

ENA driver and device can operate in conventional or adaptive interrupt
moderation mode.

**In conventional mode** the driver instructs device to postpone interrupt
posting according to static interrupt delay value. The interrupt delay
value can be configured through `ethtool(8)`. The following `ethtool`
parameters are supported by the driver: ``tx-usecs``, ``rx-usecs``

**In adaptive interrupt** moderation mode the interrupt delay value is
updated by the driver dynamically and adjusted every NAPI cycle
according to the traffic nature.

Adaptive coalescing can be switched on/off through `ethtool(8)`'s
:code:`adaptive_rx on|off` parameter.

More information about Adaptive Interrupt Moderation (DIM) can be found in
Documentation/networking/net_dim.rst

.. _`RX copybreak`:

RX copybreak
============

The rx_copybreak is initialized by default to ENA_DEFAULT_RX_COPYBREAK
and can be configured by the ETHTOOL_STUNABLE command of the
SIOCETHTOOL ioctl.

This option controls the maximum packet length for which the RX
descriptor it was received on would be recycled. When a packet smaller
than RX copybreak bytes is received, it is copied into a new memory
buffer and the RX descriptor is returned to HW.

PTP Hardware Clock

227-318

PTP Hardware Clock(`PHC`)

ENA Linux driver는 nanosecond 해상도를 얻기 위한 timestamp 기준을 제공하는 PTP hardware clock을 지원합니다.

PHC 지원

PHC는 PTP module에 의존합니다. PTP module은 module로 load되거나 kernel에 compile되어 있어야 합니다.

다음 command로 PTP module 존재 여부를 확인합니다.

grep -w '^CONFIG_PTP_1588_CLOCK=[ym]' /boot/config-`uname -r`

출력이 없으면 ENA driver를 PHC 지원과 함께 load할 수 없습니다.

PHC 활성화

이 기능은 기본적으로 꺼져 있습니다. Devlink를 사용해 다음과 같이 ENA driver의 PHC를 켭니다.

sudo devlink dev param set pci/<domain:bus:slot.function> name enable_phc value true cmode driverinit
sudo devlink dev reload pci/<domain:bus:slot.function>
# 예시:
sudo devlink dev param set pci/0000:00:06.0 name enable_phc value true cmode driverinit
sudo devlink dev reload pci/0000:00:06.0

사용 가능한 모든 PTP clock source는 다음 위치에서 확인합니다.

ls /sys/class/ptp

PHC 지원과 capability는 ethtool로 확인할 수 있습니다.

ethtool -T <interface>

PHC timestamp

PHC timestamp는 PTP hardware clock user space API로 가져옵니다. `testptp`를 사용하는 예시는 다음과 같습니다.

testptp -d /dev/ptp$(ethtool -T <interface> | awk '/PTP Hardware Clock:/ {print $NF}') -k 1

최적의 성능과 효율을 위해 PHC get time 요청은 합리적인 범위로 제한하고 과도하게 사용하지 마십시오. ENA device는 PHC get time 요청 빈도를 초당 최대 125회로 제한합니다. 이 제한을 넘으면 get time 요청이 실패하고 `phc_err_ts` 통계가 증가합니다.

PHC 통계

Debugfs가 mount되어 있으면 다음과 같이 PHC를 감시할 수 있습니다.

sudo cat /sys/kernel/debug/<domain:bus:slot.function>/phc_stats
# 예시:
sudo cat /sys/kernel/debug/0000:00:06.0/phc_stats

원하는 정확도와 신뢰성을 유지하려면 PHC error가 전체 PHC 요청의 1% 미만이어야 합니다.

  • `phc_cnt`: expire timeout 안에 성공적으로 얻은 timestamp 수입니다.
  • `phc_exp`: expire timeout을 넘겨 만료된 timestamp 수입니다.
  • `phc_skp`: block period 중 건너뛴 get time 시도 수입니다.
  • `phc_err_dv`: device error 때문에 실패한 get time 시도 수이며 block state로 진입합니다.
  • `phc_err_ts`: timestamp error 때문에 실패한 get time 시도 수이며 block state로 진입합니다. Driver가 request 제한을 넘거나 device가 잘못된 timestamp를 받으면 발생합니다.

PHC timeout

  • `expire`: 유효한 timestamp retrieval의 최대 시간입니다. 이 threshold를 넘으면 get time 요청이 실패하고 block timeout까지 새 요청을 막습니다.
  • `block`: get time 요청이 만료되거나 실패하면 시작하는 차단 기간입니다. 이 기간의 모든 get time 요청을 건너뜁니다.
.. _`PHC`:

PTP Hardware Clock (PHC)
========================
.. _`ptp-userspace-api`: https://docs.kernel.org/driver-api/ptp.html#ptp-hardware-clock-user-space-api
.. _`testptp`: https://elixir.bootlin.com/linux/latest/source/tools/testing/selftests/ptp/testptp.c

ENA Linux driver supports PTP hardware clock providing timestamp reference to achieve nanosecond resolution.

**PHC support**

PHC depends on the PTP module, which needs to be either loaded as a module or compiled into the kernel.

Verify if the PTP module is present:

.. code-block:: shell

  grep -w '^CONFIG_PTP_1588_CLOCK=[ym]' /boot/config-`uname -r`

- If no output is provided, the ENA driver cannot be loaded with PHC support.

**PHC activation**

The feature is turned off by default, in order to turn the feature on, the ENA driver
can be loaded in the following way:

- devlink:

.. code-block:: shell

  sudo devlink dev param set pci/<domain:bus:slot.function> name enable_phc value true cmode driverinit
  sudo devlink dev reload pci/<domain:bus:slot.function>
  # for example:
  sudo devlink dev param set pci/0000:00:06.0 name enable_phc value true cmode driverinit
  sudo devlink dev reload pci/0000:00:06.0

All available PTP clock sources can be tracked here:

.. code-block:: shell

  ls /sys/class/ptp

PHC support and capabilities can be verified using ethtool:

.. code-block:: shell

  ethtool -T <interface>

**PHC timestamp**

To retrieve PHC timestamp, use `ptp-userspace-api`_, usage example using `testptp`_:

.. code-block:: shell

  testptp -d /dev/ptp$(ethtool -T <interface> | awk '/PTP Hardware Clock:/ {print $NF}') -k 1

PHC get time requests should be within reasonable bounds,
avoid excessive utilization to ensure optimal performance and efficiency.
The ENA device restricts the frequency of PHC get time requests to a maximum
of 125 requests per second. If this limit is surpassed, the get time request
will fail, leading to an increment in the phc_err_ts statistic.

**PHC statistics**

PHC can be monitored using debugfs (if mounted):

.. code-block:: shell

  sudo cat /sys/kernel/debug/<domain:bus:slot.function>/phc_stats

  # for example:
  sudo cat /sys/kernel/debug/0000:00:06.0/phc_stats

PHC errors must remain below 1% of all PHC requests to maintain the desired level of accuracy and reliability

=================   ======================================================
**phc_cnt**         | Number of successful retrieved timestamps (below expire timeout).
**phc_exp**         | Number of expired retrieved timestamps (above expire timeout).
**phc_skp**         | Number of skipped get time attempts (during block period).
**phc_err_dv**      | Number of failed get time attempts due to device errors (entering into block state).
**phc_err_ts**      | Number of failed get time attempts due to timestamp errors (entering into block state),
                    | This occurs if driver exceeded the request limit or device received an invalid timestamp.
=================   ======================================================

PHC timeouts:

=================   ======================================================
**expire**          | Max time for a valid timestamp retrieval, passing this threshold will fail
                    | the get time request and block new requests until block timeout.
**block**           | Blocking period starts once get time request expires or fails,
                    | all get time requests during block period will be skipped.
=================   ======================================================

통계, MTU, offload, RSS와 devlink

319-378

통계

사용자는 `ethtool`로 ENA device 및 driver 통계를 얻을 수 있습니다. Driver는 device에서 일반 통계 또는 queue별 통계를 포함한 확장 통계를 수집할 수 있습니다.

Device reset 시 driver는 통계를 syslog에도 기록합니다.

지원되는 instance type에서는 통계에 `ena_srd` prefix가 붙는 ENA Express data도 포함됩니다. 전체 설명은 `https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ena-express.html#ena-express-monitor`를 참조하십시오.

MTU

Driver는 device와 협상한 최대값까지 임의로 큰 MTU를 지원합니다. Driver는 SetFeature command의 `ENA_ADMIN_MTU` property로 MTU를 설정합니다. 사용자는 `ip(8)` 및 비슷한 기존 tool로 MTU를 바꿀 수 있습니다.

Stateless offload

ENA driver는 다음 기능을 지원합니다.

  • IPv4 header checksum offload
  • IPv4/IPv6 위의 TCP/UDP checksum offload

RSS

  • ENA device는 유연한 Rx traffic steering을 가능하게 하는 RSS를 지원합니다.
  • Toeplitz 및 CRC32 hash function을 지원합니다.
  • L2/L3/L4 field의 여러 조합을 hash function 입력으로 설정할 수 있습니다.
  • Driver는 AQ SetFeature command의 `ENA_ADMIN_RSS_HASH_FUNCTION`, `ENA_ADMIN_RSS_HASH_INPUT`, `ENA_ADMIN_RSS_INDIRECTION_TABLE_CONFIG` property로 RSS를 설정합니다.
  • `NETIF_F_RXHASH` flag가 설정되어 있으면 Rx CQ descriptor로 전달된 32-bit hash 결과를 수신 SKB에 설정합니다.
  • 사용자는 `ethtool(8)`로 hash key와 hash function을 지정하고 indirection table을 설정할 수 있습니다.

Devlink 지원

Devlink는 driver reload와 ENA device와의 재협상 시작을 지원합니다.

sudo devlink dev reload pci/<domain:bus:slot.function>
# 예시:
sudo devlink dev reload pci/0000:00:06.0

Statistics
==========

The user can obtain ENA device and driver statistics using `ethtool`.
The driver can collect regular or extended statistics (including
per-queue stats) from the device.

In addition the driver logs the stats to syslog upon device reset.

On supported instance types, the statistics will also include the
ENA Express data (fields prefixed with `ena_srd`). For a complete
documentation of ENA Express data refer to
https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ena-express.html#ena-express-monitor

MTU
===

The driver supports an arbitrarily large MTU with a maximum that is
negotiated with the device. The driver configures MTU using the
SetFeature command (ENA_ADMIN_MTU property). The user can change MTU
via `ip(8)` and similar legacy tools.

Stateless Offloads
==================

The ENA driver supports:

- IPv4 header checksum offload
- TCP/UDP over IPv4/IPv6 checksum offloads

RSS
===

- The ENA device supports RSS that allows flexible Rx traffic
  steering.
- Toeplitz and CRC32 hash functions are supported.
- Different combinations of L2/L3/L4 fields can be configured as
  inputs for hash functions.
- The driver configures RSS settings using the AQ SetFeature command
  (ENA_ADMIN_RSS_HASH_FUNCTION, ENA_ADMIN_RSS_HASH_INPUT and
  ENA_ADMIN_RSS_INDIRECTION_TABLE_CONFIG properties).
- If the NETIF_F_RXHASH flag is set, the 32-bit result of the hash
  function delivered in the Rx CQ descriptor is set in the received
  SKB.
- The user can provide a hash key, hash function, and configure the
  indirection table through `ethtool(8)`.

DEVLINK SUPPORT
===============
.. _`devlink`: https://www.kernel.org/doc/html/latest/networking/devlink/index.html

`devlink`_ supports reloading the driver and initiating re-negotiation with the ENA device

.. code-block:: shell

  sudo devlink dev reload pci/<domain:bus:slot.function>
  # for example:
  sudo devlink dev reload pci/0000:00:06.0

Tx data path

379-415

Data path - Tx

Stack이 `ena_start_xmit()`을 호출하면 다음 작업을 수행합니다.

  • Data buffer인 `skb->data`와 fragment를 mapping합니다.
  • Driver와 device가 push mode이면 push buffer용 `ena_buf`를 채웁니다.
  • 나머지 fragment용 ENA buffer를 준비합니다.
  • 비어 있는 `req_id` ring에서 새 request ID를 할당합니다. Request ID는 Tx info에서 packet의 index이며 순서가 뒤바뀐 Tx completion을 처리하는 데 사용합니다.
  • Packet을 Tx ring의 올바른 위치에 추가합니다.
  • `ena_com_prepare_tx()`를 호출합니다. 이 ENA communication layer는 `ena_bufs`를 ENA descriptor로 변환하고 필요하면 meta ENA descriptor를 추가합니다.
  • Push mode이면 이 function이 ENA descriptor와 push buffer를 Device memory 공간에 복사합니다.
  • ENA device에 doorbell을 씁니다.
  • ENA device가 packet 송신을 마치면 completion interrupt가 발생합니다.
  • Interrupt handler가 NAPI를 schedule합니다.
  • `ena_clean_tx_irq()`를 호출합니다. 이 function은 ENA가 만든 completion descriptor를 처리하며 완료 packet 하나마다 completion descriptor 하나가 있습니다.
  • Completion descriptor에서 `req_id`를 얻고 이를 통해 packet의 `tx_info`를 찾습니다. Data buffer mapping을 해제하고 `req_id`를 빈 `req_id` ring에 반환합니다.
  • Completion descriptor 처리가 끝나거나 budget에 도달하면 function이 중지됩니다.
DATA PATH
=========

Tx
--

:code:`ena_start_xmit()` is called by the stack. This function does the following:

- Maps data buffers (``skb->data`` and frags).
- Populates ``ena_buf`` for the push buffer (if the driver and device are
  in push mode).
- Prepares ENA bufs for the remaining frags.
- Allocates a new request ID from the empty ``req_id`` ring. The request
  ID is the index of the packet in the Tx info. This is used for
  out-of-order Tx completions.
- Adds the packet to the proper place in the Tx ring.
- Calls :code:`ena_com_prepare_tx()`, an ENA communication layer that converts
  the ``ena_bufs`` to ENA descriptors (and adds meta ENA descriptors as
  needed).

  * This function also copies the ENA descriptors and the push buffer
    to the Device memory space (if in push mode).

- Writes a doorbell to the ENA device.
- When the ENA device finishes sending the packet, a completion
  interrupt is raised.
- The interrupt handler schedules NAPI.
- The :code:`ena_clean_tx_irq()` function is called. This function handles the
  completion descriptors generated by the ENA, with a single
  completion descriptor per completed packet.

  * ``req_id`` is retrieved from the completion descriptor. The ``tx_info`` of
    the packet is retrieved via the ``req_id``. The data buffers are
    unmapped and ``req_id`` is returned to the empty ``req_id`` ring.
  * The function stops when the completion descriptors are completed or
    the budget is reached.

Rx data path

416-441

Rx

  • ENA device에서 packet이 수신됩니다.
  • Interrupt handler가 NAPI를 schedule합니다.
  • `ena_clean_rx_irq()`를 호출합니다. 이 function은 ENA communication layer function인 `ena_com_rx_pkt()`를 호출합니다. 새 packet에 사용된 descriptor 수를 반환하며 새 packet이 없으면 0을 반환합니다.
  • `ena_rx_skb()`가 packet 길이를 확인합니다.
  • Packet이 작으면(`len < rx_copybreak`) driver가 새 packet용 SKB를 할당하고 packet payload를 SKB data buffer에 복사합니다.
  • 이 방식에서는 원래 data buffer를 stack에 넘기지 않고 이후 Rx packet에서 재사용합니다.
  • 그렇지 않으면 Rx buffer mapping을 해제하고 첫 descriptor를 `skb`의 linear part로, 나머지 descriptor를 `skb` fragment로 설정합니다.
  • 새 SKB에 protocol, checksum hardware 검증 결과 등 필요한 정보를 갱신한 뒤 NAPI interface function `napi_gro_receive()`로 network stack에 전달합니다.
Rx
--

- When a packet is received from the ENA device.
- The interrupt handler schedules NAPI.
- The :code:`ena_clean_rx_irq()` function is called. This function calls
  :code:`ena_com_rx_pkt()`, an ENA communication layer function, which returns the
  number of descriptors used for a new packet, and zero if
  no new packet is found.
- :code:`ena_rx_skb()` checks packet length:

  * If the packet is small (len < rx_copybreak), the driver allocates
    a SKB for the new packet, and copies the packet payload into the
    SKB data buffer.

    - In this way the original data buffer is not passed to the stack
      and is reused for future Rx packets.

  * Otherwise the function unmaps the Rx buffer, sets the first
    descriptor as `skb`'s linear part and the other descriptors as the
    `skb`'s frags.

- The new SKB is updated with the necessary information (protocol,
  checksum hw verify result, etc), and then passed to the network
  stack, using the NAPI interface function :code:`napi_gro_receive()`.

Dynamic RX Buffer

442-471

Dynamic RX Buffer(`DRB`)

RX ring의 각 RX descriptor는 system 설정에 따라 길이가 4KB 또는 16KB인 memory page 하나입니다.

작은 packet을 빠르게 처리할 때 필요한 memory allocation을 줄이기 위해, 이 page에서 사용하지 않은 공간이 2KB보다 많이 남으면 driver는 RX descriptor의 나머지 공간을 재사용하려고 합니다.

간단한 동작 예시는 다음과 같습니다.

  • Driver가 page 크기의 RX buffer를 할당해 hardware에 전달합니다. 예시 buffer는 4KB입니다.
  • 이 buffer에서 300 byte packet을 수신합니다.
  • Driver가 page reference count를 늘리고, 남은 `4KB - 300Bytes = 3796 Bytes` 영역을 RX buffer로 hardware에 다시 반환합니다.

XDP program이 load되어 있거나 RX packet이 `rx_copybreak`보다 작을 때는 이 mechanism을 사용하지 않습니다. 작은 packet은 새로 할당한 skb의 linear part로 RX buffer 밖에 복사하므로 RX buffer 크기는 그대로 유지됩니다. 자세한 내용은 `RX copybreak` 절을 참조하십시오.

Dynamic RX Buffers (DRB)
------------------------

Each RX descriptor in the RX ring is a single memory page (which is either 4KB
or 16KB long depending on system's configurations).
To reduce the memory allocations required when dealing with a high rate of small
packets, the driver tries to reuse the remaining RX descriptor's space if more
than 2KB of this page remain unused.

A simple example of this mechanism is the following sequence of events:

::

        1. Driver allocates page-sized RX buffer and passes it to hardware
                +----------------------+
                |4KB RX Buffer         |
                +----------------------+

        2. A 300Bytes packet is received on this buffer

        3. The driver increases the ref count on this page and returns it back to
           HW as an RX buffer of size 4KB - 300Bytes = 3796 Bytes
               +----+--------------------+
               |****|3796 Bytes RX Buffer|
               +----+--------------------+

This mechanism isn't used when an XDP program is loaded, or when the
RX packet is less than rx_copybreak bytes (in which case the packet is
copied out of the RX buffer into the linear part of a new skb allocated
for it and the RX buffer remains the same size, see `RX copybreak`_).