← Documents Documentation/i2c/writing-clients.rst GitHub 원문 ↗

Linux 6.18.37 · I2C

Implementing I2C device drivers

Linux I2C·SMBus 장치 드라이버의 구조, 클라이언트 바인딩과 생성, 수명 주기 및 통신 API를 설명합니다.

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

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

1. 요약·해설

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

요약·해설

writing-clients.rst:1-403

I2C 장치 드라이버는 `i2c_driver`의 ID·probe·remove 콜백으로 기존 `i2c_client`에 바인딩합니다. 장치를 명시적으로 생성할 때는 주소 확실성에 맞는 API를 쓰고, 통신은 가능하면 모든 어댑터가 지원하는 SMBus 전용 함수를 우선합니다.

문서 개요
항목
SourceDocumentation/i2c/writing-clients.rst
분량403 source lines
핵심 구조i2c_driver, i2c_client
권장 통신SMBus-level API

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

핵심 흐름
ID table과 드라이버 선언probe에서 client 초기화장치별 data 연결전용 I2C·SMBus API로 통신remove와 unregister로 정리

문서의 주요 구현·사용 순서를 압축합니다.

2. 영어 원문 전체

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

원문 전체 펼치기
1 ===============================
2 Implementing I2C device drivers
3 ===============================
4
5 This is a small guide for those who want to write kernel drivers for I2C
6 or SMBus devices, using Linux as the protocol host/master (not slave).
7
8 To set up a driver, you need to do several things. Some are optional, and
9 some things can be done slightly or completely different. Use this as a
10 guide, not as a rule book!
11
12
13 General remarks
14 ===============
15
16 Try to keep the kernel namespace as clean as possible. The best way to
17 do this is to use a unique prefix for all global symbols. This is
18 especially important for exported symbols, but it is a good idea to do
19 it for non-exported symbols too. We will use the prefix ``foo_`` in this
20 tutorial.
21
22
23 The driver structure
24 ====================
25
26 Usually, you will implement a single driver structure, and instantiate
27 all clients from it. Remember, a driver structure contains general access
28 routines, and should be zero-initialized except for fields with data you
29 provide. A client structure holds device-specific information like the
30 driver model device node, and its I2C address.
31
32 ::
33
34 static const struct i2c_device_id foo_idtable[] = {
35 { "foo", my_id_for_foo },
36 { "bar", my_id_for_bar },
37 { }
38 };
39 MODULE_DEVICE_TABLE(i2c, foo_idtable);
40
41 static struct i2c_driver foo_driver = {
42 .driver = {
43 .name = "foo",
44 .pm = &foo_pm_ops, /* optional */
45 },
46
47 .id_table = foo_idtable,
48 .probe = foo_probe,
49 .remove = foo_remove,
50
51 .shutdown = foo_shutdown, /* optional */
52 .command = foo_command, /* optional, deprecated */
53 }
54
55 The name field is the driver name, and must not contain spaces. It
56 should match the module name (if the driver can be compiled as a module),
57 although you can use MODULE_ALIAS (passing "foo" in this example) to add
58 another name for the module. If the driver name doesn't match the module
59 name, the module won't be automatically loaded (hotplug/coldplug).
60
61 All other fields are for call-back functions which will be explained
62 below.
63
64
65 Extra client data
66 =================
67
68 Each client structure has a special ``data`` field that can point to any
69 structure at all. You should use this to keep device-specific data.
70
71 ::
72
73 /* store the value */
74 void i2c_set_clientdata(struct i2c_client *client, void *data);
75
76 /* retrieve the value */
77 void *i2c_get_clientdata(const struct i2c_client *client);
78
79 Note that starting with kernel 2.6.34, you don't have to set the ``data`` field
80 to NULL in remove() or if probe() failed anymore. The i2c-core does this
81 automatically on these occasions. Those are also the only times the core will
82 touch this field.
83
84
85 Accessing the client
86 ====================
87
88 Let's say we have a valid client structure. At some time, we will need
89 to gather information from the client, or write new information to the
90 client.
91
92 I have found it useful to define foo_read and foo_write functions for this.
93 For some cases, it will be easier to call the I2C functions directly,
94 but many chips have some kind of register-value idea that can easily
95 be encapsulated.
96
97 The below functions are simple examples, and should not be copied
98 literally::
99
100 int foo_read_value(struct i2c_client *client, u8 reg)
101 {
102 if (reg < 0x10) /* byte-sized register */
103 return i2c_smbus_read_byte_data(client, reg);
104 else /* word-sized register */
105 return i2c_smbus_read_word_data(client, reg);
106 }
107
108 int foo_write_value(struct i2c_client *client, u8 reg, u16 value)
109 {
110 if (reg == 0x10) /* Impossible to write - driver error! */
111 return -EINVAL;
112 else if (reg < 0x10) /* byte-sized register */
113 return i2c_smbus_write_byte_data(client, reg, value);
114 else /* word-sized register */
115 return i2c_smbus_write_word_data(client, reg, value);
116 }
117
118
119 Probing and attaching
120 =====================
121
122 The Linux I2C stack was originally written to support access to hardware
123 monitoring chips on PC motherboards, and thus used to embed some assumptions
124 that were more appropriate to SMBus (and PCs) than to I2C. One of these
125 assumptions was that most adapters and devices drivers support the SMBUS_QUICK
126 protocol to probe device presence. Another was that devices and their drivers
127 can be sufficiently configured using only such probe primitives.
128
129 As Linux and its I2C stack became more widely used in embedded systems
130 and complex components such as DVB adapters, those assumptions became more
131 problematic. Drivers for I2C devices that issue interrupts need more (and
132 different) configuration information, as do drivers handling chip variants
133 that can't be distinguished by protocol probing, or which need some board
134 specific information to operate correctly.
135
136
137 Device/Driver Binding
138 ---------------------
139
140 System infrastructure, typically board-specific initialization code or
141 boot firmware, reports what I2C devices exist. For example, there may be
142 a table, in the kernel or from the boot loader, identifying I2C devices
143 and linking them to board-specific configuration information about IRQs
144 and other wiring artifacts, chip type, and so on. That could be used to
145 create i2c_client objects for each I2C device.
146
147 I2C device drivers using this binding model work just like any other
148 kind of driver in Linux: they provide a probe() method to bind to
149 those devices, and a remove() method to unbind.
150
151 ::
152
153 static int foo_probe(struct i2c_client *client);
154 static void foo_remove(struct i2c_client *client);
155
156 Remember that the i2c_driver does not create those client handles. The
157 handle may be used during foo_probe(). If foo_probe() reports success
158 (zero not a negative status code) it may save the handle and use it until
159 foo_remove() returns. That binding model is used by most Linux drivers.
160
161 The probe function is called when an entry in the id_table name field
162 matches the device's name. If the probe function needs that entry, it
163 can retrieve it using
164
165 ::
166
167 const struct i2c_device_id *id = i2c_match_id(foo_idtable, client);
168
169
170 Device Creation
171 ---------------
172
173 If you know for a fact that an I2C device is connected to a given I2C bus,
174 you can instantiate that device by simply filling an i2c_board_info
175 structure with the device address and driver name, and calling
176 i2c_new_client_device(). This will create the device, then the driver core
177 will take care of finding the right driver and will call its probe() method.
178 If a driver supports different device types, you can specify the type you
179 want using the type field. You can also specify an IRQ and platform data
180 if needed.
181
182 Sometimes you know that a device is connected to a given I2C bus, but you
183 don't know the exact address it uses. This happens on TV adapters for
184 example, where the same driver supports dozens of slightly different
185 models, and I2C device addresses change from one model to the next. In
186 that case, you can use the i2c_new_scanned_device() variant, which is
187 similar to i2c_new_client_device(), except that it takes an additional list
188 of possible I2C addresses to probe. A device is created for the first
189 responsive address in the list. If you expect more than one device to be
190 present in the address range, simply call i2c_new_scanned_device() that
191 many times.
192
193 The call to i2c_new_client_device() or i2c_new_scanned_device() typically
194 happens in the I2C bus driver. You may want to save the returned i2c_client
195 reference for later use.
196
197
198 Device Detection
199 ----------------
200
201 The device detection mechanism comes with a number of disadvantages.
202 You need some reliable way to identify the supported devices
203 (typically using device-specific, dedicated identification registers),
204 otherwise misdetections are likely to occur and things can get wrong
205 quickly. Keep in mind that the I2C protocol doesn't include any
206 standard way to detect the presence of a chip at a given address, let
207 alone a standard way to identify devices. Even worse is the lack of
208 semantics associated to bus transfers, which means that the same
209 transfer can be seen as a read operation by a chip and as a write
210 operation by another chip. For these reasons, device detection is
211 considered a legacy mechanism and shouldn't be used in new code.
212
213
214 Device Deletion
215 ---------------
216
217 Each I2C device which has been created using i2c_new_client_device()
218 or i2c_new_scanned_device() can be unregistered by calling
219 i2c_unregister_device(). If you don't call it explicitly, it will be
220 called automatically before the underlying I2C bus itself is removed,
221 as a device can't survive its parent in the device driver model.
222
223
224 Initializing the driver
225 =======================
226
227 When the kernel is booted, or when your foo driver module is inserted,
228 you have to do some initializing. Fortunately, just registering the
229 driver module is usually enough.
230
231 ::
232
233 static int __init foo_init(void)
234 {
235 return i2c_add_driver(&foo_driver);
236 }
237 module_init(foo_init);
238
239 static void __exit foo_cleanup(void)
240 {
241 i2c_del_driver(&foo_driver);
242 }
243 module_exit(foo_cleanup);
244
245 The module_i2c_driver() macro can be used to reduce above code.
246
247 module_i2c_driver(foo_driver);
248
249 Note that some functions are marked by ``__init``. These functions can
250 be removed after kernel booting (or module loading) is completed.
251 Likewise, functions marked by ``__exit`` are dropped by the compiler when
252 the code is built into the kernel, as they would never be called.
253
254
255 Driver Information
256 ==================
257
258 ::
259
260 /* Substitute your own name and email address */
261 MODULE_AUTHOR("Frodo Looijaard <frodol@dds.nl>"
262 MODULE_DESCRIPTION("Driver for Barf Inc. Foo I2C devices");
263
264 /* a few non-GPL license types are also allowed */
265 MODULE_LICENSE("GPL");
266
267
268 Power Management
269 ================
270
271 If your I2C device needs special handling when entering a system low
272 power state -- like putting a transceiver into a low power mode, or
273 activating a system wakeup mechanism -- do that by implementing the
274 appropriate callbacks for the dev_pm_ops of the driver (like suspend
275 and resume).
276
277 These are standard driver model calls, and they work just like they
278 would for any other driver stack. The calls can sleep, and can use
279 I2C messaging to the device being suspended or resumed (since their
280 parent I2C adapter is active when these calls are issued, and IRQs
281 are still enabled).
282
283
284 System Shutdown
285 ===============
286
287 If your I2C device needs special handling when the system shuts down
288 or reboots (including kexec) -- like turning something off -- use a
289 shutdown() method.
290
291 Again, this is a standard driver model call, working just like it
292 would for any other driver stack: the calls can sleep, and can use
293 I2C messaging.
294
295
296 Command function
297 ================
298
299 A generic ioctl-like function call back is supported. You will seldom
300 need this, and its use is deprecated anyway, so newer design should not
301 use it.
302
303
304 Sending and receiving
305 =====================
306
307 If you want to communicate with your device, there are several functions
308 to do this. You can find all of them in <linux/i2c.h>.
309
310 If you can choose between plain I2C communication and SMBus level
311 communication, please use the latter. All adapters understand SMBus level
312 commands, but only some of them understand plain I2C!
313
314
315 Plain I2C communication
316 -----------------------
317
318 ::
319
320 int i2c_master_send(struct i2c_client *client, const char *buf,
321 int count);
322 int i2c_master_recv(struct i2c_client *client, char *buf, int count);
323
324 These routines read and write some bytes from/to a client. The client
325 contains the I2C address, so you do not have to include it. The second
326 parameter contains the bytes to read/write, the third the number of bytes
327 to read/write (must be less than the length of the buffer, also should be
328 less than 64k since msg.len is u16.) Returned is the actual number of bytes
329 read/written.
330
331 ::
332
333 int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msg,
334 int num);
335
336 This sends a series of messages. Each message can be a read or write,
337 and they can be mixed in any way. The transactions are combined: no
338 stop condition is issued between transaction. The i2c_msg structure
339 contains for each message the client address, the number of bytes of the
340 message and the message data itself.
341
342 You can read the file i2c-protocol.rst for more information about the
343 actual I2C protocol.
344
345
346 SMBus communication
347 -------------------
348
349 ::
350
351 s32 i2c_smbus_xfer(struct i2c_adapter *adapter, u16 addr,
352 unsigned short flags, char read_write, u8 command,
353 int size, union i2c_smbus_data *data);
354
355 This is the generic SMBus function. All functions below are implemented
356 in terms of it. Never use this function directly!
357
358 ::
359
360 s32 i2c_smbus_read_byte(struct i2c_client *client);
361 s32 i2c_smbus_write_byte(struct i2c_client *client, u8 value);
362 s32 i2c_smbus_read_byte_data(struct i2c_client *client, u8 command);
363 s32 i2c_smbus_write_byte_data(struct i2c_client *client,
364 u8 command, u8 value);
365 s32 i2c_smbus_read_word_data(struct i2c_client *client, u8 command);
366 s32 i2c_smbus_write_word_data(struct i2c_client *client,
367 u8 command, u16 value);
368 s32 i2c_smbus_read_block_data(struct i2c_client *client,
369 u8 command, u8 *values);
370 s32 i2c_smbus_write_block_data(struct i2c_client *client,
371 u8 command, u8 length, const u8 *values);
372 s32 i2c_smbus_read_i2c_block_data(struct i2c_client *client,
373 u8 command, u8 length, u8 *values);
374 s32 i2c_smbus_write_i2c_block_data(struct i2c_client *client,
375 u8 command, u8 length,
376 const u8 *values);
377
378 These ones were removed from i2c-core because they had no users, but could
379 be added back later if needed::
380
381 s32 i2c_smbus_write_quick(struct i2c_client *client, u8 value);
382 s32 i2c_smbus_process_call(struct i2c_client *client,
383 u8 command, u16 value);
384 s32 i2c_smbus_block_process_call(struct i2c_client *client,
385 u8 command, u8 length, u8 *values);
386
387 All these transactions return a negative errno value on failure. The 'write'
388 transactions return 0 on success; the 'read' transactions return the read
389 value, except for block transactions, which return the number of values
390 read. The block buffers need not be longer than 32 bytes.
391
392 You can read the file smbus-protocol.rst for more information about the
393 actual SMBus protocol.
394
395
396 General purpose routines
397 ========================
398
399 Below all general purpose routines are listed, that were not mentioned
400 before::
401
402 /* Return the adapter number for a specific adapter */
403 int i2c_adapter_id(struct i2c_adapter *adap);
404

