← Documents Documentation/i2c/instantiating-devices.rst GitHub 원문 ↗

Linux 6.18.37 · I2C

How to instantiate I2C devices

열거되지 않는 I2C 장치를 정적 선언, 명시적 생성, 제한된 probe, 사용자 공간 sysfs로 생성하는 방법을 설명합니다.

Source pathDocumentation/i2c/instantiating-devices.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

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

1. 요약·해설

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

요약·해설

instantiating-devices.rst:1-272

I2C 장치는 하드웨어가 열거하지 않으므로 소프트웨어가 버스와 주소를 알려야 합니다. 가능하면 Device Tree·ACPI·board file 또는 소유 드라이버가 명시적으로 생성하고, 자동 probe와 사용자 공간 sysfs는 필요한 경우에 한정합니다.

문서 개요
항목
SourceDocumentation/i2c/instantiating-devices.rst
분량272 source lines
생성 방법4
sysfs 속성new_device, delete_device

원문 분량과 핵심 검토 대상을 요약합니다.

핵심 흐름
버스 번호·장치 주소의 확실성 평가정적 또는 명시적 생성 우선불가피할 때 제한된 probe예외 상황에서 sysfs 사용소유 주체가 장치 정리

문서의 주요 생성·구성 순서를 압축합니다.

2. 영어 원문 전체

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

