← Documents Documentation/PCI/msi-howto.rst GitHub 원문 ↗

Linux 6.18.37 · PCI

MSI driver 안내서 HOWTO

MSI/MSI-X의 이점, vector 할당 API, 다중 interrupt locking, quirk 범위와 진단 절차를 설명합니다.

Source pathDocumentation/PCI/msi-howto.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

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

1. 요약·해설

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

요약·해설

msi-howto.rst:1-297

MSI는 공유되지 않는 message write interrupt로, data ordering을 보장하고 event·queue·port별 vector 분리를 가능하게 합니다.

새 driver는 `pci_alloc_irq_vectors()`·`pci_irq_vector()`·`pci_free_irq_vectors()`를 사용하고, 다중 vector에서는 spinlock을 잡을 때 local interrupt를 함께 disable해야 합니다.

MSI 문제는 전역, bridge 아래, single device 범위에서 발생할 수 있으므로 dmesg·kernel config·PCI topology·`msi_bus`·driver flag 순으로 진단합니다.

2. 영어 원문 전체

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

원문 전체 펼치기
1 .. SPDX-License-Identifier: GPL-2.0
2 .. include:: <isonum.txt>
3
4 ==========================
5 The MSI Driver Guide HOWTO
6 ==========================
7
8 :Authors: Tom L Nguyen; Martine Silbermann; Matthew Wilcox
9
10 :Copyright: 2003, 2008 Intel Corporation
11
12 About this guide
13 ================
14
15 This guide describes the basics of Message Signaled Interrupts (MSIs),
16 the advantages of using MSI over traditional interrupt mechanisms, how
17 to change your driver to use MSI or MSI-X and some basic diagnostics to
18 try if a device doesn't support MSIs.
19
20
21 What are MSIs?
22 ==============
23
24 A Message Signaled Interrupt is a write from the device to a special
25 address which causes an interrupt to be received by the CPU.
26
27 The MSI capability was first specified in PCI 2.2 and was later enhanced
28 in PCI 3.0 to allow each interrupt to be masked individually. The MSI-X
29 capability was also introduced with PCI 3.0. It supports more interrupts
30 per device than MSI and allows interrupts to be independently configured.
31
32 Devices may support both MSI and MSI-X, but only one can be enabled at
33 a time.
34
35
36 Why use MSIs?
37 =============
38
39 There are three reasons why using MSIs can give an advantage over
40 traditional pin-based interrupts.
41
42 Pin-based PCI interrupts are often shared amongst several devices.
43 To support this, the kernel must call each interrupt handler associated
44 with an interrupt, which leads to reduced performance for the system as
45 a whole. MSIs are never shared, so this problem cannot arise.
46
47 When a device writes data to memory, then raises a pin-based interrupt,
48 it is possible that the interrupt may arrive before all the data has
49 arrived in memory (this becomes more likely with devices behind PCI-PCI
50 bridges). In order to ensure that all the data has arrived in memory,
51 the interrupt handler must read a register on the device which raised
52 the interrupt. PCI transaction ordering rules require that all the data
53 arrive in memory before the value may be returned from the register.
54 Using MSIs avoids this problem as the interrupt-generating write cannot
55 pass the data writes, so by the time the interrupt is raised, the driver
56 knows that all the data has arrived in memory.
57
58 PCI devices can only support a single pin-based interrupt per function.
59 Often drivers have to query the device to find out what event has
60 occurred, slowing down interrupt handling for the common case. With
61 MSIs, a device can support more interrupts, allowing each interrupt
62 to be specialised to a different purpose. One possible design gives
63 infrequent conditions (such as errors) their own interrupt which allows
64 the driver to handle the normal interrupt handling path more efficiently.
65 Other possible designs include giving one interrupt to each packet queue
66 in a network card or each port in a storage controller.
67
68
69 How to use MSIs
70 ===============
71
72 PCI devices are initialised to use pin-based interrupts. The device
73 driver has to set up the device to use MSI or MSI-X. Not all machines
74 support MSIs correctly, and for those machines, the APIs described below
75 will simply fail and the device will continue to use pin-based interrupts.
76
77 Include kernel support for MSIs
78 -------------------------------
79
80 To support MSI or MSI-X, the kernel must be built with the CONFIG_PCI_MSI
81 option enabled. This option is only available on some architectures,
82 and it may depend on some other options also being set. For example,
83 on x86, you must also enable X86_UP_APIC or SMP in order to see the
84 CONFIG_PCI_MSI option.
85
86 Using MSI
87 ---------
88
89 Most of the hard work is done for the driver in the PCI layer. The driver
90 simply has to request that the PCI layer set up the MSI capability for this
91 device.
92
93 To automatically use MSI or MSI-X interrupt vectors, use the following
94 function::
95
96 int pci_alloc_irq_vectors(struct pci_dev *dev, unsigned int min_vecs,
97 unsigned int max_vecs, unsigned int flags);
98
99 which allocates up to max_vecs interrupt vectors for a PCI device. It
100 returns the number of vectors allocated or a negative error. If the device
101 has a requirements for a minimum number of vectors the driver can pass a
102 min_vecs argument set to this limit, and the PCI core will return -ENOSPC
103 if it can't meet the minimum number of vectors.
104
105 The flags argument is used to specify which type of interrupt can be used
106 by the device and the driver (PCI_IRQ_INTX, PCI_IRQ_MSI, PCI_IRQ_MSIX).
107 A convenient short-hand (PCI_IRQ_ALL_TYPES) is also available to ask for
108 any possible kind of interrupt. If the PCI_IRQ_AFFINITY flag is set,
109 pci_alloc_irq_vectors() will spread the interrupts around the available CPUs.
110
111 To get the Linux IRQ numbers passed to request_irq() and free_irq() and the
112 vectors, use the following function::
113
114 int pci_irq_vector(struct pci_dev *dev, unsigned int nr);
115
116 Any allocated resources should be freed before removing the device using
117 the following function::
118
119 void pci_free_irq_vectors(struct pci_dev *dev);
120
121 If a device supports both MSI-X and MSI capabilities, this API will use the
122 MSI-X facilities in preference to the MSI facilities. MSI-X supports any
123 number of interrupts between 1 and 2048. In contrast, MSI is restricted to
124 a maximum of 32 interrupts (and must be a power of two). In addition, the
125 MSI interrupt vectors must be allocated consecutively, so the system might
126 not be able to allocate as many vectors for MSI as it could for MSI-X. On
127 some platforms, MSI interrupts must all be targeted at the same set of CPUs
128 whereas MSI-X interrupts can all be targeted at different CPUs.
129
130 If a device supports neither MSI-X or MSI it will fall back to a single
131 legacy IRQ vector.
132
133 The typical usage of MSI or MSI-X interrupts is to allocate as many vectors
134 as possible, likely up to the limit supported by the device. If nvec is
135 larger than the number supported by the device it will automatically be
136 capped to the supported limit, so there is no need to query the number of
137 vectors supported beforehand::
138
139 nvec = pci_alloc_irq_vectors(pdev, 1, nvec, PCI_IRQ_ALL_TYPES)
140 if (nvec < 0)
141 goto out_err;
142
143 If a driver is unable or unwilling to deal with a variable number of MSI
144 interrupts it can request a particular number of interrupts by passing that
145 number to pci_alloc_irq_vectors() function as both 'min_vecs' and
146 'max_vecs' parameters::
147
148 ret = pci_alloc_irq_vectors(pdev, nvec, nvec, PCI_IRQ_ALL_TYPES);
149 if (ret < 0)
150 goto out_err;
151
152 The most notorious example of the request type described above is enabling
153 the single MSI mode for a device. It could be done by passing two 1s as
154 'min_vecs' and 'max_vecs'::
155
156 ret = pci_alloc_irq_vectors(pdev, 1, 1, PCI_IRQ_ALL_TYPES);
157 if (ret < 0)
158 goto out_err;
159
160 Some devices might not support using legacy line interrupts, in which case
161 the driver can specify that only MSI or MSI-X is acceptable::
162
163 nvec = pci_alloc_irq_vectors(pdev, 1, nvec, PCI_IRQ_MSI | PCI_IRQ_MSIX);
164 if (nvec < 0)
165 goto out_err;
166
167 Legacy APIs
168 -----------
169
170 The following old APIs to enable and disable MSI or MSI-X interrupts should
171 not be used in new code::
172
173 pci_enable_msi() /* deprecated */
174 pci_disable_msi() /* deprecated */
175 pci_enable_msix_range() /* deprecated */
176 pci_enable_msix_exact() /* deprecated */
177 pci_disable_msix() /* deprecated */
178
179 Additionally there are APIs to provide the number of supported MSI or MSI-X
180 vectors: pci_msi_vec_count() and pci_msix_vec_count(). In general these
181 should be avoided in favor of letting pci_alloc_irq_vectors() cap the
182 number of vectors. If you have a legitimate special use case for the count
183 of vectors we might have to revisit that decision and add a
184 pci_nr_irq_vectors() helper that handles MSI and MSI-X transparently.
185
186 Considerations when using MSIs
187 ------------------------------
188
189 Spinlocks
190 ~~~~~~~~~
191
192 Most device drivers have a per-device spinlock which is taken in the
193 interrupt handler. With pin-based interrupts or a single MSI, it is not
194 necessary to disable interrupts (Linux guarantees the same interrupt will
195 not be re-entered). If a device uses multiple interrupts, the driver
196 must disable interrupts while the lock is held. If the device sends
197 a different interrupt, the driver will deadlock trying to recursively
198 acquire the spinlock. Such deadlocks can be avoided by using
199 spin_lock_irqsave() or spin_lock_irq() which disable local interrupts
200 and acquire the lock (see Documentation/kernel-hacking/locking.rst).
201
202 How to tell whether MSI/MSI-X is enabled on a device
203 ----------------------------------------------------
204
205 Using 'lspci -v' (as root) may show some devices with "MSI", "Message
206 Signalled Interrupts" or "MSI-X" capabilities. Each of these capabilities
207 has an 'Enable' flag which is followed with either "+" (enabled)
208 or "-" (disabled).
209
210
211 MSI quirks
212 ==========
213
214 Several PCI chipsets or devices are known not to support MSIs.
215 The PCI stack provides three ways to disable MSIs:
216
217 1. globally
218 2. on all devices behind a specific bridge
219 3. on a single device
220
221 Disabling MSIs globally
222 -----------------------
223
224 Some host chipsets simply don't support MSIs properly. If we're
225 lucky, the manufacturer knows this and has indicated it in the ACPI
226 FADT table. In this case, Linux automatically disables MSIs.
227 Some boards don't include this information in the table and so we have
228 to detect them ourselves. The complete list of these is found near the
229 quirk_disable_all_msi() function in drivers/pci/quirks.c.
230
231 If you have a board which has problems with MSIs, you can pass pci=nomsi
232 on the kernel command line to disable MSIs on all devices. It would be
233 in your best interests to report the problem to [email protected]
234 including a full 'lspci -v' so we can add the quirks to the kernel.
235
236 Disabling MSIs below a bridge
237 -----------------------------
238
239 Some PCI bridges are not able to route MSIs between buses properly.
240 In this case, MSIs must be disabled on all devices behind the bridge.
241
242 Some bridges allow you to enable MSIs by changing some bits in their
243 PCI configuration space (especially the Hypertransport chipsets such
244 as the nVidia nForce and Serverworks HT2000). As with host chipsets,
245 Linux mostly knows about them and automatically enables MSIs if it can.
246 If you have a bridge unknown to Linux, you can enable
247 MSIs in configuration space using whatever method you know works, then
248 enable MSIs on that bridge by doing::
249
250 echo 1 > /sys/bus/pci/devices/$bridge/msi_bus
251
252 where $bridge is the PCI address of the bridge you've enabled (eg
253 0000:00:0e.0).
254
255 To disable MSIs, echo 0 instead of 1. Changing this value should be
256 done with caution as it could break interrupt handling for all devices
257 below this bridge.
258
259 Again, please notify [email protected] of any bridges that need
260 special handling.
261
262 Disabling MSIs on a single device
263 ---------------------------------
264
265 Some devices are known to have faulty MSI implementations. Usually this
266 is handled in the individual device driver, but occasionally it's necessary
267 to handle this with a quirk. Some drivers have an option to disable use
268 of MSI. While this is a convenient workaround for the driver author,
269 it is not good practice, and should not be emulated.
270
271 Finding why MSIs are disabled on a device
272 -----------------------------------------
273
274 From the above three sections, you can see that there are many reasons
275 why MSIs may not be enabled for a given device. Your first step should
276 be to examine your dmesg carefully to determine whether MSIs are enabled
277 for your machine. You should also check your .config to be sure you
278 have enabled CONFIG_PCI_MSI.
279
280 Then, 'lspci -t' gives the list of bridges above a device. Reading
281 `/sys/bus/pci/devices/*/msi_bus` will tell you whether MSIs are enabled (1)
282 or disabled (0). If 0 is found in any of the msi_bus files belonging
283 to bridges between the PCI root and the device, MSIs are disabled.
284
285 It is also worth checking the device driver to see whether it supports MSIs.
286 For example, it may contain calls to pci_alloc_irq_vectors() with the
287 PCI_IRQ_MSI or PCI_IRQ_MSIX flags.
288
289
290 List of device drivers MSI(-X) APIs
291 ===================================
292
293 The PCI/MSI subsystem has a dedicated C file for its exported device driver
294 APIs — `drivers/pci/msi/api.c`. The following functions are exported:
295
296 .. kernel-doc:: drivers/pci/msi/api.c
297 :export:
298