3. 한국어 전문 번역

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

드라이버 구조와 클라이언트별 데이터

1-84

이 문서는 Linux가 프로토콜 호스트 또는 컨트롤러 역할을 할 때 I2C·SMBus 장치의 커널 드라이버를 작성하는 작은 안내서입니다. Linux가 타깃으로 동작하는 경우를 다루지 않습니다.

드라이버 설정에는 여러 단계가 있으며 일부는 선택 사항입니다. 구현에 따라 조금 또는 완전히 다른 방식을 쓸 수 있으므로 이 문서는 규칙집이 아니라 출발점으로 사용해야 합니다.

커널 네임스페이스를 깨끗하게 유지하려면 모든 전역 심볼에 고유 접두사를 사용해야 합니다. 특히 export 심볼에서 중요하지만 export하지 않는 심볼에도 권장합니다. 예제는 `foo_` 접두사를 사용합니다.

일반적으로 `struct i2c_driver` 하나를 구현하고 그 구조에서 모든 클라이언트를 인스턴스화합니다. 드라이버 구조는 공통 접근 루틴을 담으며, 직접 제공하는 필드를 제외하고 0으로 초기화돼야 합니다. 클라이언트 구조는 드라이버 모델의 장치 노드와 I2C 주소 같은 장치별 정보를 담습니다.

