Documentation/driver-api/media/v4l2-subdev.rst GitHub 원문 ↗

Linux 6.18.37 · Driver API

V4L2 sub-devices

V4L2 sub-device의 초기화, 동기·비동기 등록, notifier, userspace API, I2C helper와 managed state를 설명하는 전문 번역입니다.

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

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

1. 요약·해설

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

요약과 해설

v4l2-subdev.rst:1-644

`v4l2_subdev`는 bus 종류를 숨기고 bridge와 sensor·codec·controller 사이의 operation, media link, async matching과 state를 통합합니다. 등록 전에 모든 초기화와 runtime PM을 끝내고, notifier·entity·state마다 대응하는 unregister·cleanup 경로를 지켜야 합니다.

문서 구성
원문 줄내용
1-137구조·operation·media entity·link validation
138-204동기·비동기 등록
205-288Async notifier·sensor helper·callback
289-351Sub-device operation 호출
352-455Userspace·read-only API
456-563I2C driver·bridge helper
564-632Centrally managed state와 locking
633-644Multiplexed stream과 kernel-doc

2. 영어 원문 전체

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

원문 전체 펼치기
1 .. SPDX-License-Identifier: GPL-2.0
2
3 V4L2 sub-devices
4 ----------------
5
6 Many drivers need to communicate with sub-devices. These devices can do all
7 sort of tasks, but most commonly they handle audio and/or video muxing,
8 encoding or decoding. For webcams common sub-devices are sensors and camera
9 controllers.
10
11 Usually these are I2C devices, but not necessarily. In order to provide the
12 driver with a consistent interface to these sub-devices the
13 :c:type:`v4l2_subdev` struct (v4l2-subdev.h) was created.
14
15 Each sub-device driver must have a :c:type:`v4l2_subdev` struct. This struct
16 can be stand-alone for simple sub-devices or it might be embedded in a larger
17 struct if more state information needs to be stored. Usually there is a
18 low-level device struct (e.g. ``i2c_client``) that contains the device data as
19 setup by the kernel. It is recommended to store that pointer in the private
20 data of :c:type:`v4l2_subdev` using :c:func:`v4l2_set_subdevdata`. That makes
21 it easy to go from a :c:type:`v4l2_subdev` to the actual low-level bus-specific
22 device data.
23
24 You also need a way to go from the low-level struct to :c:type:`v4l2_subdev`.
25 For the common i2c_client struct the i2c_set_clientdata() call is used to store
26 a :c:type:`v4l2_subdev` pointer, for other buses you may have to use other
27 methods.
28
29 Bridges might also need to store per-subdev private data, such as a pointer to
30 bridge-specific per-subdev private data. The :c:type:`v4l2_subdev` structure
31 provides host private data for that purpose that can be accessed with
32 :c:func:`v4l2_get_subdev_hostdata` and :c:func:`v4l2_set_subdev_hostdata`.
33
34 From the bridge driver perspective, you load the sub-device module and somehow
35 obtain the :c:type:`v4l2_subdev` pointer. For i2c devices this is easy: you call
36 ``i2c_get_clientdata()``. For other buses something similar needs to be done.
37 Helper functions exist for sub-devices on an I2C bus that do most of this
38 tricky work for you.
39
40 Each :c:type:`v4l2_subdev` contains function pointers that sub-device drivers
41 can implement (or leave ``NULL`` if it is not applicable). Since sub-devices can
42 do so many different things and you do not want to end up with a huge ops struct
43 of which only a handful of ops are commonly implemented, the function pointers
44 are sorted according to category and each category has its own ops struct.
45
46 The top-level ops struct contains pointers to the category ops structs, which
47 may be NULL if the subdev driver does not support anything from that category.
48
49 It looks like this:
50
51 .. code-block:: c
52
53 struct v4l2_subdev_core_ops {
54 int (*log_status)(struct v4l2_subdev *sd);
55 int (*init)(struct v4l2_subdev *sd, u32 val);
56 ...
57 };
58
59 struct v4l2_subdev_tuner_ops {
60 ...
61 };
62
63 struct v4l2_subdev_audio_ops {
64 ...
65 };
66
67 struct v4l2_subdev_video_ops {
68 ...
69 };
70
71 struct v4l2_subdev_pad_ops {
72 ...
73 };
74
75 struct v4l2_subdev_ops {
76 const struct v4l2_subdev_core_ops *core;
77 const struct v4l2_subdev_tuner_ops *tuner;
78 const struct v4l2_subdev_audio_ops *audio;
79 const struct v4l2_subdev_video_ops *video;
80 const struct v4l2_subdev_pad_ops *video;
81 };
82
83 The core ops are common to all subdevs, the other categories are implemented
84 depending on the sub-device. E.g. a video device is unlikely to support the
85 audio ops and vice versa.
86
87 This setup limits the number of function pointers while still making it easy
88 to add new ops and categories.
89
90 A sub-device driver initializes the :c:type:`v4l2_subdev` struct using:
91
92 :c:func:`v4l2_subdev_init <v4l2_subdev_init>`
93 (:c:type:`sd <v4l2_subdev>`, &\ :c:type:`ops <v4l2_subdev_ops>`).
94
95
96 Afterwards you need to initialize :c:type:`sd <v4l2_subdev>`->name with a
97 unique name and set the module owner. This is done for you if you use the
98 i2c helper functions.
99
100 If integration with the media framework is needed, you must initialize the
101 :c:type:`media_entity` struct embedded in the :c:type:`v4l2_subdev` struct
102 (entity field) by calling :c:func:`media_entity_pads_init`, if the entity has
103 pads:
104
105 .. code-block:: c
106
107 struct media_pad *pads = &my_sd->pads;
108 int err;
109
110 err = media_entity_pads_init(&sd->entity, npads, pads);
111
112 The pads array must have been previously initialized. There is no need to
113 manually set the struct media_entity function and name fields, but the
114 revision field must be initialized if needed.
115
116 A reference to the entity will be automatically acquired/released when the
117 subdev device node (if any) is opened/closed.
118
119 Don't forget to cleanup the media entity before the sub-device is destroyed:
120
121 .. code-block:: c
122
123 media_entity_cleanup(&sd->entity);
124
125 If a sub-device driver implements sink pads, the subdev driver may set the
126 link_validate field in :c:type:`v4l2_subdev_pad_ops` to provide its own link
127 validation function. For every link in the pipeline, the link_validate pad
128 operation of the sink end of the link is called. In both cases the driver is
129 still responsible for validating the correctness of the format configuration
130 between sub-devices and video nodes.
131
132 If link_validate op is not set, the default function
133 :c:func:`v4l2_subdev_link_validate_default` is used instead. This function
134 ensures that width, height and the media bus pixel code are equal on both source
135 and sink of the link. Subdev drivers are also free to use this function to
136 perform the checks mentioned above in addition to their own checks.
137
138 Subdev registration
139 ~~~~~~~~~~~~~~~~~~~
140
141 There are currently two ways to register subdevices with the V4L2 core. The
142 first (traditional) possibility is to have subdevices registered by bridge
143 drivers. This can be done when the bridge driver has the complete information
144 about subdevices connected to it and knows exactly when to register them. This
145 is typically the case for internal subdevices, like video data processing units
146 within SoCs or complex PCI(e) boards, camera sensors in USB cameras or connected
147 to SoCs, which pass information about them to bridge drivers, usually in their
148 platform data.
149
150 There are however also situations where subdevices have to be registered
151 asynchronously to bridge devices. An example of such a configuration is a Device
152 Tree based system where information about subdevices is made available to the
153 system independently from the bridge devices, e.g. when subdevices are defined
154 in DT as I2C device nodes. The API used in this second case is described further
155 below.
156
157 Using one or the other registration method only affects the probing process, the
158 run-time bridge-subdevice interaction is in both cases the same.
159
160 Registering synchronous sub-devices
161 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
162
163 In the **synchronous** case a device (bridge) driver needs to register the
164 :c:type:`v4l2_subdev` with the v4l2_device:
165
166 :c:func:`v4l2_device_register_subdev <v4l2_device_register_subdev>`
167 (:c:type:`v4l2_dev <v4l2_device>`, :c:type:`sd <v4l2_subdev>`).
168
169 This can fail if the subdev module disappeared before it could be registered.
170 After this function was called successfully the subdev->dev field points to
171 the :c:type:`v4l2_device`.
172
173 If the v4l2_device parent device has a non-NULL mdev field, the sub-device
174 entity will be automatically registered with the media device.
175
176 You can unregister a sub-device using:
177
178 :c:func:`v4l2_device_unregister_subdev <v4l2_device_unregister_subdev>`
179 (:c:type:`sd <v4l2_subdev>`).
180
181 Afterwards the subdev module can be unloaded and
182 :c:type:`sd <v4l2_subdev>`->dev == ``NULL``.
183
184 .. _media-registering-async-subdevs:
185
186 Registering asynchronous sub-devices
187 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
188
189 In the **asynchronous** case subdevice probing can be invoked independently of
190 the bridge driver availability. The subdevice driver then has to verify whether
191 all the requirements for a successful probing are satisfied. This can include a
192 check for a master clock availability. If any of the conditions aren't satisfied
193 the driver might decide to return ``-EPROBE_DEFER`` to request further reprobing
194 attempts. Once all conditions are met the subdevice shall be registered using
195 the :c:func:`v4l2_async_register_subdev` function. Unregistration is
196 performed using the :c:func:`v4l2_async_unregister_subdev` call. Subdevices
197 registered this way are stored in a global list of subdevices, ready to be
198 picked up by bridge drivers.
199
200 Drivers must complete all initialization of the sub-device before
201 registering it using :c:func:`v4l2_async_register_subdev`, including
202 enabling runtime PM. This is because the sub-device becomes accessible
203 as soon as it gets registered.
204
205 Asynchronous sub-device notifiers
206 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
207
208 Bridge drivers in turn have to register a notifier object. This is performed
209 using the :c:func:`v4l2_async_nf_register` call. To unregister the notifier the
210 driver has to call :c:func:`v4l2_async_nf_unregister`. Before releasing memory
211 of an unregister notifier, it must be cleaned up by calling
212 :c:func:`v4l2_async_nf_cleanup`.
213
214 Before registering the notifier, bridge drivers must do two things: first, the
215 notifier must be initialized using the :c:func:`v4l2_async_nf_init`. Second,
216 bridge drivers can then begin to form a list of async connection descriptors
217 that the bridge device needs for its
218 operation. :c:func:`v4l2_async_nf_add_fwnode`,
219 :c:func:`v4l2_async_nf_add_fwnode_remote` and :c:func:`v4l2_async_nf_add_i2c`
220
221 Async connection descriptors describe connections to external sub-devices the
222 drivers for which are not yet probed. Based on an async connection, a media data
223 or ancillary link may be created when the related sub-device becomes
224 available. There may be one or more async connections to a given sub-device but
225 this is not known at the time of adding the connections to the notifier. Async
226 connections are bound as matching async sub-devices are found, one by one.
227
228 Asynchronous sub-device notifier for sub-devices
229 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
230
231 A driver that registers an asynchronous sub-device may also register an
232 asynchronous notifier. This is called an asynchronous sub-device notifier and the
233 process is similar to that of a bridge driver apart from that the notifier is
234 initialised using :c:func:`v4l2_async_subdev_nf_init` instead. A sub-device
235 notifier may complete only after the V4L2 device becomes available, i.e. there's
236 a path via async sub-devices and notifiers to a notifier that is not an
237 asynchronous sub-device notifier.
238
239 Asynchronous sub-device registration helper for camera sensor drivers
240 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
241
242 :c:func:`v4l2_async_register_subdev_sensor` is a helper function for sensor
243 drivers registering their own async connection, but it also registers a notifier
244 and further registers async connections for lens and flash devices found in
245 firmware. The notifier for the sub-device is unregistered and cleaned up with
246 the async sub-device, using :c:func:`v4l2_async_unregister_subdev`.
247
248 Asynchronous sub-device notifier example
249 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
250
251 These functions allocate an async connection descriptor which is of type struct
252 :c:type:`v4l2_async_connection` embedded in a driver-specific struct. The &struct
253 :c:type:`v4l2_async_connection` shall be the first member of this struct:
254
255 .. code-block:: c
256
257 struct my_async_connection {
258 struct v4l2_async_connection asc;
259 ...
260 };
261
262 struct my_async_connection *my_asc;
263 struct fwnode_handle *ep;
264
265 ...
266
267 my_asc = v4l2_async_nf_add_fwnode_remote(&notifier, ep,
268 struct my_async_connection);
269 fwnode_handle_put(ep);
270
271 if (IS_ERR(my_asc))
272 return PTR_ERR(my_asc);
273
274 Asynchronous sub-device notifier callbacks
275 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
276
277 The V4L2 core will then use these connection descriptors to match asynchronously
278 registered subdevices to them. If a match is detected the ``.bound()`` notifier
279 callback is called. After all connections have been bound the .complete()
280 callback is called. When a connection is removed from the system the
281 ``.unbind()`` method is called. All three callbacks are optional.
282
283 Drivers can store any type of custom data in their driver-specific
284 :c:type:`v4l2_async_connection` wrapper. If any of that data requires special
285 handling when the structure is freed, drivers must implement the ``.destroy()``
286 notifier callback. The framework will call it right before freeing the
287 :c:type:`v4l2_async_connection`.
288
289 Calling subdev operations
290 ~~~~~~~~~~~~~~~~~~~~~~~~~
291
292 The advantage of using :c:type:`v4l2_subdev` is that it is a generic struct and
293 does not contain any knowledge about the underlying hardware. So a driver might
294 contain several subdevs that use an I2C bus, but also a subdev that is
295 controlled through GPIO pins. This distinction is only relevant when setting
296 up the device, but once the subdev is registered it is completely transparent.
297
298 Once the subdev has been registered you can call an ops function either
299 directly:
300
301 .. code-block:: c
302
303 err = sd->ops->core->g_std(sd, &norm);
304
305 but it is better and easier to use this macro:
306
307 .. code-block:: c
308
309 err = v4l2_subdev_call(sd, core, g_std, &norm);
310
311 The macro will do the right ``NULL`` pointer checks and returns ``-ENODEV``
312 if :c:type:`sd <v4l2_subdev>` is ``NULL``, ``-ENOIOCTLCMD`` if either
313 :c:type:`sd <v4l2_subdev>`->core or :c:type:`sd <v4l2_subdev>`->core->g_std is ``NULL``, or the actual result of the
314 :c:type:`sd <v4l2_subdev>`->ops->core->g_std ops.
315
316 It is also possible to call all or a subset of the sub-devices:
317
318 .. code-block:: c
319
320 v4l2_device_call_all(v4l2_dev, 0, core, g_std, &norm);
321
322 Any subdev that does not support this ops is skipped and error results are
323 ignored. If you want to check for errors use this:
324
325 .. code-block:: c
326
327 err = v4l2_device_call_until_err(v4l2_dev, 0, core, g_std, &norm);
328
329 Any error except ``-ENOIOCTLCMD`` will exit the loop with that error. If no
330 errors (except ``-ENOIOCTLCMD``) occurred, then 0 is returned.
331
332 The second argument to both calls is a group ID. If 0, then all subdevs are
333 called. If non-zero, then only those whose group ID match that value will
334 be called. Before a bridge driver registers a subdev it can set
335 :c:type:`sd <v4l2_subdev>`->grp_id to whatever value it wants (it's 0 by
336 default). This value is owned by the bridge driver and the sub-device driver
337 will never modify or use it.
338
339 The group ID gives the bridge driver more control how callbacks are called.
340 For example, there may be multiple audio chips on a board, each capable of
341 changing the volume. But usually only one will actually be used when the
342 user want to change the volume. You can set the group ID for that subdev to
343 e.g. AUDIO_CONTROLLER and specify that as the group ID value when calling
344 ``v4l2_device_call_all()``. That ensures that it will only go to the subdev
345 that needs it.
346
347 If the sub-device needs to notify its v4l2_device parent of an event, then
348 it can call ``v4l2_subdev_notify(sd, notification, arg)``. This macro checks
349 whether there is a ``notify()`` callback defined and returns ``-ENODEV`` if not.
350 Otherwise the result of the ``notify()`` call is returned.
351
352 V4L2 sub-device userspace API
353 -----------------------------
354
355 Bridge drivers traditionally expose one or multiple video nodes to userspace,
356 and control subdevices through the :c:type:`v4l2_subdev_ops` operations in
357 response to video node operations. This hides the complexity of the underlying
358 hardware from applications. For complex devices, finer-grained control of the
359 device than what the video nodes offer may be required. In those cases, bridge
360 drivers that implement :ref:`the media controller API <media_controller>` may
361 opt for making the subdevice operations directly accessible from userspace.
362
363 Device nodes named ``v4l-subdev``\ *X* can be created in ``/dev`` to access
364 sub-devices directly. If a sub-device supports direct userspace configuration
365 it must set the ``V4L2_SUBDEV_FL_HAS_DEVNODE`` flag before being registered.
366
367 After registering sub-devices, the :c:type:`v4l2_device` driver can create
368 device nodes for all registered sub-devices marked with
369 ``V4L2_SUBDEV_FL_HAS_DEVNODE`` by calling
370 :c:func:`v4l2_device_register_subdev_nodes`. Those device nodes will be
371 automatically removed when sub-devices are unregistered.
372
373 The device node handles a subset of the V4L2 API.
374
375 ``VIDIOC_QUERYCTRL``,
376 ``VIDIOC_QUERYMENU``,
377 ``VIDIOC_G_CTRL``,
378 ``VIDIOC_S_CTRL``,
379 ``VIDIOC_G_EXT_CTRLS``,
380 ``VIDIOC_S_EXT_CTRLS`` and
381 ``VIDIOC_TRY_EXT_CTRLS``:
382
383 The controls ioctls are identical to the ones defined in V4L2. They
384 behave identically, with the only exception that they deal only with
385 controls implemented in the sub-device. Depending on the driver, those
386 controls can be also be accessed through one (or several) V4L2 device
387 nodes.
388
389 ``VIDIOC_DQEVENT``,
390 ``VIDIOC_SUBSCRIBE_EVENT`` and
391 ``VIDIOC_UNSUBSCRIBE_EVENT``
392
393 The events ioctls are identical to the ones defined in V4L2. They
394 behave identically, with the only exception that they deal only with
395 events generated by the sub-device. Depending on the driver, those
396 events can also be reported by one (or several) V4L2 device nodes.
397
398 Sub-device drivers that want to use events need to set the
399 ``V4L2_SUBDEV_FL_HAS_EVENTS`` :c:type:`v4l2_subdev`.flags before registering
400 the sub-device. After registration events can be queued as usual on the
401 :c:type:`v4l2_subdev`.devnode device node.
402
403 To properly support events, the ``poll()`` file operation is also
404 implemented.
405
406 Private ioctls
407
408 All ioctls not in the above list are passed directly to the sub-device
409 driver through the core::ioctl operation.
410
411 Read-only sub-device userspace API
412 ----------------------------------
413
414 Bridge drivers that control their connected subdevices through direct calls to
415 the kernel API realized by :c:type:`v4l2_subdev_ops` structure do not usually
416 want userspace to be able to change the same parameters through the subdevice
417 device node and thus do not usually register any.
418
419 It is sometimes useful to report to userspace the current subdevice
420 configuration through a read-only API, that does not permit applications to
421 change to the device parameters but allows interfacing to the subdevice device
422 node to inspect them.
423
424 For instance, to implement cameras based on computational photography, userspace
425 needs to know the detailed camera sensor configuration (in terms of skipping,
426 binning, cropping and scaling) for each supported output resolution. To support
427 such use cases, bridge drivers may expose the subdevice operations to userspace
428 through a read-only API.
429
430 To create a read-only device node for all the subdevices registered with the
431 ``V4L2_SUBDEV_FL_HAS_DEVNODE`` set, the :c:type:`v4l2_device` driver should call
432 :c:func:`v4l2_device_register_ro_subdev_nodes`.
433
434 Access to the following ioctls for userspace applications is restricted on
435 sub-device device nodes registered with
436 :c:func:`v4l2_device_register_ro_subdev_nodes`.
437
438 ``VIDIOC_SUBDEV_S_FMT``,
439 ``VIDIOC_SUBDEV_S_CROP``,
440 ``VIDIOC_SUBDEV_S_SELECTION``:
441
442 These ioctls are only allowed on a read-only subdevice device node
443 for the :ref:`V4L2_SUBDEV_FORMAT_TRY <v4l2-subdev-format-whence>`
444 formats and selection rectangles.
445
446 ``VIDIOC_SUBDEV_S_FRAME_INTERVAL``,
447 ``VIDIOC_SUBDEV_S_DV_TIMINGS``,
448 ``VIDIOC_SUBDEV_S_STD``:
449
450 These ioctls are not allowed on a read-only subdevice node.
451
452 In case the ioctl is not allowed, or the format to modify is set to
453 ``V4L2_SUBDEV_FORMAT_ACTIVE``, the core returns a negative error code and
454 the errno variable is set to ``-EPERM``.
455
456 I2C sub-device drivers
457 ----------------------
458
459 Since these drivers are so common, special helper functions are available to
460 ease the use of these drivers (``v4l2-common.h``).
461
462 The recommended method of adding :c:type:`v4l2_subdev` support to an I2C driver
463 is to embed the :c:type:`v4l2_subdev` struct into the state struct that is
464 created for each I2C device instance. Very simple devices have no state
465 struct and in that case you can just create a :c:type:`v4l2_subdev` directly.
466
467 A typical state struct would look like this (where 'chipname' is replaced by
468 the name of the chip):
469
470 .. code-block:: c
471
472 struct chipname_state {
473 struct v4l2_subdev sd;
474 ... /* additional state fields */
475 };
476
477 Initialize the :c:type:`v4l2_subdev` struct as follows:
478
479 .. code-block:: c
480
481 v4l2_i2c_subdev_init(&state->sd, client, subdev_ops);
482
483 This function will fill in all the fields of :c:type:`v4l2_subdev` ensure that
484 the :c:type:`v4l2_subdev` and i2c_client both point to one another.
485
486 You should also add a helper inline function to go from a :c:type:`v4l2_subdev`
487 pointer to a chipname_state struct:
488
489 .. code-block:: c
490
491 static inline struct chipname_state *to_state(struct v4l2_subdev *sd)
492 {
493 return container_of(sd, struct chipname_state, sd);
494 }
495
496 Use this to go from the :c:type:`v4l2_subdev` struct to the ``i2c_client``
497 struct:
498
499 .. code-block:: c
500
501 struct i2c_client *client = v4l2_get_subdevdata(sd);
502
503 And this to go from an ``i2c_client`` to a :c:type:`v4l2_subdev` struct:
504
505 .. code-block:: c
506
507 struct v4l2_subdev *sd = i2c_get_clientdata(client);
508
509 Make sure to call
510 :c:func:`v4l2_device_unregister_subdev`\ (:c:type:`sd <v4l2_subdev>`)
511 when the ``remove()`` callback is called. This will unregister the sub-device
512 from the bridge driver. It is safe to call this even if the sub-device was
513 never registered.
514
515 You need to do this because when the bridge driver destroys the i2c adapter
516 the ``remove()`` callbacks are called of the i2c devices on that adapter.
517 After that the corresponding v4l2_subdev structures are invalid, so they
518 have to be unregistered first. Calling
519 :c:func:`v4l2_device_unregister_subdev`\ (:c:type:`sd <v4l2_subdev>`)
520 from the ``remove()`` callback ensures that this is always done correctly.
521
522
523 The bridge driver also has some helper functions it can use:
524
525 .. code-block:: c
526
527 struct v4l2_subdev *sd = v4l2_i2c_new_subdev(v4l2_dev, adapter,
528 "module_foo", "chipid", 0x36, NULL);
529
530 This loads the given module (can be ``NULL`` if no module needs to be loaded)
531 and calls :c:func:`i2c_new_client_device` with the given ``i2c_adapter`` and
532 chip/address arguments. If all goes well, then it registers the subdev with
533 the v4l2_device.
534
535 You can also use the last argument of :c:func:`v4l2_i2c_new_subdev` to pass
536 an array of possible I2C addresses that it should probe. These probe addresses
537 are only used if the previous argument is 0. A non-zero argument means that you
538 know the exact i2c address so in that case no probing will take place.
539
540 Both functions return ``NULL`` if something went wrong.
541
542 Note that the chipid you pass to :c:func:`v4l2_i2c_new_subdev` is usually
543 the same as the module name. It allows you to specify a chip variant, e.g.
544 "saa7114" or "saa7115". In general though the i2c driver autodetects this.
545 The use of chipid is something that needs to be looked at more closely at a
546 later date. It differs between i2c drivers and as such can be confusing.
547 To see which chip variants are supported you can look in the i2c driver code
548 for the i2c_device_id table. This lists all the possibilities.
549
550 There are one more helper function:
551
552 :c:func:`v4l2_i2c_new_subdev_board` uses an :c:type:`i2c_board_info` struct
553 which is passed to the i2c driver and replaces the irq, platform_data and addr
554 arguments.
555
556 If the subdev supports the s_config core ops, then that op is called with
557 the irq and platform_data arguments after the subdev was setup.
558
559 The :c:func:`v4l2_i2c_new_subdev` function will call
560 :c:func:`v4l2_i2c_new_subdev_board`, internally filling a
561 :c:type:`i2c_board_info` structure using the ``client_type`` and the
562 ``addr`` to fill it.
563
564 Centrally managed subdev active state
565 -------------------------------------
566
567 Traditionally V4L2 subdev drivers maintained internal state for the active
568 device configuration. This is often implemented as e.g. an array of struct
569 v4l2_mbus_framefmt, one entry for each pad, and similarly for crop and compose
570 rectangles.
571
572 In addition to the active configuration, each subdev file handle has a struct
573 v4l2_subdev_state, managed by the V4L2 core, which contains the try
574 configuration.
575
576 To simplify the subdev drivers the V4L2 subdev API now optionally supports a
577 centrally managed active configuration represented by
578 :c:type:`v4l2_subdev_state`. One instance of state, which contains the active
579 device configuration, is stored in the sub-device itself as part of
580 the :c:type:`v4l2_subdev` structure, while the core associates a try state to
581 each open file handle, to store the try configuration related to that file
582 handle.
583
584 Sub-device drivers can opt-in and use state to manage their active configuration
585 by initializing the subdevice state with a call to v4l2_subdev_init_finalize()
586 before registering the sub-device. They must also call v4l2_subdev_cleanup()
587 to release all the allocated resources before unregistering the sub-device.
588 The core automatically allocates and initializes a state for each open file
589 handle to store the try configurations and frees it when closing the file
590 handle.
591
592 V4L2 sub-device operations that use both the :ref:`ACTIVE and TRY formats
593 <v4l2-subdev-format-whence>` receive the correct state to operate on through
594 the 'state' parameter. The state must be locked and unlocked by the
595 caller by calling :c:func:`v4l2_subdev_lock_state()` and
596 :c:func:`v4l2_subdev_unlock_state()`. The caller can do so by calling the subdev
597 operation through the :c:func:`v4l2_subdev_call_state_active()` macro.
598
599 Operations that do not receive a state parameter implicitly operate on the
600 subdevice active state, which drivers can exclusively access by
601 calling :c:func:`v4l2_subdev_lock_and_get_active_state()`. The sub-device active
602 state must equally be released by calling :c:func:`v4l2_subdev_unlock_state()`.
603
604 Drivers must never manually access the state stored in the :c:type:`v4l2_subdev`
605 or in the file handle without going through the designated helpers.
606
607 While the V4L2 core passes the correct try or active state to the subdevice
608 operations, many existing device drivers pass a NULL state when calling
609 operations with :c:func:`v4l2_subdev_call()`. This legacy construct causes
610 issues with subdevice drivers that let the V4L2 core manage the active state,
611 as they expect to receive the appropriate state as a parameter. To help the
612 conversion of subdevice drivers to a managed active state without having to
613 convert all callers at the same time, an additional wrapper layer has been
614 added to v4l2_subdev_call(), which handles the NULL case by getting and locking
615 the callee's active state with :c:func:`v4l2_subdev_lock_and_get_active_state()`,
616 and unlocking the state after the call.
617
618 The whole subdev state is in reality split into three parts: the
619 v4l2_subdev_state, subdev controls and subdev driver's internal state. In the
620 future these parts should be combined into a single state. For the time being
621 we need a way to handle the locking for these parts. This can be accomplished
622 by sharing a lock. The v4l2_ctrl_handler already supports this via its 'lock'
623 pointer and the same model is used with states. The driver can do the following
624 before calling v4l2_subdev_init_finalize():
625
626 .. code-block:: c
627
628 sd->ctrl_handler->lock = &priv->mutex;
629 sd->state_lock = &priv->mutex;
630
631 This shares the driver's private mutex between the controls and the states.
632
633 Streams, multiplexed media pads and internal routing
634 ----------------------------------------------------
635
636 A subdevice driver can implement support for multiplexed streams by setting
637 the V4L2_SUBDEV_FL_STREAMS subdev flag and implementing support for
638 centrally managed subdev active state, routing and stream based
639 configuration.
640
641 V4L2 sub-device functions and data structures
642 ---------------------------------------------
643
644 .. kernel-doc:: include/media/v4l2-subdev.h
645

