← Documents Documentation/firmware-guide/acpi/enumeration.rst GitHub 원문 ↗

Linux 6.18.37 · Firmware

ACPI Based Device Enumeration

ACPI 기반 platform·SPI·I2C·DMA·GPIO·MFD·PCI device 열거와 PRP0001 규칙의 전문 번역입니다.

Source pathDocumentation/firmware-guide/acpi/enumeration.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

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

1. 요약·해설

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

요약·해설

enumeration.rst:1-733

이 문서는 ACPI Namespace의 object를 Linux driver model의 platform, SPI, I2C, DMA, GPIO, MFD, PCI device에 연결하는 전체 규칙을 설명한다. 핵심은 `struct acpi_device`를 configuration interface로 사용하되 driver는 `struct platform_device`, `struct pci_dev`, `struct spi_device`, `struct i2c_client` 같은 실제 bus object에 bind하는 것이다.

Serial bus resource와 controller 등록 시점이 slave 열거를 결정하고, `_DSD`는 interrupt 이름, EEPROM geometry, PWM 참조, GPIO consumer 이름, RS-485 capability와 DT-compatible ID를 전달한다. API와 property는 배열 index, resource 순서, 단위를 정확히 보존해야 한다.

`PRP0001`은 DT `compatible` namespace를 ACPI에 연결하지만 `_HID`와 `_CID`에서의 위치에 따라 유효성, 열거 여부, match 우선순위가 달라진다. PCI 고정 장치는 root port부터 모든 bridge를 기술해야 하며, Exar 예제는 `00:14.1 → 05:00.0 → 06:01.0 → 07:00.0` 경로를 ACPI hierarchy로 옮긴다.

ACPI 열거 검토 순서
_HID·_CID·_ADR과 bus connector resource 확인실제 driver binding object 유형 결정Controller 등록 시점과 child 자동 열거 확인_DSD property 이름·index·단위 검증ACPI_COMPANION()으로 configuration 접근PRP0001이면 compatible 유효성과 우선순위 확인PCI 고정 장치면 root port부터 전체 hierarchy 검증

새 ACPI 지원 driver와 firmware table을 함께 검토할 때의 기준이다.

2. 영어 원문 전체

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

원문 전체 펼치기
1 .. SPDX-License-Identifier: GPL-2.0
2
3 =============================
4 ACPI Based Device Enumeration
5 =============================
6
7 ACPI 5 introduced a set of new resources (UartTSerialBus, I2cSerialBus,
8 SpiSerialBus, GpioIo and GpioInt) which can be used in enumerating slave
9 devices behind serial bus controllers.
10
11 In addition we are starting to see peripherals integrated in the
12 SoC/Chipset to appear only in ACPI namespace. These are typically devices
13 that are accessed through memory-mapped registers.
14
15 In order to support this and re-use the existing drivers as much as
16 possible we decided to do following:
17
18 - Devices that have no bus connector resource are represented as
19 platform devices.
20
21 - Devices behind real busses where there is a connector resource
22 are represented as struct spi_device or struct i2c_client. Note
23 that standard UARTs are not busses so there is no struct uart_device,
24 although some of them may be represented by struct serdev_device.
25
26 As both ACPI and Device Tree represent a tree of devices (and their
27 resources) this implementation follows the Device Tree way as much as
28 possible.
29
30 The ACPI implementation enumerates devices behind busses (platform, SPI,
31 I2C, and in some cases UART), creates the physical devices and binds them
32 to their ACPI handle in the ACPI namespace.
33
34 This means that when ACPI_HANDLE(dev) returns non-NULL the device was
35 enumerated from ACPI namespace. This handle can be used to extract other
36 device-specific configuration. There is an example of this below.
37
38 Platform bus support
39 ====================
40
41 Since we are using platform devices to represent devices that are not
42 connected to any physical bus we only need to implement a platform driver
43 for the device and add supported ACPI IDs. If this same IP-block is used on
44 some other non-ACPI platform, the driver might work out of the box or needs
45 some minor changes.
46
47 Adding ACPI support for an existing driver should be pretty
48 straightforward. Here is the simplest example::
49
50 static const struct acpi_device_id mydrv_acpi_match[] = {
51 /* ACPI IDs here */
52 { }
53 };
54 MODULE_DEVICE_TABLE(acpi, mydrv_acpi_match);
55
56 static struct platform_driver my_driver = {
57 ...
58 .driver = {
59 .acpi_match_table = mydrv_acpi_match,
60 },
61 };
62
63 If the driver needs to perform more complex initialization like getting and
64 configuring GPIOs it can get its ACPI handle and extract this information
65 from ACPI tables.
66
67 ACPI device objects
68 ===================
69
70 Generally speaking, there are two categories of devices in a system in which
71 ACPI is used as an interface between the platform firmware and the OS: Devices
72 that can be discovered and enumerated natively, through a protocol defined for
73 the specific bus that they are on (for example, configuration space in PCI),
74 without the platform firmware assistance, and devices that need to be described
75 by the platform firmware so that they can be discovered. Still, for any device
76 known to the platform firmware, regardless of which category it falls into,
77 there can be a corresponding ACPI device object in the ACPI Namespace in which
78 case the Linux kernel will create a struct acpi_device object based on it for
79 that device.
80
81 Those struct acpi_device objects are never used for binding drivers to natively
82 discoverable devices, because they are represented by other types of device
83 objects (for example, struct pci_dev for PCI devices) that are bound to by
84 device drivers (the corresponding struct acpi_device object is then used as
85 an additional source of information on the configuration of the given device).
86 Moreover, the core ACPI device enumeration code creates struct platform_device
87 objects for the majority of devices that are discovered and enumerated with the
88 help of the platform firmware and those platform device objects can be bound to
89 by platform drivers in direct analogy with the natively enumerable devices
90 case. Therefore it is logically inconsistent and so generally invalid to bind
91 drivers to struct acpi_device objects, including drivers for devices that are
92 discovered with the help of the platform firmware.
93
94 Historically, ACPI drivers that bound directly to struct acpi_device objects
95 were implemented for some devices enumerated with the help of the platform
96 firmware, but this is not recommended for any new drivers. As explained above,
97 platform device objects are created for those devices as a rule (with a few
98 exceptions that are not relevant here) and so platform drivers should be used
99 for handling them, even though the corresponding ACPI device objects are the
100 only source of device configuration information in that case.
101
102 For every device having a corresponding struct acpi_device object, the pointer
103 to it is returned by the ACPI_COMPANION() macro, so it is always possible to
104 get to the device configuration information stored in the ACPI device object
105 this way. Accordingly, struct acpi_device can be regarded as a part of the
106 interface between the kernel and the ACPI Namespace, whereas device objects of
107 other types (for example, struct pci_dev or struct platform_device) are used
108 for interacting with the rest of the system.
109
110 DMA support
111 ===========
112
113 DMA controllers enumerated via ACPI should be registered in the system to
114 provide generic access to their resources. For example, a driver that would
115 like to be accessible to slave devices via generic API call
116 dma_request_chan() must register itself at the end of the probe function like
117 this::
118
119 err = devm_acpi_dma_controller_register(dev, xlate_func, dw);
120 /* Handle the error if it's not a case of !CONFIG_ACPI */
121
122 and implement custom xlate function if needed (usually acpi_dma_simple_xlate()
123 is enough) which converts the FixedDMA resource provided by struct
124 acpi_dma_spec into the corresponding DMA channel. A piece of code for that case
125 could look like::
126
127 #ifdef CONFIG_ACPI
128 struct filter_args {
129 /* Provide necessary information for the filter_func */
130 ...
131 };
132
133 static bool filter_func(struct dma_chan *chan, void *param)
134 {
135 /* Choose the proper channel */
136 ...
137 }
138
139 static struct dma_chan *xlate_func(struct acpi_dma_spec *dma_spec,
140 struct acpi_dma *adma)
141 {
142 dma_cap_mask_t cap;
143 struct filter_args args;
144
145 /* Prepare arguments for filter_func */
146 ...
147 return dma_request_channel(cap, filter_func, &args);
148 }
149 #else
150 static struct dma_chan *xlate_func(struct acpi_dma_spec *dma_spec,
151 struct acpi_dma *adma)
152 {
153 return NULL;
154 }
155 #endif
156
157 dma_request_chan() will call xlate_func() for each registered DMA controller.
158 In the xlate function the proper channel must be chosen based on
159 information in struct acpi_dma_spec and the properties of the controller
160 provided by struct acpi_dma.
161
162 Clients must call dma_request_chan() with the string parameter that corresponds
163 to a specific FixedDMA resource. By default "tx" means the first entry of the
164 FixedDMA resource array, "rx" means the second entry. The table below shows a
165 layout::
166
167 Device (I2C0)
168 {
169 ...
170 Method (_CRS, 0, NotSerialized)
171 {
172 Name (DBUF, ResourceTemplate ()
173 {
174 FixedDMA (0x0018, 0x0004, Width32bit, _Y48)
175 FixedDMA (0x0019, 0x0005, Width32bit, )
176 })
177 ...
178 }
179 }
180
181 So, the FixedDMA with request line 0x0018 is "tx" and next one is "rx" in
182 this example.
183
184 In robust cases the client unfortunately needs to call
185 acpi_dma_request_slave_chan_by_index() directly and therefore choose the
186 specific FixedDMA resource by its index.
187
188 Named Interrupts
189 ================
190
191 Drivers enumerated via ACPI can have names to interrupts in the ACPI table
192 which can be used to get the IRQ number in the driver.
193
194 The interrupt name can be listed in _DSD as 'interrupt-names'. The names
195 should be listed as an array of strings which will map to the Interrupt()
196 resource in the ACPI table corresponding to its index.
197
198 The table below shows an example of its usage::
199
200 Device (DEV0) {
201 ...
202 Name (_CRS, ResourceTemplate() {
203 ...
204 Interrupt (ResourceConsumer, Level, ActiveHigh, Exclusive) {
205 0x20,
206 0x24
207 }
208 })
209
210 Name (_DSD, Package () {
211 ToUUID("daffd814-6eba-4d8c-8a91-bc9bbf4aa301"),
212 Package () {
213 Package () { "interrupt-names", Package () { "default", "alert" } },
214 }
215 ...
216 })
217 }
218
219 The interrupt name 'default' will correspond to 0x20 in Interrupt()
220 resource and 'alert' to 0x24. Note that only the Interrupt() resource
221 is mapped and not GpioInt() or similar.
222
223 The driver can call the function - fwnode_irq_get_byname() with the fwnode
224 and interrupt name as arguments to get the corresponding IRQ number.
225
226 SPI serial bus support
227 ======================
228
229 Slave devices behind SPI bus have SpiSerialBus resource attached to them.
230 This is extracted automatically by the SPI core and the slave devices are
231 enumerated once spi_register_master() is called by the bus driver.
232
233 Here is what the ACPI namespace for a SPI slave might look like::
234
235 Device (EEP0)
236 {
237 Name (_ADR, 1)
238 Name (_CID, Package () {
239 "ATML0025",
240 "AT25",
241 })
242 ...
243 Method (_CRS, 0, NotSerialized)
244 {
245 SPISerialBus(1, PolarityLow, FourWireMode, 8,
246 ControllerInitiated, 1000000, ClockPolarityLow,
247 ClockPhaseFirst, "\\_SB.PCI0.SPI1",)
248 }
249 ...
250
251 The SPI device drivers only need to add ACPI IDs in a similar way to
252 the platform device drivers. Below is an example where we add ACPI support
253 to at25 SPI eeprom driver (this is meant for the above ACPI snippet)::
254
255 static const struct acpi_device_id at25_acpi_match[] = {
256 { "AT25", 0 },
257 { }
258 };
259 MODULE_DEVICE_TABLE(acpi, at25_acpi_match);
260
261 static struct spi_driver at25_driver = {
262 .driver = {
263 ...
264 .acpi_match_table = at25_acpi_match,
265 },
266 };
267
268 Note that this driver actually needs more information like page size of the
269 eeprom, etc. This information can be passed via _DSD method like::
270
271 Device (EEP0)
272 {
273 ...
274 Name (_DSD, Package ()
275 {
276 ToUUID("daffd814-6eba-4d8c-8a91-bc9bbf4aa301"),
277 Package ()
278 {
279 Package () { "size", 1024 },
280 Package () { "pagesize", 32 },
281 Package () { "address-width", 16 },
282 }
283 })
284 }
285
286 Then the at25 SPI driver can get this configuration by calling device property
287 APIs during ->probe() phase like::
288
289 err = device_property_read_u32(dev, "size", &size);
290 if (err)
291 ...error handling...
292
293 err = device_property_read_u32(dev, "pagesize", &page_size);
294 if (err)
295 ...error handling...
296
297 err = device_property_read_u32(dev, "address-width", &addr_width);
298 if (err)
299 ...error handling...
300
301 I2C serial bus support
302 ======================
303
304 The slaves behind I2C bus controller only need to add the ACPI IDs like
305 with the platform and SPI drivers. The I2C core automatically enumerates
306 any slave devices behind the controller device once the adapter is
307 registered.
308
309 Below is an example of how to add ACPI support to the existing mpu3050
310 input driver::
311
312 static const struct acpi_device_id mpu3050_acpi_match[] = {
313 { "MPU3050", 0 },
314 { }
315 };
316 MODULE_DEVICE_TABLE(acpi, mpu3050_acpi_match);
317
318 static struct i2c_driver mpu3050_i2c_driver = {
319 .driver = {
320 .name = "mpu3050",
321 .pm = &mpu3050_pm,
322 .of_match_table = mpu3050_of_match,
323 .acpi_match_table = mpu3050_acpi_match,
324 },
325 .probe = mpu3050_probe,
326 .remove = mpu3050_remove,
327 .id_table = mpu3050_ids,
328 };
329 module_i2c_driver(mpu3050_i2c_driver);
330
331 Reference to PWM device
332 =======================
333
334 Sometimes a device can be a consumer of PWM channel. Obviously OS would like
335 to know which one. To provide this mapping the special property has been
336 introduced, i.e.::
337
338 Device (DEV)
339 {
340 Name (_DSD, Package ()
341 {
342 ToUUID("daffd814-6eba-4d8c-8a91-bc9bbf4aa301"),
343 Package () {
344 Package () { "compatible", Package () { "pwm-leds" } },
345 Package () { "label", "alarm-led" },
346 Package () { "pwms",
347 Package () {
348 "\\_SB.PCI0.PWM", // <PWM device reference>
349 0, // <PWM index>
350 600000000, // <PWM period>
351 0, // <PWM flags>
352 }
353 }
354 }
355 })
356 ...
357 }
358
359 In the above example the PWM-based LED driver references to the PWM channel 0
360 of \_SB.PCI0.PWM device with initial period setting equal to 600 ms (note that
361 value is given in nanoseconds).
362
363 GPIO support
364 ============
365
366 ACPI 5 introduced two new resources to describe GPIO connections: GpioIo
367 and GpioInt. These resources can be used to pass GPIO numbers used by
368 the device to the driver. ACPI 5.1 extended this with _DSD (Device
369 Specific Data) which made it possible to name the GPIOs among other things.
370
371 For example::
372
373 Device (DEV)
374 {
375 Method (_CRS, 0, NotSerialized)
376 {
377 Name (SBUF, ResourceTemplate()
378 {
379 // Used to power on/off the device
380 GpioIo (Exclusive, PullNone, 0, 0, IoRestrictionOutputOnly,
381 "\\_SB.PCI0.GPI0", 0, ResourceConsumer) { 85 }
382
383 // Interrupt for the device
384 GpioInt (Edge, ActiveHigh, ExclusiveAndWake, PullNone, 0,
385 "\\_SB.PCI0.GPI0", 0, ResourceConsumer) { 88 }
386 }
387
388 Return (SBUF)
389 }
390
391 // ACPI 5.1 _DSD used for naming the GPIOs
392 Name (_DSD, Package ()
393 {
394 ToUUID("daffd814-6eba-4d8c-8a91-bc9bbf4aa301"),
395 Package ()
396 {
397 Package () { "power-gpios", Package () { ^DEV, 0, 0, 0 } },
398 Package () { "irq-gpios", Package () { ^DEV, 1, 0, 0 } },
399 }
400 })
401 ...
402 }
403
404 These GPIO numbers are controller relative and path "\\_SB.PCI0.GPI0"
405 specifies the path to the controller. In order to use these GPIOs in Linux
406 we need to translate them to the corresponding Linux GPIO descriptors.
407
408 There is a standard GPIO API for that and it is documented in
409 Documentation/admin-guide/gpio/.
410
411 In the above example we can get the corresponding two GPIO descriptors with
412 a code like this::
413
414 #include <linux/gpio/consumer.h>
415 ...
416
417 struct gpio_desc *irq_desc, *power_desc;
418
419 irq_desc = gpiod_get(dev, "irq");
420 if (IS_ERR(irq_desc))
421 /* handle error */
422
423 power_desc = gpiod_get(dev, "power");
424 if (IS_ERR(power_desc))
425 /* handle error */
426
427 /* Now we can use the GPIO descriptors */
428
429 There are also devm_* versions of these functions which release the
430 descriptors once the device is released.
431
432 See Documentation/firmware-guide/acpi/gpio-properties.rst for more information
433 about the _DSD binding related to GPIOs.
434
435 RS-485 support
436 ==============
437
438 ACPI _DSD (Device Specific Data) can be used to describe RS-485 capability
439 of UART.
440
441 For example::
442
443 Device (DEV)
444 {
445 ...
446
447 // ACPI 5.1 _DSD used for RS-485 capabilities
448 Name (_DSD, Package ()
449 {
450 ToUUID("daffd814-6eba-4d8c-8a91-bc9bbf4aa301"),
451 Package ()
452 {
453 Package () {"rs485-rts-active-low", Zero},
454 Package () {"rs485-rx-active-high", Zero},
455 Package () {"rs485-rx-during-tx", Zero},
456 }
457 })
458 ...
459
460 MFD devices
461 ===========
462
463 The MFD devices register their children as platform devices. For the child
464 devices there needs to be an ACPI handle that they can use to reference
465 parts of the ACPI namespace that relate to them. In the Linux MFD subsystem
466 we provide two ways:
467
468 - The children share the parent ACPI handle.
469 - The MFD cell can specify the ACPI id of the device.
470
471 For the first case, the MFD drivers do not need to do anything. The
472 resulting child platform device will have its ACPI_COMPANION() set to point
473 to the parent device.
474
475 If the ACPI namespace has a device that we can match using an ACPI id or ACPI
476 adr, the cell should be set like::
477
478 static struct mfd_cell_acpi_match my_subdevice_cell_acpi_match = {
479 .pnpid = "XYZ0001",
480 .adr = 0,
481 };
482
483 static struct mfd_cell my_subdevice_cell = {
484 .name = "my_subdevice",
485 /* set the resources relative to the parent */
486 .acpi_match = &my_subdevice_cell_acpi_match,
487 };
488
489 The ACPI id "XYZ0001" is then used to lookup an ACPI device directly under
490 the MFD device and if found, that ACPI companion device is bound to the
491 resulting child platform device.
492
493 Device Tree namespace link device ID
494 ====================================
495
496 The Device Tree protocol uses device identification based on the "compatible"
497 property whose value is a string or an array of strings recognized as device
498 identifiers by drivers and the driver core. The set of all those strings may be
499 regarded as a device identification namespace analogous to the ACPI/PNP device
500 ID namespace. Consequently, in principle it should not be necessary to allocate
501 a new (and arguably redundant) ACPI/PNP device ID for a devices with an existing
502 identification string in the Device Tree (DT) namespace, especially if that ID
503 is only needed to indicate that a given device is compatible with another one,
504 presumably having a matching driver in the kernel already.
505
506 In ACPI, the device identification object called _CID (Compatible ID) is used to
507 list the IDs of devices the given one is compatible with, but those IDs must
508 belong to one of the namespaces prescribed by the ACPI specification (see
509 Section 6.1.2 of ACPI 6.0 for details) and the DT namespace is not one of them.
510 Moreover, the specification mandates that either a _HID or an _ADR identification
511 object be present for all ACPI objects representing devices (Section 6.1 of ACPI
512 6.0). For non-enumerable bus types that object must be _HID and its value must
513 be a device ID from one of the namespaces prescribed by the specification too.
514
515 The special DT namespace link device ID, PRP0001, provides a means to use the
516 existing DT-compatible device identification in ACPI and to satisfy the above
517 requirements following from the ACPI specification at the same time. Namely,
518 if PRP0001 is returned by _HID, the ACPI subsystem will look for the
519 "compatible" property in the device object's _DSD and will use the value of that
520 property to identify the corresponding device in analogy with the original DT
521 device identification algorithm. If the "compatible" property is not present
522 or its value is not valid, the device will not be enumerated by the ACPI
523 subsystem. Otherwise, it will be enumerated automatically as a platform device
524 (except when an I2C or SPI link from the device to its parent is present, in
525 which case the ACPI core will leave the device enumeration to the parent's
526 driver) and the identification strings from the "compatible" property value will
527 be used to find a driver for the device along with the device IDs listed by _CID
528 (if present).
529
530 Analogously, if PRP0001 is present in the list of device IDs returned by _CID,
531 the identification strings listed by the "compatible" property value (if present
532 and valid) will be used to look for a driver matching the device, but in that
533 case their relative priority with respect to the other device IDs listed by
534 _HID and _CID depends on the position of PRP0001 in the _CID return package.
535 Specifically, the device IDs returned by _HID and preceding PRP0001 in the _CID
536 return package will be checked first. Also in that case the bus type the device
537 will be enumerated to depends on the device ID returned by _HID.
538
539 For example, the following ACPI sample might be used to enumerate an lm75-type
540 I2C temperature sensor and match it to the driver using the Device Tree
541 namespace link::
542
543 Device (TMP0)
544 {
545 Name (_HID, "PRP0001")
546 Name (_DSD, Package () {
547 ToUUID("daffd814-6eba-4d8c-8a91-bc9bbf4aa301"),
548 Package () {
549 Package () { "compatible", "ti,tmp75" },
550 }
551 })
552 Method (_CRS, 0, Serialized)
553 {
554 Name (SBUF, ResourceTemplate ()
555 {
556 I2cSerialBusV2 (0x48, ControllerInitiated,
557 400000, AddressingMode7Bit,
558 "\\_SB.PCI0.I2C1", 0x00,
559 ResourceConsumer, , Exclusive,)
560 })
561 Return (SBUF)
562 }
563 }
564
565 It is valid to define device objects with a _HID returning PRP0001 and without
566 the "compatible" property in the _DSD or a _CID as long as one of their
567 ancestors provides a _DSD with a valid "compatible" property. Such device
568 objects are then simply regarded as additional "blocks" providing hierarchical
569 configuration information to the driver of the composite ancestor device.
570
571 However, PRP0001 can only be returned from either _HID or _CID of a device
572 object if all of the properties returned by the _DSD associated with it (either
573 the _DSD of the device object itself or the _DSD of its ancestor in the
574 "composite device" case described above) can be used in the ACPI environment.
575 Otherwise, the _DSD itself is regarded as invalid and therefore the "compatible"
576 property returned by it is meaningless.
577
578 Refer to Documentation/firmware-guide/acpi/DSD-properties-rules.rst for more
579 information.
580
581 PCI hierarchy representation
582 ============================
583
584 Sometimes it could be useful to enumerate a PCI device, knowing its position on
585 the PCI bus.
586
587 For example, some systems use PCI devices soldered directly on the mother board,
588 in a fixed position (ethernet, Wi-Fi, serial ports, etc.). In this conditions it
589 is possible to refer to these PCI devices knowing their position on the PCI bus
590 topology.
591
592 To identify a PCI device, a complete hierarchical description is required, from
593 the chipset root port to the final device, through all the intermediate
594 bridges/switches of the board.
595
596 For example, let's assume we have a system with a PCIe serial port, an
597 Exar XR17V3521, soldered on the main board. This UART chip also includes
598 16 GPIOs and we want to add the property ``gpio-line-names`` [1]_ to these pins.
599 In this case, the ``lspci`` output for this component is::
600
601 07:00.0 Serial controller: Exar Corp. XR17V3521 Dual PCIe UART (rev 03)
602
603 The complete ``lspci`` output (manually reduced in length) is::
604
605 00:00.0 Host bridge: Intel Corp... Host Bridge (rev 0d)
606 ...
607 00:13.0 PCI bridge: Intel Corp... PCI Express Port A #1 (rev fd)
608 00:13.1 PCI bridge: Intel Corp... PCI Express Port A #2 (rev fd)
609 00:13.2 PCI bridge: Intel Corp... PCI Express Port A #3 (rev fd)
610 00:14.0 PCI bridge: Intel Corp... PCI Express Port B #1 (rev fd)
611 00:14.1 PCI bridge: Intel Corp... PCI Express Port B #2 (rev fd)
612 ...
613 05:00.0 PCI bridge: Pericom Semiconductor Device 2404 (rev 05)
614 06:01.0 PCI bridge: Pericom Semiconductor Device 2404 (rev 05)
615 06:02.0 PCI bridge: Pericom Semiconductor Device 2404 (rev 05)
616 06:03.0 PCI bridge: Pericom Semiconductor Device 2404 (rev 05)
617 07:00.0 Serial controller: Exar Corp. XR17V3521 Dual PCIe UART (rev 03) <-- Exar
618 ...
619
620 The bus topology is::
621
622 -[0000:00]-+-00.0
623 ...
624 +-13.0-[01]----00.0
625 +-13.1-[02]----00.0
626 +-13.2-[03]--
627 +-14.0-[04]----00.0
628 +-14.1-[05-09]----00.0-[06-09]--+-01.0-[07]----00.0 <-- Exar
629 | +-02.0-[08]----00.0
630 | \-03.0-[09]--
631 ...
632 \-1f.1
633
634 To describe this Exar device on the PCI bus, we must start from the ACPI name
635 of the chipset bridge (also called "root port") with address::
636
637 Bus: 0 - Device: 14 - Function: 1
638
639 To find this information, it is necessary to disassemble the BIOS ACPI tables,
640 in particular the DSDT (see also [2]_)::
641
642 mkdir ~/tables/
643 cd ~/tables/
644 acpidump > acpidump
645 acpixtract -a acpidump
646 iasl -e ssdt?.* -d dsdt.dat
647
648 Now, in the dsdt.dsl, we have to search the device whose address is related to
649 0x14 (device) and 0x01 (function). In this case we can find the following
650 device::
651
652 Scope (_SB.PCI0)
653 {
654 ... other definitions follow ...
655 Device (RP02)
656 {
657 Method (_ADR, 0, NotSerialized) // _ADR: Address
658 {
659 If ((RPA2 != Zero))
660 {
661 Return (RPA2) /* \RPA2 */
662 }
663 Else
664 {
665 Return (0x00140001)
666 }
667 }
668 ... other definitions follow ...
669
670 and the _ADR method [3]_ returns exactly the device/function couple that
671 we are looking for. With this information and analyzing the above ``lspci``
672 output (both the devices list and the devices tree), we can write the following
673 ACPI description for the Exar PCIe UART, also adding the list of its GPIO line
674 names::
675
676 Scope (_SB.PCI0.RP02)
677 {
678 Device (BRG1) //Bridge
679 {
680 Name (_ADR, 0x0000)
681
682 Device (BRG2) //Bridge
683 {
684 Name (_ADR, 0x00010000)
685
686 Device (EXAR)
687 {
688 Name (_ADR, 0x0000)
689
690 Name (_DSD, Package ()
691 {
692 ToUUID("daffd814-6eba-4d8c-8a91-bc9bbf4aa301"),
693 Package ()
694 {
695 Package ()
696 {
697 "gpio-line-names",
698 Package ()
699 {
700 "mode_232",
701 "mode_422",
702 "mode_485",
703 "misc_1",
704 "misc_2",
705 "misc_3",
706 "",
707 "",
708 "aux_1",
709 "aux_2",
710 "aux_3",
711 }
712 }
713 }
714 })
715 }
716 }
717 }
718 }
719
720 The location "_SB.PCI0.RP02" is obtained by the above investigation in the
721 dsdt.dsl table, whereas the device names "BRG1", "BRG2" and "EXAR" are
722 created analyzing the position of the Exar UART in the PCI bus topology.
723
724 References
725 ==========
726
727 .. [1] Documentation/firmware-guide/acpi/gpio-properties.rst
728
729 .. [2] Documentation/admin-guide/acpi/initrd_table_override.rst
730
731 .. [3] ACPI Specifications, Version 6.3 - Paragraph 6.1.1 _ADR Address)
732 https://uefi.org/sites/default/files/resources/ACPI_6_3_May16.pdf,
733 referenced 2020-11-18
734

3. 한국어 전문 번역

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

열거 모델과 platform bus 지원

1-66

ACPI 5는 serial bus controller 뒤의 slave device를 열거할 수 있도록 `UartTSerialBus`, `I2cSerialBus`, `SpiSerialBus`, `GpioIo`, `GpioInt` resource를 도입했다. 이와 함께 SoC나 chipset에 통합되어 memory-mapped register로 접근하는 peripheral이 ACPI namespace에만 나타나는 사례도 늘고 있다.

Linux는 기존 driver를 최대한 재사용하기 위해 firmware가 설명한 device를 실제 연결 형태에 맞는 kernel device로 구체화한다. Bus connector resource가 없으면 platform device로 표현하고, 실제 bus와 connector resource가 있으면 SPI의 `struct spi_device` 또는 I2C의 `struct i2c_client`로 표현한다.

표준 UART는 bus가 아니므로 `struct uart_device`는 없다. 다만 일부 UART 연결 장치는 `struct serdev_device`로 나타낼 수 있다. ACPI와 Device Tree가 모두 device와 resource의 트리를 기술하므로, ACPI 구현도 가능한 한 Device Tree 방식과 같은 수명주기를 따른다.

ACPI 구현은 platform, SPI, I2C, 일부 UART bus 뒤의 device를 열거하고 physical device object를 생성한 다음 ACPI namespace의 handle과 결합한다. 따라서 `ACPI_HANDLE(dev)`가 `non-NULL`이면 그 device는 ACPI namespace에서 열거된 것이며, 반환된 handle로 추가 device-specific configuration을 얻을 수 있다.

ACPI resource와 Linux device 표현
Firmware 기술Linux 표현열거 시점
Bus connector resource 없음platform deviceACPI core 열거
SpiSerialBusstruct spi_deviceSPI master 등록 뒤
I2cSerialBusstruct i2c_clientI2C adapter 등록 뒤
표준 UARTstruct uart_device 없음일부는 struct serdev_device
GpioIo·GpioIntGPIO descriptor·IRQ resourceconsumer driver에서 변환

Connector resource의 존재와 bus 성격이 생성할 kernel object를 결정한다.

ACPI device 열거 흐름
ACPI namespace와 _CRS resource 해석Connector resource와 bus 유형 판별platform·SPI·I2C·serdev device 생성생성 device에 ACPI handle 결합ACPI ID match로 driver probeACPI_HANDLE(dev)로 추가 설정 조회

Namespace object가 driver에 결합되는 physical device가 되기까지의 순서다.

물리 bus에 연결되지 않은 device는 platform device로 표현되므로 driver는 platform driver를 구현하고 지원하는 ACPI ID를 추가하면 된다. 같은 IP block이 비-ACPI platform에서도 쓰인다면 기존 driver가 그대로 동작하거나 작은 수정만 필요할 수 있다.

가장 단순한 지원 방식은 `struct acpi_device_id` 배열을 선언하고 `MODULE_DEVICE_TABLE(acpi, mydrv_acpi_match)`로 module alias를 내보낸 뒤, `struct platform_driver`의 `.driver.acpi_match_table`에 그 배열을 지정하는 것이다. GPIO 획득과 설정처럼 초기화가 복잡한 경우에는 ACPI handle을 얻어 ACPI table에서 필요한 정보를 추출한다.

기존 platform driver의 ACPI 지원
단계구현 요소목적
ID 선언struct acpi_device_id지원 ACPI ID 목록
Module tableMODULE_DEVICE_TABLE(acpi, ...)자동 module loading
Driver 결합.acpi_match_tableACPI ID 기반 probe
추가 설정ACPI handle·device property APIGPIO 등 device-specific data

Match table을 추가하는 최소 변경과 probe 단계의 확장 지점을 구분한다.

.. SPDX-License-Identifier: GPL-2.0

=============================
ACPI Based Device Enumeration
=============================

ACPI 5 introduced a set of new resources (UartTSerialBus, I2cSerialBus,
SpiSerialBus, GpioIo and GpioInt) which can be used in enumerating slave
devices behind serial bus controllers.

In addition we are starting to see peripherals integrated in the
SoC/Chipset to appear only in ACPI namespace. These are typically devices
that are accessed through memory-mapped registers.

In order to support this and re-use the existing drivers as much as
possible we decided to do following:

  - Devices that have no bus connector resource are represented as
    platform devices.

  - Devices behind real busses where there is a connector resource
    are represented as struct spi_device or struct i2c_client. Note
    that standard UARTs are not busses so there is no struct uart_device,
    although some of them may be represented by struct serdev_device.

As both ACPI and Device Tree represent a tree of devices (and their
resources) this implementation follows the Device Tree way as much as
possible.

The ACPI implementation enumerates devices behind busses (platform, SPI,
I2C, and in some cases UART), creates the physical devices and binds them
to their ACPI handle in the ACPI namespace.

This means that when ACPI_HANDLE(dev) returns non-NULL the device was
enumerated from ACPI namespace. This handle can be used to extract other
device-specific configuration. There is an example of this below.

Platform bus support
====================

Since we are using platform devices to represent devices that are not
connected to any physical bus we only need to implement a platform driver
for the device and add supported ACPI IDs. If this same IP-block is used on
some other non-ACPI platform, the driver might work out of the box or needs
some minor changes.

Adding ACPI support for an existing driver should be pretty
straightforward. Here is the simplest example::

        static const struct acpi_device_id mydrv_acpi_match[] = {
                /* ACPI IDs here */
                { }
        };
        MODULE_DEVICE_TABLE(acpi, mydrv_acpi_match);

        static struct platform_driver my_driver = {
                ...
                .driver = {
                        .acpi_match_table = mydrv_acpi_match,
                },
        };

If the driver needs to perform more complex initialization like getting and
configuring GPIOs it can get its ACPI handle and extract this information
from ACPI tables.

ACPI device object와 실제 driver 결합 대상

67-109

ACPI가 platform firmware와 OS 사이의 interface인 system에서 device는 크게 두 범주로 나뉜다. PCI configuration space처럼 해당 bus protocol만으로 OS가 native하게 발견하고 열거할 수 있는 device가 있고, 발견하려면 platform firmware의 설명이 필요한 device가 있다.

어느 범주에 속하든 platform firmware가 알고 있는 device에는 ACPI Namespace의 대응 ACPI device object가 있을 수 있다. Linux kernel은 이 object를 바탕으로 해당 device의 `struct acpi_device`를 만든다. 그러나 `struct acpi_device`가 존재한다는 사실과 driver가 그 object에 직접 bind해야 한다는 것은 전혀 같은 의미가 아니다.

Native하게 발견 가능한 device의 driver는 `struct acpi_device`에 bind하지 않는다. 예를 들어 PCI device는 `struct pci_dev`로 표현되고 PCI driver가 여기에 bind한다. 대응 `struct acpi_device`는 device configuration에 관한 추가 정보원으로만 사용한다.

Firmware의 도움으로 열거되는 device도 대부분 ACPI core가 `struct platform_device`를 생성한다. 이 경우에도 platform driver가 실제 device object에 bind하는 것이 native 열거 device와 일관된 모델이다. 그러므로 예외를 제외하면 `struct acpi_device` 자체에 driver를 bind하는 것은 논리적으로 일관되지 않고 일반적으로 유효하지 않다.

과거에는 firmware 도움으로 열거한 일부 device에 대해 `struct acpi_device`에 직접 bind하는 ACPI driver가 구현되었다. 하지만 새 driver에는 이 방식을 권장하지 않는다. 일반적으로 생성되는 platform device를 platform driver로 처리하고, 필요한 configuration만 대응 ACPI device object에서 읽어야 한다.

Device object의 역할 분리
Device 유형Driver가 bind하는 objectstruct acpi_device 역할
PCI처럼 native 열거struct pci_dev추가 firmware configuration
Firmware 설명 기반struct platform_device유일하거나 추가적인 configuration
역사적 직접 ACPI driverstruct acpi_device새 driver에는 비권장

Driver binding 대상과 ACPI configuration interface를 혼동하지 않아야 한다.

대응 `struct acpi_device`가 있는 모든 device에서는 `ACPI_COMPANION()` macro가 그 pointer를 반환한다. 따라서 driver는 자신이 bind한 `struct pci_dev`, `struct platform_device` 같은 실제 device object를 유지하면서도 ACPI companion을 통해 namespace의 configuration information에 도달할 수 있다.

정리하면 `struct acpi_device`는 kernel과 ACPI Namespace 사이의 interface 일부이고, `struct pci_dev`나 `struct platform_device`는 나머지 system과 상호 작용하는 실제 device object다. 이 경계가 driver model의 핵심이다.

Driver와 ACPI companion 관계
Bus 또는 ACPI core가 실제 device object 생성PCI·platform driver가 실제 object에 bindACPI_COMPANION(dev) 호출대응 struct acpi_device 획득ACPI Namespace configuration 조회

실제 device binding을 유지하면서 firmware 정보를 가져오는 경로다.

ACPI device objects
===================

Generally speaking, there are two categories of devices in a system in which
ACPI is used as an interface between the platform firmware and the OS: Devices
that can be discovered and enumerated natively, through a protocol defined for
the specific bus that they are on (for example, configuration space in PCI),
without the platform firmware assistance, and devices that need to be described
by the platform firmware so that they can be discovered.  Still, for any device
known to the platform firmware, regardless of which category it falls into,
there can be a corresponding ACPI device object in the ACPI Namespace in which
case the Linux kernel will create a struct acpi_device object based on it for
that device.

Those struct acpi_device objects are never used for binding drivers to natively
discoverable devices, because they are represented by other types of device
objects (for example, struct pci_dev for PCI devices) that are bound to by
device drivers (the corresponding struct acpi_device object is then used as
an additional source of information on the configuration of the given device).
Moreover, the core ACPI device enumeration code creates struct platform_device
objects for the majority of devices that are discovered and enumerated with the
help of the platform firmware and those platform device objects can be bound to
by platform drivers in direct analogy with the natively enumerable devices
case.  Therefore it is logically inconsistent and so generally invalid to bind
drivers to struct acpi_device objects, including drivers for devices that are
discovered with the help of the platform firmware.

Historically, ACPI drivers that bound directly to struct acpi_device objects
were implemented for some devices enumerated with the help of the platform
firmware, but this is not recommended for any new drivers.  As explained above,
platform device objects are created for those devices as a rule (with a few
exceptions that are not relevant here) and so platform drivers should be used
for handling them, even though the corresponding ACPI device objects are the
only source of device configuration information in that case.

For every device having a corresponding struct acpi_device object, the pointer
to it is returned by the ACPI_COMPANION() macro, so it is always possible to
get to the device configuration information stored in the ACPI device object
this way.  Accordingly, struct acpi_device can be regarded as a part of the
interface between the kernel and the ACPI Namespace, whereas device objects of
other types (for example, struct pci_dev or struct platform_device) are used
for interacting with the rest of the system.

DMA controller 등록과 FixedDMA 선택

110-187

ACPI로 열거된 DMA controller는 resource에 대한 generic access를 제공하도록 system에 등록해야 한다. Slave device가 generic API `dma_request_chan()`으로 controller에 접근하게 하려면 controller driver의 probe 마지막에서 `devm_acpi_dma_controller_register(dev, xlate_func, dw)`를 호출한다. `!CONFIG_ACPI`인 경우가 아니라면 반환 오류를 처리해야 한다.

등록할 때 전달하는 `xlate_func`는 `struct acpi_dma_spec`가 제공하는 `FixedDMA` resource를 해당 DMA channel로 변환한다. 보통 `acpi_dma_simple_xlate()`로 충분하지만 controller 고유 선택 규칙이 있으면 custom xlate function을 구현한다.

예제의 `filter_args`는 `filter_func()`에 필요한 정보를 담고, `filter_func(struct dma_chan *chan, void *param)`는 적절한 channel인지 판별한다. `xlate_func(struct acpi_dma_spec *dma_spec, struct acpi_dma *adma)`는 capability mask와 filter argument를 준비한 뒤 `dma_request_channel(cap, filter_func, &args)`를 반환한다.

ACPI를 끈 build에서는 같은 `xlate_func()`가 `NULL`을 반환하는 stub이 된다. 이 조건부 구현은 controller driver가 ACPI build와 비-ACPI build를 함께 지원하게 한다.

ACPI DMA channel 변환
Controller driver probe 완료devm_acpi_dma_controller_register() 호출Client가 dma_request_chan() 요청등록된 controller별 xlate_func() 호출acpi_dma_spec·acpi_dma 정보 해석filter_func()로 적절한 dma_chan 선택

Controller 등록부터 client가 channel을 받기까지의 호출 관계다.

`dma_request_chan()`은 등록된 각 DMA controller에 대해 `xlate_func()`를 호출한다. Xlate function은 `struct acpi_dma_spec`의 request 정보와 `struct acpi_dma`가 제공하는 controller property를 함께 사용해 올바른 channel을 선택해야 한다.

Client가 `dma_request_chan()`에 넘기는 문자열은 특정 `FixedDMA` resource에 대응한다. 기본 mapping에서는 `"tx"`가 `FixedDMA` resource array의 첫 번째 entry이고 `"rx"`가 두 번째 entry다.

I2C0 예제의 `_CRS`에는 request line `0x0018`, channel `0x0004`, `Width32bit`인 첫 `FixedDMA`와 request line `0x0019`, channel `0x0005`인 두 번째 `FixedDMA`가 있다. 따라서 `0x0018`은 `tx`, 다음 `0x0019`는 `rx`다.

I2C0 FixedDMA 기본 mapping
Index이름Request lineChannelWidth
0tx0x00180x0004Width32bit
1rx0x00190x0005Width32bit

Resource array 순서가 dma_request_chan()의 기본 이름을 정한다.

순서 기반 기본 mapping만으로 견고하게 선택할 수 없는 경우에는 client가 `acpi_dma_request_slave_chan_by_index()`를 직접 호출해 원하는 `FixedDMA` resource index를 명시해야 한다.

DMA API 선택
상황API선택 기준
일반 tx·rx 요청dma_request_chan()FixedDMA array 순서
Controller 단순 변환acpi_dma_simple_xlate()표준 ACPI DMA spec
Controller 고유 변환custom xlate_func()spec·controller property
특정 resource 강제acpi_dma_request_slave_chan_by_index()FixedDMA index

일반적인 이름 기반 요청과 index를 직접 고르는 경우를 나눈다.

DMA support
===========

DMA controllers enumerated via ACPI should be registered in the system to
provide generic access to their resources. For example, a driver that would
like to be accessible to slave devices via generic API call
dma_request_chan() must register itself at the end of the probe function like
this::

        err = devm_acpi_dma_controller_register(dev, xlate_func, dw);
        /* Handle the error if it's not a case of !CONFIG_ACPI */

and implement custom xlate function if needed (usually acpi_dma_simple_xlate()
is enough) which converts the FixedDMA resource provided by struct
acpi_dma_spec into the corresponding DMA channel. A piece of code for that case
could look like::

        #ifdef CONFIG_ACPI
        struct filter_args {
                /* Provide necessary information for the filter_func */
                ...
        };

        static bool filter_func(struct dma_chan *chan, void *param)
        {
                /* Choose the proper channel */
                ...
        }

        static struct dma_chan *xlate_func(struct acpi_dma_spec *dma_spec,
                        struct acpi_dma *adma)
        {
                dma_cap_mask_t cap;
                struct filter_args args;

                /* Prepare arguments for filter_func */
                ...
                return dma_request_channel(cap, filter_func, &args);
        }
        #else
        static struct dma_chan *xlate_func(struct acpi_dma_spec *dma_spec,
                        struct acpi_dma *adma)
        {
                return NULL;
        }
        #endif

dma_request_chan() will call xlate_func() for each registered DMA controller.
In the xlate function the proper channel must be chosen based on
information in struct acpi_dma_spec and the properties of the controller
provided by struct acpi_dma.

Clients must call dma_request_chan() with the string parameter that corresponds
to a specific FixedDMA resource. By default "tx" means the first entry of the
FixedDMA resource array, "rx" means the second entry. The table below shows a
layout::

        Device (I2C0)
        {
                ...
                Method (_CRS, 0, NotSerialized)
                {
                        Name (DBUF, ResourceTemplate ()
                        {
                                FixedDMA (0x0018, 0x0004, Width32bit, _Y48)
                                FixedDMA (0x0019, 0x0005, Width32bit, )
                        })
                ...
                }
        }

So, the FixedDMA with request line 0x0018 is "tx" and next one is "rx" in
this example.

In robust cases the client unfortunately needs to call
acpi_dma_request_slave_chan_by_index() directly and therefore choose the
specific FixedDMA resource by its index.

이름이 있는 Interrupt resource

188-225

ACPI로 열거되는 driver는 ACPI table에서 interrupt에 이름을 붙이고, driver에서 그 이름으로 IRQ number를 얻을 수 있다. 이름 목록은 `_DSD`의 `interrupt-names` property에 문자열 배열로 기록한다.

각 문자열은 같은 index의 `Interrupt()` resource entry에 대응한다. DEV0 예제에서 `_CRS`의 `Interrupt(ResourceConsumer, Level, ActiveHigh, Exclusive)`는 `0x20`, `0x24` 두 interrupt를 선언하고, `_DSD`의 `interrupt-names`는 `"default"`, `"alert"` 순서로 선언한다.

Named interrupt index mapping
Indexinterrupt-namesInterrupt() 값
0default0x20
1alert0x24

interrupt-names 배열과 Interrupt() resource의 index가 일대일로 대응한다.

따라서 `default`는 `Interrupt()` resource의 `0x20`, `alert`는 `0x24`에 대응한다. 이 mapping은 오직 `Interrupt()` resource에만 적용되며 `GpioInt()`나 비슷한 resource에는 적용되지 않는다.

Driver는 firmware node와 interrupt name을 인자로 `fwnode_irq_get_byname()`을 호출해 대응 IRQ number를 얻는다. 이름을 쓸 때는 `_DSD` 문자열 순서와 `_CRS`의 `Interrupt()` entry 순서를 함께 검토해야 한다.

이름으로 IRQ 얻기
_CRS의 Interrupt() entry 나열_DSD interrupt-names 문자열 배열 작성동일 index끼리 이름과 interrupt 연결fwnode_irq_get_byname() 호출대응 Linux IRQ number 반환

Firmware의 배열 index를 Linux IRQ number로 바꾸는 흐름이다.

Named Interrupts
================

Drivers enumerated via ACPI can have names to interrupts in the ACPI table
which can be used to get the IRQ number in the driver.

The interrupt name can be listed in _DSD as 'interrupt-names'. The names
should be listed as an array of strings which will map to the Interrupt()
resource in the ACPI table corresponding to its index.

The table below shows an example of its usage::

    Device (DEV0) {
        ...
        Name (_CRS, ResourceTemplate() {
            ...
            Interrupt (ResourceConsumer, Level, ActiveHigh, Exclusive) {
                0x20,
                0x24
            }
        })

        Name (_DSD, Package () {
            ToUUID("daffd814-6eba-4d8c-8a91-bc9bbf4aa301"),
            Package () {
                Package () { "interrupt-names", Package () { "default", "alert" } },
            }
        ...
        })
    }

The interrupt name 'default' will correspond to 0x20 in Interrupt()
resource and 'alert' to 0x24. Note that only the Interrupt() resource
is mapped and not GpioInt() or similar.

The driver can call the function - fwnode_irq_get_byname() with the fwnode
and interrupt name as arguments to get the corresponding IRQ number.

SPI slave 열거와 _DSD property

226-300

SPI bus 뒤의 slave device에는 `SpiSerialBus` resource가 붙는다. SPI core가 이를 자동으로 추출하며, bus driver가 `spi_register_master()`를 호출하면 slave device가 열거된다.

EEP0 예제는 `_ADR`을 `1`로 두고 `_CID` package에 `ATML0025`, `AT25`를 제공한다. `_CRS`의 `SPISerialBus`는 chip select 1, `PolarityLow`, `FourWireMode`, 8-bit, controller initiated, 1 MHz, 낮은 clock polarity, first phase, controller path `\_SB.PCI0.SPI1`을 기술한다.

EEP0 SpiSerialBus 설정
항목
_ADR1
_CIDATML0025, AT25
Chip select1
Wire·wordFourWireMode, 8 bit
Clock1000000, ClockPolarityLow, ClockPhaseFirst
Controller\_SB.PCI0.SPI1

ACPI resource가 SPI slave의 연결 parameter와 controller를 지정한다.

SPI device driver는 platform driver와 같은 방식으로 ACPI ID를 추가하면 된다. at25 예제는 `struct acpi_device_id at25_acpi_match[]`에 `AT25`를 넣고 `MODULE_DEVICE_TABLE(acpi, at25_acpi_match)`를 선언한 뒤 `struct spi_driver`의 `.driver.acpi_match_table`에 연결한다.

EEPROM page size처럼 ID만으로 알 수 없는 설정은 `_DSD`로 전달한다. EEP0의 Device Properties UUID package는 `size=1024`, `pagesize=32`, `address-width=16`을 제공한다.

at25 EEPROM _DSD
Property의미
size1024전체 EEPROM 크기
pagesize32쓰기 page 크기
address-width16주소 폭

Probe에 필요한 EEPROM geometry를 firmware property로 전달한다.

at25 driver는 `->probe()` 단계에서 device property API를 호출해 값을 읽는다. `device_property_read_u32(dev, "size", &size)`, `device_property_read_u32(dev, "pagesize", &page_size)`, `device_property_read_u32(dev, "address-width", &addr_width)` 각각의 오류를 처리해야 한다.

SPI slave의 ACPI 열거
EEP0에 _ADR·_CID·SpiSerialBus 기술Bus driver가 spi_register_master() 호출SPI core가 SpiSerialBus resource 추출struct spi_device 생성AT25 ACPI ID로 at25_driver matchdevice_property_read_u32()로 _DSD 설정 획득

Controller 등록에서 driver가 EEPROM geometry를 얻기까지의 절차다.

SPI serial bus support
======================

Slave devices behind SPI bus have SpiSerialBus resource attached to them.
This is extracted automatically by the SPI core and the slave devices are
enumerated once spi_register_master() is called by the bus driver.

Here is what the ACPI namespace for a SPI slave might look like::

        Device (EEP0)
        {
                Name (_ADR, 1)
                Name (_CID, Package () {
                        "ATML0025",
                        "AT25",
                })
                ...
                Method (_CRS, 0, NotSerialized)
                {
                        SPISerialBus(1, PolarityLow, FourWireMode, 8,
                                ControllerInitiated, 1000000, ClockPolarityLow,
                                ClockPhaseFirst, "\\_SB.PCI0.SPI1",)
                }
                ...

The SPI device drivers only need to add ACPI IDs in a similar way to
the platform device drivers. Below is an example where we add ACPI support
to at25 SPI eeprom driver (this is meant for the above ACPI snippet)::

        static const struct acpi_device_id at25_acpi_match[] = {
                { "AT25", 0 },
                { }
        };
        MODULE_DEVICE_TABLE(acpi, at25_acpi_match);

        static struct spi_driver at25_driver = {
                .driver = {
                        ...
                        .acpi_match_table = at25_acpi_match,
                },
        };

Note that this driver actually needs more information like page size of the
eeprom, etc. This information can be passed via _DSD method like::

        Device (EEP0)
        {
                ...
                Name (_DSD, Package ()
                {
                        ToUUID("daffd814-6eba-4d8c-8a91-bc9bbf4aa301"),
                        Package ()
                        {
                                Package () { "size", 1024 },
                                Package () { "pagesize", 32 },
                                Package () { "address-width", 16 },
                        }
                })
        }

Then the at25 SPI driver can get this configuration by calling device property
APIs during ->probe() phase like::

        err = device_property_read_u32(dev, "size", &size);
        if (err)
                ...error handling...

        err = device_property_read_u32(dev, "pagesize", &page_size);
        if (err)
                ...error handling...

        err = device_property_read_u32(dev, "address-width", &addr_width);
        if (err)
                ...error handling...

I2C slave와 PWM consumer 참조

301-362

I2C controller 뒤의 slave도 platform 및 SPI driver와 마찬가지로 ACPI ID를 추가하면 된다. Adapter가 등록되면 I2C core가 controller 뒤의 모든 slave device를 자동으로 열거한다.

기존 mpu3050 input driver 예제는 `struct acpi_device_id mpu3050_acpi_match[]`에 `MPU3050`을 추가하고 `MODULE_DEVICE_TABLE(acpi, mpu3050_acpi_match)`로 내보낸다. `struct i2c_driver mpu3050_i2c_driver`는 기존 `.of_match_table`과 함께 `.acpi_match_table = mpu3050_acpi_match`를 지정한다.

I2C driver의 `probe`, `remove`, `id_table`은 기존 구성을 유지하며 `module_i2c_driver(mpu3050_i2c_driver)`로 등록한다. 즉 ACPI 지원은 별도 driver model을 만드는 일이 아니라 동일 I2C driver에 firmware match 경로를 추가하는 일이다.

I2C slave 열거
I2C controller driver가 adapter 등록I2C core가 ACPI child와 serial bus resource 탐색I2C slave device 자동 생성MPU3050 ACPI ID matchmpu3050_probe() 실행

I2C adapter 등록이 ACPI slave 생성의 시작점이다.

Device가 PWM channel의 consumer라면 OS가 어느 PWM을 쓸지 알 수 있도록 특별한 `pwms` property를 제공한다. DEV 예제는 Device Properties UUID package에 `compatible="pwm-leds"`, `label="alarm-led"`와 PWM specifier를 넣는다.

`pwms`의 nested package는 순서대로 PWM provider `\_SB.PCI0.PWM`, PWM index `0`, period `600000000`, flags `0`을 담는다. Period 값 단위는 nanosecond이므로 `600000000 ns`는 `600 ms`다.

alarm-led PWM 참조
순서필드
0PWM device reference\_SB.PCI0.PWM
1PWM index0
2PWM period600000000 ns = 600 ms
3PWM flags0

pwms package의 각 cell은 provider와 channel 초기 설정을 나타낸다.

이 mapping에 따라 PWM 기반 LED driver는 `\_SB.PCI0.PWM` device의 channel 0을 참조하고 초기 period를 600 ms로 설정한다. 숫자만 볼 때 단위를 잘못 해석하지 않도록 nanosecond 단위를 보존해야 한다.

I2C serial bus support
======================

The slaves behind I2C bus controller only need to add the ACPI IDs like
with the platform and SPI drivers. The I2C core automatically enumerates
any slave devices behind the controller device once the adapter is
registered.

Below is an example of how to add ACPI support to the existing mpu3050
input driver::

        static const struct acpi_device_id mpu3050_acpi_match[] = {
                { "MPU3050", 0 },
                { }
        };
        MODULE_DEVICE_TABLE(acpi, mpu3050_acpi_match);

        static struct i2c_driver mpu3050_i2c_driver = {
                .driver        = {
                        .name        = "mpu3050",
                        .pm        = &mpu3050_pm,
                        .of_match_table = mpu3050_of_match,
                        .acpi_match_table = mpu3050_acpi_match,
                },
                .probe                = mpu3050_probe,
                .remove                = mpu3050_remove,
                .id_table        = mpu3050_ids,
        };
        module_i2c_driver(mpu3050_i2c_driver);

Reference to PWM device
=======================

Sometimes a device can be a consumer of PWM channel. Obviously OS would like
to know which one. To provide this mapping the special property has been
introduced, i.e.::

    Device (DEV)
    {
        Name (_DSD, Package ()
        {
            ToUUID("daffd814-6eba-4d8c-8a91-bc9bbf4aa301"),
            Package () {
                Package () { "compatible", Package () { "pwm-leds" } },
                Package () { "label", "alarm-led" },
                Package () { "pwms",
                    Package () {
                        "\\_SB.PCI0.PWM",  // <PWM device reference>
                        0,                 // <PWM index>
                        600000000,         // <PWM period>
                        0,                 // <PWM flags>
                    }
                }
            }
        })
        ...
    }

In the above example the PWM-based LED driver references to the PWM channel 0
of \_SB.PCI0.PWM device with initial period setting equal to 600 ms (note that
value is given in nanoseconds).

GPIO descriptor와 RS-485 capability

363-459

ACPI 5는 GPIO connection을 기술하는 `GpioIo`와 `GpioInt` resource를 도입했다. 이 resource로 device가 사용하는 GPIO number를 driver에 전달할 수 있다. ACPI 5.1의 `_DSD`는 여기에 GPIO 이름을 붙이는 기능을 추가했다.

DEV 예제의 `_CRS`는 device 전원을 켜고 끄는 output-only `GpioIo` pin `85`와, edge-triggered active-high wake-capable `GpioInt` pin `88`을 선언한다. 두 resource 모두 controller path `\_SB.PCI0.GPI0`을 사용하므로 pin number는 이 controller에 상대적이다.

`_DSD`의 Device Properties UUID package는 `power-gpios`를 `{ ^DEV, 0, 0, 0 }`, `irq-gpios`를 `{ ^DEV, 1, 0, 0 }`에 연결한다. 여기서 index 0은 `_CRS`의 첫 GPIO resource인 pin 85, index 1은 두 번째 resource인 pin 88을 가리킨다.

DEV GPIO resource mapping
_CRS indexResourceController pin_DSD propertyConsumer 이름
0GpioIo85power-gpiospower
1GpioInt88irq-gpiosirq

_CRS resource 순서와 _DSD 이름이 Linux consumer 이름을 만든다.

Linux에서 controller-relative number를 직접 쓰지 않고 대응 GPIO descriptor로 변환한다. 표준 GPIO consumer API는 `Documentation/admin-guide/gpio/`에 문서화되어 있다.

Driver는 `<linux/gpio/consumer.h>`를 include하고 `gpiod_get(dev, "irq")`로 `irq_desc`, `gpiod_get(dev, "power")`로 `power_desc`를 얻는다. 각 반환값은 `IS_ERR()`로 검사해야 한다. Device가 해제될 때 descriptor도 자동 해제하려면 대응 `devm_*` variant를 사용할 수 있다.

ACPI GPIO를 descriptor로 변환
_CRS에서 GpioIo·GpioInt와 controller path 해석_DSD의 power-gpios·irq-gpios index 연결gpiod_get(dev, consumer_name) 호출Controller-relative pin을 gpio_desc로 변환IS_ERR() 확인 뒤 descriptor 사용devm_* variant면 device 해제 시 자동 정리

Firmware pin number를 Linux consumer API의 안정적인 descriptor로 바꾸는 과정이다.

GPIO `_DSD` binding의 자세한 규칙은 `Documentation/firmware-guide/acpi/gpio-properties.rst`를 참조한다.

UART의 RS-485 capability도 ACPI `_DSD`로 기술할 수 있다. 예제의 Device Properties UUID package는 `rs485-rts-active-low`, `rs485-rx-active-high`, `rs485-rx-during-tx` property를 각각 `Zero`와 함께 선언한다.

RS-485 _DSD capability
Property예제 값표현하는 capability
rs485-rts-active-lowZeroRTS active polarity
rs485-rx-active-highZeroRX active polarity
rs485-rx-during-txZero송신 중 수신 지원

UART driver가 해석할 RS-485 polarity와 동시 송수신 특성이다.

GPIO support
============

ACPI 5 introduced two new resources to describe GPIO connections: GpioIo
and GpioInt. These resources can be used to pass GPIO numbers used by
the device to the driver. ACPI 5.1 extended this with _DSD (Device
Specific Data) which made it possible to name the GPIOs among other things.

For example::

        Device (DEV)
        {
                Method (_CRS, 0, NotSerialized)
                {
                        Name (SBUF, ResourceTemplate()
                        {
                                // Used to power on/off the device
                                GpioIo (Exclusive, PullNone, 0, 0, IoRestrictionOutputOnly,
                                        "\\_SB.PCI0.GPI0", 0, ResourceConsumer) { 85 }

                                // Interrupt for the device
                                GpioInt (Edge, ActiveHigh, ExclusiveAndWake, PullNone, 0,
                                         "\\_SB.PCI0.GPI0", 0, ResourceConsumer) { 88 }
                        }

                        Return (SBUF)
                }

                // ACPI 5.1 _DSD used for naming the GPIOs
                Name (_DSD, Package ()
                {
                        ToUUID("daffd814-6eba-4d8c-8a91-bc9bbf4aa301"),
                        Package ()
                        {
                                Package () { "power-gpios", Package () { ^DEV, 0, 0, 0 } },
                                Package () { "irq-gpios", Package () { ^DEV, 1, 0, 0 } },
                        }
                })
                ...
        }

These GPIO numbers are controller relative and path "\\_SB.PCI0.GPI0"
specifies the path to the controller. In order to use these GPIOs in Linux
we need to translate them to the corresponding Linux GPIO descriptors.

There is a standard GPIO API for that and it is documented in
Documentation/admin-guide/gpio/.

In the above example we can get the corresponding two GPIO descriptors with
a code like this::

        #include <linux/gpio/consumer.h>
        ...

        struct gpio_desc *irq_desc, *power_desc;

        irq_desc = gpiod_get(dev, "irq");
        if (IS_ERR(irq_desc))
                /* handle error */

        power_desc = gpiod_get(dev, "power");
        if (IS_ERR(power_desc))
                /* handle error */

        /* Now we can use the GPIO descriptors */

There are also devm_* versions of these functions which release the
descriptors once the device is released.

See Documentation/firmware-guide/acpi/gpio-properties.rst for more information
about the _DSD binding related to GPIOs.

RS-485 support
==============

ACPI _DSD (Device Specific Data) can be used to describe RS-485 capability
of UART.

For example::

        Device (DEV)
        {
                ...

                // ACPI 5.1 _DSD used for RS-485 capabilities
                Name (_DSD, Package ()
                {
                        ToUUID("daffd814-6eba-4d8c-8a91-bc9bbf4aa301"),
                        Package ()
                        {
                                Package () {"rs485-rts-active-low", Zero},
                                Package () {"rs485-rx-active-high", Zero},
                                Package () {"rs485-rx-during-tx", Zero},
                        }
                })
                ...

MFD child와 PRP0001 namespace link

460-580

MFD device는 child를 platform device로 등록한다. 각 child에는 자신과 관련된 ACPI namespace 부분을 참조할 ACPI handle이 필요하다. Linux MFD subsystem은 child가 parent ACPI handle을 공유하는 방식과, MFD cell이 device의 ACPI ID를 지정하는 두 방식을 제공한다.

첫 방식에서는 MFD driver가 추가 작업을 할 필요가 없다. 생성된 child platform device의 `ACPI_COMPANION()`은 parent device를 가리킨다.

ACPI namespace에 ACPI ID 또는 ACPI address로 match할 수 있는 device가 있다면 cell에 `struct mfd_cell_acpi_match`를 지정한다. 예제는 `.pnpid = "XYZ0001"`, `.adr = 0`을 설정하고, `struct mfd_cell my_subdevice_cell`의 `.acpi_match`가 이를 가리킨다.

MFD subsystem은 `XYZ0001`을 사용해 MFD device 바로 아래의 ACPI device를 찾는다. 찾으면 그 ACPI companion을 생성되는 child platform device에 bind한다. Cell resource는 parent 기준 상대값으로 설정한다.

MFD child의 ACPI companion
방식MFD 설정Child ACPI_COMPANION()
Parent 공유추가 설정 없음Parent ACPI device
Child object matchpnpid=XYZ0001, adr=0직접 찾은 child ACPI device

Namespace 구성에 따라 parent handle 공유 또는 child ID match를 선택한다.

Device Tree protocol은 driver와 driver core가 device identifier로 인식하는 문자열 또는 문자열 배열인 `compatible` property를 사용한다. 이 문자열 집합은 ACPI/PNP device ID namespace와 유사한 DT identification namespace로 볼 수 있다.

이미 DT namespace에 identification string이 있고 kernel driver도 존재한다면, 단지 compatibility를 나타내기 위해 중복 ACPI/PNP ID를 새로 할당하는 것은 원칙적으로 불필요하다. 하지만 ACPI의 `_CID`에 들어갈 ID는 ACPI specification이 정한 namespace에 속해야 하고 DT namespace는 그 목록에 없다.

또한 ACPI 6.0 Section 6.1은 device를 나타내는 모든 ACPI object가 `_HID` 또는 `_ADR` identification object를 가져야 한다고 규정한다. 열거할 수 없는 bus 유형에서는 반드시 `_HID`여야 하며 그 값도 specification이 정한 namespace의 device ID여야 한다.

특별한 DT namespace link device ID `PRP0001`은 기존 DT-compatible identification을 ACPI에서 사용하면서 위 요구도 만족하게 한다.

PRP0001이 _HID인 경우
_HID가 PRP0001 반환ACPI subsystem이 _DSD compatible 검색compatible 문자열·배열 유효성 검사없거나 invalid이면 device를 열거하지 않음유효하면 원칙적으로 platform device 자동 열거I2C·SPI parent link면 parent driver에 열거 위임compatible과 _CID ID로 driver 검색

compatible property의 유효성이 device 열거 여부를 직접 결정한다.

`PRP0001`을 `_HID`가 반환하면 ACPI subsystem은 device object의 `_DSD`에서 `compatible` property를 찾아 DT의 원래 identification algorithm과 같은 방식으로 device를 식별한다. `compatible`이 없거나 값이 유효하지 않으면 ACPI subsystem은 device를 열거하지 않는다.

유효하다면 I2C 또는 SPI link가 parent와 연결된 경우를 제외하고 platform device로 자동 열거한다. I2C/SPI link가 있으면 ACPI core가 parent driver에 열거를 맡긴다. Driver 검색에는 `compatible`의 identification string과 존재한다면 `_CID`가 나열한 ID를 함께 사용한다.

`PRP0001`이 `_CID`의 device ID 목록에 있으면 유효한 `compatible` 문자열도 driver match에 사용한다. 다만 `_HID`와 `_CID`의 다른 ID에 대한 상대 우선순위는 `_CID` return package 안의 `PRP0001` 위치에 따라 달라진다.

구체적으로 `_HID`가 반환한 ID와 `_CID`에서 `PRP0001`보다 앞에 있는 ID를 먼저 검사한다. 이 경우에도 device가 어느 bus type으로 열거되는지는 `_HID`가 반환한 device ID에 따라 정해진다.

PRP0001 위치별 동작
위치compatible 역할열거·우선순위
_HID필수 identificationinvalid이면 미열거, 유효하면 bus 규칙에 따라 열거
_CID추가 compatible ID_HID 및 PRP0001 앞의 _CID ID를 먼저 검사

_HID와 _CID에서의 위치가 열거와 driver match 우선순위를 바꾼다.

TMP0 예제는 `_HID="PRP0001"`과 `_DSD`의 `compatible="ti,tmp75"`를 사용해 lm75 계열 I2C temperature sensor를 식별한다. `_CRS`의 `I2cSerialBusV2`는 address `0x48`, controller initiated, `400000` Hz, `AddressingMode7Bit`, controller `\_SB.PCI0.I2C1`, exclusive connection을 기술한다.

TMP0 DT namespace link
항목
_HIDPRP0001
compatibleti,tmp75
I2C address0x48
Bus speed400000
Address modeAddressingMode7Bit
Controller\_SB.PCI0.I2C1

PRP0001과 I2C serial bus resource가 기존 DT-compatible driver로 이어진다.

어떤 device object가 `_HID=PRP0001`이면서 자체 `_DSD`에 `compatible`이 없고 `_CID`도 없더라도, ancestor가 유효한 `compatible` property를 가진 `_DSD`를 제공하면 유효하다. 이런 child object는 composite ancestor device의 driver에 계층형 configuration을 제공하는 추가 block으로 본다.

단 `PRP0001`은 연관 `_DSD`가 반환하는 모든 property를 ACPI environment에서 사용할 수 있을 때만 device object의 `_HID` 또는 `_CID`에서 반환할 수 있다. Composite device라면 자체 `_DSD`뿐 아니라 ancestor의 `_DSD`도 이 조건에 포함된다. 조건을 만족하지 않으면 `_DSD` 자체가 invalid이고 그 `compatible` property도 의미가 없다.

추가 규칙은 `Documentation/firmware-guide/acpi/DSD-properties-rules.rst`를 참조한다.

MFD devices
===========

The MFD devices register their children as platform devices. For the child
devices there needs to be an ACPI handle that they can use to reference
parts of the ACPI namespace that relate to them. In the Linux MFD subsystem
we provide two ways:

  - The children share the parent ACPI handle.
  - The MFD cell can specify the ACPI id of the device.

For the first case, the MFD drivers do not need to do anything. The
resulting child platform device will have its ACPI_COMPANION() set to point
to the parent device.

If the ACPI namespace has a device that we can match using an ACPI id or ACPI
adr, the cell should be set like::

        static struct mfd_cell_acpi_match my_subdevice_cell_acpi_match = {
                .pnpid = "XYZ0001",
                .adr = 0,
        };

        static struct mfd_cell my_subdevice_cell = {
                .name = "my_subdevice",
                /* set the resources relative to the parent */
                .acpi_match = &my_subdevice_cell_acpi_match,
        };

The ACPI id "XYZ0001" is then used to lookup an ACPI device directly under
the MFD device and if found, that ACPI companion device is bound to the
resulting child platform device.

Device Tree namespace link device ID
====================================

The Device Tree protocol uses device identification based on the "compatible"
property whose value is a string or an array of strings recognized as device
identifiers by drivers and the driver core.  The set of all those strings may be
regarded as a device identification namespace analogous to the ACPI/PNP device
ID namespace.  Consequently, in principle it should not be necessary to allocate
a new (and arguably redundant) ACPI/PNP device ID for a devices with an existing
identification string in the Device Tree (DT) namespace, especially if that ID
is only needed to indicate that a given device is compatible with another one,
presumably having a matching driver in the kernel already.

In ACPI, the device identification object called _CID (Compatible ID) is used to
list the IDs of devices the given one is compatible with, but those IDs must
belong to one of the namespaces prescribed by the ACPI specification (see
Section 6.1.2 of ACPI 6.0 for details) and the DT namespace is not one of them.
Moreover, the specification mandates that either a _HID or an _ADR identification
object be present for all ACPI objects representing devices (Section 6.1 of ACPI
6.0).  For non-enumerable bus types that object must be _HID and its value must
be a device ID from one of the namespaces prescribed by the specification too.

The special DT namespace link device ID, PRP0001, provides a means to use the
existing DT-compatible device identification in ACPI and to satisfy the above
requirements following from the ACPI specification at the same time.  Namely,
if PRP0001 is returned by _HID, the ACPI subsystem will look for the
"compatible" property in the device object's _DSD and will use the value of that
property to identify the corresponding device in analogy with the original DT
device identification algorithm.  If the "compatible" property is not present
or its value is not valid, the device will not be enumerated by the ACPI
subsystem.  Otherwise, it will be enumerated automatically as a platform device
(except when an I2C or SPI link from the device to its parent is present, in
which case the ACPI core will leave the device enumeration to the parent's
driver) and the identification strings from the "compatible" property value will
be used to find a driver for the device along with the device IDs listed by _CID
(if present).

Analogously, if PRP0001 is present in the list of device IDs returned by _CID,
the identification strings listed by the "compatible" property value (if present
and valid) will be used to look for a driver matching the device, but in that
case their relative priority with respect to the other device IDs listed by
_HID and _CID depends on the position of PRP0001 in the _CID return package.
Specifically, the device IDs returned by _HID and preceding PRP0001 in the _CID
return package will be checked first.  Also in that case the bus type the device
will be enumerated to depends on the device ID returned by _HID.

For example, the following ACPI sample might be used to enumerate an lm75-type
I2C temperature sensor and match it to the driver using the Device Tree
namespace link::

        Device (TMP0)
        {
                Name (_HID, "PRP0001")
                Name (_DSD, Package () {
                        ToUUID("daffd814-6eba-4d8c-8a91-bc9bbf4aa301"),
                        Package () {
                                Package () { "compatible", "ti,tmp75" },
                        }
                })
                Method (_CRS, 0, Serialized)
                {
                        Name (SBUF, ResourceTemplate ()
                        {
                                I2cSerialBusV2 (0x48, ControllerInitiated,
                                        400000, AddressingMode7Bit,
                                        "\\_SB.PCI0.I2C1", 0x00,
                                        ResourceConsumer, , Exclusive,)
                        })
                        Return (SBUF)
                }
        }

It is valid to define device objects with a _HID returning PRP0001 and without
the "compatible" property in the _DSD or a _CID as long as one of their
ancestors provides a _DSD with a valid "compatible" property.  Such device
objects are then simply regarded as additional "blocks" providing hierarchical
configuration information to the driver of the composite ancestor device.

However, PRP0001 can only be returned from either _HID or _CID of a device
object if all of the properties returned by the _DSD associated with it (either
the _DSD of the device object itself or the _DSD of its ancestor in the
"composite device" case described above) can be used in the ACPI environment.
Otherwise, the _DSD itself is regarded as invalid and therefore the "compatible"
property returned by it is meaningless.

Refer to Documentation/firmware-guide/acpi/DSD-properties-rules.rst for more
information.

PCI 계층 표현과 Exar UART 예제

581-733

PCI bus상의 고정 위치를 알면 특정 PCI device를 열거하는 데 활용할 수 있다. Ethernet, Wi-Fi, serial port처럼 motherboard에 직접 납땜되어 위치가 고정된 PCI device는 PCI bus topology상의 위치로 참조할 수 있다.

PCI device를 정확히 식별하려면 chipset root port에서 최종 device까지, board의 모든 intermediate bridge와 switch를 통과하는 완전한 계층 설명이 필요하다.

예제 system에는 main board에 납땜된 PCIe serial port Exar XR17V3521이 있다. 이 UART chip은 16 GPIO도 포함하며, 문서는 이 pin들에 `gpio-line-names` [1]_ property를 추가한다. 축약하지 않은 핵심 `lspci` 식별은 `07:00.0 Serial controller: Exar Corp. XR17V3521 Dual PCIe UART (rev 03)`이다.

축약된 전체 `lspci` 목록에서는 bus 0의 여러 Intel PCI Express root port, `05:00.0`의 Pericom bridge, `06:01.0`·`06:02.0`·`06:03.0`의 Pericom bridge, 그리고 최종 `07:00.0` Exar UART를 확인할 수 있다.

Exar까지의 PCI device 목록
PCI 주소장치계층 역할
00:14.1Intel PCI Express Port B #2Chipset root port
05:00.0Pericom Device 2404첫 번째 bridge
06:01.0Pericom Device 2404Exar 방향 두 번째 bridge
06:02.0Pericom Device 2404Bus 08 branch
06:03.0Pericom Device 2404Bus 09 branch
07:00.0Exar XR17V3521 Dual PCIe UART최종 대상

lspci 주소와 계층 역할을 사람이 검토하기 쉬운 표로 정리했다.

Exar PCI 계층 구조
PCI domain 0000, bus 0000:14.1 root port → secondary bus range 05-0905:00.0 bridge → secondary bus range 06-0906:01.0 bridge → bus 07 → 07:00.0 Exar XR17V352106:02.0 sibling bridge → bus 08 → 08:00.006:03.0 sibling bridge → bus 09

원문의 ASCII bus topology를 같은 연결 관계의 구조화 도식으로 다시 그렸다. 06:02.0과 06:03.0은 06 bus에서 갈라지는 sibling branch다.

이 구조를 ACPI에 기술하려면 먼저 주소 `Bus: 0 - Device: 14 - Function: 1`인 chipset bridge, 즉 root port의 ACPI name을 찾아야 한다.

이 정보는 BIOS ACPI table, 특히 DSDT를 disassemble해서 찾는다. 원문 명령은 `mkdir ~/tables/`, `cd ~/tables/`, `acpidump > acpidump`, `acpixtract -a acpidump`, `iasl -e ssdt?.* -d dsdt.dat` 순서다. Table override에 관한 배경은 [2]_를 참조한다.

Root port ACPI name 찾기
lspci tree에서 00:14.1 root port 식별acpidump로 firmware ACPI table 수집acpixtract로 table 분리iasl로 DSDT와 SSDT disassembledsdt.dsl에서 device 0x14·function 0x01 검색_ADR 반환값 0x00140001 확인대응 object _SB.PCI0.RP02 확정

PCI address와 DSDT object를 대조하는 조사 절차다.

`dsdt.dsl`에서 device `0x14`, function `0x01`에 대응하는 object를 찾으면 `Scope (_SB.PCI0)` 아래 `Device (RP02)`가 나온다. `RP02._ADR` method는 `RPA2`가 `Zero`가 아니면 그 값을 반환하고, 그렇지 않으면 `0x00140001`을 반환한다.

`0x00140001`은 찾던 device/function pair와 정확히 일치한다. 이 DSDT 정보와 `lspci`의 device 목록 및 tree를 결합하면 Exar PCIe UART까지의 ACPI hierarchy를 작성할 수 있다.

작성한 hierarchy는 `Scope (_SB.PCI0.RP02)` 아래 `_ADR=0x0000`인 `BRG1`, 그 아래 `_ADR=0x00010000`인 `BRG2`, 다시 그 아래 `_ADR=0x0000`인 `EXAR`로 이어진다. `BRG1`, `BRG2`, `EXAR`라는 이름은 bus topology를 분석해 새로 만든 이름이고, `_SB.PCI0.RP02`는 DSDT 조사에서 얻은 실제 위치다.

PCI topology와 ACPI object 대응
PCI 위치ACPI object_ADR의미
00:14.1_SB.PCI0.RP020x00140001Chipset root port
05:00.0BRG10x0000Bus 05 device 0 function 0
06:01.0BRG20x00010000Bus 06 device 1 function 0
07:00.0EXAR0x0000Bus 07 device 0 function 0

각 bridge의 PCI 위치를 ACPI child와 _ADR 값으로 연결한다.

EXAR object의 `_DSD`는 Device Properties UUID 아래 `gpio-line-names` package를 제공한다. 원문 목록은 `mode_232`, `mode_422`, `mode_485`, `misc_1`, `misc_2`, `misc_3`, 빈 문자열 두 개, `aux_1`, `aux_2`, `aux_3` 순서다. Chip은 16 GPIO를 가지지만 예제 package에 명시된 항목 수와 빈 항목의 위치는 원문 그대로 보존해야 한다.

Exar gpio-line-names
IndexGPIO line name
0mode_232
1mode_422
2mode_485
3misc_1
4misc_2
5misc_3
6(빈 문자열)
7(빈 문자열)
8aux_1
9aux_2
10aux_3

원문 _DSD package의 index와 문자열을 그대로 대응시켰다.

참고 자료 [1]은 `Documentation/firmware-guide/acpi/gpio-properties.rst`, [2]는 `Documentation/admin-guide/acpi/initrd_table_override.rst`다. [3]은 ACPI Specifications Version 6.3의 Paragraph 6.1.1 `_ADR` Address이며, 원문 URL은 `https://uefi.org/sites/default/files/resources/ACPI_6_3_May16.pdf`, 참조일은 2020-11-18이다.

PCI hierarchy 참고 자료
번호자료용도
[1]Documentation/firmware-guide/acpi/gpio-properties.rstgpio-line-names property
[2]Documentation/admin-guide/acpi/initrd_table_override.rstACPI table override
[3]ACPI 6.3 Paragraph 6.1.1 _ADRPCI device/function address 표현

원문의 reference 번호, source path와 규격 위치를 보존했다.

PCI hierarchy representation
============================

Sometimes it could be useful to enumerate a PCI device, knowing its position on
the PCI bus.

For example, some systems use PCI devices soldered directly on the mother board,
in a fixed position (ethernet, Wi-Fi, serial ports, etc.). In this conditions it
is possible to refer to these PCI devices knowing their position on the PCI bus
topology.

To identify a PCI device, a complete hierarchical description is required, from
the chipset root port to the final device, through all the intermediate
bridges/switches of the board.

For example, let's assume we have a system with a PCIe serial port, an
Exar XR17V3521, soldered on the main board. This UART chip also includes
16 GPIOs and we want to add the property ``gpio-line-names`` [1]_ to these pins.
In this case, the ``lspci`` output for this component is::

        07:00.0 Serial controller: Exar Corp. XR17V3521 Dual PCIe UART (rev 03)

The complete ``lspci`` output (manually reduced in length) is::

        00:00.0 Host bridge: Intel Corp... Host Bridge (rev 0d)
        ...
        00:13.0 PCI bridge: Intel Corp... PCI Express Port A #1 (rev fd)
        00:13.1 PCI bridge: Intel Corp... PCI Express Port A #2 (rev fd)
        00:13.2 PCI bridge: Intel Corp... PCI Express Port A #3 (rev fd)
        00:14.0 PCI bridge: Intel Corp... PCI Express Port B #1 (rev fd)
        00:14.1 PCI bridge: Intel Corp... PCI Express Port B #2 (rev fd)
        ...
        05:00.0 PCI bridge: Pericom Semiconductor Device 2404 (rev 05)
        06:01.0 PCI bridge: Pericom Semiconductor Device 2404 (rev 05)
        06:02.0 PCI bridge: Pericom Semiconductor Device 2404 (rev 05)
        06:03.0 PCI bridge: Pericom Semiconductor Device 2404 (rev 05)
        07:00.0 Serial controller: Exar Corp. XR17V3521 Dual PCIe UART (rev 03) <-- Exar
        ...

The bus topology is::

        -[0000:00]-+-00.0
                   ...
                   +-13.0-[01]----00.0
                   +-13.1-[02]----00.0
                   +-13.2-[03]--
                   +-14.0-[04]----00.0
                   +-14.1-[05-09]----00.0-[06-09]--+-01.0-[07]----00.0 <-- Exar
                   |                               +-02.0-[08]----00.0
                   |                               \-03.0-[09]--
                   ...
                   \-1f.1

To describe this Exar device on the PCI bus, we must start from the ACPI name
of the chipset bridge (also called "root port") with address::

        Bus: 0 - Device: 14 - Function: 1

To find this information, it is necessary to disassemble the BIOS ACPI tables,
in particular the DSDT (see also [2]_)::

        mkdir ~/tables/
        cd ~/tables/
        acpidump > acpidump
        acpixtract -a acpidump
        iasl -e ssdt?.* -d dsdt.dat

Now, in the dsdt.dsl, we have to search the device whose address is related to
0x14 (device) and 0x01 (function). In this case we can find the following
device::

        Scope (_SB.PCI0)
        {
        ... other definitions follow ...
                Device (RP02)
                {
                        Method (_ADR, 0, NotSerialized)  // _ADR: Address
                        {
                                If ((RPA2 != Zero))
                                {
                                        Return (RPA2) /* \RPA2 */
                                }
                                Else
                                {
                                        Return (0x00140001)
                                }
                        }
        ... other definitions follow ...

and the _ADR method [3]_ returns exactly the device/function couple that
we are looking for. With this information and analyzing the above ``lspci``
output (both the devices list and the devices tree), we can write the following
ACPI description for the Exar PCIe UART, also adding the list of its GPIO line
names::

        Scope (_SB.PCI0.RP02)
        {
                Device (BRG1) //Bridge
                {
                        Name (_ADR, 0x0000)

                        Device (BRG2) //Bridge
                        {
                                Name (_ADR, 0x00010000)

                                Device (EXAR)
                                {
                                        Name (_ADR, 0x0000)

                                        Name (_DSD, Package ()
                                        {
                                                ToUUID("daffd814-6eba-4d8c-8a91-bc9bbf4aa301"),
                                                Package ()
                                                {
                                                        Package ()
                                                        {
                                                                "gpio-line-names",
                                                                Package ()
                                                                {
                                                                        "mode_232",
                                                                        "mode_422",
                                                                        "mode_485",
                                                                        "misc_1",
                                                                        "misc_2",
                                                                        "misc_3",
                                                                        "",
                                                                        "",
                                                                        "aux_1",
                                                                        "aux_2",
                                                                        "aux_3",
                                                                }
                                                        }
                                                }
                                        })
                                }
                        }
                }
        }

The location "_SB.PCI0.RP02" is obtained by the above investigation in the
dsdt.dsl table, whereas the device names "BRG1", "BRG2" and "EXAR" are
created analyzing the position of the Exar UART in the PCI bus topology.

References
==========

.. [1] Documentation/firmware-guide/acpi/gpio-properties.rst

.. [2] Documentation/admin-guide/acpi/initrd_table_override.rst

.. [3] ACPI Specifications, Version 6.3 - Paragraph 6.1.1 _ADR Address)
    https://uefi.org/sites/default/files/resources/ACPI_6_3_May16.pdf,
    referenced 2020-11-18