요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
.. 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.
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.
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.
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.
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:
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.
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.
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`.
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(¬ifier, 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`.
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
-----------------------------
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
----------------------------------
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 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.
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 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.
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.
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.
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 functions and data structures
---------------------------------------------
.. kernel-doc:: include/media/v4l2-subdev.h
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가 복잡한 설정 대부분을 처리합니다.
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를 쉽게 추가할 수 있게 합니다.
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-137Sub-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는 자체 검사에 더해 이 기본 함수를 호출할 수도 있습니다.
등록 전 초기화와 파괴 전 정리를 대칭으로 수행합니다.
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-159V4L2 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 상호 작용은 같습니다.
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-185Synchronous 방식에서는 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`이 됩니다.
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-204Asynchronous 방식에서는 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에 접근할 수 있기 때문입니다.
모든 자원이 준비된 뒤에만 전역 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-227Bridge 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합니다.
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-247Asynchronous 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됩니다.
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-288Async 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하기 직전에 호출합니다.
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(¬ifier, 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 결과를 반환합니다.
단일 호출, 전체 호출과 오류 중단 호출을 목적에 맞게 선택합니다.
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에 직접 전달됩니다.
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-455Kernel `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 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-522I2C 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하면 이 순서를 항상 올바르게 지킬 수 있습니다.
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-563Bridge는 `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()`를 호출합니다.
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 때 해제합니다.
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-617ACTIVE와 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합니다.
명시적 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.
Multiplexed stream과 internal routing
633-640Sub-device driver는 `V4L2_SUBDEV_FL_STREAMS` flag를 설정해 multiplexed stream을 지원할 수 있습니다.
이 기능을 사용하려면 centrally managed active state, 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를 제공합니다.
V4L2 sub-device functions and data structures
---------------------------------------------
.. kernel-doc:: include/media/v4l2-subdev.h
요약과 해설
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 경로를 지켜야 합니다.