예제의 `foo_idtable`은 `foo`와 `bar` 장치 이름을 각 내부 ID에 매핑하고 빈 항목으로 끝납니다. `MODULE_DEVICE_TABLE(i2c, foo_idtable)`은 모듈 자동 로딩에 필요한 테이블을 노출합니다.

`foo_driver.driver.name`은 공백 없는 드라이버 이름이며, 모듈로 빌드할 수 있다면 모듈 이름과 일치해야 합니다. `MODULE_ALIAS("foo")`로 별칭을 추가할 수 있지만 이름이나 별칭이 맞지 않으면 hotplug 또는 coldplug 때 모듈이 자동으로 로드되지 않습니다.

i2c_driver 주요 필드
필드예제필수 여부와 역할
`.driver.name``"foo"`필수, 공백 없는 드라이버·모듈 이름
`.driver.pm``&foo_pm_ops`선택, 전원 관리 콜백
`.id_table``foo_idtable`장치 이름과 ID 매칭
`.probe``foo_probe`장치 바인딩
`.remove``foo_remove`장치 바인딩 해제
`.shutdown``foo_shutdown`선택, 종료·재부팅 처리
`.command``foo_command`선택, 폐기된 범용 명령 콜백

예제 드라이버 구조의 필수·선택 콜백입니다.