원문 전체 펼치기
1 ==============================
2 How to instantiate I2C devices
3 ==============================
4
5 Unlike PCI or USB devices, I2C devices are not enumerated at the hardware
6 level. Instead, the software must know which devices are connected on each
7 I2C bus segment, and what address these devices are using. For this
8 reason, the kernel code must instantiate I2C devices explicitly. There are
9 several ways to achieve this, depending on the context and requirements.
10
11
12 Method 1: Declare the I2C devices statically
13 --------------------------------------------
14
15 This method is appropriate when the I2C bus is a system bus as is the case
16 for many embedded systems. On such systems, each I2C bus has a number which
17 is known in advance. It is thus possible to pre-declare the I2C devices
18 which live on this bus.
19
20 This information is provided to the kernel in a different way on different
21 architectures: device tree, ACPI or board files.
22
23 When the I2C bus in question is registered, the I2C devices will be
24 instantiated automatically by i2c-core. The devices will be automatically
25 unbound and destroyed when the I2C bus they sit on goes away (if ever).
26
27
28 Declare the I2C devices via devicetree
29 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
30
31 On platforms using devicetree, the declaration of I2C devices is done in
32 subnodes of the master controller.
33
34 Example:
35
36 .. code-block:: dts
37
38 i2c1: i2c@400a0000 {
39 /* ... master properties skipped ... */
40 clock-frequency = <100000>;
41
42 flash@50 {
43 compatible = "atmel,24c256";
44 reg = <0x50>;
45 };
46
47 pca9532: gpio@60 {
48 compatible = "nxp,pca9532";
49 gpio-controller;
50 #gpio-cells = <2>;
51 reg = <0x60>;
52 };
53 };
54
55 Here, two devices are attached to the bus using a speed of 100kHz. For
56 additional properties which might be needed to set up the device, please refer
57 to its devicetree documentation in Documentation/devicetree/bindings/.
58
59
60 Declare the I2C devices via ACPI
61 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
62
63 ACPI can also describe I2C devices. There is special documentation for this
64 which is currently located at Documentation/firmware-guide/acpi/enumeration.rst.
65
66
67 Declare the I2C devices in board files
68 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
69
70 In many embedded architectures, devicetree has replaced the old hardware
71 description based on board files, but the latter are still used in old
72 code. Instantiating I2C devices via board files is done with an array of
73 struct i2c_board_info which is registered by calling
74 i2c_register_board_info().
75
76 Example (from omap2 h4):
77
78 .. code-block:: c
79
80 static struct i2c_board_info h4_i2c_board_info[] __initdata = {
81 {
82 I2C_BOARD_INFO("isp1301_omap", 0x2d),
83 .irq = OMAP_GPIO_IRQ(125),
84 },
85 { /* EEPROM on mainboard */
86 I2C_BOARD_INFO("24c01", 0x52),
87 .platform_data = &m24c01,
88 },
89 { /* EEPROM on cpu card */
90 I2C_BOARD_INFO("24c01", 0x57),
91 .platform_data = &m24c01,
92 },
93 };
94
95 static void __init omap_h4_init(void)
96 {
97 (...)
98 i2c_register_board_info(1, h4_i2c_board_info,
99 ARRAY_SIZE(h4_i2c_board_info));
100 (...)
101 }
102
103 The above code declares 3 devices on I2C bus 1, including their respective
104 addresses and custom data needed by their drivers.
105
106
107 Method 2: Instantiate the devices explicitly
108 --------------------------------------------
109
110 This method is appropriate when a larger device uses an I2C bus for
111 internal communication. A typical case is TV adapters. These can have a
112 tuner, a video decoder, an audio decoder, etc. usually connected to the
113 main chip by the means of an I2C bus. You won't know the number of the I2C
114 bus in advance, so the method 1 described above can't be used. Instead,
115 you can instantiate your I2C devices explicitly. This is done by filling
116 a struct i2c_board_info and calling i2c_new_client_device().
117
118 Example (from the sfe4001 network driver):
119
120 .. code-block:: c
121
122 static struct i2c_board_info sfe4001_hwmon_info = {
123 I2C_BOARD_INFO("max6647", 0x4e),
124 };
125
126 int sfe4001_init(struct efx_nic *efx)
127 {
128 (...)
129 efx->board_info.hwmon_client =
130 i2c_new_client_device(&efx->i2c_adap, &sfe4001_hwmon_info);
131
132 (...)
133 }
134
135 The above code instantiates 1 I2C device on the I2C bus which is on the
136 network adapter in question.
137
138 A variant of this is when you don't know for sure if an I2C device is
139 present or not (for example for an optional feature which is not present
140 on cheap variants of a board but you have no way to tell them apart), or
141 it may have different addresses from one board to the next (manufacturer
142 changing its design without notice). In this case, you can call
143 i2c_new_scanned_device() instead of i2c_new_client_device().
144
145 Example (from the nxp OHCI driver):
146
147 .. code-block:: c
148
149 static const unsigned short normal_i2c[] = { 0x2c, 0x2d, I2C_CLIENT_END };
150
151 static int usb_hcd_nxp_probe(struct platform_device *pdev)
152 {
153 (...)
154 struct i2c_adapter *i2c_adap;
155 struct i2c_board_info i2c_info;
156
157 (...)
158 i2c_adap = i2c_get_adapter(2);
159 memset(&i2c_info, 0, sizeof(struct i2c_board_info));
160 strscpy(i2c_info.type, "isp1301_nxp", sizeof(i2c_info.type));
161 isp1301_i2c_client = i2c_new_scanned_device(i2c_adap, &i2c_info,
162 normal_i2c, NULL);
163 i2c_put_adapter(i2c_adap);
164 (...)
165 }
166
167 The above code instantiates up to 1 I2C device on the I2C bus which is on
168 the OHCI adapter in question. It first tries at address 0x2c, if nothing
169 is found there it tries address 0x2d, and if still nothing is found, it
170 simply gives up.
171
172 The driver which instantiated the I2C device is responsible for destroying
173 it on cleanup. This is done by calling i2c_unregister_device() on the
174 pointer that was earlier returned by i2c_new_client_device() or
175 i2c_new_scanned_device().
176
177
178 Method 3: Probe an I2C bus for certain devices
179 ----------------------------------------------
180
181 Sometimes you do not have enough information about an I2C device, not even
182 to call i2c_new_scanned_device(). The typical case is hardware monitoring
183 chips on PC mainboards. There are several dozen models, which can live
184 at 25 different addresses. Given the huge number of mainboards out there,
185 it is next to impossible to build an exhaustive list of the hardware
186 monitoring chips being used. Fortunately, most of these chips have
187 manufacturer and device ID registers, so they can be identified by
188 probing.
189
190 In that case, I2C devices are neither declared nor instantiated
191 explicitly. Instead, i2c-core will probe for such devices as soon as their
192 drivers are loaded, and if any is found, an I2C device will be
193 instantiated automatically. In order to prevent any misbehavior of this
194 mechanism, the following restrictions apply:
195
196 * The I2C device driver must implement the detect() method, which
197 identifies a supported device by reading from arbitrary registers.
198 * Only buses which are likely to have a supported device and agree to be
199 probed, will be probed. For example this avoids probing for hardware
200 monitoring chips on a TV adapter.
201
202 Example:
203 See lm90_driver and lm90_detect() in drivers/hwmon/lm90.c
204
205 I2C devices instantiated as a result of such a successful probe will be
206 destroyed automatically when the driver which detected them is removed,
207 or when the underlying I2C bus is itself destroyed, whichever happens
208 first.
209
210 Those of you familiar with the I2C subsystem of 2.4 kernels and early 2.6
211 kernels will find out that this method 3 is essentially similar to what
212 was done there. Two significant differences are:
213
214 * Probing is only one way to instantiate I2C devices now, while it was the
215 only way back then. Where possible, methods 1 and 2 should be preferred.
216 Method 3 should only be used when there is no other way, as it can have
217 undesirable side effects.
218 * I2C buses must now explicitly say which I2C driver classes can probe
219 them (by the means of the class bitfield), while all I2C buses were
220 probed by default back then. The default is an empty class which means
221 that no probing happens. The purpose of the class bitfield is to limit
222 the aforementioned undesirable side effects.
223
224 Once again, method 3 should be avoided wherever possible. Explicit device
225 instantiation (methods 1 and 2) is much preferred for it is safer and
226 faster.
227
228
229 Method 4: Instantiate from user-space
230 -------------------------------------
231
232 In general, the kernel should know which I2C devices are connected and
233 what addresses they live at. However, in certain cases, it does not, so a
234 sysfs interface was added to let the user provide the information. This
235 interface is made of 2 attribute files which are created in every I2C bus
236 directory: ``new_device`` and ``delete_device``. Both files are write
237 only and you must write the right parameters to them in order to properly
238 instantiate, respectively delete, an I2C device.
239
240 File ``new_device`` takes 2 parameters: the name of the I2C device (a
241 string) and the address of the I2C device (a number, typically expressed
242 in hexadecimal starting with 0x, but can also be expressed in decimal.)
243
244 File ``delete_device`` takes a single parameter: the address of the I2C
245 device. As no two devices can live at the same address on a given I2C
246 segment, the address is sufficient to uniquely identify the device to be
247 deleted.
248
249 Example::
250
251 # echo eeprom 0x50 > /sys/bus/i2c/devices/i2c-3/new_device
252
253 While this interface should only be used when in-kernel device declaration
254 can't be done, there is a variety of cases where it can be helpful:
255
256 * The I2C driver usually detects devices (method 3 above) but the bus
257 segment your device lives on doesn't have the proper class bit set and
258 thus detection doesn't trigger.
259 * The I2C driver usually detects devices, but your device lives at an
260 unexpected address.
261 * The I2C driver usually detects devices, but your device is not detected,
262 either because the detection routine is too strict, or because your
263 device is not officially supported yet but you know it is compatible.
264 * You are developing a driver on a test board, where you soldered the I2C
265 device yourself.
266
267 This interface is a replacement for the force_* module parameters some I2C
268 drivers implement. Being implemented in i2c-core rather than in each
269 device driver individually, it is much more efficient, and also has the
270 advantage that you do not have to reload the driver to change a setting.
271 You can also instantiate the device before the driver is loaded or even
272 available, and you don't need to know what driver the device needs.
273