3. 한국어 전문 번역

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

안내서 소개

1-20

저자는 Tom L Nguyen, Martine Silbermann, Matthew Wilcox이며 저작권은 2003년과 2008년 Intel Corporation에 있습니다.

이 안내서는 Message Signaled Interrupt(MSI)의 기본, 전통적인 interrupt 방식보다 MSI가 유리한 이유, driver를 MSI 또는 MSI-X용으로 바꾸는 방법, device가 MSI를 지원하지 않을 때 시도할 기본 진단을 설명합니다.

.. SPDX-License-Identifier: GPL-2.0
.. include:: <isonum.txt>

==========================
The MSI Driver Guide HOWTO
==========================

:Authors: Tom L Nguyen; Martine Silbermann; Matthew Wilcox

:Copyright: 2003, 2008 Intel Corporation

About this guide
================

This guide describes the basics of Message Signaled Interrupts (MSIs),
the advantages of using MSI over traditional interrupt mechanisms, how
to change your driver to use MSI or MSI-X and some basic diagnostics to
try if a device doesn't support MSIs.

MSI와 MSI-X란 무엇인가

21-35

Message Signaled Interrupt는 device가 특별한 address에 write하여 CPU가 interrupt를 받게 하는 방식입니다.

MSI capability는 PCI 2.2에서 처음 규정됐고, PCI 3.0에서는 각 interrupt를 개별 mask할 수 있도록 확장됐습니다. PCI 3.0에서 함께 도입된 MSI-X는 device당 더 많은 interrupt를 지원하고 각각을 독립적으로 구성할 수 있습니다.