각 `i2c_client`에는 임의 구조를 가리킬 수 있는 전용 `data` 필드가 있습니다. 장치별 상태를 보관할 때 `i2c_set_clientdata(client, data)`로 저장하고 `i2c_get_clientdata(client)`로 가져옵니다.

커널 2.6.34부터 `remove()` 또는 실패한 `probe()`에서 `data`를 직접 `NULL`로 설정할 필요가 없습니다. 이 두 시점에는 i2c-core가 자동으로 지우며, core가 이 필드를 건드리는 경우도 이때뿐입니다.

클라이언트별 상태 연결
`foo_probe()`에서 장치별 상태 할당`i2c_set_clientdata()`로 client에 연결동작 중 `i2c_get_clientdata()`로 조회`foo_remove()` 또는 probe 실패i2c-core가 data 필드를 자동으로 NULL 처리

probe에서 만든 장치 상태를 remove까지 유지합니다.

===============================
Implementing I2C device drivers
===============================

This is a small guide for those who want to write kernel drivers for I2C
or SMBus devices, using Linux as the protocol host/master (not slave).

To set up a driver, you need to do several things. Some are optional, and
some things can be done slightly or completely different. Use this as a
guide, not as a rule book!


General remarks
===============

Try to keep the kernel namespace as clean as possible. The best way to
do this is to use a unique prefix for all global symbols. This is
especially important for exported symbols, but it is a good idea to do
it for non-exported symbols too. We will use the prefix ``foo_`` in this
tutorial.


The driver structure
====================

Usually, you will implement a single driver structure, and instantiate
all clients from it. Remember, a driver structure contains general access
routines, and should be zero-initialized except for fields with data you
provide.  A client structure holds device-specific information like the
driver model device node, and its I2C address.

::

  static const struct i2c_device_id foo_idtable[] = {
        { "foo", my_id_for_foo },
        { "bar", my_id_for_bar },
        { }
  };
  MODULE_DEVICE_TABLE(i2c, foo_idtable);

  static struct i2c_driver foo_driver = {
        .driver = {
                .name        = "foo",
                .pm        = &foo_pm_ops,        /* optional */
        },

        .id_table        = foo_idtable,
        .probe                = foo_probe,
        .remove                = foo_remove,

        .shutdown        = foo_shutdown,        /* optional */
        .command        = foo_command,        /* optional, deprecated */
  }

The name field is the driver name, and must not contain spaces.  It
should match the module name (if the driver can be compiled as a module),
although you can use MODULE_ALIAS (passing "foo" in this example) to add
another name for the module.  If the driver name doesn't match the module
name, the module won't be automatically loaded (hotplug/coldplug).

All other fields are for call-back functions which will be explained
below.


Extra client data
=================

Each client structure has a special ``data`` field that can point to any
structure at all.  You should use this to keep device-specific data.

::

        /* store the value */
        void i2c_set_clientdata(struct i2c_client *client, void *data);

        /* retrieve the value */
        void *i2c_get_clientdata(const struct i2c_client *client);

Note that starting with kernel 2.6.34, you don't have to set the ``data`` field
to NULL in remove() or if probe() failed anymore. The i2c-core does this
automatically on these occasions. Those are also the only times the core will
touch this field.

레지스터 접근 도우미

85-118

유효한 클라이언트 구조가 있으면 장치에서 정보를 읽거나 새 값을 써야 합니다. 많은 칩은 레지스터와 값의 관계가 있으므로 `foo_read_value()`와 `foo_write_value()` 같은 도우미로 캡슐화하면 유용합니다. 단순한 경우에는 I2C 함수를 직접 호출하는 편이 더 쉬울 수도 있습니다.

원문의 함수는 개념을 보여주는 단순 예이며 그대로 복사해서는 안 됩니다.

`foo_read_value(client, reg)`는 `reg < 0x10`이면 바이트 크기 레지스터로 보고 `i2c_smbus_read_byte_data()`를 호출하고, 그 외에는 워드 크기 레지스터로 보고 `i2c_smbus_read_word_data()`를 호출합니다.

`foo_write_value(client, reg, value)`는 쓰기가 불가능하다고 가정한 레지스터 `0x10`에 `-EINVAL`을 반환합니다. `reg < 0x10`이면 `i2c_smbus_write_byte_data()`, 그 외에는 `i2c_smbus_write_word_data()`를 호출합니다.

예제 레지스터 접근 규칙
조건읽기쓰기
`reg < 0x10``i2c_smbus_read_byte_data()``i2c_smbus_write_byte_data()`
`reg == 0x10``i2c_smbus_read_word_data()``-EINVAL`
`reg > 0x10``i2c_smbus_read_word_data()``i2c_smbus_write_word_data()`

주소 범위에 따라 SMBus 바이트·워드 API를 선택합니다.

Accessing the client
====================

Let's say we have a valid client structure. At some time, we will need
to gather information from the client, or write new information to the
client.

I have found it useful to define foo_read and foo_write functions for this.
For some cases, it will be easier to call the I2C functions directly,
but many chips have some kind of register-value idea that can easily
be encapsulated.

