요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
===============================
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.
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);
}
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.
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 <[email protected]>"
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.
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.
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);
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_client`에는 임의 구조를 가리킬 수 있는 전용 `data` 필드가 있습니다. 장치별 상태를 보관할 때 `i2c_set_clientdata(client, data)`로 저장하고 `i2c_get_clientdata(client)`로 가져옵니다.
커널 2.6.34부터 `remove()` 또는 실패한 `probe()`에서 `data`를 직접 `NULL`로 설정할 필요가 없습니다. 이 두 시점에는 i2c-core가 자동으로 지우며, core가 이 필드를 건드리는 경우도 이때뿐입니다.
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()`를 호출합니다.
주소 범위에 따라 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)`로 가져옵니다.
클라이언트 생성 주체와 드라이버 콜백을 구분합니다.
주소와 드라이버 이름을 확실히 아는 장치는 `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` 참조는 나중 사용을 위해 저장할 수 있습니다.
주소 확실성과 생성 결과에 따른 API 선택입니다.
장치 감지에는 여러 단점이 있습니다. 보통 전용 식별 레지스터처럼 지원 장치를 신뢰성 있게 식별할 방법이 없으면 오감지 위험이 큽니다.
I2C 프로토콜에는 특정 주소에 칩이 존재하는지 감지하는 표준 방법도, 장치를 식별하는 표준 방법도 없습니다. 버스 전송에 의미 정보가 없어 같은 전송을 한 칩은 읽기로, 다른 칩은 쓰기로 해석할 수도 있습니다. 이런 이유로 자동 장치 감지는 레거시 메커니즘이며 새 코드에서 사용하면 안 됩니다.
`i2c_new_client_device()` 또는 `i2c_new_scanned_device()`로 만든 장치는 `i2c_unregister_device()`로 등록 해제할 수 있습니다. 명시적으로 호출하지 않아도 기반 I2C 버스가 제거되기 전에 자동 호출됩니다. 장치 드라이버 모델에서 자식 장치는 부모 버스보다 오래 존재할 수 없기 때문입니다.
시스템 설명에서 삭제까지의 일반 경로입니다.
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으로 빌드하면 호출될 일이 없으므로 컴파일러가 버립니다.
명시적 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` 콜백도 지원하지만 필요한 경우가 드물고 이미 폐기됐으므로 새 설계에서는 사용하지 않아야 합니다.
전원 전환과 시스템 종료에 사용할 콜백입니다.
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 <[email protected]>"
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`를 참조합니다.
단일 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()`를 제공합니다.
데이터 형식별 읽기·쓰기 API입니다.
사용자가 없어 i2c-core에서 제거된 함수는 `i2c_smbus_write_quick()`, `i2c_smbus_process_call()`, `i2c_smbus_block_process_call()`입니다. 필요해지면 나중에 다시 추가할 수 있습니다.
모든 트랜잭션은 실패 시 음수 errno를 반환합니다. 쓰기 트랜잭션은 성공 시 0, 읽기 트랜잭션은 읽은 값을 반환합니다. 블록 읽기는 예외적으로 읽은 값의 개수를 반환합니다. 블록 버퍼는 32바이트보다 길 필요가 없습니다.
실제 SMBus 프로토콜은 `smbus-protocol.rst`를 참조합니다.
장치 프로토콜과 어댑터 기능에 맞는 가장 구체적인 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)`가 있습니다. 특정 어댑터의 번호를 반환합니다.
어댑터 식별에 쓰는 함수입니다.
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);
요약·해설
writing-clients.rst:1-403I2C 장치 드라이버는 `i2c_driver`의 ID·probe·remove 콜백으로 기존 `i2c_client`에 바인딩합니다. 장치를 명시적으로 생성할 때는 주소 확실성에 맞는 API를 쓰고, 통신은 가능하면 모든 어댑터가 지원하는 SMBus 전용 함수를 우선합니다.
원문 분량과 핵심 검토 대상을 요약합니다.
문서의 주요 구현·사용 순서를 압축합니다.