Device가 MSI와 MSI-X를 모두 지원할 수는 있지만 한 번에 하나만 enable할 수 있습니다.

MSI capability 비교
Capability도입특징
MSIPCI 2.2PCI 3.0부터 개별 mask, 최대 32 vector
MSI-XPCI 3.0독립 구성, 최대 2048 vector

PCI revision과 핵심 차이를 정리합니다.

What are MSIs?
==============

A Message Signaled Interrupt is a write from the device to a special
address which causes an interrupt to be received by the CPU.

The MSI capability was first specified in PCI 2.2 and was later enhanced
in PCI 3.0 to allow each interrupt to be masked individually.  The MSI-X
capability was also introduced with PCI 3.0.  It supports more interrupts
per device than MSI and allows interrupts to be independently configured.

Devices may support both MSI and MSI-X, but only one can be enabled at
a time.

MSI를 사용하는 세 가지 이유

36-68

첫째, pin 기반 PCI interrupt는 여러 device가 공유하는 경우가 많아 kernel이 연결된 interrupt handler를 모두 호출해야 합니다. MSI는 공유되지 않으므로 이로 인한 system 전체 성능 저하가 없습니다.

둘째, pin 기반 interrupt는 device가 memory에 쓴 data가 모두 도착하기 전에 CPU에 도착할 수 있습니다. 특히 PCI-PCI bridge 뒤의 device에서 가능성이 커집니다. Handler가 interrupt를 일으킨 device register를 읽으면 PCI transaction ordering 규칙에 따라 data가 먼저 memory에 도착하도록 보장할 수 있지만 추가 read가 필요합니다.