The below functions are simple examples, and should not be copied
literally::

  int foo_read_value(struct i2c_client *client, u8 reg)
  {
        if (reg < 0x10)        /* byte-sized register */
                return i2c_smbus_read_byte_data(client, reg);
        else                /* word-sized register */
                return i2c_smbus_read_word_data(client, reg);
  }

  int foo_write_value(struct i2c_client *client, u8 reg, u16 value)
  {
        if (reg == 0x10)        /* Impossible to write - driver error! */
                return -EINVAL;
        else if (reg < 0x10)        /* byte-sized register */
                return i2c_smbus_write_byte_data(client, reg, value);
        else                        /* word-sized register */
                return i2c_smbus_write_word_data(client, reg, value);
  }

장치 바인딩, 생성, 감지와 삭제

119-223

초기 Linux I2C 스택은 PC 메인보드의 하드웨어 모니터링 칩 접근을 위해 작성돼 I2C보다 SMBus와 PC에 더 적합한 가정을 포함했습니다. 대부분의 어댑터와 장치 드라이버가 장치 존재를 probe하는 `SMBUS_QUICK`을 지원하고, 이런 probe 기본 동작만으로 장치와 드라이버를 충분히 설정할 수 있다는 가정이 대표적입니다.

Linux I2C가 임베디드 시스템과 DVB 어댑터 같은 복잡한 구성 요소에 널리 쓰이면서 이 가정은 문제가 됐습니다. 인터럽트를 내는 장치, 프로토콜 probe로 구분할 수 없는 칩 변형, 보드별 배선 정보가 필요한 장치는 더 많고 다른 설정 정보가 필요합니다.

대개 보드별 초기화 코드나 부팅 펌웨어 같은 시스템 인프라가 존재하는 I2C 장치를 보고합니다. 커널이나 부트로더의 테이블이 장치와 IRQ, 배선, 칩 유형 같은 보드별 설정을 연결하고, 이를 바탕으로 각 장치의 `i2c_client` 객체를 만들 수 있습니다.

이 바인딩 모델의 I2C 드라이버는 다른 Linux 드라이버처럼 `probe()`로 장치에 바인딩하고 `remove()`로 해제합니다. 예제 시그니처는 `static int foo_probe(struct i2c_client *client)`와 `static void foo_remove(struct i2c_client *client)`입니다.

`i2c_driver` 자체는 클라이언트 핸들을 만들지 않습니다. `foo_probe()`는 전달받은 핸들을 사용할 수 있고, 0을 반환해 성공을 보고하면 저장한 뒤 `foo_remove()`가 반환할 때까지 사용할 수 있습니다. 대부분의 Linux 드라이버가 이 모델을 사용합니다.

`id_table`의 이름 필드가 장치 이름과 맞을 때 probe가 호출됩니다. probe에서 해당 ID 항목이 필요하면 `i2c_match_id(foo_idtable, client)`로 가져옵니다.

Device/Driver 바인딩 책임
주체책임
보드 코드·펌웨어장치 존재, 주소, IRQ, 배선, 칩 유형 기술
I2C·driver core`i2c_client` 생성과 적합한 드라이버 탐색
`foo_probe()`전달된 client로 초기화하고 성공 시 0 반환
`foo_remove()`저장한 client의 자원 정리와 바인딩 해제

클라이언트 생성 주체와 드라이버 콜백을 구분합니다.

주소와 드라이버 이름을 확실히 아는 장치는 `i2c_board_info`에 채운 뒤 `i2c_new_client_device()`를 호출해 생성합니다. Driver core가 맞는 드라이버를 찾고 `probe()`를 호출합니다. 여러 장치 유형을 지원하면 `type` 필드로 유형을 지정하고, 필요하면 IRQ와 platform data도 넣을 수 있습니다.

장치가 특정 버스에 연결됐지만 정확한 주소를 모를 때는 후보 주소 목록을 추가로 받는 `i2c_new_scanned_device()`를 사용합니다. 목록에서 처음 응답하는 주소에 장치를 하나 만듭니다. 범위 안에 여러 장치가 있을 것으로 예상하면 필요한 수만큼 이 함수를 반복 호출합니다.

`i2c_new_client_device()`와 `i2c_new_scanned_device()`는 보통 I2C 버스 드라이버에서 호출하며, 반환된 `i2c_client` 참조는 나중 사용을 위해 저장할 수 있습니다.

명시적 I2C 장치 생성
상황API결과
정확한 주소를 앎`i2c_new_client_device()`지정 주소에 client 생성
후보 주소만 앎`i2c_new_scanned_device()`처음 응답한 주소에 client 하나 생성
여러 장치 예상`i2c_new_scanned_device()` 반복호출 횟수만큼 탐색·생성

주소 확실성과 생성 결과에 따른 API 선택입니다.

장치 감지에는 여러 단점이 있습니다. 보통 전용 식별 레지스터처럼 지원 장치를 신뢰성 있게 식별할 방법이 없으면 오감지 위험이 큽니다.

I2C 프로토콜에는 특정 주소에 칩이 존재하는지 감지하는 표준 방법도, 장치를 식별하는 표준 방법도 없습니다. 버스 전송에 의미 정보가 없어 같은 전송을 한 칩은 읽기로, 다른 칩은 쓰기로 해석할 수도 있습니다. 이런 이유로 자동 장치 감지는 레거시 메커니즘이며 새 코드에서 사용하면 안 됩니다.

`i2c_new_client_device()` 또는 `i2c_new_scanned_device()`로 만든 장치는 `i2c_unregister_device()`로 등록 해제할 수 있습니다. 명시적으로 호출하지 않아도 기반 I2C 버스가 제거되기 전에 자동 호출됩니다. 장치 드라이버 모델에서 자식 장치는 부모 버스보다 오래 존재할 수 없기 때문입니다.