3. 한국어 전문 번역

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

Sub-device 구조와 private data

1-38

많은 driver는 sub-device와 통신해야 합니다. Sub-device는 여러 작업을 할 수 있지만 주로 audio·video muxing, encoding, decoding을 담당하며 webcam에서는 sensor와 camera controller가 대표적입니다.

보통 I2C 장치이지만 반드시 그런 것은 아닙니다. Bus 종류와 무관하게 일관된 interface를 제공하기 위해 `v4l2-subdev.h`의 `v4l2_subdev` 구조체가 만들어졌습니다.

각 sub-device driver는 `v4l2_subdev`를 가져야 합니다. 단순 장치는 독립 구조체를 쓸 수 있고 상태가 더 필요하면 큰 driver 구조체 안에 포함할 수 있습니다.

Kernel이 설정한 장치 자료를 담는 `i2c_client` 같은 low-level 구조체가 보통 존재합니다. `v4l2_set_subdevdata()`로 그 pointer를 `v4l2_subdev`의 private data에 저장하면 subdev에서 bus 전용 장치 자료로 쉽게 이동할 수 있습니다.

반대 방향 연결도 필요합니다. 일반적인 `i2c_client`에는 `i2c_set_clientdata()`로 `v4l2_subdev` pointer를 저장하며, 다른 bus에서는 해당 bus에 맞는 방법을 사용합니다.