MSI에서는 interrupt를 생성하는 write가 앞선 data write를 추월할 수 없습니다. 따라서 interrupt가 발생했을 때 driver는 모든 data가 memory에 도착했음을 알 수 있습니다.

셋째, PCI function 하나는 pin 기반 interrupt 하나만 지원하지만 MSI는 여러 interrupt를 제공할 수 있습니다. Error처럼 드문 상태, network card의 packet queue별 처리, storage controller의 port별 처리에 vector를 나누면 일반 경로가 더 효율적입니다.

MSI의 장점
관점Pin 기반MSI/MSI-X
공유여러 device handler 호출Vector를 공유하지 않음
OrderingRegister read로 data 도착 확인Interrupt write가 data write를 추월하지 못함
구분Function당 interrupt 하나Queue·port·error별 vector 가능

공유·ordering·event 분리 관점의 이점입니다.

Why use MSIs?
=============

There are three reasons why using MSIs can give an advantage over
traditional pin-based interrupts.

Pin-based PCI interrupts are often shared amongst several devices.
To support this, the kernel must call each interrupt handler associated
with an interrupt, which leads to reduced performance for the system as
a whole.  MSIs are never shared, so this problem cannot arise.

When a device writes data to memory, then raises a pin-based interrupt,
it is possible that the interrupt may arrive before all the data has
arrived in memory (this becomes more likely with devices behind PCI-PCI
bridges).  In order to ensure that all the data has arrived in memory,
the interrupt handler must read a register on the device which raised
the interrupt.  PCI transaction ordering rules require that all the data
arrive in memory before the value may be returned from the register.
Using MSIs avoids this problem as the interrupt-generating write cannot
pass the data writes, so by the time the interrupt is raised, the driver
knows that all the data has arrived in memory.

PCI devices can only support a single pin-based interrupt per function.
Often drivers have to query the device to find out what event has
occurred, slowing down interrupt handling for the common case.  With
MSIs, a device can support more interrupts, allowing each interrupt
to be specialised to a different purpose.  One possible design gives
infrequent conditions (such as errors) their own interrupt which allows
the driver to handle the normal interrupt handling path more efficiently.
Other possible designs include giving one interrupt to each packet queue
in a network card or each port in a storage controller.

MSI 사용과 kernel 지원

69-85

PCI device는 처음에는 pin 기반 interrupt를 사용하도록 초기화됩니다. Device driver가 MSI 또는 MSI-X를 사용하도록 설정해야 합니다.

MSI를 올바르게 지원하지 않는 machine에서는 아래 API가 실패하고 device는 pin 기반 interrupt를 계속 사용합니다.

Kernel은 `CONFIG_PCI_MSI`를 enable하여 build해야 합니다. 이 option은 일부 architecture에서만 제공되고 다른 option에 의존할 수 있습니다. 예를 들어 x86에서는 `CONFIG_PCI_MSI`를 보려면 `X86_UP_APIC` 또는 `SMP`도 enable해야 합니다.

