Documentation/driver-api/driver-model/driver.rst GitHub 원문 ↗

Linux 6.18.37 · Driver API

Device Drivers

struct device_driver 선언·등록과 probe, sync_state, remove·PM callback, sysfs attribute를 설명합니다.

Source pathDocumentation/driver-api/driver-model/driver.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

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

1. 요약·해설

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

요약과 해설

driver.rst:1-286

struct device_driver는 driver 전체를 나타내며 bus-specific outer structure에 embed할 수 있습니다. 조기 registration으로 core field를 초기화하고 probe/defer·sync_state·remove·suspend/resume callback과 driver sysfs attribute를 lifecycle 계약에 맞게 구현합니다.

2. 영어 원문 전체

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

원문 전체 펼치기
1 ==============
2 Device Drivers
3 ==============
4
5 See the kerneldoc for the struct device_driver.
6
7 Allocation
8 ~~~~~~~~~~
9
10 Device drivers are statically allocated structures. Though there may
11 be multiple devices in a system that a driver supports, struct
12 device_driver represents the driver as a whole (not a particular
13 device instance).
14
15 Initialization
16 ~~~~~~~~~~~~~~
17
18 The driver must initialize at least the name and bus fields. It should
19 also initialize the devclass field (when it arrives), so it may obtain
20 the proper linkage internally. It should also initialize as many of
21 the callbacks as possible, though each is optional.
22
23 Declaration
24 ~~~~~~~~~~~
25
26 As stated above, struct device_driver objects are statically
27 allocated. Below is an example declaration of the eepro100
28 driver. This declaration is hypothetical only; it relies on the driver
29 being converted completely to the new model::
30
31 static struct device_driver eepro100_driver = {
32 .name = "eepro100",
33 .bus = &pci_bus_type,
34
35 .probe = eepro100_probe,
36 .remove = eepro100_remove,
37 .suspend = eepro100_suspend,
38 .resume = eepro100_resume,
39 };
40
41 Most drivers will not be able to be converted completely to the new
42 model because the bus they belong to has a bus-specific structure with
43 bus-specific fields that cannot be generalized.
44
45 The most common example of this are device ID structures. A driver
46 typically defines an array of device IDs that it supports. The format
47 of these structures and the semantics for comparing device IDs are
48 completely bus-specific. Defining them as bus-specific entities would
49 sacrifice type-safety, so we keep bus-specific structures around.
50
51 Bus-specific drivers should include a generic struct device_driver in
52 the definition of the bus-specific driver. Like this::
53
54 struct pci_driver {
55 const struct pci_device_id *id_table;
56 struct device_driver driver;
57 };
58
59 A definition that included bus-specific fields would look like
60 (using the eepro100 driver again)::
61
62 static struct pci_driver eepro100_driver = {
63 .id_table = eepro100_pci_tbl,
64 .driver = {
65 .name = "eepro100",
66 .bus = &pci_bus_type,
67 .probe = eepro100_probe,
68 .remove = eepro100_remove,
69 .suspend = eepro100_suspend,
70 .resume = eepro100_resume,
71 },
72 };
73
74 Some may find the syntax of embedded struct initialization awkward or
75 even a bit ugly. So far, it's the best way we've found to do what we want...
76
77 Registration
78 ~~~~~~~~~~~~
79
80 ::
81
82 int driver_register(struct device_driver *drv);
83
84 The driver registers the structure on startup. For drivers that have
85 no bus-specific fields (i.e. don't have a bus-specific driver
86 structure), they would use driver_register and pass a pointer to their
87 struct device_driver object.
88
89 Most drivers, however, will have a bus-specific structure and will
90 need to register with the bus using something like pci_driver_register.
91
92 It is important that drivers register their driver structure as early as
93 possible. Registration with the core initializes several fields in the
94 struct device_driver object, including the reference count and the
95 lock. These fields are assumed to be valid at all times and may be
96 used by the device model core or the bus driver.
97
98
99 Transition Bus Drivers
100 ~~~~~~~~~~~~~~~~~~~~~~
101
102 By defining wrapper functions, the transition to the new model can be
103 made easier. Drivers can ignore the generic structure altogether and
104 let the bus wrapper fill in the fields. For the callbacks, the bus can
105 define generic callbacks that forward the call to the bus-specific
106 callbacks of the drivers.
107
108 This solution is intended to be only temporary. In order to get class
109 information in the driver, the drivers must be modified anyway. Since
110 converting drivers to the new model should reduce some infrastructural
111 complexity and code size, it is recommended that they are converted as
112 class information is added.
113
114 Access
115 ~~~~~~
116
117 Once the object has been registered, it may access the common fields of
118 the object, like the lock and the list of devices::
119
120 int driver_for_each_dev(struct device_driver *drv, void *data,
121 int (*callback)(struct device *dev, void *data));
122
123 The devices field is a list of all the devices that have been bound to
124 the driver. The LDM core provides a helper function to operate on all
125 the devices a driver controls. This helper locks the driver on each
126 node access, and does proper reference counting on each device as it
127 accesses it.
128
129
130 sysfs
131 ~~~~~
132
133 When a driver is registered, a sysfs directory is created in its
134 bus's directory. In this directory, the driver can export an interface
135 to userspace to control operation of the driver on a global basis;
136 e.g. toggling debugging output in the driver.
137
138 A future feature of this directory will be a 'devices' directory. This
139 directory will contain symlinks to the directories of devices it
140 supports.
141
142
143
144 Callbacks
145 ~~~~~~~~~
146
147 ::
148
149 int (*probe) (struct device *dev);
150
151 The probe() entry is called in task context, with the bus's rwsem locked
152 and the driver partially bound to the device. Drivers commonly use
153 container_of() to convert "dev" to a bus-specific type, both in probe()
154 and other routines. That type often provides device resource data, such
155 as pci_dev.resource[] or platform_device.resources, which is used in
156 addition to dev->platform_data to initialize the driver.
157
158 This callback holds the driver-specific logic to bind the driver to a
159 given device. That includes verifying that the device is present, that
160 it's a version the driver can handle, that driver data structures can
161 be allocated and initialized, and that any hardware can be initialized.
162 Drivers often store a pointer to their state with dev_set_drvdata().
163 When the driver has successfully bound itself to that device, then probe()
164 returns zero and the driver model code will finish its part of binding
165 the driver to that device.
166
167 A driver's probe() may return a negative errno value to indicate that
168 the driver did not bind to this device, in which case it should have
169 released all resources it allocated.
170
171 Optionally, probe() may return -EPROBE_DEFER if the driver depends on
172 resources that are not yet available (e.g., supplied by a driver that
173 hasn't initialized yet). The driver core will put the device onto the
174 deferred probe list and will try to call it again later. If a driver
175 must defer, it should return -EPROBE_DEFER as early as possible to
176 reduce the amount of time spent on setup work that will need to be
177 unwound and reexecuted at a later time.
178
179 .. warning::
180 -EPROBE_DEFER must not be returned if probe() has already created
181 child devices, even if those child devices are removed again
182 in a cleanup path. If -EPROBE_DEFER is returned after a child
183 device has been registered, it may result in an infinite loop of
184 .probe() calls to the same driver.
185
186 ::
187
188 void (*sync_state) (struct device *dev);
189
190 sync_state is called only once for a device. It's called when all the consumer
191 devices of the device have successfully probed. The list of consumers of the
192 device is obtained by looking at the device links connecting that device to its
193 consumer devices.
194
195 The first attempt to call sync_state() is made during late_initcall_sync() to
196 give firmware and drivers time to link devices to each other. During the first
197 attempt at calling sync_state(), if all the consumers of the device at that
198 point in time have already probed successfully, sync_state() is called right
199 away. If there are no consumers of the device during the first attempt, that
200 too is considered as "all consumers of the device have probed" and sync_state()
201 is called right away.
202
203 If during the first attempt at calling sync_state() for a device, there are
204 still consumers that haven't probed successfully, the sync_state() call is
205 postponed and reattempted in the future only when one or more consumers of the
206 device probe successfully. If during the reattempt, the driver core finds that
207 there are one or more consumers of the device that haven't probed yet, then
208 sync_state() call is postponed again.
209
210 A typical use case for sync_state() is to have the kernel cleanly take over
211 management of devices from the bootloader. For example, if a device is left on
212 and at a particular hardware configuration by the bootloader, the device's
213 driver might need to keep the device in the boot configuration until all the
214 consumers of the device have probed. Once all the consumers of the device have
215 probed, the device's driver can synchronize the hardware state of the device to
216 match the aggregated software state requested by all the consumers. Hence the
217 name sync_state().
218
219 While obvious examples of resources that can benefit from sync_state() include
220 resources such as regulator, sync_state() can also be useful for complex
221 resources like IOMMUs. For example, IOMMUs with multiple consumers (devices
222 whose addresses are remapped by the IOMMU) might need to keep their mappings
223 fixed at (or additive to) the boot configuration until all its consumers have
224 probed.
225
226 While the typical use case for sync_state() is to have the kernel cleanly take
227 over management of devices from the bootloader, the usage of sync_state() is
228 not restricted to that. Use it whenever it makes sense to take an action after
229 all the consumers of a device have probed::
230
231 int (*remove) (struct device *dev);
232
233 remove is called to unbind a driver from a device. This may be
234 called if a device is physically removed from the system, if the
235 driver module is being unloaded, during a reboot sequence, or
236 in other cases.
237
238 It is up to the driver to determine if the device is present or
239 not. It should free any resources allocated specifically for the
240 device; i.e. anything in the device's driver_data field.
241
242 If the device is still present, it should quiesce the device and place
243 it into a supported low-power state.
244
245 ::
246
247 int (*suspend) (struct device *dev, pm_message_t state);
248
249 suspend is called to put the device in a low power state.
250
251 ::
252
253 int (*resume) (struct device *dev);
254
255 Resume is used to bring a device back from a low power state.
256
257
258 Attributes
259 ~~~~~~~~~~
260
261 ::
262
263 struct driver_attribute {
264 struct attribute attr;
265 ssize_t (*show)(struct device_driver *driver, char *buf);
266 ssize_t (*store)(struct device_driver *, const char *buf, size_t count);
267 };
268
269 Device drivers can export attributes via their sysfs directories.
270 Drivers can declare attributes using a DRIVER_ATTR_RW and DRIVER_ATTR_RO
271 macro that works identically to the DEVICE_ATTR_RW and DEVICE_ATTR_RO
272 macros.
273
274 Example::
275
276 DRIVER_ATTR_RW(debug);
277
278 This is equivalent to declaring::
279
280 struct driver_attribute driver_attr_debug;
281
282 This can then be used to add and remove the attribute from the
283 driver's directory using::
284
285 int driver_create_file(struct device_driver *, const struct driver_attribute *);
286 void driver_remove_file(struct device_driver *, const struct driver_attribute *);
287

3. 한국어 전문 번역

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

Device driver 기본 구조

1-6

`struct device_driver`의 상세 정의는 해당 kerneldoc을 참고합니다.

정적 allocation

7-14

device driver는 statically allocated structure입니다. system에 한 driver가 지원하는 device가 여러 개 있을 수 있지만 `struct device_driver`는 특정 device instance가 아니라 driver 전체를 나타냅니다.

초기화 field

15-22

driver는 최소한 `name`과 `bus` field를 초기화해야 합니다. 적절한 internal linkage를 얻도록 제공되는 경우 `devclass` field도 초기화해야 하며, callback은 각각 optional이지만 가능한 한 많이 초기화하는 것이 좋습니다.

Generic과 bus-specific driver 선언

23-76

`struct device_driver` object는 정적으로 할당합니다. 다음은 eepro100 driver가 새 model로 완전히 변환되었다고 가정한 예제 선언입니다.

static struct device_driver eepro100_driver = {
       .name                = "eepro100",
       .bus                = &pci_bus_type,

       .probe                = eepro100_probe,
       .remove                = eepro100_remove,
       .suspend                = eepro100_suspend,
       .resume                = eepro100_resume,
};

대부분의 driver는 자신이 속한 bus가 일반화할 수 없는 bus-specific field를 가진 구조체를 사용하므로 새 model로 완전히 변환할 수 없습니다. 대표적인 예가 device ID 구조체입니다. driver는 보통 지원 ID 배열을 정의하며 형식과 비교 semantics가 완전히 bus-specific입니다. 이를 generic entity로 만들면 type safety를 잃으므로 bus-specific 구조체를 유지합니다.

bus-specific driver 정의에는 generic `struct device_driver`를 embedded member로 포함해야 합니다.

struct pci_driver {
       const struct pci_device_id *id_table;
       struct device_driver          driver;
};

eepro100의 bus-specific field까지 포함한 정의는 다음과 같습니다.

static struct pci_driver eepro100_driver = {
       .id_table       = eepro100_pci_tbl,
       .driver               = {
              .name                = "eepro100",
              .bus                = &pci_bus_type,
              .probe                = eepro100_probe,
              .remove                = eepro100_remove,
              .suspend        = eepro100_suspend,
              .resume                = eepro100_resume,
       },
};

embedded struct initializer syntax가 어색하거나 보기 좋지 않을 수 있지만 현재 목적을 달성하는 가장 좋은 방식입니다.

Generic driver embedding
LayerStructure / fieldRole
Bus-specificstruct pci_driverPCI ID table과 bus-specific state
Identityid_tableSupported struct pci_device_id array
Generic coredriver: struct device_drivername, bus, callbacks
Type safetyOuter bus structureBus-specific ID semantics 유지

bus-specific driver가 generic core object를 포함하는 구조입니다.

Driver 등록

77-98
::

  int driver_register(struct device_driver *drv);

driver는 startup 때 구조체를 등록합니다. bus-specific field가 없어 별도 bus driver 구조체가 없는 driver는 `driver_register()`에 `struct device_driver` pointer를 전달합니다. 그러나 대부분은 bus-specific 구조체를 가지므로 `pci_driver_register` 같은 bus registration function을 사용해야 합니다.

driver 구조체는 가능한 한 일찍 등록해야 합니다. core registration은 reference count와 lock을 포함한 `struct device_driver`의 여러 field를 초기화합니다. device model core와 bus driver는 이 field가 항상 유효하다고 가정하고 사용할 수 있습니다.

Driver registration 선택
static driver structurebus-specific fields?no: driver_register(struct device_driver *)yes: bus wrapper such as pci_driver_registercore initializes reference count and lock

generic과 bus-specific 등록 경로를 구분합니다.

Transition bus driver wrapper

99-113

wrapper function을 정의하면 새 model로 쉽게 전환할 수 있습니다. driver는 generic 구조체를 무시하고 bus wrapper가 field를 채우게 할 수 있습니다. callback에는 bus가 generic callback을 정의해 driver의 bus-specific callback으로 전달합니다.

이 solution은 임시 용도입니다. class 정보를 driver에 넣으려면 결국 driver를 수정해야 합니다. 새 model로 바꾸면 infrastructure complexity와 code size를 줄일 수 있으므로 class 정보를 추가할 때 함께 변환하는 것이 좋습니다.

Bound device 목록 접근

114-129

object를 등록한 뒤에는 lock과 device 목록 같은 common field에 접근할 수 있습니다.

int driver_for_each_dev(struct device_driver *drv, void *data,
                        int (*callback)(struct device *dev, void *data));

`devices` field는 driver에 bind된 모든 device 목록입니다. LDM core helper는 driver가 제어하는 모든 device에 작업을 수행합니다. 각 node에 접근할 때 driver를 lock하고 각 device에 올바른 reference counting을 적용합니다.

Driver sysfs directory

130-143

driver를 등록하면 그 bus directory 아래에 sysfs directory를 만듭니다. driver는 여기서 debugging output toggle처럼 driver 전체 동작을 제어하는 userspace interface를 export할 수 있습니다.

향후 이 directory에는 driver가 지원하는 device directory를 가리키는 symlink를 담는 `devices` directory가 추가될 예정입니다.

probe callback과 deferred probe

144-185
::

        int        (*probe)        (struct device *dev);

`probe()`는 task context에서 bus의 rwsem을 lock한 채 driver가 device에 부분적으로 bind된 상태에서 호출됩니다. driver는 `probe()`와 다른 routine에서 흔히 `container_of()`로 `dev`를 bus-specific type으로 변환합니다. 그 type은 `pci_dev.resource[]`나 `platform_device.resources` 같은 resource data를 제공하며 `dev->platform_data`와 함께 초기화에 사용합니다.

callback에는 device 존재·지원 version 확인, driver data structure allocation과 초기화, hardware 초기화 같은 device-specific binding logic이 들어갑니다. driver는 흔히 `dev_set_drvdata()`로 state pointer를 저장합니다. 성공하면 0을 반환하고 driver model이 나머지 binding을 완료합니다.

bind하지 못하면 negative errno를 반환하고 자신이 할당한 모든 resource를 release해야 합니다. 아직 사용할 수 없는 다른 driver 제공 resource에 의존하면 `-EPROBE_DEFER`를 반환할 수 있습니다. core는 device를 deferred probe list에 넣고 나중에 다시 시도합니다. defer가 필요하다면 되돌릴 setup work를 줄이기 위해 가능한 한 일찍 반환해야 합니다.

경고: `probe()`가 이미 child device를 만들었다면 cleanup path에서 child를 다시 제거하더라도 `-EPROBE_DEFER`를 반환하면 안 됩니다. child 등록 뒤 defer하면 같은 driver의 `.probe()`가 무한 반복(`infinite loop`)될 수 있습니다.

probe() 반환 결과
ReturnMeaningRequired action
0Successfully boundCore finishes binding
negative errnoDid not bindRelease all allocated resources
-EPROBE_DEFERDependency unavailableReturn early; core retries later
-EPROBE_DEFER after child registrationForbiddenAvoid infinite probe loop

binding 결과와 driver cleanup 책임을 정리했습니다.

sync_state callback

186-229
void        (*sync_state)        (struct device *dev);

`sync_state`는 device마다 한 번만 호출되며 device link로 연결된 모든 consumer device가 성공적으로 probe된 때 호출됩니다.

첫 시도는 firmware와 driver가 device link를 구성할 시간을 주기 위해 `late_initcall_sync()` 중에 합니다. 그 시점의 consumer가 모두 probe됐거나 consumer가 하나도 없으면 즉시 호출합니다.

아직 probe되지 않은 consumer가 있으면 호출을 미루고 이후 consumer 하나 이상이 성공적으로 probe될 때만 재시도합니다. 재시도 때도 미완료 consumer가 있으면 다시 미룹니다.

대표 용도는 bootloader에서 kernel로 device 관리를 안전하게 인계하는 것입니다. bootloader가 device를 켜고 특정 설정을 남긴 경우 모든 consumer가 probe될 때까지 그 boot 상태를 유지한 뒤 consumer가 요청한 aggregate software state에 hardware를 동기화합니다. regulator뿐 아니라 여러 consumer의 boot mapping을 유지해야 하는 IOMMU 같은 복잡한 resource에도 유용합니다.

bootloader 인계에만 제한되지 않으며 모든 consumer probe 뒤 수행해야 하는 action이라면 사용할 수 있습니다.

sync_state 호출 조건
late_initcall_sync first attemptcollect consumers from device linksall probed or none: call oncepending consumer: postponeconsumer probes successfullyrecheck until all complete

첫 시도와 지연 재시도 조건을 나타냅니다.

remove, suspend, resume callback

230-257
int         (*remove)        (struct device *dev);

`remove`는 device physical removal, driver module unload, reboot sequence 등의 상황에서 driver를 device에서 unbind할 때 호출됩니다. device 존재 여부는 driver가 판단하고 `driver_data` field 등 해당 device에 특별히 할당한 resource를 free해야 합니다. device가 남아 있다면 quiesce하고 지원되는 low-power state로 전환합니다.

int        (*suspend)        (struct device *dev, pm_message_t state);

`suspend`는 device를 low-power state로 전환합니다.

int        (*resume)        (struct device *dev);

`resume`은 device를 low-power state에서 복귀시킵니다.

Driver lifecycle callback
CallbackWhenDriver responsibility
probeBinding attemptValidate, allocate, initialize
sync_stateAll consumers probedSynchronize aggregate hardware state
removeUnbind/removal/rebootFree per-device resource, quiesce
suspendPower transition downEnter low-power state
resumePower transition upRestore operational state

주요 callback의 시점과 책임입니다.

Driver attribute

258-286
::

  struct driver_attribute {
          struct attribute        attr;
          ssize_t (*show)(struct device_driver *driver, char *buf);
          ssize_t (*store)(struct device_driver *, const char *buf, size_t count);
  };

device driver는 자신의 sysfs directory를 통해 attribute를 export할 수 있습니다. `DRIVER_ATTR_RW`와 `DRIVER_ATTR_RO` macro는 `DEVICE_ATTR_RW`와 `DEVICE_ATTR_RO`와 동일하게 동작합니다.

예시는 다음과 같습니다.

DRIVER_ATTR_RW(debug);

이는 다음 선언과 같습니다.

struct driver_attribute driver_attr_debug;

그 다음 아래 함수로 driver directory에 attribute를 추가하거나 제거합니다.

int driver_create_file(struct device_driver *, const struct driver_attribute *);
void driver_remove_file(struct device_driver *, const struct driver_attribute *);