I2C 장치의 수명 주기
펌웨어·보드 코드가 장치 정보 제공core가 `i2c_client` 생성ID가 맞는 드라이버의 `probe()` 호출드라이버가 client 상태 사용`i2c_unregister_device()` 또는 부모 버스 제거`remove()` 완료 후 client 소멸

시스템 설명에서 삭제까지의 일반 경로입니다.

Probing and attaching
=====================

The Linux I2C stack was originally written to support access to hardware
monitoring chips on PC motherboards, and thus used to embed some assumptions
that were more appropriate to SMBus (and PCs) than to I2C.  One of these
assumptions was that most adapters and devices drivers support the SMBUS_QUICK
protocol to probe device presence.  Another was that devices and their drivers
can be sufficiently configured using only such probe primitives.

As Linux and its I2C stack became more widely used in embedded systems
and complex components such as DVB adapters, those assumptions became more
problematic.  Drivers for I2C devices that issue interrupts need more (and
different) configuration information, as do drivers handling chip variants
that can't be distinguished by protocol probing, or which need some board
specific information to operate correctly.


Device/Driver Binding
---------------------

System infrastructure, typically board-specific initialization code or
boot firmware, reports what I2C devices exist.  For example, there may be
a table, in the kernel or from the boot loader, identifying I2C devices
and linking them to board-specific configuration information about IRQs
and other wiring artifacts, chip type, and so on.  That could be used to
create i2c_client objects for each I2C device.

I2C device drivers using this binding model work just like any other
kind of driver in Linux:  they provide a probe() method to bind to
those devices, and a remove() method to unbind.

::

        static int foo_probe(struct i2c_client *client);
        static void foo_remove(struct i2c_client *client);

Remember that the i2c_driver does not create those client handles.  The
handle may be used during foo_probe().  If foo_probe() reports success
(zero not a negative status code) it may save the handle and use it until
foo_remove() returns.  That binding model is used by most Linux drivers.

The probe function is called when an entry in the id_table name field
matches the device's name. If the probe function needs that entry, it
can retrieve it using

::

        const struct i2c_device_id *id = i2c_match_id(foo_idtable, client);


Device Creation
---------------

If you know for a fact that an I2C device is connected to a given I2C bus,
you can instantiate that device by simply filling an i2c_board_info
structure with the device address and driver name, and calling
i2c_new_client_device().  This will create the device, then the driver core
will take care of finding the right driver and will call its probe() method.
If a driver supports different device types, you can specify the type you
want using the type field.  You can also specify an IRQ and platform data
if needed.

Sometimes you know that a device is connected to a given I2C bus, but you
don't know the exact address it uses.  This happens on TV adapters for
example, where the same driver supports dozens of slightly different
models, and I2C device addresses change from one model to the next.  In
that case, you can use the i2c_new_scanned_device() variant, which is
similar to i2c_new_client_device(), except that it takes an additional list
of possible I2C addresses to probe.  A device is created for the first
responsive address in the list.  If you expect more than one device to be
present in the address range, simply call i2c_new_scanned_device() that
many times.

The call to i2c_new_client_device() or i2c_new_scanned_device() typically
happens in the I2C bus driver. You may want to save the returned i2c_client
reference for later use.


Device Detection
----------------

The device detection mechanism comes with a number of disadvantages.
You need some reliable way to identify the supported devices
(typically using device-specific, dedicated identification registers),
otherwise misdetections are likely to occur and things can get wrong
quickly.  Keep in mind that the I2C protocol doesn't include any
standard way to detect the presence of a chip at a given address, let
alone a standard way to identify devices.  Even worse is the lack of
semantics associated to bus transfers, which means that the same
transfer can be seen as a read operation by a chip and as a write
operation by another chip.  For these reasons, device detection is
considered a legacy mechanism and shouldn't be used in new code.


Device Deletion
---------------

Each I2C device which has been created using i2c_new_client_device()
or i2c_new_scanned_device() can be unregistered by calling
i2c_unregister_device().  If you don't call it explicitly, it will be
called automatically before the underlying I2C bus itself is removed,
as a device can't survive its parent in the device driver model.

드라이버 등록, 메타데이터와 전원·종료 처리

224-303

커널 부팅 또는 `foo` 모듈 삽입 때 보통 드라이버 모듈을 등록하는 것만으로 초기화가 충분합니다. `foo_init()`은 `i2c_add_driver(&foo_driver)`를 반환하고, `foo_cleanup()`은 `i2c_del_driver(&foo_driver)`를 호출합니다.

이 초기화·정리 코드는 `module_i2c_driver(foo_driver)` 매크로로 줄일 수 있습니다.

`__init` 표시 함수는 커널 부팅이나 모듈 로딩이 끝난 뒤 제거할 수 있습니다. 반대로 `__exit` 함수는 커널에 built-in으로 빌드하면 호출될 일이 없으므로 컴파일러가 버립니다.

드라이버 등록 방식
방식등록해제
명시적 함수`i2c_add_driver(&foo_driver)``i2c_del_driver(&foo_driver)`
편의 매크로`module_i2c_driver(foo_driver)`매크로가 자동 생성

명시적 init/exit와 편의 매크로를 비교합니다.

모듈은 `MODULE_AUTHOR`, `MODULE_DESCRIPTION`, `MODULE_LICENSE`로 작성자, 설명과 라이선스를 제공합니다. 예제는 GPL을 사용하며 일부 비GPL 라이선스 유형도 허용됩니다.

시스템 저전력 상태 진입 때 트랜시버를 저전력 모드로 바꾸거나 시스템 깨우기 메커니즘을 활성화하는 등 특별 처리가 필요하면 드라이버의 `dev_pm_ops`에 `suspend`와 `resume` 같은 적절한 콜백을 구현합니다.