How to use MSIs
===============

PCI devices are initialised to use pin-based interrupts.  The device
driver has to set up the device to use MSI or MSI-X.  Not all machines
support MSIs correctly, and for those machines, the APIs described below
will simply fail and the device will continue to use pin-based interrupts.

Include kernel support for MSIs
-------------------------------

To support MSI or MSI-X, the kernel must be built with the CONFIG_PCI_MSI
option enabled.  This option is only available on some architectures,
and it may depend on some other options also being set.  For example,
on x86, you must also enable X86_UP_APIC or SMP in order to see the
CONFIG_PCI_MSI option.

Vector 할당·조회·해제 API

86-120

어려운 작업 대부분은 PCI layer가 처리합니다. Driver는 PCI layer에 해당 device의 MSI capability 설정을 요청하면 됩니다.

`pci_alloc_irq_vectors()`는 PCI device에 `max_vecs` 이하의 interrupt vector를 할당하고, 성공하면 할당된 수를, 실패하면 음수 error를 반환합니다. 최소 vector 요구가 있으면 `min_vecs`에 지정하며 PCI core가 이를 만족하지 못하면 `-ENOSPC`를 반환합니다.

int pci_alloc_irq_vectors(struct pci_dev *dev, unsigned int min_vecs,
                          unsigned int max_vecs, unsigned int flags);

`flags`에는 device와 driver가 사용할 수 있는 interrupt 유형 `PCI_IRQ_INTX`, `PCI_IRQ_MSI`, `PCI_IRQ_MSIX`를 지정합니다. `PCI_IRQ_ALL_TYPES`는 가능한 모든 유형을 허용하는 축약형입니다. `PCI_IRQ_AFFINITY`를 설정하면 `pci_alloc_irq_vectors()`가 사용 가능한 CPU들에 interrupt를 분산합니다.

`request_irq()`와 `free_irq()`에 전달할 Linux IRQ number 및 vector는 `pci_irq_vector()`로 구합니다.

int pci_irq_vector(struct pci_dev *dev, unsigned int nr);

Device를 제거하기 전에 할당된 resource를 `pci_free_irq_vectors()`로 해제해야 합니다.

void pci_free_irq_vectors(struct pci_dev *dev);
MSI vector 생명주기
pci_alloc_irq_vectors()pci_irq_vector()request_irq()/free_irq()pci_free_irq_vectors()

할당한 vector 번호를 IRQ 등록에 사용하고 device 제거 전에 해제합니다.

Using MSI
---------

Most of the hard work is done for the driver in the PCI layer.  The driver
simply has to request that the PCI layer set up the MSI capability for this
device.

To automatically use MSI or MSI-X interrupt vectors, use the following
function::

  int pci_alloc_irq_vectors(struct pci_dev *dev, unsigned int min_vecs,
                unsigned int max_vecs, unsigned int flags);

which allocates up to max_vecs interrupt vectors for a PCI device.  It
returns the number of vectors allocated or a negative error.  If the device
has a requirements for a minimum number of vectors the driver can pass a
min_vecs argument set to this limit, and the PCI core will return -ENOSPC
if it can't meet the minimum number of vectors.

The flags argument is used to specify which type of interrupt can be used
by the device and the driver (PCI_IRQ_INTX, PCI_IRQ_MSI, PCI_IRQ_MSIX).
A convenient short-hand (PCI_IRQ_ALL_TYPES) is also available to ask for
any possible kind of interrupt.  If the PCI_IRQ_AFFINITY flag is set,
pci_alloc_irq_vectors() will spread the interrupts around the available CPUs.

To get the Linux IRQ numbers passed to request_irq() and free_irq() and the
vectors, use the following function::

  int pci_irq_vector(struct pci_dev *dev, unsigned int nr);

Any allocated resources should be freed before removing the device using
the following function::

  void pci_free_irq_vectors(struct pci_dev *dev);

MSI-X 우선순위와 vector 제한

121-132

Device가 MSI-X와 MSI를 모두 지원하면 이 API는 MSI-X를 우선 사용합니다. MSI-X는 1개부터 2048개까지 임의 개수의 interrupt를 지원합니다.

MSI는 최대 32개이며 개수는 2의 거듭제곱이어야 합니다. MSI vector는 연속으로 할당해야 하므로 system이 MSI-X만큼 많은 vector를 제공하지 못할 수 있습니다.

일부 platform에서는 모든 MSI interrupt가 같은 CPU 집합을 대상으로 해야 하지만 MSI-X interrupt는 서로 다른 CPU를 대상으로 지정할 수 있습니다.

MSI-X와 MSI를 모두 지원하지 않으면 single legacy IRQ vector로 fallback합니다.

If a device supports both MSI-X and MSI capabilities, this API will use the
MSI-X facilities in preference to the MSI facilities.  MSI-X supports any
number of interrupts between 1 and 2048.  In contrast, MSI is restricted to
a maximum of 32 interrupts (and must be a power of two).  In addition, the
MSI interrupt vectors must be allocated consecutively, so the system might
not be able to allocate as many vectors for MSI as it could for MSI-X.  On
some platforms, MSI interrupts must all be targeted at the same set of CPUs
whereas MSI-X interrupts can all be targeted at different CPUs.