Bridge는 subdev별 bridge 전용 자료도 저장할 수 있습니다. `v4l2_get_subdev_hostdata()`와 `v4l2_set_subdev_hostdata()`가 제공하는 host private data를 사용합니다.

Bridge driver는 sub-device module을 load하고 `v4l2_subdev` pointer를 얻습니다. I2C 장치에서는 `i2c_get_clientdata()`를 사용하며 I2C helper가 복잡한 설정 대부분을 처리합니다.

Sub-device 양방향 연결
`v4l2_subdev``v4l2_set_subdevdata()``i2c_client` 등 low-level object
Low-level object`i2c_set_clientdata()``v4l2_subdev`
BridgeHost private data`v4l2_get/set_subdev_hostdata()`

Framework object, bus object와 bridge 전용 자료를 서로 찾을 수 있게 연결합니다.

.. SPDX-License-Identifier: GPL-2.0

V4L2 sub-devices
----------------

Many drivers need to communicate with sub-devices. These devices can do all
sort of tasks, but most commonly they handle audio and/or video muxing,
encoding or decoding. For webcams common sub-devices are sensors and camera
controllers.

Usually these are I2C devices, but not necessarily. In order to provide the
driver with a consistent interface to these sub-devices the
:c:type:`v4l2_subdev` struct (v4l2-subdev.h) was created.