이 콜백은 표준 드라이버 모델 호출입니다. sleep할 수 있고, 호출 시 부모 I2C 어댑터가 활성 상태이며 IRQ도 켜져 있으므로 suspend 또는 resume 대상 장치에 I2C 메시지를 보낼 수 있습니다.

시스템 종료, 재부팅과 `kexec` 때 장치를 끄는 등 특별 처리가 필요하면 `shutdown()` 메서드를 사용합니다. 이 역시 표준 드라이버 모델 호출이며 sleep하거나 I2C 메시지를 사용할 수 있습니다.

범용 ioctl 유사 `command` 콜백도 지원하지만 필요한 경우가 드물고 이미 폐기됐으므로 새 설계에서는 사용하지 않아야 합니다.

수명 주기 콜백의 실행 조건
상황콜백sleepI2C 메시지
저전력 진입`dev_pm_ops.suspend`가능가능
저전력 복귀`dev_pm_ops.resume`가능가능
shutdown·reboot·kexec`shutdown()`가능가능
범용 명령`command`폐기됨새 코드에서 사용 금지

전원 전환과 시스템 종료에 사용할 콜백입니다.

Initializing the driver
=======================

When the kernel is booted, or when your foo driver module is inserted,
you have to do some initializing. Fortunately, just registering the
driver module is usually enough.

::

  static int __init foo_init(void)
  {
        return i2c_add_driver(&foo_driver);
  }
  module_init(foo_init);

  static void __exit foo_cleanup(void)
  {
        i2c_del_driver(&foo_driver);
  }
  module_exit(foo_cleanup);

  The module_i2c_driver() macro can be used to reduce above code.

  module_i2c_driver(foo_driver);

Note that some functions are marked by ``__init``.  These functions can
be removed after kernel booting (or module loading) is completed.
Likewise, functions marked by ``__exit`` are dropped by the compiler when
the code is built into the kernel, as they would never be called.


Driver Information
==================

::

  /* Substitute your own name and email address */
  MODULE_AUTHOR("Frodo Looijaard <frodol@dds.nl>"
  MODULE_DESCRIPTION("Driver for Barf Inc. Foo I2C devices");

  /* a few non-GPL license types are also allowed */
  MODULE_LICENSE("GPL");


Power Management
================

If your I2C device needs special handling when entering a system low
power state -- like putting a transceiver into a low power mode, or
activating a system wakeup mechanism -- do that by implementing the
appropriate callbacks for the dev_pm_ops of the driver (like suspend
and resume).

These are standard driver model calls, and they work just like they
would for any other driver stack.  The calls can sleep, and can use
I2C messaging to the device being suspended or resumed (since their
parent I2C adapter is active when these calls are issued, and IRQs
are still enabled).


System Shutdown
===============

If your I2C device needs special handling when the system shuts down
or reboots (including kexec) -- like turning something off -- use a
shutdown() method.

Again, this is a standard driver model call, working just like it
would for any other driver stack:  the calls can sleep, and can use
I2C messaging.


Command function
================

A generic ioctl-like function call back is supported. You will seldom
need this, and its use is deprecated anyway, so newer design should not
use it.

일반 I2C와 SMBus 송수신 API

304-395

장치 통신 함수는 `<linux/i2c.h>`에 있습니다. 일반 I2C와 SMBus 계층 통신 중 선택할 수 있다면 SMBus를 사용해야 합니다. 모든 어댑터가 SMBus 계층 명령을 이해하지만 일반 I2C를 이해하는 어댑터는 일부뿐입니다.

`i2c_master_send(client, buf, count)`와 `i2c_master_recv(client, buf, count)`는 클라이언트에 바이트를 쓰거나 읽습니다. 주소는 `client`에 들어 있으므로 버퍼에 포함하지 않습니다.

두 번째 매개변수는 읽거나 쓸 바이트 버퍼이고 세 번째는 바이트 수입니다. 바이트 수는 버퍼 길이보다 작아야 하며 `msg.len`이 `u16`이므로 64KiB보다 작아야 합니다. 반환값은 실제로 읽거나 쓴 바이트 수입니다.

`i2c_transfer(adap, msg, num)`는 여러 메시지를 연속으로 보냅니다. 각 `i2c_msg`는 읽기 또는 쓰기일 수 있고 임의로 혼합할 수 있습니다. 메시지는 결합돼 중간에 STOP 조건이 나오지 않습니다. 각 메시지 구조에는 클라이언트 주소, 바이트 수와 데이터가 있습니다.

실제 일반 I2C 프로토콜은 `i2c-protocol.rst`를 참조합니다.

일반 I2C API
API주소 위치단위STOP 동작반환
`i2c_master_send()``client`바이트 버퍼 하나호출 끝실제 쓴 바이트 수
`i2c_master_recv()``client`바이트 버퍼 하나호출 끝실제 읽은 바이트 수
`i2c_transfer()`각 `i2c_msg`읽기·쓰기 메시지 배열메시지 사이 없음처리한 메시지 수 또는 오류

단일 client 접근과 결합 메시지 전송을 비교합니다.

`i2c_smbus_xfer()`는 범용 SMBus 함수이며 아래의 모든 전용 함수가 이를 바탕으로 구현됩니다. 드라이버가 이 함수를 직접 호출하면 안 됩니다.

전용 API에는 단일 바이트의 `i2c_smbus_read_byte()`·`i2c_smbus_write_byte()`, command 지정 바이트의 `i2c_smbus_read_byte_data()`·`i2c_smbus_write_byte_data()`, 워드의 `i2c_smbus_read_word_data()`·`i2c_smbus_write_word_data()`가 있습니다.

블록 API는 SMBus 블록용 `i2c_smbus_read_block_data()`·`i2c_smbus_write_block_data()`와 I2C 블록용 `i2c_smbus_read_i2c_block_data()`·`i2c_smbus_write_i2c_block_data()`를 제공합니다.

권장 SMBus 전용 함수
형식읽기쓰기
Byte`i2c_smbus_read_byte()``i2c_smbus_write_byte()`
Byte data`i2c_smbus_read_byte_data()``i2c_smbus_write_byte_data()`
Word data`i2c_smbus_read_word_data()``i2c_smbus_write_word_data()`
SMBus block`i2c_smbus_read_block_data()``i2c_smbus_write_block_data()`
I2C block`i2c_smbus_read_i2c_block_data()``i2c_smbus_write_i2c_block_data()`

데이터 형식별 읽기·쓰기 API입니다.

사용자가 없어 i2c-core에서 제거된 함수는 `i2c_smbus_write_quick()`, `i2c_smbus_process_call()`, `i2c_smbus_block_process_call()`입니다. 필요해지면 나중에 다시 추가할 수 있습니다.

모든 트랜잭션은 실패 시 음수 errno를 반환합니다. 쓰기 트랜잭션은 성공 시 0, 읽기 트랜잭션은 읽은 값을 반환합니다. 블록 읽기는 예외적으로 읽은 값의 개수를 반환합니다. 블록 버퍼는 32바이트보다 길 필요가 없습니다.

실제 SMBus 프로토콜은 `smbus-protocol.rst`를 참조합니다.

통신 API 선택
장치가 SMBus 명령으로 표현 가능한지 확인가능하면 `i2c_smbus_*` 전용 함수 선택일반 I2C가 필요하면 send/recv 또는 `i2c_transfer()` 선택반환값이 음수면 errno 처리읽기·쓰기·블록별 성공 반환 의미 확인

장치 프로토콜과 어댑터 기능에 맞는 가장 구체적인 API를 고릅니다.

Sending and receiving
=====================

If you want to communicate with your device, there are several functions
to do this. You can find all of them in <linux/i2c.h>.

If you can choose between plain I2C communication and SMBus level
communication, please use the latter. All adapters understand SMBus level
commands, but only some of them understand plain I2C!


Plain I2C communication
-----------------------

::

        int i2c_master_send(struct i2c_client *client, const char *buf,
                            int count);
        int i2c_master_recv(struct i2c_client *client, char *buf, int count);

These routines read and write some bytes from/to a client. The client
contains the I2C address, so you do not have to include it. The second
parameter contains the bytes to read/write, the third the number of bytes
to read/write (must be less than the length of the buffer, also should be
less than 64k since msg.len is u16.) Returned is the actual number of bytes
read/written.

::

        int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msg,
                         int num);

This sends a series of messages. Each message can be a read or write,
and they can be mixed in any way. The transactions are combined: no
stop condition is issued between transaction. The i2c_msg structure
contains for each message the client address, the number of bytes of the
message and the message data itself.

You can read the file i2c-protocol.rst for more information about the
actual I2C protocol.


SMBus communication
-------------------

::

        s32 i2c_smbus_xfer(struct i2c_adapter *adapter, u16 addr,
                           unsigned short flags, char read_write, u8 command,
                           int size, union i2c_smbus_data *data);

This is the generic SMBus function. All functions below are implemented
in terms of it. Never use this function directly!

::

        s32 i2c_smbus_read_byte(struct i2c_client *client);
        s32 i2c_smbus_write_byte(struct i2c_client *client, u8 value);
        s32 i2c_smbus_read_byte_data(struct i2c_client *client, u8 command);
        s32 i2c_smbus_write_byte_data(struct i2c_client *client,
                                      u8 command, u8 value);
        s32 i2c_smbus_read_word_data(struct i2c_client *client, u8 command);
        s32 i2c_smbus_write_word_data(struct i2c_client *client,
                                      u8 command, u16 value);
        s32 i2c_smbus_read_block_data(struct i2c_client *client,
                                      u8 command, u8 *values);
        s32 i2c_smbus_write_block_data(struct i2c_client *client,
                                       u8 command, u8 length, const u8 *values);
        s32 i2c_smbus_read_i2c_block_data(struct i2c_client *client,
                                          u8 command, u8 length, u8 *values);
        s32 i2c_smbus_write_i2c_block_data(struct i2c_client *client,
                                           u8 command, u8 length,
                                           const u8 *values);

These ones were removed from i2c-core because they had no users, but could
be added back later if needed::

        s32 i2c_smbus_write_quick(struct i2c_client *client, u8 value);
        s32 i2c_smbus_process_call(struct i2c_client *client,
                                   u8 command, u16 value);
        s32 i2c_smbus_block_process_call(struct i2c_client *client,
                                         u8 command, u8 length, u8 *values);

All these transactions return a negative errno value on failure. The 'write'
transactions return 0 on success; the 'read' transactions return the read
value, except for block transactions, which return the number of values
read. The block buffers need not be longer than 32 bytes.

You can read the file smbus-protocol.rst for more information about the
actual SMBus protocol.

일반 목적 루틴

396-403

앞 절에서 언급하지 않은 일반 목적 루틴으로 `i2c_adapter_id(struct i2c_adapter *adap)`가 있습니다. 특정 어댑터의 번호를 반환합니다.

일반 목적 I2C 루틴
함수입력반환
`i2c_adapter_id()``struct i2c_adapter *adap`해당 어댑터 번호

어댑터 식별에 쓰는 함수입니다.

General purpose routines
========================

Below all general purpose routines are listed, that were not mentioned
before::

        /* Return the adapter number for a specific adapter */
        int i2c_adapter_id(struct i2c_adapter *adap);