If a device supports neither MSI-X or MSI it will fall back to a single
legacy IRQ vector.

Vector 할당 방식

133-166

일반적인 방식은 device가 지원하는 한도까지 가능한 많은 MSI 또는 MSI-X vector를 할당하는 것입니다. `nvec`가 지원 한도보다 크면 자동으로 제한되므로 사전에 지원 개수를 조회할 필요가 없습니다.

nvec = pci_alloc_irq_vectors(pdev, 1, nvec, PCI_IRQ_ALL_TYPES)
if (nvec < 0)
        goto out_err;

Driver가 가변 개수 MSI를 처리할 수 없거나 원하지 않으면 `min_vecs`와 `max_vecs`에 같은 값을 전달해 정확한 수를 요청합니다.

ret = pci_alloc_irq_vectors(pdev, nvec, nvec, PCI_IRQ_ALL_TYPES);
if (ret < 0)
        goto out_err;

대표적인 정확 수 요청은 single MSI mode이며 두 인자에 모두 `1`을 전달합니다.

ret = pci_alloc_irq_vectors(pdev, 1, 1, PCI_IRQ_ALL_TYPES);
if (ret < 0)
        goto out_err;

Legacy line interrupt를 지원하지 않는 device에서는 MSI 또는 MSI-X만 허용하도록 지정할 수 있습니다.

nvec = pci_alloc_irq_vectors(pdev, 1, nvec, PCI_IRQ_MSI | PCI_IRQ_MSIX);
if (nvec < 0)
        goto out_err;
Vector 요청 패턴
요청min_vecsmax_vecsflags
가능한 만큼1nvecPCI_IRQ_ALL_TYPES
정확히 nvecnvecnvecPCI_IRQ_ALL_TYPES
Single MSI11PCI_IRQ_ALL_TYPES
Legacy 금지1nvecPCI_IRQ_MSI | PCI_IRQ_MSIX

min/max와 flags 조합별 목적입니다.

The typical usage of MSI or MSI-X interrupts is to allocate as many vectors
as possible, likely up to the limit supported by the device.  If nvec is
larger than the number supported by the device it will automatically be
capped to the supported limit, so there is no need to query the number of
vectors supported beforehand::

        nvec = pci_alloc_irq_vectors(pdev, 1, nvec, PCI_IRQ_ALL_TYPES)
        if (nvec < 0)
                goto out_err;

If a driver is unable or unwilling to deal with a variable number of MSI
interrupts it can request a particular number of interrupts by passing that
number to pci_alloc_irq_vectors() function as both 'min_vecs' and
'max_vecs' parameters::

        ret = pci_alloc_irq_vectors(pdev, nvec, nvec, PCI_IRQ_ALL_TYPES);
        if (ret < 0)
                goto out_err;

The most notorious example of the request type described above is enabling
the single MSI mode for a device.  It could be done by passing two 1s as
'min_vecs' and 'max_vecs'::

        ret = pci_alloc_irq_vectors(pdev, 1, 1, PCI_IRQ_ALL_TYPES);
        if (ret < 0)
                goto out_err;

Some devices might not support using legacy line interrupts, in which case
the driver can specify that only MSI or MSI-X is acceptable::

        nvec = pci_alloc_irq_vectors(pdev, 1, nvec, PCI_IRQ_MSI | PCI_IRQ_MSIX);
        if (nvec < 0)
                goto out_err;

사용하지 말아야 할 legacy API

167-185

새 code에서는 MSI 또는 MSI-X를 enable·disable하는 다음의 오래된 API를 사용하지 않아야 합니다.

pci_enable_msi()          /* deprecated */
pci_disable_msi()         /* deprecated */
pci_enable_msix_range()   /* deprecated */
pci_enable_msix_exact()   /* deprecated */
pci_disable_msix()        /* deprecated */

지원 vector 수를 제공하는 `pci_msi_vec_count()`와 `pci_msix_vec_count()`도 있습니다. 일반적으로는 이를 피하고 `pci_alloc_irq_vectors()`가 vector 수를 제한하도록 해야 합니다.

Vector 수 자체가 필요한 정당한 특수 사례가 있다면 MSI와 MSI-X를 투명하게 처리하는 `pci_nr_irq_vectors()` helper를 추가하는 결정을 재검토할 수 있습니다.

Legacy APIs
-----------

The following old APIs to enable and disable MSI or MSI-X interrupts should
not be used in new code::

  pci_enable_msi()                /* deprecated */
  pci_disable_msi()                /* deprecated */
  pci_enable_msix_range()        /* deprecated */
  pci_enable_msix_exact()        /* deprecated */
  pci_disable_msix()                /* deprecated */