3. 한국어 전문 번역

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

I2C 장치를 명시적으로 생성해야 하는 이유

1-26

PCI나 USB 장치와 달리 I2C 장치는 하드웨어 수준에서 열거되지 않습니다. 소프트웨어가 각 I2C 버스 세그먼트에 어떤 장치가 연결되어 있고 어떤 주소를 사용하는지 알고 있어야 합니다.

따라서 커널 코드는 I2C 장치를 명시적으로 생성해야 합니다. 상황과 요구사항에 따라 여러 방법을 사용할 수 있습니다.

방법 1은 I2C 버스가 시스템 버스인 많은 임베디드 시스템에 적합합니다. 이런 시스템에서는 각 I2C 버스 번호를 미리 알 수 있으므로 그 버스에 존재하는 장치를 사전에 선언할 수 있습니다.

이 정보는 아키텍처에 따라 Device Tree, ACPI, board file로 커널에 전달됩니다. 해당 I2C 버스가 등록되면 i2c-core가 장치를 자동 생성합니다. 장치가 놓인 버스가 사라지면 장치도 자동으로 바인딩 해제되고 제거됩니다.

I2C 장치 생성이 필요한 이유
버스하드웨어 열거장치 정보 제공
PCI·USB지원버스가 장치를 발견
I2C지원하지 않음소프트웨어가 버스 세그먼트와 주소를 명시