Each sub-device driver must have a :c:type:`v4l2_subdev` struct. This struct
can be stand-alone for simple sub-devices or it might be embedded in a larger
struct if more state information needs to be stored. Usually there is a
low-level device struct (e.g. ``i2c_client``) that contains the device data as
setup by the kernel. It is recommended to store that pointer in the private
data of :c:type:`v4l2_subdev` using :c:func:`v4l2_set_subdevdata`. That makes
it easy to go from a :c:type:`v4l2_subdev` to the actual low-level bus-specific
device data.

You also need a way to go from the low-level struct to :c:type:`v4l2_subdev`.
For the common i2c_client struct the i2c_set_clientdata() call is used to store
a :c:type:`v4l2_subdev` pointer, for other buses you may have to use other
methods.

Bridges might also need to store per-subdev private data, such as a pointer to
bridge-specific per-subdev private data. The :c:type:`v4l2_subdev` structure
provides host private data for that purpose that can be accessed with
:c:func:`v4l2_get_subdev_hostdata` and :c:func:`v4l2_set_subdev_hostdata`.

From the bridge driver perspective, you load the sub-device module and somehow
obtain the :c:type:`v4l2_subdev` pointer. For i2c devices this is easy: you call
``i2c_get_clientdata()``. For other buses something similar needs to be done.
Helper functions exist for sub-devices on an I2C bus that do most of this
tricky work for you.

Sub-device operation 분류

39-89

각 `v4l2_subdev`에는 sub-device driver가 구현하거나 적용되지 않으면 `NULL`로 둘 function pointer가 있습니다.

Sub-device 기능이 매우 다양하므로 하나의 거대한 operation 구조체를 두지 않습니다. Function pointer는 category별 구조체로 나누며 top-level `v4l2_subdev_ops`가 각 category ops를 가리킵니다. 지원하지 않는 category pointer는 `NULL`일 수 있습니다.

`v4l2_subdev_core_ops`는 모든 subdev에 공통이며, tuner·audio·video·pad category는 장치 기능에 따라 선택적으로 구현합니다. Video 장치가 audio ops를 지원하거나 그 반대인 경우는 드뭅니다.

이 구성은 function pointer 수를 제한하면서 새 operation과 category를 쉽게 추가할 수 있게 합니다.

v4l2_subdev operation category
Category역할
`core`모든 sub-device의 공통 operation
`tuner`Tuner 제어
`audio`Audio 제어
`video`Video stream 제어
`pad`Pad format·routing 제어


Each :c:type:`v4l2_subdev` contains function pointers that sub-device drivers
can implement (or leave ``NULL`` if it is not applicable). Since sub-devices can
do so many different things and you do not want to end up with a huge ops struct
of which only a handful of ops are commonly implemented, the function pointers
are sorted according to category and each category has its own ops struct.

The top-level ops struct contains pointers to the category ops structs, which
may be NULL if the subdev driver does not support anything from that category.

It looks like this:

.. code-block:: c

        struct v4l2_subdev_core_ops {
                int (*log_status)(struct v4l2_subdev *sd);
                int (*init)(struct v4l2_subdev *sd, u32 val);
                ...
        };

        struct v4l2_subdev_tuner_ops {
                ...
        };

        struct v4l2_subdev_audio_ops {
                ...
        };

        struct v4l2_subdev_video_ops {
                ...
        };

        struct v4l2_subdev_pad_ops {
                ...
        };

        struct v4l2_subdev_ops {
                const struct v4l2_subdev_core_ops  *core;
                const struct v4l2_subdev_tuner_ops *tuner;
                const struct v4l2_subdev_audio_ops *audio;
                const struct v4l2_subdev_video_ops *video;
                const struct v4l2_subdev_pad_ops *video;
        };

The core ops are common to all subdevs, the other categories are implemented
depending on the sub-device. E.g. a video device is unlikely to support the
audio ops and vice versa.

This setup limits the number of function pointers while still making it easy
to add new ops and categories.

초기화, media entity와 link validation

90-137

Sub-device driver는 `v4l2_subdev_init(sd, &ops)`로 `v4l2_subdev`를 초기화합니다. 이후 `sd->name`에 고유 이름을 넣고 module owner를 지정해야 하며 I2C helper를 사용하면 이 작업은 자동으로 처리됩니다.

Media framework와 통합하고 entity에 pad가 있다면 `v4l2_subdev.entity`에 포함된 `media_entity`를 `media_entity_pads_init()`으로 초기화해야 합니다. Pad 배열은 미리 초기화되어 있어야 합니다.

`media_entity`의 function과 name은 수동 설정할 필요가 없지만 필요한 경우 revision field는 초기화해야 합니다. Subdev device node를 열고 닫을 때 entity reference는 자동으로 획득·해제됩니다.

Sub-device를 파괴하기 전에 `media_entity_cleanup(&sd->entity)`을 호출해야 합니다.

Sink pad를 구현한 driver는 `v4l2_subdev_pad_ops.link_validate`에 자체 link 검증 함수를 둘 수 있습니다. Pipeline의 각 link마다 sink 쪽 operation이 호출되며, driver는 sub-device와 video node 사이 format 구성이 올바른지 검증할 책임이 있습니다.

`link_validate`를 지정하지 않으면 `v4l2_subdev_link_validate_default()`가 source와 sink의 width, height, media bus pixel code가 같은지 확인합니다. Driver는 자체 검사에 더해 이 기본 함수를 호출할 수도 있습니다.

Sub-device 초기화와 media 정리
`v4l2_subdev_init()`이름·ownerPad 준비`media_entity_pads_init()`
Pipeline linkSink `link_validate`Format 일치 검사
파괴 전`media_entity_cleanup()`

등록 전 초기화와 파괴 전 정리를 대칭으로 수행합니다.

A sub-device driver initializes the :c:type:`v4l2_subdev` struct using:

        :c:func:`v4l2_subdev_init <v4l2_subdev_init>`
        (:c:type:`sd <v4l2_subdev>`, &\ :c:type:`ops <v4l2_subdev_ops>`).


Afterwards you need to initialize :c:type:`sd <v4l2_subdev>`->name with a
unique name and set the module owner. This is done for you if you use the
i2c helper functions.

If integration with the media framework is needed, you must initialize the
:c:type:`media_entity` struct embedded in the :c:type:`v4l2_subdev` struct
(entity field) by calling :c:func:`media_entity_pads_init`, if the entity has
pads:

.. code-block:: c

        struct media_pad *pads = &my_sd->pads;
        int err;

        err = media_entity_pads_init(&sd->entity, npads, pads);

The pads array must have been previously initialized. There is no need to
manually set the struct media_entity function and name fields, but the
revision field must be initialized if needed.

A reference to the entity will be automatically acquired/released when the
subdev device node (if any) is opened/closed.

Don't forget to cleanup the media entity before the sub-device is destroyed:

.. code-block:: c

        media_entity_cleanup(&sd->entity);

If a sub-device driver implements sink pads, the subdev driver may set the
link_validate field in :c:type:`v4l2_subdev_pad_ops` to provide its own link
validation function. For every link in the pipeline, the link_validate pad
operation of the sink end of the link is called. In both cases the driver is
still responsible for validating the correctness of the format configuration
between sub-devices and video nodes.

If link_validate op is not set, the default function
:c:func:`v4l2_subdev_link_validate_default` is used instead. This function
ensures that width, height and the media bus pixel code are equal on both source
and sink of the link. Subdev drivers are also free to use this function to
perform the checks mentioned above in addition to their own checks.

Sub-device 등록 방식

138-159

V4L2 core에 sub-device를 등록하는 방법은 두 가지입니다. 전통적인 synchronous 방식에서는 bridge driver가 연결된 sub-device의 전체 정보를 알고 정확한 등록 시점을 결정합니다.

SoC 내부 video processing unit, 복잡한 PCI·PCIe board의 내부 장치, USB camera나 SoC에 연결되어 platform data로 정보가 전달되는 camera sensor가 이에 해당합니다.

Device Tree에서 sub-device가 독립적인 I2C device node로 정의되는 경우처럼 bridge와 별도로 정보가 제공되면 asynchronous 등록이 필요합니다.

두 방식의 차이는 probing 과정에만 영향을 주며 runtime의 bridge와 sub-device 상호 작용은 같습니다.

Sub-device 등록 방식 비교
방식정보와 등록 주체Runtime 상호 작용
SynchronousBridge가 전체 연결과 시점을 앎동일
AsynchronousSub-device가 bridge와 독립적으로 probe동일

Subdev registration
~~~~~~~~~~~~~~~~~~~

There are currently two ways to register subdevices with the V4L2 core. The
first (traditional) possibility is to have subdevices registered by bridge
drivers. This can be done when the bridge driver has the complete information
about subdevices connected to it and knows exactly when to register them. This
is typically the case for internal subdevices, like video data processing units
within SoCs or complex PCI(e) boards, camera sensors in USB cameras or connected
to SoCs, which pass information about them to bridge drivers, usually in their
platform data.