Additionally there are APIs to provide the number of supported MSI or MSI-X
vectors: pci_msi_vec_count() and pci_msix_vec_count().  In general these
should be avoided in favor of letting pci_alloc_irq_vectors() cap the
number of vectors.  If you have a legitimate special use case for the count
of vectors we might have to revisit that decision and add a
pci_nr_irq_vectors() helper that handles MSI and MSI-X transparently.

다중 interrupt와 spinlock

186-201

대부분의 device driver에는 interrupt handler가 잡는 device별 spinlock이 있습니다. Pin 기반 interrupt나 single MSI에서는 Linux가 같은 interrupt의 재진입을 막으므로 interrupt를 disable할 필요가 없습니다.

Device가 여러 interrupt를 사용하면 lock을 보유하는 동안 local interrupt를 disable해야 합니다. 다른 interrupt가 들어오면 같은 spinlock을 재귀적으로 잡으려다 deadlock이 발생할 수 있습니다.

`spin_lock_irqsave()` 또는 `spin_lock_irq()`로 local interrupt를 disable하면서 lock을 획득하면 이를 피할 수 있습니다. 자세한 내용은 `Documentation/kernel-hacking/locking.rst`를 참조하십시오.

Considerations when using MSIs
------------------------------

Spinlocks
~~~~~~~~~

Most device drivers have a per-device spinlock which is taken in the
interrupt handler.  With pin-based interrupts or a single MSI, it is not
necessary to disable interrupts (Linux guarantees the same interrupt will
not be re-entered).  If a device uses multiple interrupts, the driver
must disable interrupts while the lock is held.  If the device sends
a different interrupt, the driver will deadlock trying to recursively
acquire the spinlock.  Such deadlocks can be avoided by using
spin_lock_irqsave() or spin_lock_irq() which disable local interrupts
and acquire the lock (see Documentation/kernel-hacking/locking.rst).

Device의 MSI enable 상태 확인

202-210

Root 권한으로 `lspci -v`를 실행하면 일부 device에 `MSI`, `Message Signalled Interrupts`, `MSI-X` capability가 표시됩니다.

각 capability의 `Enable` flag 뒤에 `+`가 있으면 enable, `-`가 있으면 disable 상태입니다.

lspci -v
MSI: Enable+
MSI-X: Enable-
How to tell whether MSI/MSI-X is enabled on a device
----------------------------------------------------

Using 'lspci -v' (as root) may show some devices with "MSI", "Message
Signalled Interrupts" or "MSI-X" capabilities.  Each of these capabilities
has an 'Enable' flag which is followed with either "+" (enabled)
or "-" (disabled).

MSI quirk의 세 범위

211-220

MSI를 지원하지 않는 것으로 알려진 PCI chipset과 device가 여러 개 있습니다. PCI stack은 MSI를 세 범위에서 disable할 수 있습니다.

MSI disable 범위
범위대상
전역Machine의 모든 device
Bridge 아래특정 bridge 뒤의 모든 device
Single device결함이 있는 device 하나

문제 위치에 따라 적용 범위를 선택합니다.

MSI quirks
==========

Several PCI chipsets or devices are known not to support MSIs.
The PCI stack provides three ways to disable MSIs:

1. globally
2. on all devices behind a specific bridge
3. on a single device

MSI 전역 비활성화

221-235

일부 host chipset은 MSI를 올바르게 지원하지 않습니다. 제조사가 ACPI FADT table에 이를 표시한 경우 Linux가 MSI를 자동으로 disable합니다.

Table에 정보가 없는 board는 kernel이 직접 감지해야 하며 전체 목록은 `drivers/pci/quirks.c`의 `quirk_disable_all_msi()` 근처에 있습니다.

MSI 문제가 있는 board에서는 kernel command line에 `pci=nomsi`를 전달해 모든 device의 MSI를 disable할 수 있습니다.

문제를 kernel quirk에 추가할 수 있도록 전체 `lspci -v`와 함께 `[email protected]`에 보고하는 것이 좋습니다.

Disabling MSIs globally
-----------------------

Some host chipsets simply don't support MSIs properly.  If we're
lucky, the manufacturer knows this and has indicated it in the ACPI
FADT table.  In this case, Linux automatically disables MSIs.
Some boards don't include this information in the table and so we have
to detect them ourselves.  The complete list of these is found near the
quirk_disable_all_msi() function in drivers/pci/quirks.c.

If you have a board which has problems with MSIs, you can pass pci=nomsi
on the kernel command line to disable MSIs on all devices.  It would be
in your best interests to report the problem to [email protected]
including a full 'lspci -v' so we can add the quirks to the kernel.

Bridge 아래 MSI 제어

236-261

일부 PCI bridge는 bus 사이에서 MSI를 올바르게 route하지 못하므로 그 bridge 뒤의 모든 device에서 MSI를 disable해야 합니다.

일부 bridge, 특히 nVidia nForce와 Serverworks HT2000 같은 HyperTransport chipset은 PCI configuration space의 bit를 바꾸면 MSI를 enable할 수 있습니다. Linux는 알려진 bridge를 대부분 자동 처리합니다.