열거 방식과 소프트웨어 책임을 비교합니다.

정적 선언 입력
플랫폼선언 방식
Device Tree 플랫폼마스터 컨트롤러의 자식 노드
ACPI 플랫폼ACPI 장치 설명
기존 임베디드 코드`struct i2c_board_info` board file

플랫폼에 따라 장치 정보를 제공하는 방식입니다.

정적 장치 수명 주기
펌웨어·board file에 장치 선언I2C 버스 등록i2c-core가 선언된 장치 자동 생성드라이버 바인딩버스 제거 시 자동 바인딩 해제·장치 제거

버스의 등록과 제거에 장치 수명이 종속됩니다.

==============================
How to instantiate I2C devices
==============================

Unlike PCI or USB devices, I2C devices are not enumerated at the hardware
level. Instead, the software must know which devices are connected on each
I2C bus segment, and what address these devices are using. For this
reason, the kernel code must instantiate I2C devices explicitly. There are
several ways to achieve this, depending on the context and requirements.


Method 1: Declare the I2C devices statically
--------------------------------------------

This method is appropriate when the I2C bus is a system bus as is the case
for many embedded systems. On such systems, each I2C bus has a number which
is known in advance. It is thus possible to pre-declare the I2C devices
which live on this bus.

This information is provided to the kernel in a different way on different
architectures: device tree, ACPI or board files.

When the I2C bus in question is registered, the I2C devices will be
instantiated automatically by i2c-core. The devices will be automatically
unbound and destroyed when the I2C bus they sit on goes away (if ever).

방법 1: Device Tree, ACPI, board file 정적 선언

27-105

Device Tree를 사용하는 플랫폼에서는 I2C 장치를 마스터 컨트롤러의 자식 노드로 선언합니다.

예제의 `i2c1: i2c@400a0000` 컨트롤러는 `clock-frequency = <100000>`으로 100kHz를 사용합니다. 그 아래 주소 `0x50`의 `atmel,24c256` 플래시와 주소 `0x60`의 `nxp,pca9532` GPIO 컨트롤러를 선언합니다.

장치 설정에 필요한 추가 속성은 `Documentation/devicetree/bindings/` 아래의 해당 Device Tree 바인딩 문서를 참조해야 합니다.

Device Tree 예제 장치
노드`compatible``reg`추가 속성
`flash@50``atmel,24c256``0x50`-
`gpio@60``nxp,pca9532``0x60``gpio-controller`, `#gpio-cells = <2>`

마스터 노드 아래 두 자식 장치의 속성입니다.

ACPI도 I2C 장치를 기술할 수 있습니다. 자세한 내용은 `Documentation/firmware-guide/acpi/enumeration.rst`에 있는 전용 문서를 참조합니다.

많은 임베디드 아키텍처에서 Device Tree가 예전 board file 기반 하드웨어 설명을 대체했지만, 오래된 코드에서는 board file도 여전히 사용됩니다.

board file에서는 `struct i2c_board_info` 배열을 만들고 `i2c_register_board_info()`로 등록해 I2C 장치를 생성합니다.

omap2 h4 예제는 I2C 버스 1에 주소 `0x2d`의 `isp1301_omap`, 주소 `0x52`와 `0x57`의 `24c01` EEPROM 두 개를 선언합니다. 각 장치 주소와 드라이버에 필요한 IRQ 또는 사용자 데이터도 함께 제공합니다.

omap h4 board_info
장치 유형주소추가 정보
`isp1301_omap``0x2d``.irq = OMAP_GPIO_IRQ(125)`
`24c01` mainboard EEPROM`0x52``.platform_data = &m24c01`
`24c01` CPU card EEPROM`0x57``.platform_data = &m24c01`

board file이 버스 1에 선언하는 세 장치입니다.

board file 정적 등록
`i2c_board_info` 배열 작성유형·주소·IRQ·platform_data 설정`i2c_register_board_info(1, ...)` 호출버스 1 등록 시 i2c-core가 세 장치 생성

부팅 초기화 코드에서 버스 번호와 장치 배열을 연결합니다.


Declare the I2C devices via devicetree
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

On platforms using devicetree, the declaration of I2C devices is done in
subnodes of the master controller.

Example:

.. code-block:: dts

        i2c1: i2c@400a0000 {
                /* ... master properties skipped ... */
                clock-frequency = <100000>;

                flash@50 {
                        compatible = "atmel,24c256";
                        reg = <0x50>;
                };

                pca9532: gpio@60 {
                        compatible = "nxp,pca9532";
                        gpio-controller;
                        #gpio-cells = <2>;
                        reg = <0x60>;
                };
        };

Here, two devices are attached to the bus using a speed of 100kHz. For
additional properties which might be needed to set up the device, please refer
to its devicetree documentation in Documentation/devicetree/bindings/.


Declare the I2C devices via ACPI
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

ACPI can also describe I2C devices. There is special documentation for this
which is currently located at Documentation/firmware-guide/acpi/enumeration.rst.


Declare the I2C devices in board files
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

In many embedded architectures, devicetree has replaced the old hardware
description based on board files, but the latter are still used in old
code. Instantiating I2C devices via board files is done with an array of
struct i2c_board_info which is registered by calling
i2c_register_board_info().

Example (from omap2 h4):

.. code-block:: c

  static struct i2c_board_info h4_i2c_board_info[] __initdata = {
        {
                I2C_BOARD_INFO("isp1301_omap", 0x2d),
                .irq                = OMAP_GPIO_IRQ(125),
        },
        {        /* EEPROM on mainboard */
                I2C_BOARD_INFO("24c01", 0x52),
                .platform_data        = &m24c01,
        },
        {        /* EEPROM on cpu card */
                I2C_BOARD_INFO("24c01", 0x57),
                .platform_data        = &m24c01,
        },
  };

  static void __init omap_h4_init(void)
  {
        (...)
        i2c_register_board_info(1, h4_i2c_board_info,
                        ARRAY_SIZE(h4_i2c_board_info));
        (...)
  }

The above code declares 3 devices on I2C bus 1, including their respective
addresses and custom data needed by their drivers.

방법 2: 드라이버가 장치를 명시적으로 생성

106-177

더 큰 장치가 내부 통신용으로 I2C 버스를 사용할 때는 장치를 명시적으로 생성하는 방법이 적합합니다. TV 어댑터의 메인 칩에 튜너, 비디오 디코더, 오디오 디코더 등이 I2C로 연결되는 경우가 전형적입니다.

이런 내부 버스는 번호를 미리 알 수 없으므로 방법 1을 사용할 수 없습니다. 대신 `struct i2c_board_info`를 채우고 `i2c_new_client_device()`를 호출합니다.

sfe4001 네트워크 드라이버 예제는 `I2C_BOARD_INFO("max6647", 0x4e)`로 hwmon 장치 정보를 만들고, 네트워크 어댑터 내부의 `efx->i2c_adap`에 `i2c_new_client_device()`를 호출해 I2C 장치 하나를 생성합니다.

장치가 실제로 존재하는지 확실하지 않거나 보드 변형에 따라 주소가 달라질 수 있다면 `i2c_new_client_device()` 대신 `i2c_new_scanned_device()`를 사용할 수 있습니다.

nxp OHCI 예제는 후보 주소 배열 `0x2c`, `0x2d`, `I2C_CLIENT_END`를 만들고 어댑터 2를 얻습니다. 장치 유형을 `isp1301_nxp`로 설정한 뒤 후보 주소를 스캔하고 마지막에 어댑터 참조를 반환합니다.

이 코드는 주소 `0x2c`를 먼저 시도하고 없으면 `0x2d`를 시도합니다. 둘 다 없으면 포기하므로 최대 한 개의 장치만 생성합니다.

I2C 장치를 생성한 드라이버는 정리할 때 이를 제거할 책임도 집니다. 앞서 `i2c_new_client_device()` 또는 `i2c_new_scanned_device()`가 반환한 포인터로 `i2c_unregister_device()`를 호출해야 합니다.

명시적 장치 생성 API
상황API결과
장치 유형과 주소를 알고 있음`i2c_new_client_device()`지정 주소에 장치 하나 생성
장치 존재 또는 주소가 불확실`i2c_new_scanned_device()`후보 주소를 순서대로 검사해 최대 하나 생성
드라이버 정리`i2c_unregister_device()`생성한 장치 제거

주소 확실성에 따라 API를 선택합니다.

후보 주소 스캔
`i2c_get_adapter(2)`장치 유형 `isp1301_nxp` 설정주소 `0x2c` 시도없으면 `0x2d` 시도장치 생성 또는 포기`i2c_put_adapter()`정리 시 `i2c_unregister_device()`

nxp OHCI 예제의 주소 선택과 수명 주기입니다.


Method 2: Instantiate the devices explicitly
--------------------------------------------

This method is appropriate when a larger device uses an I2C bus for
internal communication. A typical case is TV adapters. These can have a
tuner, a video decoder, an audio decoder, etc. usually connected to the
main chip by the means of an I2C bus. You won't know the number of the I2C
bus in advance, so the method 1 described above can't be used. Instead,
you can instantiate your I2C devices explicitly. This is done by filling
a struct i2c_board_info and calling i2c_new_client_device().

Example (from the sfe4001 network driver):

.. code-block:: c

  static struct i2c_board_info sfe4001_hwmon_info = {
        I2C_BOARD_INFO("max6647", 0x4e),
  };

  int sfe4001_init(struct efx_nic *efx)
  {
        (...)
        efx->board_info.hwmon_client =
                i2c_new_client_device(&efx->i2c_adap, &sfe4001_hwmon_info);

        (...)
  }

The above code instantiates 1 I2C device on the I2C bus which is on the
network adapter in question.

A variant of this is when you don't know for sure if an I2C device is
present or not (for example for an optional feature which is not present
on cheap variants of a board but you have no way to tell them apart), or
it may have different addresses from one board to the next (manufacturer
changing its design without notice). In this case, you can call
i2c_new_scanned_device() instead of i2c_new_client_device().

Example (from the nxp OHCI driver):

.. code-block:: c

  static const unsigned short normal_i2c[] = { 0x2c, 0x2d, I2C_CLIENT_END };

  static int usb_hcd_nxp_probe(struct platform_device *pdev)
  {
        (...)
        struct i2c_adapter *i2c_adap;
        struct i2c_board_info i2c_info;

        (...)
        i2c_adap = i2c_get_adapter(2);
        memset(&i2c_info, 0, sizeof(struct i2c_board_info));
        strscpy(i2c_info.type, "isp1301_nxp", sizeof(i2c_info.type));
        isp1301_i2c_client = i2c_new_scanned_device(i2c_adap, &i2c_info,
                                                    normal_i2c, NULL);
        i2c_put_adapter(i2c_adap);
        (...)
  }

The above code instantiates up to 1 I2C device on the I2C bus which is on
the OHCI adapter in question. It first tries at address 0x2c, if nothing
is found there it tries address 0x2d, and if still nothing is found, it
simply gives up.

The driver which instantiated the I2C device is responsible for destroying
it on cleanup. This is done by calling i2c_unregister_device() on the
pointer that was earlier returned by i2c_new_client_device() or
i2c_new_scanned_device().

방법 3: 특정 장치를 찾기 위한 버스 probe

178-228

때로는 `i2c_new_scanned_device()`를 호출할 만큼의 정보조차 없습니다. PC 메인보드의 하드웨어 모니터링 칩이 전형적인 사례입니다. 모델이 수십 종이고 25개의 서로 다른 주소에 있을 수 있어 모든 메인보드의 사용 칩을 완전하게 나열하는 것은 사실상 불가능합니다.

다행히 대부분의 칩에는 제조사와 장치 ID 레지스터가 있어 probe로 식별할 수 있습니다.

이 경우 I2C 장치를 사전에 선언하거나 명시적으로 생성하지 않습니다. 드라이버가 로드되면 i2c-core가 장치를 probe하고, 지원 장치를 찾으면 I2C 장치를 자동 생성합니다.

오동작을 막기 위해 두 가지 제한이 적용됩니다. I2C 장치 드라이버는 임의 레지스터를 읽어 지원 장치를 식별하는 `detect()` 메서드를 구현해야 합니다. 또한 지원 장치가 있을 가능성이 있고 probe에 동의한 버스만 검사합니다. 이렇게 하면 TV 어댑터에서 하드웨어 모니터링 칩을 잘못 probe하는 일을 피할 수 있습니다.

구현 예는 `drivers/hwmon/lm90.c`의 `lm90_driver`와 `lm90_detect()`입니다.

성공적인 probe로 생성된 장치는 이를 감지한 드라이버가 제거되거나 기반 I2C 버스가 제거될 때 자동으로 삭제됩니다. 둘 중 먼저 일어난 사건이 장치 수명을 끝냅니다.

이 방식은 2.4와 초기 2.6 커널의 I2C 동작과 본질적으로 비슷하지만 두 가지 중요한 차이가 있습니다.

과거에는 probe가 유일한 장치 생성 방식이었지만 현재는 여러 방식 중 하나입니다. 부작용이 있을 수 있으므로 다른 방법이 없을 때만 방법 3을 사용하고, 가능하면 방법 1과 2를 우선해야 합니다.

과거에는 모든 I2C 버스를 기본으로 probe했지만 현재는 버스가 class 비트필드로 어떤 I2C 드라이버 클래스의 probe를 허용하는지 명시해야 합니다. 기본 class는 비어 있어 probe가 일어나지 않으며, 이 제한은 원치 않는 부작용을 줄입니다.

결론적으로 방법 3은 가능한 한 피해야 합니다. 명시적인 장치 생성인 방법 1과 2가 더 안전하고 빠릅니다.

probe 방식의 안전 조건
조건요구사항
드라이버지원 장치를 식별하는 `detect()` 구현
버스해당 드라이버 class의 probe를 명시적으로 허용
기본값빈 class, probe 없음
수명 종료감지 드라이버 제거 또는 기반 버스 제거 중 먼저 발생한 시점

자동 탐색의 범위를 드라이버와 버스 양쪽에서 제한합니다.

방법 3 자동 probe
detect 메서드가 있는 I2C 드라이버 로드class가 허용된 버스만 선택후보 주소의 ID 레지스터 검사지원 장치 확인 시 자동 생성드라이버 또는 버스 제거 시 자동 삭제

드라이버 로드에서 자동 장치 생성까지의 흐름입니다.

Method 3: Probe an I2C bus for certain devices
----------------------------------------------

Sometimes you do not have enough information about an I2C device, not even
to call i2c_new_scanned_device(). The typical case is hardware monitoring
chips on PC mainboards. There are several dozen models, which can live
at 25 different addresses. Given the huge number of mainboards out there,
it is next to impossible to build an exhaustive list of the hardware
monitoring chips being used. Fortunately, most of these chips have
manufacturer and device ID registers, so they can be identified by
probing.

In that case, I2C devices are neither declared nor instantiated
explicitly. Instead, i2c-core will probe for such devices as soon as their
drivers are loaded, and if any is found, an I2C device will be
instantiated automatically. In order to prevent any misbehavior of this
mechanism, the following restrictions apply:

* The I2C device driver must implement the detect() method, which
  identifies a supported device by reading from arbitrary registers.
* Only buses which are likely to have a supported device and agree to be
  probed, will be probed. For example this avoids probing for hardware
  monitoring chips on a TV adapter.

Example:
See lm90_driver and lm90_detect() in drivers/hwmon/lm90.c

I2C devices instantiated as a result of such a successful probe will be
destroyed automatically when the driver which detected them is removed,
or when the underlying I2C bus is itself destroyed, whichever happens
first.

Those of you familiar with the I2C subsystem of 2.4 kernels and early 2.6
kernels will find out that this method 3 is essentially similar to what
was done there. Two significant differences are:

* Probing is only one way to instantiate I2C devices now, while it was the
  only way back then. Where possible, methods 1 and 2 should be preferred.
  Method 3 should only be used when there is no other way, as it can have
  undesirable side effects.
* I2C buses must now explicitly say which I2C driver classes can probe
  them (by the means of the class bitfield), while all I2C buses were
  probed by default back then. The default is an empty class which means
  that no probing happens. The purpose of the class bitfield is to limit
  the aforementioned undesirable side effects.

Once again, method 3 should be avoided wherever possible. Explicit device
instantiation (methods 1 and 2) is much preferred for it is safer and
faster.

방법 4: 사용자 공간에서 sysfs로 생성·삭제

229-272

일반적으로 커널은 연결된 I2C 장치와 주소를 알아야 합니다. 그러나 그렇지 못한 일부 상황을 위해 사용자가 정보를 제공할 수 있는 sysfs 인터페이스가 추가되었습니다.

모든 I2C 버스 디렉터리에는 쓰기 전용 속성 `new_device`와 `delete_device`가 있습니다. 올바른 매개변수를 쓰면 각각 I2C 장치를 생성하거나 삭제합니다.

`new_device`에는 I2C 장치 이름 문자열과 장치 주소 숫자 두 개를 씁니다. 주소는 보통 `0x`로 시작하는 16진수지만 10진수도 사용할 수 있습니다.

`delete_device`에는 장치 주소 하나만 씁니다. 같은 I2C 세그먼트에서 같은 주소를 두 장치가 공유할 수 없으므로 주소만으로 삭제할 장치를 고유하게 식별할 수 있습니다.

예제는 `echo eeprom 0x50 > /sys/bus/i2c/devices/i2c-3/new_device`로 논리 버스 3의 주소 `0x50`에 `eeprom` 장치를 생성합니다.

사용자 공간 sysfs 속성
속성입력
`new_device`장치 이름 + 주소`eeprom 0x50`
`delete_device`주소`0x50`

생성과 삭제에 필요한 입력입니다.

이 인터페이스는 커널 안에서 장치를 선언할 수 없을 때만 사용해야 하지만 여러 상황에서 유용합니다. 드라이버가 보통 방법 3으로 감지하더라도 해당 세그먼트에 올바른 class 비트가 없거나, 장치가 예상 밖 주소에 있거나, 감지 조건이 너무 엄격하거나, 아직 공식 지원되지 않았지만 호환됨을 알고 있는 경우가 해당합니다.

시험 보드에 I2C 장치를 직접 납땜한 채 드라이버를 개발하는 경우에도 유용합니다.

이 인터페이스는 일부 I2C 드라이버의 `force_*` 모듈 매개변수를 대체합니다. 각 장치 드라이버가 아니라 i2c-core에서 구현하므로 더 효율적이고, 설정을 바꾸기 위해 드라이버를 다시 로드할 필요가 없습니다.

드라이버가 로드되거나 제공되기 전에도 장치를 생성할 수 있으며, 어떤 드라이버가 필요한지 알 필요도 없습니다.

sysfs 생성이 유용한 경우
상황문제
버스 class 미설정일반 detect가 시작되지 않음
예상 밖 주소드라이버의 기본 후보에 없음
감지 실패detect가 너무 엄격하거나 아직 공식 지원 전
시험 보드개발자가 직접 장치를 추가

커널 내 선언을 사용할 수 없을 때의 예외 상황입니다.

sysfs 장치 생성·바인딩
대상 논리 버스와 주소 확인`new_device`에 이름과 주소 기록i2c-core가 장치 생성호환 드라이버가 있으면 바인딩필요 시 `delete_device`에 주소 기록

장치는 드라이버보다 먼저 생성할 수도 있습니다.

Method 4: Instantiate from user-space
-------------------------------------

In general, the kernel should know which I2C devices are connected and
what addresses they live at. However, in certain cases, it does not, so a
sysfs interface was added to let the user provide the information. This
interface is made of 2 attribute files which are created in every I2C bus
directory: ``new_device`` and ``delete_device``. Both files are write
only and you must write the right parameters to them in order to properly
instantiate, respectively delete, an I2C device.

File ``new_device`` takes 2 parameters: the name of the I2C device (a
string) and the address of the I2C device (a number, typically expressed
in hexadecimal starting with 0x, but can also be expressed in decimal.)

File ``delete_device`` takes a single parameter: the address of the I2C
device. As no two devices can live at the same address on a given I2C
segment, the address is sufficient to uniquely identify the device to be
deleted.

Example::

  # echo eeprom 0x50 > /sys/bus/i2c/devices/i2c-3/new_device

While this interface should only be used when in-kernel device declaration
can't be done, there is a variety of cases where it can be helpful:

* The I2C driver usually detects devices (method 3 above) but the bus
  segment your device lives on doesn't have the proper class bit set and
  thus detection doesn't trigger.
* The I2C driver usually detects devices, but your device lives at an
  unexpected address.
* The I2C driver usually detects devices, but your device is not detected,
  either because the detection routine is too strict, or because your
  device is not officially supported yet but you know it is compatible.
* You are developing a driver on a test board, where you soldered the I2C
  device yourself.

This interface is a replacement for the force_* module parameters some I2C
drivers implement. Being implemented in i2c-core rather than in each
device driver individually, it is much more efficient, and also has the
advantage that you do not have to reload the driver to change a setting.
You can also instantiate the device before the driver is loaded or even
available, and you don't need to know what driver the device needs.