There are however also situations where subdevices have to be registered
asynchronously to bridge devices. An example of such a configuration is a Device
Tree based system where information about subdevices is made available to the
system independently from the bridge devices, e.g. when subdevices are defined
in DT as I2C device nodes. The API used in this second case is described further
below.

Using one or the other registration method only affects the probing process, the
run-time bridge-subdevice interaction is in both cases the same.

Synchronous sub-device 등록

160-185

Synchronous 방식에서는 bridge driver가 `v4l2_device_register_subdev(v4l2_dev, sd)`로 `v4l2_subdev`를 `v4l2_device`에 등록합니다.

등록 전에 subdev module이 사라지면 실패할 수 있습니다. 성공 후 `subdev->dev`는 부모 `v4l2_device`를 가리킵니다.

부모 `v4l2_device.mdev`가 `NULL`이 아니면 sub-device entity도 Media device에 자동 등록됩니다.

등록 해제는 `v4l2_device_unregister_subdev(sd)`로 수행합니다. 이후 subdev module을 unload할 수 있고 `sd->dev`는 `NULL`이 됩니다.

Synchronous 등록 수명주기
Bridge probe`v4l2_device_register_subdev()``sd->dev = v4l2_device`
부모 `mdev` 존재Media entity 자동 등록
제거`v4l2_device_unregister_subdev()``sd->dev = NULL`

Bridge가 sub-device를 직접 등록하고 해제합니다.

Registering synchronous sub-devices
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

In the **synchronous** case a device (bridge) driver needs to register the
:c:type:`v4l2_subdev` with the v4l2_device:

        :c:func:`v4l2_device_register_subdev <v4l2_device_register_subdev>`
        (:c:type:`v4l2_dev <v4l2_device>`, :c:type:`sd <v4l2_subdev>`).

This can fail if the subdev module disappeared before it could be registered.
After this function was called successfully the subdev->dev field points to
the :c:type:`v4l2_device`.

If the v4l2_device parent device has a non-NULL mdev field, the sub-device
entity will be automatically registered with the media device.

You can unregister a sub-device using:

        :c:func:`v4l2_device_unregister_subdev <v4l2_device_unregister_subdev>`
        (:c:type:`sd <v4l2_subdev>`).

Afterwards the subdev module can be unloaded and
:c:type:`sd <v4l2_subdev>`->dev == ``NULL``.

.. _media-registering-async-subdevs:

Asynchronous sub-device 등록

186-204

Asynchronous 방식에서는 bridge driver의 준비 여부와 독립적으로 sub-device probe가 실행될 수 있습니다.

Sub-device driver는 master clock을 포함해 성공적인 probe에 필요한 모든 조건을 검사해야 합니다. 조건이 충족되지 않으면 `-EPROBE_DEFER`를 반환해 나중에 다시 probe하도록 요청할 수 있습니다.

조건이 모두 충족되면 `v4l2_async_register_subdev()`로 등록하고 `v4l2_async_unregister_subdev()`로 해제합니다. 이렇게 등록된 sub-device는 bridge가 선택할 수 있도록 전역 sub-device 목록에 저장됩니다.

Runtime PM 활성화를 포함한 모든 초기화는 `v4l2_async_register_subdev()` 전에 끝내야 합니다. 등록되는 즉시 sub-device에 접근할 수 있기 때문입니다.

Asynchronous sub-device probe
독립 probeClock·resource 검사
준비 안 됨`-EPROBE_DEFER`재시도
준비 완료Runtime PM 포함 초기화`v4l2_async_register_subdev()`전역 목록

모든 자원이 준비된 뒤에만 전역 matching 목록에 공개합니다.

Registering asynchronous sub-devices
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

In the **asynchronous** case subdevice probing can be invoked independently of
the bridge driver availability. The subdevice driver then has to verify whether
all the requirements for a successful probing are satisfied. This can include a
check for a master clock availability. If any of the conditions aren't satisfied
the driver might decide to return ``-EPROBE_DEFER`` to request further reprobing
attempts. Once all conditions are met the subdevice shall be registered using
the :c:func:`v4l2_async_register_subdev` function. Unregistration is
performed using the :c:func:`v4l2_async_unregister_subdev` call. Subdevices
registered this way are stored in a global list of subdevices, ready to be
picked up by bridge drivers.

Drivers must complete all initialization of the sub-device before
registering it using :c:func:`v4l2_async_register_subdev`, including
enabling runtime PM. This is because the sub-device becomes accessible
as soon as it gets registered.

Bridge asynchronous notifier

205-227

Bridge driver는 `v4l2_async_nf_register()`로 notifier object를 등록하고 `v4l2_async_nf_unregister()`로 해제합니다. Unregister한 notifier의 메모리를 풀기 전에 `v4l2_async_nf_cleanup()`으로 정리해야 합니다.

등록 전 `v4l2_async_nf_init()`으로 notifier를 초기화하고 bridge 동작에 필요한 async connection descriptor 목록을 만듭니다.

Connection은 `v4l2_async_nf_add_fwnode()`, `v4l2_async_nf_add_fwnode_remote()`, `v4l2_async_nf_add_i2c()`로 추가할 수 있습니다.

Async connection descriptor는 아직 driver가 probe되지 않은 외부 sub-device 연결을 설명합니다. 관련 sub-device가 준비되면 이를 바탕으로 media data link 또는 ancillary link를 만들 수 있습니다.

한 sub-device에 connection이 하나 이상 있을 수 있지만 notifier에 추가하는 시점에는 알 수 없습니다. 일치하는 async sub-device를 찾을 때마다 connection을 하나씩 bind합니다.

Bridge notifier 수명주기
`v4l2_async_nf_init()`Connection descriptor 추가`v4l2_async_nf_register()`
Matching sub-device 발견Connection bindMedia·ancillary link
해제`v4l2_async_nf_unregister()``v4l2_async_nf_cleanup()`

Notifier와 connection descriptor를 준비한 뒤 등록하고, 해제 시 cleanup까지 수행합니다.

Asynchronous sub-device notifiers
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Bridge drivers in turn have to register a notifier object. This is performed
using the :c:func:`v4l2_async_nf_register` call. To unregister the notifier the
driver has to call :c:func:`v4l2_async_nf_unregister`. Before releasing memory
of an unregister notifier, it must be cleaned up by calling
:c:func:`v4l2_async_nf_cleanup`.

Before registering the notifier, bridge drivers must do two things: first, the
notifier must be initialized using the :c:func:`v4l2_async_nf_init`.  Second,
bridge drivers can then begin to form a list of async connection descriptors
that the bridge device needs for its
operation. :c:func:`v4l2_async_nf_add_fwnode`,
:c:func:`v4l2_async_nf_add_fwnode_remote` and :c:func:`v4l2_async_nf_add_i2c`

Async connection descriptors describe connections to external sub-devices the
drivers for which are not yet probed. Based on an async connection, a media data
or ancillary link may be created when the related sub-device becomes
available. There may be one or more async connections to a given sub-device but
this is not known at the time of adding the connections to the notifier. Async
connections are bound as matching async sub-devices are found, one by one.

Sub-device notifier와 sensor helper

228-247

Asynchronous sub-device를 등록하는 driver도 자체 asynchronous notifier를 등록할 수 있습니다. 이 sub-device notifier는 bridge notifier와 비슷하지만 `v4l2_async_subdev_nf_init()`으로 초기화합니다.

Sub-device notifier는 async sub-device와 notifier 경로를 따라 일반 bridge notifier에 도달하고 V4L2 device가 준비된 뒤에만 complete될 수 있습니다.

`v4l2_async_register_subdev_sensor()`는 sensor driver용 helper입니다. Sensor 자체 async connection을 등록할 뿐 아니라 notifier도 등록하고 firmware에서 찾은 lens와 flash 장치의 async connection까지 추가합니다.

Sub-device notifier는 `v4l2_async_unregister_subdev()`로 async sub-device와 함께 unregister되고 cleanup됩니다.

Camera sensor async helper
Sensor driver`v4l2_async_register_subdev_sensor()`
Sensor async connectionSub-device notifier
Firmware lens·flash추가 async connection
V4L2 device 준비Notifier complete

Sensor, lens와 flash connection을 하나의 nested notifier 경로로 구성합니다.

Asynchronous sub-device notifier for sub-devices
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

A driver that registers an asynchronous sub-device may also register an
asynchronous notifier. This is called an asynchronous sub-device notifier and the
process is similar to that of a bridge driver apart from that the notifier is
initialised using :c:func:`v4l2_async_subdev_nf_init` instead. A sub-device
notifier may complete only after the V4L2 device becomes available, i.e. there's
a path via async sub-devices and notifiers to a notifier that is not an
asynchronous sub-device notifier.

Asynchronous sub-device registration helper for camera sensor drivers
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

:c:func:`v4l2_async_register_subdev_sensor` is a helper function for sensor
drivers registering their own async connection, but it also registers a notifier
and further registers async connections for lens and flash devices found in
firmware. The notifier for the sub-device is unregistered and cleaned up with
the async sub-device, using :c:func:`v4l2_async_unregister_subdev`.

Async connection wrapper와 callback

248-288

Async connection 추가 함수는 driver 전용 구조체에 포함된 `v4l2_async_connection` descriptor를 할당합니다. `v4l2_async_connection`은 이 wrapper 구조체의 첫 번째 member여야 합니다.

예제는 `v4l2_async_nf_add_fwnode_remote()`로 remote firmware endpoint connection을 notifier에 추가한 뒤 `fwnode_handle_put()`으로 endpoint reference를 반환합니다. 오류 pointer이면 `PTR_ERR()`를 반환합니다.

V4L2 core는 connection descriptor와 asynchronous 등록 sub-device를 match합니다. Match 시 선택적인 `.bound()` callback을 호출하고 모든 connection이 bind되면 `.complete()`를 호출합니다. Connection이 제거되면 `.unbind()`를 호출합니다.

Driver는 전용 `v4l2_async_connection` wrapper에 임의 자료를 저장할 수 있습니다. 구조체를 해제할 때 특별한 처리가 필요한 자료가 있으면 `.destroy()` callback을 구현해야 하며 framework가 descriptor를 free하기 직전에 호출합니다.

Async notifier callback
Callback호출 시점
`.bound()`Connection과 sub-device가 match됨
`.complete()`모든 connection이 bind됨
`.unbind()`Connection이 system에서 제거됨
`.destroy()`Connection wrapper를 free하기 직전

Asynchronous sub-device notifier example
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

These functions allocate an async connection descriptor which is of type struct
:c:type:`v4l2_async_connection` embedded in a driver-specific struct. The &struct
:c:type:`v4l2_async_connection` shall be the first member of this struct:

.. code-block:: c

        struct my_async_connection {
                struct v4l2_async_connection asc;
                ...
        };

        struct my_async_connection *my_asc;
        struct fwnode_handle *ep;

        ...

        my_asc = v4l2_async_nf_add_fwnode_remote(&notifier, ep,
                                                 struct my_async_connection);
        fwnode_handle_put(ep);

        if (IS_ERR(my_asc))
                return PTR_ERR(my_asc);

Asynchronous sub-device notifier callbacks
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The V4L2 core will then use these connection descriptors to match asynchronously
registered subdevices to them. If a match is detected the ``.bound()`` notifier
callback is called. After all connections have been bound the .complete()
callback is called. When a connection is removed from the system the
``.unbind()`` method is called. All three callbacks are optional.

Drivers can store any type of custom data in their driver-specific
:c:type:`v4l2_async_connection` wrapper. If any of that data requires special
handling when the structure is freed, drivers must implement the ``.destroy()``
notifier callback. The framework will call it right before freeing the
:c:type:`v4l2_async_connection`.

Sub-device operation 호출

289-351

`v4l2_subdev`는 underlying hardware를 모르는 일반 구조체입니다. 한 driver 안에 I2C subdev와 GPIO로 제어하는 subdev가 함께 있어도 등록 후에는 bus 차이가 투명해집니다.

등록된 subdev operation을 `sd->ops->core->g_std()`처럼 직접 호출할 수 있지만 `v4l2_subdev_call(sd, core, g_std, &norm)` macro가 더 안전하고 간단합니다.

Macro는 `NULL` pointer를 검사합니다. `sd`가 `NULL`이면 `-ENODEV`, category 또는 operation이 `NULL`이면 `-ENOIOCTLCMD`, 그 외에는 실제 operation 결과를 반환합니다.

`v4l2_device_call_all()`은 모든 sub-device 또는 group subset을 호출하며 지원하지 않는 operation은 건너뛰고 오류 결과도 무시합니다.

오류를 확인하려면 `v4l2_device_call_until_err()`를 사용합니다. `-ENOIOCTLCMD` 이외 오류가 발생하면 loop를 끝내고 그 오류를 반환하며, 그러한 오류가 없으면 0을 반환합니다.

두 호출의 두 번째 인자는 group ID입니다. 0이면 모든 subdev, 0이 아니면 `sd->grp_id`가 일치하는 subdev만 호출합니다. Bridge가 등록 전에 값을 설정하며 sub-device driver는 수정하거나 사용하지 않습니다.

예를 들어 여러 audio chip 중 실제 volume controller에만 `AUDIO_CONTROLLER` group을 지정하면 해당 subdev만 호출할 수 있습니다.

Sub-device가 부모 `v4l2_device`에 event를 알리려면 `v4l2_subdev_notify(sd, notification, arg)`를 사용합니다. `notify()` callback이 없으면 `-ENODEV`, 있으면 callback 결과를 반환합니다.

Sub-device operation dispatch
단일 subdev`v4l2_subdev_call()`NULL·operation 검사
전체·group`v4l2_device_call_all()`오류 무시
전체·group`v4l2_device_call_until_err()`첫 실제 오류에서 중단
부모 통지`v4l2_subdev_notify()``v4l2_device.notify()`

단일 호출, 전체 호출과 오류 중단 호출을 목적에 맞게 선택합니다.

Calling subdev operations
~~~~~~~~~~~~~~~~~~~~~~~~~

The advantage of using :c:type:`v4l2_subdev` is that it is a generic struct and
does not contain any knowledge about the underlying hardware. So a driver might
contain several subdevs that use an I2C bus, but also a subdev that is
controlled through GPIO pins. This distinction is only relevant when setting
up the device, but once the subdev is registered it is completely transparent.

Once the subdev has been registered you can call an ops function either
directly:

.. code-block:: c

        err = sd->ops->core->g_std(sd, &norm);

but it is better and easier to use this macro:

.. code-block:: c

        err = v4l2_subdev_call(sd, core, g_std, &norm);

The macro will do the right ``NULL`` pointer checks and returns ``-ENODEV``
if :c:type:`sd <v4l2_subdev>` is ``NULL``, ``-ENOIOCTLCMD`` if either
:c:type:`sd <v4l2_subdev>`->core or :c:type:`sd <v4l2_subdev>`->core->g_std is ``NULL``, or the actual result of the
:c:type:`sd <v4l2_subdev>`->ops->core->g_std ops.

It is also possible to call all or a subset of the sub-devices:

.. code-block:: c

        v4l2_device_call_all(v4l2_dev, 0, core, g_std, &norm);

Any subdev that does not support this ops is skipped and error results are
ignored. If you want to check for errors use this:

.. code-block:: c

        err = v4l2_device_call_until_err(v4l2_dev, 0, core, g_std, &norm);

Any error except ``-ENOIOCTLCMD`` will exit the loop with that error. If no
errors (except ``-ENOIOCTLCMD``) occurred, then 0 is returned.

The second argument to both calls is a group ID. If 0, then all subdevs are
called. If non-zero, then only those whose group ID match that value will
be called. Before a bridge driver registers a subdev it can set
:c:type:`sd <v4l2_subdev>`->grp_id to whatever value it wants (it's 0 by
default). This value is owned by the bridge driver and the sub-device driver
will never modify or use it.

The group ID gives the bridge driver more control how callbacks are called.
For example, there may be multiple audio chips on a board, each capable of
changing the volume. But usually only one will actually be used when the
user want to change the volume. You can set the group ID for that subdev to
e.g. AUDIO_CONTROLLER and specify that as the group ID value when calling
``v4l2_device_call_all()``. That ensures that it will only go to the subdev
that needs it.

If the sub-device needs to notify its v4l2_device parent of an event, then
it can call ``v4l2_subdev_notify(sd, notification, arg)``. This macro checks
whether there is a ``notify()`` callback defined and returns ``-ENODEV`` if not.
Otherwise the result of the ``notify()`` call is returned.

V4L2 sub-device userspace API

352-410

전통적으로 bridge driver는 하나 이상의 video node를 userspace에 노출하고, video node operation에 응답해 `v4l2_subdev_ops`로 sub-device를 제어합니다. 이 방식은 application에서 hardware 복잡성을 숨깁니다.

복잡한 장치에서 video node보다 세밀한 제어가 필요하면 Media Controller API를 구현한 bridge가 sub-device operation을 userspace에 직접 공개할 수 있습니다.

직접 접근 node는 `/dev/v4l-subdevX`입니다. Sub-device가 userspace 직접 설정을 지원하면 등록 전에 `V4L2_SUBDEV_FL_HAS_DEVNODE` flag를 설정해야 합니다. 등록 후 `v4l2_device_register_subdev_nodes()`를 호출하면 flag가 있는 모든 subdev node가 생성되고 unregister 시 자동 제거됩니다.

Subdev node의 control ioctl은 일반 V4L2와 동일하지만 해당 sub-device가 구현한 control만 처리합니다. Driver에 따라 같은 control을 하나 이상의 V4L2 video node에서도 접근할 수 있습니다.

Event ioctl도 일반 V4L2와 동일하지만 해당 sub-device가 만든 event만 처리합니다. Event를 쓰는 driver는 등록 전에 `v4l2_subdev.flags`에 `V4L2_SUBDEV_FL_HAS_EVENTS`를 설정해야 하며 등록 후 `v4l2_subdev.devnode`에 event를 queue합니다. Poll operation도 제공됩니다.

나열된 control·event ioctl 외의 private ioctl은 `core::ioctl` operation을 통해 sub-device driver에 직접 전달됩니다.

Sub-device devnode API
API 그룹범위
Control ioctl해당 sub-device control만 처리
Event ioctl해당 sub-device event만 처리
`poll()`Event 대기 지원
Private ioctl`core::ioctl`에 직접 전달

V4L2 sub-device userspace API
-----------------------------

Bridge drivers traditionally expose one or multiple video nodes to userspace,
and control subdevices through the :c:type:`v4l2_subdev_ops` operations in
response to video node operations. This hides the complexity of the underlying
hardware from applications. For complex devices, finer-grained control of the
device than what the video nodes offer may be required. In those cases, bridge
drivers that implement :ref:`the media controller API <media_controller>` may
opt for making the subdevice operations directly accessible from userspace.

Device nodes named ``v4l-subdev``\ *X* can be created in ``/dev`` to access
sub-devices directly. If a sub-device supports direct userspace configuration
it must set the ``V4L2_SUBDEV_FL_HAS_DEVNODE`` flag before being registered.

After registering sub-devices, the :c:type:`v4l2_device` driver can create
device nodes for all registered sub-devices marked with
``V4L2_SUBDEV_FL_HAS_DEVNODE`` by calling
:c:func:`v4l2_device_register_subdev_nodes`. Those device nodes will be
automatically removed when sub-devices are unregistered.

The device node handles a subset of the V4L2 API.

``VIDIOC_QUERYCTRL``,
``VIDIOC_QUERYMENU``,
``VIDIOC_G_CTRL``,
``VIDIOC_S_CTRL``,
``VIDIOC_G_EXT_CTRLS``,
``VIDIOC_S_EXT_CTRLS`` and
``VIDIOC_TRY_EXT_CTRLS``:

        The controls ioctls are identical to the ones defined in V4L2. They
        behave identically, with the only exception that they deal only with
        controls implemented in the sub-device. Depending on the driver, those
        controls can be also be accessed through one (or several) V4L2 device
        nodes.

``VIDIOC_DQEVENT``,
``VIDIOC_SUBSCRIBE_EVENT`` and
``VIDIOC_UNSUBSCRIBE_EVENT``

        The events ioctls are identical to the ones defined in V4L2. They
        behave identically, with the only exception that they deal only with
        events generated by the sub-device. Depending on the driver, those
        events can also be reported by one (or several) V4L2 device nodes.

        Sub-device drivers that want to use events need to set the
        ``V4L2_SUBDEV_FL_HAS_EVENTS`` :c:type:`v4l2_subdev`.flags before registering
        the sub-device. After registration events can be queued as usual on the
        :c:type:`v4l2_subdev`.devnode device node.

        To properly support events, the ``poll()`` file operation is also
        implemented.

Private ioctls

        All ioctls not in the above list are passed directly to the sub-device
        driver through the core::ioctl operation.

Read-only sub-device userspace API

411-455

Kernel `v4l2_subdev_ops`를 직접 호출해 sub-device를 제어하는 bridge는 보통 userspace가 같은 parameter를 바꾸지 못하게 하므로 subdev device node를 등록하지 않습니다.

그러나 application이 parameter를 변경하지 않고 현재 sub-device 구성을 조사하도록 read-only API를 제공하는 것이 유용할 수 있습니다.

Computational photography camera에서는 각 출력 해상도에 대한 sensor의 skipping, binning, cropping, scaling 구성을 userspace가 알아야 합니다. Bridge는 이런 용도로 read-only sub-device operation을 공개할 수 있습니다.

`V4L2_SUBDEV_FL_HAS_DEVNODE`가 설정된 모든 subdev에 read-only node를 만들려면 `v4l2_device_register_ro_subdev_nodes()`를 호출합니다.

`VIDIOC_SUBDEV_S_FMT`, `VIDIOC_SUBDEV_S_CROP`, `VIDIOC_SUBDEV_S_SELECTION`은 read-only node에서 `V4L2_SUBDEV_FORMAT_TRY` format과 selection rectangle에만 허용됩니다.

`VIDIOC_SUBDEV_S_FRAME_INTERVAL`, `VIDIOC_SUBDEV_S_DV_TIMINGS`, `VIDIOC_SUBDEV_S_STD`는 read-only node에서 허용되지 않습니다.

허용되지 않는 ioctl이거나 수정 대상 format이 `V4L2_SUBDEV_FORMAT_ACTIVE`이면 core가 음수 오류를 반환하고 errno는 `-EPERM`으로 설정됩니다.

Read-only subdev 제한
Operation허용 범위
S_FMT·S_CROP·S_SELECTION`V4L2_SUBDEV_FORMAT_TRY`만 허용
S_FRAME_INTERVAL·S_DV_TIMINGS·S_STD허용하지 않음
ACTIVE 변경 또는 금지 ioctl`-EPERM`

Read-only sub-device userspace API
----------------------------------

Bridge drivers that control their connected subdevices through direct calls to
the kernel API realized by :c:type:`v4l2_subdev_ops` structure do not usually
want userspace to be able to change the same parameters through the subdevice
device node and thus do not usually register any.

It is sometimes useful to report to userspace the current subdevice
configuration through a read-only API, that does not permit applications to
change to the device parameters but allows interfacing to the subdevice device
node to inspect them.

For instance, to implement cameras based on computational photography, userspace
needs to know the detailed camera sensor configuration (in terms of skipping,
binning, cropping and scaling) for each supported output resolution. To support
such use cases, bridge drivers may expose the subdevice operations to userspace
through a read-only API.

To create a read-only device node for all the subdevices registered with the
``V4L2_SUBDEV_FL_HAS_DEVNODE`` set, the :c:type:`v4l2_device` driver should call
:c:func:`v4l2_device_register_ro_subdev_nodes`.

Access to the following ioctls for userspace applications is restricted on
sub-device device nodes registered with
:c:func:`v4l2_device_register_ro_subdev_nodes`.

``VIDIOC_SUBDEV_S_FMT``,
``VIDIOC_SUBDEV_S_CROP``,
``VIDIOC_SUBDEV_S_SELECTION``:

        These ioctls are only allowed on a read-only subdevice device node
        for the :ref:`V4L2_SUBDEV_FORMAT_TRY <v4l2-subdev-format-whence>`
        formats and selection rectangles.

``VIDIOC_SUBDEV_S_FRAME_INTERVAL``,
``VIDIOC_SUBDEV_S_DV_TIMINGS``,
``VIDIOC_SUBDEV_S_STD``:

        These ioctls are not allowed on a read-only subdevice node.

In case the ioctl is not allowed, or the format to modify is set to
``V4L2_SUBDEV_FORMAT_ACTIVE``, the core returns a negative error code and
the errno variable is set to ``-EPERM``.

I2C sub-device driver 구조

456-522

I2C sub-device driver는 매우 흔하므로 `v4l2-common.h`에 전용 helper가 제공됩니다.

권장 방식은 I2C 장치 instance마다 만드는 state 구조체에 `v4l2_subdev`를 포함하는 것입니다. 상태가 없는 매우 단순한 장치는 `v4l2_subdev`를 직접 만들 수 있습니다.

`v4l2_i2c_subdev_init(&state->sd, client, subdev_ops)`은 subdev field를 채우고 `v4l2_subdev`와 `i2c_client`가 서로를 가리키게 합니다.

`v4l2_subdev` pointer에서 driver state로 이동하는 `to_state()` inline helper는 `container_of(sd, struct chipname_state, sd)`를 사용합니다.

Subdev에서 I2C client는 `v4l2_get_subdevdata(sd)`로, I2C client에서 subdev는 `i2c_get_clientdata(client)`로 얻습니다.

I2C driver의 `remove()` callback에서는 `v4l2_device_unregister_subdev(sd)`를 반드시 호출해야 합니다. 등록되지 않은 sub-device에 호출해도 안전합니다.

Bridge가 I2C adapter를 파괴하면 adapter의 I2C 장치 `remove()` callback들이 호출되고 그 뒤 해당 `v4l2_subdev`는 무효가 됩니다. Remove callback에서 먼저 unregister하면 이 순서를 항상 올바르게 지킬 수 있습니다.

I2C sub-device pointer 변환
`chipname_state``container_of()``v4l2_subdev`
`v4l2_subdev``v4l2_get_subdevdata()``i2c_client`
`i2c_client``i2c_get_clientdata()``v4l2_subdev`
`remove()``v4l2_device_unregister_subdev()`

Driver state, subdev와 I2C client 사이의 양방향 이동을 helper로 고정합니다.

I2C sub-device drivers
----------------------

Since these drivers are so common, special helper functions are available to
ease the use of these drivers (``v4l2-common.h``).

The recommended method of adding :c:type:`v4l2_subdev` support to an I2C driver
is to embed the :c:type:`v4l2_subdev` struct into the state struct that is
created for each I2C device instance. Very simple devices have no state
struct and in that case you can just create a :c:type:`v4l2_subdev` directly.

A typical state struct would look like this (where 'chipname' is replaced by
the name of the chip):

.. code-block:: c

        struct chipname_state {
                struct v4l2_subdev sd;
                ...  /* additional state fields */
        };

Initialize the :c:type:`v4l2_subdev` struct as follows:

.. code-block:: c

        v4l2_i2c_subdev_init(&state->sd, client, subdev_ops);

This function will fill in all the fields of :c:type:`v4l2_subdev` ensure that
the :c:type:`v4l2_subdev` and i2c_client both point to one another.

You should also add a helper inline function to go from a :c:type:`v4l2_subdev`
pointer to a chipname_state struct:

.. code-block:: c

        static inline struct chipname_state *to_state(struct v4l2_subdev *sd)
        {
                return container_of(sd, struct chipname_state, sd);
        }

Use this to go from the :c:type:`v4l2_subdev` struct to the ``i2c_client``
struct:

.. code-block:: c

        struct i2c_client *client = v4l2_get_subdevdata(sd);

And this to go from an ``i2c_client`` to a :c:type:`v4l2_subdev` struct:

.. code-block:: c

        struct v4l2_subdev *sd = i2c_get_clientdata(client);

Make sure to call
:c:func:`v4l2_device_unregister_subdev`\ (:c:type:`sd <v4l2_subdev>`)
when the ``remove()`` callback is called. This will unregister the sub-device
from the bridge driver. It is safe to call this even if the sub-device was
never registered.

You need to do this because when the bridge driver destroys the i2c adapter
the ``remove()`` callbacks are called of the i2c devices on that adapter.
After that the corresponding v4l2_subdev structures are invalid, so they
have to be unregistered first. Calling
:c:func:`v4l2_device_unregister_subdev`\ (:c:type:`sd <v4l2_subdev>`)
from the ``remove()`` callback ensures that this is always done correctly.

Bridge I2C sub-device helper

523-563

Bridge는 `v4l2_i2c_new_subdev(v4l2_dev, adapter, module, chipid, addr, probe_addrs)` helper를 사용할 수 있습니다.

이 함수는 필요한 module을 load하고 `i2c_adapter`와 chip·address 인자로 `i2c_new_client_device()`를 호출합니다. 성공하면 subdev를 `v4l2_device`에 등록합니다.

마지막 인자로 probe할 I2C 주소 배열을 전달할 수 있으며 직전 address 인자가 0일 때만 사용합니다. 정확한 주소를 나타내는 0이 아닌 값을 주면 probing하지 않습니다. 오류가 나면 `NULL`을 반환합니다.

`chipid`는 보통 module 이름과 같지만 `saa7114`, `saa7115`처럼 chip variant를 지정할 수 있습니다. Driver가 자동 감지하는 경우가 많고 driver마다 사용 방식이 달라 혼동될 수 있습니다. 지원 variant는 I2C driver의 `i2c_device_id` table에서 확인합니다.

`v4l2_i2c_new_subdev_board()`는 IRQ, platform_data, address 인자를 대신하는 `i2c_board_info`를 사용합니다.

Subdev가 `s_config` core operation을 지원하면 설정 후 IRQ와 platform_data를 전달해 호출합니다. `v4l2_i2c_new_subdev()`는 내부적으로 client type과 address로 `i2c_board_info`를 채워 `v4l2_i2c_new_subdev_board()`를 호출합니다.

Bridge의 I2C subdev 생성
`v4l2_i2c_new_subdev()`Module load`i2c_new_client_device()`Subdev 등록
정확한 address직접 생성
Address 0후보 배열 probe
Board info`v4l2_i2c_new_subdev_board()`선택적 `s_config`

Module load부터 client 생성과 V4L2 등록까지 helper가 이어서 처리합니다.

The bridge driver also has some helper functions it can use:

.. code-block:: c

        struct v4l2_subdev *sd = v4l2_i2c_new_subdev(v4l2_dev, adapter,
                                        "module_foo", "chipid", 0x36, NULL);

This loads the given module (can be ``NULL`` if no module needs to be loaded)
and calls :c:func:`i2c_new_client_device` with the given ``i2c_adapter`` and
chip/address arguments. If all goes well, then it registers the subdev with
the v4l2_device.

You can also use the last argument of :c:func:`v4l2_i2c_new_subdev` to pass
an array of possible I2C addresses that it should probe. These probe addresses
are only used if the previous argument is 0. A non-zero argument means that you
know the exact i2c address so in that case no probing will take place.

Both functions return ``NULL`` if something went wrong.

Note that the chipid you pass to :c:func:`v4l2_i2c_new_subdev` is usually
the same as the module name. It allows you to specify a chip variant, e.g.
"saa7114" or "saa7115". In general though the i2c driver autodetects this.
The use of chipid is something that needs to be looked at more closely at a
later date. It differs between i2c drivers and as such can be confusing.
To see which chip variants are supported you can look in the i2c driver code
for the i2c_device_id table. This lists all the possibilities.

There are one more helper function:

:c:func:`v4l2_i2c_new_subdev_board` uses an :c:type:`i2c_board_info` struct
which is passed to the i2c driver and replaces the irq, platform_data and addr
arguments.

If the subdev supports the s_config core ops, then that op is called with
the irq and platform_data arguments after the subdev was setup.

The :c:func:`v4l2_i2c_new_subdev` function will call
:c:func:`v4l2_i2c_new_subdev_board`, internally filling a
:c:type:`i2c_board_info` structure using the ``client_type`` and the
``addr`` to fill it.

Centrally managed active state

564-590

전통적으로 V4L2 subdev driver는 active 장치 구성을 자체 상태로 관리했습니다. 흔히 pad마다 하나의 `v4l2_mbus_framefmt` 배열을 두고 crop·compose rectangle도 비슷하게 보관합니다.

Active 구성 외에도 각 subdev file handle에는 V4L2 core가 관리하는 `v4l2_subdev_state`가 있으며 TRY 구성을 담습니다.

Driver 단순화를 위해 V4L2 subdev API는 선택적으로 중앙 관리 active configuration을 지원합니다. Active state 하나는 `v4l2_subdev` 자체에 저장되고, core는 각 open file handle에 별도 TRY state를 연결합니다.

Driver는 sub-device 등록 전에 `v4l2_subdev_init_finalize()`를 호출해 state를 초기화함으로써 이 방식에 참여합니다. Unregister 전에 `v4l2_subdev_cleanup()`을 호출해 할당 자원을 해제해야 합니다.

Core는 각 open file handle의 TRY state를 자동으로 할당·초기화하며 close 때 해제합니다.

Subdev state 배치
State소유 위치수명
ACTIVE`v4l2_subdev`Sub-device 등록 수명
TRY각 open file handleOpen부터 close까지 core가 관리
초기화·정리`v4l2_subdev_init_finalize()`·`v4l2_subdev_cleanup()`등록 전·해제 전

Centrally managed subdev active state
-------------------------------------

Traditionally V4L2 subdev drivers maintained internal state for the active
device configuration. This is often implemented as e.g. an array of struct
v4l2_mbus_framefmt, one entry for each pad, and similarly for crop and compose
rectangles.

In addition to the active configuration, each subdev file handle has a struct
v4l2_subdev_state, managed by the V4L2 core, which contains the try
configuration.

To simplify the subdev drivers the V4L2 subdev API now optionally supports a
centrally managed active configuration represented by
:c:type:`v4l2_subdev_state`. One instance of state, which contains the active
device configuration, is stored in the sub-device itself as part of
the :c:type:`v4l2_subdev` structure, while the core associates a try state to
each open file handle, to store the try configuration related to that file
handle.

Sub-device drivers can opt-in and use state to manage their active configuration
by initializing the subdevice state with a call to v4l2_subdev_init_finalize()
before registering the sub-device. They must also call v4l2_subdev_cleanup()
to release all the allocated resources before unregistering the sub-device.
The core automatically allocates and initializes a state for each open file
handle to store the try configurations and frees it when closing the file
handle.

Subdev state locking과 legacy NULL

591-617

ACTIVE와 TRY format을 모두 사용하는 sub-device operation은 `state` 인자로 올바른 state를 받습니다. Caller가 `v4l2_subdev_lock_state()`와 `v4l2_subdev_unlock_state()`로 lock해야 하며 `v4l2_subdev_call_state_active()` macro가 이를 수행할 수 있습니다.

State 인자가 없는 operation은 암묵적으로 active state에서 동작합니다. Driver는 `v4l2_subdev_lock_and_get_active_state()`로 독점 접근하고 `v4l2_subdev_unlock_state()`로 해제해야 합니다.

Driver는 지정 helper를 거치지 않고 `v4l2_subdev`나 file handle에 저장된 state를 직접 접근해서는 안 됩니다.

기존 caller 중에는 `v4l2_subdev_call()`로 state 기반 operation을 호출하면서 `NULL` state를 전달하는 경우가 많습니다. Core가 active state를 관리하는 driver는 올바른 state 인자를 기대하므로 문제가 됩니다.

모든 caller를 동시에 바꾸지 않고 managed state로 전환할 수 있도록 `v4l2_subdev_call()` wrapper가 `NULL`을 처리합니다. Callee의 active state를 `v4l2_subdev_lock_and_get_active_state()`로 얻어 lock하고 호출 뒤 unlock합니다.

Operation별 state 획득
ACTIVE·TRY operation`state` 인자`v4l2_subdev_lock_state()`호출Unlock
State 인자 없음`v4l2_subdev_lock_and_get_active_state()`호출Unlock
Legacy NULL`v4l2_subdev_call()` wrapperActive state 획득·lock호출·unlock

명시적 state와 legacy NULL 호출 모두 lock된 올바른 state로 수렴합니다.


V4L2 sub-device operations that use both the :ref:`ACTIVE and TRY formats
<v4l2-subdev-format-whence>` receive the correct state to operate on through
the 'state' parameter. The state must be locked and unlocked by the
caller by calling :c:func:`v4l2_subdev_lock_state()` and
:c:func:`v4l2_subdev_unlock_state()`. The caller can do so by calling the subdev
operation through the :c:func:`v4l2_subdev_call_state_active()` macro.

Operations that do not receive a state parameter implicitly operate on the
subdevice active state, which drivers can exclusively access by
calling :c:func:`v4l2_subdev_lock_and_get_active_state()`. The sub-device active
state must equally be released by calling :c:func:`v4l2_subdev_unlock_state()`.

Drivers must never manually access the state stored in the :c:type:`v4l2_subdev`
or in the file handle without going through the designated helpers.

While the V4L2 core passes the correct try or active state to the subdevice
operations, many existing device drivers pass a NULL state when calling
operations with :c:func:`v4l2_subdev_call()`. This legacy construct causes
issues with subdevice drivers that let the V4L2 core manage the active state,
as they expect to receive the appropriate state as a parameter. To help the
conversion of subdevice drivers to a managed active state without having to
convert all callers at the same time, an additional wrapper layer has been
added to v4l2_subdev_call(), which handles the NULL case by getting and locking
the callee's active state with :c:func:`v4l2_subdev_lock_and_get_active_state()`,
and unlocking the state after the call.

State·control·driver 상태의 공유 lock

618-632

전체 subdev state는 실제로 `v4l2_subdev_state`, subdev control, subdev driver 내부 상태의 세 부분으로 나뉩니다. 미래에는 하나의 state로 합쳐야 하지만 현재는 세 부분의 locking을 조정해야 합니다.

이를 위해 하나의 lock을 공유할 수 있습니다. `v4l2_ctrl_handler`의 `lock` pointer와 state의 `state_lock`에 같은 driver private mutex를 지정합니다.

이 설정은 `v4l2_subdev_init_finalize()`를 호출하기 전에 수행하며 control과 state가 같은 mutex 아래에서 직렬화됩니다.

공유 mutex
`priv->mutex``sd->ctrl_handler->lock`
`priv->mutex``sd->state_lock`
공유 lock`v4l2_subdev_init_finalize()`

분리된 control·state·driver 내부 상태를 하나의 lock domain으로 묶습니다.

The whole subdev state is in reality split into three parts: the
v4l2_subdev_state, subdev controls and subdev driver's internal state. In the
future these parts should be combined into a single state. For the time being
we need a way to handle the locking for these parts. This can be accomplished
by sharing a lock. The v4l2_ctrl_handler already supports this via its 'lock'
pointer and the same model is used with states. The driver can do the following
before calling v4l2_subdev_init_finalize():

.. code-block:: c

        sd->ctrl_handler->lock = &priv->mutex;
        sd->state_lock = &priv->mutex;

This shares the driver's private mutex between the controls and the states.

Multiplexed stream과 internal routing

633-640

Sub-device driver는 `V4L2_SUBDEV_FL_STREAMS` flag를 설정해 multiplexed stream을 지원할 수 있습니다.

이 기능을 사용하려면 centrally managed active state, routing과 stream 기반 configuration도 구현해야 합니다.

Multiplexed stream 요구사항
요구사항설정
Stream 기능 표시`V4L2_SUBDEV_FL_STREAMS`
구성 관리Centrally managed active state
경로 제어Internal routing
형식 관리Stream 기반 configuration

Streams, multiplexed media pads and internal routing
----------------------------------------------------

A subdevice driver can implement support for multiplexed streams by setting
the V4L2_SUBDEV_FL_STREAMS subdev flag and implementing support for
centrally managed subdev active state, routing and stream based
configuration.

V4L2 sub-device 함수와 자료구조

641-644

`include/media/v4l2-subdev.h`의 kernel-doc에서 V4L2 sub-device 함수와 자료구조의 상세 API를 제공합니다.

API 정의 위치
Header내용
`include/media/v4l2-subdev.h`V4L2 sub-device 함수·자료구조

V4L2 sub-device functions and data structures
---------------------------------------------

.. kernel-doc:: include/media/v4l2-subdev.h