Linux가 모르는 bridge라면 동작하는 방식으로 configuration space에서 MSI를 enable한 뒤 해당 bridge의 `msi_bus`에 `1`을 기록합니다. `$bridge`는 `0000:00:0e.0` 같은 PCI address입니다.

echo 1 > /sys/bus/pci/devices/$bridge/msi_bus

Disable하려면 `1` 대신 `0`을 기록합니다. 이 값 변경은 bridge 아래 모든 device의 interrupt 처리를 망가뜨릴 수 있으므로 주의해야 합니다.

특수 처리가 필요한 bridge도 `[email protected]`에 알려주십시오.

Disabling MSIs below a bridge
-----------------------------

Some PCI bridges are not able to route MSIs between buses properly.
In this case, MSIs must be disabled on all devices behind the bridge.

Some bridges allow you to enable MSIs by changing some bits in their
PCI configuration space (especially the Hypertransport chipsets such
as the nVidia nForce and Serverworks HT2000).  As with host chipsets,
Linux mostly knows about them and automatically enables MSIs if it can.
If you have a bridge unknown to Linux, you can enable
MSIs in configuration space using whatever method you know works, then
enable MSIs on that bridge by doing::

       echo 1 > /sys/bus/pci/devices/$bridge/msi_bus

where $bridge is the PCI address of the bridge you've enabled (eg
0000:00:0e.0).

To disable MSIs, echo 0 instead of 1.  Changing this value should be
done with caution as it could break interrupt handling for all devices
below this bridge.

Again, please notify [email protected] of any bridges that need
special handling.

Single device의 MSI 비활성화

262-270

MSI 구현에 결함이 있는 것으로 알려진 device가 있습니다. 보통 개별 device driver에서 처리하지만 때로는 quirk로 처리해야 합니다.

일부 driver는 MSI 사용을 끄는 option을 제공합니다. Driver 작성자에게 편리한 workaround이지만 좋은 관행이 아니므로 따라 하지 않아야 합니다.

Disabling MSIs on a single device
---------------------------------

Some devices are known to have faulty MSI implementations.  Usually this
is handled in the individual device driver, but occasionally it's necessary
to handle this with a quirk.  Some drivers have an option to disable use
of MSI.  While this is a convenient workaround for the driver author,
it is not good practice, and should not be emulated.

MSI가 비활성화된 이유 찾기

271-289

특정 device에서 MSI가 enable되지 않는 이유는 여러 가지입니다. 먼저 `dmesg`를 자세히 확인해 machine에서 MSI가 enable됐는지 판단하고, `.config`에서 `CONFIG_PCI_MSI`를 enable했는지 확인합니다.

그 다음 `lspci -t`로 device 위의 bridge 목록을 봅니다. `/sys/bus/pci/devices/*/msi_bus`는 MSI가 enable이면 `1`, disable이면 `0`입니다. PCI root와 device 사이 어느 bridge의 `msi_bus`라도 `0`이면 MSI는 disable됩니다.

Device driver 자체가 MSI를 지원하는지도 확인해야 합니다. 예를 들어 `PCI_IRQ_MSI` 또는 `PCI_IRQ_MSIX` flag로 `pci_alloc_irq_vectors()`를 호출하는지 살펴볼 수 있습니다.

MSI 진단 순서
dmesgCONFIG_PCI_MSIlspci -t각 bridge msi_busdriver의 pci_alloc_irq_vectors() flags

Machine·bridge·driver 순으로 범위를 좁힙니다.

Finding why MSIs are disabled on a device
-----------------------------------------

From the above three sections, you can see that there are many reasons
why MSIs may not be enabled for a given device.  Your first step should
be to examine your dmesg carefully to determine whether MSIs are enabled
for your machine.  You should also check your .config to be sure you
have enabled CONFIG_PCI_MSI.

Then, 'lspci -t' gives the list of bridges above a device. Reading
`/sys/bus/pci/devices/*/msi_bus` will tell you whether MSIs are enabled (1)
or disabled (0).  If 0 is found in any of the msi_bus files belonging
to bridges between the PCI root and the device, MSIs are disabled.

It is also worth checking the device driver to see whether it supports MSIs.
For example, it may contain calls to pci_alloc_irq_vectors() with the
PCI_IRQ_MSI or PCI_IRQ_MSIX flags.

Device driver용 MSI API 목록

290-297

PCI/MSI subsystem의 exported device driver API는 전용 C file `drivers/pci/msi/api.c`에 있습니다.

마지막 `.. kernel-doc:: drivers/pci/msi/api.c`와 `:export:` 지시문은 Sphinx build 시 해당 source file의 exported kernel-doc 함수 설명을 이 페이지에 삽입합니다.

.. kernel-doc:: drivers/pci/msi/api.c
   :export:
List of device drivers MSI(-X) APIs
===================================

The PCI/MSI subsystem has a dedicated C file for its exported device driver
APIs — `drivers/pci/msi/api.c`. The following functions are exported:

.. kernel-doc:: drivers/pci/msi/api.c
   :export: