# Media devices

---

# Media subsystem kernel internal API

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> This section contains usage information about media subsystem and its supported drivers.

<a id="rst-media-subsystem-kernel-internal-api"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

This section contains usage information about media subsystem and its supported drivers.

Please see:

[Documentation/admin-guide/media/index.rst](/kernel/administration/admin-guide/media/index.md)

> - for usage information about media subsystem and supported drivers;

[Documentation/userspace-api/media/index.rst](/kernel/userspace/userspace-api/media/index.md)

> - for the userspace APIs used on media devices.

**Table of Contents**

1. [Media Subsystem Profile](</kernel/hardware/driver-api/media/maintainer-entry-profile.md>)
2. [Video4Linux devices](</kernel/hardware/driver-api/media/v4l2-core.md>)
3. [Digital TV (DVB) devices](</kernel/hardware/driver-api/media/dtv-core.md>)
4. [Remote Controller devices](</kernel/hardware/driver-api/media/rc-core.md>)
5. [Media Controller devices](</kernel/hardware/driver-api/media/mc-core.md>)
6. [CEC Kernel Support](</kernel/hardware/driver-api/media/cec-core.md>)
7. [Pixel data transmitter and receiver drivers](</kernel/hardware/driver-api/media/tx-rx.md>)
8. [Writing camera sensor drivers](</kernel/hardware/driver-api/media/camera-sensor.md>)
9. [Media driver-specific documentation](</kernel/hardware/driver-api/media-drivers/index.md>)

**Copyright** © 2009-2020 : LinuxTV Developers



```text
This documentation is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your option) any
later version.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.

For more details see the file COPYING in the source distribution of Linux.
```

---

# Writing camera sensor drivers

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> This document covers the in-kernel APIs only. For the best practices on userspace API implementation in camera sensor drivers, please see media_using_camera_sensor_drivers.

<a id="rst-writing-camera-sensor-drivers"></a>
<a id="rst-media-writing-camera-sensor-drivers"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document covers the in-kernel APIs only. For the best practices on userspace API implementation in camera sensor drivers, please see [Using camera sensor drivers](</kernel/userspace/userspace-api/media-drivers/camera-sensor.md#rst-media-using-camera-sensor-drivers>).

<a id="rst-csi-2-parallel-and-bt-656-buses"></a>

## CSI-2, parallel and BT.656 buses

Please see [Pixel data transmitter and receiver drivers](</kernel/hardware/driver-api/media/tx-rx.md#rst-transmitter-receiver>).

<a id="rst-handling-clocks"></a>

## Handling clocks

Camera sensors have an internal clock tree including a PLL and a number of divisors. The clock tree is generally configured by the driver based on a few input parameters that are specific to the hardware: the external clock frequency and the link frequency. The two parameters generally are obtained from system firmware. **No other frequencies should be used in any circumstances.**

The reason why the clock frequencies are so important is that the clock signals come out of the SoC, and in many cases a specific frequency is designed to be used in the system. Using another frequency may cause harmful effects elsewhere. Therefore only the pre-determined frequencies are configurable by the user.

The external clock frequency shall be retrieved by obtaining the external clock using the `devm_v4l2_sensor_clk_get()` helper function, and then getting its frequency with `clk_get_rate()`. Usage of the helper function guarantees correct behaviour regardless of whether the sensor is integrated in a DT-based or ACPI-based system.

<a id="rst-acpi"></a>

### ACPI

ACPI-based systems typically don't register the sensor external clock with the kernel, but specify the external clock frequency in the `clock-frequency` \_DSD property. The `devm_v4l2_sensor_clk_get()` helper creates and returns a fixed clock set at that rate.

<a id="rst-devicetree"></a>

### Devicetree

Devicetree-based systems declare the sensor external clock in the device tree and reference it from the sensor node. The preferred way to select the external clock frequency is to use the `assigned-clocks`, `assigned-clock-parents` and `assigned-clock-rates` properties in the sensor node to set the clock rate. See the [clock device tree bindings](<https://github.com/devicetree-org/dt-schema/blob/main/dtschema/schemas/clock/clock.yaml>)<a id="rst-clock-device-tree-bindings"></a> for more information. The `devm_v4l2_sensor_clk_get()` helper retrieves and returns that clock.

This approach has the drawback that there's no guarantee that the frequency hasn't been modified directly or indirectly by another driver, or supported by the board's clock tree to begin with. Changes to the Common Clock Framework API are required to ensure reliability.

<a id="rst-power-management"></a>

## Power management

Camera sensors are used in conjunction with other devices to form a camera pipeline. They must obey the rules listed herein to ensure coherent power management over the pipeline.

Camera sensor drivers are responsible for controlling the power state of the device they otherwise control as well. They shall use runtime PM to manage power states. Runtime PM shall be enabled at probe time and disabled at remove time. Drivers should enable runtime PM autosuspend. Also see [async sub-device registration](</kernel/hardware/driver-api/media/v4l2-subdev.md#rst-media-registering-async-subdevs>).

The runtime PM handlers shall handle clocks, regulators, GPIOs, and other system resources required to power the sensor up and down. For drivers that don't use any of those resources (such as drivers that support ACPI systems only), the runtime PM handlers may be left unimplemented.

In general, the device shall be powered on at least when its registers are being accessed and when it is streaming. Drivers should use `pm_runtime_resume_and_get()` when starting streaming and `pm_runtime_put()` or `pm_runtime_put_autosuspend()` when stopping streaming. They may power the device up at probe time (for example to read identification registers), but should not keep it powered unconditionally after probe.

At system suspend time, the whole camera pipeline must stop streaming, and restart when the system is resumed. This requires coordination between the camera sensor and the rest of the camera pipeline. Bridge drivers are responsible for this coordination, and instruct camera sensors to stop and restart streaming by calling the appropriate subdev operations (`.enable_streams()` or `.disable_streams()`). Camera sensor drivers shall therefore **not** keep track of the streaming state to stop streaming in the PM suspend handler and restart it in the resume handler. Drivers should in general not implement the system PM handlers.

Camera sensor drivers shall **not** implement the subdev `.s_power()` operation, as it is deprecated. While this operation is implemented in some existing drivers as they predate the deprecation, new drivers shall use runtime PM instead. If you feel you need to begin calling `.s_power()` from an ISP or a bridge driver, instead add runtime PM support to the sensor driver you are using and drop its `.s_power()` handler.

Please also see [examples](<#rst-media-camera-sensor-examples>).

<a id="rst-control-framework"></a>

### Control framework

`v4l2_ctrl_handler_setup()` function may not be used in the device's runtime PM `runtime_resume` callback, as it has no way to figure out the power state of the device. This is because the power state of the device is only changed after the power state transition has taken place. The `s_ctrl` callback can be used to obtain device's power state after the power state transition:





<a id="c-pm_runtime_get_if_in_use"></a>

```c
int pm_runtime_get_if_in_use(struct device *dev);
```

The function returns a non-zero value if it succeeded getting the power count or runtime PM was disabled, in either of which cases the driver may proceed to access the device.

<a id="rst-rotation-orientation-and-flipping"></a>

## Rotation, orientation and flipping

Use `v4l2_fwnode_device_parse()` to obtain rotation and orientation information from system firmware and `v4l2_ctrl_new_fwnode_properties()` to register the appropriate controls.

<a id="rst-example-drivers"></a>
<a id="rst-media-camera-sensor-examples"></a>

## Example drivers

Features implemented by sensor drivers vary, and depending on the set of supported features and other qualities, particular sensor drivers better serve the purpose of an example. The following drivers are known to be good examples:


<table>
<caption>Example sensor drivers</caption>
<tbody>
<tr>
<td>


Driver name

</td>
<td>


File(s)

</td>
<td>


Driver type

</td>
<td>


Example topic

</td>
</tr>
<tr>
<td>


CCS

</td>
<td>


`drivers/media/i2c/ccs/`

</td>
<td>


Freely configurable

</td>
<td>


Power management (ACPI and DT), UAPI

</td>
</tr>
<tr>
<td>


imx219

</td>
<td>


`drivers/media/i2c/imx219.c`

</td>
<td>


Register list based

</td>
<td>


Power management (DT), UAPI, mode selection

</td>
</tr>
<tr>
<td>


imx319

</td>
<td>


`drivers/media/i2c/imx319.c`

</td>
<td>


Register list based

</td>
<td>


Power management (ACPI and DT)

</td>
</tr>
</tbody>
</table>

---

# CEC Kernel Support

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> The CEC framework provides a unified kernel interface for use with HDMI CEC hardware. It is designed to handle a multiple types of hardware (receivers, transmitters, USB dongles). The framework also gives the option to decide what to do in…

<a id="rst-cec-kernel-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The CEC framework provides a unified kernel interface for use with HDMI CEC hardware. It is designed to handle a multiple types of hardware (receivers, transmitters, USB dongles). The framework also gives the option to decide what to do in the kernel driver and what should be handled by userspace applications. In addition it integrates the remote control passthrough feature into the kernel's remote control framework.

<a id="rst-the-cec-protocol"></a>

## The CEC Protocol

The CEC protocol enables consumer electronic devices to communicate with each other through the HDMI connection. The protocol uses logical addresses in the communication. The logical address is strictly connected with the functionality provided by the device. The TV acting as the communication hub is always assigned address 0. The physical address is determined by the physical connection between devices.

The CEC framework described here is up to date with the CEC 2.0 specification. It is documented in the HDMI 1.4 specification with the new 2.0 bits documented in the HDMI 2.0 specification. But for most of the features the freely available HDMI 1.3a specification is sufficient:

[https://www.hdmi.org/spec/index](<https://www.hdmi.org/spec/index>)

<a id="rst-cec-adapter-interface"></a>

## CEC Adapter Interface

The struct cec_adapter represents the CEC adapter hardware. It is created by calling cec_allocate_adapter() and deleted by calling cec_delete_adapter():





<a id="c-cec_allocate_adapter"></a>

```c
struct cec_adapter *cec_allocate_adapter(const struct cec_adap_ops *ops, \
                                         void *priv, const char *name, \
                                         u32 caps, u8 available_las);
```





<a id="c-cec_delete_adapter"></a>

```c
void cec_delete_adapter(struct cec_adapter *adap);
```

To create an adapter you need to pass the following information:

- **ops:**

  adapter operations which are called by the CEC framework and that you have to implement.

- **priv:**

  will be stored in adap-&gt;priv and can be used by the adapter ops. Use cec_get_drvdata(adap) to get the priv pointer.

- **name:**

  the name of the CEC adapter. Note: this name will be copied.

- **caps:**

  capabilities of the CEC adapter. These capabilities determine the capabilities of the hardware and which parts are to be handled by userspace and which parts are handled by kernelspace. The capabilities are returned by CEC_ADAP_G_CAPS.

- **available_las:**

  the number of simultaneous logical addresses that this adapter can handle. Must be 1 &lt;= available_las &lt;= CEC_MAX_LOG_ADDRS.

To obtain the priv pointer use this helper function:





<a id="c-cec_get_drvdata"></a>

```c
void *cec_get_drvdata(const struct cec_adapter *adap);
```

To register the /dev/cecX device node and the remote control device (if CEC_CAP_RC is set) you call:





<a id="c-cec_register_adapter"></a>

```c
int cec_register_adapter(struct cec_adapter *adap, \
                         struct device *parent);
```

where parent is the parent device.

To unregister the devices call:





<a id="c-cec_unregister_adapter"></a>

```c
void cec_unregister_adapter(struct cec_adapter *adap);
```

Note: if cec_register_adapter() fails, then call cec_delete_adapter() to clean up. But if cec_register_adapter() succeeded, then only call cec_unregister_adapter() to clean up, never cec_delete_adapter(). The unregister function will delete the adapter automatically once the last user of that /dev/cecX device has closed its file handle.

<a id="rst-implementing-the-low-level-cec-adapter"></a>

## Implementing the Low-Level CEC Adapter

The following low-level adapter operations have to be implemented in your driver:





<a id="c-struct-cec_adap_ops"></a>

```c
cec_adap_ops
```



```none
struct cec_adap_ops
{
        /* Low-level callbacks */
        int (*adap_enable)(struct cec_adapter *adap, bool enable);
        int (*adap_monitor_all_enable)(struct cec_adapter *adap, bool enable);
        int (*adap_monitor_pin_enable)(struct cec_adapter *adap, bool enable);
        int (*adap_log_addr)(struct cec_adapter *adap, u8 logical_addr);
        void (*adap_unconfigured)(struct cec_adapter *adap);
        int (*adap_transmit)(struct cec_adapter *adap, u8 attempts,
                              u32 signal_free_time, struct cec_msg *msg);
        void (*adap_nb_transmit_canceled)(struct cec_adapter *adap,
                                          const struct cec_msg *msg);
        void (*adap_status)(struct cec_adapter *adap, struct seq_file *file);
        void (*adap_free)(struct cec_adapter *adap);

        /* Error injection callbacks */
        ...

        /* High-level callback */
        ...
};
```

These low-level ops deal with various aspects of controlling the CEC adapter hardware. They are all called with the mutex adap-&gt;lock held.

To enable/disable the hardware:



```text
int (*adap_enable)(struct cec_adapter *adap, bool enable);
```

This callback enables or disables the CEC hardware. Enabling the CEC hardware means powering it up in a state where no logical addresses are claimed. The physical address will always be valid if CEC_CAP_NEEDS_HPD is set. If that capability is not set, then the physical address can change while the CEC hardware is enabled. CEC drivers should not set CEC_CAP_NEEDS_HPD unless the hardware design requires that as this will make it impossible to wake up displays that pull the HPD low when in standby mode.  The initial state of the CEC adapter after calling cec_allocate_adapter() is disabled.

Note that adap_enable must return 0 if enable is false.

To enable/disable the 'monitor all' mode:



```text
int (*adap_monitor_all_enable)(struct cec_adapter *adap, bool enable);
```

If enabled, then the adapter should be put in a mode to also monitor messages that are not for us. Not all hardware supports this and this function is only called if the CEC_CAP_MONITOR_ALL capability is set. This callback is optional (some hardware may always be in 'monitor all' mode).

Note that adap_monitor_all_enable must return 0 if enable is false.

To enable/disable the 'monitor pin' mode:



```text
int (*adap_monitor_pin_enable)(struct cec_adapter *adap, bool enable);
```

If enabled, then the adapter should be put in a mode to also monitor CEC pin changes. Not all hardware supports this and this function is only called if the CEC_CAP_MONITOR_PIN capability is set. This callback is optional (some hardware may always be in 'monitor pin' mode).

Note that adap_monitor_pin_enable must return 0 if enable is false.

To program a new logical address:



```text
int (*adap_log_addr)(struct cec_adapter *adap, u8 logical_addr);
```

If logical_addr == CEC_LOG_ADDR_INVALID then all programmed logical addresses are to be erased. Otherwise the given logical address should be programmed. If the maximum number of available logical addresses is exceeded, then it should return -ENXIO. Once a logical address is programmed the CEC hardware can receive directed messages to that address.

Note that adap_log_addr must return 0 if logical_addr is CEC_LOG_ADDR_INVALID.

Called when the adapter is unconfigured:



```text
void (*adap_unconfigured)(struct cec_adapter *adap);
```

The adapter is unconfigured. If the driver has to take specific actions after unconfiguration, then that can be done through this optional callback.

To transmit a new message:



```text
int (*adap_transmit)(struct cec_adapter *adap, u8 attempts,
                     u32 signal_free_time, struct cec_msg *msg);
```

This transmits a new message. The attempts argument is the suggested number of attempts for the transmit.

The signal_free_time is the number of data bit periods that the adapter should wait when the line is free before attempting to send a message. This value depends on whether this transmit is a retry, a message from a new initiator or a new message for the same initiator. Most hardware will handle this automatically, but in some cases this information is needed.

The CEC_FREE_TIME_TO_USEC macro can be used to convert signal_free_time to microseconds (one data bit period is 2.4 ms).

To pass on the result of a canceled non-blocking transmit:



```text
void (*adap_nb_transmit_canceled)(struct cec_adapter *adap,
                                  const struct cec_msg *msg);
```

This optional callback can be used to obtain the result of a canceled non-blocking transmit with sequence number msg-&gt;sequence. This is called if the transmit was aborted, the transmit timed out (i.e. the hardware never signaled that the transmit finished), or the transmit was successful, but the wait for the expected reply was either aborted or it timed out.

To log the current CEC hardware status:



```text
void (*adap_status)(struct cec_adapter *adap, struct seq_file *file);
```

This optional callback can be used to show the status of the CEC hardware. The status is available through debugfs: cat /sys/kernel/debug/cec/cecX/status

To free any resources when the adapter is deleted:



```text
void (*adap_free)(struct cec_adapter *adap);
```

This optional callback can be used to free any resources that might have been allocated by the driver. It's called from cec_delete_adapter.

Your adapter driver will also have to react to events (typically interrupt driven) by calling into the framework in the following situations:

When a transmit finished (successfully or otherwise):



```text
void cec_transmit_done(struct cec_adapter *adap, u8 status,
                       u8 arb_lost_cnt,  u8 nack_cnt, u8 low_drive_cnt,
                       u8 error_cnt);
```

or:



```text
void cec_transmit_attempt_done(struct cec_adapter *adap, u8 status);
```

The status can be one of:

- **CEC_TX_STATUS_OK:**

  the transmit was successful.

- **CEC_TX_STATUS_ARB_LOST:**

  arbitration was lost: another CEC initiator took control of the CEC line and you lost the arbitration.

- **CEC_TX_STATUS_NACK:**

  the message was nacked (for a directed message) or acked (for a broadcast message). A retransmission is needed.

- **CEC_TX_STATUS_LOW_DRIVE:**

  low drive was detected on the CEC bus. This indicates that a follower detected an error on the bus and requested a retransmission.

- **CEC_TX_STATUS_ERROR:**

  some unspecified error occurred: this can be one of ARB_LOST or LOW_DRIVE if the hardware cannot differentiate or something else entirely. Some hardware only supports OK and FAIL as the result of a transmit, i.e. there is no way to differentiate between the different possible errors. In that case map FAIL to CEC_TX_STATUS_NACK and not to CEC_TX_STATUS_ERROR.

- **CEC_TX_STATUS_MAX_RETRIES:**

  could not transmit the message after trying multiple times. Should only be set by the driver if it has hardware support for retrying messages. If set, then the framework assumes that it doesn't have to make another attempt to transmit the message since the hardware did that already.

The hardware must be able to differentiate between OK, NACK and 'something else'.

The \*\_cnt arguments are the number of error conditions that were seen. This may be 0 if no information is available. Drivers that do not support hardware retry can just set the counter corresponding to the transmit error to 1, if the hardware does support retry then either set these counters to 0 if the hardware provides no feedback of which errors occurred and how many times, or fill in the correct values as reported by the hardware.

Be aware that calling these functions can immediately start a new transmit if there is one pending in the queue. So make sure that the hardware is in a state where new transmits can be started *before* calling these functions.

The cec_transmit_attempt_done() function is a helper for cases where the hardware never retries, so the transmit is always for just a single attempt. It will call cec_transmit_done() in turn, filling in 1 for the count argument corresponding to the status. Or all 0 if the status was OK.

When a CEC message was received:





<a id="c-cec_received_msg"></a>

```c
void cec_received_msg(struct cec_adapter *adap, struct cec_msg *msg);
```

Speaks for itself.

<a id="rst-implementing-the-interrupt-handler"></a>

## Implementing the interrupt handler

Typically the CEC hardware provides interrupts that signal when a transmit finished and whether it was successful or not, and it provides and interrupt when a CEC message was received.

The CEC driver should always process the transmit interrupts first before handling the receive interrupt. The framework expects to see the cec_transmit_done call before the cec_received_msg call, otherwise it can get confused if the received message was in reply to the transmitted message.

<a id="rst-optional-implementing-error-injection-support"></a>

## Optional: Implementing Error Injection Support

If the CEC adapter supports Error Injection functionality, then that can be exposed through the Error Injection callbacks:



```none
struct cec_adap_ops {
        /* Low-level callbacks */
        ...

        /* Error injection callbacks */
        int (*error_inj_show)(struct cec_adapter *adap, struct seq_file *sf);
        bool (*error_inj_parse_line)(struct cec_adapter *adap, char *line);

        /* High-level CEC message callback */
        ...
};
```

If both callbacks are set, then an `error-inj` file will appear in debugfs. The basic syntax is as follows:

Leading spaces/tabs are ignored. If the next character is a `#` or the end of the line was reached, then the whole line is ignored. Otherwise a command is expected.

This basic parsing is done in the CEC Framework. It is up to the driver to decide what commands to implement. The only requirement is that the command `clear` without any arguments must be implemented and that it will remove all current error injection commands.

This ensures that you can always do `echo clear >error-inj` to clear any error injections without having to know the details of the driver-specific commands.

Note that the output of `error-inj` shall be valid as input to `error-inj`. So this must work:



```none
$ cat error-inj >einj.txt
$ cat einj.txt >error-inj
```

The first callback is called when this file is read and it should show the current error injection state:



```text
int (*error_inj_show)(struct cec_adapter *adap, struct seq_file *sf);
```

It is recommended that it starts with a comment block with basic usage information. It returns 0 for success and an error otherwise.

The second callback will parse commands written to the `error-inj` file:



```text
bool (*error_inj_parse_line)(struct cec_adapter *adap, char *line);
```

The `line` argument points to the start of the command. Any leading spaces or tabs have already been skipped. It is a single line only (so there are no embedded newlines) and it is 0-terminated. The callback is free to modify the contents of the buffer. It is only called for lines containing a command, so this callback is never called for empty lines or comment lines.

Return true if the command was valid or false if there were syntax errors.

<a id="rst-implementing-the-high-level-cec-adapter"></a>

## Implementing the High-Level CEC Adapter

The low-level operations drive the hardware, the high-level operations are CEC protocol driven. The high-level callbacks are called without the adap-&gt;lock mutex being held. The following high-level callbacks are available:



```none
struct cec_adap_ops {
        /* Low-level callbacks */
        ...

        /* Error injection callbacks */
        ...

        /* High-level CEC message callback */
        void (*configured)(struct cec_adapter *adap);
        int (*received)(struct cec_adapter *adap, struct cec_msg *msg);
};
```

Called when the adapter is configured:



```text
void (*configured)(struct cec_adapter *adap);
```

The adapter is fully configured, i.e. all logical addresses have been successfully claimed. If the driver has to take specific actions after configuration, then that can be done through this optional callback.

The received() callback allows the driver to optionally handle a newly received CEC message:



```text
int (*received)(struct cec_adapter *adap, struct cec_msg *msg);
```

If the driver wants to process a CEC message, then it can implement this callback. If it doesn't want to handle this message, then it should return -ENOMSG, otherwise the CEC framework assumes it processed this message and it will not do anything with it.

<a id="rst-cec-framework-functions"></a>

## CEC framework functions

CEC Adapter drivers can call the following CEC framework functions:





<a id="c-cec_transmit_msg"></a>

```c
int cec_transmit_msg(struct cec_adapter *adap, struct cec_msg *msg, \
                     bool block);
```

Transmit a CEC message. If block is true, then wait until the message has been transmitted, otherwise just queue it and return.





<a id="c-cec_s_phys_addr"></a>

```c
void cec_s_phys_addr(struct cec_adapter *adap, u16 phys_addr, bool block);
```

Change the physical address. This function will set adap-&gt;phys_addr and send an event if it has changed. If cec_s_log_addrs() has been called and the physical address has become valid, then the CEC framework will start claiming the logical addresses. If block is true, then this function won't return until this process has finished.

When the physical address is set to a valid value the CEC adapter will be enabled (see the adap_enable op). When it is set to CEC_PHYS_ADDR_INVALID, then the CEC adapter will be disabled. If you change a valid physical address to another valid physical address, then this function will first set the address to CEC_PHYS_ADDR_INVALID before enabling the new physical address.





<a id="c-cec_s_phys_addr_from_edid"></a>

```c
void cec_s_phys_addr_from_edid(struct cec_adapter *adap, \
                               const struct edid *edid);
```

A helper function that extracts the physical address from the edid struct and calls cec_s_phys_addr() with that address, or CEC_PHYS_ADDR_INVALID if the EDID did not contain a physical address or edid was a NULL pointer.





<a id="c-cec_s_log_addrs"></a>

```c
int cec_s_log_addrs(struct cec_adapter *adap, \
                    struct cec_log_addrs *log_addrs, bool block);
```

Claim the CEC logical addresses. Should never be called if CEC_CAP_LOG_ADDRS is set. If block is true, then wait until the logical addresses have been claimed, otherwise just queue it and return. To unconfigure all logical addresses call this function with log_addrs set to NULL or with log_addrs-&gt;num_log_addrs set to 0. The block argument is ignored when unconfiguring. This function will just return if the physical address is invalid. Once the physical address becomes valid, then the framework will attempt to claim these logical addresses.

<a id="rst-cec-pin-framework"></a>

## CEC Pin framework

Most CEC hardware operates on full CEC messages where the software provides the message and the hardware handles the low-level CEC protocol. But some hardware only drives the CEC pin and software has to handle the low-level CEC protocol. The CEC pin framework was created to handle such devices.

Note that due to the close-to-realtime requirements it can never be guaranteed to work 100%. This framework uses highres timers internally, but if a timer goes off too late by more than 300 microseconds wrong results can occur. In reality it appears to be fairly reliable.

One advantage of this low-level implementation is that it can be used as a cheap CEC analyser, especially if interrupts can be used to detect CEC pin transitions from low to high or vice versa.


#### <a id="c-struct-cec_pin_ops"></a>`struct cec_pin_ops`

low-level CEC pin operations

**Definition**

```c
struct cec_pin_ops {
    int (*read)(struct cec_adapter *adap);
    void (*low)(struct cec_adapter *adap);
    void (*high)(struct cec_adapter *adap);
    bool (*enable_irq)(struct cec_adapter *adap);
    void (*disable_irq)(struct cec_adapter *adap);
    void (*free)(struct cec_adapter *adap);
    void (*status)(struct cec_adapter *adap, struct seq_file *file);
    int (*read_hpd)(struct cec_adapter *adap);
    int (*read_5v)(struct cec_adapter *adap);
    int (*received)(struct cec_adapter *adap, struct cec_msg *msg);
};
```

**Members**

- `read`: read the CEC pin. Returns > 0 if high, 0 if low, or an error
  if negative.
- `low`: drive the CEC pin low.
- `high`: stop driving the CEC pin. The pull-up will drive the pin
  high, unless someone else is driving the pin low.
- `enable_irq`: optional, enable the interrupt to detect pin voltage changes.
- `disable_irq`: optional, disable the interrupt.
- `free`: optional. Free any allocated resources. Called when the
  adapter is deleted.
- `status`: optional, log status information.
- `read_hpd`: optional. Read the HPD pin. Returns > 0 if high, 0 if low or
  an error if negative.
- `read_5v`: optional. Read the 5V pin. Returns > 0 if high, 0 if low or
  an error if negative.
- `received`: optional. High-level CEC message callback. Allows the driver
  to process CEC messages.

**Description**

These operations (except for the **received** op) are used by the
cec pin framework to manipulate the CEC pin.

#### <a id="c-cec_pin_changed"></a>`cec_pin_changed()`

```c
void cec_pin_changed(struct cec_adapter *adap, bool value)
```

update pin state from interrupt

**Parameters**

- `struct cec_adapter *adap`: pointer to the cec adapter
- `bool value`: when true the pin is high, otherwise it is low

**Description**

If changes of the CEC voltage are detected via an interrupt, then
cec_pin_changed is called from the interrupt with the new value.

#### <a id="c-cec_pin_allocate_adapter"></a>`cec_pin_allocate_adapter()`

```c
struct cec_adapter * cec_pin_allocate_adapter(const struct cec_pin_ops *pin_ops, void *priv, const char *name, u32 caps)
```

allocate a pin-based cec adapter

**Parameters**

- `const struct cec_pin_ops *pin_ops`: low-level pin operations
- `void *priv`: will be stored in adap->priv and can be used by the adapter ops.
  Use cec_get_drvdata(adap) to get the priv pointer.
- `const char *name`: the name of the CEC adapter. Note: this name will be copied.
- `u32 caps`: capabilities of the CEC adapter. This will be ORed with
  CEC_CAP_MONITOR_ALL and CEC_CAP_MONITOR_PIN.

**Description**

Allocate a cec adapter using the cec pin framework.

**Return**

a pointer to the cec adapter or an error pointer


<a id="rst-cec-notifier-framework"></a>

## CEC Notifier framework

Most drm HDMI implementations have an integrated CEC implementation and no notifier support is needed. But some have independent CEC implementations that have their own driver. This could be an IP block for an SoC or a completely separate chip that deals with the CEC pin. For those cases a drm driver can install a notifier and use the notifier to inform the CEC driver about changes in the physical address.


#### <a id="c-cec_notifier_conn_register"></a>`cec_notifier_conn_register()`

```c
struct cec_notifier * cec_notifier_conn_register(struct device *hdmi_dev, const char *port_name, const struct cec_connector_info *conn_info)
```

find or create a new cec_notifier for the given HDMI device and connector tuple.

**Parameters**

- `struct device *hdmi_dev`: HDMI device that sends the events.
- `const char *port_name`: the connector name from which the event occurs. May be NULL
  if there is always only one HDMI connector created by the HDMI device.
- `const struct cec_connector_info *conn_info`: the connector info from which the event occurs (may be NULL)

**Description**

If a notifier for device **dev** and connector **port_name** already exists, then
increase the refcount and return that notifier.

If it doesn't exist, then allocate a new notifier struct and return a
pointer to that new struct.

Return NULL if the memory could not be allocated.

#### <a id="c-cec_notifier_conn_unregister"></a>`cec_notifier_conn_unregister()`

```c
void cec_notifier_conn_unregister(struct cec_notifier *n)
```

decrease refcount and delete when the refcount reaches 0.

**Parameters**

- `struct cec_notifier *n`: notifier. If NULL, then this function does nothing.

#### <a id="c-cec_notifier_cec_adap_register"></a>`cec_notifier_cec_adap_register()`

```c
struct cec_notifier * cec_notifier_cec_adap_register(struct device *hdmi_dev, const char *port_name, struct cec_adapter *adap)
```

find or create a new cec_notifier for the given device.

**Parameters**

- `struct device *hdmi_dev`: HDMI device that sends the events.
- `const char *port_name`: the connector name from which the event occurs. May be NULL
  if there is always only one HDMI connector created by the HDMI device.
- `struct cec_adapter *adap`: the cec adapter that registered this notifier.

**Description**

If a notifier for device **dev** and connector **port_name** already exists, then
increase the refcount and return that notifier.

If it doesn't exist, then allocate a new notifier struct and return a
pointer to that new struct.

Return NULL if the memory could not be allocated.

#### <a id="c-cec_notifier_cec_adap_unregister"></a>`cec_notifier_cec_adap_unregister()`

```c
void cec_notifier_cec_adap_unregister(struct cec_notifier *n, struct cec_adapter *adap)
```

decrease refcount and delete when the refcount reaches 0.

**Parameters**

- `struct cec_notifier *n`: notifier. If NULL, then this function does nothing.
- `struct cec_adapter *adap`: the cec adapter that registered this notifier.

#### <a id="c-cec_notifier_set_phys_addr"></a>`cec_notifier_set_phys_addr()`

```c
void cec_notifier_set_phys_addr(struct cec_notifier *n, u16 pa)
```

set a new physical address.

**Parameters**

- `struct cec_notifier *n`: the CEC notifier
- `u16 pa`: the CEC physical address

**Description**

Set a new CEC physical address.
Does nothing if **n** == NULL.

#### <a id="c-cec_notifier_set_phys_addr_from_edid"></a>`cec_notifier_set_phys_addr_from_edid()`

```c
void cec_notifier_set_phys_addr_from_edid(struct cec_notifier *n, const struct edid *edid)
```

set parse the PA from the EDID.

**Parameters**

- `struct cec_notifier *n`: the CEC notifier
- `const struct edid *edid`: the struct edid pointer

**Description**

Parses the EDID to obtain the new CEC physical address and set it.
Does nothing if **n** == NULL.

#### <a id="c-cec_notifier_parse_hdmi_phandle"></a>`cec_notifier_parse_hdmi_phandle()`

```c
struct device * cec_notifier_parse_hdmi_phandle(struct device *dev)
```

find the hdmi device from "hdmi-phandle"

**Parameters**

- `struct device *dev`: the device with the "hdmi-phandle" device tree property

**Description**

Returns the device pointer referenced by the "hdmi-phandle" property.
Note that the refcount of the returned device is not incremented.
This device pointer is only used as a key value in the notifier
list, but it is never accessed by the CEC driver.

#### <a id="c-cec_notifier_phys_addr_invalidate"></a>`cec_notifier_phys_addr_invalidate()`

```c
void cec_notifier_phys_addr_invalidate(struct cec_notifier *n)
```

set the physical address to INVALID

**Parameters**

- `struct cec_notifier *n`: the CEC notifier

**Description**

This is a simple helper function to invalidate the physical
address. Does nothing if **n** == NULL.

---

# Digital TV Conditional Access kABI

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for Digital TV Conditional Access kABI.

<a id="rst-digital-tv-conditional-access-kabi"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-struct-dvb_ca_en50221"></a>`struct dvb_ca_en50221`

Structure describing a CA interface

**Definition**

```c
struct dvb_ca_en50221 {
    struct module *owner;
    int (*read_attribute_mem)(struct dvb_ca_en50221 *ca, int slot, int address);
    int (*write_attribute_mem)(struct dvb_ca_en50221 *ca, int slot, int address, u8 value);
    int (*read_cam_control)(struct dvb_ca_en50221 *ca, int slot, u8 address);
    int (*write_cam_control)(struct dvb_ca_en50221 *ca, int slot, u8 address, u8 value);
    int (*read_data)(struct dvb_ca_en50221 *ca, int slot, u8 *ebuf, int ecount);
    int (*write_data)(struct dvb_ca_en50221 *ca, int slot, u8 *ebuf, int ecount);
    int (*slot_reset)(struct dvb_ca_en50221 *ca, int slot);
    int (*slot_shutdown)(struct dvb_ca_en50221 *ca, int slot);
    int (*slot_ts_enable)(struct dvb_ca_en50221 *ca, int slot);
    int (*poll_slot_status)(struct dvb_ca_en50221 *ca, int slot, int open);
    void *data;
    void *private;
};
```

**Members**

- `owner`: the module owning this structure
- `read_attribute_mem`: function for reading attribute memory on the CAM
- `write_attribute_mem`: function for writing attribute memory on the CAM
- `read_cam_control`: function for reading the control interface on the CAM
- `write_cam_control`: function for reading the control interface on the CAM
- `read_data`: function for reading data (block mode)
- `write_data`: function for writing data (block mode)
- `slot_reset`: function to reset the CAM slot
- `slot_shutdown`: function to shutdown a CAM slot
- `slot_ts_enable`: function to enable the Transport Stream on a CAM slot
- `poll_slot_status`: function to poll slot status. Only necessary if
  DVB_CA_FLAG_EN50221_IRQ_CAMCHANGE is not set.
- `data`: private data, used by caller.
- `private`: Opaque data used by the dvb_ca core. Do not modify!

**NOTE**

the read_*, write_* and poll_slot_status functions will be
called for different slots concurrently and need to use locks where
and if appropriate. There will be no concurrent access to one slot.

#### <a id="c-dvb_ca_en50221_camchange_irq"></a>`dvb_ca_en50221_camchange_irq()`

```c
void dvb_ca_en50221_camchange_irq(struct dvb_ca_en50221 *pubca, int slot, int change_type)
```

A CAMCHANGE IRQ has occurred.

**Parameters**

- `struct dvb_ca_en50221 *pubca`: CA instance.
- `int slot`: Slot concerned.
- `int change_type`: One of the DVB_CA_CAMCHANGE_* values

#### <a id="c-dvb_ca_en50221_camready_irq"></a>`dvb_ca_en50221_camready_irq()`

```c
void dvb_ca_en50221_camready_irq(struct dvb_ca_en50221 *pubca, int slot)
```

A CAMREADY IRQ has occurred.

**Parameters**

- `struct dvb_ca_en50221 *pubca`: CA instance.
- `int slot`: Slot concerned.

#### <a id="c-dvb_ca_en50221_frda_irq"></a>`dvb_ca_en50221_frda_irq()`

```c
void dvb_ca_en50221_frda_irq(struct dvb_ca_en50221 *ca, int slot)
```

An FR or a DA IRQ has occurred.

**Parameters**

- `struct dvb_ca_en50221 *ca`: CA instance.
- `int slot`: Slot concerned.

#### <a id="c-dvb_ca_en50221_init"></a>`dvb_ca_en50221_init()`

```c
int dvb_ca_en50221_init(struct dvb_adapter *dvb_adapter, struct dvb_ca_en50221 *ca, int flags, int slot_count)
```

Initialise a new DVB CA device.

**Parameters**

- `struct dvb_adapter *dvb_adapter`: DVB adapter to attach the new CA device to.
- `struct dvb_ca_en50221 *ca`: The dvb_ca instance.
- `int flags`: Flags describing the CA device (DVB_CA_EN50221_FLAG_*).
- `int slot_count`: Number of slots supported.

**Description**

**return** 0 on success, nonzero on failure

#### <a id="c-dvb_ca_en50221_release"></a>`dvb_ca_en50221_release()`

```c
void dvb_ca_en50221_release(struct dvb_ca_en50221 *ca)
```

Release a DVB CA device.

**Parameters**

- `struct dvb_ca_en50221 *ca`: The associated dvb_ca instance.

---

# Digital TV Common functions

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Those functions are responsible for handling the DVB device nodes.

<a id="rst-digital-tv-common-functions"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-dvb-devices"></a>

## DVB devices

Those functions are responsible for handling the DVB device nodes.


#### <a id="c-enum-dvb_device_type"></a>`enum dvb_device_type`

type of the Digital TV device

**Constants**

- `DVB_DEVICE_SEC`: Digital TV standalone Common Interface (CI)
- `DVB_DEVICE_FRONTEND`: Digital TV frontend.
- `DVB_DEVICE_DEMUX`: Digital TV demux.
- `DVB_DEVICE_DVR`: Digital TV digital video record (DVR).
- `DVB_DEVICE_CA`: Digital TV Conditional Access (CA).
- `DVB_DEVICE_NET`: Digital TV network.
- `DVB_DEVICE_VIDEO`: Digital TV video decoder.
  Deprecated. Used only on av7110-av.
- `DVB_DEVICE_AUDIO`: Digital TV audio decoder.
  Deprecated. Used only on av7110-av.
- `DVB_DEVICE_OSD`: Digital TV On Screen Display (OSD).
  Deprecated. Used only on av7110.

#### <a id="c-struct-dvb_adapter"></a>`struct dvb_adapter`

represents a Digital TV adapter using Linux DVB API

**Definition**

```c
struct dvb_adapter {
        int num;
        struct list_head list_head;
        struct list_head device_list;
        const char *name;
        u8 proposed_mac [6];
        void* priv;
        struct device *device;
        struct module *module;
        int mfe_shared;
        struct dvb_device *mfe_dvbdev;
        struct mutex mfe_lock;
    #if defined(CONFIG_MEDIA_CONTROLLER_DVB);
        struct mutex mdev_lock;
        struct media_device *mdev;
        struct media_entity *conn;
        struct media_pad *conn_pads;
    #endif;
};
```

**Members**

- `num`: Number of the adapter
- `list_head`: List with the DVB adapters
- `device_list`: List with the DVB devices
- `name`: Name of the adapter
- `proposed_mac`: proposed MAC address for the adapter
- `priv`: private data
- `device`: pointer to struct device
- `module`: pointer to struct module
- `mfe_shared`: indicates mutually exclusive frontends.
  1 = legacy exclusion behavior: blocking any `open()` call
  2 = enhanced exclusion behavior, emulating the standard
  behavior of busy frontends: allowing read-only sharing
  and otherwise returning immediately with -EBUSY when any
  of the frontends is already opened with write access.
- `mfe_dvbdev`: Frontend device in use, in the case of MFE
- `mfe_lock`: Lock to prevent using the other frontends when MFE is
  used.
- `mdev_lock`: Protect access to the mdev pointer.
- `mdev`: pointer to struct media_device, used when the media
  controller is used.
- `conn`: RF connector. Used only if the device has no separate
  tuner.
- `conn_pads`: pointer to struct media_pad associated with **conn**;

#### <a id="c-struct-dvb_device"></a>`struct dvb_device`

represents a DVB device node

**Definition**

```c
struct dvb_device {
        struct list_head list_head;
        struct kref ref;
        const struct file_operations *fops;
        struct dvb_adapter *adapter;
        enum dvb_device_type type;
        int minor;
        u32 id;
        int readers;
        int writers;
        int users;
        wait_queue_head_t wait_queue;
        int (*kernel_ioctl)(struct file *file, unsigned int cmd, void *arg);
    #if defined(CONFIG_MEDIA_CONTROLLER_DVB);
        const char *name;
        struct media_intf_devnode *intf_devnode;
        unsigned tsout_num_entities;
        struct media_entity *entity, *tsout_entity;
        struct media_pad *pads, *tsout_pads;
    #endif;
        void *priv;
};
```

**Members**

- `list_head`: List head with all DVB devices
- `ref`: reference count for this device
- `fops`: pointer to struct file_operations
- `adapter`: pointer to the adapter that holds this device node
- `type`: type of the device, as defined by [`enum dvb_device_type`](#c-enum-dvb_device_type).
- `minor`: devnode minor number. Major number is always DVB_MAJOR.
- `id`: device ID number, inside the adapter
- `readers`: Initialized by the caller. Each call to `open()` in Read Only mode
  decreases this counter by one.
- `writers`: Initialized by the caller. Each call to `open()` in Read/Write
  mode decreases this counter by one.
- `users`: Initialized by the caller. Each call to `open()` in any mode
  decreases this counter by one.
- `wait_queue`: wait queue, used to wait for certain events inside one of
  the DVB API callers
- `kernel_ioctl`: callback function used to handle ioctl calls from userspace.
- `name`: Name to be used for the device at the Media Controller
- `intf_devnode`: Pointer to media_intf_devnode. Used by the dvbdev core to
  store the MC device node interface
- `tsout_num_entities`: Number of Transport Stream output entities
- `entity`: pointer to struct media_entity associated with the device node
- `tsout_entity`: array with MC entities associated to each TS output node
- `pads`: pointer to struct media_pad associated with **entity**;
- `tsout_pads`: array with the source pads for each **tsout_entity**
- `priv`: private data

**Description**

This structure is used by the DVB core (frontend, CA, net, demux) in
order to create the device nodes. Usually, driver should not initialize
this struct diretly.

#### <a id="c-struct-dvbdevfops_node"></a>`struct dvbdevfops_node`

fops nodes registered in dvbdevfops_list

**Definition**

```c
struct dvbdevfops_node {
    struct file_operations *fops;
    enum dvb_device_type type;
    const struct dvb_device *template;
    struct list_head list_head;
};
```

**Members**

- `fops`: Dynamically allocated fops for ->owner registration
- `type`: type of dvb_device
- `template`: dvb_device used for registration
- `list_head`: list_head for dvbdevfops_list

#### <a id="c-dvb_device_get"></a>`dvb_device_get()`

```c
struct dvb_device * dvb_device_get(struct dvb_device *dvbdev)
```

Increase dvb_device reference

**Parameters**

- `struct dvb_device *dvbdev`: pointer to struct dvb_device

#### <a id="c-dvb_device_put"></a>`dvb_device_put()`

```c
void dvb_device_put(struct dvb_device *dvbdev)
```

Decrease dvb_device reference

**Parameters**

- `struct dvb_device *dvbdev`: pointer to struct dvb_device

#### <a id="c-dvb_register_adapter"></a>`dvb_register_adapter()`

```c
int dvb_register_adapter(struct dvb_adapter *adap, const char *name, struct module *module, struct device *device, short *adapter_nums)
```

Registers a new DVB adapter

**Parameters**

- `struct dvb_adapter *adap`: pointer to struct dvb_adapter
- `const char *name`: Adapter's name
- `struct module *module`: initialized with THIS_MODULE at the caller
- `struct device *device`: pointer to struct device that corresponds to the device driver
- `short *adapter_nums`: Array with a list of the numbers for **dvb_register_adapter**;
  to select among them. Typically, initialized with:
  DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nums)

#### <a id="c-dvb_unregister_adapter"></a>`dvb_unregister_adapter()`

```c
int dvb_unregister_adapter(struct dvb_adapter *adap)
```

Unregisters a DVB adapter

**Parameters**

- `struct dvb_adapter *adap`: pointer to struct dvb_adapter

#### <a id="c-dvb_register_device"></a>`dvb_register_device()`

```c
int dvb_register_device(struct dvb_adapter *adap, struct dvb_device **pdvbdev, const struct dvb_device *template, void *priv, enum dvb_device_type type, int demux_sink_pads)
```

Registers a new DVB device

**Parameters**

- `struct dvb_adapter *adap`: pointer to struct dvb_adapter
- `struct dvb_device **pdvbdev`: pointer to the place where the new struct dvb_device will be
  stored
- `const struct dvb_device *template`: Template used to create `pdvbdev`;
- `void *priv`: private data
- `enum dvb_device_type type`: type of the device, as defined by [`enum dvb_device_type`](#c-enum-dvb_device_type).
- `int demux_sink_pads`: Number of demux outputs, to be used to create the TS
  outputs via the Media Controller.

#### <a id="c-dvb_remove_device"></a>`dvb_remove_device()`

```c
void dvb_remove_device(struct dvb_device *dvbdev)
```

Remove a registered DVB device

**Parameters**

- `struct dvb_device *dvbdev`: pointer to struct dvb_device

**Description**

This does not free memory. `dvb_free_device()` will do that when
reference counter is empty

#### <a id="c-dvb_unregister_device"></a>`dvb_unregister_device()`

```c
void dvb_unregister_device(struct dvb_device *dvbdev)
```

Unregisters a DVB device

**Parameters**

- `struct dvb_device *dvbdev`: pointer to struct dvb_device

#### <a id="c-dvb_create_media_graph"></a>`dvb_create_media_graph()`

```c
int dvb_create_media_graph(struct dvb_adapter *adap, bool create_rf_connector)
```

Creates media graph for the Digital TV part of the device.

**Parameters**

- `struct dvb_adapter *adap`: pointer to [`struct dvb_adapter`](#c-struct-dvb_adapter)
- `bool create_rf_connector`: if true, it creates the RF connector too

**Description**

This function checks all DVB-related functions at the media controller
entities and creates the needed links for the media graph. It is
capable of working with multiple tuners or multiple frontends, but it
won't create links if the device has multiple tuners and multiple frontends
or if the device has multiple muxes. In such case, the caller driver should
manually create the remaining links.

#### <a id="c-dvb_register_media_controller"></a>`dvb_register_media_controller()`

```c
void dvb_register_media_controller(struct dvb_adapter *adap, struct media_device *mdev)
```

registers a media controller at DVB adapter

**Parameters**

- `struct dvb_adapter *adap`: pointer to [`struct dvb_adapter`](#c-struct-dvb_adapter)
- `struct media_device *mdev`: pointer to [`struct media_device`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_device)

#### <a id="c-dvb_get_media_controller"></a>`dvb_get_media_controller()`

```c
struct media_device * dvb_get_media_controller(struct dvb_adapter *adap)
```

gets the associated media controller

**Parameters**

- `struct dvb_adapter *adap`: pointer to [`struct dvb_adapter`](#c-struct-dvb_adapter)

#### <a id="c-dvb_generic_open"></a>`dvb_generic_open()`

```c
int dvb_generic_open(struct inode *inode, struct file *file)
```

Digital TV open function, used by DVB devices

**Parameters**

- `struct inode *inode`: pointer to `struct inode`.
- `struct file *file`: pointer to [`struct file`](/kernel/internals/filesystems/api-summary.md#c-struct-file).

**Description**

Checks if a DVB devnode is still valid, and if the permissions are
OK and increment negative use count.

#### <a id="c-dvb_generic_release"></a>`dvb_generic_release()`

```c
int dvb_generic_release(struct inode *inode, struct file *file)
```

Digital TV close function, used by DVB devices

**Parameters**

- `struct inode *inode`: pointer to `struct inode`.
- `struct file *file`: pointer to [`struct file`](/kernel/internals/filesystems/api-summary.md#c-struct-file).

**Description**

Checks if a DVB devnode is still valid, and if the permissions are
OK and decrement negative use count.

#### <a id="c-dvb_generic_ioctl"></a>`dvb_generic_ioctl()`

```c
long dvb_generic_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
```

Digital TV close function, used by DVB devices

**Parameters**

- `struct file *file`: pointer to [`struct file`](/kernel/internals/filesystems/api-summary.md#c-struct-file).
- `unsigned int cmd`: Ioctl name.
- `unsigned long arg`: Ioctl argument.

**Description**

Checks if a DVB devnode and struct dvbdev.kernel_ioctl is still valid.
If so, calls [`dvb_usercopy()`](#c-dvb_usercopy).

#### <a id="c-dvb_usercopy"></a>`dvb_usercopy()`

```c
int dvb_usercopy(struct file *file, unsigned int cmd, unsigned long arg, int (*func)(struct file *file, unsigned int cmd, void *arg))
```

copies data from/to userspace memory when an ioctl is issued.

**Parameters**

- `struct file *file`: Pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file).
- `unsigned int cmd`: Ioctl name.
- `unsigned long arg`: Ioctl argument.
- `int (*func)(struct file *file, unsigned int cmd, void *arg)`: function that will actually handle the ioctl

**Description**

Ancillary function that uses ioctl direction and size to copy from
userspace. Then, it calls **func**, and, if needed, data is copied back
to userspace.

#### <a id="c-dvb_module_probe"></a>`dvb_module_probe()`

```c
struct i2c_client * dvb_module_probe(const char *module_name, const char *name, struct i2c_adapter *adap, unsigned char addr, void *platform_data)
```

helper routine to probe an I2C module

**Parameters**

- `const char *module_name`: Name of the I2C module to be probed
- `const char *name`: Optional name for the I2C module. Used for debug purposes.
  If `NULL`, defaults to **module_name**.
- `struct i2c_adapter *adap`: pointer to `struct i2c_adapter` that describes the I2C adapter where
  the module will be bound.
- `unsigned char addr`: I2C address of the adapter, in 7-bit notation.
- `void *platform_data`: Platform data to be passed to the I2C module probed.

**Description**

This function binds an I2C device into the DVB core. Should be used by
all drivers that use I2C bus to control the hardware. A module bound
with [`dvb_module_probe()`](#c-dvb_module_probe) should use [`dvb_module_release()`](#c-dvb_module_release) to unbind.

> [!NOTE]
> In the past, DVB modules (mainly, frontends) were bound via [`dvb_attach()`](#c-dvb_attach)
> macro, with does an ugly hack, using I2C low level functions. Such
> usage is deprecated and will be removed soon. Instead, use this routine.

**Return**

On success, return an [`struct i2c_client`](/kernel/hardware/driver-api/buses/i2c.md#c-struct-i2c_client), pointing to the bound
I2C device. `NULL` otherwise.

#### <a id="c-dvb_module_release"></a>`dvb_module_release()`

```c
void dvb_module_release(struct i2c_client *client)
```

releases an I2C device allocated with [`dvb_module_probe()`](#c-dvb_module_probe).

**Parameters**

- `struct i2c_client *client`: pointer to [`struct i2c_client`](/kernel/hardware/driver-api/buses/i2c.md#c-struct-i2c_client) with the I2C client to be released.
  can be `NULL`.

**Description**

This function should be used to free all resources reserved by
[`dvb_module_probe()`](#c-dvb_module_probe) and unbinding the I2C hardware.

#### <a id="c-dvb_attach"></a>`dvb_attach()`

```c
dvb_attach(FUNCTION, ARGS...)
```

attaches a DVB frontend into the DVB core.

**Parameters**

- `FUNCTION`: function on a frontend module to be called.
- `ARGS...`:

  **FUNCTION** arguments.

**Description**

This ancillary function loads a frontend module in runtime and runs
the **FUNCTION** function there, with **ARGS**.
As it increments symbol usage cont, at unregister, [`dvb_detach()`](#c-dvb_detach)
should be called.

> [!NOTE]
> In the past, DVB modules (mainly, frontends) were bound via [`dvb_attach()`](#c-dvb_attach)
> macro, with does an ugly hack, using I2C low level functions. Such
> usage is deprecated and will be removed soon. Instead, you should use
> [`dvb_module_probe()`](#c-dvb_module_probe).

#### <a id="c-dvb_detach"></a>`dvb_detach()`

```c
dvb_detach(FUNC)
```

detaches a DVB frontend loaded via [`dvb_attach()`](#c-dvb_attach)

**Parameters**

- `FUNC`: attach function

**Description**

Decrements usage count for a function previously called via [`dvb_attach()`](#c-dvb_attach).


<a id="rst-digital-tv-ring-buffer"></a>

## Digital TV Ring buffer

Those routines implement ring buffers used to handle digital TV data and copy it from/to userspace.

> [!NOTE]
>
> 1. For performance reasons read and write routines don't check buffer sizes and/or number of bytes free/available. This has to be done before these routines are called. For example:
>
> >
> >
> > ```c
> > /* write @buflen: bytes */
> > free = dvb_ringbuffer_free(rbuf);
> > if (free >= buflen)
> >         count = dvb_ringbuffer_write(rbuf, buffer, buflen);
> > else
> >         /* do something */
> >
> > /* read min. 1000, max. @bufsize: bytes */
> > avail = dvb_ringbuffer_avail(rbuf);
> > if (avail >= 1000)
> >         count = dvb_ringbuffer_read(rbuf, buffer, min(avail, bufsize));
> > else
> >         /* do something */
> > ```
>
> 2. If there is exactly one reader and one writer, there is no need to lock read or write operations. Two or more readers must be locked against each other. Flushing the buffer counts as a read operation. Resetting the buffer counts as a read and write operation. Two or more writers must be locked against each other.


#### <a id="c-struct-dvb_ringbuffer"></a>`struct dvb_ringbuffer`

Describes a ring buffer used at DVB framework

**Definition**

```c
struct dvb_ringbuffer {
    u8 *data;
    ssize_t size;
    ssize_t pread;
    ssize_t pwrite;
    int error;
    wait_queue_head_t queue;
    spinlock_t lock;
};
```

**Members**

- `data`: Area were the ringbuffer data is written
- `size`: size of the ringbuffer
- `pread`: next position to read
- `pwrite`: next position to write
- `error`: used by ringbuffer clients to indicate that an error happened.
- `queue`: Wait queue used by ringbuffer clients to indicate when buffer
  was filled
- `lock`: Spinlock used to protect the ringbuffer

#### <a id="c-dvb_ringbuffer_init"></a>`dvb_ringbuffer_init()`

```c
void dvb_ringbuffer_init(struct dvb_ringbuffer *rbuf, void *data, size_t len)
```

initialize ring buffer, lock and queue

**Parameters**

- `struct dvb_ringbuffer *rbuf`: pointer to struct dvb_ringbuffer
- `void *data`: pointer to the buffer where the data will be stored
- `size_t len`: bytes from ring buffer into **buf**

#### <a id="c-dvb_ringbuffer_empty"></a>`dvb_ringbuffer_empty()`

```c
int dvb_ringbuffer_empty(struct dvb_ringbuffer *rbuf)
```

test whether buffer is empty

**Parameters**

- `struct dvb_ringbuffer *rbuf`: pointer to struct dvb_ringbuffer

#### <a id="c-dvb_ringbuffer_free"></a>`dvb_ringbuffer_free()`

```c
ssize_t dvb_ringbuffer_free(struct dvb_ringbuffer *rbuf)
```

returns the number of free bytes in the buffer

**Parameters**

- `struct dvb_ringbuffer *rbuf`: pointer to struct dvb_ringbuffer

**Return**

number of free bytes in the buffer

#### <a id="c-dvb_ringbuffer_avail"></a>`dvb_ringbuffer_avail()`

```c
ssize_t dvb_ringbuffer_avail(struct dvb_ringbuffer *rbuf)
```

returns the number of bytes waiting in the buffer

**Parameters**

- `struct dvb_ringbuffer *rbuf`: pointer to struct dvb_ringbuffer

**Return**

number of bytes waiting in the buffer

#### <a id="c-dvb_ringbuffer_reset"></a>`dvb_ringbuffer_reset()`

```c
void dvb_ringbuffer_reset(struct dvb_ringbuffer *rbuf)
```

resets the ringbuffer to initial state

**Parameters**

- `struct dvb_ringbuffer *rbuf`: pointer to struct dvb_ringbuffer

**Description**

Resets the read and write pointers to zero and flush the buffer.

This counts as a read and write operation

#### <a id="c-dvb_ringbuffer_flush"></a>`dvb_ringbuffer_flush()`

```c
void dvb_ringbuffer_flush(struct dvb_ringbuffer *rbuf)
```

flush buffer

**Parameters**

- `struct dvb_ringbuffer *rbuf`: pointer to struct dvb_ringbuffer

#### <a id="c-dvb_ringbuffer_flush_spinlock_wakeup"></a>`dvb_ringbuffer_flush_spinlock_wakeup()`

```c
void dvb_ringbuffer_flush_spinlock_wakeup(struct dvb_ringbuffer *rbuf)
```

flush buffer protected by spinlock and wake-up waiting task(s)

**Parameters**

- `struct dvb_ringbuffer *rbuf`: pointer to struct dvb_ringbuffer

#### <a id="c-DVB_RINGBUFFER_PEEK"></a>`DVB_RINGBUFFER_PEEK()`

```c
DVB_RINGBUFFER_PEEK(rbuf, offs)
```

peek at byte **offs** in the buffer

**Parameters**

- `rbuf`: pointer to struct dvb_ringbuffer
- `offs`: offset inside the ringbuffer

#### <a id="c-DVB_RINGBUFFER_SKIP"></a>`DVB_RINGBUFFER_SKIP()`

```c
DVB_RINGBUFFER_SKIP(rbuf, num)
```

advance read ptr by **num** bytes

**Parameters**

- `rbuf`: pointer to struct dvb_ringbuffer
- `num`: number of bytes to advance

#### <a id="c-dvb_ringbuffer_read_user"></a>`dvb_ringbuffer_read_user()`

```c
ssize_t dvb_ringbuffer_read_user(struct dvb_ringbuffer *rbuf, u8 __user *buf, size_t len)
```

Reads a buffer into a user pointer

**Parameters**

- `struct dvb_ringbuffer *rbuf`: pointer to struct dvb_ringbuffer
- `u8 __user *buf`: pointer to the buffer where the data will be stored
- `size_t len`: bytes from ring buffer into **buf**

**Description**

This variant assumes that the buffer is a memory at the userspace. So,
it will internally call `copy_to_user()`.

**Return**

number of bytes transferred or -EFAULT

#### <a id="c-dvb_ringbuffer_read"></a>`dvb_ringbuffer_read()`

```c
void dvb_ringbuffer_read(struct dvb_ringbuffer *rbuf, u8 *buf, size_t len)
```

Reads a buffer into a pointer

**Parameters**

- `struct dvb_ringbuffer *rbuf`: pointer to struct dvb_ringbuffer
- `u8 *buf`: pointer to the buffer where the data will be stored
- `size_t len`: bytes from ring buffer into **buf**

**Description**

This variant assumes that the buffer is a memory at the Kernel space

**Return**

number of bytes transferred or -EFAULT

#### <a id="c-DVB_RINGBUFFER_WRITE_BYTE"></a>`DVB_RINGBUFFER_WRITE_BYTE()`

```c
DVB_RINGBUFFER_WRITE_BYTE(rbuf, byte)
```

write single byte to ring buffer

**Parameters**

- `rbuf`: pointer to struct dvb_ringbuffer
- `byte`: byte to write

#### <a id="c-dvb_ringbuffer_write"></a>`dvb_ringbuffer_write()`

```c
ssize_t dvb_ringbuffer_write(struct dvb_ringbuffer *rbuf, const u8 *buf, size_t len)
```

Writes a buffer into the ringbuffer

**Parameters**

- `struct dvb_ringbuffer *rbuf`: pointer to struct dvb_ringbuffer
- `const u8 *buf`: pointer to the buffer where the data will be read
- `size_t len`: bytes from ring buffer into **buf**

**Description**

This variant assumes that the buffer is a memory at the Kernel space

**Return**

number of bytes transferred or -EFAULT

#### <a id="c-dvb_ringbuffer_write_user"></a>`dvb_ringbuffer_write_user()`

```c
ssize_t dvb_ringbuffer_write_user(struct dvb_ringbuffer *rbuf, const u8 __user *buf, size_t len)
```

Writes a buffer received via a user pointer

**Parameters**

- `struct dvb_ringbuffer *rbuf`: pointer to struct dvb_ringbuffer
- `const u8 __user *buf`: pointer to the buffer where the data will be read
- `size_t len`: bytes from ring buffer into **buf**

**Description**

This variant assumes that the buffer is a memory at the userspace. So,
it will internally call `copy_from_user()`.

**Return**

number of bytes transferred or -EFAULT

#### <a id="c-dvb_ringbuffer_pkt_write"></a>`dvb_ringbuffer_pkt_write()`

```c
ssize_t dvb_ringbuffer_pkt_write(struct dvb_ringbuffer *rbuf, u8 *buf, size_t len)
```

Write a packet into the ringbuffer.

**Parameters**

- `struct dvb_ringbuffer *rbuf`: Ringbuffer to write to.
- `u8 *buf`: Buffer to write.
- `size_t len`: Length of buffer (currently limited to 65535 bytes max).

**Return**

Number of bytes written, or -EFAULT, -ENOMEM, -EINVAL.

#### <a id="c-dvb_ringbuffer_pkt_read_user"></a>`dvb_ringbuffer_pkt_read_user()`

```c
ssize_t dvb_ringbuffer_pkt_read_user(struct dvb_ringbuffer *rbuf, size_t idx, int offset, u8 __user *buf, size_t len)
```

Read from a packet in the ringbuffer.

**Parameters**

- `struct dvb_ringbuffer *rbuf`: Ringbuffer concerned.
- `size_t idx`: Packet index as returned by [`dvb_ringbuffer_pkt_next()`](#c-dvb_ringbuffer_pkt_next).
- `int offset`: Offset into packet to read from.
- `u8 __user *buf`: Destination buffer for data.
- `size_t len`: Size of destination buffer.

**Return**

Number of bytes read, or -EFAULT.

**Description**

> [!NOTE]
> unlike [`dvb_ringbuffer_read()`](#c-dvb_ringbuffer_read), this does **NOT** update the read pointer
> in the ringbuffer. You must use [`dvb_ringbuffer_pkt_dispose()`](#c-dvb_ringbuffer_pkt_dispose) to mark a
> packet as no longer required.

#### <a id="c-dvb_ringbuffer_pkt_read"></a>`dvb_ringbuffer_pkt_read()`

```c
ssize_t dvb_ringbuffer_pkt_read(struct dvb_ringbuffer *rbuf, size_t idx, int offset, u8 *buf, size_t len)
```

Read from a packet in the ringbuffer.

**Parameters**

- `struct dvb_ringbuffer *rbuf`: Ringbuffer concerned.
- `size_t idx`: Packet index as returned by [`dvb_ringbuffer_pkt_next()`](#c-dvb_ringbuffer_pkt_next).
- `int offset`: Offset into packet to read from.
- `u8 *buf`: Destination buffer for data.
- `size_t len`: Size of destination buffer.

**Note**

unlike [`dvb_ringbuffer_read_user()`](#c-dvb_ringbuffer_read_user), this DOES update the read pointer
in the ringbuffer.

**Return**

Number of bytes read, or -EFAULT.

#### <a id="c-dvb_ringbuffer_pkt_dispose"></a>`dvb_ringbuffer_pkt_dispose()`

```c
void dvb_ringbuffer_pkt_dispose(struct dvb_ringbuffer *rbuf, size_t idx)
```

Dispose of a packet in the ring buffer.

**Parameters**

- `struct dvb_ringbuffer *rbuf`: Ring buffer concerned.
- `size_t idx`: Packet index as returned by [`dvb_ringbuffer_pkt_next()`](#c-dvb_ringbuffer_pkt_next).

#### <a id="c-dvb_ringbuffer_pkt_next"></a>`dvb_ringbuffer_pkt_next()`

```c
ssize_t dvb_ringbuffer_pkt_next(struct dvb_ringbuffer *rbuf, size_t idx, size_t *pktlen)
```

Get the index of the next packet in a ringbuffer.

**Parameters**

- `struct dvb_ringbuffer *rbuf`: Ringbuffer concerned.
- `size_t idx`: Previous packet index, or -1 to return the first packet index.
- `size_t *pktlen`: On success, will be updated to contain the length of the packet
  in bytes.
  returns Packet index (if >=0), or -1 if no packets available.


<a id="rst-digital-tv-vb2-handler"></a>

## Digital TV VB2 handler


#### <a id="c-enum-dvb_buf_type"></a>`enum dvb_buf_type`

types of Digital TV memory-mapped buffers

**Constants**

- `DVB_BUF_TYPE_CAPTURE`: buffer is filled by the Kernel,
  with a received Digital TV stream

#### <a id="c-enum-dvb_vb2_states"></a>`enum dvb_vb2_states`

states to control VB2 state machine

**Constants**

- `DVB_VB2_STATE_NONE`: VB2 engine not initialized yet, init failed or VB2 was released.
- `DVB_VB2_STATE_INIT`: VB2 engine initialized.
- `DVB_VB2_STATE_REQBUFS`: Buffers were requested
- `DVB_VB2_STATE_STREAMON`: VB2 is streaming. Callers should not check it directly. Instead,
  they should use [`dvb_vb2_is_streaming()`](#c-dvb_vb2_is_streaming).

**Note**

Callers should not touch at the state machine directly. This
is handled inside dvb_vb2.c.

#### <a id="c-struct-dvb_buffer"></a>`struct dvb_buffer`

video buffer information for v4l2.

**Definition**

```c
struct dvb_buffer {
    struct vb2_buffer       vb;
    struct list_head        list;
};
```

**Members**

- `vb`: embedded struct [`vb2_buffer`](/kernel/hardware/driver-api/media/v4l2-videobuf2.md#c-struct-vb2_buffer).
- `list`: list of [`struct dvb_buffer`](#c-struct-dvb_buffer).

#### <a id="c-struct-dvb_vb2_ctx"></a>`struct dvb_vb2_ctx`

control struct for VB2 handler

**Definition**

```c
struct dvb_vb2_ctx {
    struct vb2_queue        vb_q;
    spinlock_t slock;
    struct list_head        dvb_q;
    struct dvb_buffer       *buf;
    int offset;
    int remain;
    int state;
    int buf_siz;
    int buf_cnt;
    int nonblocking;
    enum dmx_buffer_flags flags;
    u32 count;
    char name[DVB_VB2_NAME_MAX + 1];
};
```

**Members**

- `vb_q`: pointer to [`struct vb2_queue`](/kernel/hardware/driver-api/media/v4l2-videobuf2.md#c-struct-vb2_queue) with videobuf2 queue.
- `slock`: spin lock used to protect buffer filling at dvb_vb2.c.
- `dvb_q`: List of buffers that are not filled yet.
- `buf`: Pointer to the buffer that are currently being filled.
- `offset`: index to the next position at the **buf** to be filled.
- `remain`: How many bytes are left to be filled at **buf**.
- `state`: bitmask of buffer states as defined by [`enum dvb_vb2_states`](#c-enum-dvb_vb2_states).
- `buf_siz`: size of each VB2 buffer.
- `buf_cnt`: number of VB2 buffers.
- `nonblocking`: If different than zero, device is operating on non-blocking
  mode.
- `flags`: buffer flags as defined by [`enum dmx_buffer_flags`](/kernel/userspace/userspace-api/media-dvb/dmx-types.md#c-enum-dmx_buffer_flags).
  Filled only at `DMX_DQBUF`. `DMX_QBUF` should zero this field.
- `count`: monotonic counter for filled buffers. Helps to identify
  data stream loses. Filled only at `DMX_DQBUF`. `DMX_QBUF` should
  zero this field.
- `name`: name of the device type. Currently, it can either be
  "dvr" or "demux_filter".

#### <a id="c-dvb_vb2_init"></a>`dvb_vb2_init()`

```c
int dvb_vb2_init(struct dvb_vb2_ctx *ctx, const char *name, struct mutex *mutex, int non_blocking)
```

initializes VB2 handler

**Parameters**

- `struct dvb_vb2_ctx *ctx`: control struct for VB2 handler
- `const char *name`: name for the VB2 handler
- `struct mutex *mutex`: pointer to the mutex that serializes vb2 ioctls
- `int non_blocking`: if not zero, it means that the device is at non-blocking mode

#### <a id="c-dvb_vb2_release"></a>`dvb_vb2_release()`

```c
int dvb_vb2_release(struct dvb_vb2_ctx *ctx)
```

Releases the VB2 handler allocated resources and put **ctx** at DVB_VB2_STATE_NONE state.

**Parameters**

- `struct dvb_vb2_ctx *ctx`: control struct for VB2 handler

#### <a id="c-dvb_vb2_is_streaming"></a>`dvb_vb2_is_streaming()`

```c
int dvb_vb2_is_streaming(struct dvb_vb2_ctx *ctx)
```

checks if the VB2 handler is streaming

**Parameters**

- `struct dvb_vb2_ctx *ctx`: control struct for VB2 handler

**Return**

0 if not streaming, 1 otherwise.

#### <a id="c-dvb_vb2_fill_buffer"></a>`dvb_vb2_fill_buffer()`

```c
int dvb_vb2_fill_buffer(struct dvb_vb2_ctx *ctx, const unsigned char *src, int len, enum dmx_buffer_flags *buffer_flags, bool flush)
```

fills a VB2 buffer

**Parameters**

- `struct dvb_vb2_ctx *ctx`: control struct for VB2 handler
- `const unsigned char *src`: place where the data is stored
- `int len`: number of bytes to be copied from **src**
- `enum dmx_buffer_flags *buffer_flags`: pointer to buffer flags as defined by [`enum dmx_buffer_flags`](/kernel/userspace/userspace-api/media-dvb/dmx-types.md#c-enum-dmx_buffer_flags).
  can be NULL.
- `bool flush`: flush the buffer, even if it isn't full.

#### <a id="c-dvb_vb2_poll"></a>`dvb_vb2_poll()`

```c
__poll_t dvb_vb2_poll(struct dvb_vb2_ctx *ctx, struct file *file, poll_table *wait)
```

Wrapper to [`vb2_core_streamon()`](/kernel/hardware/driver-api/media/v4l2-videobuf2.md#c-vb2_core_streamon) for Digital TV buffer handling.

**Parameters**

- `struct dvb_vb2_ctx *ctx`: control struct for VB2 handler
- `struct file *file`: [`struct file`](/kernel/internals/filesystems/api-summary.md#c-struct-file) argument passed to the poll
  file operation handler.
- `poll_table *wait`: `poll_table` wait argument passed to the poll
  file operation handler.

**Description**

Implements poll `syscall()` logic.

#### <a id="c-dvb_vb2_stream_on"></a>`dvb_vb2_stream_on()`

```c
int dvb_vb2_stream_on(struct dvb_vb2_ctx *ctx)
```

Wrapper to [`vb2_core_streamon()`](/kernel/hardware/driver-api/media/v4l2-videobuf2.md#c-vb2_core_streamon) for Digital TV buffer handling.

**Parameters**

- `struct dvb_vb2_ctx *ctx`: control struct for VB2 handler

**Description**

Starts dvb streaming

#### <a id="c-dvb_vb2_stream_off"></a>`dvb_vb2_stream_off()`

```c
int dvb_vb2_stream_off(struct dvb_vb2_ctx *ctx)
```

Wrapper to [`vb2_core_streamoff()`](/kernel/hardware/driver-api/media/v4l2-videobuf2.md#c-vb2_core_streamoff) for Digital TV buffer handling.

**Parameters**

- `struct dvb_vb2_ctx *ctx`: control struct for VB2 handler

**Description**

Stops dvb streaming

#### <a id="c-dvb_vb2_reqbufs"></a>`dvb_vb2_reqbufs()`

```c
int dvb_vb2_reqbufs(struct dvb_vb2_ctx *ctx, struct dmx_requestbuffers *req)
```

Wrapper to [`vb2_core_reqbufs()`](/kernel/hardware/driver-api/media/v4l2-videobuf2.md#c-vb2_core_reqbufs) for Digital TV buffer handling.

**Parameters**

- `struct dvb_vb2_ctx *ctx`: control struct for VB2 handler
- `struct dmx_requestbuffers *req`: [`struct dmx_requestbuffers`](/kernel/userspace/userspace-api/media-dvb/dmx-types.md#c-struct-dmx_requestbuffers) passed from userspace in
  order to handle `DMX_REQBUFS`.

**Description**

Initiate streaming by requesting a number of buffers. Also used to
free previously requested buffers, is `req->count` is zero.

#### <a id="c-dvb_vb2_querybuf"></a>`dvb_vb2_querybuf()`

```c
int dvb_vb2_querybuf(struct dvb_vb2_ctx *ctx, struct dmx_buffer *b)
```

Wrapper to [`vb2_core_querybuf()`](/kernel/hardware/driver-api/media/v4l2-videobuf2.md#c-vb2_core_querybuf) for Digital TV buffer handling.

**Parameters**

- `struct dvb_vb2_ctx *ctx`: control struct for VB2 handler
- `struct dmx_buffer *b`: [`struct dmx_buffer`](/kernel/userspace/userspace-api/media-dvb/dmx-types.md#c-struct-dmx_buffer) passed from userspace in
  order to handle `DMX_QUERYBUF`.

#### <a id="c-dvb_vb2_expbuf"></a>`dvb_vb2_expbuf()`

```c
int dvb_vb2_expbuf(struct dvb_vb2_ctx *ctx, struct dmx_exportbuffer *exp)
```

Wrapper to [`vb2_core_expbuf()`](/kernel/hardware/driver-api/media/v4l2-videobuf2.md#c-vb2_core_expbuf) for Digital TV buffer handling.

**Parameters**

- `struct dvb_vb2_ctx *ctx`: control struct for VB2 handler
- `struct dmx_exportbuffer *exp`: [`struct dmx_exportbuffer`](/kernel/userspace/userspace-api/media-dvb/dmx-types.md#c-struct-dmx_exportbuffer) passed from userspace in
  order to handle `DMX_EXPBUF`.

**Description**

Export a buffer as a file descriptor.

#### <a id="c-dvb_vb2_qbuf"></a>`dvb_vb2_qbuf()`

```c
int dvb_vb2_qbuf(struct dvb_vb2_ctx *ctx, struct dmx_buffer *b)
```

Wrapper to [`vb2_core_qbuf()`](/kernel/hardware/driver-api/media/v4l2-videobuf2.md#c-vb2_core_qbuf) for Digital TV buffer handling.

**Parameters**

- `struct dvb_vb2_ctx *ctx`: control struct for VB2 handler
- `struct dmx_buffer *b`: [`struct dmx_buffer`](/kernel/userspace/userspace-api/media-dvb/dmx-types.md#c-struct-dmx_buffer) passed from userspace in
  order to handle `DMX_QBUF`.

**Description**

Queue a Digital TV buffer as requested by userspace

#### <a id="c-dvb_vb2_dqbuf"></a>`dvb_vb2_dqbuf()`

```c
int dvb_vb2_dqbuf(struct dvb_vb2_ctx *ctx, struct dmx_buffer *b)
```

Wrapper to [`vb2_core_dqbuf()`](/kernel/hardware/driver-api/media/v4l2-videobuf2.md#c-vb2_core_dqbuf) for Digital TV buffer handling.

**Parameters**

- `struct dvb_vb2_ctx *ctx`: control struct for VB2 handler
- `struct dmx_buffer *b`: [`struct dmx_buffer`](/kernel/userspace/userspace-api/media-dvb/dmx-types.md#c-struct-dmx_buffer) passed from userspace in
  order to handle `DMX_DQBUF`.

**Description**

Dequeue a Digital TV buffer to the userspace

#### <a id="c-dvb_vb2_mmap"></a>`dvb_vb2_mmap()`

```c
int dvb_vb2_mmap(struct dvb_vb2_ctx *ctx, struct vm_area_struct *vma)
```

Wrapper to [`vb2_mmap()`](/kernel/hardware/driver-api/media/v4l2-videobuf2.md#c-vb2_mmap) for Digital TV buffer handling.

**Parameters**

- `struct dvb_vb2_ctx *ctx`: control struct for VB2 handler
- `struct vm_area_struct *vma`: pointer to `struct vm_area_struct` with the vma passed
  to the mmap file operation handler in the driver.

**Description**

map Digital TV video buffers into application address space.

---

# Digital TV (DVB) devices

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Digital TV devices are implemented by several different drivers:

<a id="rst-digital-tv-dvb-devices"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Digital TV devices are implemented by several different drivers:

- A bridge driver that is responsible to talk with the bus where the other devices are connected (PCI, USB, SPI), bind to the other drivers and implement the digital demux logic (either in software or in hardware);

- Frontend drivers that are usually implemented as two separate drivers:

  - A tuner driver that implements the logic which commands the part of the hardware responsible for tuning into a digital TV transponder or physical channel. The output of a tuner is usually a baseband or Intermediate Frequency (IF) signal;

  - A demodulator driver (a.k.a "demod") that implements the logic which commands the digital TV decoding hardware. The output of a demod is a digital stream, with multiple audio, video and data channels typically multiplexed using MPEG Transport Stream <a id="rst-footnote-reference-1"></a>[1](#rst-f1).

On most hardware, the frontend drivers talk with the bridge driver using an I2C bus.

<a id="rst-f1"></a>



**[1]** Some standards use TCP/IP for multiplexing data, like DVB-H (an abandoned standard, not used anymore) and ATSC version 3.0 current proposals. Currently, the DVB subsystem doesn't implement those standards.

- [Digital TV Common functions](</kernel/hardware/driver-api/media/dtv-common.md>)
- [Digital TV Frontend kABI](</kernel/hardware/driver-api/media/dtv-frontend.md>)
- [Digital TV Demux kABI](</kernel/hardware/driver-api/media/dtv-demux.md>)
- [Digital TV Conditional Access kABI](</kernel/hardware/driver-api/media/dtv-ca.md>)
- [Digital TV Network kABI](</kernel/hardware/driver-api/media/dtv-net.md>)

---

# Digital TV Demux kABI

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> The Kernel Digital TV Demux kABI defines a driver-internal interface for registering low-level, hardware specific driver to a hardware independent demux layer. It is only of interest for Digital TV device driver writers. The header file…

<a id="rst-digital-tv-demux-kabi"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-digital-tv-demux"></a>

## Digital TV Demux

The Kernel Digital TV Demux kABI defines a driver-internal interface for registering low-level, hardware specific driver to a hardware independent demux layer. It is only of interest for Digital TV device driver writers. The header file for this kABI is named `demux.h` and located in `include/media`.

The demux kABI should be implemented for each demux in the system. It is used to select the TS source of a demux and to manage the demux resources. When the demux client allocates a resource via the demux kABI, it receives a pointer to the kABI of that resource.

Each demux receives its TS input from a DVB front-end or from memory, as set via this demux kABI. In a system with more than one front-end, the kABI can be used to select one of the DVB front-ends as a TS source for a demux, unless this is fixed in the HW platform.

The demux kABI only controls front-ends regarding to their connections with demuxes; the kABI used to set the other front-end parameters, such as tuning, are defined via the Digital TV Frontend kABI.

The functions that implement the abstract interface demux should be defined static or module private and registered to the Demux core for external access. It is not necessary to implement every function in the struct `dmx_demux`. For example, a demux interface might support Section filtering, but not PES filtering. The kABI client is expected to check the value of any function pointer before calling the function: the value of `NULL` means that the function is not available.

Whenever the functions of the demux API modify shared data, the possibilities of lost update and race condition problems should be addressed, e.g. by protecting parts of code with mutexes.

Note that functions called from a bottom half context must not sleep. Even a simple memory allocation without using `GFP_ATOMIC` can result in a kernel thread being put to sleep if swapping is needed. For example, the Linux Kernel calls the functions of a network device interface from a bottom half context. Thus, if a demux kABI function is called from network device code, the function must not sleep.

<a id="rst-demux-callback-api"></a>

## Demux Callback API

This kernel-space API comprises the callback functions that deliver filtered data to the demux client. Unlike the other DVB kABIs, these functions are provided by the client and called from the demux code.

The function pointers of this abstract interface are not packed into a structure as in the other demux APIs, because the callback functions are registered and used independent of each other. As an example, it is possible for the API client to provide several callback functions for receiving TS packets and no callbacks for PES packets or sections.

The functions that implement the callback API need not be re-entrant: when a demux driver calls one of these functions, the driver is not allowed to call the function again before the original call returns. If a callback is triggered by a hardware interrupt, it is recommended to use the Linux bottom half mechanism or start a tasklet instead of making the callback function call directly from a hardware interrupt.

This mechanism is implemented by `dmx_ts_cb()` and `dmx_section_cb()` callbacks.

<a id="rst-digital-tv-demux-device-registration-functions-and-data-structures"></a>

## Digital TV Demux device registration functions and data structures


#### <a id="c-enum-dmxdev_type"></a>`enum dmxdev_type`

type of demux filter type.

**Constants**

- `DMXDEV_TYPE_NONE`: no filter set.
- `DMXDEV_TYPE_SEC`: section filter.
- `DMXDEV_TYPE_PES`: Program Elementary Stream (PES) filter.

#### <a id="c-enum-dmxdev_state"></a>`enum dmxdev_state`

state machine for the dmxdev.

**Constants**

- `DMXDEV_STATE_FREE`: indicates that the filter is freed.
- `DMXDEV_STATE_ALLOCATED`: indicates that the filter was allocated
  to be used.
- `DMXDEV_STATE_SET`: indicates that the filter parameters are set.
- `DMXDEV_STATE_GO`: indicates that the filter is running.
- `DMXDEV_STATE_DONE`: indicates that a packet was already filtered
  and the filter is now disabled.
  Set only if `DMX_ONESHOT`. See
  [`dmx_sct_filter_params`](/kernel/userspace/userspace-api/media-dvb/dmx-types.md#c-struct-dmx_sct_filter_params).
- `DMXDEV_STATE_TIMEDOUT`: Indicates a timeout condition.

#### <a id="c-struct-dmxdev_feed"></a>`struct dmxdev_feed`

digital TV dmxdev feed

**Definition**

```c
struct dmxdev_feed {
    u16 pid;
    struct dmx_ts_feed *ts;
    struct list_head next;
};
```

**Members**

- `pid`: Program ID to be filtered
- `ts`: pointer to [`struct dmx_ts_feed`](#c-struct-dmx_ts_feed)
- `next`: `struct list_head` pointing to the next feed.

#### <a id="c-struct-dmxdev_filter"></a>`struct dmxdev_filter`

digital TV dmxdev filter

**Definition**

```c
struct dmxdev_filter {
    union {
        struct dmx_section_filter *sec;
    } filter;
    union {
        struct list_head ts;
        struct dmx_section_feed *sec;
    } feed;
    union {
        struct dmx_sct_filter_params sec;
        struct dmx_pes_filter_params pes;
    } params;
    enum dmxdev_type type;
    enum dmxdev_state state;
    struct dmxdev *dev;
    struct dvb_ringbuffer buffer;
    struct dvb_vb2_ctx vb2_ctx;
    struct mutex mutex;
    struct timer_list timer;
    int todo;
    u8 secheader[3];
};
```

**Members**

- `filter`: a union describing a dmxdev filter.
  Currently used only for section filters.
- `filter.sec`: a [`struct dmx_section_filter`](#c-struct-dmx_section_filter) pointer.
  For section filter only.
- `feed`: a union describing a dmxdev feed.
  Depending on the filter type, it can be either
  **feed.ts** or **feed.sec**.
- `feed.ts`: a `struct list_head` list.
  For TS and PES feeds.
- `feed.sec`: a [`struct dmx_section_feed`](#c-struct-dmx_section_feed) pointer.
  For section feed only.
- `params`: a union describing dmxdev filter parameters.
  Depending on the filter type, it can be either
  **params.sec** or **params.pes**.
- `params.sec`: a [`struct dmx_sct_filter_params`](/kernel/userspace/userspace-api/media-dvb/dmx-types.md#c-struct-dmx_sct_filter_params) embedded struct.
  For section filter only.
- `params.pes`: a [`struct dmx_pes_filter_params`](/kernel/userspace/userspace-api/media-dvb/dmx-types.md#c-struct-dmx_pes_filter_params) embedded struct.
  For PES filter only.
- `type`: type of the dmxdev filter, as defined by [`enum dmxdev_type`](#c-enum-dmxdev_type).
- `state`: state of the dmxdev filter, as defined by [`enum dmxdev_state`](#c-enum-dmxdev_state).
- `dev`: pointer to [`struct dmxdev`](#c-struct-dmxdev).
- `buffer`: an embedded [`struct dvb_ringbuffer`](/kernel/hardware/driver-api/media/dtv-common.md#c-struct-dvb_ringbuffer) buffer.
- `vb2_ctx`: control struct for VB2 handler
- `mutex`: protects the access to [`struct dmxdev_filter`](#c-struct-dmxdev_filter).
- `timer`: `struct timer_list` embedded timer, used to check for
  feed timeouts.
  Only for section filter.
- `todo`: index for the **secheader**.
  Only for section filter.
- `secheader`: buffer cache to parse the section header.
  Only for section filter.

#### <a id="c-struct-dmxdev"></a>`struct dmxdev`

Describes a digital TV demux device.

**Definition**

```c
struct dmxdev {
        struct dvb_device *dvbdev;
        struct dvb_device *dvr_dvbdev;
        struct dmxdev_filter *filter;
        struct dmx_demux *demux;
        int filternum;
        int capabilities;
        unsigned int may_do_mmap:1;
        unsigned int exit:1;
    #define DMXDEV_CAP_DUPLEX 1;
        struct dmx_frontend *dvr_orig_fe;
        struct dvb_ringbuffer dvr_buffer;
    #define DVR_BUFFER_SIZE (10*188*1024);
        struct dvb_vb2_ctx dvr_vb2_ctx;
        struct mutex mutex;
        spinlock_t lock;
};
```

**Members**

- `dvbdev`: pointer to [`struct dvb_device`](/kernel/hardware/driver-api/media/dtv-common.md#c-struct-dvb_device) associated with
  the demux device node.
- `dvr_dvbdev`: pointer to [`struct dvb_device`](/kernel/hardware/driver-api/media/dtv-common.md#c-struct-dvb_device) associated with
  the dvr device node.
- `filter`: pointer to [`struct dmxdev_filter`](#c-struct-dmxdev_filter).
- `demux`: pointer to [`struct dmx_demux`](#c-struct-dmx_demux).
- `filternum`: number of filters.
- `capabilities`: demux capabilities as defined by [`enum dmx_demux_caps`](#c-enum-dmx_demux_caps).
- `may_do_mmap`: flag used to indicate if the device may do mmap.
- `exit`: flag to indicate that the demux is being released.
- `dvr_orig_fe`: pointer to [`struct dmx_frontend`](#c-struct-dmx_frontend).
- `dvr_buffer`: embedded [`struct dvb_ringbuffer`](/kernel/hardware/driver-api/media/dtv-common.md#c-struct-dvb_ringbuffer) for DVB output.
- `dvr_vb2_ctx`: control struct for VB2 handler
- `mutex`: protects the usage of this structure.
- `lock`: protects access to [`dmxdev->filter`](#c-struct-dmxdev)->data.

#### <a id="c-dvb_dmxdev_init"></a>`dvb_dmxdev_init()`

```c
int dvb_dmxdev_init(struct dmxdev *dmxdev, struct dvb_adapter *adap)
```

initializes a digital TV demux and registers both demux and DVR devices.

**Parameters**

- `struct dmxdev *dmxdev`: pointer to [`struct dmxdev`](#c-struct-dmxdev).
- `struct dvb_adapter *adap`: pointer to [`struct dvb_adapter`](/kernel/hardware/driver-api/media/dtv-common.md#c-struct-dvb_adapter).

#### <a id="c-dvb_dmxdev_release"></a>`dvb_dmxdev_release()`

```c
void dvb_dmxdev_release(struct dmxdev *dmxdev)
```

releases a digital TV demux and unregisters it.

**Parameters**

- `struct dmxdev *dmxdev`: pointer to [`struct dmxdev`](#c-struct-dmxdev).


<a id="rst-high-level-digital-tv-demux-interface"></a>

## High-level Digital TV demux interface


#### <a id="c-enum-dvb_dmx_filter_type"></a>`enum dvb_dmx_filter_type`

type of demux feed.

**Constants**

- `DMX_TYPE_TS`: feed is in TS mode.
- `DMX_TYPE_SEC`: feed is in Section mode.

#### <a id="c-enum-dvb_dmx_state"></a>`enum dvb_dmx_state`

state machine for a demux filter.

**Constants**

- `DMX_STATE_FREE`: indicates that the filter is freed.
- `DMX_STATE_ALLOCATED`: indicates that the filter was allocated
  to be used.
- `DMX_STATE_READY`: indicates that the filter is ready
  to be used.
- `DMX_STATE_GO`: indicates that the filter is running.

#### <a id="c-struct-dvb_demux_filter"></a>`struct dvb_demux_filter`

Describes a DVB demux section filter.

**Definition**

```c
struct dvb_demux_filter {
    struct dmx_section_filter filter;
    u8 maskandmode[DMX_MAX_FILTER_SIZE];
    u8 maskandnotmode[DMX_MAX_FILTER_SIZE];
    bool doneq;
    struct dvb_demux_filter *next;
    struct dvb_demux_feed *feed;
    int index;
    enum dvb_dmx_state state;
    enum dvb_dmx_filter_type type;
};
```

**Members**

- `filter`: Section filter as defined by [`struct dmx_section_filter`](#c-struct-dmx_section_filter).
- `maskandmode`: logical `and` bit mask.
- `maskandnotmode`: logical `and not` bit mask.
- `doneq`: flag that indicates when a filter is ready.
- `next`: pointer to the next section filter.
- `feed`: [`struct dvb_demux_feed`](#c-struct-dvb_demux_feed) pointer.
- `index`: index of the used demux filter.
- `state`: state of the filter as described by [`enum dvb_dmx_state`](#c-enum-dvb_dmx_state).
- `type`: type of the filter as described
  by [`enum dvb_dmx_filter_type`](#c-enum-dvb_dmx_filter_type).

#### <a id="c-struct-dvb_demux_feed"></a>`struct dvb_demux_feed`

describes a DVB field

**Definition**

```c
struct dvb_demux_feed {
    union {
        struct dmx_ts_feed ts;
        struct dmx_section_feed sec;
    } feed;
    union {
        dmx_ts_cb ts;
        dmx_section_cb sec;
    } cb;
    struct dvb_demux *demux;
    void *priv;
    enum dvb_dmx_filter_type type;
    enum dvb_dmx_state state;
    u16 pid;
    ktime_t timeout;
    struct dvb_demux_filter *filter;
    u32 buffer_flags;
    enum ts_filter_type ts_type;
    enum dmx_ts_pes pes_type;
    int cc;
    bool pusi_seen;
    u16 peslen;
    struct list_head list_head;
    unsigned int index;
};
```

**Members**

- `feed`: a union describing a digital TV feed.
  Depending on the feed type, it can be either
  **feed.ts** or **feed.sec**.
- `feed.ts`: a [`struct dmx_ts_feed`](#c-struct-dmx_ts_feed) pointer.
  For TS feed only.
- `feed.sec`: a [`struct dmx_section_feed`](#c-struct-dmx_section_feed) pointer.
  For section feed only.
- `cb`: a union describing digital TV callbacks.
  Depending on the feed type, it can be either
  **cb.ts** or **cb.sec**.
- `cb.ts`: a [`dmx_ts_cb()`](#c-dmx_ts_cb) calback function pointer.
  For TS feed only.
- `cb.sec`: a [`dmx_section_cb()`](#c-dmx_section_cb) callback function pointer.
  For section feed only.
- `demux`: pointer to [`struct dvb_demux`](#c-struct-dvb_demux).
- `priv`: private data that can optionally be used by a DVB driver.
- `type`: type of the filter, as defined by [`enum dvb_dmx_filter_type`](#c-enum-dvb_dmx_filter_type).
- `state`: state of the filter as defined by [`enum dvb_dmx_state`](#c-enum-dvb_dmx_state).
- `pid`: PID to be filtered.
- `timeout`: feed timeout.
- `filter`: pointer to [`struct dvb_demux_filter`](#c-struct-dvb_demux_filter).
- `buffer_flags`: Buffer flags used to report discontinuity users via DVB
  memory mapped API, as defined by [`enum dmx_buffer_flags`](/kernel/userspace/userspace-api/media-dvb/dmx-types.md#c-enum-dmx_buffer_flags).
- `ts_type`: type of TS, as defined by [`enum ts_filter_type`](#c-enum-ts_filter_type).
- `pes_type`: type of PES, as defined by [`enum dmx_ts_pes`](/kernel/userspace/userspace-api/media-dvb/dmx-types.md#c-enum-dmx_ts_pes).
- `cc`: MPEG-TS packet continuity counter
- `pusi_seen`: if true, indicates that a discontinuity was detected.
  it is used to prevent feeding of garbage from previous section.
- `peslen`: length of the PES (Packet Elementary Stream).
- `list_head`: head for the list of digital TV demux feeds.
- `index`: a unique index for each feed. Can be used as hardware
  pid filter index.

#### <a id="c-struct-dvb_demux"></a>`struct dvb_demux`

represents a digital TV demux

**Definition**

```c
struct dvb_demux {
        struct dmx_demux dmx;
        void *priv;
        int filternum;
        int feednum;
        int (*start_feed)(struct dvb_demux_feed *feed);
        int (*stop_feed)(struct dvb_demux_feed *feed);
        int (*write_to_decoder)(struct dvb_demux_feed *feed, const u8 *buf, size_t len);
        u32 (*check_crc32)(struct dvb_demux_feed *feed, const u8 *buf, size_t len);
        void (*memcopy)(struct dvb_demux_feed *feed, u8 *dst, const u8 *src, size_t len);
        int users;
    #define MAX_DVB_DEMUX_USERS 10;
        struct dvb_demux_filter *filter;
        struct dvb_demux_feed *feed;
        struct list_head frontend_list;
        struct dvb_demux_feed *pesfilter[DMX_PES_OTHER];
        u16 pids[DMX_PES_OTHER];
    #define DMX_MAX_PID 0x2000;
        struct list_head feed_list;
        u8 tsbuf[204];
        int tsbufp;
        struct mutex mutex;
        spinlock_t lock;
        uint8_t *cnt_storage;
        ktime_t speed_last_time;
        uint32_t speed_pkts_cnt;
};
```

**Members**

- `dmx`: embedded [`struct dmx_demux`](#c-struct-dmx_demux) with demux capabilities
  and callbacks.
- `priv`: private data that can optionally be used by
  a DVB driver.
- `filternum`: maximum amount of DVB filters.
- `feednum`: maximum amount of DVB feeds.
- `start_feed`: callback routine to be called in order to start
  a DVB feed.
- `stop_feed`: callback routine to be called in order to stop
  a DVB feed.
- `write_to_decoder`: callback routine to be called if the feed is TS and
  it is routed to an A/V decoder, when a new TS packet
  is received.
  Used only on av7110-av.c.
- `check_crc32`: callback routine to check CRC. If not initialized,
  dvb_demux will use an internal one.
- `memcopy`: callback routine to memcopy received data.
  If not initialized, dvb_demux will default to [`memcpy()`](/kernel/internals/core-api/kernel-api.md#c-memcpy).
- `users`: counter for the number of demux opened file descriptors.
  Currently, it is limited to 10 users.
- `filter`: pointer to [`struct dvb_demux_filter`](#c-struct-dvb_demux_filter).
- `feed`: pointer to [`struct dvb_demux_feed`](#c-struct-dvb_demux_feed).
- `frontend_list`: `struct list_head` with frontends used by the demux.
- `pesfilter`: array of [`struct dvb_demux_feed`](#c-struct-dvb_demux_feed) with the PES types
  that will be filtered.
- `pids`: list of filtered program IDs.
- `feed_list`: `struct list_head` with feeds.
- `tsbuf`: temporary buffer used internally to store TS packets.
- `tsbufp`: temporary buffer index used internally.
- `mutex`: pointer to `struct mutex` used to protect feed set
  logic.
- `lock`: pointer to `spinlock_t`, used to protect buffer handling.
- `cnt_storage`: buffer used for TS/TEI continuity check.
- `speed_last_time`: `ktime_t` used for TS speed check.
- `speed_pkts_cnt`: packets count used for TS speed check.

#### <a id="c-dvb_dmx_init"></a>`dvb_dmx_init()`

```c
int dvb_dmx_init(struct dvb_demux *demux)
```

initialize a digital TV demux struct.

**Parameters**

- `struct dvb_demux *demux`: [`struct dvb_demux`](#c-struct-dvb_demux) to be initialized.

**Description**

Before being able to register a digital TV demux struct, drivers
should call this routine. On its typical usage, some fields should
be initialized at the driver before calling it.

A typical usecase is:

```text
dvb->demux.dmx.capabilities =
        DMX_TS_FILTERING | DMX_SECTION_FILTERING |
        DMX_MEMORY_BASED_FILTERING;
dvb->demux.priv       = dvb;
dvb->demux.filternum  = 256;
dvb->demux.feednum    = 256;
dvb->demux.start_feed = driver_start_feed;
dvb->demux.stop_feed  = driver_stop_feed;
ret = dvb_dmx_init(&dvb->demux);
if (ret < 0)
        return ret;
```

#### <a id="c-dvb_dmx_release"></a>`dvb_dmx_release()`

```c
void dvb_dmx_release(struct dvb_demux *demux)
```

releases a digital TV demux internal buffers.

**Parameters**

- `struct dvb_demux *demux`: [`struct dvb_demux`](#c-struct-dvb_demux) to be released.

**Description**

The DVB core internally allocates data at **demux**. This routine
releases those data. Please notice that the struct itelf is not
released, as it can be embedded on other structs.

#### <a id="c-dvb_dmx_swfilter_packets"></a>`dvb_dmx_swfilter_packets()`

```c
void dvb_dmx_swfilter_packets(struct dvb_demux *demux, const u8 *buf, size_t count)
```

use dvb software filter for a buffer with multiple MPEG-TS packets with 188 bytes each.

**Parameters**

- `struct dvb_demux *demux`: pointer to [`struct dvb_demux`](#c-struct-dvb_demux)
- `const u8 *buf`: buffer with data to be filtered
- `size_t count`: number of MPEG-TS packets with size of 188.

**Description**

The routine will discard a DVB packet that don't start with 0x47.

Use this routine if the DVB demux fills MPEG-TS buffers that are
already aligned.

**NOTE**

The **buf** size should have size equal to `count * 188`.

#### <a id="c-dvb_dmx_swfilter"></a>`dvb_dmx_swfilter()`

```c
void dvb_dmx_swfilter(struct dvb_demux *demux, const u8 *buf, size_t count)
```

use dvb software filter for a buffer with multiple MPEG-TS packets with 188 bytes each.

**Parameters**

- `struct dvb_demux *demux`: pointer to [`struct dvb_demux`](#c-struct-dvb_demux)
- `const u8 *buf`: buffer with data to be filtered
- `size_t count`: number of MPEG-TS packets with size of 188.

**Description**

If a DVB packet doesn't start with 0x47, it will seek for the first
byte that starts with 0x47.

Use this routine if the DVB demux fill buffers that may not start with
a packet start mark (0x47).

**NOTE**

The **buf** size should have size equal to `count * 188`.

#### <a id="c-dvb_dmx_swfilter_204"></a>`dvb_dmx_swfilter_204()`

```c
void dvb_dmx_swfilter_204(struct dvb_demux *demux, const u8 *buf, size_t count)
```

use dvb software filter for a buffer with multiple MPEG-TS packets with 204 bytes each.

**Parameters**

- `struct dvb_demux *demux`: pointer to [`struct dvb_demux`](#c-struct-dvb_demux)
- `const u8 *buf`: buffer with data to be filtered
- `size_t count`: number of MPEG-TS packets with size of 204.

**Description**

If a DVB packet doesn't start with 0x47, it will seek for the first
byte that starts with 0x47.

Use this routine if the DVB demux fill buffers that may not start with
a packet start mark (0x47).

**NOTE**

The **buf** size should have size equal to `count * 204`.

#### <a id="c-dvb_dmx_swfilter_raw"></a>`dvb_dmx_swfilter_raw()`

```c
void dvb_dmx_swfilter_raw(struct dvb_demux *demux, const u8 *buf, size_t count)
```

make the raw data available to userspace without filtering

**Parameters**

- `struct dvb_demux *demux`: pointer to [`struct dvb_demux`](#c-struct-dvb_demux)
- `const u8 *buf`: buffer with data
- `size_t count`: number of packets to be passed. The actual size of each packet
  depends on the [`dvb_demux->feed`](#c-struct-dvb_demux)->cb.ts logic.

**Description**

Use it if the driver needs to deliver the raw payload to userspace without
passing through the kernel demux. That is meant to support some
delivery systems that aren't based on MPEG-TS.

This function relies on [`dvb_demux->feed`](#c-struct-dvb_demux)->cb.ts to actually handle the
buffer.


<a id="rst-driver-internal-low-level-hardware-specific-driver-demux-interface"></a>

## Driver-internal low-level hardware specific driver demux interface


#### <a id="c-enum-ts_filter_type"></a>`enum ts_filter_type`

filter type bitmap for dmx_ts_feed.set\(\)

**Constants**

- `TS_PACKET`: Send TS packets (188 bytes) to callback (default).
- `TS_PAYLOAD_ONLY`: In case TS_PACKET is set, only send the TS payload
  (\<=184 bytes per packet) to callback
- `TS_DECODER`: Send stream to built-in decoder (if present).
- `TS_DEMUX`: In case TS_PACKET is set, send the TS to the demux
  device, not to the dvr device

#### <a id="c-struct-dmx_ts_feed"></a>`struct dmx_ts_feed`

Structure that contains a TS feed filter

**Definition**

```c
struct dmx_ts_feed {
    int is_filtering;
    struct dmx_demux *parent;
    void *priv;
    int (*set)(struct dmx_ts_feed *feed, u16 pid, int type, enum dmx_ts_pes pes_type, ktime_t timeout);
    int (*start_filtering)(struct dmx_ts_feed *feed);
    int (*stop_filtering)(struct dmx_ts_feed *feed);
};
```

**Members**

- `is_filtering`: Set to non-zero when filtering in progress
- `parent`: pointer to struct dmx_demux
- `priv`: pointer to private data of the API client
- `set`: sets the TS filter
- `start_filtering`: starts TS filtering
- `stop_filtering`: stops TS filtering

**Description**

A TS feed is typically mapped to a hardware PID filter on the demux chip.
Using this API, the client can set the filtering properties to start/stop
filtering TS packets on a particular TS feed.

#### <a id="c-struct-dmx_section_filter"></a>`struct dmx_section_filter`

Structure that describes a section filter

**Definition**

```c
struct dmx_section_filter {
    u8 filter_value[DMX_MAX_FILTER_SIZE];
    u8 filter_mask[DMX_MAX_FILTER_SIZE];
    u8 filter_mode[DMX_MAX_FILTER_SIZE];
    struct dmx_section_feed *parent;
    void *priv;
};
```

**Members**

- `filter_value`: Contains up to 16 bytes (128 bits) of the TS section header
  that will be matched by the section filter
- `filter_mask`: Contains a 16 bytes (128 bits) filter mask with the bits
  specified by **filter_value** that will be used on the filter
  match logic.
- `filter_mode`: Contains a 16 bytes (128 bits) filter mode.
- `parent`: Back-pointer to struct dmx_section_feed.
- `priv`: Pointer to private data of the API client.

**Description**

The **filter_mask** controls which bits of **filter_value** are compared with
the section headers/payload. On a binary value of 1 in filter_mask, the
corresponding bits are compared. The filter only accepts sections that are
equal to filter_value in all the tested bit positions.

#### <a id="c-struct-dmx_section_feed"></a>`struct dmx_section_feed`

Structure that contains a section feed filter

**Definition**

```c
struct dmx_section_feed {
    int is_filtering;
    struct dmx_demux *parent;
    void *priv;
    int check_crc;
    int (*set)(struct dmx_section_feed *feed, u16 pid, int check_crc);
    int (*allocate_filter)(struct dmx_section_feed *feed, struct dmx_section_filter **filter);
    int (*release_filter)(struct dmx_section_feed *feed, struct dmx_section_filter *filter);
    int (*start_filtering)(struct dmx_section_feed *feed);
    int (*stop_filtering)(struct dmx_section_feed *feed);
};
```

**Members**

- `is_filtering`: Set to non-zero when filtering in progress
- `parent`: pointer to struct dmx_demux
- `priv`: pointer to private data of the API client
- `check_crc`: If non-zero, check the CRC values of filtered sections.
- `set`: sets the section filter
- `allocate_filter`: This function is used to allocate a section filter on
  the demux. It should only be called when no filtering
  is in progress on this section feed. If a filter cannot
  be allocated, the function fails with -ENOSPC.
- `release_filter`: This function releases all the resources of a
  previously allocated section filter. The function
  should not be called while filtering is in progress
  on this section feed. After calling this function,
  the caller should not try to dereference the filter
  pointer.
- `start_filtering`: starts section filtering
- `stop_filtering`: stops section filtering

**Description**

A TS feed is typically mapped to a hardware PID filter on the demux chip.
Using this API, the client can set the filtering properties to start/stop
filtering TS packets on a particular TS feed.

#### <a id="c-dmx_ts_cb"></a>`dmx_ts_cb()`

```c
typedef int dmx_ts_cb(const u8 *buffer1, size_t buffer1_length, const u8 *buffer2, size_t buffer2_length, struct dmx_ts_feed *source, u32 *buffer_flags)
```

DVB demux TS filter callback function prototype

**Parameters**

- `const u8 *buffer1`: Pointer to the start of the filtered TS packets.
- `size_t buffer1_length`: Length of the TS data in buffer1.
- `const u8 *buffer2`: Pointer to the tail of the filtered TS packets, or NULL.
- `size_t buffer2_length`: Length of the TS data in buffer2.
- `struct dmx_ts_feed *source`: Indicates which TS feed is the source of the callback.
- `u32 *buffer_flags`: Address where buffer flags are stored. Those are
  used to report discontinuity users via DVB
  memory mapped API, as defined by
  [`enum dmx_buffer_flags`](/kernel/userspace/userspace-api/media-dvb/dmx-types.md#c-enum-dmx_buffer_flags).

**Description**

This function callback prototype, provided by the client of the demux API,
is called from the demux code. The function is only called when filtering
on a TS feed has been enabled using the start_filtering\(\) function at
the [`dmx_demux`](#c-struct-dmx_demux).
Any TS packets that match the filter settings are copied to a circular
buffer. The filtered TS packets are delivered to the client using this
callback function.
It is expected that the **buffer1** and **buffer2** callback parameters point to
addresses within the circular buffer, but other implementations are also
possible. Note that the called party should not try to free the memory
the **buffer1** and **buffer2** parameters point to.

When this function is called, the **buffer1** parameter typically points to
the start of the first undelivered TS packet within a circular buffer.
The **buffer2** buffer parameter is normally NULL, except when the received
TS packets have crossed the last address of the circular buffer and
"wrapped" to the beginning of the buffer. In the latter case the **buffer1**
parameter would contain an address within the circular buffer, while the
**buffer2** parameter would contain the first address of the circular buffer.
The number of bytes delivered with this function (i.e. **buffer1_length** +
**buffer2_length**) is usually equal to the value of callback_length parameter
given in the `set()` function, with one exception: if a timeout occurs before
receiving callback_length bytes of TS data, any undelivered packets are
immediately delivered to the client by calling this function. The timeout
duration is controlled by the `set()` function in the TS Feed API.

If a TS packet is received with errors that could not be fixed by the
TS-level forward error correction (FEC), the Transport_error_indicator
flag of the TS packet header should be set. The TS packet should not be
discarded, as the error can possibly be corrected by a higher layer
protocol. If the called party is slow in processing the callback, it
is possible that the circular buffer eventually fills up. If this happens,
the demux driver should discard any TS packets received while the buffer
is full and return -EOVERFLOW.

The type of data returned to the callback can be selected by the
[`dmx_ts_feed`](#c-struct-dmx_ts_feed).**set** function. The type parameter decides if the raw
TS packet (TS_PACKET) or just the payload (TS_PACKET|TS_PAYLOAD_ONLY)
should be returned. If additionally the TS_DECODER bit is set the stream
will also be sent to the hardware MPEG decoder.

- 0, on success;

- -EOVERFLOW, on buffer overflow.

#### <a id="c-dmx_section_cb"></a>`dmx_section_cb()`

```c
typedef int dmx_section_cb(const u8 *buffer1, size_t buffer1_len, const u8 *buffer2, size_t buffer2_len, struct dmx_section_filter *source, u32 *buffer_flags)
```

DVB demux TS filter callback function prototype

**Parameters**

- `const u8 *buffer1`: Pointer to the start of the filtered section, e.g.
  within the circular buffer of the demux driver.
- `size_t buffer1_len`: Length of the filtered section data in **buffer1**,
  including headers and CRC.
- `const u8 *buffer2`: Pointer to the tail of the filtered section data,
  or NULL. Useful to handle the wrapping of a
  circular buffer.
- `size_t buffer2_len`: Length of the filtered section data in **buffer2**,
  including headers and CRC.
- `struct dmx_section_filter *source`: Indicates which section feed is the source of the
  callback.
- `u32 *buffer_flags`: Address where buffer flags are stored. Those are
  used to report discontinuity users via DVB
  memory mapped API, as defined by
  [`enum dmx_buffer_flags`](/kernel/userspace/userspace-api/media-dvb/dmx-types.md#c-enum-dmx_buffer_flags).

**Description**

This function callback prototype, provided by the client of the demux API,
is called from the demux code. The function is only called when
filtering of sections has been enabled using the function
[`dmx_ts_feed`](#c-struct-dmx_ts_feed).**start_filtering**. When the demux driver has received a
complete section that matches at least one section filter, the client
is notified via this callback function. Normally this function is called
for each received section; however, it is also possible to deliver
multiple sections with one callback, for example when the system load
is high. If an error occurs while receiving a section, this
function should be called with the corresponding error type set in the
success field, whether or not there is data to deliver. The Section Feed
implementation should maintain a circular buffer for received sections.
However, this is not necessary if the Section Feed API is implemented as
a client of the TS Feed API, because the TS Feed implementation then
buffers the received data. The size of the circular buffer can be
configured using the [`dmx_ts_feed`](#c-struct-dmx_ts_feed).**set** function in the Section Feed API.
If there is no room in the circular buffer when a new section is received,
the section must be discarded. If this happens, the value of the success
parameter should be DMX_OVERRUN_ERROR on the next callback.

#### <a id="c-enum-dmx_frontend_source"></a>`enum dmx_frontend_source`

Used to identify the type of frontend

**Constants**

- `DMX_MEMORY_FE`: The source of the demux is memory. It means that
  the MPEG-TS to be filtered comes from userspace,
  via `write()` syscall.
- `DMX_FRONTEND_0`: The source of the demux is a frontend connected
  to the demux.

#### <a id="c-struct-dmx_frontend"></a>`struct dmx_frontend`

Structure that lists the frontends associated with a demux

**Definition**

```c
struct dmx_frontend {
    struct list_head connectivity_list;
    enum dmx_frontend_source source;
};
```

**Members**

- `connectivity_list`: List of front-ends that can be connected to a
  particular demux;
- `source`: Type of the frontend.

**Description**

- FIXME: this structure should likely be replaced soon by some

  media-controller based logic.

#### <a id="c-enum-dmx_demux_caps"></a>`enum dmx_demux_caps`

MPEG-2 TS Demux capabilities bitmap

**Constants**

- `DMX_TS_FILTERING`: set if TS filtering is supported;
- `DMX_SECTION_FILTERING`: set if section filtering is supported;
- `DMX_MEMORY_BASED_FILTERING`: set if `write()` available.

**Description**

Those flags are OR'ed in the [`dmx_demux.capabilities`](#c-struct-dmx_demux) field

#### <a id="c-DMX_FE_ENTRY"></a>`DMX_FE_ENTRY()`

```c
DMX_FE_ENTRY(list)
```

Casts elements in the list of registered front-ends from the generic type struct list_head to the type * struct dmx_frontend

**Parameters**

- `list`: list of struct dmx_frontend

#### <a id="c-struct-dmx_demux"></a>`struct dmx_demux`

Structure that contains the demux capabilities and callbacks.

**Definition**

```c
struct dmx_demux {
    enum dmx_demux_caps capabilities;
    struct dmx_frontend *frontend;
    void *priv;
    int (*open)(struct dmx_demux *demux);
    int (*close)(struct dmx_demux *demux);
    int (*write)(struct dmx_demux *demux, const char __user *buf, size_t count);
    int (*allocate_ts_feed)(struct dmx_demux *demux, struct dmx_ts_feed **feed, dmx_ts_cb callback);
    int (*release_ts_feed)(struct dmx_demux *demux, struct dmx_ts_feed *feed);
    int (*allocate_section_feed)(struct dmx_demux *demux, struct dmx_section_feed **feed, dmx_section_cb callback);
    int (*release_section_feed)(struct dmx_demux *demux, struct dmx_section_feed *feed);
    int (*add_frontend)(struct dmx_demux *demux, struct dmx_frontend *frontend);
    int (*remove_frontend)(struct dmx_demux *demux, struct dmx_frontend *frontend);
    struct list_head *(*get_frontends)(struct dmx_demux *demux);
    int (*connect_frontend)(struct dmx_demux *demux, struct dmx_frontend *frontend);
    int (*disconnect_frontend)(struct dmx_demux *demux);
    int (*get_pes_pids)(struct dmx_demux *demux, u16 *pids);
};
```

**Members**

- `capabilities`: Bitfield of capability flags.
- `frontend`: Front-end connected to the demux
- `priv`: Pointer to private data of the API client
- `open`: This function reserves the demux for use by the caller and, if
  necessary, initializes the demux. When the demux is no longer needed,
  the function **close** should be called. It should be possible for
  multiple clients to access the demux at the same time. Thus, the
  function implementation should increment the demux usage count when
  **open** is called and decrement it when **close** is called.
  The **demux** function parameter contains a pointer to the demux API and
  instance data.
  It returns:
  0 on success;
  -EUSERS, if maximum usage count was reached;
  -EINVAL, on bad parameter.
- `close`: This function reserves the demux for use by the caller and, if
  necessary, initializes the demux. When the demux is no longer needed,
  the function **close** should be called. It should be possible for
  multiple clients to access the demux at the same time. Thus, the
  function implementation should increment the demux usage count when
  **open** is called and decrement it when **close** is called.
  The **demux** function parameter contains a pointer to the demux API and
  instance data.
  It returns:
  0 on success;
  -ENODEV, if demux was not in use (e. g. no users);
  -EINVAL, on bad parameter.
- `write`: This function provides the demux driver with a memory buffer
  containing TS packets. Instead of receiving TS packets from the DVB
  front-end, the demux driver software will read packets from memory.
  Any clients of this demux with active TS, PES or Section filters will
  receive filtered data via the Demux callback API (see 0). The function
  returns when all the data in the buffer has been consumed by the demux.
  Demux hardware typically cannot read TS from memory. If this is the
  case, memory-based filtering has to be implemented entirely in software.
  The **demux** function parameter contains a pointer to the demux API and
  instance data.
  The **buf** function parameter contains a pointer to the TS data in
  kernel-space memory.
  The **count** function parameter contains the length of the TS data.
  It returns:
  0 on success;
  -ERESTARTSYS, if mutex lock was interrupted;
  -EINTR, if a signal handling is pending;
  -ENODEV, if demux was removed;
  -EINVAL, on bad parameter.
- `allocate_ts_feed`: Allocates a new TS feed, which is used to filter the TS
  packets carrying a certain PID. The TS feed normally corresponds to a
  hardware PID filter on the demux chip.
  The **demux** function parameter contains a pointer to the demux API and
  instance data.
  The **feed** function parameter contains a pointer to the TS feed API and
  instance data.
  The **callback** function parameter contains a pointer to the callback
  function for passing received TS packet.
  It returns:
  0 on success;
  -ERESTARTSYS, if mutex lock was interrupted;
  -EBUSY, if no more TS feeds is available;
  -EINVAL, on bad parameter.
- `release_ts_feed`: Releases the resources allocated with **allocate_ts_feed**.
  Any filtering in progress on the TS feed should be stopped before
  calling this function.
  The **demux** function parameter contains a pointer to the demux API and
  instance data.
  The **feed** function parameter contains a pointer to the TS feed API and
  instance data.
  It returns:
  0 on success;
  -EINVAL on bad parameter.
- `allocate_section_feed`: Allocates a new section feed, i.e. a demux resource
  for filtering and receiving sections. On platforms with hardware
  support for section filtering, a section feed is directly mapped to
  the demux HW. On other platforms, TS packets are first PID filtered in
  hardware and a hardware section filter then emulated in software. The
  caller obtains an API pointer of type dmx_section_feed_t as an out
  parameter. Using this API the caller can set filtering parameters and
  start receiving sections.
  The **demux** function parameter contains a pointer to the demux API and
  instance data.
  The **feed** function parameter contains a pointer to the TS feed API and
  instance data.
  The **callback** function parameter contains a pointer to the callback
  function for passing received TS packet.
  It returns:
  0 on success;
  -EBUSY, if no more TS feeds is available;
  -EINVAL, on bad parameter.
- `release_section_feed`: Releases the resources allocated with
  **allocate_section_feed**, including allocated filters. Any filtering in
  progress on the section feed should be stopped before calling this
  function.
  The **demux** function parameter contains a pointer to the demux API and
  instance data.
  The **feed** function parameter contains a pointer to the TS feed API and
  instance data.
  It returns:
  0 on success;
  -EINVAL, on bad parameter.
- `add_frontend`: Registers a connectivity between a demux and a front-end,
  i.e., indicates that the demux can be connected via a call to
  **connect_frontend** to use the given front-end as a TS source. The
  client of this function has to allocate dynamic or static memory for
  the frontend structure and initialize its fields before calling this
  function. This function is normally called during the driver
  initialization. The caller must not free the memory of the frontend
  struct before successfully calling **remove_frontend**.
  The **demux** function parameter contains a pointer to the demux API and
  instance data.
  The **frontend** function parameter contains a pointer to the front-end
  instance data.
  It returns:
  0 on success;
  -EINVAL, on bad parameter.
- `remove_frontend`: Indicates that the given front-end, registered by a call
  to **add_frontend**, can no longer be connected as a TS source by this
  demux. The function should be called when a front-end driver or a demux
  driver is removed from the system. If the front-end is in use, the
  function fails with the return value of -EBUSY. After successfully
  calling this function, the caller can free the memory of the frontend
  struct if it was dynamically allocated before the **add_frontend**
  operation.
  The **demux** function parameter contains a pointer to the demux API and
  instance data.
  The **frontend** function parameter contains a pointer to the front-end
  instance data.
  It returns:
  0 on success;
  -ENODEV, if the front-end was not found,
  -EINVAL, on bad parameter.
- `get_frontends`: Provides the APIs of the front-ends that have been
  registered for this demux. Any of the front-ends obtained with this
  call can be used as a parameter for **connect_frontend**. The include
  file demux.h contains the macro [`DMX_FE_ENTRY()`](#c-DMX_FE_ENTRY) for converting an
  element of the generic type struct `list_head` * to the type
  struct [`dmx_frontend`](#c-struct-dmx_frontend) *. The caller must not free the memory of any of
  the elements obtained via this function call.
  The **demux** function parameter contains a pointer to the demux API and
  instance data.
  It returns a struct list_head pointer to the list of front-end
  interfaces, or NULL in the case of an empty list.
- `connect_frontend`: Connects the TS output of the front-end to the input of
  the demux. A demux can only be connected to a front-end registered to
  the demux with the function **add_frontend**. It may or may not be
  possible to connect multiple demuxes to the same front-end, depending
  on the capabilities of the HW platform. When not used, the front-end
  should be released by calling **disconnect_frontend**.
  The **demux** function parameter contains a pointer to the demux API and
  instance data.
  The **frontend** function parameter contains a pointer to the front-end
  instance data.
  It returns:
  0 on success;
  -EINVAL, on bad parameter.
- `disconnect_frontend`: Disconnects the demux and a front-end previously
  connected by a **connect_frontend** call.
  The **demux** function parameter contains a pointer to the demux API and
  instance data.
  It returns:
  0 on success;
  -EINVAL on bad parameter.
- `get_pes_pids`: Get the PIDs for DMX_PES_AUDIO0, DMX_PES_VIDEO0,
  DMX_PES_TELETEXT0, DMX_PES_SUBTITLE0 and DMX_PES_PCR0.
  The **demux** function parameter contains a pointer to the demux API and
  instance data.
  The **pids** function parameter contains an array with five u16 elements
  where the PIDs will be stored.
  It returns:
  0 on success;
  -EINVAL on bad parameter.

---

# Digital TV Frontend kABI

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> The Digital TV Frontend kABI defines a driver-internal interface for registering low-level, hardware specific driver to a hardware independent frontend layer. It is only of interest for Digital TV device driver writers. The header file for…

<a id="rst-digital-tv-frontend-kabi"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-digital-tv-frontend"></a>

## Digital TV Frontend

The Digital TV Frontend kABI defines a driver-internal interface for registering low-level, hardware specific driver to a hardware independent frontend layer. It is only of interest for Digital TV device driver writers. The header file for this API is named `dvb_frontend.h` and located in `include/media/`.

<a id="rst-demodulator-driver"></a>

### Demodulator driver

The demodulator driver is responsible for talking with the decoding part of the hardware. Such driver should implement `dvb_frontend_ops`, which tells what type of digital TV standards are supported, and points to a series of functions that allow the DVB core to command the hardware via the code under `include/media/dvb_frontend.c`.

A typical example of such struct in a driver `foo` is:



```text
static struct dvb_frontend_ops foo_ops = {
        .delsys = { SYS_DVBT, SYS_DVBT2, SYS_DVBC_ANNEX_A },
        .info = {
                .name   = "foo DVB-T/T2/C driver",
                .caps = FE_CAN_FEC_1_2 |
                        FE_CAN_FEC_2_3 |
                        FE_CAN_FEC_3_4 |
                        FE_CAN_FEC_5_6 |
                        FE_CAN_FEC_7_8 |
                        FE_CAN_FEC_AUTO |
                        FE_CAN_QPSK |
                        FE_CAN_QAM_16 |
                        FE_CAN_QAM_32 |
                        FE_CAN_QAM_64 |
                        FE_CAN_QAM_128 |
                        FE_CAN_QAM_256 |
                        FE_CAN_QAM_AUTO |
                        FE_CAN_TRANSMISSION_MODE_AUTO |
                        FE_CAN_GUARD_INTERVAL_AUTO |
                        FE_CAN_HIERARCHY_AUTO |
                        FE_CAN_MUTE_TS |
                        FE_CAN_2G_MODULATION,
                .frequency_min = 42000000, /* Hz */
                .frequency_max = 1002000000, /* Hz */
                .symbol_rate_min = 870000,
                .symbol_rate_max = 11700000
        },
        .init = foo_init,
        .sleep = foo_sleep,
        .release = foo_release,
        .set_frontend = foo_set_frontend,
        .get_frontend = foo_get_frontend,
        .read_status = foo_get_status_and_stats,
        .tune = foo_tune,
        .i2c_gate_ctrl = foo_i2c_gate_ctrl,
        .get_frontend_algo = foo_get_algo,
};
```

A typical example of such struct in a driver `bar` meant to be used on Satellite TV reception is:



```text
static const struct dvb_frontend_ops bar_ops = {
        .delsys = { SYS_DVBS, SYS_DVBS2 },
        .info = {
                .name           = "Bar DVB-S/S2 demodulator",
                .frequency_min  = 500000, /* KHz */
                .frequency_max  = 2500000, /* KHz */
                .frequency_stepsize     = 0,
                .symbol_rate_min = 1000000,
                .symbol_rate_max = 45000000,
                .symbol_rate_tolerance = 500,
                .caps = FE_CAN_INVERSION_AUTO |
                        FE_CAN_FEC_AUTO |
                        FE_CAN_QPSK,
        },
        .init = bar_init,
        .sleep = bar_sleep,
        .release = bar_release,
        .set_frontend = bar_set_frontend,
        .get_frontend = bar_get_frontend,
        .read_status = bar_get_status_and_stats,
        .i2c_gate_ctrl = bar_i2c_gate_ctrl,
        .get_frontend_algo = bar_get_algo,
        .tune = bar_tune,

        /* Satellite-specific */
        .diseqc_send_master_cmd = bar_send_diseqc_msg,
        .diseqc_send_burst = bar_send_burst,
        .set_tone = bar_set_tone,
        .set_voltage = bar_set_voltage,
};
```

> [!NOTE]
>
> 1. For satellite digital TV standards (DVB-S, DVB-S2, ISDB-S), the frequencies are specified in kHz, while, for terrestrial and cable standards, they're specified in Hz. Due to that, if the same frontend supports both types, you'll need to have two separate `dvb_frontend_ops` structures, one for each standard.
>
> 2. The `.i2c_gate_ctrl` field is present only when the hardware has allows controlling an I2C gate (either directly of via some GPIO pin), in order to remove the tuner from the I2C bus after a channel is tuned.
>
> 3. All new drivers should implement the [DVBv5 statistics](<#rst-dvbv5-stats>) via `.read_status`. Yet, there are a number of callbacks meant to get statistics for signal strength, S/N and UCB. Those are there to provide backward compatibility with legacy applications that don't support the DVBv5 API. Implementing those callbacks are optional. Those callbacks may be removed in the future, after we have all existing drivers supporting DVBv5 stats.
>
> 4. Other callbacks are required for satellite TV standards, in order to control LNBf and DiSEqC: `.diseqc_send_master_cmd`, `.diseqc_send_burst`, `.set_tone`, `.set_voltage`.

The `include/media/dvb_frontend.c` has a kernel thread which is responsible for tuning the device. It supports multiple algorithms to detect a channel, as defined at enum `dvbfe_algo()`.

The algorithm to be used is obtained via `.get_frontend_algo`. If the driver doesn't fill its field at struct dvb_frontend_ops, it will default to `DVBFE_ALGO_SW`, meaning that the dvb-core will do a zigzag when tuning, e. g. it will try first to use the specified center frequency `f`, then, it will do `f` + Δ, `f` - Δ, `f` + 2 x Δ, `f` - 2 x Δ and so on.

If the hardware has internally a some sort of zigzag algorithm, you should define a `.get_frontend_algo` function that would return `DVBFE_ALGO_HW`.

> [!NOTE]
>
> The core frontend support also supports a third type (`DVBFE_ALGO_CUSTOM`), in order to allow the driver to define its own hardware-assisted algorithm. Very few hardware need to use it nowadays. Using `DVBFE_ALGO_CUSTOM` require to provide other function callbacks at struct dvb_frontend_ops.

<a id="rst-attaching-frontend-driver-to-the-bridge-driver"></a>

### Attaching frontend driver to the bridge driver

Before using the Digital TV frontend core, the bridge driver should attach the frontend demod, tuner and SEC devices and call `dvb_register_frontend()`, in order to register the new frontend at the subsystem. At device detach/removal, the bridge driver should call `dvb_unregister_frontend()` to remove the frontend from the core and then `dvb_frontend_detach()` to free the memory allocated by the frontend drivers.

The drivers should also call `dvb_frontend_suspend()` as part of their handler for the `device_driver`.`suspend()`, and `dvb_frontend_resume()` as part of their handler for `device_driver`.`resume()`.

A few other optional functions are provided to handle some special cases.

<a id="rst-digital-tv-frontend-statistics"></a>
<a id="rst-dvbv5-stats"></a>

## Digital TV Frontend statistics

<a id="rst-introduction"></a>

### Introduction

Digital TV frontends provide a range of [statistics](</kernel/userspace/userspace-api/media-dvb/frontend-stat-properties.md#rst-frontend-stat-properties>) meant to help tuning the device and measuring the quality of service.

For each statistics measurement, the driver should set the type of scale used, or `FE_SCALE_NOT_AVAILABLE` if the statistics is not available on a given time. Drivers should also provide the number of statistics for each type. that's usually 1 for most video standards <a id="rst-footnote-reference-1"></a>[1](#rst-f2).

Drivers should initialize each statistic counters with length and scale at its init code. For example, if the frontend provides signal strength, it should have, on its init code:



```text
struct dtv_frontend_properties *c = &state->fe.dtv_property_cache;

c->strength.len = 1;
c->strength.stat[0].scale = FE_SCALE_NOT_AVAILABLE;
```

And, when the statistics got updated, set the scale:



```text
c->strength.stat[0].scale = FE_SCALE_DECIBEL;
c->strength.stat[0].uvalue = strength;
```

<a id="rst-f2"></a>



**[1]** For ISDB-T, it may provide both a global statistics and a per-layer set of statistics. On such cases, len should be equal to 4. The first value corresponds to the global stat; the other ones to each layer, e. g.:

- c-&gt;cnr.stat\[0\] for global S/N carrier ratio,

- c-&gt;cnr.stat\[1\] for Layer A S/N carrier ratio,

- c-&gt;cnr.stat\[2\] for layer B S/N carrier ratio,

- c-&gt;cnr.stat\[3\] for layer C S/N carrier ratio.

> [!NOTE]
>
> Please prefer to use `FE_SCALE_DECIBEL` instead of `FE_SCALE_RELATIVE` for signal strength and CNR measurements.

<a id="rst-groups-of-statistics"></a>

### Groups of statistics

There are several groups of statistics currently supported:

- **Signal strength ([DTV_STAT_SIGNAL_STRENGTH](</kernel/userspace/userspace-api/media-dvb/frontend-stat-properties.md#rst-dtv-stat-signal-strength>))**

  - Measures the signal strength level at the analog part of the tuner or demod.

  - Typically obtained from the gain applied to the tuner and/or frontend in order to detect the carrier. When no carrier is detected, the gain is at the maximum value (so, strength is on its minimal).

  - As the gain is visible through the set of registers that adjust the gain, typically, this statistics is always available <a id="rst-footnote-reference-2"></a>[2](#rst-f3).

  - Drivers should try to make it available all the times, as these statistics can be used when adjusting an antenna position and to check for troubles at the cabling.

  <a id="rst-f3"></a>



  **[2]** On a few devices, the gain keeps floating if there is no carrier. On such devices, strength report should check first if carrier is detected at the tuner (`FE_HAS_CARRIER`, see `fe_status`), and otherwise return the lowest possible value.

- **Carrier Signal to Noise ratio ([DTV_STAT_CNR](</kernel/userspace/userspace-api/media-dvb/frontend-stat-properties.md#rst-dtv-stat-cnr>))**

  - Signal to Noise ratio for the main carrier.

  - Signal to Noise measurement depends on the device. On some hardware, it is available when the main carrier is detected. On those hardware, CNR measurement usually comes from the tuner (e. g. after `FE_HAS_CARRIER`, see `fe_status`).

    On other devices, it requires inner FEC decoding, as the frontend measures it indirectly from other parameters (e. g. after `FE_HAS_VITERBI`, see `fe_status`).

    Having it available after inner FEC is more common.

- **Bit counts post-FEC ([DTV_STAT_POST_ERROR_BIT_COUNT](</kernel/userspace/userspace-api/media-dvb/frontend-stat-properties.md#rst-dtv-stat-post-error-bit-count>) and [DTV_STAT_POST_TOTAL_BIT_COUNT](</kernel/userspace/userspace-api/media-dvb/frontend-stat-properties.md#rst-dtv-stat-post-total-bit-count>))**

  - Those counters measure the number of bits and bit errors after the forward error correction (FEC) on the inner coding block (after Viterbi, LDPC or other inner code).

  - Due to its nature, those statistics depend on full coding lock (e. g. after `FE_HAS_SYNC` or after `FE_HAS_LOCK`, see `fe_status`).

- **Bit counts pre-FEC ([DTV_STAT_PRE_ERROR_BIT_COUNT](</kernel/userspace/userspace-api/media-dvb/frontend-stat-properties.md#rst-dtv-stat-pre-error-bit-count>) and [DTV_STAT_PRE_TOTAL_BIT_COUNT](</kernel/userspace/userspace-api/media-dvb/frontend-stat-properties.md#rst-dtv-stat-pre-total-bit-count>))**

  - Those counters measure the number of bits and bit errors before the forward error correction (FEC) on the inner coding block (before Viterbi, LDPC or other inner code).

  - Not all frontends provide this kind of statistics.

  - Due to its nature, those statistics depend on inner coding lock (e. g. after `FE_HAS_VITERBI`, see `fe_status`).

- **Block counts ([DTV_STAT_ERROR_BLOCK_COUNT](</kernel/userspace/userspace-api/media-dvb/frontend-stat-properties.md#rst-dtv-stat-error-block-count>) and [DTV-STAT_TOTAL_BLOCK_COUNT](</kernel/userspace/userspace-api/media-dvb/frontend-stat-properties.md#rst-dtv-stat-total-block-count>))**

  - Those counters measure the number of blocks and block errors after the forward error correction (FEC) on the inner coding block (before Viterbi, LDPC or other inner code).

  - Due to its nature, those statistics depend on full coding lock (e. g. after `FE_HAS_SYNC` or after `FE_HAS_LOCK`, see `fe_status`).

> [!NOTE]
>
> All counters should be monotonically increased as they're collected from the hardware.

A typical example of the logic that handle status and statistics is:



```text
static int foo_get_status_and_stats(struct dvb_frontend *fe)
{
        struct foo_state *state = fe->demodulator_priv;
        struct dtv_frontend_properties *c = &fe->dtv_property_cache;

        int rc;
        enum fe_status *status;

        /* Both status and strength are always available */
        rc = foo_read_status(fe, &status);
        if (rc < 0)
                return rc;

        rc = foo_read_strength(fe);
        if (rc < 0)
                return rc;

        /* Check if CNR is available */
        if (!(fe->status & FE_HAS_CARRIER))
                return 0;

        rc = foo_read_cnr(fe);
        if (rc < 0)
                return rc;

        /* Check if pre-BER stats are available */
        if (!(fe->status & FE_HAS_VITERBI))
                return 0;

        rc = foo_get_pre_ber(fe);
        if (rc < 0)
                return rc;

        /* Check if post-BER stats are available */
        if (!(fe->status & FE_HAS_SYNC))
                return 0;

        rc = foo_get_post_ber(fe);
        if (rc < 0)
                return rc;
}

static const struct dvb_frontend_ops ops = {
        /* ... */
        .read_status = foo_get_status_and_stats,
};
```

<a id="rst-statistics-collection"></a>

### Statistics collection

On almost all frontend hardware, the bit and byte counts are stored by the hardware after a certain amount of time or after the total bit/block counter reaches a certain value (usually programmable), for example, on every 1000 ms or after receiving 1,000,000 bits.

So, if you read the registers too soon, you'll end by reading the same value as in the previous reading, causing the monotonic value to be incremented too often.

Drivers should take the responsibility to avoid too often reads. That can be done using two approaches:

<a id="rst-if-the-driver-have-a-bit-that-indicates-when-a-collected-data-is-ready"></a>

#### if the driver have a bit that indicates when a collected data is ready

Driver should check such bit before making the statistics available.

An example of such behavior can be found at this code snippet (adapted from mb86a20s driver's logic):



```text
static int foo_get_pre_ber(struct dvb_frontend *fe)
{
        struct foo_state *state = fe->demodulator_priv;
        struct dtv_frontend_properties *c = &fe->dtv_property_cache;
        int rc, bit_error;

        /* Check if the BER measures are already available */
        rc = foo_read_u8(state, 0x54);
        if (rc < 0)
                return rc;

        if (!rc)
                return 0;

        /* Read Bit Error Count */
        bit_error = foo_read_u32(state, 0x55);
        if (bit_error < 0)
                return bit_error;

        /* Read Total Bit Count */
        rc = foo_read_u32(state, 0x51);
        if (rc < 0)
                return rc;

        c->pre_bit_error.stat[0].scale = FE_SCALE_COUNTER;
        c->pre_bit_error.stat[0].uvalue += bit_error;
        c->pre_bit_count.stat[0].scale = FE_SCALE_COUNTER;
        c->pre_bit_count.stat[0].uvalue += rc;

        return 0;
}
```

<a id="rst-if-the-driver-doesn-t-provide-a-statistics-available-check-bit"></a>

#### If the driver doesn't provide a statistics available check bit

A few devices, however, may not provide a way to check if the stats are available (or the way to check it is unknown). They may not even provide a way to directly read the total number of bits or blocks.

On those devices, the driver need to ensure that it won't be reading from the register too often and/or estimate the total number of bits/blocks.

On such drivers, a typical routine to get statistics would be like (adapted from dib8000 driver's logic):



```text
struct foo_state {
        /* ... */

        unsigned long per_jiffies_stats;
}

static int foo_get_pre_ber(struct dvb_frontend *fe)
{
        struct foo_state *state = fe->demodulator_priv;
        struct dtv_frontend_properties *c = &fe->dtv_property_cache;
        int rc, bit_error;
        u64 bits;

        /* Check if time for stats was elapsed */
        if (!time_after(jiffies, state->per_jiffies_stats))
                return 0;

        /* Next stat should be collected in 1000 ms */
        state->per_jiffies_stats = jiffies + msecs_to_jiffies(1000);

        /* Read Bit Error Count */
        bit_error = foo_read_u32(state, 0x55);
        if (bit_error < 0)
                return bit_error;

        /*
         * On this particular frontend, there's no register that
         * would provide the number of bits per 1000ms sample. So,
         * some function would calculate it based on DTV properties
         */
        bits = get_number_of_bits_per_1000ms(fe);

        c->pre_bit_error.stat[0].scale = FE_SCALE_COUNTER;
        c->pre_bit_error.stat[0].uvalue += bit_error;
        c->pre_bit_count.stat[0].scale = FE_SCALE_COUNTER;
        c->pre_bit_count.stat[0].uvalue += bits;

        return 0;
}
```

Please notice that, on both cases, we're getting the statistics using the `dvb_frontend_ops` `.read_status` callback. The rationale is that the frontend core will automatically call this function periodically (usually, 3 times per second, when the frontend is locked).

That warrants that we won't miss to collect a counter and increment the monotonic stats at the right time.

<a id="rst-digital-tv-frontend-functions-and-types"></a>

## Digital TV Frontend functions and types


#### <a id="c-struct-dvb_frontend_tune_settings"></a>`struct dvb_frontend_tune_settings`

parameters to adjust frontend tuning

**Definition**

```c
struct dvb_frontend_tune_settings {
    int min_delay_ms;
    int step_size;
    int max_drift;
};
```

**Members**

- `min_delay_ms`: minimum delay for tuning, in ms
- `step_size`: step size between two consecutive frequencies
- `max_drift`: maximum drift

**NOTE**

step_size is in Hz, for terrestrial/cable or kHz for satellite

#### <a id="c-struct-dvb_tuner_info"></a>`struct dvb_tuner_info`

Frontend name and min/max ranges/bandwidths

**Definition**

```c
struct dvb_tuner_info {
    char name[128];
    u32 frequency_min_hz;
    u32 frequency_max_hz;
    u32 frequency_step_hz;
    u32 bandwidth_min;
    u32 bandwidth_max;
    u32 bandwidth_step;
};
```

**Members**

- `name`: name of the Frontend
- `frequency_min_hz`: minimal frequency supported in Hz
- `frequency_max_hz`: maximum frequency supported in Hz
- `frequency_step_hz`: frequency step in Hz
- `bandwidth_min`: minimal frontend bandwidth supported
- `bandwidth_max`: maximum frontend bandwidth supported
- `bandwidth_step`: frontend bandwidth step

#### <a id="c-struct-analog_parameters"></a>`struct analog_parameters`

Parameters to tune into an analog/radio channel

**Definition**

```c
struct analog_parameters {
    unsigned int frequency;
    unsigned int mode;
    unsigned int audmode;
    u64 std;
};
```

**Members**

- `frequency`: Frequency used by analog TV tuner (either in 62.5 kHz step,
  for TV, or 62.5 Hz for radio)
- `mode`: Tuner mode, as defined on enum v4l2_tuner_type
- `audmode`: Audio mode as defined for the rxsubchans field at videodev2.h,
  e. g. V4L2_TUNER_MODE_*
- `std`: TV standard bitmap as defined at videodev2.h, e. g. V4L2_STD_*

**Description**

Hybrid tuners should be supported by both V4L2 and DVB APIs. This
struct contains the data that are used by the V4L2 side. To avoid
dependencies from V4L2 headers, all enums here are declared as integers.

#### <a id="c-enum-dvbfe_algo"></a>`enum dvbfe_algo`

defines the algorithm used to tune into a channel

**Constants**

- `DVBFE_ALGO_HW`: Hardware Algorithm -
  Devices that support this algorithm do everything in hardware
  and no software support is needed to handle them.
  Requesting these devices to LOCK is the only thing required,
  device is supposed to do everything in the hardware.
- `DVBFE_ALGO_SW`: Software Algorithm -
  These are dumb devices, that require software to do everything
- `DVBFE_ALGO_CUSTOM`: Customizable Agorithm -
  Devices having this algorithm can be customized to have specific
  algorithms in the frontend driver, rather than simply doing a
  software zig-zag. In this case the zigzag maybe hardware assisted
  or it maybe completely done in hardware. In all cases, usage of
  this algorithm, in conjunction with the search and track
  callbacks, utilizes the driver specific algorithm.
- `DVBFE_ALGO_RECOVERY`: Recovery Algorithm -
  These devices have AUTO recovery capabilities from LOCK failure

#### <a id="c-enum-dvbfe_search"></a>`enum dvbfe_search`

search callback possible return status

**Constants**

- `DVBFE_ALGO_SEARCH_SUCCESS`: The frontend search algorithm completed and returned successfully
- `DVBFE_ALGO_SEARCH_ASLEEP`: The frontend search algorithm is sleeping
- `DVBFE_ALGO_SEARCH_FAILED`: The frontend search for a signal failed
- `DVBFE_ALGO_SEARCH_INVALID`: The frontend search algorithm was probably supplied with invalid
  parameters and the search is an invalid one
- `DVBFE_ALGO_SEARCH_AGAIN`: The frontend search algorithm was requested to search again
- `DVBFE_ALGO_SEARCH_ERROR`: The frontend search algorithm failed due to some error

#### <a id="c-struct-dvb_tuner_ops"></a>`struct dvb_tuner_ops`

Tuner information and callbacks

**Definition**

```c
struct dvb_tuner_ops {
        struct dvb_tuner_info info;
        void (*release)(struct dvb_frontend *fe);
        int (*init)(struct dvb_frontend *fe);
        int (*sleep)(struct dvb_frontend *fe);
        int (*suspend)(struct dvb_frontend *fe);
        int (*resume)(struct dvb_frontend *fe);
        int (*set_params)(struct dvb_frontend *fe);
        int (*set_analog_params)(struct dvb_frontend *fe, struct analog_parameters *p);
        int (*set_config)(struct dvb_frontend *fe, void *priv_cfg);
        int (*get_frequency)(struct dvb_frontend *fe, u32 *frequency);
        int (*get_bandwidth)(struct dvb_frontend *fe, u32 *bandwidth);
        int (*get_if_frequency)(struct dvb_frontend *fe, u32 *frequency);
    #define TUNER_STATUS_LOCKED 1;
    #define TUNER_STATUS_STEREO 2;
        int (*get_status)(struct dvb_frontend *fe, u32 *status);
        int (*get_rf_strength)(struct dvb_frontend *fe, u16 *strength);
        int (*get_afc)(struct dvb_frontend *fe, s32 *afc);
        int (*calc_regs)(struct dvb_frontend *fe, u8 *buf, int buf_len);
        int (*set_frequency)(struct dvb_frontend *fe, u32 frequency);
        int (*set_bandwidth)(struct dvb_frontend *fe, u32 bandwidth);
};
```

**Members**

- `info`: embedded [`struct dvb_tuner_info`](#c-struct-dvb_tuner_info) with tuner properties
- `release`: callback function called when frontend is detached.
  drivers should free any allocated memory.
- `init`: callback function used to initialize the tuner device.
- `sleep`: callback function used to put the tuner to sleep.
- `suspend`: callback function used to inform that the Kernel will
  suspend.
- `resume`: callback function used to inform that the Kernel is
  resuming from suspend.
- `set_params`: callback function used to inform the tuner to tune
  into a digital TV channel. The properties to be used
  are stored at [`struct dvb_frontend`](#c-struct-dvb_frontend).dtv_property_cache.
  The tuner demod can change the parameters to reflect
  the changes needed for the channel to be tuned, and
  update statistics. This is the recommended way to set
  the tuner parameters and should be used on newer
  drivers.
- `set_analog_params`: callback function used to tune into an analog TV
  channel on hybrid tuners. It passes **analog_parameters**
  to the driver.
- `set_config`: callback function used to send some tuner-specific
  parameters.
- `get_frequency`: get the actual tuned frequency
- `get_bandwidth`: get the bandwidth used by the low pass filters
- `get_if_frequency`: get the Intermediate Frequency, in Hz. For baseband,
  should return 0.
- `get_status`: returns the frontend lock status
- `get_rf_strength`: returns the RF signal strength. Used mostly to support
  analog TV and radio. Digital TV should report, instead,
  via DVBv5 API ([`struct dvb_frontend`](#c-struct-dvb_frontend).dtv_property_cache).
- `get_afc`: Used only by analog TV core. Reports the frequency
  drift due to AFC.
- `calc_regs`: callback function used to pass register data settings
  for simple tuners.  Shouldn't be used on newer drivers.
- `set_frequency`: Set a new frequency. Shouldn't be used on newer drivers.
- `set_bandwidth`: Set a new frequency. Shouldn't be used on newer drivers.

**NOTE**

frequencies used on **get_frequency** and **set_frequency** are in Hz for
terrestrial/cable or kHz for satellite.

#### <a id="c-struct-analog_demod_info"></a>`struct analog_demod_info`

Information struct for analog TV part of the demod

**Definition**

```c
struct analog_demod_info {
    char *name;
};
```

**Members**

- `name`: Name of the analog TV demodulator

#### <a id="c-struct-analog_demod_ops"></a>`struct analog_demod_ops`

Demodulation information and callbacks for analog TV and radio

**Definition**

```c
struct analog_demod_ops {
    struct analog_demod_info info;
    void (*set_params)(struct dvb_frontend *fe, struct analog_parameters *params);
    int (*has_signal)(struct dvb_frontend *fe, u16 *signal);
    int (*get_afc)(struct dvb_frontend *fe, s32 *afc);
    void (*tuner_status)(struct dvb_frontend *fe);
    void (*standby)(struct dvb_frontend *fe);
    void (*release)(struct dvb_frontend *fe);
    int (*i2c_gate_ctrl)(struct dvb_frontend *fe, int enable);
    int (*set_config)(struct dvb_frontend *fe, void *priv_cfg);
};
```

**Members**

- `info`: pointer to struct analog_demod_info
- `set_params`: callback function used to inform the demod to set the
  demodulator parameters needed to decode an analog or
  radio channel. The properties are passed via
  `struct analog_params`.
- `has_signal`: returns 0xffff if has signal, or 0 if it doesn't.
- `get_afc`: Used only by analog TV core. Reports the frequency
  drift due to AFC.
- `tuner_status`: callback function that returns tuner status bits, e. g.
  `TUNER_STATUS_LOCKED` and `TUNER_STATUS_STEREO`.
- `standby`: set the tuner to standby mode.
- `release`: callback function called when frontend is detached.
  drivers should free any allocated memory.
- `i2c_gate_ctrl`: controls the I2C gate. Newer drivers should use I2C
  mux support instead.
- `set_config`: callback function used to send some tuner-specific
  parameters.

#### <a id="c-struct-dvb_frontend_internal_info"></a>`struct dvb_frontend_internal_info`

Frontend properties and capabilities

**Definition**

```c
struct dvb_frontend_internal_info {
    char name[128];
    u32 frequency_min_hz;
    u32 frequency_max_hz;
    u32 frequency_stepsize_hz;
    u32 frequency_tolerance_hz;
    u32 symbol_rate_min;
    u32 symbol_rate_max;
    u32 symbol_rate_tolerance;
    enum fe_caps caps;
};
```

**Members**

- `name`: Name of the frontend
- `frequency_min_hz`: Minimal frequency supported by the frontend.
- `frequency_max_hz`: Minimal frequency supported by the frontend.
- `frequency_stepsize_hz`: All frequencies are multiple of this value.
- `frequency_tolerance_hz`: Frequency tolerance.
- `symbol_rate_min`: Minimal symbol rate, in bauds
  (for Cable/Satellite systems).
- `symbol_rate_max`: Maximal symbol rate, in bauds
  (for Cable/Satellite systems).
- `symbol_rate_tolerance`: Maximal symbol rate tolerance, in ppm
  (for Cable/Satellite systems).
- `caps`: Capabilities supported by the frontend,
  as specified in [`enum fe_caps`](/kernel/userspace/userspace-api/media-dvb/frontend-header.md#c-enum-fe_caps).

#### <a id="c-struct-dvb_frontend_ops"></a>`struct dvb_frontend_ops`

Demodulation information and callbacks for ditialt TV

**Definition**

```c
struct dvb_frontend_ops {
    struct dvb_frontend_internal_info info;
    u8 delsys[MAX_DELSYS];
    void (*detach)(struct dvb_frontend *fe);
    void (*release)(struct dvb_frontend* fe);
    void (*release_sec)(struct dvb_frontend* fe);
    int (*init)(struct dvb_frontend* fe);
    int (*sleep)(struct dvb_frontend* fe);
    int (*suspend)(struct dvb_frontend *fe);
    int (*resume)(struct dvb_frontend *fe);
    int (*write)(struct dvb_frontend* fe, const u8 buf[], int len);
    int (*tune)(struct dvb_frontend* fe, bool re_tune, unsigned int mode_flags, unsigned int *delay, enum fe_status *status);
    enum dvbfe_algo (*get_frontend_algo)(struct dvb_frontend *fe);
    int (*set_frontend)(struct dvb_frontend *fe);
    int (*get_tune_settings)(struct dvb_frontend* fe, struct dvb_frontend_tune_settings* settings);
    int (*get_frontend)(struct dvb_frontend *fe, struct dtv_frontend_properties *props);
    int (*read_status)(struct dvb_frontend *fe, enum fe_status *status);
    int (*read_ber)(struct dvb_frontend* fe, u32* ber);
    int (*read_signal_strength)(struct dvb_frontend* fe, u16* strength);
    int (*read_snr)(struct dvb_frontend* fe, u16* snr);
    int (*read_ucblocks)(struct dvb_frontend* fe, u32* ucblocks);
    int (*diseqc_reset_overload)(struct dvb_frontend* fe);
    int (*diseqc_send_master_cmd)(struct dvb_frontend* fe, struct dvb_diseqc_master_cmd* cmd);
    int (*diseqc_recv_slave_reply)(struct dvb_frontend* fe, struct dvb_diseqc_slave_reply* reply);
    int (*diseqc_send_burst)(struct dvb_frontend *fe, enum fe_sec_mini_cmd minicmd);
    int (*set_tone)(struct dvb_frontend *fe, enum fe_sec_tone_mode tone);
    int (*set_voltage)(struct dvb_frontend *fe, enum fe_sec_voltage voltage);
    int (*enable_high_lnb_voltage)(struct dvb_frontend* fe, long arg);
    int (*dishnetwork_send_legacy_command)(struct dvb_frontend* fe, unsigned long cmd);
    int (*i2c_gate_ctrl)(struct dvb_frontend* fe, int enable);
    int (*ts_bus_ctrl)(struct dvb_frontend* fe, int acquire);
    int (*set_lna)(struct dvb_frontend *);
    enum dvbfe_search (*search)(struct dvb_frontend *fe);
    struct dvb_tuner_ops tuner_ops;
    struct analog_demod_ops analog_ops;
};
```

**Members**

- `info`: embedded [`struct dvb_tuner_info`](#c-struct-dvb_tuner_info) with tuner properties
- `delsys`: Delivery systems supported by the frontend
- `detach`: callback function called when frontend is detached.
  drivers should clean up, but not yet free the [`struct dvb_frontend`](#c-struct-dvb_frontend) allocation.
- `release`: callback function called when frontend is ready to be
  freed.
  drivers should free any allocated memory.
- `release_sec`: callback function requesting that the Satellite Equipment
  Control (SEC) driver to release and free any memory
  allocated by the driver.
- `init`: callback function used to initialize the tuner device.
- `sleep`: callback function used to put the tuner to sleep.
- `suspend`: callback function used to inform that the Kernel will
  suspend.
- `resume`: callback function used to inform that the Kernel is
  resuming from suspend.
- `write`: callback function used by some demod legacy drivers to
  allow other drivers to write data into their registers.
  Should not be used on new drivers.
- `tune`: callback function used by demod drivers that use
  **DVBFE_ALGO_HW** to tune into a frequency.
- `get_frontend_algo`: returns the desired hardware algorithm.
- `set_frontend`: callback function used to inform the demod to set the
  parameters for demodulating a digital TV channel.
  The properties to be used are stored at [`struct dvb_frontend`](#c-struct-dvb_frontend).dtv_property_cache. The demod can change
  the parameters to reflect the changes needed for the
  channel to be decoded, and update statistics.
- `get_tune_settings`: callback function
- `get_frontend`: callback function used to inform the parameters
  actuall in use. The properties to be used are stored at
  [`struct dvb_frontend`](#c-struct-dvb_frontend).dtv_property_cache and update
  statistics. Please notice that it should not return
  an error code if the statistics are not available
  because the demog is not locked.
- `read_status`: returns the locking status of the frontend.
- `read_ber`: legacy callback function to return the bit error rate.
  Newer drivers should provide such info via DVBv5 API,
  e. g. **set_frontend**;/**get_frontend**, implementing this
  callback only if DVBv3 API compatibility is wanted.
- `read_signal_strength`: legacy callback function to return the signal
  strength. Newer drivers should provide such info via
  DVBv5 API, e. g. **set_frontend**/**get_frontend**,
  implementing this callback only if DVBv3 API
  compatibility is wanted.
- `read_snr`: legacy callback function to return the Signal/Noise
  rate. Newer drivers should provide such info via
  DVBv5 API, e. g. **set_frontend**/**get_frontend**,
  implementing this callback only if DVBv3 API
  compatibility is wanted.
- `read_ucblocks`: legacy callback function to return the Uncorrected Error
  Blocks. Newer drivers should provide such info via
  DVBv5 API, e. g. **set_frontend**/**get_frontend**,
  implementing this callback only if DVBv3 API
  compatibility is wanted.
- `diseqc_reset_overload`: callback function to implement the
  `FE_DISEQC_RESET_OVERLOAD()` ioctl (only Satellite)
- `diseqc_send_master_cmd`: callback function to implement the
  `FE_DISEQC_SEND_MASTER_CMD()` ioctl (only Satellite).
- `diseqc_recv_slave_reply`: callback function to implement the
  `FE_DISEQC_RECV_SLAVE_REPLY()` ioctl (only Satellite)
- `diseqc_send_burst`: callback function to implement the
  `FE_DISEQC_SEND_BURST()` ioctl (only Satellite).
- `set_tone`: callback function to implement the
  `FE_SET_TONE()` ioctl (only Satellite).
- `set_voltage`: callback function to implement the
  `FE_SET_VOLTAGE()` ioctl (only Satellite).
- `enable_high_lnb_voltage`: callback function to implement the
  `FE_ENABLE_HIGH_LNB_VOLTAGE()` ioctl (only Satellite).
- `dishnetwork_send_legacy_command`: callback function to implement the
  `FE_DISHNETWORK_SEND_LEGACY_CMD()` ioctl (only Satellite).
  Drivers should not use this, except when the DVB
  core emulation fails to provide proper support (e.g.
  if **set_voltage** takes more than 8ms to work), and
  when backward compatibility with this legacy API is
  required.
- `i2c_gate_ctrl`: controls the I2C gate. Newer drivers should use I2C
  mux support instead.
- `ts_bus_ctrl`: callback function used to take control of the TS bus.
- `set_lna`: callback function to power on/off/auto the LNA.
- `search`: callback function used on some custom algo search algos.
- `tuner_ops`: pointer to [`struct dvb_tuner_ops`](#c-struct-dvb_tuner_ops)
- `analog_ops`: pointer to [`struct analog_demod_ops`](#c-struct-analog_demod_ops)

#### <a id="c-struct-dtv_frontend_properties"></a>`struct dtv_frontend_properties`

contains a list of properties that are specific to a digital TV standard.

**Definition**

```c
struct dtv_frontend_properties {
    u32 frequency;
    enum fe_modulation      modulation;
    enum fe_sec_voltage     voltage;
    enum fe_sec_tone_mode   sectone;
    enum fe_spectral_inversion inversion;
    enum fe_code_rate       fec_inner;
    enum fe_transmit_mode   transmission_mode;
    u32 bandwidth_hz;
    enum fe_guard_interval  guard_interval;
    enum fe_hierarchy       hierarchy;
    u32 symbol_rate;
    enum fe_code_rate       code_rate_HP;
    enum fe_code_rate       code_rate_LP;
    enum fe_pilot           pilot;
    enum fe_rolloff         rolloff;
    enum fe_delivery_system delivery_system;
    enum fe_interleaving    interleaving;
    u8 isdbt_partial_reception;
    u8 isdbt_sb_mode;
    u8 isdbt_sb_subchannel;
    u32 isdbt_sb_segment_idx;
    u32 isdbt_sb_segment_count;
    u8 isdbt_layer_enabled;
    struct {
        u8 segment_count;
        enum fe_code_rate   fec;
        enum fe_modulation  modulation;
        u8 interleaving;
    } layer[3];
    u32 stream_id;
    u32 scrambling_sequence_index;
    u8 atscmh_fic_ver;
    u8 atscmh_parade_id;
    u8 atscmh_nog;
    u8 atscmh_tnog;
    u8 atscmh_sgn;
    u8 atscmh_prc;
    u8 atscmh_rs_frame_mode;
    u8 atscmh_rs_frame_ensemble;
    u8 atscmh_rs_code_mode_pri;
    u8 atscmh_rs_code_mode_sec;
    u8 atscmh_sccc_block_mode;
    u8 atscmh_sccc_code_mode_a;
    u8 atscmh_sccc_code_mode_b;
    u8 atscmh_sccc_code_mode_c;
    u8 atscmh_sccc_code_mode_d;
    u32 lna;
    struct dtv_fe_stats     strength;
    struct dtv_fe_stats     cnr;
    struct dtv_fe_stats     pre_bit_error;
    struct dtv_fe_stats     pre_bit_count;
    struct dtv_fe_stats     post_bit_error;
    struct dtv_fe_stats     post_bit_count;
    struct dtv_fe_stats     block_error;
    struct dtv_fe_stats     block_count;
};
```

**Members**

- `frequency`: frequency in Hz for terrestrial/cable or in kHz for
  Satellite
- `modulation`: Frontend modulation type
- `voltage`: SEC voltage (only Satellite)
- `sectone`: SEC tone mode (only Satellite)
- `inversion`: Spectral inversion
- `fec_inner`: Forward error correction inner Code Rate
- `transmission_mode`: Transmission Mode
- `bandwidth_hz`: Bandwidth, in Hz. A zero value means that userspace
  wants to autodetect.
- `guard_interval`: Guard Interval
- `hierarchy`: Hierarchy
- `symbol_rate`: Symbol Rate
- `code_rate_HP`: high priority stream code rate
- `code_rate_LP`: low priority stream code rate
- `pilot`: Enable/disable/autodetect pilot tones
- `rolloff`: Rolloff factor (alpha)
- `delivery_system`: FE delivery system (e. g. digital TV standard)
- `interleaving`: interleaving
- `isdbt_partial_reception`: ISDB-T partial reception (only ISDB standard)
- `isdbt_sb_mode`: ISDB-T Sound Broadcast (SB) mode (only ISDB standard)
- `isdbt_sb_subchannel`: ISDB-T SB subchannel (only ISDB standard)
- `isdbt_sb_segment_idx`: ISDB-T SB segment index (only ISDB standard)
- `isdbt_sb_segment_count`: ISDB-T SB segment count (only ISDB standard)
- `isdbt_layer_enabled`: ISDB Layer enabled (only ISDB standard)
- `layer`: ISDB per-layer data (only ISDB standard)
- `layer.segment_count`: Segment Count;
- `layer.fec`: per layer code rate;
- `layer.modulation`: per layer modulation;
- `layer.interleaving`: per layer interleaving.
- `stream_id`: If different than zero, enable substream filtering, if
  hardware supports (DVB-S2 and DVB-T2).
- `scrambling_sequence_index`: Carries the index of the DVB-S2 physical layer
  scrambling sequence.
- `atscmh_fic_ver`: Version number of the FIC (Fast Information Channel)
  signaling data (only ATSC-M/H)
- `atscmh_parade_id`: Parade identification number (only ATSC-M/H)
- `atscmh_nog`: Number of MH groups per MH subframe for a designated
  parade (only ATSC-M/H)
- `atscmh_tnog`: Total number of MH groups including all MH groups
  belonging to all MH parades in one MH subframe
  (only ATSC-M/H)
- `atscmh_sgn`: Start group number (only ATSC-M/H)
- `atscmh_prc`: Parade repetition cycle (only ATSC-M/H)
- `atscmh_rs_frame_mode`: Reed Solomon (RS) frame mode (only ATSC-M/H)
- `atscmh_rs_frame_ensemble`: RS frame ensemble (only ATSC-M/H)
- `atscmh_rs_code_mode_pri`: RS code mode pri (only ATSC-M/H)
- `atscmh_rs_code_mode_sec`: RS code mode sec (only ATSC-M/H)
- `atscmh_sccc_block_mode`: Series Concatenated Convolutional Code (SCCC)
  Block Mode (only ATSC-M/H)
- `atscmh_sccc_code_mode_a`: SCCC code mode A (only ATSC-M/H)
- `atscmh_sccc_code_mode_b`: SCCC code mode B (only ATSC-M/H)
- `atscmh_sccc_code_mode_c`: SCCC code mode C (only ATSC-M/H)
- `atscmh_sccc_code_mode_d`: SCCC code mode D (only ATSC-M/H)
- `lna`: Power ON/OFF/AUTO the Linear Now-noise Amplifier (LNA)
- `strength`: DVBv5 API statistics: Signal Strength
- `cnr`: DVBv5 API statistics: Signal to Noise ratio of the
  (main) carrier
- `pre_bit_error`: DVBv5 API statistics: pre-Viterbi bit error count
- `pre_bit_count`: DVBv5 API statistics: pre-Viterbi bit count
- `post_bit_error`: DVBv5 API statistics: post-Viterbi bit error count
- `post_bit_count`: DVBv5 API statistics: post-Viterbi bit count
- `block_error`: DVBv5 API statistics: block error count
- `block_count`: DVBv5 API statistics: block count

**NOTE**

derivated statistics like Uncorrected Error blocks (UCE) are
calculated on userspace.

Only a subset of the properties are needed for a given delivery system.
For more info, consult the media_api.html with the documentation of the
Userspace API.

#### <a id="c-struct-dvb_frontend"></a>`struct dvb_frontend`

Frontend structure to be used on drivers.

**Definition**

```c
struct dvb_frontend {
        struct kref refcount;
        struct dvb_frontend_ops ops;
        struct dvb_adapter *dvb;
        void *demodulator_priv;
        void *tuner_priv;
        void *frontend_priv;
        void *sec_priv;
        void *analog_demod_priv;
        struct dtv_frontend_properties dtv_property_cache;
    #define DVB_FRONTEND_COMPONENT_TUNER 0;
    #define DVB_FRONTEND_COMPONENT_DEMOD 1;
        int (*callback)(void *adapter_priv, int component, int cmd, int arg);
        int id;
        unsigned int exit;
};
```

**Members**

- `refcount`: refcount to keep track of [`struct dvb_frontend`](#c-struct-dvb_frontend)
  references
- `ops`: embedded [`struct dvb_frontend_ops`](#c-struct-dvb_frontend_ops)
- `dvb`: pointer to [`struct dvb_adapter`](/kernel/hardware/driver-api/media/dtv-common.md#c-struct-dvb_adapter)
- `demodulator_priv`: demod private data
- `tuner_priv`: tuner private data
- `frontend_priv`: frontend private data
- `sec_priv`: SEC private data
- `analog_demod_priv`: Analog demod private data
- `dtv_property_cache`: embedded [`struct dtv_frontend_properties`](#c-struct-dtv_frontend_properties)
- `callback`: callback function used on some drivers to call
  either the tuner or the demodulator.
- `id`: Frontend ID
- `exit`: Used to inform the DVB core that the frontend
  thread should exit (usually, means that the hardware
  got disconnected.

#### <a id="c-dvb_register_frontend"></a>`dvb_register_frontend()`

```c
int dvb_register_frontend(struct dvb_adapter *dvb, struct dvb_frontend *fe)
```

Registers a DVB frontend at the adapter

**Parameters**

- `struct dvb_adapter *dvb`: pointer to [`struct dvb_adapter`](/kernel/hardware/driver-api/media/dtv-common.md#c-struct-dvb_adapter)
- `struct dvb_frontend *fe`: pointer to [`struct dvb_frontend`](#c-struct-dvb_frontend)

**Description**

Allocate and initialize the private data needed by the frontend core to
manage the frontend and calls [`dvb_register_device()`](/kernel/hardware/driver-api/media/dtv-common.md#c-dvb_register_device) to register a new
frontend. It also cleans the property cache that stores the frontend
parameters and selects the first available delivery system.

#### <a id="c-dvb_unregister_frontend"></a>`dvb_unregister_frontend()`

```c
int dvb_unregister_frontend(struct dvb_frontend *fe)
```

Unregisters a DVB frontend

**Parameters**

- `struct dvb_frontend *fe`: pointer to [`struct dvb_frontend`](#c-struct-dvb_frontend)

**Description**

Stops the frontend kthread, calls [`dvb_unregister_device()`](/kernel/hardware/driver-api/media/dtv-common.md#c-dvb_unregister_device) and frees the
private frontend data allocated by [`dvb_register_frontend()`](#c-dvb_register_frontend).

**NOTE**

This function doesn't frees the memory allocated by the demod,
by the SEC driver and by the tuner. In order to free it, an explicit call to
[`dvb_frontend_detach()`](#c-dvb_frontend_detach) is needed, after calling this function.

#### <a id="c-dvb_frontend_detach"></a>`dvb_frontend_detach()`

```c
void dvb_frontend_detach(struct dvb_frontend *fe)
```

Detaches and frees frontend specific data

**Parameters**

- `struct dvb_frontend *fe`: pointer to [`struct dvb_frontend`](#c-struct-dvb_frontend)

**Description**

This function should be called after [`dvb_unregister_frontend()`](#c-dvb_unregister_frontend). It
calls the SEC, tuner and demod release functions:
[`dvb_frontend_ops.release_sec`](#c-struct-dvb_frontend_ops), [`dvb_frontend_ops.tuner_ops`](#c-struct-dvb_frontend_ops).release,
[`dvb_frontend_ops.analog_ops`](#c-struct-dvb_frontend_ops).release and [`dvb_frontend_ops.release`](#c-struct-dvb_frontend_ops).

If the driver is compiled with `CONFIG_MEDIA_ATTACH`, it also decreases
the module reference count, needed to allow userspace to remove the
previously used DVB frontend modules.

#### <a id="c-dvb_frontend_suspend"></a>`dvb_frontend_suspend()`

```c
int dvb_frontend_suspend(struct dvb_frontend *fe)
```

Suspends a Digital TV frontend

**Parameters**

- `struct dvb_frontend *fe`: pointer to [`struct dvb_frontend`](#c-struct-dvb_frontend)

**Description**

This function prepares a Digital TV frontend to suspend.

In order to prepare the tuner to suspend, if
[`dvb_frontend_ops.tuner_ops`](#c-struct-dvb_frontend_ops).suspend\(\) is available, it calls it. Otherwise,
it will call [`dvb_frontend_ops.tuner_ops`](#c-struct-dvb_frontend_ops).sleep\(\), if available.

It will also call [`dvb_frontend_ops.suspend`](#c-struct-dvb_frontend_ops)\(\) to put the demod to suspend,
if available. Otherwise it will call [`dvb_frontend_ops.sleep`](#c-struct-dvb_frontend_ops)\(\).

The drivers should also call dvb_frontend_suspend\(\) as part of their
handler for the [`device_driver.suspend`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device_driver)\(\).

#### <a id="c-dvb_frontend_resume"></a>`dvb_frontend_resume()`

```c
int dvb_frontend_resume(struct dvb_frontend *fe)
```

Resumes a Digital TV frontend

**Parameters**

- `struct dvb_frontend *fe`: pointer to [`struct dvb_frontend`](#c-struct-dvb_frontend)

**Description**

This function resumes the usual operation of the tuner after resume.

In order to resume the frontend, it calls the demod
[`dvb_frontend_ops.resume`](#c-struct-dvb_frontend_ops)\(\) if available. Otherwise it calls demod
[`dvb_frontend_ops.init`](#c-struct-dvb_frontend_ops)\(\).

If [`dvb_frontend_ops.tuner_ops`](#c-struct-dvb_frontend_ops).resume\(\) is available, It, it calls it.
Otherwise,t will call [`dvb_frontend_ops.tuner_ops`](#c-struct-dvb_frontend_ops).init\(\), if available.

Once tuner and demods are resumed, it will enforce that the SEC voltage and
tone are restored to their previous values and wake up the frontend's
kthread in order to retune the frontend.

The drivers should also call [`dvb_frontend_resume()`](#c-dvb_frontend_resume) as part of their
handler for the [`device_driver.resume`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device_driver)\(\).

#### <a id="c-dvb_frontend_reinitialise"></a>`dvb_frontend_reinitialise()`

```c
void dvb_frontend_reinitialise(struct dvb_frontend *fe)
```

forces a reinitialisation at the frontend

**Parameters**

- `struct dvb_frontend *fe`: pointer to [`struct dvb_frontend`](#c-struct-dvb_frontend)

**Description**

Calls [`dvb_frontend_ops.init`](#c-struct-dvb_frontend_ops)\(\) and [`dvb_frontend_ops.tuner_ops`](#c-struct-dvb_frontend_ops).init\(\),
and resets SEC tone and voltage (for Satellite systems).

**NOTE**

Currently, this function is used only by one driver (budget-av).
It seems to be due to address some special issue with that specific
frontend.

#### <a id="c-dvb_frontend_sleep_until"></a>`dvb_frontend_sleep_until()`

```c
void dvb_frontend_sleep_until(ktime_t *waketime, u32 add_usec)
```

Sleep for the amount of time given by add_usec parameter

**Parameters**

- `ktime_t *waketime`: pointer to `struct ktime_t`
- `u32 add_usec`: time to sleep, in microseconds

**Description**

This function is used to measure the time required for the
`FE_DISHNETWORK_SEND_LEGACY_CMD()` ioctl to work. It needs to be as precise
as possible, as it affects the detection of the dish tone command at the
satellite subsystem.

Its used internally by the DVB frontend core, in order to emulate
`FE_DISHNETWORK_SEND_LEGACY_CMD()` using the [`dvb_frontend_ops.set_voltage`](#c-struct-dvb_frontend_ops)\(\)
callback.

**NOTE**

it should not be used at the drivers, as the emulation for the
legacy callback is provided by the Kernel. The only situation where this
should be at the drivers is when there are some bugs at the hardware that
would prevent the core emulation to work. On such cases, the driver would
be writing a [`dvb_frontend_ops.dishnetwork_send_legacy_command`](#c-struct-dvb_frontend_ops)\(\) and
calling this function directly.

---

# Digital TV Network kABI

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for Digital TV Network kABI.

<a id="rst-digital-tv-network-kabi"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-struct-dvb_net"></a>`struct dvb_net`

describes a DVB network interface

**Definition**

```c
struct dvb_net {
    struct dvb_device *dvbdev;
    struct net_device *device[DVB_NET_DEVICES_MAX];
    int state[DVB_NET_DEVICES_MAX];
    unsigned int exit:1;
    struct dmx_demux *demux;
    struct mutex ioctl_mutex;
    struct mutex remove_mutex;
};
```

**Members**

- `dvbdev`: pointer to [`struct dvb_device`](/kernel/hardware/driver-api/media/dtv-common.md#c-struct-dvb_device).
- `device`: array of pointers to [`struct net_device`](/kernel/internals/networking/kapi.md#c-struct-net_device).
- `state`: array of integers to each net device. A value
  different than zero means that the interface is
  in usage.
- `exit`: flag to indicate when the device is being removed.
- `demux`: pointer to [`struct dmx_demux`](/kernel/hardware/driver-api/media/dtv-demux.md#c-struct-dmx_demux).
- `ioctl_mutex`: protect access to this struct.
- `remove_mutex`: mutex that avoids a race condition between a callback
  called when the hardware is disconnected and the
  file_operations of dvb_net.

**Description**

Currently, the core supports up to `DVB_NET_DEVICES_MAX` (10) network
devices.

#### <a id="c-dvb_net_init"></a>`dvb_net_init()`

```c
int dvb_net_init(struct dvb_adapter *adap, struct dvb_net *dvbnet, struct dmx_demux *dmxdemux)
```

nitializes a digital TV network device and registers it.

**Parameters**

- `struct dvb_adapter *adap`: pointer to [`struct dvb_adapter`](/kernel/hardware/driver-api/media/dtv-common.md#c-struct-dvb_adapter).
- `struct dvb_net *dvbnet`: pointer to [`struct dvb_net`](#c-struct-dvb_net).
- `struct dmx_demux *dmxdemux`: pointer to [`struct dmx_demux`](/kernel/hardware/driver-api/media/dtv-demux.md#c-struct-dmx_demux).

#### <a id="c-dvb_net_release"></a>`dvb_net_release()`

```c
void dvb_net_release(struct dvb_net *dvbnet)
```

releases a digital TV network device and unregisters it.

**Parameters**

- `struct dvb_net *dvbnet`: pointer to [`struct dvb_net`](#c-struct-dvb_net).

---

# Media Subsystem Profile

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> The media subsystem covers support for a variety of devices: stream capture, analog and digital TV streams, cameras, remote controllers, HDMI CEC and media pipeline control.

<a id="rst-media-subsystem-profile"></a>

<a id="rst-overview"></a>

## Overview

The media subsystem covers support for a variety of devices: stream capture, analog and digital TV streams, cameras, remote controllers, HDMI CEC and media pipeline control.

It covers, mainly, the contents of those directories:

> - drivers/media
>
> - drivers/staging/media
>
> - Documentation/admin-guide/media
>
> - Documentation/driver-api/media
>
> - Documentation/userspace-api/media
>
> - Documentation/devicetree/bindings/media/<a id="rst-footnote-reference-1"></a>[1](#rst-footnote-1)
>
> - include/media

<a id="rst-footnote-1"></a>



**[1]** Device tree bindings are maintained by the OPEN FIRMWARE AND FLATTENED DEVICE TREE BINDINGS maintainers (see the MAINTAINERS file). So, changes there must be reviewed by them before being merged via the media subsystem's development tree.

Both media userspace and Kernel APIs are documented and the documentation must be kept in sync with the API changes. It means that all patches that add new features to the subsystem must also bring changes to the corresponding API files.

Due to the size and wide scope of the media subsystem, media's maintainership model is to have sub-maintainers that have a broad knowledge of a specific aspect of the subsystem. It is the sub-maintainers' task to review the patches, providing feedback to users if the patches are following the subsystem rules and are properly using the media kernel and userspace APIs.

Patches for the media subsystem must be sent to the media mailing list at [linux-media@vger.kernel.org](<mailto:linux-media@vger.kernel.org>) as plain text only e-mail. Emails with HTML will be automatically rejected by the mail server. It could be wise to also copy the sub-maintainer(s).

Media's workflow is heavily based on Patchwork, meaning that, once a patch is submitted, the e-mail will first be accepted by the mailing list server, and, after a while, it should appear at:

> - [https://patchwork.linuxtv.org/project/linux-media/list/](<https://patchwork.linuxtv.org/project/linux-media/list/>)

If it doesn't automatically appear there after a few minutes, then probably something went wrong on your submission. Please check if the email is in plain text<a id="rst-footnote-reference-2"></a>[2](#rst-footnote-2) only and if your emailer is not mangling whitespaces before complaining or submitting them again.

You can check if the mailing list server accepted your patch, by looking at:

> - [https://lore.kernel.org/linux-media/](<https://lore.kernel.org/linux-media/>)

<a id="rst-footnote-2"></a>



**[2]** If your email contains HTML, the mailing list server will simply drop it, without any further notice.

<a id="rst-media-maintainers"></a>

### Media maintainers

At the media subsystem, we have a group of senior developers that are responsible for doing the code reviews at the drivers (also known as sub-maintainers), and another senior developer responsible for the subsystem as a whole. For core changes, whenever possible, multiple media maintainers do the review.

The media maintainers that work on specific areas of the subsystem are:

- - **Remote Controllers (infrared):**

    Sean Young &lt;[sean@mess.org](<mailto:sean@mess.org>)&gt;

- - **HDMI CEC:**

    Hans Verkuil &lt;[hverkuil@kernel.org](<mailto:hverkuil@kernel.org>)&gt;

- - **Media controller drivers:**

    Laurent Pinchart &lt;[laurent.pinchart@ideasonboard.com](<mailto:laurent.pinchart@ideasonboard.com>)&gt;

- - **ISP, v4l2-async, v4l2-fwnode, v4l2-flash-led-class and Sensor drivers:**

    Sakari Ailus &lt;[sakari.ailus@linux.intel.com](<mailto:sakari.ailus@linux.intel.com>)&gt;

- - **V4L2 drivers and core V4L2 frameworks:**

    Hans Verkuil &lt;[hverkuil@kernel.org](<mailto:hverkuil@kernel.org>)&gt;

- **The subsystem maintainer is:**

  Mauro Carvalho Chehab &lt;[mchehab@kernel.org](<mailto:mchehab@kernel.org>)&gt;

Media maintainers may delegate a patch to other media maintainers as needed. On such case, checkpatch's `delegate` field indicates who's currently responsible for reviewing a patch.

<a id="rst-submit-checklist-addendum"></a>

## Submit Checklist Addendum

Patches that change the Open Firmware/Device Tree bindings must be reviewed by the Device Tree maintainers. So, DT maintainers should be Cc:ed when those are submitted via devicetree@vger.kernel.org mailing list.

There is a set of compliance tools at [https://git.linuxtv.org/v4l-utils.git/](<https://git.linuxtv.org/v4l-utils.git/>) that should be used in order to check if the drivers are properly implementing the media APIs:


<table>
<thead>
<tr>
<th>


Type

</th>
<th>


Tool

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


V4L2 drivers<a id="rst-footnote-reference-3"></a>[3](#rst-footnote-3)

</td>
<td>


`v4l2-compliance`

</td>
</tr>
<tr>
<td>


V4L2 virtual drivers

</td>
<td>


`contrib/test/test-media`

</td>
</tr>
<tr>
<td>


CEC drivers

</td>
<td>


`cec-compliance`

</td>
</tr>
</tbody>
</table>

<a id="rst-footnote-3"></a>



**[3]** The `v4l2-compliance` also covers the media controller usage inside V4L2 drivers.

Other compliance tools are under development to check other parts of the subsystem.

Those tests need to pass before the patches go upstream.

Also, please notice that we build the Kernel with:



```text
make CF=-D__CHECK_ENDIAN__ CONFIG_DEBUG_SECTION_MISMATCH=y C=1 W=1 CHECK=check_script
```

Where the check script is:



```text
#!/bin/bash
/devel/smatch/smatch -p=kernel $@ >&2
/devel/sparse/sparse $@ >&2
```

Be sure to not introduce new warnings on your patches without a very good reason.

<a id="rst-style-cleanup-patches"></a>

### Style Cleanup Patches

Style cleanups are welcome when they come together with other changes at the files where the style changes will affect.

We may accept pure standalone style cleanups, but they should ideally be one patch for the whole subsystem (if the cleanup is low volume), or at least be grouped per directory. So, for example, if you're doing a big cleanup change set at drivers under drivers/media, please send a single patch for all drivers under drivers/media/pci, another one for drivers/media/usb and so on.

<a id="rst-coding-style-addendum"></a>

### Coding Style Addendum

Media development uses `checkpatch.pl` on strict mode to verify the code style, e.g.:



```text
$ ./scripts/checkpatch.pl --strict --max-line-length=80
```

In principle, patches should follow the coding style rules, but exceptions are allowed if there are good reasons. On such case, maintainers and reviewers may question about the rationale for not addressing the `checkpatch.pl`.

Please notice that the goal here is to improve code readability. On a few cases, `checkpatch.pl` may actually point to something that would look worse. So, you should use good sense.

Note that addressing one `checkpatch.pl` issue (of any kind) alone may lead to having longer lines than 80 characters per line. While this is not strictly prohibited, efforts should be made towards staying within 80 characters per line. This could include using re-factoring code that leads to less indentation, shorter variable or function names and last but not least, simply wrapping the lines.

In particular, we accept lines with more than 80 columns:

> - on strings, as they shouldn't be broken due to line length limits;
>
> - when a function or variable name need to have a big identifier name, which keeps hard to honor the 80 columns limit;
>
> - on arithmetic expressions, when breaking lines makes them harder to read;
>
> - when they avoid a line to end with an open parenthesis or an open bracket.

<a id="rst-key-cycle-dates"></a>

## Key Cycle Dates

New submissions can be sent at any time, but if they intend to hit the next merge window they should be sent before -rc5, and ideally stabilized in the linux-media branch by -rc6.

<a id="rst-review-cadence"></a>

## Review Cadence

Provided that your patch is at [https://patchwork.linuxtv.org](<https://patchwork.linuxtv.org>), it should be sooner or later handled, so you don't need to re-submit a patch.

Except for bug fixes, we don't usually add new patches to the development tree between -rc6 and the next -rc1.

Please notice that the media subsystem is a high traffic one, so it could take a while for us to be able to review your patches. Feel free to ping if you don't get a feedback in a couple of weeks or to ask other developers to publicly add Reviewed-by and, more importantly, `Tested-by:` tags.

Please note that we expect a detailed description for `Tested-by:`, identifying what boards were used at the test and what it was tested.

---

# Media Controller devices

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> The media controller userspace API is documented in the Media Controller uAPI book <media_controller>. This document focus on the kernel-side implementation of the media framework.

<a id="rst-media-controller-devices"></a>

<a id="rst-media-controller"></a>

## Media Controller

<!-- SPDX-License-Identifier: GPL-2.0 -->

The media controller userspace API is documented in [the Media Controller uAPI book](</kernel/userspace/userspace-api/media-mediactl/media-controller.md#rst-media-controller>). This document focus on the kernel-side implementation of the media framework.

<a id="rst-abstract-media-device-model"></a>

## Abstract media device model

Discovering a device internal topology, and configuring it at runtime, is one of the goals of the media framework. To achieve this, hardware devices are modelled as an oriented graph of building blocks called entities connected through pads.

An entity is a basic media hardware building block. It can correspond to a large variety of logical blocks such as physical hardware devices (CMOS sensor for instance), logical hardware devices (a building block in a System-on-Chip image processing pipeline), DMA channels or physical connectors.

A pad is a connection endpoint through which an entity can interact with other entities. Data (not restricted to video) produced by an entity flows from the entity's output to one or more entity inputs. Pads should not be confused with physical pins at chip boundaries.

A link is a point-to-point oriented connection between two pads, either on the same entity or on different entities. Data flows from a source pad to a sink pad.

<a id="rst-media-device"></a>

## Media device

A media device is represented by a struct media_device instance, defined in `include/media/media-device.h`. Allocation of the structure is handled by the media device driver, usually by embedding the `media_device` instance in a larger driver-specific structure.

Drivers initialise media device instances by calling `media_device_init()`. After initialising a media device instance, it is registered by calling `__media_device_register()` via the macro `media_device_register()` and unregistered by calling `media_device_unregister()`. An initialised media device must be eventually cleaned up by calling `media_device_cleanup()`.

Note that it is not allowed to unregister a media device instance that was not previously registered, or clean up a media device instance that was not previously initialised.

<a id="rst-entities"></a>

## Entities

Entities are represented by a struct media_entity instance, defined in `include/media/media-entity.h`. The structure is usually embedded into a higher-level structure, such as `v4l2_subdev` or `video_device` instances, although drivers can allocate entities directly.

Drivers initialize entity pads by calling `media_entity_pads_init()`.

Drivers register entities with a media device by calling `media_device_register_entity()` and unregistered by calling `media_device_unregister_entity()`.

<a id="rst-interfaces"></a>

## Interfaces

Interfaces are represented by a struct media_interface instance, defined in `include/media/media-entity.h`. Currently, only one type of interface is defined: a device node. Such interfaces are represented by a struct media_intf_devnode.

Drivers initialize and create device node interfaces by calling `media_devnode_create()` and remove them by calling: `media_devnode_remove()`.

<a id="rst-pads"></a>

## Pads

Pads are represented by a struct media_pad instance, defined in `include/media/media-entity.h`. Each entity stores its pads in a pads array managed by the entity driver. Drivers usually embed the array in a driver-specific structure.

Pads are identified by their entity and their 0-based index in the pads array.

Both information are stored in the struct media_pad, making the struct media_pad pointer the canonical way to store and pass link references.

Pads have flags that describe the pad capabilities and state.

`MEDIA_PAD_FL_SINK` indicates that the pad supports sinking data. `MEDIA_PAD_FL_SOURCE` indicates that the pad supports sourcing data.

> [!NOTE]
>
> One and only one of `MEDIA_PAD_FL_SINK` or `MEDIA_PAD_FL_SOURCE` must be set for each pad.

<a id="rst-links"></a>

## Links

Links are represented by a struct media_link instance, defined in `include/media/media-entity.h`. There are two types of links:

**1. pad to pad links**:

Associate two entities via their PADs. Each entity has a list that points to all links originating at or targeting any of its pads. A given link is thus stored twice, once in the source entity and once in the target entity.

Drivers create pad to pad links by calling: `media_create_pad_link()` and remove with `media_entity_remove_links()`.

**2. interface to entity links**:

Associate one interface to a Link.

Drivers create interface to entity links by calling: `media_create_intf_link()` and remove with `media_remove_intf_links()`.

> [!NOTE]
>
> Links can only be created after having both ends already created.

Links have flags that describe the link capabilities and state. The valid values are described at `media_create_pad_link()` and `media_create_intf_link()`.

<a id="rst-graph-traversal"></a>

## Graph traversal

The media framework provides APIs to traverse media graphs, locating connected entities and links.

To iterate over all entities belonging to a media device, drivers can use the media_device_for_each_entity macro, defined in `include/media/media-device.h`.



```c
struct media_entity *entity;

media_device_for_each_entity(entity, mdev) {
// entity will point to each entity in turn
...
}
```

Helper functions can be used to find a link between two given pads, or a pad connected to another pad through an enabled link (`media_entity_find_link()`, `media_pad_remote_pad_first()`, `media_entity_remote_source_pad_unique()` and `media_pad_remote_pad_unique()`).

<a id="rst-use-count-and-power-handling"></a>

## Use count and power handling

Due to the wide differences between drivers regarding power management needs, the media controller does not implement power management. However, the struct media_entity includes a `use_count` field that media drivers can use to track the number of users of every entity for power management needs.

The `media_entity<media_entity>`.`use_count` field is owned by media drivers and must not be touched by entity drivers. Access to the field must be protected by the `media_device`.`graph_mutex` lock.

<a id="rst-links-setup"></a>

## Links setup

Link properties can be modified at runtime by calling `media_entity_setup_link()`.

<a id="rst-pipelines-and-media-streams"></a>

## Pipelines and media streams

A media stream is a stream of pixels or metadata originating from one or more source devices (such as a sensors) and flowing through media entity pads towards the final sinks. The stream can be modified on the route by the devices (e.g. scaling or pixel format conversions), or it can be split into multiple branches, or multiple branches can be merged.

A media pipeline is a set of media streams which are interdependent. This interdependency can be caused by the hardware (e.g. configuration of a second stream cannot be changed if the first stream has been enabled) or by the driver due to the software design. Most commonly a media pipeline consists of a single stream which does not branch.

When starting streaming, drivers must notify all entities in the pipeline to prevent link states from being modified during streaming by calling `media_pipeline_start()`.

The function will mark all the pads which are part of the pipeline as streaming.

The struct media_pipeline instance pointed to by the pipe argument will be stored in every pad in the pipeline. Drivers should embed the struct media_pipeline in higher-level pipeline structures and can then access the pipeline through the struct media_pad pipe field.

Calls to `media_pipeline_start()` can be nested. The pipeline pointer must be identical for all nested calls to the function.

`media_pipeline_start()` may return an error. In that case, it will clean up any of the changes it did by itself.

When stopping the stream, drivers must notify the entities with `media_pipeline_stop()`.

If multiple calls to `media_pipeline_start()` have been made the same number of `media_pipeline_stop()` calls are required to stop streaming. The `media_entity`.`pipe` field is reset to `NULL` on the last nested stop call.

Link configuration will fail with `-EBUSY` by default if either end of the link is a streaming entity. Links that can be modified while streaming must be marked with the `MEDIA_LNK_FL_DYNAMIC` flag.

If other operations need to be disallowed on streaming entities (such as changing entities configuration parameters) drivers can explicitly check the media_entity stream_count field to find out if an entity is streaming. This operation must be done with the media_device graph_mutex held.

<a id="rst-link-validation"></a>

## Link validation

Link validation is performed by `media_pipeline_start()` for any entity which has sink pads in the pipeline. The `media_entity`.`link_validate()` callback is used for that purpose. In `link_validate()` callback, entity driver should check that the properties of the source pad of the connected entity and its own sink pad match. It is up to the type of the entity (and in the end, the properties of the hardware) what matching actually means.

Subsystems should facilitate link validation by providing subsystem specific helper functions to provide easy access for commonly needed information, and in the end provide a way to use driver-specific callbacks.

<a id="rst-pipeline-traversal"></a>

## Pipeline traversal

Once a pipeline has been constructed with `media_pipeline_start()`, drivers can iterate over entities or pads in the pipeline with the :c:macro:´media_pipeline_for_each_entity\` and :c:macro:´media_pipeline_for_each_pad\` macros. Iterating over pads is straightforward:



```c
media_pipeline_pad_iter iter;
struct media_pad *pad;

media_pipeline_for_each_pad(pipe, &iter, pad) {
    /* 'pad' will point to each pad in turn */
    ...
}
```

To iterate over entities, the iterator needs to be initialized and cleaned up as an additional steps:



```c
media_pipeline_entity_iter iter;
struct media_entity *entity;
int ret;

ret = media_pipeline_entity_iter_init(pipe, &iter);
if (ret)
    ...;

media_pipeline_for_each_entity(pipe, &iter, entity) {
    /* 'entity' will point to each entity in turn */
    ...
}

media_pipeline_entity_iter_cleanup(&iter);
```

<a id="rst-media-controller-device-allocator-api"></a>

## Media Controller Device Allocator API

When the media device belongs to more than one driver, the shared media device is allocated with the shared struct device as the key for look ups.

The shared media device should stay in registered state until the last driver unregisters it. In addition, the media device should be released when all the references are released. Each driver gets a reference to the media device during probe, when it allocates the media device. If media device is already allocated, the allocate API bumps up the refcount and returns the existing media device. The driver puts the reference back in its disconnect routine when it calls `media_device_delete()`.

The media device is unregistered and cleaned up from the kref put handler to ensure that the media device stays in registered state until the last driver unregisters the media device.

**Driver Usage**

Drivers should use the appropriate media-core routines to manage the shared media device life-time handling the two states: 1. allocate -&gt; register -&gt; delete 2. get reference to already registered device -&gt; delete

call `media_device_delete()` routine to make sure the shared media device delete is handled correctly.

**driver probe:** Call `media_device_usb_allocate()` to allocate or get a reference Call `media_device_register()`, if media devnode isn't registered

**driver disconnect:** Call `media_device_delete()` to free the media_device. Freeing is handled by the kref put handler.

<a id="rst-api-definitions"></a>

## API Definitions


#### <a id="c-struct-media_entity_notify"></a>`struct media_entity_notify`

Media Entity Notify

**Definition**

```c
struct media_entity_notify {
    struct list_head list;
    void *notify_data;
    void (*notify)(struct media_entity *entity, void *notify_data);
};
```

**Members**

- `list`: List head
- `notify_data`: Input data to invoke the callback
- `notify`: Callback function pointer

**Description**

Drivers may register a callback to take action when new entities get
registered with the media device. This handler is intended for creating
links between existing entities and should not create entities and register
them.

#### <a id="c-struct-media_device_ops"></a>`struct media_device_ops`

Media device operations

**Definition**

```c
struct media_device_ops {
    int (*link_notify)(struct media_link *link, u32 flags, unsigned int notification);
    struct media_request *(*req_alloc)(struct media_device *mdev);
    void (*req_free)(struct media_request *req);
    int (*req_validate)(struct media_request *req);
    void (*req_queue)(struct media_request *req);
};
```

**Members**

- `link_notify`: Link state change notification callback. This callback is
  called with the graph_mutex held.
- `req_alloc`: Allocate a request. Set this if you need to allocate a struct
  larger then struct media_request. **req_alloc** and **req_free** must
  either both be set or both be NULL.
- `req_free`: Free a request. Set this if **req_alloc** was set as well, leave
  to NULL otherwise.
- `req_validate`: Validate a request, but do not queue yet. The req_queue_mutex
  lock is held when this op is called.
- `req_queue`: Queue a validated request, cannot fail. If something goes
  wrong when queueing this request then it should be marked
  as such internally in the driver and any related buffers
  must eventually return to vb2 with state VB2_BUF_STATE_ERROR.
  The req_queue_mutex lock is held when this op is called.
  It is important that vb2 buffer objects are queued last after
  all other object types are queued: queueing a buffer kickstarts
  the request processing, so all other objects related to the
  request (and thus the buffer) must be available to the driver.
  And once a buffer is queued, then the driver can complete
  or delete objects from the request before req_queue exits.

#### <a id="c-struct-media_device"></a>`struct media_device`

Media device

**Definition**

```c
struct media_device {
    struct device *dev;
    struct media_devnode *devnode;
    char model[32];
    char driver_name[32];
    char serial[40];
    char bus_info[32];
    u32 hw_revision;
    u64 topology_version;
    u32 id;
    struct ida entity_internal_idx;
    int entity_internal_idx_max;
    struct list_head entities;
    struct list_head interfaces;
    struct list_head pads;
    struct list_head links;
    struct list_head entity_notify;
    struct mutex graph_mutex;
    struct media_graph pm_count_walk;
    void *source_priv;
    int (*enable_source)(struct media_entity *entity, struct media_pipeline *pipe);
    void (*disable_source)(struct media_entity *entity);
    const struct media_device_ops *ops;
    struct mutex req_queue_mutex;
    atomic_t num_requests;
    atomic_t num_request_objects;
    struct dentry *media_dir;
    atomic_t request_id;
};
```

**Members**

- `dev`: Parent device
- `devnode`: Media device node
- `model`: Device model name
- `driver_name`: Optional device driver name. If not set, calls to
  `MEDIA_IOC_DEVICE_INFO` will return `dev->driver->name`.
  This is needed for USB drivers for example, as otherwise
  they'll all appear as if the driver name was "usb".
- `serial`: Device serial number (optional)
- `bus_info`: Unique and stable device location identifier
- `hw_revision`: Hardware device revision
- `topology_version`: Monotonic counter for storing the version of the graph
  topology. Should be incremented each time the topology changes.
- `id`: Unique ID used on the last registered graph object
- `entity_internal_idx`: Unique internal entity ID used by the graph traversal
  algorithms
- `entity_internal_idx_max`: Allocated internal entity indices
- `entities`: List of registered entities
- `interfaces`: List of registered interfaces
- `pads`: List of registered pads
- `links`: List of registered links
- `entity_notify`: List of registered entity_notify callbacks
- `graph_mutex`: Protects access to struct media_device data
- `pm_count_walk`: Graph walk for power state walk. Access serialised using
  graph_mutex.
- `source_priv`: Driver Private data for enable/disable source handlers
- `enable_source`: Enable Source Handler function pointer
- `disable_source`: Disable Source Handler function pointer
- `ops`: Operation handler callbacks
- `req_queue_mutex`: Serialise the MEDIA_REQUEST_IOC_QUEUE ioctl w.r.t.
  other operations that stop or start streaming.
- `num_requests`: number of associated requests
- `num_request_objects`: number of associated request objects
- `media_dir`: DebugFS media directory
- `request_id`: Used to generate unique request IDs

**Description**

This structure represents an abstract high-level media device. It allows easy
access to entities and provides basic media device-level support. The
structure can be allocated directly or embedded in a larger structure.

The parent **dev** is a physical device. It must be set before registering the
media device.

**model** is a descriptive model name exported through sysfs. It doesn't have to
be unique.

**enable_source** is a handler to find source entity for the
sink entity  and activate the link between them if source
entity is free. Drivers should call this handler before
accessing the source.

**disable_source** is a handler to find source entity for the
sink entity  and deactivate the link between them. Drivers
should call this handler to release the source.

Use-case: find tuner entity connected to the decoder
entity and check if it is available, and activate the
link between them from **enable_source** and deactivate
from **disable_source**.

> [!NOTE]
> Bridge driver is expected to implement and set the
> handler when [`media_device`](#c-struct-media_device) is registered or when
> bridge driver finds the media_device during probe.
> Bridge driver sets source_priv with information
> necessary to run **enable_source** and **disable_source** handlers.
> Callers should hold graph_mutex to access and call **enable_source**
> and **disable_source** handlers.

#### <a id="c-media_device_init"></a>`media_device_init()`

```c
void media_device_init(struct media_device *mdev)
```

Initializes a media device element

**Parameters**

- `struct media_device *mdev`: pointer to struct [`media_device`](#c-struct-media_device)

**Description**

This function initializes the media device prior to its registration.
The media device initialization and registration is split in two functions
to avoid race conditions and make the media device available to user-space
before the media graph has been completed.

So drivers need to first initialize the media device, register any entity
within the media device, create pad to pad links and then finally register
the media device by calling [`media_device_register()`](#c-media_device_register) as a final step.

The caller is responsible for initializing the media device before
registration. The following fields must be set:

- dev must point to the parent device
- model must be filled with the device model name

The bus_info field is set by [`media_device_init()`](#c-media_device_init) for PCI and platform devices
if the field begins with '\0'.

#### <a id="c-media_device_cleanup"></a>`media_device_cleanup()`

```c
void media_device_cleanup(struct media_device *mdev)
```

Cleanups a media device element

**Parameters**

- `struct media_device *mdev`: pointer to struct [`media_device`](#c-struct-media_device)

**Description**

This function that will destroy the graph_mutex that is
initialized in [`media_device_init()`](#c-media_device_init).

#### <a id="c-__media_device_register"></a>`__media_device_register()`

```c
int __media_device_register(struct media_device *mdev, struct module *owner)
```

Registers a media device element

**Parameters**

- `struct media_device *mdev`: pointer to struct [`media_device`](#c-struct-media_device)
- `struct module *owner`: should be filled with `THIS_MODULE`

**Description**

Users, should, instead, call the [`media_device_register()`](#c-media_device_register) macro.

The caller is responsible for initializing the [`media_device`](#c-struct-media_device) structure
before registration. The following fields of [`media_device`](#c-struct-media_device) must be set:

- [`media_device.model`](#c-struct-media_device) must be filled with the device model name as a
  NUL-terminated UTF-8 string. The device/model revision must not be
  stored in this field.

The following fields are optional:

- [`media_device.serial`](#c-struct-media_device) is a unique serial number stored as a
  NUL-terminated ASCII string. The field is big enough to store a GUID
  in text form. If the hardware doesn't provide a unique serial number
  this field must be left empty.

- [`media_device.bus_info`](#c-struct-media_device) represents the location of the device in the
  system as a NUL-terminated ASCII string. For PCI/PCIe devices
  [`media_device.bus_info`](#c-struct-media_device) must be set to "PCI:" (or "PCIe:") followed by
  the value of `pci_name()`. For USB devices,the [`usb_make_path()`](/kernel/hardware/driver-api/usb/usb.md#c-usb_make_path) function
  must be used. This field is used by applications to distinguish between
  otherwise identical devices that don't provide a serial number.

- [`media_device.hw_revision`](#c-struct-media_device) is the hardware device revision in a
  driver-specific format. When possible the revision should be formatted
  with the `KERNEL_VERSION()` macro.

> [!NOTE]
> \#) Upon successful registration a character device named media\[0-9\]+ is created. The device major and minor numbers are dynamic. The model name is exported as a sysfs attribute.
>
> \#) Unregistering a media device that hasn't been registered is **NOT** safe.

**Return**

returns zero on success or a negative error code.

#### <a id="c-media_device_register"></a>`media_device_register()`

```c
media_device_register(mdev)
```

Registers a media device element

**Parameters**

- `mdev`: pointer to struct [`media_device`](#c-struct-media_device)

**Description**

This macro calls [`__media_device_register()`](#c-__media_device_register) passing `THIS_MODULE` as
the [`__media_device_register()`](#c-__media_device_register) second argument (**owner**).

#### <a id="c-media_device_unregister"></a>`media_device_unregister()`

```c
void media_device_unregister(struct media_device *mdev)
```

Unregisters a media device element

**Parameters**

- `struct media_device *mdev`: pointer to struct [`media_device`](#c-struct-media_device)

**Description**

It is safe to call this function on an unregistered (but initialised)
media device.

#### <a id="c-media_device_register_entity"></a>`media_device_register_entity()`

```c
int media_device_register_entity(struct media_device *mdev, struct media_entity *entity)
```

registers a media entity inside a previously registered media device.

**Parameters**

- `struct media_device *mdev`: pointer to struct [`media_device`](#c-struct-media_device)
- `struct media_entity *entity`: pointer to struct [`media_entity`](#c-struct-media_entity) to be registered

**Description**

Entities are identified by a unique positive integer ID. The media
controller framework will such ID automatically. IDs are not guaranteed
to be contiguous, and the ID number can change on newer Kernel versions.
So, neither the driver nor userspace should hardcode ID numbers to refer
to the entities, but, instead, use the framework to find the ID, when
needed.

The media_entity name, type and flags fields should be initialized before
calling [`media_device_register_entity()`](#c-media_device_register_entity). Entities embedded in higher-level
standard structures can have some of those fields set by the higher-level
framework.

If the device has pads, [`media_entity_pads_init()`](#c-media_entity_pads_init) should be called before
this function. Otherwise, the [`media_entity.pad`](#c-struct-media_entity) and [`media_entity.num_pads`](#c-struct-media_entity)
should be zeroed before calling this function.

Entities have flags that describe the entity capabilities and state:

- `MEDIA_ENT_FL_DEFAULT`:
  indicates the default entity for a given type.
  This can be used to report the default audio and video devices or the
  default camera sensor.

> [!NOTE]
> Drivers should set the entity function before calling this function.
> Please notice that the values `MEDIA_ENT_F_V4L2_SUBDEV_UNKNOWN` and
> `MEDIA_ENT_F_UNKNOWN` should not be used by the drivers.

#### <a id="c-media_device_unregister_entity"></a>`media_device_unregister_entity()`

```c
void media_device_unregister_entity(struct media_entity *entity)
```

unregisters a media entity.

**Parameters**

- `struct media_entity *entity`: pointer to struct [`media_entity`](#c-struct-media_entity) to be unregistered

**Description**

All links associated with the entity and all PADs are automatically
unregistered from the media_device when this function is called.

Unregistering an entity will not change the IDs of the other entities and
the previoully used ID will never be reused for a newly registered entities.

When a media device is unregistered, all its entities are unregistered
automatically. No manual entities unregistration is then required.

> [!NOTE]
> The media_entity instance itself must be freed explicitly by
> the driver if required.

#### <a id="c-media_device_register_entity_notify"></a>`media_device_register_entity_notify()`

```c
void media_device_register_entity_notify(struct media_device *mdev, struct media_entity_notify *nptr)
```

Registers a media entity_notify callback

**Parameters**

- `struct media_device *mdev`: The media device
- `struct media_entity_notify *nptr`: The media_entity_notify

**Description**

> [!NOTE]
> When a new entity is registered, all the registered
> media_entity_notify callbacks are invoked.

#### <a id="c-media_device_unregister_entity_notify"></a>`media_device_unregister_entity_notify()`

```c
void media_device_unregister_entity_notify(struct media_device *mdev, struct media_entity_notify *nptr)
```

Unregister a media entity notify callback

**Parameters**

- `struct media_device *mdev`: The media device
- `struct media_entity_notify *nptr`: The media_entity_notify

#### <a id="c-media_device_pci_init"></a>`media_device_pci_init()`

```c
void media_device_pci_init(struct media_device *mdev, struct pci_dev *pci_dev, const char *name)
```

create and initialize a struct [`media_device`](#c-struct-media_device) from a PCI device.

**Parameters**

- `struct media_device *mdev`: pointer to struct [`media_device`](#c-struct-media_device)
- `struct pci_dev *pci_dev`: pointer to struct pci_dev
- `const char *name`: media device name. If `NULL`, the routine will use the default
  name for the pci device, given by `pci_name()` macro.

#### <a id="c-__media_device_usb_init"></a>`__media_device_usb_init()`

```c
void __media_device_usb_init(struct media_device *mdev, struct usb_device *udev, const char *board_name, const char *driver_name)
```

create and initialize a struct [`media_device`](#c-struct-media_device) from a PCI device.

**Parameters**

- `struct media_device *mdev`: pointer to struct [`media_device`](#c-struct-media_device)
- `struct usb_device *udev`: pointer to struct usb_device
- `const char *board_name`: media device name. If `NULL`, the routine will use the usb
  product name, if available.
- `const char *driver_name`: name of the driver. if `NULL`, the routine will use the name
  given by `udev->dev->driver->name`, with is usually the wrong
  thing to do.

**Description**

> [!NOTE]
> It is better to call [`media_device_usb_init()`](#c-media_device_usb_init) instead, as
> such macro fills driver_name with `KBUILD_MODNAME`.

#### <a id="c-media_device_usb_init"></a>`media_device_usb_init()`

```c
media_device_usb_init(mdev, udev, name)
```

create and initialize a struct [`media_device`](#c-struct-media_device) from a PCI device.

**Parameters**

- `mdev`: pointer to struct [`media_device`](#c-struct-media_device)
- `udev`: pointer to struct usb_device
- `name`: media device name. If `NULL`, the routine will use the usb
  product name, if available.

**Description**

This macro calls [`media_device_usb_init()`](#c-media_device_usb_init) passing the
[`media_device_usb_init()`](#c-media_device_usb_init) **driver_name** parameter filled with
`KBUILD_MODNAME`.

#### <a id="c-media_set_bus_info"></a>`media_set_bus_info()`

```c
void media_set_bus_info(char *bus_info, size_t bus_info_size, struct device *dev)
```

Set bus_info field

**Parameters**

- `char *bus_info`: Variable where to write the bus info (char array)
- `size_t bus_info_size`: Length of the bus_info
- `struct device *dev`: Related struct device

**Description**

Sets bus information based on `dev`. This is currently done for PCI and
platform devices. dev is required to be non-NULL for this to happen.

This function is not meant to be called from drivers.



#### <a id="c-struct-media_file_operations"></a>`struct media_file_operations`

Media device file operations

**Definition**

```c
struct media_file_operations {
    struct module *owner;
    ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);
    ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);
    __poll_t (*poll) (struct file *, struct poll_table_struct *);
    long (*ioctl) (struct file *, unsigned int, unsigned long);
    long (*compat_ioctl) (struct file *, unsigned int, unsigned long);
    int (*open) (struct file *);
    int (*release) (struct file *);
};
```

**Members**

- `owner`: should be filled with `THIS_MODULE`
- `read`: pointer to the function that implements `read()` syscall
- `write`: pointer to the function that implements `write()` syscall
- `poll`: pointer to the function that implements `poll()` syscall
- `ioctl`: pointer to the function that implements `ioctl()` syscall
- `compat_ioctl`: pointer to the function that will handle 32 bits userspace
  calls to the `ioctl()` syscall on a Kernel compiled with 64 bits.
- `open`: pointer to the function that implements `open()` syscall
- `release`: pointer to the function that will release the resources allocated
  by the **open** function.

#### <a id="c-struct-media_devnode"></a>`struct media_devnode`

Media device node

**Definition**

```c
struct media_devnode {
    struct media_device *media_dev;
    const struct media_file_operations *fops;
    struct device dev;
    struct cdev cdev;
    struct device *parent;
    int minor;
    unsigned long flags;
    void (*release)(struct media_devnode *devnode);
};
```

**Members**

- `media_dev`: pointer to struct [`media_device`](#c-struct-media_device)
- `fops`: pointer to struct [`media_file_operations`](#c-struct-media_file_operations) with media device ops
- `dev`: pointer to struct [`device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) containing the media controller device
- `cdev`: struct cdev pointer character device
- `parent`: parent device
- `minor`: device node minor number
- `flags`: flags, combination of the `MEDIA_FLAG_*` constants
- `release`: release callback called at the end of `media_devnode_release()`
  routine at media-device.c.

**Description**

This structure represents a media-related device node.

The **parent** is a physical device. It must be set by core or device drivers
before registering the node.

#### <a id="c-media_devnode_register"></a>`media_devnode_register()`

```c
int media_devnode_register(struct media_device *mdev, struct media_devnode *devnode, struct module *owner)
```

register a media device node

**Parameters**

- `struct media_device *mdev`: struct media_device we want to register a device node
- `struct media_devnode *devnode`: media device node structure we want to register
- `struct module *owner`: should be filled with `THIS_MODULE`

**Description**

The registration code assigns minor numbers and registers the new device node
with the kernel. An error is returned if no free minor number can be found,
or if the registration of the device node fails.

Zero is returned on success.

Note that if the media_devnode_register call fails, the `release()` callback of
the media_devnode structure is *not* called, so the caller is responsible for
freeing any data.

#### <a id="c-media_devnode_unregister_prepare"></a>`media_devnode_unregister_prepare()`

```c
void media_devnode_unregister_prepare(struct media_devnode *devnode)
```

clear the media device node register bit

**Parameters**

- `struct media_devnode *devnode`: the device node to prepare for unregister

**Description**

This clears the passed device register bit. Future open calls will be met
with errors. Should be called before [`media_devnode_unregister()`](#c-media_devnode_unregister) to avoid
races with unregister and device file open calls.

This function can safely be called if the device node has never been
registered or has already been unregistered.

#### <a id="c-media_devnode_unregister"></a>`media_devnode_unregister()`

```c
void media_devnode_unregister(struct media_devnode *devnode)
```

unregister a media device node

**Parameters**

- `struct media_devnode *devnode`: the device node to unregister

**Description**

This unregisters the passed device. Future open calls will be met with
errors.

Should be called after [`media_devnode_unregister_prepare()`](#c-media_devnode_unregister_prepare)

#### <a id="c-media_devnode_data"></a>`media_devnode_data()`

```c
struct media_devnode * media_devnode_data(struct file *filp)
```

returns a pointer to the [`media_devnode`](#c-struct-media_devnode)

**Parameters**

- `struct file *filp`: pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file)

#### <a id="c-media_devnode_is_registered"></a>`media_devnode_is_registered()`

```c
int media_devnode_is_registered(struct media_devnode *devnode)
```

returns true if [`media_devnode`](#c-struct-media_devnode) is registered; false otherwise.

**Parameters**

- `struct media_devnode *devnode`: pointer to struct [`media_devnode`](#c-struct-media_devnode).

**Note**

If mdev is NULL, it also returns false.



#### <a id="c-enum-media_gobj_type"></a>`enum media_gobj_type`

type of a graph object

**Constants**

- `MEDIA_GRAPH_ENTITY`: Identify a media entity
- `MEDIA_GRAPH_PAD`: Identify a media pad
- `MEDIA_GRAPH_LINK`: Identify a media link
- `MEDIA_GRAPH_INTF_DEVNODE`: Identify a media Kernel API interface via
  a device node

#### <a id="c-struct-media_gobj"></a>`struct media_gobj`

Define a graph object.

**Definition**

```c
struct media_gobj {
    struct media_device     *mdev;
    u32 id;
    struct list_head        list;
};
```

**Members**

- `mdev`: Pointer to the struct [`media_device`](#c-struct-media_device) that owns the object
- `id`: Non-zero object ID identifier. The ID should be unique
  inside a media_device, as it is composed by
  `MEDIA_BITS_PER_TYPE` to store the type plus
  `MEDIA_BITS_PER_ID` to store the ID
- `list`: List entry stored in one of the per-type mdev object lists

**Description**

All objects on the media graph should have this struct embedded

#### <a id="c-struct-media_entity_enum"></a>`struct media_entity_enum`

An enumeration of media entities.

**Definition**

```c
struct media_entity_enum {
    unsigned long *bmap;
    int idx_max;
};
```

**Members**

- `bmap`: Bit map in which each bit represents one entity at struct
  media_entity->internal_idx.
- `idx_max`: Number of bits in bmap

#### <a id="c-struct-media_graph"></a>`struct media_graph`

Media graph traversal state

**Definition**

```c
struct media_graph {
    struct {
        struct media_entity *entity;
        struct list_head *link;
    } stack[MEDIA_ENTITY_ENUM_MAX_DEPTH];
    struct media_entity_enum ent_enum;
    int top;
};
```

**Members**

- `stack`: Graph traversal stack; the stack contains information
  on the path the media entities to be walked and the
  links through which they were reached.
- `stack.entity`: pointer to [`struct media_entity`](#c-struct-media_entity) at the graph.
- `stack.link`: pointer to `struct list_head`.
- `ent_enum`: Visited entities
- `top`: The top of the stack

#### <a id="c-struct-media_pipeline"></a>`struct media_pipeline`

Media pipeline related information

**Definition**

```c
struct media_pipeline {
    bool allocated;
    struct media_device *mdev;
    struct list_head pads;
    int start_count;
};
```

**Members**

- `allocated`: Media pipeline allocated and freed by the framework
- `mdev`: The media device the pipeline is part of
- `pads`: List of media_pipeline_pad
- `start_count`: Media pipeline start - stop count

#### <a id="c-struct-media_pipeline_pad"></a>`struct media_pipeline_pad`

A pad part of a media pipeline

**Definition**

```c
struct media_pipeline_pad {
    struct list_head list;
    struct media_pipeline *pipe;
    struct media_pad *pad;
};
```

**Members**

- `list`: Entry in the media_pad pads list
- `pipe`: The media_pipeline that the pad is part of
- `pad`: The media pad

**Description**

This structure associate a pad with a media pipeline. Instances of
media_pipeline_pad are created by [`media_pipeline_start()`](#c-media_pipeline_start) when it builds the
pipeline, and stored in the [`media_pad.pads`](#c-struct-media_pad) list. [`media_pipeline_stop()`](#c-media_pipeline_stop)
removes the entries from the list and deletes them.

#### <a id="c-struct-media_pipeline_pad_iter"></a>`struct media_pipeline_pad_iter`

Iterator for media_pipeline_for_each_pad

**Definition**

```c
struct media_pipeline_pad_iter {
    struct list_head *cursor;
};
```

**Members**

- `cursor`: The current element

#### <a id="c-struct-media_pipeline_entity_iter"></a>`struct media_pipeline_entity_iter`

Iterator for media_pipeline_for_each_entity

**Definition**

```c
struct media_pipeline_entity_iter {
    struct media_entity_enum ent_enum;
    struct list_head *cursor;
};
```

**Members**

- `ent_enum`: The entity enumeration tracker
- `cursor`: The current element

#### <a id="c-struct-media_link"></a>`struct media_link`

A link object part of a media graph.

**Definition**

```c
struct media_link {
    struct media_gobj graph_obj;
    struct list_head list;
    union {
        struct media_gobj *gobj0;
        struct media_pad *source;
        struct media_interface *intf;
    };
    union {
        struct media_gobj *gobj1;
        struct media_pad *sink;
        struct media_entity *entity;
    };
    struct media_link *reverse;
    unsigned long flags;
    bool is_backlink;
};
```

**Members**

- `graph_obj`: Embedded structure containing the media object common data
- `list`: Linked list associated with an entity or an interface that
  owns the link.
- `{unnamed_union}`: anonymous
- `gobj0`: Part of a union. Used to get the pointer for the first
  graph_object of the link.
- `source`: Part of a union. Used only if the first object (gobj0) is
  a pad. In that case, it represents the source pad.
- `intf`: Part of a union. Used only if the first object (gobj0) is
  an interface.
- `{unnamed_union}`: anonymous
- `gobj1`: Part of a union. Used to get the pointer for the second
  graph_object of the link.
- `sink`: Part of a union. Used only if the second object (gobj1) is
  a pad. In that case, it represents the sink pad.
- `entity`: Part of a union. Used only if the second object (gobj1) is
  an entity.
- `reverse`: Pointer to the link for the reverse direction of a pad to pad
  link.
- `flags`: Link flags, as defined in uapi/media.h (MEDIA_LNK_FL_*)
- `is_backlink`: Indicate if the link is a backlink.

#### <a id="c-enum-media_pad_signal_type"></a>`enum media_pad_signal_type`

type of the signal inside a media pad

**Constants**

- `PAD_SIGNAL_DEFAULT`: Default signal. Use this when all inputs or all outputs are
  uniquely identified by the pad number.
- `PAD_SIGNAL_ANALOG`: The pad contains an analog signal. It can be Radio Frequency,
  Intermediate Frequency, a baseband signal or sub-carriers.
  Tuner inputs, IF-PLL demodulators, composite and s-video signals
  should use it.
- `PAD_SIGNAL_DV`: Contains a digital video signal, with can be a bitstream of samples
  taken from an analog TV video source. On such case, it usually
  contains the VBI data on it.
- `PAD_SIGNAL_AUDIO`: Contains an Intermediate Frequency analog signal from an audio
  sub-carrier or an audio bitstream. IF signals are provided by tuners
  and consumed by audio AM/FM decoders. Bitstream audio is provided by
  an audio decoder.

#### <a id="c-struct-media_pad"></a>`struct media_pad`

A media pad graph object.

**Definition**

```c
struct media_pad {
    struct media_gobj graph_obj;
    struct media_entity *entity;
    u16 index;
    u16 num_links;
    enum media_pad_signal_type sig_type;
    unsigned long flags;
    struct media_pipeline *pipe;
};
```

**Members**

- `graph_obj`: Embedded structure containing the media object common data
- `entity`: Entity this pad belongs to
- `index`: Pad index in the entity pads array, numbered from 0 to n
- `num_links`: Number of links connected to this pad
- `sig_type`: Type of the signal inside a media pad
- `flags`: Pad flags, as defined in
  include/uapi/linux/media.h
  (seek for `MEDIA_PAD_FL_*`)
- `pipe`: Pipeline this pad belongs to. Use [`media_entity_pipeline()`](#c-media_entity_pipeline) to
  access this field.

#### <a id="c-struct-media_entity_operations"></a>`struct media_entity_operations`

Media entity operations

**Definition**

```c
struct media_entity_operations {
    int (*get_fwnode_pad)(struct media_entity *entity, struct fwnode_endpoint *endpoint);
    int (*link_setup)(struct media_entity *entity, const struct media_pad *local, const struct media_pad *remote, u32 flags);
    int (*link_validate)(struct media_link *link);
    bool (*has_pad_interdep)(struct media_entity *entity, unsigned int pad0, unsigned int pad1);
};
```

**Members**

- `get_fwnode_pad`: Return the pad number based on a fwnode endpoint or
  a negative value on error. This operation can be used
  to map a fwnode to a media pad number. Optional.
- `link_setup`: Notify the entity of link changes. The operation can
  return an error, in which case link setup will be
  cancelled. Optional.
- `link_validate`: Return whether a link is valid from the entity point of
  view. The [`media_pipeline_start()`](#c-media_pipeline_start) function
  validates all links by calling this operation. Optional.
- `has_pad_interdep`: Return whether two pads of the entity are
  interdependent. If two pads are interdependent they are
  part of the same pipeline and enabling one of the pads
  means that the other pad will become "locked" and
  doesn't allow configuration changes. pad0 and pad1 are
  guaranteed to not both be sinks or sources. Never call
  the .`has_pad_interdep()` operation directly, always use
  `media_entity_has_pad_interdep()`.
  Optional: If the operation isn't implemented all pads
  will be considered as interdependent.

**Description**

> [!NOTE]
> Those these callbacks are called with struct [`media_device.graph_mutex`](#c-struct-media_device)
> mutex held.

#### <a id="c-enum-media_entity_type"></a>`enum media_entity_type`

Media entity type

**Constants**

- `MEDIA_ENTITY_TYPE_BASE`: The entity isn't embedded in another subsystem structure.
- `MEDIA_ENTITY_TYPE_VIDEO_DEVICE`: The entity is embedded in a struct video_device instance.
- `MEDIA_ENTITY_TYPE_V4L2_SUBDEV`: The entity is embedded in a struct v4l2_subdev instance.

**Description**

Media entity objects are often not instantiated directly, but the media
entity structure is inherited by (through embedding) other subsystem-specific
structures. The media entity type identifies the type of the subclass
structure that implements a media entity instance.

This allows runtime type identification of media entities and safe casting to
the correct object type. For instance, a media entity structure instance
embedded in a v4l2_subdev structure instance will have the type
`MEDIA_ENTITY_TYPE_V4L2_SUBDEV` and can safely be cast to a [`v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)
structure using the [`container_of()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-container_of) macro.

#### <a id="c-struct-media_entity"></a>`struct media_entity`

A media entity graph object.

**Definition**

```c
struct media_entity {
    struct media_gobj graph_obj;
    const char *name;
    enum media_entity_type obj_type;
    u32 function;
    unsigned long flags;
    u16 num_pads;
    u16 num_links;
    u16 num_backlinks;
    int internal_idx;
    struct media_pad *pads;
    struct list_head links;
    const struct media_entity_operations *ops;
    int use_count;
    union {
        struct {
            u32 major;
            u32 minor;
        } dev;
    } info;
};
```

**Members**

- `graph_obj`: Embedded structure containing the media object common data.
- `name`: Entity name.
- `obj_type`: Type of the object that implements the media_entity.
- `function`: Entity main function, as defined in
  include/uapi/linux/media.h
  (seek for `MEDIA_ENT_F_*`)
- `flags`: Entity flags, as defined in
  include/uapi/linux/media.h
  (seek for `MEDIA_ENT_FL_*`)
- `num_pads`: Number of sink and source pads.
- `num_links`: Total number of links, forward and back, enabled and disabled.
- `num_backlinks`: Number of backlinks
- `internal_idx`: An unique internal entity specific number. The numbers are
  re-used if entities are unregistered or registered again.
- `pads`: Pads array with the size defined by **num_pads**.
- `links`: List of data links.
- `ops`: Entity operations.
- `use_count`: Use count for the entity.
- `info`: Union with devnode information.  Kept just for backward
  compatibility.
- `info.dev`: Contains device major and minor info.
- `info.dev.major`: device node major, if the device is a devnode.
- `info.dev.minor`: device node minor, if the device is a devnode.

**Description**

> [!NOTE]
> The **use_count** reference count must never be negative, but is a signed
> integer on purpose: a simple `WARN_ON(<0)` check can be used to detect
> reference count bugs that would make it negative.

#### <a id="c-media_entity_for_each_pad"></a>`media_entity_for_each_pad()`

```c
media_entity_for_each_pad(entity, iter)
```

Iterate on all pads in an entity

**Parameters**

- `entity`: The entity the pads belong to
- `iter`: The iterator pad

**Description**

Iterate on all pads in a media entity.

#### <a id="c-struct-media_interface"></a>`struct media_interface`

A media interface graph object.

**Definition**

```c
struct media_interface {
    struct media_gobj               graph_obj;
    struct list_head                links;
    u32 type;
    u32 flags;
};
```

**Members**

- `graph_obj`: embedded graph object
- `links`: List of links pointing to graph entities
- `type`: Type of the interface as defined in
  include/uapi/linux/media.h
  (seek for `MEDIA_INTF_T_*`)
- `flags`: Interface flags as defined in
  include/uapi/linux/media.h
  (seek for `MEDIA_INTF_FL_*`)

**Description**

> [!NOTE]
> Currently, no flags for [`media_interface`](#c-struct-media_interface) is defined.

#### <a id="c-struct-media_intf_devnode"></a>`struct media_intf_devnode`

A media interface via a device node.

**Definition**

```c
struct media_intf_devnode {
    struct media_interface          intf;
    u32 major;
    u32 minor;
};
```

**Members**

- `intf`: embedded interface object
- `major`: Major number of a device node
- `minor`: Minor number of a device node

#### <a id="c-media_entity_id"></a>`media_entity_id()`

```c
u32 media_entity_id(struct media_entity *entity)
```

return the media entity graph object id

**Parameters**

- `struct media_entity *entity`: pointer to [`media_entity`](#c-struct-media_entity)

#### <a id="c-media_type"></a>`media_type()`

```c
enum media_gobj_type media_type(struct media_gobj *gobj)
```

return the media object type

**Parameters**

- `struct media_gobj *gobj`: Pointer to the struct [`media_gobj`](#c-struct-media_gobj) graph object

#### <a id="c-media_id"></a>`media_id()`

```c
u32 media_id(struct media_gobj *gobj)
```

return the media object ID

**Parameters**

- `struct media_gobj *gobj`: Pointer to the struct [`media_gobj`](#c-struct-media_gobj) graph object

#### <a id="c-media_gobj_gen_id"></a>`media_gobj_gen_id()`

```c
u32 media_gobj_gen_id(enum media_gobj_type type, u64 local_id)
```

encapsulates type and ID on at the object ID

**Parameters**

- `enum media_gobj_type type`: object type as define at enum [`media_gobj_type`](#c-enum-media_gobj_type).
- `u64 local_id`: next ID, from struct [`media_device.id`](#c-struct-media_device).

#### <a id="c-is_media_entity_v4l2_video_device"></a>`is_media_entity_v4l2_video_device()`

```c
bool is_media_entity_v4l2_video_device(struct media_entity *entity)
```

Check if the entity is a video_device

**Parameters**

- `struct media_entity *entity`: pointer to entity

**Return**

`true` if the entity is an instance of a video_device object and can
safely be cast to a struct video_device using the [`container_of()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-container_of) macro, or
`false` otherwise.

#### <a id="c-is_media_entity_v4l2_subdev"></a>`is_media_entity_v4l2_subdev()`

```c
bool is_media_entity_v4l2_subdev(struct media_entity *entity)
```

Check if the entity is a v4l2_subdev

**Parameters**

- `struct media_entity *entity`: pointer to entity

**Return**

`true` if the entity is an instance of a [`v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev) object and can
safely be cast to a struct [`v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev) using the [`container_of()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-container_of) macro, or
`false` otherwise.

#### <a id="c-media_entity_enum_init"></a>`media_entity_enum_init()`

```c
int media_entity_enum_init(struct media_entity_enum *ent_enum, struct media_device *mdev)
```

Initialise an entity enumeration

**Parameters**

- `struct media_entity_enum *ent_enum`: Entity enumeration to be initialised
- `struct media_device *mdev`: The related media device

**Return**

zero on success or a negative error code.

#### <a id="c-media_entity_enum_cleanup"></a>`media_entity_enum_cleanup()`

```c
void media_entity_enum_cleanup(struct media_entity_enum *ent_enum)
```

Release resources of an entity enumeration

**Parameters**

- `struct media_entity_enum *ent_enum`: Entity enumeration to be released

#### <a id="c-media_entity_enum_zero"></a>`media_entity_enum_zero()`

```c
void media_entity_enum_zero(struct media_entity_enum *ent_enum)
```

Clear the entire enum

**Parameters**

- `struct media_entity_enum *ent_enum`: Entity enumeration to be cleared

#### <a id="c-media_entity_enum_set"></a>`media_entity_enum_set()`

```c
void media_entity_enum_set(struct media_entity_enum *ent_enum, struct media_entity *entity)
```

Mark a single entity in the enum

**Parameters**

- `struct media_entity_enum *ent_enum`: Entity enumeration
- `struct media_entity *entity`: Entity to be marked

#### <a id="c-media_entity_enum_clear"></a>`media_entity_enum_clear()`

```c
void media_entity_enum_clear(struct media_entity_enum *ent_enum, struct media_entity *entity)
```

Unmark a single entity in the enum

**Parameters**

- `struct media_entity_enum *ent_enum`: Entity enumeration
- `struct media_entity *entity`: Entity to be unmarked

#### <a id="c-media_entity_enum_test"></a>`media_entity_enum_test()`

```c
bool media_entity_enum_test(struct media_entity_enum *ent_enum, struct media_entity *entity)
```

Test whether the entity is marked

**Parameters**

- `struct media_entity_enum *ent_enum`: Entity enumeration
- `struct media_entity *entity`: Entity to be tested

**Description**

Returns `true` if the entity was marked.

#### <a id="c-media_entity_enum_test_and_set"></a>`media_entity_enum_test_and_set()`

```c
bool media_entity_enum_test_and_set(struct media_entity_enum *ent_enum, struct media_entity *entity)
```

Test whether the entity is marked, and mark it

**Parameters**

- `struct media_entity_enum *ent_enum`: Entity enumeration
- `struct media_entity *entity`: Entity to be tested

**Description**

Returns `true` if the entity was marked, and mark it before doing so.

#### <a id="c-media_entity_enum_empty"></a>`media_entity_enum_empty()`

```c
bool media_entity_enum_empty(struct media_entity_enum *ent_enum)
```

Test whether the entire enum is empty

**Parameters**

- `struct media_entity_enum *ent_enum`: Entity enumeration

**Return**

`true` if the entity was empty.

#### <a id="c-media_entity_enum_intersects"></a>`media_entity_enum_intersects()`

```c
bool media_entity_enum_intersects(struct media_entity_enum *ent_enum1, struct media_entity_enum *ent_enum2)
```

Test whether two enums intersect

**Parameters**

- `struct media_entity_enum *ent_enum1`: First entity enumeration
- `struct media_entity_enum *ent_enum2`: Second entity enumeration

**Return**

`true` if entity enumerations **ent_enum1** and **ent_enum2** intersect,
otherwise `false`.

#### <a id="c-gobj_to_entity"></a>`gobj_to_entity()`

```c
gobj_to_entity(gobj)
```

returns the struct [`media_entity`](#c-struct-media_entity) pointer from the **gobj** contained on it.

**Parameters**

- `gobj`: Pointer to the struct [`media_gobj`](#c-struct-media_gobj) graph object

#### <a id="c-gobj_to_pad"></a>`gobj_to_pad()`

```c
gobj_to_pad(gobj)
```

returns the struct [`media_pad`](#c-struct-media_pad) pointer from the **gobj** contained on it.

**Parameters**

- `gobj`: Pointer to the struct [`media_gobj`](#c-struct-media_gobj) graph object

#### <a id="c-gobj_to_link"></a>`gobj_to_link()`

```c
gobj_to_link(gobj)
```

returns the struct [`media_link`](#c-struct-media_link) pointer from the **gobj** contained on it.

**Parameters**

- `gobj`: Pointer to the struct [`media_gobj`](#c-struct-media_gobj) graph object

#### <a id="c-gobj_to_intf"></a>`gobj_to_intf()`

```c
gobj_to_intf(gobj)
```

returns the struct [`media_interface`](#c-struct-media_interface) pointer from the **gobj** contained on it.

**Parameters**

- `gobj`: Pointer to the struct [`media_gobj`](#c-struct-media_gobj) graph object

#### <a id="c-intf_to_devnode"></a>`intf_to_devnode()`

```c
intf_to_devnode(intf)
```

returns the struct media_intf_devnode pointer from the **intf** contained on it.

**Parameters**

- `intf`: Pointer to struct [`media_intf_devnode`](#c-struct-media_intf_devnode)

#### <a id="c-media_gobj_create"></a>`media_gobj_create()`

```c
void media_gobj_create(struct media_device *mdev, enum media_gobj_type type, struct media_gobj *gobj)
```

Initialize a graph object

**Parameters**

- `struct media_device *mdev`: Pointer to the [`media_device`](#c-struct-media_device) that contains the object
- `enum media_gobj_type type`: Type of the object
- `struct media_gobj *gobj`: Pointer to the struct [`media_gobj`](#c-struct-media_gobj) graph object

**Description**

This routine initializes the embedded struct [`media_gobj`](#c-struct-media_gobj) inside a
media graph object. It is called automatically if `media_*_create`
function calls are used. However, if the object (entity, link, pad,
interface) is embedded on some other object, this function should be
called before registering the object at the media controller.

#### <a id="c-media_gobj_destroy"></a>`media_gobj_destroy()`

```c
void media_gobj_destroy(struct media_gobj *gobj)
```

Stop using a graph object on a media device

**Parameters**

- `struct media_gobj *gobj`: Pointer to the struct [`media_gobj`](#c-struct-media_gobj) graph object

**Description**

This should be called by all routines like [`media_device_unregister()`](#c-media_device_unregister)
that remove/destroy media graph objects.

#### <a id="c-media_entity_pads_init"></a>`media_entity_pads_init()`

```c
int media_entity_pads_init(struct media_entity *entity, u16 num_pads, struct media_pad *pads)
```

Initialize the entity pads

**Parameters**

- `struct media_entity *entity`: entity where the pads belong
- `u16 num_pads`: total number of sink and source pads
- `struct media_pad *pads`: Array of **num_pads** pads.

**Description**

The pads array is managed by the entity driver and passed to
[`media_entity_pads_init()`](#c-media_entity_pads_init) where its pointer will be stored in the
[`media_entity`](#c-struct-media_entity) structure.

If no pads are needed, drivers could either directly fill
[`media_entity->num_pads`](#c-struct-media_entity) with 0 and [`media_entity->pads`](#c-struct-media_entity) with `NULL` or call
this function that will do the same.

As the number of pads is known in advance, the pads array is not allocated
dynamically but is managed by the entity driver. Most drivers will embed the
pads array in a driver-specific structure, avoiding dynamic allocation.

Drivers must set the direction of every pad in the pads array before calling
[`media_entity_pads_init()`](#c-media_entity_pads_init). The function will initialize the other pads fields.

#### <a id="c-media_entity_cleanup"></a>`media_entity_cleanup()`

```c
void media_entity_cleanup(struct media_entity *entity)
```

free resources associated with an entity

**Parameters**

- `struct media_entity *entity`: entity where the pads belong

**Description**

This function must be called during the cleanup phase after unregistering
the entity (currently, it does nothing).

Calling [`media_entity_cleanup()`](#c-media_entity_cleanup) on a media_entity whose memory has been
zeroed but that has not been initialized with `media_entity_pad_init()` is
valid and is a no-op.

#### <a id="c-media_get_pad_index"></a>`media_get_pad_index()`

```c
int media_get_pad_index(struct media_entity *entity, u32 pad_type, enum media_pad_signal_type sig_type)
```

retrieves a pad index from an entity

**Parameters**

- `struct media_entity *entity`: entity where the pads belong
- `u32 pad_type`: the type of the pad, one of MEDIA_PAD_FL_* pad types
- `enum media_pad_signal_type sig_type`: type of signal of the pad to be search

**Description**

This helper function finds the first pad index inside an entity that
satisfies both **is_sink** and **sig_type** conditions.

On success, return the pad number. If the pad was not found or the media
entity is a NULL pointer, return -EINVAL.

#### <a id="c-media_create_pad_link"></a>`media_create_pad_link()`

```c
int media_create_pad_link(struct media_entity *source, u16 source_pad, struct media_entity *sink, u16 sink_pad, u32 flags)
```

creates a link between two entities.

**Parameters**

- `struct media_entity *source`: pointer to [`media_entity`](#c-struct-media_entity) of the source pad.
- `u16 source_pad`: number of the source pad in the pads array
- `struct media_entity *sink`: pointer to [`media_entity`](#c-struct-media_entity) of the sink pad.
- `u16 sink_pad`: number of the sink pad in the pads array.
- `u32 flags`: Link flags, as defined in
  include/uapi/linux/media.h
  ( seek for `MEDIA_LNK_FL_*`)

**Description**

Valid values for flags:

- `MEDIA_LNK_FL_ENABLED`:
  Indicates that the link is enabled and can be used to transfer media data.
  When two or more links target a sink pad, only one of them can be
  enabled at a time.

- `MEDIA_LNK_FL_IMMUTABLE`:
  Indicates that the link enabled state can't be modified at runtime. If
  `MEDIA_LNK_FL_IMMUTABLE` is set, then `MEDIA_LNK_FL_ENABLED` must also be
  set, since an immutable link is always enabled.

> [!NOTE]
> Before calling this function, [`media_entity_pads_init()`](#c-media_entity_pads_init) and
> [`media_device_register_entity()`](#c-media_device_register_entity) should be called previously for both ends.

#### <a id="c-media_create_pad_links"></a>`media_create_pad_links()`

```c
int media_create_pad_links(const struct media_device *mdev, const u32 source_function, struct media_entity *source, const u16 source_pad, const u32 sink_function, struct media_entity *sink, const u16 sink_pad, u32 flags, const bool allow_both_undefined)
```

creates a link between two entities.

**Parameters**

- `const struct media_device *mdev`: Pointer to the media_device that contains the object
- `const u32 source_function`: Function of the source entities. Used only if **source** is
  NULL.
- `struct media_entity *source`: pointer to [`media_entity`](#c-struct-media_entity) of the source pad. If NULL, it will use
  all entities that matches the **sink_function**.
- `const u16 source_pad`: number of the source pad in the pads array
- `const u32 sink_function`: Function of the sink entities. Used only if **sink** is NULL.
- `struct media_entity *sink`: pointer to [`media_entity`](#c-struct-media_entity) of the sink pad. If NULL, it will use
  all entities that matches the **sink_function**.
- `const u16 sink_pad`: number of the sink pad in the pads array.
- `u32 flags`: Link flags, as defined in include/uapi/linux/media.h.
- `const bool allow_both_undefined`: if `true`, then both **source** and **sink** can be NULL.
  In such case, it will create a crossbar between all entities that
  matches **source_function** to all entities that matches **sink_function**.
  If `false`, it will return 0 and won't create any link if both **source**
  and **sink** are NULL.

**Description**

Valid values for flags:

- A `MEDIA_LNK_FL_ENABLED` flag indicates that the link is enabled and can be

  used to transfer media data. If multiple links are created and this
  flag is passed as an argument, only the first created link will have
  this flag.

- A `MEDIA_LNK_FL_IMMUTABLE` flag indicates that the link enabled state can't

  be modified at runtime. If `MEDIA_LNK_FL_IMMUTABLE` is set, then
  `MEDIA_LNK_FL_ENABLED` must also be set since an immutable link is
  always enabled.

It is common for some devices to have multiple source and/or sink entities
of the same type that should be linked. While [`media_create_pad_link()`](#c-media_create_pad_link)
creates link by link, this function is meant to allow 1:n, n:1 and even
cross-bar (n:n) links.

> [!NOTE]
> Before calling this function, [`media_entity_pads_init()`](#c-media_entity_pads_init) and
> [`media_device_register_entity()`](#c-media_device_register_entity) should be called previously for the
> entities to be linked.

#### <a id="c-media_entity_remove_links"></a>`media_entity_remove_links()`

```c
void media_entity_remove_links(struct media_entity *entity)
```

remove all links associated with an entity

**Parameters**

- `struct media_entity *entity`: pointer to [`media_entity`](#c-struct-media_entity)

**Description**

> [!NOTE]
> This is called automatically when an entity is unregistered via
> [`media_device_register_entity()`](#c-media_device_register_entity).

#### <a id="c-__media_entity_setup_link"></a>`__media_entity_setup_link()`

```c
int __media_entity_setup_link(struct media_link *link, u32 flags)
```

Configure a media link without locking

**Parameters**

- `struct media_link *link`: The link being configured
- `u32 flags`: Link configuration flags

**Description**

The bulk of link setup is handled by the two entities connected through the
link. This function notifies both entities of the link configuration change.

If the link is immutable or if the current and new configuration are
identical, return immediately.

The user is expected to hold link->source->parent->mutex. If not,
[`media_entity_setup_link()`](#c-media_entity_setup_link) should be used instead.

#### <a id="c-media_entity_setup_link"></a>`media_entity_setup_link()`

```c
int media_entity_setup_link(struct media_link *link, u32 flags)
```

changes the link flags properties in runtime

**Parameters**

- `struct media_link *link`: pointer to [`media_link`](#c-struct-media_link)
- `u32 flags`: the requested new link flags

**Description**

The only configurable property is the `MEDIA_LNK_FL_ENABLED` link flag
to enable/disable a link. Links marked with the
`MEDIA_LNK_FL_IMMUTABLE` link flag can not be enabled or disabled.

When a link is enabled or disabled, the media framework calls the
link_setup operation for the two entities at the source and sink of the
link, in that order. If the second link_setup call fails, another
link_setup call is made on the first entity to restore the original link
flags.

Media device drivers can be notified of link setup operations by setting the
[`media_device.link_notify`](#c-struct-media_device) pointer to a callback function. If provided, the
notification callback will be called before enabling and after disabling
links.

Entity drivers must implement the link_setup operation if any of their links
is non-immutable. The operation must either configure the hardware or store
the configuration information to be applied later.

Link configuration must not have any side effect on other links. If an
enabled link at a sink pad prevents another link at the same pad from
being enabled, the link_setup operation must return `-EBUSY` and can't
implicitly disable the first enabled link.

> [!NOTE]
> The valid values of the flags for the link is the same as described
> on [`media_create_pad_link()`](#c-media_create_pad_link), for pad to pad links or the same as described
> on [`media_create_intf_link()`](#c-media_create_intf_link), for interface to entity links.

#### <a id="c-media_entity_find_link"></a>`media_entity_find_link()`

```c
struct media_link * media_entity_find_link(struct media_pad *source, struct media_pad *sink)
```

Find a link between two pads

**Parameters**

- `struct media_pad *source`: Source pad
- `struct media_pad *sink`: Sink pad

**Return**

returns a pointer to the link between the two entities. If no
such link exists, return `NULL`.

#### <a id="c-media_pad_remote_pad_first"></a>`media_pad_remote_pad_first()`

```c
struct media_pad * media_pad_remote_pad_first(const struct media_pad *pad)
```

Find the first pad at the remote end of a link

**Parameters**

- `const struct media_pad *pad`: Pad at the local end of the link

**Description**

Search for a remote pad connected to the given pad by iterating over all
links originating or terminating at that pad until an enabled link is found.

**Return**

returns a pointer to the pad at the remote end of the first found
enabled link, or `NULL` if no enabled link has been found.

#### <a id="c-media_pad_remote_pad_unique"></a>`media_pad_remote_pad_unique()`

```c
struct media_pad * media_pad_remote_pad_unique(const struct media_pad *pad)
```

Find a remote pad connected to a pad

**Parameters**

- `const struct media_pad *pad`: The pad

**Description**

Search for and return a remote pad connected to **pad** through an enabled
link. If multiple (or no) remote pads are found, an error is returned.

The uniqueness constraint makes this helper function suitable for entities
that support a single active source at a time on a given pad.

* -ENOTUNIQ - Multiple links are enabled
* -ENOLINK - No connected pad found

**Return**

A pointer to the remote pad, or one of the following error pointers
if an error occurs:

#### <a id="c-media_entity_remote_pad_unique"></a>`media_entity_remote_pad_unique()`

```c
struct media_pad * media_entity_remote_pad_unique(const struct media_entity *entity, unsigned int type)
```

Find a remote pad connected to an entity

**Parameters**

- `const struct media_entity *entity`: The entity
- `unsigned int type`: The type of pad to find (MEDIA_PAD_FL_SINK or MEDIA_PAD_FL_SOURCE)

**Description**

Search for and return a remote pad of **type** connected to **entity** through an
enabled link. If multiple (or no) remote pads match these criteria, an error
is returned.

The uniqueness constraint makes this helper function suitable for entities
that support a single active source or sink at a time.

* -ENOTUNIQ - Multiple links are enabled
* -ENOLINK - No connected pad found

**Return**

A pointer to the remote pad, or one of the following error pointers
if an error occurs:

#### <a id="c-media_entity_remote_source_pad_unique"></a>`media_entity_remote_source_pad_unique()`

```c
struct media_pad * media_entity_remote_source_pad_unique(const struct media_entity *entity)
```

Find a remote source pad connected to an entity

**Parameters**

- `const struct media_entity *entity`: The entity

**Description**

Search for and return a remote source pad connected to **entity** through an
enabled link. If multiple (or no) remote pads match these criteria, an error
is returned.

The uniqueness constraint makes this helper function suitable for entities
that support a single active source at a time.

* -ENOTUNIQ - Multiple links are enabled
* -ENOLINK - No connected pad found

**Return**

A pointer to the remote pad, or one of the following error pointers
if an error occurs:

#### <a id="c-media_pad_is_streaming"></a>`media_pad_is_streaming()`

```c
bool media_pad_is_streaming(const struct media_pad *pad)
```

Test if a pad is part of a streaming pipeline

**Parameters**

- `const struct media_pad *pad`: The pad

**Return**

True if the pad is part of a pipeline started with the
[`media_pipeline_start()`](#c-media_pipeline_start) function, false otherwise.

#### <a id="c-media_entity_is_streaming"></a>`media_entity_is_streaming()`

```c
bool media_entity_is_streaming(const struct media_entity *entity)
```

Test if an entity is part of a streaming pipeline

**Parameters**

- `const struct media_entity *entity`: The entity

**Return**

True if the entity is part of a pipeline started with the
[`media_pipeline_start()`](#c-media_pipeline_start) function, false otherwise.

#### <a id="c-media_entity_pipeline"></a>`media_entity_pipeline()`

```c
struct media_pipeline * media_entity_pipeline(struct media_entity *entity)
```

Get the media pipeline an entity is part of

**Parameters**

- `struct media_entity *entity`: The entity

**Description**

DEPRECATED: use [`media_pad_pipeline()`](#c-media_pad_pipeline) instead.

This function returns the media pipeline that an entity has been associated
with when constructing the pipeline with [`media_pipeline_start()`](#c-media_pipeline_start). The pointer
remains valid until [`media_pipeline_stop()`](#c-media_pipeline_stop) is called.

In general, entities can be part of multiple pipelines, when carrying
multiple streams (either on different pads, or on the same pad using
multiplexed streams). This function is to be used only for entities that
do not support multiple pipelines.

**Return**

The media_pipeline the entity is part of, or NULL if the entity is
not part of any pipeline.

#### <a id="c-media_pad_pipeline"></a>`media_pad_pipeline()`

```c
struct media_pipeline * media_pad_pipeline(struct media_pad *pad)
```

Get the media pipeline a pad is part of

**Parameters**

- `struct media_pad *pad`: The pad

**Description**

This function returns the media pipeline that a pad has been associated
with when constructing the pipeline with [`media_pipeline_start()`](#c-media_pipeline_start). The pointer
remains valid until [`media_pipeline_stop()`](#c-media_pipeline_stop) is called.

**Return**

The media_pipeline the pad is part of, or NULL if the pad is
not part of any pipeline.

#### <a id="c-media_entity_get_fwnode_pad"></a>`media_entity_get_fwnode_pad()`

```c
int media_entity_get_fwnode_pad(struct media_entity *entity, const struct fwnode_handle *fwnode, unsigned long direction_flags)
```

Get pad number from fwnode

**Parameters**

- `struct media_entity *entity`: The entity
- `const struct fwnode_handle *fwnode`: Pointer to the fwnode_handle which should be used to find the pad
- `unsigned long direction_flags`: Expected direction of the pad, as defined in
  include/uapi/linux/media.h
  (seek for `MEDIA_PAD_FL_*`)

**Description**

This function can be used to resolve the media pad number from
a fwnode. This is useful for devices which use more complex
mappings of media pads.

If the entity does not implement the `get_fwnode_pad()` operation
then this function searches the entity for the first pad that
matches the **direction_flags**.

**Return**

returns the pad number on success or a negative error code.

#### <a id="c-media_graph_walk_init"></a>`media_graph_walk_init()`

```c
int media_graph_walk_init(struct media_graph *graph, struct media_device *mdev)
```

Allocate resources used by graph walk.

**Parameters**

- `struct media_graph *graph`: Media graph structure that will be used to walk the graph
- `struct media_device *mdev`: Pointer to the [`media_device`](#c-struct-media_device) that contains the object

**Description**

This function is deprecated, use [`media_pipeline_for_each_pad()`](#c-media_pipeline_for_each_pad) instead.

The caller is required to hold the media_device graph_mutex during the graph
walk until the graph state is released.

Returns zero on success or a negative error code otherwise.

#### <a id="c-media_graph_walk_cleanup"></a>`media_graph_walk_cleanup()`

```c
void media_graph_walk_cleanup(struct media_graph *graph)
```

Release resources used by graph walk.

**Parameters**

- `struct media_graph *graph`: Media graph structure that will be used to walk the graph

**Description**

This function is deprecated, use [`media_pipeline_for_each_pad()`](#c-media_pipeline_for_each_pad) instead.

#### <a id="c-media_graph_walk_start"></a>`media_graph_walk_start()`

```c
void media_graph_walk_start(struct media_graph *graph, struct media_entity *entity)
```

Start walking the media graph at a given entity

**Parameters**

- `struct media_graph *graph`: Media graph structure that will be used to walk the graph
- `struct media_entity *entity`: Starting entity

**Description**

This function is deprecated, use [`media_pipeline_for_each_pad()`](#c-media_pipeline_for_each_pad) instead.

Before using this function, [`media_graph_walk_init()`](#c-media_graph_walk_init) must be
used to allocate resources used for walking the graph. This
function initializes the graph traversal structure to walk the
entities graph starting at the given entity. The traversal
structure must not be modified by the caller during graph
traversal. After the graph walk, the resources must be released
using [`media_graph_walk_cleanup()`](#c-media_graph_walk_cleanup).

#### <a id="c-media_graph_walk_next"></a>`media_graph_walk_next()`

```c
struct media_entity * media_graph_walk_next(struct media_graph *graph)
```

Get the next entity in the graph

**Parameters**

- `struct media_graph *graph`: Media graph structure

**Description**

This function is deprecated, use [`media_pipeline_for_each_pad()`](#c-media_pipeline_for_each_pad) instead.

Perform a depth-first traversal of the given media entities graph.

The graph structure must have been previously initialized with a call to
[`media_graph_walk_start()`](#c-media_graph_walk_start).

**Return**

returns the next entity in the graph or `NULL` if the whole graph
have been traversed.

#### <a id="c-media_pipeline_start"></a>`media_pipeline_start()`

```c
int media_pipeline_start(struct media_pad *origin, struct media_pipeline *pipe)
```

Mark a pipeline as streaming

**Parameters**

- `struct media_pad *origin`: Starting pad
- `struct media_pipeline *pipe`: Media pipeline to be assigned to all pads in the pipeline.

**Description**

Mark all pads connected to pad **origin** through enabled links, either
directly or indirectly, as streaming. The given pipeline object is assigned
to every pad in the pipeline and stored in the media_pad pipe field.

Calls to this function can be nested, in which case the same number of
[`media_pipeline_stop()`](#c-media_pipeline_stop) calls will be required to stop streaming. The
pipeline pointer must be identical for all nested calls to
[`media_pipeline_start()`](#c-media_pipeline_start).

#### <a id="c-__media_pipeline_start"></a>`__media_pipeline_start()`

```c
int __media_pipeline_start(struct media_pad *origin, struct media_pipeline *pipe)
```

Mark a pipeline as streaming

**Parameters**

- `struct media_pad *origin`: Starting pad
- `struct media_pipeline *pipe`: Media pipeline to be assigned to all pads in the pipeline.

**Description**

..note:: This is the non-locking version of [`media_pipeline_start()`](#c-media_pipeline_start)

#### <a id="c-media_pipeline_stop"></a>`media_pipeline_stop()`

```c
void media_pipeline_stop(struct media_pad *pad)
```

Mark a pipeline as not streaming

**Parameters**

- `struct media_pad *pad`: Starting pad

**Description**

Mark all pads connected to a given pad through enabled links, either
directly or indirectly, as not streaming. The media_pad pipe field is
reset to `NULL`.

If multiple calls to [`media_pipeline_start()`](#c-media_pipeline_start) have been made, the same
number of calls to this function are required to mark the pipeline as not
streaming.

#### <a id="c-__media_pipeline_stop"></a>`__media_pipeline_stop()`

```c
void __media_pipeline_stop(struct media_pad *pad)
```

Mark a pipeline as not streaming

**Parameters**

- `struct media_pad *pad`: Starting pad

**Description**

> [!NOTE]
> This is the non-locking version of [`media_pipeline_stop()`](#c-media_pipeline_stop)

#### <a id="c-media_pipeline_for_each_pad"></a>`media_pipeline_for_each_pad()`

```c
media_pipeline_for_each_pad(pipe, iter, pad)
```

Iterate on all pads in a media pipeline

**Parameters**

- `pipe`: The pipeline
- `iter`: The iterator (struct media_pipeline_pad_iter)
- `pad`: The iterator pad

**Description**

Iterate on all pads in a media pipeline. This is only valid after the
pipeline has been built with [`media_pipeline_start()`](#c-media_pipeline_start) and before it gets
destroyed with [`media_pipeline_stop()`](#c-media_pipeline_stop).

#### <a id="c-media_pipeline_entity_iter_init"></a>`media_pipeline_entity_iter_init()`

```c
int media_pipeline_entity_iter_init(struct media_pipeline *pipe, struct media_pipeline_entity_iter *iter)
```

Initialize a pipeline entity iterator

**Parameters**

- `struct media_pipeline *pipe`: The pipeline
- `struct media_pipeline_entity_iter *iter`: The iterator

**Description**

This function must be called to initialize the iterator before using it in a
[`media_pipeline_for_each_entity()`](#c-media_pipeline_for_each_entity) loop. The iterator must be destroyed by a
call to media_pipeline_entity_iter_cleanup after the loop (including in code
paths that break from the loop).

The same iterator can be used in multiple consecutive loops without being
destroyed and reinitialized.

**Return**

0 on success or a negative error code otherwise.

#### <a id="c-media_pipeline_entity_iter_cleanup"></a>`media_pipeline_entity_iter_cleanup()`

```c
void media_pipeline_entity_iter_cleanup(struct media_pipeline_entity_iter *iter)
```

Destroy a pipeline entity iterator

**Parameters**

- `struct media_pipeline_entity_iter *iter`: The iterator

**Description**

This function must be called to destroy iterators initialized with
[`media_pipeline_entity_iter_init()`](#c-media_pipeline_entity_iter_init).

#### <a id="c-media_pipeline_for_each_entity"></a>`media_pipeline_for_each_entity()`

```c
media_pipeline_for_each_entity(pipe, iter, entity)
```

Iterate on all entities in a media pipeline

**Parameters**

- `pipe`: The pipeline
- `iter`: The iterator (struct media_pipeline_entity_iter)
- `entity`: The iterator entity

**Description**

Iterate on all entities in a media pipeline. This is only valid after the
pipeline has been built with [`media_pipeline_start()`](#c-media_pipeline_start) and before it gets
destroyed with [`media_pipeline_stop()`](#c-media_pipeline_stop). The iterator must be initialized with
[`media_pipeline_entity_iter_init()`](#c-media_pipeline_entity_iter_init) before iteration, and destroyed with
[`media_pipeline_entity_iter_cleanup()`](#c-media_pipeline_entity_iter_cleanup) after (including in code paths that
break from the loop).

#### <a id="c-media_pipeline_alloc_start"></a>`media_pipeline_alloc_start()`

```c
int media_pipeline_alloc_start(struct media_pad *pad)
```

Mark a pipeline as streaming

**Parameters**

- `struct media_pad *pad`: Starting pad

**Description**

[`media_pipeline_alloc_start()`](#c-media_pipeline_alloc_start) is similar to [`media_pipeline_start()`](#c-media_pipeline_start) but instead
of working on a given pipeline the function will use an existing pipeline if
the pad is already part of a pipeline, or allocate a new pipeline.

Calls to [`media_pipeline_alloc_start()`](#c-media_pipeline_alloc_start) must be matched with
[`media_pipeline_stop()`](#c-media_pipeline_stop).

#### <a id="c-media_devnode_create"></a>`media_devnode_create()`

```c
struct media_intf_devnode * media_devnode_create(struct media_device *mdev, u32 type, u32 flags, u32 major, u32 minor)
```

creates and initializes a device node interface

**Parameters**

- `struct media_device *mdev`: pointer to struct [`media_device`](#c-struct-media_device)
- `u32 type`: type of the interface, as given by
  include/uapi/linux/media.h
  ( seek for `MEDIA_INTF_T_*`) macros.
- `u32 flags`: Interface flags, as defined in
  include/uapi/linux/media.h
  ( seek for `MEDIA_INTF_FL_*`)
- `u32 major`: Device node major number.
- `u32 minor`: Device node minor number.

**Return**

if succeeded, returns a pointer to the newly allocated
[`media_intf_devnode`](#c-struct-media_intf_devnode) pointer.

**Description**

> [!NOTE]
> Currently, no flags for [`media_interface`](#c-struct-media_interface) is defined.

#### <a id="c-media_devnode_remove"></a>`media_devnode_remove()`

```c
void media_devnode_remove(struct media_intf_devnode *devnode)
```

removes a device node interface

**Parameters**

- `struct media_intf_devnode *devnode`: pointer to [`media_intf_devnode`](#c-struct-media_intf_devnode) to be freed.

**Description**

When a device node interface is removed, all links to it are automatically
removed.

#### <a id="c-media_create_intf_link"></a>`media_create_intf_link()`

```c
struct media_link * media_create_intf_link(struct media_entity *entity, struct media_interface *intf, u32 flags)
```

creates a link between an entity and an interface

**Parameters**

- `struct media_entity *entity`: pointer to `media_entity`
- `struct media_interface *intf`: pointer to `media_interface`
- `u32 flags`: Link flags, as defined in
  include/uapi/linux/media.h
  ( seek for `MEDIA_LNK_FL_*`)

**Description**

Valid values for flags:

- `MEDIA_LNK_FL_ENABLED`:
  Indicates that the interface is connected to the entity hardware.
  That's the default value for interfaces. An interface may be disabled if
  the hardware is busy due to the usage of some other interface that it is
  currently controlling the hardware.

  A typical example is an hybrid TV device that handle only one type of
  stream on a given time. So, when the digital TV is streaming,
  the V4L2 interfaces won't be enabled, as such device is not able to
  also stream analog TV or radio.

> [!NOTE]
> Before calling this function, [`media_devnode_create()`](#c-media_devnode_create) should be called for
> the interface and [`media_device_register_entity()`](#c-media_device_register_entity) should be called for the
> interface that will be part of the link.

#### <a id="c-__media_remove_intf_link"></a>`__media_remove_intf_link()`

```c
void __media_remove_intf_link(struct media_link *link)
```

remove a single interface link

**Parameters**

- `struct media_link *link`: pointer to [`media_link`](#c-struct-media_link).

**Description**

> [!NOTE]
> This is an unlocked version of [`media_remove_intf_link()`](#c-media_remove_intf_link)

#### <a id="c-media_remove_intf_link"></a>`media_remove_intf_link()`

```c
void media_remove_intf_link(struct media_link *link)
```

remove a single interface link

**Parameters**

- `struct media_link *link`: pointer to [`media_link`](#c-struct-media_link).

**Description**

> [!NOTE]
> Prefer to use this one, instead of [`__media_remove_intf_link()`](#c-__media_remove_intf_link)

#### <a id="c-__media_remove_intf_links"></a>`__media_remove_intf_links()`

```c
void __media_remove_intf_links(struct media_interface *intf)
```

remove all links associated with an interface

**Parameters**

- `struct media_interface *intf`: pointer to [`media_interface`](#c-struct-media_interface)

**Description**

> [!NOTE]
> This is an unlocked version of [`media_remove_intf_links()`](#c-media_remove_intf_links).

#### <a id="c-media_remove_intf_links"></a>`media_remove_intf_links()`

```c
void media_remove_intf_links(struct media_interface *intf)
```

remove all links associated with an interface

**Parameters**

- `struct media_interface *intf`: pointer to [`media_interface`](#c-struct-media_interface)

**Description**

> [!NOTE]
> - #) This is called automatically when an entity is unregistered via
>
>   [`media_device_register_entity()`](#c-media_device_register_entity) and by [`media_devnode_remove()`](#c-media_devnode_remove).
>
> \#) Prefer to use this one, instead of [`__media_remove_intf_links()`](#c-__media_remove_intf_links).

#### <a id="c-media_entity_call"></a>`media_entity_call()`

```c
media_entity_call(entity, operation, args...)
```

Calls a struct media_entity_operations operation on an entity

**Parameters**

- `entity`: entity where the **operation** will be called
- `operation`: type of the operation. Should be the name of a member of
  struct [`media_entity_operations`](#c-struct-media_entity_operations).
- `args...`: variable arguments

**Description**

This helper function will check if **operation** is not `NULL`. On such case,
it will issue a call to **operation**\(**entity**, **args**\).

#### <a id="c-media_create_ancillary_link"></a>`media_create_ancillary_link()`

```c
struct media_link * media_create_ancillary_link(struct media_entity *primary, struct media_entity *ancillary)
```

create an ancillary link between two instances of [`media_entity`](#c-struct-media_entity)

**Parameters**

- `struct media_entity *primary`: pointer to the primary [`media_entity`](#c-struct-media_entity)
- `struct media_entity *ancillary`: pointer to the ancillary [`media_entity`](#c-struct-media_entity)

**Description**

Create an ancillary link between two entities, indicating that they
represent two connected pieces of hardware that form a single logical unit.
A typical example is a camera lens controller being linked to the sensor that
it is supporting.

The function sets both MEDIA_LNK_FL_ENABLED and MEDIA_LNK_FL_IMMUTABLE for
the new link.

#### <a id="c-__media_entity_next_link"></a>`__media_entity_next_link()`

```c
struct media_link * __media_entity_next_link(struct media_entity *entity, struct media_link *link, unsigned long link_type)
```

Iterate through a [`media_entity`](#c-struct-media_entity)'s links

**Parameters**

- `struct media_entity *entity`: pointer to the [`media_entity`](#c-struct-media_entity)
- `struct media_link *link`: pointer to a [`media_link`](#c-struct-media_link) to hold the iterated values
- `unsigned long link_type`: one of the MEDIA_LNK_FL_LINK_TYPE flags

**Description**

Return the next link against an entity matching a specific link type. This
allows iteration through an entity's links whilst guaranteeing all of the
returned links are of the given type.

#### <a id="c-for_each_media_entity_data_link"></a>`for_each_media_entity_data_link()`

```c
for_each_media_entity_data_link(entity, link)
```

Iterate through an entity's data links

**Parameters**

- `entity`: pointer to the [`media_entity`](#c-struct-media_entity)
- `link`: pointer to a [`media_link`](#c-struct-media_link) to hold the iterated values

**Description**

Iterate over a [`media_entity`](#c-struct-media_entity)'s data links



#### <a id="c-enum-media_request_state"></a>`enum media_request_state`

media request state

**Constants**

- `MEDIA_REQUEST_STATE_IDLE`: Idle
- `MEDIA_REQUEST_STATE_VALIDATING`: Validating the request, no state changes
  allowed
- `MEDIA_REQUEST_STATE_QUEUED`: Queued
- `MEDIA_REQUEST_STATE_COMPLETE`: Completed, the request is done
- `MEDIA_REQUEST_STATE_CLEANING`: Cleaning, the request is being re-inited
- `MEDIA_REQUEST_STATE_UPDATING`: The request is being updated, i.e.
  request objects are being added,
  modified or removed
- `NR_OF_MEDIA_REQUEST_STATE`: The number of media request states, used
  internally for sanity check purposes

#### <a id="c-struct-media_request"></a>`struct media_request`

Media device request

**Definition**

```c
struct media_request {
    struct media_device *mdev;
    struct kref kref;
    char debug_str[TASK_COMM_LEN + 11];
    enum media_request_state state;
    unsigned int updating_count;
    unsigned int access_count;
    struct list_head objects;
    unsigned int num_incomplete_objects;
    bool manual_completion;
    wait_queue_head_t poll_wait;
    spinlock_t lock;
};
```

**Members**

- `mdev`: Media device this request belongs to
- `kref`: Reference count
- `debug_str`: Prefix for debug messages (process name:fd)
- `state`: The state of the request
- `updating_count`: count the number of request updates that are in progress
- `access_count`: count the number of request accesses that are in progress
- `objects`: List of **struct** media_request_object request objects
- `num_incomplete_objects`: The number of incomplete objects in the request
- `manual_completion`: if true, then the request won't be marked as completed
  when **num_incomplete_objects** reaches 0. Call [`media_request_manual_complete()`](#c-media_request_manual_complete)
  to complete the request after **num_incomplete_objects** == 0.
- `poll_wait`: Wait queue for poll
- `lock`: Serializes access to this struct

#### <a id="c-media_request_lock_for_access"></a>`media_request_lock_for_access()`

```c
int media_request_lock_for_access(struct media_request *req)
```

Lock the request to access its objects

**Parameters**

- `struct media_request *req`: The media request

**Description**

Use before accessing a completed request. A reference to the request must
be held during the access. This usually takes place automatically through
a file handle. Use **media_request_unlock_for_access** when done.

#### <a id="c-media_request_unlock_for_access"></a>`media_request_unlock_for_access()`

```c
void media_request_unlock_for_access(struct media_request *req)
```

Unlock a request previously locked for access

**Parameters**

- `struct media_request *req`: The media request

**Description**

Unlock a request that has previously been locked using
**media_request_lock_for_access**.

#### <a id="c-media_request_lock_for_update"></a>`media_request_lock_for_update()`

```c
int media_request_lock_for_update(struct media_request *req)
```

Lock the request for updating its objects

**Parameters**

- `struct media_request *req`: The media request

**Description**

Use before updating a request, i.e. adding, modifying or removing a request
object in it. A reference to the request must be held during the update. This
usually takes place automatically through a file handle. Use
**media_request_unlock_for_update** when done.

#### <a id="c-media_request_unlock_for_update"></a>`media_request_unlock_for_update()`

```c
void media_request_unlock_for_update(struct media_request *req)
```

Unlock a request previously locked for update

**Parameters**

- `struct media_request *req`: The media request

**Description**

Unlock a request that has previously been locked using
**media_request_lock_for_update**.

#### <a id="c-media_request_get"></a>`media_request_get()`

```c
void media_request_get(struct media_request *req)
```

Get the media request

**Parameters**

- `struct media_request *req`: The media request

**Description**

Get the media request.

#### <a id="c-media_request_put"></a>`media_request_put()`

```c
void media_request_put(struct media_request *req)
```

Put the media request

**Parameters**

- `struct media_request *req`: The media request

**Description**

Put the media request. The media request will be released
when the refcount reaches 0.

#### <a id="c-media_request_get_by_fd"></a>`media_request_get_by_fd()`

```c
struct media_request * media_request_get_by_fd(struct media_device *mdev, int request_fd)
```

Get a media request by fd

**Parameters**

- `struct media_device *mdev`: Media device this request belongs to
- `int request_fd`: The file descriptor of the request

**Description**

Get the request represented by **request_fd** that is owned
by the media device.

Return a -EBADR error pointer if requests are not supported
by this driver. Return -EINVAL if the request was not found.
Return the pointer to the request if found: the caller will
have to call **media_request_put** when it finished using the
request.

#### <a id="c-media_request_alloc"></a>`media_request_alloc()`

```c
int media_request_alloc(struct media_device *mdev, int *alloc_fd)
```

Allocate the media request

**Parameters**

- `struct media_device *mdev`: Media device this request belongs to
- `int *alloc_fd`: Store the request's file descriptor in this int

**Description**

Allocated the media request and put the fd in **alloc_fd**.

#### <a id="c-media_request_mark_manual_completion"></a>`media_request_mark_manual_completion()`

```c
void media_request_mark_manual_completion(struct media_request *req)
```

Enable manual completion

**Parameters**

- `struct media_request *req`: The request

**Description**

Mark that the request has to be manually completed by calling
[`media_request_manual_complete()`](#c-media_request_manual_complete).

This function shall be called in the req_queue callback.

#### <a id="c-media_request_manual_complete"></a>`media_request_manual_complete()`

```c
void media_request_manual_complete(struct media_request *req)
```

Mark the request as completed

**Parameters**

- `struct media_request *req`: The request

**Description**

This function completes a request that was marked for manual completion by an
earlier call to [`media_request_mark_manual_completion()`](#c-media_request_mark_manual_completion). The request's
**manual_completion** field is reset to false.

All objects contained in the request must have been completed previously. It
is an error to call this function otherwise. If such an error occurred, the
function will WARN and the object completion will be delayed until
**num_incomplete_objects** is 0.

#### <a id="c-struct-media_request_object_ops"></a>`struct media_request_object_ops`

Media request object operations

**Definition**

```c
struct media_request_object_ops {
    int (*prepare)(struct media_request_object *object);
    void (*unprepare)(struct media_request_object *object);
    void (*queue)(struct media_request_object *object);
    void (*unbind)(struct media_request_object *object);
    void (*release)(struct media_request_object *object);
};
```

**Members**

- `prepare`: Validate and prepare the request object, optional.
- `unprepare`: Unprepare the request object, optional.
- `queue`: Queue the request object, optional.
- `unbind`: Unbind the request object, optional.
- `release`: Release the request object, required.

#### <a id="c-struct-media_request_object"></a>`struct media_request_object`

An opaque object that belongs to a media request

**Definition**

```c
struct media_request_object {
    struct media_device *mdev;
    const struct media_request_object_ops *ops;
    void *priv;
    struct media_request *req;
    struct list_head list;
    struct kref kref;
    bool completed;
};
```

**Members**

- `mdev`: Media device this object belongs to
- `ops`: object's operations
- `priv`: object's priv pointer
- `req`: the request this object belongs to (can be NULL)
- `list`: List entry of the object for **struct** media_request
- `kref`: Reference count of the object, acquire before releasing req->lock
- `completed`: If true, then this object was completed.

**Description**

An object related to the request. This struct is always embedded in
another struct that contains the actual data for this request object.

#### <a id="c-media_request_object_get"></a>`media_request_object_get()`

```c
void media_request_object_get(struct media_request_object *obj)
```

Get a media request object

**Parameters**

- `struct media_request_object *obj`: The object

**Description**

Get a media request object.

#### <a id="c-media_request_object_put"></a>`media_request_object_put()`

```c
void media_request_object_put(struct media_request_object *obj)
```

Put a media request object

**Parameters**

- `struct media_request_object *obj`: The object

**Description**

Put a media request object. Once all references are gone, the
object's memory is released.

#### <a id="c-media_request_object_find"></a>`media_request_object_find()`

```c
struct media_request_object * media_request_object_find(struct media_request *req, const struct media_request_object_ops *ops, void *priv)
```

Find an object in a request

**Parameters**

- `struct media_request *req`: The media request
- `const struct media_request_object_ops *ops`: Find an object with this ops value
- `void *priv`: Find an object with this priv value

**Description**

Both **ops** and **priv** must be non-NULL.

Returns the object pointer or NULL if not found. The caller must
call [`media_request_object_put()`](#c-media_request_object_put) once it finished using the object.

Since this function needs to walk the list of objects it takes
the **req->lock** spin lock to make this safe.

#### <a id="c-media_request_object_init"></a>`media_request_object_init()`

```c
void media_request_object_init(struct media_request_object *obj)
```

Initialise a media request object

**Parameters**

- `struct media_request_object *obj`: The object

**Description**

Initialise a media request object. The object will be released using the
release callback of the ops once it has no references (this function
initialises references to one).

#### <a id="c-media_request_object_bind"></a>`media_request_object_bind()`

```c
int media_request_object_bind(struct media_request *req, const struct media_request_object_ops *ops, void *priv, bool is_buffer, struct media_request_object *obj)
```

Bind a media request object to a request

**Parameters**

- `struct media_request *req`: The media request
- `const struct media_request_object_ops *ops`: The object ops for this object
- `void *priv`: A driver-specific priv pointer associated with this object
- `bool is_buffer`: Set to true if the object is a buffer object.
- `struct media_request_object *obj`: The object

**Description**

Bind this object to the request and set the ops and priv values of
the object so it can be found later with [`media_request_object_find()`](#c-media_request_object_find).

Every bound object must be unbound or completed by the kernel at some
point in time, otherwise the request will never complete. When the
request is released all completed objects will be unbound by the
request core code.

Buffer objects will be added to the end of the request's object
list, non-buffer objects will be added to the front of the list.
This ensures that all buffer objects are at the end of the list
and that all non-buffer objects that they depend on are processed
first.

#### <a id="c-media_request_object_unbind"></a>`media_request_object_unbind()`

```c
void media_request_object_unbind(struct media_request_object *obj)
```

Unbind a media request object

**Parameters**

- `struct media_request_object *obj`: The object

**Description**

Unbind the media request object from the request.

#### <a id="c-media_request_object_complete"></a>`media_request_object_complete()`

```c
void media_request_object_complete(struct media_request_object *obj)
```

Mark the media request object as complete

**Parameters**

- `struct media_request_object *obj`: The object

**Description**

Mark the media request object as complete. Only bound objects can
be completed.



#### <a id="c-media_device_usb_allocate"></a>`media_device_usb_allocate()`

```c
struct media_device * media_device_usb_allocate(struct usb_device *udev, const char *module_name, struct module *owner)
```

Allocate and return struct `media` device

**Parameters**

- `struct usb_device *udev`: struct [`usb_device`](/kernel/hardware/driver-api/usb/usb.md#c-struct-usb_device) pointer
- `const char *module_name`: should be filled with `KBUILD_MODNAME`
- `struct module *owner`: struct module pointer `THIS_MODULE` for the driver.
  `THIS_MODULE` is null for a built-in driver.
  It is safe even when `THIS_MODULE` is null.

**Description**

This interface should be called to allocate a Media Device when multiple
drivers share usb_device and the media device. This interface allocates
[`media_device`](#c-struct-media_device) structure and calls [`media_device_usb_init()`](#c-media_device_usb_init) to initialize
it.

#### <a id="c-media_device_delete"></a>`media_device_delete()`

```c
void media_device_delete(struct media_device *mdev, const char *module_name, struct module *owner)
```

Release media device. Calls [`kref_put()`](/kernel/internals/core-api/kref.md#c-kref_put).

**Parameters**

- `struct media_device *mdev`: struct [`media_device`](#c-struct-media_device) pointer
- `const char *module_name`: should be filled with `KBUILD_MODNAME`
- `struct module *owner`: struct module pointer `THIS_MODULE` for the driver.
  `THIS_MODULE` is null for a built-in driver.
  It is safe even when `THIS_MODULE` is null.

**Description**

This interface should be called to put Media Device Instance kref.

---

# Remote Controller devices

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> The remote controller core implements infrastructure to receive and send remote controller keyboard keystrokes and mouse events.

<a id="rst-remote-controller-devices"></a>

<a id="rst-remote-controller-core"></a>

## Remote Controller core

<!-- SPDX-License-Identifier: GPL-2.0 -->

The remote controller core implements infrastructure to receive and send remote controller keyboard keystrokes and mouse events.

Every time a key is pressed on a remote controller, a scan code is produced. Also, on most hardware, keeping a key pressed for more than a few dozens of milliseconds produce a repeat key event. That's somewhat similar to what a normal keyboard or mouse is handled internally on Linux<a id="rst-footnote-reference-1"></a>[1](#rst-f1). So, the remote controller core is implemented on the top of the linux input/evdev interface.

<a id="rst-f1"></a>



**[1]** The main difference is that, on keyboard events, the keyboard controller produces one event for a key press and another one for key release. On infrared-based remote controllers, there's no key release event. Instead, an extra code is produced to indicate key repeats.

However, most of the remote controllers use infrared (IR) to transmit signals. As there are several protocols used to modulate infrared signals, one important part of the core is dedicated to adjust the driver and the core system to support the infrared protocol used by the emitter.

The infrared transmission is done by blinking a infrared emitter using a carrier. The carrier can be switched on or off by the IR transmitter hardware. When the carrier is switched on, it is called *PULSE*. When the carrier is switched off, it is called *SPACE*.

In other words, a typical IR transmission can be viewed as a sequence of *PULSE* and *SPACE* events, each with a given duration.

The carrier parameters (frequency, duty cycle) and the intervals for *PULSE* and *SPACE* events depend on the protocol. For example, the NEC protocol uses a carrier of 38kHz, and transmissions start with a 9ms *PULSE* and a 4.5ms SPACE. It then transmits 16 bits of scan code, being 8 bits for address (usually it is a fixed number for a given remote controller), followed by 8 bits of code. A bit "1" is modulated with 560µs *PULSE* followed by 1690µs *SPACE* and a bit "0"  is modulated with 560µs *PULSE* followed by 560µs *SPACE*.

At receiver, a simple low-pass filter can be used to convert the received signal in a sequence of *PULSE/SPACE* events, filtering out the carrier frequency. Due to that, the receiver doesn't care about the carrier's actual frequency parameters: all it has to do is to measure the amount of time it receives *PULSE/SPACE* events. So, a simple IR receiver hardware will just provide a sequence of timings for those events to the Kernel. The drivers for hardware with such kind of receivers are identified by  `RC_DRIVER_IR_RAW`, as defined by `rc_driver_type`<a id="rst-footnote-reference-2"></a>[2](#rst-f2). Other hardware come with a microcontroller that decode the *PULSE/SPACE* sequence and return scan codes to the Kernel. Such kind of receivers are identified by `RC_DRIVER_SCANCODE`.

<a id="rst-f2"></a>



**[2]** The RC core also supports devices that have just IR emitters, without any receivers. Right now, all such devices work only in raw TX mode. Such kind of hardware is identified as `RC_DRIVER_IR_RAW_TX`.

When the RC core receives events produced by `RC_DRIVER_IR_RAW` IR receivers, it needs to decode the IR protocol, in order to obtain the corresponding scan code. The protocols supported by the RC core are defined at enum `rc_proto`.

When the RC code receives a scan code (either directly, by a driver of the type `RC_DRIVER_SCANCODE`, or via its IR decoders), it needs to convert into a Linux input event code. This is done via a mapping table.

The Kernel has support for mapping tables available on most media devices. It also supports loading a table in runtime, via some sysfs nodes. See the [RC userspace API](</kernel/userspace/userspace-api/media-rc/rc-intro.md#rst-remote-controllers-intro>) for more details.

<a id="rst-remote-controller-data-structures-and-functions"></a>

## Remote controller data structures and functions


#### <a id="c-enum-rc_driver_type"></a>`enum rc_driver_type`

type of the RC driver.

**Constants**

- `RC_DRIVER_SCANCODE`: Driver or hardware generates a scancode.
- `RC_DRIVER_IR_RAW`: Driver or hardware generates pulse/space sequences.
  It needs a Infra-Red pulse/space decoder
- `RC_DRIVER_IR_RAW_TX`: Device transmitter only,
  driver requires pulse/space data sequence.

#### <a id="c-struct-rc_scancode_filter"></a>`struct rc_scancode_filter`

Filter scan codes.

**Definition**

```c
struct rc_scancode_filter {
    u32 data;
    u32 mask;
};
```

**Members**

- `data`: Scancode data to match.
- `mask`: Mask of bits of scancode to compare.

#### <a id="c-enum-rc_filter_type"></a>`enum rc_filter_type`

Filter type constants.

**Constants**

- `RC_FILTER_NORMAL`: Filter for normal operation.
- `RC_FILTER_WAKEUP`: Filter for waking from suspend.
- `RC_FILTER_MAX`: Number of filter types.

#### <a id="c-struct-lirc_fh"></a>`struct lirc_fh`

represents an open lirc file

**Definition**

```c
struct lirc_fh {
    struct list_head list;
    struct rc_dev *rc;
    unsigned int *rawir;
    struct lirc_scancode *scancodes;
    wait_queue_head_t wait_poll;
    u32 carrier_low;
    u8 send_mode;
    u8 rec_mode;
};
```

**Members**

- `list`: list of open file handles
- `rc`: rcdev for this lirc chardev
- `rawir`: queue for incoming raw IR
- `scancodes`: queue for incoming decoded scancodes
- `wait_poll`: poll struct for lirc device
- `carrier_low`: when setting the carrier range, first the low end must be
  set with an ioctl and then the high end with another ioctl
- `send_mode`: lirc mode for sending, either LIRC_MODE_SCANCODE or
  LIRC_MODE_PULSE
- `rec_mode`: lirc mode for receiving, either LIRC_MODE_SCANCODE or
  LIRC_MODE_MODE2

#### <a id="c-struct-rc_dev"></a>`struct rc_dev`

represents a remote control device

**Definition**

```c
struct rc_dev {
        struct device                   dev;
        bool managed_alloc;
        bool registered;
        bool idle;
        bool encode_wakeup;
        unsigned int                    minor;
        const struct attribute_group    *sysfs_groups[5];
        const char                      *device_name;
        const char                      *input_phys;
        struct input_id                 input_id;
        const char                      *driver_name;
        const char                      *map_name;
        struct rc_map                   rc_map;
        struct mutex                    lock;
        struct ir_raw_event_ctrl        *raw;
        struct input_dev                *input_dev;
        enum rc_driver_type             driver_type;
        u32 users;
        u64 allowed_protocols;
        u64 enabled_protocols;
        u64 allowed_wakeup_protocols;
        enum rc_proto                   wakeup_protocol;
        struct rc_scancode_filter       scancode_filter;
        struct rc_scancode_filter       scancode_wakeup_filter;
        u32 scancode_mask;
        void *priv;
        spinlock_t keylock;
        bool keypressed;
        u8 last_toggle;
        u32 last_keycode;
        enum rc_proto                   last_protocol;
        u64 last_scancode;
        unsigned long                   keyup_jiffies;
        struct timer_list               timer_keyup;
        struct timer_list               timer_repeat;
        u32 timeout;
        u32 min_timeout;
        u32 max_timeout;
        u32 rx_resolution;
    #ifdef CONFIG_LIRC;
        struct device                   lirc_dev;
        struct cdev                     lirc_cdev;
        ktime_t gap_start;
        spinlock_t lirc_fh_lock;
        struct list_head                lirc_fh;
    #endif;
        int (*change_protocol)(struct rc_dev *dev, u64 *rc_proto);
        int (*open)(struct rc_dev *dev);
        void (*close)(struct rc_dev *dev);
        int (*s_tx_mask)(struct rc_dev *dev, u32 mask);
        int (*s_tx_carrier)(struct rc_dev *dev, u32 carrier);
        int (*s_tx_duty_cycle)(struct rc_dev *dev, u32 duty_cycle);
        int (*s_rx_carrier_range)(struct rc_dev *dev, u32 min, u32 max);
        int (*tx_ir)(struct rc_dev *dev, unsigned *txbuf, unsigned n);
        void (*s_idle)(struct rc_dev *dev, bool enable);
        int (*s_wideband_receiver)(struct rc_dev *dev, int enable);
        int (*s_carrier_report) (struct rc_dev *dev, int enable);
        int (*s_filter)(struct rc_dev *dev, struct rc_scancode_filter *filter);
        int (*s_wakeup_filter)(struct rc_dev *dev, struct rc_scancode_filter *filter);
        int (*s_timeout)(struct rc_dev *dev, unsigned int timeout);
};
```

**Members**

- `dev`: driver model's view of this device
- `managed_alloc`: devm_rc_allocate_device was used to create rc_dev
- `registered`: set to true by [`rc_register_device()`](#c-rc_register_device), false by
  rc_unregister_device
- `idle`: used to keep track of RX state
- `encode_wakeup`: wakeup filtering uses IR encode API, therefore the allowed
  wakeup protocols is the set of all raw encoders
- `minor`: unique minor remote control device number
- `sysfs_groups`: sysfs attribute groups
- `device_name`: name of the rc child device
- `input_phys`: physical path to the input child device
- `input_id`: id of the input child device (struct input_id)
- `driver_name`: name of the hardware driver which registered this device
- `map_name`: name of the default keymap
- `rc_map`: current scan/key table
- `lock`: used to ensure we've filled in all protocol details before
  anyone can call show_protocols or store_protocols
- `raw`: additional data for raw pulse/space devices
- `input_dev`: the input child device used to communicate events to userspace
- `driver_type`: specifies if protocol decoding is done in hardware or software
- `users`: number of current users of the device
- `allowed_protocols`: bitmask with the supported RC_PROTO_BIT_* protocols
- `enabled_protocols`: bitmask with the enabled RC_PROTO_BIT_* protocols
- `allowed_wakeup_protocols`: bitmask with the supported RC_PROTO_BIT_* wakeup
  protocols
- `wakeup_protocol`: the enabled RC_PROTO_* wakeup protocol or
  RC_PROTO_UNKNOWN if disabled.
- `scancode_filter`: scancode filter
- `scancode_wakeup_filter`: scancode wakeup filters
- `scancode_mask`: some hardware decoders are not capable of providing the full
  scancode to the application. As this is a hardware limit, we can't do
  anything with it. Yet, as the same keycode table can be used with other
  devices, a mask is provided to allow its usage. Drivers should generally
  leave this field in blank
- `priv`: driver-specific data
- `keylock`: protects the remaining members of the struct
- `keypressed`: whether a key is currently pressed
- `last_toggle`: toggle value of last command
- `last_keycode`: keycode of last keypress
- `last_protocol`: protocol of last keypress
- `last_scancode`: scancode of last keypress
- `keyup_jiffies`: time (in jiffies) when the current keypress should be released
- `timer_keyup`: timer for releasing a keypress
- `timer_repeat`: timer for autorepeat events. This is needed for CEC, which
  has non-standard repeats.
- `timeout`: optional time after which device stops sending data
- `min_timeout`: minimum timeout supported by device
- `max_timeout`: maximum timeout supported by device
- `rx_resolution`: resolution (in us) of input sampler
- `lirc_dev`: lirc device
- `lirc_cdev`: lirc char cdev
- `gap_start`: start time for gap after timeout if non-zero
- `lirc_fh_lock`: protects lirc_fh list
- `lirc_fh`: list of open files
- `change_protocol`: allow changing the protocol used on hardware decoders
- `open`: callback to allow drivers to enable polling/irq when IR input device
  is opened.
- `close`: callback to allow drivers to disable polling/irq when IR input device
  is opened.
- `s_tx_mask`: set transmitter mask (for devices with multiple tx outputs)
- `s_tx_carrier`: set transmit carrier frequency
- `s_tx_duty_cycle`: set transmit duty cycle (0% - 100%)
- `s_rx_carrier_range`: inform driver about carrier it is expected to handle
- `tx_ir`: transmit IR
- `s_idle`: enable/disable hardware idle mode, upon which,
  device doesn't interrupt host until it sees IR pulses
- `s_wideband_receiver`: enable wide band receiver used for learning
- `s_carrier_report`: enable carrier reports
- `s_filter`: set the scancode filter
- `s_wakeup_filter`: set the wakeup scancode filter. If the mask is zero
  then wakeup should be disabled. wakeup_protocol will be set to
  a valid protocol if mask is nonzero.
- `s_timeout`: set hardware timeout in us

#### <a id="c-rc_allocate_device"></a>`rc_allocate_device()`

```c
struct rc_dev * rc_allocate_device(enum rc_driver_type)
```

Allocates a RC device

**Parameters**

- `enum rc_driver_type`: specifies the type of the RC output to be allocated
  returns a pointer to struct rc_dev.

#### <a id="c-devm_rc_allocate_device"></a>`devm_rc_allocate_device()`

```c
struct rc_dev * devm_rc_allocate_device(struct device *dev, enum rc_driver_type)
```

Managed RC device allocation

**Parameters**

- `struct device *dev`: pointer to struct device
- `enum rc_driver_type`: specifies the type of the RC output to be allocated
  returns a pointer to struct rc_dev.

#### <a id="c-rc_free_device"></a>`rc_free_device()`

```c
void rc_free_device(struct rc_dev *dev)
```

Frees a RC device

**Parameters**

- `struct rc_dev *dev`: pointer to struct rc_dev.

#### <a id="c-rc_register_device"></a>`rc_register_device()`

```c
int rc_register_device(struct rc_dev *dev)
```

Registers a RC device

**Parameters**

- `struct rc_dev *dev`: pointer to struct rc_dev.

#### <a id="c-devm_rc_register_device"></a>`devm_rc_register_device()`

```c
int devm_rc_register_device(struct device *parent, struct rc_dev *dev)
```

Manageded registering of a RC device

**Parameters**

- `struct device *parent`: pointer to struct device.
- `struct rc_dev *dev`: pointer to struct rc_dev.

#### <a id="c-rc_unregister_device"></a>`rc_unregister_device()`

```c
void rc_unregister_device(struct rc_dev *dev)
```

Unregisters a RC device

**Parameters**

- `struct rc_dev *dev`: pointer to struct rc_dev.



#### <a id="c-struct-rc_map_table"></a>`struct rc_map_table`

represents a scancode/keycode pair

**Definition**

```c
struct rc_map_table {
    u64 scancode;
    u32 keycode;
};
```

**Members**

- `scancode`: scan code (u64)
- `keycode`: Linux input keycode

#### <a id="c-struct-rc_map"></a>`struct rc_map`

represents a keycode map table

**Definition**

```c
struct rc_map {
    struct rc_map_table     *scan;
    unsigned int            size;
    unsigned int            len;
    unsigned int            alloc;
    enum rc_proto           rc_proto;
    const char              *name;
    spinlock_t lock;
};
```

**Members**

- `scan`: pointer to struct [`rc_map_table`](#c-struct-rc_map_table)
- `size`: Max number of entries
- `len`: Number of entries that are in use
- `alloc`: size of \*scan, in bytes
- `rc_proto`: type of the remote controller protocol, as defined at
  enum [`rc_proto`](/kernel/userspace/userspace-api/media-rc/lirc-dev-intro.md#c-enum-rc_proto)
- `name`: name of the key map table
- `lock`: lock to protect access to this structure

#### <a id="c-struct-rc_map_list"></a>`struct rc_map_list`

list of the registered [`rc_map`](#c-struct-rc_map) maps

**Definition**

```c
struct rc_map_list {
    struct list_head         list;
    struct rc_map map;
};
```

**Members**

- `list`: pointer to struct `list_head`
- `map`: pointer to struct [`rc_map`](#c-struct-rc_map)

#### <a id="c-rc_map_register"></a>`rc_map_register()`

```c
int rc_map_register(struct rc_map_list *map)
```

Registers a Remote Controller scancode map

**Parameters**

- `struct rc_map_list *map`: pointer to struct rc_map_list

#### <a id="c-rc_map_unregister"></a>`rc_map_unregister()`

```c
void rc_map_unregister(struct rc_map_list *map)
```

Unregisters a Remote Controller scancode map

**Parameters**

- `struct rc_map_list *map`: pointer to struct rc_map_list

#### <a id="c-rc_map_get"></a>`rc_map_get()`

```c
struct rc_map * rc_map_get(const char *name)
```

gets an RC map from its name

**Parameters**

- `const char *name`: name of the RC scancode map

---

# Pixel data transmitter and receiver drivers

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> V4L2 supports various devices that transmit and receive pixel data. Examples of these devices include a camera sensor, a TV tuner and a parallel, a BT.656 or a CSI-2 receiver in an SoC.

<a id="rst-pixel-data-transmitter-and-receiver-drivers"></a>
<a id="rst-transmitter-receiver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

V4L2 supports various devices that transmit and receive pixel data. Examples of these devices include a camera sensor, a TV tuner and a parallel, a BT.656 or a CSI-2 receiver in an SoC.

<a id="rst-bus-types"></a>

## Bus types

The following buses are the most common. This section discusses these two only.

<a id="rst-mipi-csi-2"></a>

### MIPI CSI-2

CSI-2 is a data bus intended for transferring images from cameras to the host SoC. It is defined by the [MIPI alliance](<https://www.mipi.org/>).

<a id="rst-mipi-alliance"></a>



<a id="rst-parallel-and-bt-656"></a>

### Parallel and BT.656

The parallel and [BT.656](<https://en.wikipedia.org/wiki/ITU-R_BT.656>) buses transport one bit of data on each clock cycle per data line. The parallel bus uses synchronisation and other additional signals whereas BT.656 embeds synchronisation.

<a id="rst-bt-656"></a>



<a id="rst-transmitter-drivers"></a>

## Transmitter drivers

Transmitter drivers generally need to provide the receiver drivers with the configuration of the transmitter. What is required depends on the type of the bus. These are common for both buses.

<a id="rst-media-bus-pixel-code"></a>

### Media bus pixel code

See [v4l2-mbus-pixelcode](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/userspace-api/media/v4l/subdev-formats.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>).

<a id="rst-link-frequency"></a>

### Link frequency

The [V4L2_CID_LINK_FREQ](</kernel/userspace/userspace-api/media-v4l/ext-ctrls-image-process.md#rst-v4l2-cid-link-freq>) control is used to tell the receiver the frequency of the bus (i.e. it is not the same as the symbol rate).

Drivers that do not have user-configurable link frequency should report it through the `.get_mbus_config()` subdev pad operation, in the `link_freq` field of struct v4l2_mbus_config, instead of through controls.

Receiver drivers should use `v4l2_get_link_freq()` helper to obtain the link frequency from the transmitter sub-device.

<a id="rst-enable-streams-and-disable-streams-callbacks"></a>

### `.enable_streams()` and `.disable_streams()` callbacks

The struct v4l2_subdev_pad_ops-&gt;enable_streams() and struct v4l2_subdev_pad_ops-&gt;disable_streams() callbacks are used by the receiver driver to control the transmitter driver's streaming state. These callbacks may not be called directly, but by using `v4l2_subdev_enable_streams()` and `v4l2_subdev_disable_streams()`.

<a id="rst-stopping-the-transmitter"></a>

### Stopping the transmitter

A transmitter stops sending the stream of images as a result of calling the `.disable_streams()` callback. Some transmitters may stop the stream at a frame boundary whereas others stop immediately, effectively leaving the current frame unfinished. The receiver driver should not make assumptions either way, but function properly in both cases.

<a id="rst-csi-2-transmitter-drivers"></a>

## CSI-2 transmitter drivers

<a id="rst-pixel-rate"></a>

### Pixel rate

The pixel rate on the bus is calculated as follows:



```text
pixel_rate = link_freq * 2 * nr_of_lanes * 16 / k / bits_per_sample
```

where


<table>
<caption>variables in pixel rate calculation</caption>
<thead>
<tr>
<th>


variable or constant

</th>
<th>


description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


link_freq

</td>
<td>


The value of the `V4L2_CID_LINK_FREQ` integer64 menu item.

</td>
</tr>
<tr>
<td>


nr_of_lanes

</td>
<td>


Number of data lanes used on the CSI-2 link.

</td>
</tr>
<tr>
<td>


2

</td>
<td>


Data is transferred on both rising and falling edge of the signal.

</td>
</tr>
<tr>
<td>


bits_per_sample

</td>
<td>


Number of bits per sample.

</td>
</tr>
<tr>
<td>


k

</td>
<td>


16 for D-PHY and 7 for C-PHY.

</td>
</tr>
</tbody>
</table>

Information on whether D-PHY or C-PHY is used, and the value of `nr_of_lanes`, can be obtained from the OF endpoint configuration.

> [!NOTE]
>
> The pixel rate calculated this way is **not** the same thing as the pixel rate on the camera sensor's pixel array which is indicated by the [V4L2_CID_PIXEL_RATE](</kernel/userspace/userspace-api/media-v4l/ext-ctrls-image-process.md#rst-v4l2-cid-pixel-rate>) control.

<a id="rst-lp-11-and-lp-111-states"></a>

### LP-11 and LP-111 states

As part of transitioning to high speed mode, a CSI-2 transmitter typically briefly sets the bus to LP-11 or LP-111 state, depending on the PHY. This period may be as short as 100 µs, during which the receiver observes this state and proceeds its own part of high speed mode transition.

Most receivers are capable of autonomously handling this once the software has configured them to do so, but there are receivers which require software involvement in observing LP-11 or LP-111 state. 100 µs is a brief period to hit in software, especially when there is no interrupt telling something is happening.

One way to address this is to configure the transmitter side explicitly to LP-11 or LP-111 state, which requires support from the transmitter hardware. This is not universally available. Many devices return to this state once streaming is stopped while the state after power-on is LP-00 or LP-000.

The `.pre_streamon()` callback may be used to prepare a transmitter for transitioning to streaming state, but not yet start streaming. Similarly, the `.post_streamoff()` callback is used to undo what was done by the `.pre_streamon()` callback. The caller of `.pre_streamon()` is thus required to call `.post_streamoff()` for each successful call of `.pre_streamon()`.

In the context of CSI-2, the `.pre_streamon()` callback is used to transition the transmitter to the LP-11 or LP-111 state. This also requires powering on the device, so this should be only done when it is needed.

Receiver drivers that do not need explicit LP-11 or LP-111 state setup are waived from calling the two callbacks.

---

# V4L2 async kAPI

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for V4L2 async kAPI.

<a id="rst-v4l2-async-kapi"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-enum-v4l2_async_match_type"></a>`enum v4l2_async_match_type`

type of asynchronous subdevice logic to be used in order to identify a match

**Constants**

- `V4L2_ASYNC_MATCH_TYPE_I2C`: Match will check for I2C adapter ID and address
- `V4L2_ASYNC_MATCH_TYPE_FWNODE`: Match will use firmware node

**Description**

This enum is used by the asynchronous connection logic to define the
algorithm that will be used to match an asynchronous device.

#### <a id="c-struct-v4l2_async_match_desc"></a>`struct v4l2_async_match_desc`

async connection match information

**Definition**

```c
struct v4l2_async_match_desc {
    enum v4l2_async_match_type type;
    union {
        struct fwnode_handle *fwnode;
        struct {
            int adapter_id;
            unsigned short address;
        } i2c;
    };
};
```

**Members**

- `type`: type of match that will be used
- `{unnamed_union}`: anonymous
- `fwnode`: pointer to `struct fwnode_handle` to be matched.
  Used if **match_type** is `V4L2_ASYNC_MATCH_TYPE_FWNODE`.
- `i2c`: embedded struct with I2C parameters to be matched.
  Both **match.i2c.adapter_id** and **match.i2c.address**
  should be matched.
  Used if **match_type** is `V4L2_ASYNC_MATCH_TYPE_I2C`.
- `i2c.adapter_id`: I2C adapter ID to be matched.
  Used if **match_type** is `V4L2_ASYNC_MATCH_TYPE_I2C`.
- `i2c.address`: I2C address to be matched.
  Used if **match_type** is `V4L2_ASYNC_MATCH_TYPE_I2C`.

#### <a id="c-struct-v4l2_async_connection"></a>`struct v4l2_async_connection`

sub-device connection descriptor, as known to a bridge

**Definition**

```c
struct v4l2_async_connection {
    struct v4l2_async_match_desc match;
    struct v4l2_async_notifier *notifier;
    struct list_head asc_entry;
    struct list_head asc_subdev_entry;
    struct v4l2_subdev *sd;
};
```

**Members**

- `match`: struct of match type and per-bus type matching data sets
- `notifier`: the async notifier the connection is related to
- `asc_entry`: used to add struct v4l2_async_connection objects to the
  notifier **waiting_list** or **done_list**
- `asc_subdev_entry`: entry in struct v4l2_async_subdev.asc_list list
- `sd`: the related sub-device

**Description**

When this struct is used as a member in a driver specific struct, the driver
specific struct shall contain the [`struct v4l2_async_connection`](#c-struct-v4l2_async_connection) as its first
member.

#### <a id="c-struct-v4l2_async_notifier_operations"></a>`struct v4l2_async_notifier_operations`

Asynchronous V4L2 notifier operations

**Definition**

```c
struct v4l2_async_notifier_operations {
    int (*bound)(struct v4l2_async_notifier *notifier, struct v4l2_subdev *subdev, struct v4l2_async_connection *asc);
    int (*complete)(struct v4l2_async_notifier *notifier);
    void (*unbind)(struct v4l2_async_notifier *notifier, struct v4l2_subdev *subdev, struct v4l2_async_connection *asc);
    void (*destroy)(struct v4l2_async_connection *asc);
};
```

**Members**

- `bound`: a sub-device has been bound by the given connection
- `complete`: All connections have been bound successfully. The complete
  callback is only executed for the root notifier.
- `unbind`: a subdevice is leaving
- `destroy`: the asc is about to be freed

#### <a id="c-struct-v4l2_async_notifier"></a>`struct v4l2_async_notifier`

v4l2_device notifier data

**Definition**

```c
struct v4l2_async_notifier {
    const struct v4l2_async_notifier_operations *ops;
    struct v4l2_device *v4l2_dev;
    struct v4l2_subdev *sd;
    struct v4l2_async_notifier *parent;
    struct list_head waiting_list;
    struct list_head done_list;
    struct list_head notifier_entry;
};
```

**Members**

- `ops`: notifier operations
- `v4l2_dev`: v4l2_device of the root notifier, NULL otherwise
- `sd`: sub-device that registered the notifier, NULL otherwise
- `parent`: parent notifier
- `waiting_list`: list of struct v4l2_async_connection, waiting for their
  drivers
- `done_list`: list of struct v4l2_subdev, already probed
- `notifier_entry`: member in a global list of notifiers

#### <a id="c-struct-v4l2_async_subdev_endpoint"></a>`struct v4l2_async_subdev_endpoint`

Entry in sub-device's fwnode list

**Definition**

```c
struct v4l2_async_subdev_endpoint {
    struct list_head async_subdev_endpoint_entry;
    struct fwnode_handle *endpoint;
};
```

**Members**

- `async_subdev_endpoint_entry`: An entry in async_subdev_endpoint_list of
  [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)
- `endpoint`: Endpoint fwnode agains which to match the sub-device

#### <a id="c-v4l2_async_debug_init"></a>`v4l2_async_debug_init()`

```c
void v4l2_async_debug_init(struct dentry *debugfs_dir)
```

Initialize debugging tools.

**Parameters**

- `struct dentry *debugfs_dir`: pointer to the parent debugfs `struct dentry`

#### <a id="c-v4l2_async_nf_init"></a>`v4l2_async_nf_init()`

```c
void v4l2_async_nf_init(struct v4l2_async_notifier *notifier, struct v4l2_device *v4l2_dev)
```

Initialize a notifier.

**Parameters**

- `struct v4l2_async_notifier *notifier`: pointer to [`struct v4l2_async_notifier`](#c-struct-v4l2_async_notifier)
- `struct v4l2_device *v4l2_dev`: pointer to [`struct v4l2_device`](/kernel/hardware/driver-api/media/v4l2-device.md#c-struct-v4l2_device)

**Description**

This function initializes the notifier **asc_entry**. It must be called
before adding a subdevice to a notifier, using one of:
[`v4l2_async_nf_add_fwnode_remote()`](#c-v4l2_async_nf_add_fwnode_remote),
[`v4l2_async_nf_add_fwnode()`](#c-v4l2_async_nf_add_fwnode) or
[`v4l2_async_nf_add_i2c()`](#c-v4l2_async_nf_add_i2c).

#### <a id="c-v4l2_async_subdev_nf_init"></a>`v4l2_async_subdev_nf_init()`

```c
void v4l2_async_subdev_nf_init(struct v4l2_async_notifier *notifier, struct v4l2_subdev *sd)
```

Initialize a sub-device notifier.

**Parameters**

- `struct v4l2_async_notifier *notifier`: pointer to [`struct v4l2_async_notifier`](#c-struct-v4l2_async_notifier)
- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)

**Description**

This function initializes the notifier **asc_list**. It must be called
before adding a subdevice to a notifier, using one of:
[`v4l2_async_nf_add_fwnode_remote()`](#c-v4l2_async_nf_add_fwnode_remote), [`v4l2_async_nf_add_fwnode()`](#c-v4l2_async_nf_add_fwnode) or
[`v4l2_async_nf_add_i2c()`](#c-v4l2_async_nf_add_i2c).

#### <a id="c-v4l2_async_nf_add_fwnode"></a>`v4l2_async_nf_add_fwnode()`

```c
v4l2_async_nf_add_fwnode(notifier, fwnode, type)
```

Allocate and add a fwnode async subdev to the notifier's master asc_list.

**Parameters**

- `notifier`: pointer to [`struct v4l2_async_notifier`](#c-struct-v4l2_async_notifier)
- `fwnode`: fwnode handle of the sub-device to be matched, pointer to
  `struct fwnode_handle`
- `type`: Type of the driver's async sub-device or connection struct. The
  [`struct v4l2_async_connection`](#c-struct-v4l2_async_connection) shall be the first member of the
  driver's async struct, i.e. both begin at the same memory address.

**Description**

Allocate a fwnode-matched asc of size asc_struct_size, and add it to the
notifiers **asc_list**. The function also gets a reference of the fwnode which
is released later at notifier cleanup time.

#### <a id="c-v4l2_async_nf_add_fwnode_remote"></a>`v4l2_async_nf_add_fwnode_remote()`

```c
v4l2_async_nf_add_fwnode_remote(notifier, ep, type)
```

Allocate and add a fwnode remote async subdev to the notifier's master asc_list.

**Parameters**

- `notifier`: pointer to [`struct v4l2_async_notifier`](#c-struct-v4l2_async_notifier)
- `ep`: local endpoint pointing to the remote connection to be matched,
  pointer to `struct fwnode_handle`
- `type`: Type of the driver's async connection struct. The [`struct v4l2_async_connection`](#c-struct-v4l2_async_connection) shall be the first member of the driver's async
  connection struct, i.e. both begin at the same memory address.

**Description**

Gets the remote endpoint of a given local endpoint, set it up for fwnode
matching and adds the async connection to the notifier's **asc_list**. The
function also gets a reference of the fwnode which is released later at
notifier cleanup time.

This is just like [`v4l2_async_nf_add_fwnode()`](#c-v4l2_async_nf_add_fwnode), but with the
exception that the fwnode refers to a local endpoint, not the remote one.

#### <a id="c-v4l2_async_nf_add_i2c"></a>`v4l2_async_nf_add_i2c()`

```c
v4l2_async_nf_add_i2c(notifier, adapter, address, type)
```

Allocate and add an i2c async subdev to the notifier's master asc_list.

**Parameters**

- `notifier`: pointer to [`struct v4l2_async_notifier`](#c-struct-v4l2_async_notifier)
- `adapter`: I2C adapter ID to be matched
- `address`: I2C address of connection to be matched
- `type`: Type of the driver's async connection struct. The [`struct v4l2_async_connection`](#c-struct-v4l2_async_connection) shall be the first member of the driver's async
  connection struct, i.e. both begin at the same memory address.

**Description**

Same as [`v4l2_async_nf_add_fwnode()`](#c-v4l2_async_nf_add_fwnode) but for I2C matched
connections.

#### <a id="c-v4l2_async_subdev_endpoint_add"></a>`v4l2_async_subdev_endpoint_add()`

```c
int v4l2_async_subdev_endpoint_add(struct v4l2_subdev *sd, struct fwnode_handle *fwnode)
```

Add an endpoint fwnode to async sub-device matching list

**Parameters**

- `struct v4l2_subdev *sd`: the sub-device
- `struct fwnode_handle *fwnode`: the endpoint fwnode to match

**Description**

Add a fwnode to the async sub-device's matching list. This allows registering
multiple async sub-devices from a single device.

Note that calling [`v4l2_subdev_cleanup()`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-v4l2_subdev_cleanup) as part of the sub-device's cleanup
if endpoints have been added to the sub-device's fwnode matching list.

Returns an error on failure, 0 on success.

#### <a id="c-v4l2_async_connection_unique"></a>`v4l2_async_connection_unique()`

```c
struct v4l2_async_connection * v4l2_async_connection_unique(struct v4l2_subdev *sd)
```

return a unique [`struct v4l2_async_connection`](#c-struct-v4l2_async_connection) for a sub-device

**Parameters**

- `struct v4l2_subdev *sd`: the sub-device

**Description**

Return an async connection for a sub-device, when there is a single
one only.

#### <a id="c-v4l2_async_nf_register"></a>`v4l2_async_nf_register()`

```c
int v4l2_async_nf_register(struct v4l2_async_notifier *notifier)
```

registers a subdevice asynchronous notifier

**Parameters**

- `struct v4l2_async_notifier *notifier`: pointer to [`struct v4l2_async_notifier`](#c-struct-v4l2_async_notifier)

#### <a id="c-v4l2_async_nf_unregister"></a>`v4l2_async_nf_unregister()`

```c
void v4l2_async_nf_unregister(struct v4l2_async_notifier *notifier)
```

unregisters a subdevice asynchronous notifier

**Parameters**

- `struct v4l2_async_notifier *notifier`: pointer to [`struct v4l2_async_notifier`](#c-struct-v4l2_async_notifier)

#### <a id="c-v4l2_async_nf_cleanup"></a>`v4l2_async_nf_cleanup()`

```c
void v4l2_async_nf_cleanup(struct v4l2_async_notifier *notifier)
```

clean up notifier resources

**Parameters**

- `struct v4l2_async_notifier *notifier`: the notifier the resources of which are to be cleaned up

**Description**

Release memory resources related to a notifier, including the async
connections allocated for the purposes of the notifier but not the notifier
itself. The user is responsible for calling this function to clean up the
notifier after calling [`v4l2_async_nf_add_fwnode_remote()`](#c-v4l2_async_nf_add_fwnode_remote),
[`v4l2_async_nf_add_fwnode()`](#c-v4l2_async_nf_add_fwnode) or [`v4l2_async_nf_add_i2c()`](#c-v4l2_async_nf_add_i2c).

There is no harm from calling [`v4l2_async_nf_cleanup()`](#c-v4l2_async_nf_cleanup) in other
cases as long as its memory has been zeroed after it has been
allocated.

#### <a id="c-v4l2_async_register_subdev"></a>`v4l2_async_register_subdev()`

```c
v4l2_async_register_subdev(sd)
```

registers a sub-device to the asynchronous subdevice framework

**Parameters**

- `sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)

#### <a id="c-v4l2_async_register_subdev_sensor"></a>`v4l2_async_register_subdev_sensor()`

```c
int v4l2_async_register_subdev_sensor(struct v4l2_subdev *sd)
```

registers a sensor sub-device to the asynchronous sub-device framework and parse set up common sensor related devices

**Parameters**

- `struct v4l2_subdev *sd`: pointer to struct [`v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)

**Description**

This function is just like [`v4l2_async_register_subdev()`](#c-v4l2_async_register_subdev) with the exception
that calling it will also parse firmware interfaces for remote references
using `v4l2_async_nf_parse_fwnode_sensor()` and registers the
async sub-devices. The sub-device is similarly unregistered by calling
[`v4l2_async_unregister_subdev()`](#c-v4l2_async_unregister_subdev).

While registered, the subdev module is marked as in-use.

An error is returned if the module is no longer loaded on any attempts
to register it.

#### <a id="c-v4l2_async_unregister_subdev"></a>`v4l2_async_unregister_subdev()`

```c
void v4l2_async_unregister_subdev(struct v4l2_subdev *sd)
```

unregisters a sub-device to the asynchronous subdevice framework

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)

---

# V4L2 CCI kAPI

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for V4L2 CCI kAPI.

<a id="rst-v4l2-cci-kapi"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-struct-cci_reg_sequence"></a>`struct cci_reg_sequence`

An individual write from a sequence of CCI writes

**Definition**

```c
struct cci_reg_sequence {
    u32 reg;
    u64 val;
};
```

**Members**

- `reg`: Register address, use CCI_REG#() macros to encode reg width
- `val`: Register value

**Description**

Register/value pairs for sequences of writes.

#### <a id="c-cci_read"></a>`cci_read()`

```c
int cci_read(struct regmap *map, u32 reg, u64 *val, int *err)
```

Read a value from a single CCI register

**Parameters**

- `struct regmap *map`: Register map to read from
- `u32 reg`: Register address to read, use CCI_REG#() macros to encode reg width
- `u64 *val`: Pointer to store read value
- `int *err`: Optional pointer to store errors, if a previous error is set
  then the read will be skipped

**Return**

`0` on success or a negative error code on failure.

#### <a id="c-cci_write"></a>`cci_write()`

```c
int cci_write(struct regmap *map, u32 reg, u64 val, int *err)
```

Write a value to a single CCI register

**Parameters**

- `struct regmap *map`: Register map to write to
- `u32 reg`: Register address to write, use CCI_REG#() macros to encode reg width
- `u64 val`: Value to be written
- `int *err`: Optional pointer to store errors, if a previous error is set
  then the write will be skipped

**Return**

`0` on success or a negative error code on failure.

#### <a id="c-cci_update_bits"></a>`cci_update_bits()`

```c
int cci_update_bits(struct regmap *map, u32 reg, u64 mask, u64 val, int *err)
```

Perform a read/modify/write cycle on a single CCI register

**Parameters**

- `struct regmap *map`: Register map to update
- `u32 reg`: Register address to update, use CCI_REG#() macros to encode reg width
- `u64 mask`: Bitmask to change
- `u64 val`: New value for bitmask
- `int *err`: Optional pointer to store errors, if a previous error is set
  then the update will be skipped

**Description**

Note this uses read-modify-write to update the bits, atomicity with regards
to other cci_*() register access functions is NOT guaranteed.

**Return**

`0` on success or a negative error code on failure.

#### <a id="c-cci_multi_reg_write"></a>`cci_multi_reg_write()`

```c
int cci_multi_reg_write(struct regmap *map, const struct cci_reg_sequence *regs, unsigned int num_regs, int *err)
```

Write multiple registers to the device

**Parameters**

- `struct regmap *map`: Register map to write to
- `const struct cci_reg_sequence *regs`: Array of structures containing register-address, -value pairs to be
  written, register-addresses use CCI_REG#() macros to encode reg width
- `unsigned int num_regs`: Number of registers to write
- `int *err`: Optional pointer to store errors, if a previous error is set
  then the write will be skipped

**Description**

Write multiple registers to the device where the set of register, value
pairs are supplied in any order, possibly not all in a single range.

Use of the CCI_REG#() macros to encode reg width is mandatory.

For raw lists of register-address, -value pairs with only 8 bit
wide writes `regmap_multi_reg_write()` can be used instead.

**Return**

`0` on success or a negative error code on failure.

#### <a id="c-devm_cci_regmap_init_i2c"></a>`devm_cci_regmap_init_i2c()`

```c
struct regmap * devm_cci_regmap_init_i2c(struct i2c_client *client, int reg_addr_bits)
```

Create regmap to use with cci_*() register access functions

**Parameters**

- `struct i2c_client *client`: i2c_client to create the regmap for
- `int reg_addr_bits`: register address width to use (8 or 16)

**Description**

Note the memory for the created regmap is `devm()` managed, tied to the client.

**Return**

`0` on success or a negative error code on failure.

---

# V4L2 common functions and data structures

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for V4L2 common functions and data structures.

<a id="rst-v4l2-common-functions-and-data-structures"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-v4l2_ctrl_query_fill"></a>`v4l2_ctrl_query_fill()`

```c
int v4l2_ctrl_query_fill(struct v4l2_queryctrl *qctrl, s32 min, s32 max, s32 step, s32 def)
```

Fill in a struct v4l2_queryctrl

**Parameters**

- `struct v4l2_queryctrl *qctrl`: pointer to the [`struct v4l2_queryctrl`](/kernel/userspace/userspace-api/media-v4l/vidioc-queryctrl.md#c-struct-v4l2_queryctrl) to be filled
- `s32 min`: minimum value for the control
- `s32 max`: maximum value for the control
- `s32 step`: control step
- `s32 def`: default value for the control

**Description**

Fills the [`struct v4l2_queryctrl`](/kernel/userspace/userspace-api/media-v4l/vidioc-queryctrl.md#c-struct-v4l2_queryctrl) fields for the query control.

> [!NOTE]
> This function assumes that the **qctrl->id** field is filled.

Returns -EINVAL if the control is not known by the V4L2 core, 0 on success.

#### <a id="c-enum-v4l2_i2c_tuner_type"></a>`enum v4l2_i2c_tuner_type`

specifies the range of tuner address that should be used when seeking for I2C devices.

**Constants**

- `ADDRS_RADIO`: Radio tuner addresses.
  Represent the following I2C addresses:
  0x10 (if compiled with tea5761 support)
  and 0x60.
- `ADDRS_DEMOD`: Demod tuner addresses.
  Represent the following I2C addresses:
  0x42, 0x43, 0x4a and 0x4b.
- `ADDRS_TV`: TV tuner addresses.
  Represent the following I2C addresses:
  0x42, 0x43, 0x4a, 0x4b, 0x60, 0x61, 0x62,
  0x63 and 0x64.
- `ADDRS_TV_WITH_DEMOD`: TV tuner addresses if demod is present, this
  excludes addresses used by the demodulator
  from the list of candidates.
  Represent the following I2C addresses:
  0x60, 0x61, 0x62, 0x63 and 0x64.

**NOTE**

All I2C addresses above use the 7-bit notation.

#### <a id="c-v4l2_i2c_new_subdev"></a>`v4l2_i2c_new_subdev()`

```c
struct v4l2_subdev * v4l2_i2c_new_subdev(struct v4l2_device *v4l2_dev, struct i2c_adapter *adapter, const char *client_type, u8 addr, const unsigned short *probe_addrs)
```

Load an i2c module and return an initialized [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev).

**Parameters**

- `struct v4l2_device *v4l2_dev`: pointer to [`struct v4l2_device`](/kernel/hardware/driver-api/media/v4l2-device.md#c-struct-v4l2_device)
- `struct i2c_adapter *adapter`: pointer to struct i2c_adapter
- `const char *client_type`: name of the chip that's on the adapter.
- `u8 addr`: I2C address. If zero, it will use **probe_addrs**
- `const unsigned short *probe_addrs`: array with a list of address. The last entry at such
  array should be `I2C_CLIENT_END`.

**Description**

returns a [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev) pointer.

#### <a id="c-v4l2_i2c_new_subdev_board"></a>`v4l2_i2c_new_subdev_board()`

```c
struct v4l2_subdev * v4l2_i2c_new_subdev_board(struct v4l2_device *v4l2_dev, struct i2c_adapter *adapter, struct i2c_board_info *info, const unsigned short *probe_addrs)
```

Load an i2c module and return an initialized [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev).

**Parameters**

- `struct v4l2_device *v4l2_dev`: pointer to [`struct v4l2_device`](/kernel/hardware/driver-api/media/v4l2-device.md#c-struct-v4l2_device)
- `struct i2c_adapter *adapter`: pointer to struct i2c_adapter
- `struct i2c_board_info *info`: pointer to struct i2c_board_info used to replace the irq,
  platform_data and addr arguments.
- `const unsigned short *probe_addrs`: array with a list of address. The last entry at such
  array should be `I2C_CLIENT_END`.

**Description**

returns a [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev) pointer.

#### <a id="c-v4l2_i2c_subdev_set_name"></a>`v4l2_i2c_subdev_set_name()`

```c
void v4l2_i2c_subdev_set_name(struct v4l2_subdev *sd, struct i2c_client *client, const char *devname, const char *postfix)
```

Set name for an I²C sub-device

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)
- `struct i2c_client *client`: pointer to struct i2c_client
- `const char *devname`: the name of the device; if NULL, the I²C device drivers's name
  will be used
- `const char *postfix`: sub-device specific string to put right after the I²C device name;
  may be NULL

#### <a id="c-v4l2_i2c_subdev_init"></a>`v4l2_i2c_subdev_init()`

```c
void v4l2_i2c_subdev_init(struct v4l2_subdev *sd, struct i2c_client *client, const struct v4l2_subdev_ops *ops)
```

Initializes a [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev) with data from an i2c_client struct.

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)
- `struct i2c_client *client`: pointer to struct i2c_client
- `const struct v4l2_subdev_ops *ops`: pointer to [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops)

#### <a id="c-v4l2_i2c_subdev_addr"></a>`v4l2_i2c_subdev_addr()`

```c
unsigned short v4l2_i2c_subdev_addr(struct v4l2_subdev *sd)
```

returns i2c client address of [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev).

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)

**Description**

Returns the address of an I2C sub-device

#### <a id="c-v4l2_i2c_tuner_addrs"></a>`v4l2_i2c_tuner_addrs()`

```c
const unsigned short * v4l2_i2c_tuner_addrs(enum v4l2_i2c_tuner_type type)
```

Return a list of I2C tuner addresses to probe.

**Parameters**

- `enum v4l2_i2c_tuner_type type`: type of the tuner to seek, as defined by
  [`enum v4l2_i2c_tuner_type`](#c-enum-v4l2_i2c_tuner_type).

**NOTE**

Use only if the tuner addresses are unknown.

#### <a id="c-v4l2_i2c_subdev_unregister"></a>`v4l2_i2c_subdev_unregister()`

```c
void v4l2_i2c_subdev_unregister(struct v4l2_subdev *sd)
```

Unregister a v4l2_subdev

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)

#### <a id="c-v4l2_spi_new_subdev"></a>`v4l2_spi_new_subdev()`

```c
struct v4l2_subdev * v4l2_spi_new_subdev(struct v4l2_device *v4l2_dev, struct spi_controller *ctlr, struct spi_board_info *info)
```

Load an spi module and return an initialized [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev).

**Parameters**

- `struct v4l2_device *v4l2_dev`: pointer to [`struct v4l2_device`](/kernel/hardware/driver-api/media/v4l2-device.md#c-struct-v4l2_device).
- `struct spi_controller *ctlr`: pointer to struct spi_controller.
- `struct spi_board_info *info`: pointer to struct spi_board_info.

**Description**

returns a [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev) pointer.

#### <a id="c-v4l2_spi_subdev_init"></a>`v4l2_spi_subdev_init()`

```c
void v4l2_spi_subdev_init(struct v4l2_subdev *sd, struct spi_device *spi, const struct v4l2_subdev_ops *ops)
```

Initialize a v4l2_subdev with data from an spi_device struct.

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)
- `struct spi_device *spi`: pointer to struct spi_device.
- `const struct v4l2_subdev_ops *ops`: pointer to [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops)

#### <a id="c-v4l2_spi_subdev_unregister"></a>`v4l2_spi_subdev_unregister()`

```c
void v4l2_spi_subdev_unregister(struct v4l2_subdev *sd)
```

Unregister a v4l2_subdev

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)

#### <a id="c-v4l_bound_align_image"></a>`v4l_bound_align_image()`

```c
void v4l_bound_align_image(unsigned int *width, unsigned int wmin, unsigned int wmax, unsigned int walign, unsigned int *height, unsigned int hmin, unsigned int hmax, unsigned int halign, unsigned int salign)
```

adjust video dimensions according to a given constraints.

**Parameters**

- `unsigned int *width`: pointer to width that will be adjusted if needed.
- `unsigned int wmin`: minimum width.
- `unsigned int wmax`: maximum width.
- `unsigned int walign`: least significant bit on width.
- `unsigned int *height`: pointer to height that will be adjusted if needed.
- `unsigned int hmin`: minimum height.
- `unsigned int hmax`: maximum height.
- `unsigned int halign`: least significant bit on height.
- `unsigned int salign`: least significant bit for the image size (e. g.
  width * height).

**Description**

Clip an image to have **width** between **wmin** and **wmax**, and **height** between
**hmin** and **hmax**, inclusive.

Additionally, the **width** will be a multiple of 2^{walign},
the **height** will be a multiple of 2^{halign}, and the overall
size width * height will be a multiple of 2^{salign}.

> [!NOTE]
> 1. The clipping rectangle may be shrunk or enlarged to fit the alignment
>    constraints.
> 1. **wmax** must not be smaller than **wmin**.
> 1. **hmax** must not be smaller than **hmin**.
> 1. The alignments must not be so high there are no possible image
>    sizes within the allowed bounds.
> 1. **wmin** and **hmin** must be at least 1 (don't use 0).
> 1. For **walign**, **halign** and **salign**, if you don't care about a certain
>    alignment, specify `0`, as 2^0 = 1 and one byte alignment
>    is equivalent to no alignment.
> 1. If you only want to adjust downward, specify a maximum that's the
>    same as the initial value.

#### <a id="c-v4l2_find_nearest_size_conditional"></a>`v4l2_find_nearest_size_conditional()`

```c
v4l2_find_nearest_size_conditional(array, array_size, width_field, height_field, width, height, func, context)
```

Find the nearest size among a discrete set of resolutions contained in an array of a driver specific struct, with conditionally exlusion of certain modes

**Parameters**

- `array`: a driver specific array of image sizes
- `array_size`: the length of the driver specific array of image sizes
- `width_field`: the name of the width field in the driver specific struct
- `height_field`: the name of the height field in the driver specific struct
- `width`: desired width
- `height`: desired height
- `func`: ignores mode if returns false
- `context`: context for the function

**Description**

Finds the closest resolution to minimize the width and height differences
between what requested and the supported resolutions. The size of the width
and height fields in the driver specific must equal to that of u32, i.e. four
bytes. **func** is called for each mode considered, a mode is ignored if **func**
returns false for it.

Returns the best match or NULL if the length of the array is zero.

#### <a id="c-v4l2_find_nearest_size"></a>`v4l2_find_nearest_size()`

```c
v4l2_find_nearest_size(array, array_size, width_field, height_field, width, height)
```

Find the nearest size among a discrete set of resolutions contained in an array of a driver specific struct

**Parameters**

- `array`: a driver specific array of image sizes
- `array_size`: the length of the driver specific array of image sizes
- `width_field`: the name of the width field in the driver specific struct
- `height_field`: the name of the height field in the driver specific struct
- `width`: desired width
- `height`: desired height

**Description**

Finds the closest resolution to minimize the width and height differences
between what requested and the supported resolutions. The size of the width
and height fields in the driver specific must equal to that of u32, i.e. four
bytes.

Returns the best match or NULL if the length of the array is zero.

#### <a id="c-v4l2_g_parm_cap"></a>`v4l2_g_parm_cap()`

```c
int v4l2_g_parm_cap(struct video_device *vdev, struct v4l2_subdev *sd, struct v4l2_streamparm *a)
```

helper routine for vidioc_g_parm to fill this in by calling the get_frame_interval op of the given subdev. It only works for V4L2_BUF_TYPE_VIDEO_CAPTURE(_MPLANE), hence the _cap in the function name.

**Parameters**

- `struct video_device *vdev`: the struct video_device pointer. Used to determine the device caps.
- `struct v4l2_subdev *sd`: the sub-device pointer.
- `struct v4l2_streamparm *a`: the VIDIOC_G_PARM argument.

#### <a id="c-v4l2_s_parm_cap"></a>`v4l2_s_parm_cap()`

```c
int v4l2_s_parm_cap(struct video_device *vdev, struct v4l2_subdev *sd, struct v4l2_streamparm *a)
```

helper routine for vidioc_s_parm to fill this in by calling the set_frame_interval op of the given subdev. It only works for V4L2_BUF_TYPE_VIDEO_CAPTURE(_MPLANE), hence the _cap in the function name.

**Parameters**

- `struct video_device *vdev`: the struct video_device pointer. Used to determine the device caps.
- `struct v4l2_subdev *sd`: the sub-device pointer.
- `struct v4l2_streamparm *a`: the VIDIOC_S_PARM argument.

#### <a id="c-enum-v4l2_pixel_encoding"></a>`enum v4l2_pixel_encoding`

specifies the pixel encoding value

**Constants**

- `V4L2_PIXEL_ENC_UNKNOWN`: Pixel encoding is unknown/un-initialized
- `V4L2_PIXEL_ENC_YUV`: Pixel encoding is YUV
- `V4L2_PIXEL_ENC_RGB`: Pixel encoding is RGB
- `V4L2_PIXEL_ENC_BAYER`: Pixel encoding is Bayer

#### <a id="c-struct-v4l2_format_info"></a>`struct v4l2_format_info`

information about a V4L2 format

**Definition**

```c
struct v4l2_format_info {
    u32 format;
    u8 pixel_enc;
    u8 mem_planes;
    u8 comp_planes;
    u8 bpp[4];
    u8 bpp_div[4];
    u8 hdiv;
    u8 vdiv;
    u8 block_w[4];
    u8 block_h[4];
};
```

**Members**

- `format`: 4CC format identifier (V4L2_PIX_FMT_*)
- `pixel_enc`: Pixel encoding (see enum v4l2_pixel_encoding above)
- `mem_planes`: Number of memory planes, which includes the alpha plane (1 to 4).
- `comp_planes`: Number of component planes, which includes the alpha plane (1 to 4).
- `bpp`: Array of per-plane bytes per pixel
- `bpp_div`: Array of per-plane bytes per pixel divisors to support fractional pixel sizes.
- `hdiv`: Horizontal chroma subsampling factor
- `vdiv`: Vertical chroma subsampling factor
- `block_w`: Per-plane macroblock pixel width (optional)
- `block_h`: Per-plane macroblock pixel height (optional)

#### <a id="c-v4l2_get_link_freq"></a>`v4l2_get_link_freq()`

```c
s64 v4l2_get_link_freq(const struct media_pad *pad, unsigned int mul, unsigned int div)
```

Get link rate from transmitter

**Parameters**

- `const struct media_pad *pad`: The transmitter's media pad
- `unsigned int mul`: The multiplier between pixel rate and link frequency. Bits per pixel on
  D-PHY, samples per clock on parallel. 0 otherwise.
- `unsigned int div`: The divisor between pixel rate and link frequency. Number of data lanes
  times two on D-PHY, 1 on parallel. 0 otherwise.

**Description**

This function obtains and returns the link frequency from the transmitter
sub-device's pad. The link frequency is retrieved using the get_mbus_config
sub-device pad operation. If this fails, the function falls back to obtaining
the frequency either directly from the V4L2_CID_LINK_FREQ control if
implemented by the transmitter, or by calculating it from the pixel rate
obtained from the V4L2_CID_PIXEL_RATE control.

**Return**

* >0: Link frequency
* `-ENOENT`: Link frequency or pixel rate control not found
* `-EINVAL`: Invalid link frequency value

#### <a id="c-v4l2_get_active_data_lanes"></a>`v4l2_get_active_data_lanes()`

```c
int v4l2_get_active_data_lanes(const struct media_pad *pad, unsigned int max_data_lanes)
```

Get number of active data lanes from driver

**Parameters**

- `const struct media_pad *pad`: The transmitter's media pad.
- `unsigned int max_data_lanes`: The maximum number of active data lanes supported by
  the MIPI CSI link in hardware.

**Description**

This function is intended for obtaining the number of data lanes that are
actively being used by the driver for a MIPI CSI-2 device on a given media pad.
This information is derived from a mbus_config fetched from a device driver
using the get_mbus_config v4l2_subdev pad op.

**Return**

* >0: Number of active data lanes
* `-EINVAL`: Number of active data lanes is invalid, as it exceeds the maximum
  supported data lanes.

#### <a id="c-v4l2_link_freq_to_bitmap"></a>`v4l2_link_freq_to_bitmap()`

```c
int v4l2_link_freq_to_bitmap(struct device *dev, const u64 *fw_link_freqs, unsigned int num_of_fw_link_freqs, const s64 *driver_link_freqs, unsigned int num_of_driver_link_freqs, unsigned long *bitmap)
```

Figure out platform-supported link frequencies

**Parameters**

- `struct device *dev`: The struct device
- `const u64 *fw_link_freqs`: Array of link frequencies from firmware
- `unsigned int num_of_fw_link_freqs`: Number of entries in **fw_link_freqs**
- `const s64 *driver_link_freqs`: Array of link frequencies supported by the driver
- `unsigned int num_of_driver_link_freqs`: Number of entries in **driver_link_freqs**
- `unsigned long *bitmap`: Bitmap of driver-supported link frequencies found in **fw_link_freqs**

**Description**

This function checks which driver-supported link frequencies are enabled in
system firmware and sets the corresponding bits in **bitmap** (after first
zeroing it).

**Return**

* `0`: Success
* `-ENOENT`: No match found between driver-supported link frequencies and
  those available in firmware.
* `-ENODATA`: No link frequencies were specified in firmware.

#### <a id="c-devm_v4l2_sensor_clk_get"></a>`devm_v4l2_sensor_clk_get()`

```c
struct clk * devm_v4l2_sensor_clk_get(struct device *dev, const char *id)
```

lookup and obtain a reference to a clock producer for a camera sensor

**Parameters**

- `struct device *dev`: device for v4l2 sensor clock "consumer"
- `const char *id`: clock consumer ID

**Description**

This function behaves the same way as [`devm_clk_get()`](/kernel/internals/core-api/kernel-api.md#c-devm_clk_get) except where there
is no clock producer like in ACPI-based platforms.

For ACPI-based platforms, the function will read the "clock-frequency"
ACPI _DSD property and register a fixed-clock with the frequency indicated
in the property.

This function also handles the special ACPI-based system case where:

* The clock-frequency _DSD property is present.
* A reference to the clock producer is present, where the clock is provided
  by a camera sensor PMIC driver (e.g. int3472/tps68470.c)

In this case try to set the clock-frequency value to the provided clock.

As the name indicates, this function may only be used on camera sensor
devices. This is because generally only camera sensors do need a clock to
query the frequency from, due to the requirement to configure the PLL for a
given CSI-2 interface frequency where the sensor's external clock frequency
is a factor. Additionally, the clock frequency tends to be available on ACPI
firmware based systems for camera sensors specifically (if e.g. DisCo for
Imaging compliant).

Returns a pointer to a struct clk on success or an error pointer on failure.

#### <a id="c-devm_v4l2_sensor_clk_get_legacy"></a>`devm_v4l2_sensor_clk_get_legacy()`

```c
struct clk * devm_v4l2_sensor_clk_get_legacy(struct device *dev, const char *id, bool fixed_rate, unsigned long clk_rate)
```

lookup and obtain a reference to a clock producer for a camera sensor.

**Parameters**

- `struct device *dev`: device for v4l2 sensor clock "consumer"
- `const char *id`: clock consumer ID
- `bool fixed_rate`: interpret the **clk_rate** as a fixed rate or default rate
- `unsigned long clk_rate`: the clock rate

**Description**

This function behaves the same way as [`devm_v4l2_sensor_clk_get()`](#c-devm_v4l2_sensor_clk_get) except that
it extends the behaviour on ACPI platforms to all platforms.

The function also provides the ability to set the clock rate to a fixed
frequency by setting **fixed_rate** to true and specifying the fixed frequency
in **clk_rate**, or to use a default clock rate when the "clock-frequency"
property is absent by setting **fixed_rate** to false and specifying the default
frequency in **clk_rate**. Setting **fixed_rate** to true and **clk_rate** to 0 is an
error.

This function is meant to support legacy behaviour in existing drivers only.
It must not be used in any new driver.

Returns a pointer to a struct clk on success or an error pointer on failure.



#### <a id="c-struct-v4l2_ioctl_ops"></a>`struct v4l2_ioctl_ops`

describe operations for each V4L2 ioctl

**Definition**

```c
struct v4l2_ioctl_ops {
        int (*vidioc_querycap)(struct file *file, void *priv, struct v4l2_capability *cap);
        int (*vidioc_enum_fmt_vid_cap)(struct file *file, void *priv, struct v4l2_fmtdesc *f);
        int (*vidioc_enum_fmt_vid_overlay)(struct file *file, void *priv, struct v4l2_fmtdesc *f);
        int (*vidioc_enum_fmt_vid_out)(struct file *file, void *priv, struct v4l2_fmtdesc *f);
        int (*vidioc_enum_fmt_sdr_cap)(struct file *file, void *priv, struct v4l2_fmtdesc *f);
        int (*vidioc_enum_fmt_sdr_out)(struct file *file, void *priv, struct v4l2_fmtdesc *f);
        int (*vidioc_enum_fmt_meta_cap)(struct file *file, void *priv, struct v4l2_fmtdesc *f);
        int (*vidioc_enum_fmt_meta_out)(struct file *file, void *priv, struct v4l2_fmtdesc *f);
        int (*vidioc_g_fmt_vid_cap)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_g_fmt_vid_overlay)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_g_fmt_vid_out)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_g_fmt_vid_out_overlay)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_g_fmt_vbi_cap)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_g_fmt_vbi_out)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_g_fmt_sliced_vbi_cap)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_g_fmt_sliced_vbi_out)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_g_fmt_vid_cap_mplane)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_g_fmt_vid_out_mplane)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_g_fmt_sdr_cap)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_g_fmt_sdr_out)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_g_fmt_meta_cap)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_g_fmt_meta_out)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_s_fmt_vid_cap)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_s_fmt_vid_overlay)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_s_fmt_vid_out)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_s_fmt_vid_out_overlay)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_s_fmt_vbi_cap)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_s_fmt_vbi_out)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_s_fmt_sliced_vbi_cap)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_s_fmt_sliced_vbi_out)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_s_fmt_vid_cap_mplane)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_s_fmt_vid_out_mplane)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_s_fmt_sdr_cap)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_s_fmt_sdr_out)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_s_fmt_meta_cap)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_s_fmt_meta_out)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_try_fmt_vid_cap)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_try_fmt_vid_overlay)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_try_fmt_vid_out)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_try_fmt_vid_out_overlay)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_try_fmt_vbi_cap)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_try_fmt_vbi_out)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_try_fmt_sliced_vbi_cap)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_try_fmt_sliced_vbi_out)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_try_fmt_vid_cap_mplane)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_try_fmt_vid_out_mplane)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_try_fmt_sdr_cap)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_try_fmt_sdr_out)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_try_fmt_meta_cap)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_try_fmt_meta_out)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_reqbufs)(struct file *file, void *priv, struct v4l2_requestbuffers *b);
        int (*vidioc_querybuf)(struct file *file, void *priv, struct v4l2_buffer *b);
        int (*vidioc_qbuf)(struct file *file, void *priv, struct v4l2_buffer *b);
        int (*vidioc_expbuf)(struct file *file, void *priv, struct v4l2_exportbuffer *e);
        int (*vidioc_dqbuf)(struct file *file, void *priv, struct v4l2_buffer *b);
        int (*vidioc_create_bufs)(struct file *file, void *priv, struct v4l2_create_buffers *b);
        int (*vidioc_prepare_buf)(struct file *file, void *priv, struct v4l2_buffer *b);
        int (*vidioc_remove_bufs)(struct file *file, void *priv, struct v4l2_remove_buffers *d);
        int (*vidioc_overlay)(struct file *file, void *priv, unsigned int i);
        int (*vidioc_g_fbuf)(struct file *file, void *priv, struct v4l2_framebuffer *a);
        int (*vidioc_s_fbuf)(struct file *file, void *priv, const struct v4l2_framebuffer *a);
        int (*vidioc_streamon)(struct file *file, void *priv, enum v4l2_buf_type i);
        int (*vidioc_streamoff)(struct file *file, void *priv, enum v4l2_buf_type i);
        int (*vidioc_g_std)(struct file *file, void *priv, v4l2_std_id *norm);
        int (*vidioc_s_std)(struct file *file, void *priv, v4l2_std_id norm);
        int (*vidioc_querystd)(struct file *file, void *priv, v4l2_std_id *a);
        int (*vidioc_enum_input)(struct file *file, void *priv, struct v4l2_input *inp);
        int (*vidioc_g_input)(struct file *file, void *priv, unsigned int *i);
        int (*vidioc_s_input)(struct file *file, void *priv, unsigned int i);
        int (*vidioc_enum_output)(struct file *file, void *priv, struct v4l2_output *a);
        int (*vidioc_g_output)(struct file *file, void *priv, unsigned int *i);
        int (*vidioc_s_output)(struct file *file, void *priv, unsigned int i);
        int (*vidioc_query_ext_ctrl)(struct file *file, void *priv, struct v4l2_query_ext_ctrl *a);
        int (*vidioc_g_ext_ctrls)(struct file *file, void *priv, struct v4l2_ext_controls *a);
        int (*vidioc_s_ext_ctrls)(struct file *file, void *priv, struct v4l2_ext_controls *a);
        int (*vidioc_try_ext_ctrls)(struct file *file, void *priv, struct v4l2_ext_controls *a);
        int (*vidioc_querymenu)(struct file *file, void *priv, struct v4l2_querymenu *a);
        int (*vidioc_enumaudio)(struct file *file, void *priv, struct v4l2_audio *a);
        int (*vidioc_g_audio)(struct file *file, void *priv, struct v4l2_audio *a);
        int (*vidioc_s_audio)(struct file *file, void *priv, const struct v4l2_audio *a);
        int (*vidioc_enumaudout)(struct file *file, void *priv, struct v4l2_audioout *a);
        int (*vidioc_g_audout)(struct file *file, void *priv, struct v4l2_audioout *a);
        int (*vidioc_s_audout)(struct file *file, void *priv, const struct v4l2_audioout *a);
        int (*vidioc_g_modulator)(struct file *file, void *priv, struct v4l2_modulator *a);
        int (*vidioc_s_modulator)(struct file *file, void *priv, const struct v4l2_modulator *a);
        int (*vidioc_g_pixelaspect)(struct file *file, void *priv, int buf_type, struct v4l2_fract *aspect);
        int (*vidioc_g_selection)(struct file *file, void *priv, struct v4l2_selection *s);
        int (*vidioc_s_selection)(struct file *file, void *priv, struct v4l2_selection *s);
        int (*vidioc_g_jpegcomp)(struct file *file, void *priv, struct v4l2_jpegcompression *a);
        int (*vidioc_s_jpegcomp)(struct file *file, void *priv, const struct v4l2_jpegcompression *a);
        int (*vidioc_g_enc_index)(struct file *file, void *priv, struct v4l2_enc_idx *a);
        int (*vidioc_encoder_cmd)(struct file *file, void *priv, struct v4l2_encoder_cmd *a);
        int (*vidioc_try_encoder_cmd)(struct file *file, void *priv, struct v4l2_encoder_cmd *a);
        int (*vidioc_decoder_cmd)(struct file *file, void *priv, struct v4l2_decoder_cmd *a);
        int (*vidioc_try_decoder_cmd)(struct file *file, void *priv, struct v4l2_decoder_cmd *a);
        int (*vidioc_g_parm)(struct file *file, void *priv, struct v4l2_streamparm *a);
        int (*vidioc_s_parm)(struct file *file, void *priv, struct v4l2_streamparm *a);
        int (*vidioc_g_tuner)(struct file *file, void *priv, struct v4l2_tuner *a);
        int (*vidioc_s_tuner)(struct file *file, void *priv, const struct v4l2_tuner *a);
        int (*vidioc_g_frequency)(struct file *file, void *priv, struct v4l2_frequency *a);
        int (*vidioc_s_frequency)(struct file *file, void *priv, const struct v4l2_frequency *a);
        int (*vidioc_enum_freq_bands)(struct file *file, void *priv, struct v4l2_frequency_band *band);
        int (*vidioc_g_sliced_vbi_cap)(struct file *file, void *priv, struct v4l2_sliced_vbi_cap *a);
        int (*vidioc_log_status)(struct file *file, void *priv);
        int (*vidioc_s_hw_freq_seek)(struct file *file, void *priv, const struct v4l2_hw_freq_seek *a);
    #ifdef CONFIG_VIDEO_ADV_DEBUG;
        int (*vidioc_g_register)(struct file *file, void *priv, struct v4l2_dbg_register *reg);
        int (*vidioc_s_register)(struct file *file, void *priv, const struct v4l2_dbg_register *reg);
        int (*vidioc_g_chip_info)(struct file *file, void *priv, struct v4l2_dbg_chip_info *chip);
    #endif;
        int (*vidioc_enum_framesizes)(struct file *file, void *priv, struct v4l2_frmsizeenum *fsize);
        int (*vidioc_enum_frameintervals)(struct file *file, void *priv, struct v4l2_frmivalenum *fival);
        int (*vidioc_s_dv_timings)(struct file *file, void *priv, struct v4l2_dv_timings *timings);
        int (*vidioc_g_dv_timings)(struct file *file, void *priv, struct v4l2_dv_timings *timings);
        int (*vidioc_query_dv_timings)(struct file *file, void *priv, struct v4l2_dv_timings *timings);
        int (*vidioc_enum_dv_timings)(struct file *file, void *priv, struct v4l2_enum_dv_timings *timings);
        int (*vidioc_dv_timings_cap)(struct file *file, void *priv, struct v4l2_dv_timings_cap *cap);
        int (*vidioc_g_edid)(struct file *file, void *priv, struct v4l2_edid *edid);
        int (*vidioc_s_edid)(struct file *file, void *priv, struct v4l2_edid *edid);
        int (*vidioc_subscribe_event)(struct v4l2_fh *fh, const struct v4l2_event_subscription *sub);
        int (*vidioc_unsubscribe_event)(struct v4l2_fh *fh, const struct v4l2_event_subscription *sub);
        long (*vidioc_default)(struct file *file, void *priv, bool valid_prio, unsigned int cmd, void *arg);
};
```

**Members**

- `vidioc_querycap`: pointer to the function that implements
  VIDIOC_QUERYCAP ioctl
- `vidioc_enum_fmt_vid_cap`: pointer to the function that implements
  VIDIOC_ENUM_FMT ioctl logic
  for video capture in single and multi plane mode
- `vidioc_enum_fmt_vid_overlay`: pointer to the function that implements
  VIDIOC_ENUM_FMT ioctl logic
  for video overlay
- `vidioc_enum_fmt_vid_out`: pointer to the function that implements
  VIDIOC_ENUM_FMT ioctl logic
  for video output in single and multi plane mode
- `vidioc_enum_fmt_sdr_cap`: pointer to the function that implements
  VIDIOC_ENUM_FMT ioctl logic
  for Software Defined Radio capture
- `vidioc_enum_fmt_sdr_out`: pointer to the function that implements
  VIDIOC_ENUM_FMT ioctl logic
  for Software Defined Radio output
- `vidioc_enum_fmt_meta_cap`: pointer to the function that implements
  VIDIOC_ENUM_FMT ioctl logic
  for metadata capture
- `vidioc_enum_fmt_meta_out`: pointer to the function that implements
  VIDIOC_ENUM_FMT ioctl logic
  for metadata output
- `vidioc_g_fmt_vid_cap`: pointer to the function that implements
  VIDIOC_G_FMT ioctl logic for video capture
  in single plane mode
- `vidioc_g_fmt_vid_overlay`: pointer to the function that implements
  VIDIOC_G_FMT ioctl logic for video overlay
- `vidioc_g_fmt_vid_out`: pointer to the function that implements
  VIDIOC_G_FMT ioctl logic for video out
  in single plane mode
- `vidioc_g_fmt_vid_out_overlay`: pointer to the function that implements
  VIDIOC_G_FMT ioctl logic for video overlay output
- `vidioc_g_fmt_vbi_cap`: pointer to the function that implements
  VIDIOC_G_FMT ioctl logic for raw VBI capture
- `vidioc_g_fmt_vbi_out`: pointer to the function that implements
  VIDIOC_G_FMT ioctl logic for raw VBI output
- `vidioc_g_fmt_sliced_vbi_cap`: pointer to the function that implements
  VIDIOC_G_FMT ioctl logic for sliced VBI capture
- `vidioc_g_fmt_sliced_vbi_out`: pointer to the function that implements
  VIDIOC_G_FMT ioctl logic for sliced VBI output
- `vidioc_g_fmt_vid_cap_mplane`: pointer to the function that implements
  VIDIOC_G_FMT ioctl logic for video capture
  in multiple plane mode
- `vidioc_g_fmt_vid_out_mplane`: pointer to the function that implements
  VIDIOC_G_FMT ioctl logic for video out
  in multiplane plane mode
- `vidioc_g_fmt_sdr_cap`: pointer to the function that implements
  VIDIOC_G_FMT ioctl logic for Software Defined
  Radio capture
- `vidioc_g_fmt_sdr_out`: pointer to the function that implements
  VIDIOC_G_FMT ioctl logic for Software Defined
  Radio output
- `vidioc_g_fmt_meta_cap`: pointer to the function that implements
  VIDIOC_G_FMT ioctl logic for metadata capture
- `vidioc_g_fmt_meta_out`: pointer to the function that implements
  VIDIOC_G_FMT ioctl logic for metadata output
- `vidioc_s_fmt_vid_cap`: pointer to the function that implements
  VIDIOC_S_FMT ioctl logic for video capture
  in single plane mode
- `vidioc_s_fmt_vid_overlay`: pointer to the function that implements
  VIDIOC_S_FMT ioctl logic for video overlay
- `vidioc_s_fmt_vid_out`: pointer to the function that implements
  VIDIOC_S_FMT ioctl logic for video out
  in single plane mode
- `vidioc_s_fmt_vid_out_overlay`: pointer to the function that implements
  VIDIOC_S_FMT ioctl logic for video overlay output
- `vidioc_s_fmt_vbi_cap`: pointer to the function that implements
  VIDIOC_S_FMT ioctl logic for raw VBI capture
- `vidioc_s_fmt_vbi_out`: pointer to the function that implements
  VIDIOC_S_FMT ioctl logic for raw VBI output
- `vidioc_s_fmt_sliced_vbi_cap`: pointer to the function that implements
  VIDIOC_S_FMT ioctl logic for sliced VBI capture
- `vidioc_s_fmt_sliced_vbi_out`: pointer to the function that implements
  VIDIOC_S_FMT ioctl logic for sliced VBI output
- `vidioc_s_fmt_vid_cap_mplane`: pointer to the function that implements
  VIDIOC_S_FMT ioctl logic for video capture
  in multiple plane mode
- `vidioc_s_fmt_vid_out_mplane`: pointer to the function that implements
  VIDIOC_S_FMT ioctl logic for video out
  in multiplane plane mode
- `vidioc_s_fmt_sdr_cap`: pointer to the function that implements
  VIDIOC_S_FMT ioctl logic for Software Defined
  Radio capture
- `vidioc_s_fmt_sdr_out`: pointer to the function that implements
  VIDIOC_S_FMT ioctl logic for Software Defined
  Radio output
- `vidioc_s_fmt_meta_cap`: pointer to the function that implements
  VIDIOC_S_FMT ioctl logic for metadata capture
- `vidioc_s_fmt_meta_out`: pointer to the function that implements
  VIDIOC_S_FMT ioctl logic for metadata output
- `vidioc_try_fmt_vid_cap`: pointer to the function that implements
  VIDIOC_TRY_FMT ioctl logic for video capture
  in single plane mode
- `vidioc_try_fmt_vid_overlay`: pointer to the function that implements
  VIDIOC_TRY_FMT ioctl logic for video overlay
- `vidioc_try_fmt_vid_out`: pointer to the function that implements
  VIDIOC_TRY_FMT ioctl logic for video out
  in single plane mode
- `vidioc_try_fmt_vid_out_overlay`: pointer to the function that implements
  VIDIOC_TRY_FMT ioctl logic for video overlay
  output
- `vidioc_try_fmt_vbi_cap`: pointer to the function that implements
  VIDIOC_TRY_FMT ioctl logic for raw VBI capture
- `vidioc_try_fmt_vbi_out`: pointer to the function that implements
  VIDIOC_TRY_FMT ioctl logic for raw VBI output
- `vidioc_try_fmt_sliced_vbi_cap`: pointer to the function that implements
  VIDIOC_TRY_FMT ioctl logic for sliced VBI
  capture
- `vidioc_try_fmt_sliced_vbi_out`: pointer to the function that implements
  VIDIOC_TRY_FMT ioctl logic for sliced VBI output
- `vidioc_try_fmt_vid_cap_mplane`: pointer to the function that implements
  VIDIOC_TRY_FMT ioctl logic for video capture
  in multiple plane mode
- `vidioc_try_fmt_vid_out_mplane`: pointer to the function that implements
  VIDIOC_TRY_FMT ioctl logic for video out
  in multiplane plane mode
- `vidioc_try_fmt_sdr_cap`: pointer to the function that implements
  VIDIOC_TRY_FMT ioctl logic for Software Defined
  Radio capture
- `vidioc_try_fmt_sdr_out`: pointer to the function that implements
  VIDIOC_TRY_FMT ioctl logic for Software Defined
  Radio output
- `vidioc_try_fmt_meta_cap`: pointer to the function that implements
  VIDIOC_TRY_FMT ioctl logic for metadata capture
- `vidioc_try_fmt_meta_out`: pointer to the function that implements
  VIDIOC_TRY_FMT ioctl logic for metadata output
- `vidioc_reqbufs`: pointer to the function that implements
  VIDIOC_REQBUFS ioctl
- `vidioc_querybuf`: pointer to the function that implements
  VIDIOC_QUERYBUF ioctl
- `vidioc_qbuf`: pointer to the function that implements
  VIDIOC_QBUF ioctl
- `vidioc_expbuf`: pointer to the function that implements
  VIDIOC_EXPBUF ioctl
- `vidioc_dqbuf`: pointer to the function that implements
  VIDIOC_DQBUF ioctl
- `vidioc_create_bufs`: pointer to the function that implements
  VIDIOC_CREATE_BUFS ioctl
- `vidioc_prepare_buf`: pointer to the function that implements
  VIDIOC_PREPARE_BUF ioctl
- `vidioc_remove_bufs`: pointer to the function that implements
  VIDIOC_REMOVE_BUFS ioctl
- `vidioc_overlay`: pointer to the function that implements
  VIDIOC_OVERLAY ioctl
- `vidioc_g_fbuf`: pointer to the function that implements
  VIDIOC_G_FBUF ioctl
- `vidioc_s_fbuf`: pointer to the function that implements
  VIDIOC_S_FBUF ioctl
- `vidioc_streamon`: pointer to the function that implements
  VIDIOC_STREAMON ioctl
- `vidioc_streamoff`: pointer to the function that implements
  VIDIOC_STREAMOFF ioctl
- `vidioc_g_std`: pointer to the function that implements
  VIDIOC_G_STD ioctl
- `vidioc_s_std`: pointer to the function that implements
  VIDIOC_S_STD ioctl
- `vidioc_querystd`: pointer to the function that implements
  VIDIOC_QUERYSTD ioctl
- `vidioc_enum_input`: pointer to the function that implements
  VIDIOC_ENUM_INPUT ioctl
- `vidioc_g_input`: pointer to the function that implements
  VIDIOC_G_INPUT ioctl
- `vidioc_s_input`: pointer to the function that implements
  VIDIOC_S_INPUT ioctl
- `vidioc_enum_output`: pointer to the function that implements
  VIDIOC_ENUM_OUTPUT ioctl
- `vidioc_g_output`: pointer to the function that implements
  VIDIOC_G_OUTPUT ioctl
- `vidioc_s_output`: pointer to the function that implements
  VIDIOC_S_OUTPUT ioctl
- `vidioc_query_ext_ctrl`: pointer to the function that implements
  VIDIOC_QUERY_EXT_CTRL ioctl
- `vidioc_g_ext_ctrls`: pointer to the function that implements
  VIDIOC_G_EXT_CTRLS ioctl
- `vidioc_s_ext_ctrls`: pointer to the function that implements
  VIDIOC_S_EXT_CTRLS ioctl
- `vidioc_try_ext_ctrls`: pointer to the function that implements
  VIDIOC_TRY_EXT_CTRLS ioctl
- `vidioc_querymenu`: pointer to the function that implements
  VIDIOC_QUERYMENU ioctl
- `vidioc_enumaudio`: pointer to the function that implements
  VIDIOC_ENUMAUDIO ioctl
- `vidioc_g_audio`: pointer to the function that implements
  VIDIOC_G_AUDIO ioctl
- `vidioc_s_audio`: pointer to the function that implements
  VIDIOC_S_AUDIO ioctl
- `vidioc_enumaudout`: pointer to the function that implements
  VIDIOC_ENUMAUDOUT ioctl
- `vidioc_g_audout`: pointer to the function that implements
  VIDIOC_G_AUDOUT ioctl
- `vidioc_s_audout`: pointer to the function that implements
  VIDIOC_S_AUDOUT ioctl
- `vidioc_g_modulator`: pointer to the function that implements
  VIDIOC_G_MODULATOR ioctl
- `vidioc_s_modulator`: pointer to the function that implements
  VIDIOC_S_MODULATOR ioctl
- `vidioc_g_pixelaspect`: pointer to the function that implements
  the pixelaspect part of the VIDIOC_CROPCAP ioctl
- `vidioc_g_selection`: pointer to the function that implements
  VIDIOC_G_SELECTION ioctl
- `vidioc_s_selection`: pointer to the function that implements
  VIDIOC_S_SELECTION ioctl
- `vidioc_g_jpegcomp`: pointer to the function that implements
  VIDIOC_G_JPEGCOMP ioctl
- `vidioc_s_jpegcomp`: pointer to the function that implements
  VIDIOC_S_JPEGCOMP ioctl
- `vidioc_g_enc_index`: pointer to the function that implements
  VIDIOC_G_ENC_INDEX ioctl
- `vidioc_encoder_cmd`: pointer to the function that implements
  VIDIOC_ENCODER_CMD ioctl
- `vidioc_try_encoder_cmd`: pointer to the function that implements
  VIDIOC_TRY_ENCODER_CMD ioctl
- `vidioc_decoder_cmd`: pointer to the function that implements
  VIDIOC_DECODER_CMD ioctl
- `vidioc_try_decoder_cmd`: pointer to the function that implements
  VIDIOC_TRY_DECODER_CMD ioctl
- `vidioc_g_parm`: pointer to the function that implements
  VIDIOC_G_PARM ioctl
- `vidioc_s_parm`: pointer to the function that implements
  VIDIOC_S_PARM ioctl
- `vidioc_g_tuner`: pointer to the function that implements
  VIDIOC_G_TUNER ioctl
- `vidioc_s_tuner`: pointer to the function that implements
  VIDIOC_S_TUNER ioctl
- `vidioc_g_frequency`: pointer to the function that implements
  VIDIOC_G_FREQUENCY ioctl
- `vidioc_s_frequency`: pointer to the function that implements
  VIDIOC_S_FREQUENCY ioctl
- `vidioc_enum_freq_bands`: pointer to the function that implements
  VIDIOC_ENUM_FREQ_BANDS ioctl
- `vidioc_g_sliced_vbi_cap`: pointer to the function that implements
  VIDIOC_G_SLICED_VBI_CAP ioctl
- `vidioc_log_status`: pointer to the function that implements
  VIDIOC_LOG_STATUS ioctl
- `vidioc_s_hw_freq_seek`: pointer to the function that implements
  VIDIOC_S_HW_FREQ_SEEK ioctl
- `vidioc_g_register`: pointer to the function that implements
  VIDIOC_DBG_G_REGISTER ioctl
- `vidioc_s_register`: pointer to the function that implements
  VIDIOC_DBG_S_REGISTER ioctl
- `vidioc_g_chip_info`: pointer to the function that implements
  VIDIOC_DBG_G_CHIP_INFO ioctl
- `vidioc_enum_framesizes`: pointer to the function that implements
  VIDIOC_ENUM_FRAMESIZES ioctl
- `vidioc_enum_frameintervals`: pointer to the function that implements
  VIDIOC_ENUM_FRAMEINTERVALS ioctl
- `vidioc_s_dv_timings`: pointer to the function that implements
  VIDIOC_S_DV_TIMINGS ioctl
- `vidioc_g_dv_timings`: pointer to the function that implements
  VIDIOC_G_DV_TIMINGS ioctl
- `vidioc_query_dv_timings`: pointer to the function that implements
  VIDIOC_QUERY_DV_TIMINGS ioctl
- `vidioc_enum_dv_timings`: pointer to the function that implements
  VIDIOC_ENUM_DV_TIMINGS ioctl
- `vidioc_dv_timings_cap`: pointer to the function that implements
  VIDIOC_DV_TIMINGS_CAP ioctl
- `vidioc_g_edid`: pointer to the function that implements
  VIDIOC_G_EDID ioctl
- `vidioc_s_edid`: pointer to the function that implements
  VIDIOC_S_EDID ioctl
- `vidioc_subscribe_event`: pointer to the function that implements
  VIDIOC_SUBSCRIBE_EVENT ioctl
- `vidioc_unsubscribe_event`: pointer to the function that implements
  VIDIOC_UNSUBSCRIBE_EVENT ioctl
- `vidioc_default`: pointed used to allow other ioctls

#### <a id="c-v4l2_norm_to_name"></a>`v4l2_norm_to_name()`

```c
const char * v4l2_norm_to_name(v4l2_std_id id)
```

Ancillary routine to analog TV standard name from its ID.

**Parameters**

- `v4l2_std_id id`: analog TV standard ID.

**Return**

returns a string with the name of the analog TV standard.
If the standard is not found or if **id** points to multiple standard,
it returns "Unknown".

#### <a id="c-v4l2_video_std_frame_period"></a>`v4l2_video_std_frame_period()`

```c
void v4l2_video_std_frame_period(int id, struct v4l2_fract *frameperiod)
```

Ancillary routine that fills a struct `v4l2_fract` pointer with the default framerate fraction.

**Parameters**

- `int id`: analog TV standard ID.
- `struct v4l2_fract *frameperiod`: struct `v4l2_fract` pointer to be filled

#### <a id="c-v4l2_video_std_construct"></a>`v4l2_video_std_construct()`

```c
int v4l2_video_std_construct(struct v4l2_standard *vs, int id, const char *name)
```

Ancillary routine that fills in the fields of a `v4l2_standard` structure according to the **id** parameter.

**Parameters**

- `struct v4l2_standard *vs`: struct `v4l2_standard` pointer to be filled
- `int id`: analog TV standard ID.
- `const char *name`: name of the standard to be used

**Description**

> [!NOTE]
> This ancillary routine is obsolete. Shouldn't be used on newer drivers.

#### <a id="c-v4l_video_std_enumstd"></a>`v4l_video_std_enumstd()`

```c
int v4l_video_std_enumstd(struct v4l2_standard *vs, v4l2_std_id id)
```

Ancillary routine that fills in the fields of a `v4l2_standard` structure according to the **id** and **vs->index** parameters.

**Parameters**

- `struct v4l2_standard *vs`: struct `v4l2_standard` pointer to be filled.
- `v4l2_std_id id`: analog TV standard ID.

#### <a id="c-v4l_printk_ioctl"></a>`v4l_printk_ioctl()`

```c
void v4l_printk_ioctl(const char *prefix, unsigned int cmd)
```

Ancillary routine that prints the ioctl in a human-readable format.

**Parameters**

- `const char *prefix`: prefix to be added at the ioctl prints.
- `unsigned int cmd`: ioctl name

**Description**

> [!NOTE]
> If prefix != `NULL`, then it will issue a
> `printk(KERN_DEBUG "%s: ", prefix)` first.

#### <a id="c-v4l2_field_names"></a>`v4l2_field_names`

```c
extern const char *v4l2_field_names[];
```

Helper array mapping `V4L2_FIELD_*` to strings.

**Initialization**

default: `v4l2_field_names`

**Description**

Specially when printing debug messages, it is interesting to output
the field order at the V4L2 buffers. This array associates all possible
values of field pix format from V4L2 API into a string.

#### <a id="c-v4l2_type_names"></a>`v4l2_type_names`

```c
extern const char *v4l2_type_names[];
```

Helper array mapping `V4L2_BUF_TYPE_*` to strings.

**Initialization**

default: `v4l2_type_names`

**Description**

When printing debug messages, it is interesting to output the V4L2 buffer
type number with a name that represents its content.

#### <a id="c-v4l2_compat_ioctl32"></a>`v4l2_compat_ioctl32()`

```c
long int v4l2_compat_ioctl32(struct file *file, unsigned int cmd, unsigned long arg)
```

32 Bits compatibility layer for 64 bits processors

**Parameters**

- `struct file *file`: Pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file).
- `unsigned int cmd`: Ioctl name.
- `unsigned long arg`: Ioctl argument.

#### <a id="c-v4l2_kioctl"></a>`v4l2_kioctl()`

```c
typedef long v4l2_kioctl(struct file *file, unsigned int cmd, void *arg)
```

Typedef used to pass an ioctl handler.

**Parameters**

- `struct file *file`: Pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file).
- `unsigned int cmd`: Ioctl name.
- `void *arg`: Ioctl argument.

#### <a id="c-video_usercopy"></a>`video_usercopy()`

```c
long int video_usercopy(struct file *file, unsigned int cmd, unsigned long int arg, v4l2_kioctl func)
```

copies data from/to userspace memory when an ioctl is issued.

**Parameters**

- `struct file *file`: Pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file).
- `unsigned int cmd`: Ioctl name.
- `unsigned long int arg`: Ioctl argument.
- `v4l2_kioctl func`: function that will handle the ioctl

**Description**

> [!NOTE]
> This routine should be used only inside the V4L2 core.

#### <a id="c-video_ioctl2"></a>`video_ioctl2()`

```c
long int video_ioctl2(struct file *file, unsigned int cmd, unsigned long int arg)
```

Handles a V4L2 ioctl.

**Parameters**

- `struct file *file`: Pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file).
- `unsigned int cmd`: Ioctl name.
- `unsigned long int arg`: Ioctl argument.

**Description**

Method used to hancle an ioctl. Should be used to fill the
[`v4l2_ioctl_ops.unlocked_ioctl`](#c-struct-v4l2_ioctl_ops) on all V4L2 drivers.

---

# V4L2 Controls

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> The V4L2 control API seems simple enough, but quickly becomes very hard to implement correctly in drivers. But much of the code needed to handle controls is actually not driver specific and can be moved to the V4L core framework.

<a id="rst-v4l2-controls"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

The V4L2 control API seems simple enough, but quickly becomes very hard to implement correctly in drivers. But much of the code needed to handle controls is actually not driver specific and can be moved to the V4L core framework.

After all, the only part that a driver developer is interested in is:

1. How do I add a control?

2. How do I set the control's value? (i.e. s_ctrl)

And occasionally:

3. How do I get the control's value? (i.e. g_volatile_ctrl)

4. How do I validate the user's proposed control value? (i.e. try_ctrl)

All the rest is something that can be done centrally.

The control framework was created in order to implement all the rules of the V4L2 specification with respect to controls in a central place. And to make life as easy as possible for the driver developer.

Note that the control framework relies on the presence of a struct `v4l2_device` for V4L2 drivers and struct v4l2_subdev for sub-device drivers.

<a id="rst-objects-in-the-framework"></a>

## Objects in the framework

There are two main objects:

The `v4l2_ctrl` object describes the control properties and keeps track of the control's value (both the current value and the proposed new value).

`v4l2_ctrl_handler` is the object that keeps track of controls. It maintains a list of v4l2_ctrl objects that it owns and another list of references to controls, possibly to controls owned by other handlers.

<a id="rst-basic-usage-for-v4l2-and-sub-device-drivers"></a>

## Basic usage for V4L2 and sub-device drivers

1. Prepare the driver:



```c
#include <media/v4l2-ctrls.h>
```

1.1) Add the handler to your driver's top-level struct:

For V4L2 drivers:



```c
struct foo_dev {
        ...
        struct v4l2_device v4l2_dev;
        ...
        struct v4l2_ctrl_handler ctrl_handler;
        ...
};
```

For sub-device drivers:



```c
struct foo_dev {
        ...
        struct v4l2_subdev sd;
        ...
        struct v4l2_ctrl_handler ctrl_handler;
        ...
};
```

1.2) Initialize the handler:



```c
v4l2_ctrl_handler_init(&foo->ctrl_handler, nr_of_controls);
```

The second argument is a hint telling the function how many controls this handler is expected to handle. It will allocate a hashtable based on this information. It is a hint only.

1.3) Hook the control handler into the driver:

For V4L2 drivers:



```c
foo->v4l2_dev.ctrl_handler = &foo->ctrl_handler;
```

For sub-device drivers:



```c
foo->sd.ctrl_handler = &foo->ctrl_handler;
```

1.4) Clean up the handler at the end:



```c
v4l2_ctrl_handler_free(&foo->ctrl_handler);
```

`v4l2_ctrl_handler_free()` does not touch the handler's `error` field.

2. Add controls:

You add non-menu controls by calling `v4l2_ctrl_new_std()`:



```c
struct v4l2_ctrl *v4l2_ctrl_new_std(struct v4l2_ctrl_handler *hdl,
                const struct v4l2_ctrl_ops *ops,
                u32 id, s32 min, s32 max, u32 step, s32 def);
```

Menu and integer menu controls are added by calling `v4l2_ctrl_new_std_menu()`:



```c
struct v4l2_ctrl *v4l2_ctrl_new_std_menu(struct v4l2_ctrl_handler *hdl,
                const struct v4l2_ctrl_ops *ops,
                u32 id, s32 max, s32 skip_mask, s32 def);
```

Menu controls with a driver specific menu are added by calling `v4l2_ctrl_new_std_menu_items()`:



```c
struct v4l2_ctrl *v4l2_ctrl_new_std_menu_items(
                struct v4l2_ctrl_handler *hdl,
                const struct v4l2_ctrl_ops *ops, u32 id, s32 max,
                s32 skip_mask, s32 def, const char * const *qmenu);
```

Standard compound controls can be added by calling `v4l2_ctrl_new_std_compound()`:



```c
struct v4l2_ctrl *v4l2_ctrl_new_std_compound(struct v4l2_ctrl_handler *hdl,
                const struct v4l2_ctrl_ops *ops, u32 id,
                const union v4l2_ctrl_ptr p_def);
```

Integer menu controls with a driver specific menu can be added by calling `v4l2_ctrl_new_int_menu()`:



```c
struct v4l2_ctrl *v4l2_ctrl_new_int_menu(struct v4l2_ctrl_handler *hdl,
                const struct v4l2_ctrl_ops *ops,
                u32 id, s32 max, s32 def, const s64 *qmenu_int);
```

These functions are typically called right after the `v4l2_ctrl_handler_init()`:



```c
static const s64 exp_bias_qmenu[] = {
       -2, -1, 0, 1, 2
};
static const char * const test_pattern[] = {
        "Disabled",
        "Vertical Bars",
        "Solid Black",
        "Solid White",
};

v4l2_ctrl_handler_init(&foo->ctrl_handler, nr_of_controls);
v4l2_ctrl_new_std(&foo->ctrl_handler, &foo_ctrl_ops,
                V4L2_CID_BRIGHTNESS, 0, 255, 1, 128);
v4l2_ctrl_new_std(&foo->ctrl_handler, &foo_ctrl_ops,
                V4L2_CID_CONTRAST, 0, 255, 1, 128);
v4l2_ctrl_new_std_menu(&foo->ctrl_handler, &foo_ctrl_ops,
                V4L2_CID_POWER_LINE_FREQUENCY,
                V4L2_CID_POWER_LINE_FREQUENCY_60HZ, 0,
                V4L2_CID_POWER_LINE_FREQUENCY_DISABLED);
v4l2_ctrl_new_int_menu(&foo->ctrl_handler, &foo_ctrl_ops,
                V4L2_CID_EXPOSURE_BIAS,
                ARRAY_SIZE(exp_bias_qmenu) - 1,
                ARRAY_SIZE(exp_bias_qmenu) / 2 - 1,
                exp_bias_qmenu);
v4l2_ctrl_new_std_menu_items(&foo->ctrl_handler, &foo_ctrl_ops,
                V4L2_CID_TEST_PATTERN, ARRAY_SIZE(test_pattern) - 1, 0,
                0, test_pattern);
...
if (foo->ctrl_handler.error)
        return v4l2_ctrl_handler_free(&foo->ctrl_handler);
```

The `v4l2_ctrl_new_std()` function returns the v4l2_ctrl pointer to the new control, but if you do not need to access the pointer outside the control ops, then there is no need to store it.

The `v4l2_ctrl_new_std()` function will fill in most fields based on the control ID except for the min, max, step and default values. These are passed in the last four arguments. These values are driver specific while control attributes like type, name, flags are all global. The control's current value will be set to the default value.

The `v4l2_ctrl_new_std_menu()` function is very similar but it is used for menu controls. There is no min argument since that is always 0 for menu controls, and instead of a step there is a skip_mask argument: if bit X is 1, then menu item X is skipped.

The `v4l2_ctrl_new_int_menu()` function creates a new standard integer menu control with driver-specific items in the menu. It differs from v4l2_ctrl_new_std_menu in that it doesn't have the mask argument and takes as the last argument an array of signed 64-bit integers that form an exact menu item list.

The `v4l2_ctrl_new_std_menu_items()` function is very similar to v4l2_ctrl_new_std_menu but takes an extra parameter qmenu, which is the driver specific menu for an otherwise standard menu control. A good example for this control is the test pattern control for capture/display/sensors devices that have the capability to generate test patterns. These test patterns are hardware specific, so the contents of the menu will vary from device to device.

Note that if something fails, the function will return NULL or an error and set ctrl_handler-&gt;error to the error code. If ctrl_handler-&gt;error was already set, then it will just return and do nothing. This is also true for v4l2_ctrl_handler_init if it cannot allocate the internal data structure.

This makes it easy to init the handler and just add all controls and only check the error code at the end. Saves a lot of repetitive error checking.

It is recommended to add controls in ascending control ID order: it will be a bit faster that way.

3. Optionally force initial control setup:



```c
v4l2_ctrl_handler_setup(&foo->ctrl_handler);
```

This will call s_ctrl for all controls unconditionally. Effectively this initializes the hardware to the default control values. It is recommended that you do this as this ensures that both the internal data structures and the hardware are in sync.

4. Finally: implement the `v4l2_ctrl_ops`



```c
static const struct v4l2_ctrl_ops foo_ctrl_ops = {
        .s_ctrl = foo_s_ctrl,
};
```

Usually all you need is s_ctrl:



```c
static int foo_s_ctrl(struct v4l2_ctrl *ctrl)
{
        struct foo *state = container_of(ctrl->handler, struct foo, ctrl_handler);

        switch (ctrl->id) {
        case V4L2_CID_BRIGHTNESS:
                write_reg(0x123, ctrl->val);
                break;
        case V4L2_CID_CONTRAST:
                write_reg(0x456, ctrl->val);
                break;
        }
        return 0;
}
```

The control ops are called with the v4l2_ctrl pointer as argument. The new control value has already been validated, so all you need to do is to actually update the hardware registers.

You're done\! And this is sufficient for most of the drivers we have. No need to do any validation of control values, or implement QUERYCTRL, QUERY_EXT_CTRL and QUERYMENU. And G/S_CTRL as well as G/TRY/S_EXT_CTRLS are automatically supported.

> [!NOTE]
>
> The remainder sections deal with more advanced controls topics and scenarios. In practice the basic usage as described above is sufficient for most drivers.

<a id="rst-inheriting-sub-device-controls"></a>

## Inheriting Sub-device Controls

When a sub-device is registered with a V4L2 driver by calling v4l2_device_register_subdev() and the ctrl_handler fields of both v4l2_subdev and v4l2_device are set, then the controls of the subdev will become automatically available in the V4L2 driver as well. If the subdev driver contains controls that already exist in the V4L2 driver, then those will be skipped (so a V4L2 driver can always override a subdev control).

What happens here is that v4l2_device_register_subdev() calls v4l2_ctrl_add_handler() adding the controls of the subdev to the controls of v4l2_device.

<a id="rst-accessing-control-values"></a>

## Accessing Control Values

The following union is used inside the control framework to access control values:



```c
union v4l2_ctrl_ptr {
        s32 *p_s32;
        s64 *p_s64;
        char *p_char;
        void *p;
};
```

The v4l2_ctrl struct contains these fields that can be used to access both current and new values:



```c
s32 val;
struct {
        s32 val;
} cur;


union v4l2_ctrl_ptr p_new;
union v4l2_ctrl_ptr p_cur;
```

If the control has a simple s32 type, then:



```c
&ctrl->val == ctrl->p_new.p_s32
&ctrl->cur.val == ctrl->p_cur.p_s32
```

For all other types use ctrl-&gt;p_cur.p&lt;something&gt;. Basically the val and cur.val fields can be considered an alias since these are used so often.

Within the control ops you can freely use these. The val and cur.val speak for themselves. The p_char pointers point to character buffers of length ctrl-&gt;maximum + 1, and are always 0-terminated.

Unless the control is marked volatile the p_cur field points to the current cached control value. When you create a new control this value is made identical to the default value. After calling v4l2_ctrl_handler_setup() this value is passed to the hardware. It is generally a good idea to call this function.

Whenever a new value is set that new value is automatically cached. This means that most drivers do not need to implement the g_volatile_ctrl() op. The exception is for controls that return a volatile register such as a signal strength read-out that changes continuously. In that case you will need to implement g_volatile_ctrl like this:



```c
static int foo_g_volatile_ctrl(struct v4l2_ctrl *ctrl)
{
        switch (ctrl->id) {
        case V4L2_CID_BRIGHTNESS:
                ctrl->val = read_reg(0x123);
                break;
        }
}
```

Note that you use the 'new value' union as well in g_volatile_ctrl. In general controls that need to implement g_volatile_ctrl are read-only controls. If they are not, a V4L2_EVENT_CTRL_CH_VALUE will not be generated when the control changes.

To mark a control as volatile you have to set V4L2_CTRL_FLAG_VOLATILE:



```c
ctrl = v4l2_ctrl_new_std(&sd->ctrl_handler, ...);
if (ctrl)
        ctrl->flags |= V4L2_CTRL_FLAG_VOLATILE;
```

For try/s_ctrl the new values (i.e. as passed by the user) are filled in and you can modify them in try_ctrl or set them in s_ctrl. The 'cur' union contains the current value, which you can use (but not change\!) as well.

If s_ctrl returns 0 (OK), then the control framework will copy the new final values to the 'cur' union.

While in g_volatile/s/try_ctrl you can access the value of all controls owned by the same handler since the handler's lock is held. If you need to access the value of controls owned by other handlers, then you have to be very careful not to introduce deadlocks.

Outside of the control ops you have to go through to helper functions to get or set a single control value safely in your driver:



```c
s32 v4l2_ctrl_g_ctrl(struct v4l2_ctrl *ctrl);
int v4l2_ctrl_s_ctrl(struct v4l2_ctrl *ctrl, s32 val);
```

These functions go through the control framework just as VIDIOC_G/S_CTRL ioctls do. Don't use these inside the control ops g_volatile/s/try_ctrl, though, that will result in a deadlock since these helpers lock the handler as well.

You can also take the handler lock yourself:



```c
mutex_lock(&state->ctrl_handler.lock);
pr_info("String value is '%s'\n", ctrl1->p_cur.p_char);
pr_info("Integer value is '%s'\n", ctrl2->cur.val);
mutex_unlock(&state->ctrl_handler.lock);
```

<a id="rst-menu-controls"></a>

## Menu Controls

The v4l2_ctrl struct contains this union:



```c
union {
        u32 step;
        u32 menu_skip_mask;
};
```

For menu controls menu_skip_mask is used. What it does is that it allows you to easily exclude certain menu items. This is used in the VIDIOC_QUERYMENU implementation where you can return -EINVAL if a certain menu item is not present. Note that VIDIOC_QUERYCTRL always returns a step value of 1 for menu controls.

A good example is the MPEG Audio Layer II Bitrate menu control where the menu is a list of standardized possible bitrates. But in practice hardware implementations will only support a subset of those. By setting the skip mask you can tell the framework which menu items should be skipped. Setting it to 0 means that all menu items are supported.

You set this mask either through the v4l2_ctrl_config struct for a custom control, or by calling v4l2_ctrl_new_std_menu().

<a id="rst-custom-controls"></a>

## Custom Controls

Driver specific controls can be created using v4l2_ctrl_new_custom():



```c
static const struct v4l2_ctrl_config ctrl_filter = {
        .ops = &ctrl_custom_ops,
        .id = V4L2_CID_MPEG_CX2341X_VIDEO_SPATIAL_FILTER,
        .name = "Spatial Filter",
        .type = V4L2_CTRL_TYPE_INTEGER,
        .flags = V4L2_CTRL_FLAG_SLIDER,
        .max = 15,
        .step = 1,
};

ctrl = v4l2_ctrl_new_custom(&foo->ctrl_handler, &ctrl_filter, NULL);
```

The last argument is the priv pointer which can be set to driver-specific private data.

The v4l2_ctrl_config struct also has a field to set the is_private flag.

If the name field is not set, then the framework will assume this is a standard control and will fill in the name, type and flags fields accordingly.

<a id="rst-active-and-grabbed-controls"></a>

## Active and Grabbed Controls

If you get more complex relationships between controls, then you may have to activate and deactivate controls. For example, if the Chroma AGC control is on, then the Chroma Gain control is inactive. That is, you may set it, but the value will not be used by the hardware as long as the automatic gain control is on. Typically user interfaces can disable such input fields.

You can set the 'active' status using v4l2_ctrl_activate(). By default all controls are active. Note that the framework does not check for this flag. It is meant purely for GUIs. The function is typically called from within s_ctrl.

The other flag is the 'grabbed' flag. A grabbed control means that you cannot change it because it is in use by some resource. Typical examples are MPEG bitrate controls that cannot be changed while capturing is in progress.

If a control is set to 'grabbed' using v4l2_ctrl_grab(), then the framework will return -EBUSY if an attempt is made to set this control. The v4l2_ctrl_grab() function is typically called from the driver when it starts or stops streaming.

<a id="rst-control-clusters"></a>

## Control Clusters

By default all controls are independent from the others. But in more complex scenarios you can get dependencies from one control to another. In that case you need to 'cluster' them:



```c
struct foo {
        struct v4l2_ctrl_handler ctrl_handler;
#define AUDIO_CL_VOLUME (0)
#define AUDIO_CL_MUTE   (1)
        struct v4l2_ctrl *audio_cluster[2];
        ...
};

state->audio_cluster[AUDIO_CL_VOLUME] =
        v4l2_ctrl_new_std(&state->ctrl_handler, ...);
state->audio_cluster[AUDIO_CL_MUTE] =
        v4l2_ctrl_new_std(&state->ctrl_handler, ...);
v4l2_ctrl_cluster(ARRAY_SIZE(state->audio_cluster), state->audio_cluster);
```

From now on whenever one or more of the controls belonging to the same cluster is set (or 'gotten', or 'tried'), only the control ops of the first control ('volume' in this example) is called. You effectively create a new composite control. Similar to how a 'struct' works in C.

So when s_ctrl is called with V4L2_CID_AUDIO_VOLUME as argument, you should set all two controls belonging to the audio_cluster:



```c
static int foo_s_ctrl(struct v4l2_ctrl *ctrl)
{
        struct foo *state = container_of(ctrl->handler, struct foo, ctrl_handler);

        switch (ctrl->id) {
        case V4L2_CID_AUDIO_VOLUME: {
                struct v4l2_ctrl *mute = ctrl->cluster[AUDIO_CL_MUTE];

                write_reg(0x123, mute->val ? 0 : ctrl->val);
                break;
        }
        case V4L2_CID_CONTRAST:
                write_reg(0x456, ctrl->val);
                break;
        }
        return 0;
}
```

In the example above the following are equivalent for the VOLUME case:



```c
ctrl == ctrl->cluster[AUDIO_CL_VOLUME] == state->audio_cluster[AUDIO_CL_VOLUME]
ctrl->cluster[AUDIO_CL_MUTE] == state->audio_cluster[AUDIO_CL_MUTE]
```

In practice using cluster arrays like this becomes very tiresome. So instead the following equivalent method is used:



```c
struct {
        /* audio cluster */
        struct v4l2_ctrl *volume;
        struct v4l2_ctrl *mute;
};
```

The anonymous struct is used to clearly 'cluster' these two control pointers, but it serves no other purpose. The effect is the same as creating an array with two control pointers. So you can just do:



```c
state->volume = v4l2_ctrl_new_std(&state->ctrl_handler, ...);
state->mute = v4l2_ctrl_new_std(&state->ctrl_handler, ...);
v4l2_ctrl_cluster(2, &state->volume);
```

And in foo_s_ctrl you can use these pointers directly: state-&gt;mute-&gt;val.

Note that controls in a cluster may be NULL. For example, if for some reason mute was never added (because the hardware doesn't support that particular feature), then mute will be NULL. So in that case we have a cluster of 2 controls, of which only 1 is actually instantiated. The only restriction is that the first control of the cluster must always be present, since that is the 'master' control of the cluster. The master control is the one that identifies the cluster and that provides the pointer to the v4l2_ctrl_ops struct that is used for that cluster.

Obviously, all controls in the cluster array must be initialized to either a valid control or to NULL.

In rare cases you might want to know which controls of a cluster actually were set explicitly by the user. For this you can check the 'is_new' flag of each control. For example, in the case of a volume/mute cluster the 'is_new' flag of the mute control would be set if the user called VIDIOC_S_CTRL for mute only. If the user would call VIDIOC_S_EXT_CTRLS for both mute and volume controls, then the 'is_new' flag would be 1 for both controls.

The 'is_new' flag is always 1 when called from v4l2_ctrl_handler_setup().

<a id="rst-handling-autogain-gain-type-controls-with-auto-clusters"></a>

## Handling autogain/gain-type Controls with Auto Clusters

A common type of control cluster is one that handles 'auto-foo/foo'-type controls. Typical examples are autogain/gain, autoexposure/exposure, autowhitebalance/red balance/blue balance. In all cases you have one control that determines whether another control is handled automatically by the hardware, or whether it is under manual control from the user.

If the cluster is in automatic mode, then the manual controls should be marked inactive and volatile. When the volatile controls are read the g_volatile_ctrl operation should return the value that the hardware's automatic mode set up automatically.

If the cluster is put in manual mode, then the manual controls should become active again and the volatile flag is cleared (so g_volatile_ctrl is no longer called while in manual mode). In addition just before switching to manual mode the current values as determined by the auto mode are copied as the new manual values.

Finally the V4L2_CTRL_FLAG_UPDATE should be set for the auto control since changing that control affects the control flags of the manual controls.

In order to simplify this a special variation of v4l2_ctrl_cluster was introduced:



```c
void v4l2_ctrl_auto_cluster(unsigned ncontrols, struct v4l2_ctrl **controls,
                            u8 manual_val, bool set_volatile);
```

The first two arguments are identical to v4l2_ctrl_cluster. The third argument tells the framework which value switches the cluster into manual mode. The last argument will optionally set V4L2_CTRL_FLAG_VOLATILE for the non-auto controls. If it is false, then the manual controls are never volatile. You would typically use that if the hardware does not give you the option to read back to values as determined by the auto mode (e.g. if autogain is on, the hardware doesn't allow you to obtain the current gain value).

The first control of the cluster is assumed to be the 'auto' control.

Using this function will ensure that you don't need to handle all the complex flag and volatile handling.

<a id="rst-vidioc-log-status-support"></a>

## VIDIOC_LOG_STATUS Support

This ioctl allow you to dump the current status of a driver to the kernel log. The v4l2_ctrl_handler_log_status(ctrl_handler, prefix) can be used to dump the value of the controls owned by the given handler to the log. You can supply a prefix as well. If the prefix didn't end with a space, then ': ' will be added for you.

<a id="rst-different-handlers-for-different-video-nodes"></a>

## Different Handlers for Different Video Nodes

Usually the V4L2 driver has just one control handler that is global for all video nodes. But you can also specify different control handlers for different video nodes. You can do that by manually setting the ctrl_handler field of struct video_device.

That is no problem if there are no subdevs involved but if there are, then you need to block the automatic merging of subdev controls to the global control handler. You do that by simply setting the ctrl_handler field in struct v4l2_device to NULL. Now v4l2_device_register_subdev() will no longer merge subdev controls.

After each subdev was added, you will then have to call v4l2_ctrl_add_handler manually to add the subdev's control handler (sd-&gt;ctrl_handler) to the desired control handler. This control handler may be specific to the video_device or for a subset of video_device's. For example: the radio device nodes only have audio controls, while the video and vbi device nodes share the same control handler for the audio and video controls.

If you want to have one handler (e.g. for a radio device node) have a subset of another handler (e.g. for a video device node), then you should first add the controls to the first handler, add the other controls to the second handler and finally add the first handler to the second. For example:



```c
v4l2_ctrl_new_std(&radio_ctrl_handler, &radio_ops, V4L2_CID_AUDIO_VOLUME, ...);
v4l2_ctrl_new_std(&radio_ctrl_handler, &radio_ops, V4L2_CID_AUDIO_MUTE, ...);
v4l2_ctrl_new_std(&video_ctrl_handler, &video_ops, V4L2_CID_BRIGHTNESS, ...);
v4l2_ctrl_new_std(&video_ctrl_handler, &video_ops, V4L2_CID_CONTRAST, ...);
v4l2_ctrl_add_handler(&video_ctrl_handler, &radio_ctrl_handler, NULL);
```

The last argument to v4l2_ctrl_add_handler() is a filter function that allows you to filter which controls will be added. Set it to NULL if you want to add all controls.

Or you can add specific controls to a handler:



```c
volume = v4l2_ctrl_new_std(&video_ctrl_handler, &ops, V4L2_CID_AUDIO_VOLUME, ...);
v4l2_ctrl_new_std(&video_ctrl_handler, &ops, V4L2_CID_BRIGHTNESS, ...);
v4l2_ctrl_new_std(&video_ctrl_handler, &ops, V4L2_CID_CONTRAST, ...);
```

What you should not do is make two identical controls for two handlers. For example:



```c
v4l2_ctrl_new_std(&radio_ctrl_handler, &radio_ops, V4L2_CID_AUDIO_MUTE, ...);
v4l2_ctrl_new_std(&video_ctrl_handler, &video_ops, V4L2_CID_AUDIO_MUTE, ...);
```

This would be bad since muting the radio would not change the video mute control. The rule is to have one control for each hardware 'knob' that you can twiddle.

<a id="rst-finding-controls"></a>

## Finding Controls

Normally you have created the controls yourself and you can store the struct v4l2_ctrl pointer into your own struct.

But sometimes you need to find a control from another handler that you do not own. For example, if you have to find a volume control from a subdev.

You can do that by calling v4l2_ctrl_find:



```c
struct v4l2_ctrl *volume;

volume = v4l2_ctrl_find(sd->ctrl_handler, V4L2_CID_AUDIO_VOLUME);
```

Since v4l2_ctrl_find will lock the handler you have to be careful where you use it. For example, this is not a good idea:



```c
struct v4l2_ctrl_handler ctrl_handler;

v4l2_ctrl_new_std(&ctrl_handler, &video_ops, V4L2_CID_BRIGHTNESS, ...);
v4l2_ctrl_new_std(&ctrl_handler, &video_ops, V4L2_CID_CONTRAST, ...);
```

...and in video_ops.s_ctrl:



```c
case V4L2_CID_BRIGHTNESS:
        contrast = v4l2_find_ctrl(&ctrl_handler, V4L2_CID_CONTRAST);
        ...
```

When s_ctrl is called by the framework the ctrl_handler.lock is already taken, so attempting to find another control from the same handler will deadlock.

It is recommended not to use this function from inside the control ops.

<a id="rst-preventing-controls-inheritance"></a>

## Preventing Controls inheritance

When one control handler is added to another using v4l2_ctrl_add_handler, then by default all controls from one are merged to the other. But a subdev might have low-level controls that make sense for some advanced embedded system, but not when it is used in consumer-level hardware. In that case you want to keep those low-level controls local to the subdev. You can do this by simply setting the 'is_private' flag of the control to 1:



```c
static const struct v4l2_ctrl_config ctrl_private = {
        .ops = &ctrl_custom_ops,
        .id = V4L2_CID_...,
        .name = "Some Private Control",
        .type = V4L2_CTRL_TYPE_INTEGER,
        .max = 15,
        .step = 1,
        .is_private = 1,
};

ctrl = v4l2_ctrl_new_custom(&foo->ctrl_handler, &ctrl_private, NULL);
```

These controls will now be skipped when v4l2_ctrl_add_handler is called.

<a id="rst-v4l2-ctrl-type-ctrl-class-controls"></a>

## V4L2_CTRL_TYPE_CTRL_CLASS Controls

Controls of this type can be used by GUIs to get the name of the control class. A fully featured GUI can make a dialog with multiple tabs with each tab containing the controls belonging to a particular control class. The name of each tab can be found by querying a special control with ID &lt;control class \| 1&gt;.

Drivers do not have to care about this. The framework will automatically add a control of this type whenever the first control belonging to a new control class is added.

<a id="rst-adding-notify-callbacks"></a>

## Adding Notify Callbacks

Sometimes the platform or bridge driver needs to be notified when a control from a sub-device driver changes. You can set a notify callback by calling this function:



```c
void v4l2_ctrl_notify(struct v4l2_ctrl *ctrl,
        void (*notify)(struct v4l2_ctrl *ctrl, void *priv), void *priv);
```

Whenever the give control changes value the notify callback will be called with a pointer to the control and the priv pointer that was passed with v4l2_ctrl_notify. Note that the control's handler lock is held when the notify function is called.

There can be only one notify function per control handler. Any attempt to set another notify function will cause a WARN_ON.

<a id="rst-v4l2-ctrl-functions-and-data-structures"></a>

## v4l2_ctrl functions and data structures


#### <a id="c-union-v4l2_ctrl_ptr"></a>`union v4l2_ctrl_ptr`

A pointer to a control value.

**Definition**

```c
union v4l2_ctrl_ptr {
    s32 *p_s32;
    s64 *p_s64;
    u8 *p_u8;
    u16 *p_u16;
    u32 *p_u32;
    char *p_char;
    struct v4l2_ctrl_mpeg2_sequence *p_mpeg2_sequence;
    struct v4l2_ctrl_mpeg2_picture *p_mpeg2_picture;
    struct v4l2_ctrl_mpeg2_quantisation *p_mpeg2_quantisation;
    struct v4l2_ctrl_fwht_params *p_fwht_params;
    struct v4l2_ctrl_h264_sps *p_h264_sps;
    struct v4l2_ctrl_h264_pps *p_h264_pps;
    struct v4l2_ctrl_h264_scaling_matrix *p_h264_scaling_matrix;
    struct v4l2_ctrl_h264_slice_params *p_h264_slice_params;
    struct v4l2_ctrl_h264_decode_params *p_h264_decode_params;
    struct v4l2_ctrl_h264_pred_weights *p_h264_pred_weights;
    struct v4l2_ctrl_vp8_frame *p_vp8_frame;
    struct v4l2_ctrl_hevc_sps *p_hevc_sps;
    struct v4l2_ctrl_hevc_pps *p_hevc_pps;
    struct v4l2_ctrl_hevc_slice_params *p_hevc_slice_params;
    struct v4l2_ctrl_vp9_compressed_hdr *p_vp9_compressed_hdr_probs;
    struct v4l2_ctrl_vp9_frame *p_vp9_frame;
    struct v4l2_ctrl_hdr10_cll_info *p_hdr10_cll;
    struct v4l2_ctrl_hdr10_mastering_display *p_hdr10_mastering;
    struct v4l2_area *p_area;
    struct v4l2_ctrl_av1_sequence *p_av1_sequence;
    struct v4l2_ctrl_av1_tile_group_entry *p_av1_tile_group_entry;
    struct v4l2_ctrl_av1_frame *p_av1_frame;
    struct v4l2_ctrl_av1_film_grain *p_av1_film_grain;
    struct v4l2_rect *p_rect;
    void *p;
    const void *p_const;
};
```

**Members**

- `p_s32`: Pointer to a 32-bit signed value.
- `p_s64`: Pointer to a 64-bit signed value.
- `p_u8`: Pointer to a 8-bit unsigned value.
- `p_u16`: Pointer to a 16-bit unsigned value.
- `p_u32`: Pointer to a 32-bit unsigned value.
- `p_char`: Pointer to a string.
- `p_mpeg2_sequence`: Pointer to a MPEG2 sequence structure.
- `p_mpeg2_picture`: Pointer to a MPEG2 picture structure.
- `p_mpeg2_quantisation`: Pointer to a MPEG2 quantisation data structure.
- `p_fwht_params`: Pointer to a FWHT stateless parameters structure.
- `p_h264_sps`: Pointer to a struct v4l2_ctrl_h264_sps.
- `p_h264_pps`: Pointer to a struct v4l2_ctrl_h264_pps.
- `p_h264_scaling_matrix`: Pointer to a struct v4l2_ctrl_h264_scaling_matrix.
- `p_h264_slice_params`: Pointer to a struct v4l2_ctrl_h264_slice_params.
- `p_h264_decode_params`: Pointer to a struct v4l2_ctrl_h264_decode_params.
- `p_h264_pred_weights`: Pointer to a struct v4l2_ctrl_h264_pred_weights.
- `p_vp8_frame`: Pointer to a VP8 frame params structure.
- `p_hevc_sps`: Pointer to an HEVC sequence parameter set structure.
- `p_hevc_pps`: Pointer to an HEVC picture parameter set structure.
- `p_hevc_slice_params`: Pointer to an HEVC slice parameters structure.
- `p_vp9_compressed_hdr_probs`: Pointer to a VP9 frame compressed header probs structure.
- `p_vp9_frame`: Pointer to a VP9 frame params structure.
- `p_hdr10_cll`: Pointer to an HDR10 Content Light Level structure.
- `p_hdr10_mastering`: Pointer to an HDR10 Mastering Display structure.
- `p_area`: Pointer to an area.
- `p_av1_sequence`: Pointer to an AV1 sequence structure.
- `p_av1_tile_group_entry`: Pointer to an AV1 tile group entry structure.
- `p_av1_frame`: Pointer to an AV1 frame structure.
- `p_av1_film_grain`: Pointer to an AV1 film grain structure.
- `p_rect`: Pointer to a rectangle.
- `p`: Pointer to a compound value.
- `p_const`: Pointer to a constant compound value.

#### <a id="c-v4l2_ctrl_ptr_create"></a>`v4l2_ctrl_ptr_create()`

```c
union v4l2_ctrl_ptr v4l2_ctrl_ptr_create(void *ptr)
```

Helper function to return a v4l2_ctrl_ptr from a void pointer

**Parameters**

- `void *ptr`: The void pointer

#### <a id="c-struct-v4l2_ctrl_ops"></a>`struct v4l2_ctrl_ops`

The control operations that the driver has to provide.

**Definition**

```c
struct v4l2_ctrl_ops {
    int (*g_volatile_ctrl)(struct v4l2_ctrl *ctrl);
    int (*try_ctrl)(struct v4l2_ctrl *ctrl);
    int (*s_ctrl)(struct v4l2_ctrl *ctrl);
};
```

**Members**

- `g_volatile_ctrl`: Get a new value for this control. Generally only relevant
  for volatile (and usually read-only) controls such as a control
  that returns the current signal strength which changes
  continuously.
  If not set, then the currently cached value will be returned.
- `try_ctrl`: Test whether the control's value is valid. Only relevant when
  the usual min/max/step checks are not sufficient.
- `s_ctrl`: Actually set the new control value. s_ctrl is compulsory. The
  ctrl->handler->lock is held when these ops are called, so no
  one else can access controls owned by that handler.

#### <a id="c-struct-v4l2_ctrl_type_ops"></a>`struct v4l2_ctrl_type_ops`

The control type operations that the driver has to provide.

**Definition**

```c
struct v4l2_ctrl_type_ops {
    bool (*equal)(const struct v4l2_ctrl *ctrl, union v4l2_ctrl_ptr ptr1, union v4l2_ctrl_ptr ptr2);
    void (*init)(const struct v4l2_ctrl *ctrl, u32 from_idx, union v4l2_ctrl_ptr ptr);
    void (*minimum)(const struct v4l2_ctrl *ctrl, u32 idx, union v4l2_ctrl_ptr ptr);
    void (*maximum)(const struct v4l2_ctrl *ctrl, u32 idx, union v4l2_ctrl_ptr ptr);
    void (*log)(const struct v4l2_ctrl *ctrl);
    int (*validate)(const struct v4l2_ctrl *ctrl, union v4l2_ctrl_ptr ptr);
};
```

**Members**

- `equal`: return true if all ctrl->elems array elements are equal.
- `init`: initialize the value for array elements from from_idx to ctrl->elems.
- `minimum`: set the value to the minimum value of the control.
- `maximum`: set the value to the maximum value of the control.
- `log`: log the value.
- `validate`: validate the value for ctrl->new_elems array elements.
  Return 0 on success and a negative value otherwise.

#### <a id="c-v4l2_ctrl_notify_fnc"></a>`v4l2_ctrl_notify_fnc()`

```c
typedef void v4l2_ctrl_notify_fnc(struct v4l2_ctrl *ctrl, void *priv)
```

typedef for a notify argument with a function that should be called when a control value has changed.

**Parameters**

- `struct v4l2_ctrl *ctrl`: pointer to struct [`v4l2_ctrl`](#c-struct-v4l2_ctrl)
- `void *priv`: control private data

**Description**

This typedef definition is used as an argument to [`v4l2_ctrl_notify()`](#c-v4l2_ctrl_notify)
and as an argument at struct [`v4l2_ctrl_handler`](#c-struct-v4l2_ctrl_handler).

#### <a id="c-struct-v4l2_ctrl"></a>`struct v4l2_ctrl`

The control structure.

**Definition**

```c
struct v4l2_ctrl {
    struct list_head node;
    struct list_head ev_subs;
    struct v4l2_ctrl_handler *handler;
    struct v4l2_ctrl **cluster;
    unsigned int ncontrols;
    unsigned int done:1;
    unsigned int is_new:1;
    unsigned int has_changed:1;
    unsigned int is_private:1;
    unsigned int is_auto:1;
    unsigned int is_int:1;
    unsigned int is_string:1;
    unsigned int is_ptr:1;
    unsigned int is_array:1;
    unsigned int is_dyn_array:1;
    unsigned int has_volatiles:1;
    unsigned int call_notify:1;
    unsigned int manual_mode_value:8;
    const struct v4l2_ctrl_ops *ops;
    const struct v4l2_ctrl_type_ops *type_ops;
    u32 id;
    const char *name;
    enum v4l2_ctrl_type type;
    s64 minimum, maximum, default_value;
    u32 elems;
    u32 elem_size;
    u32 new_elems;
    u32 dims[V4L2_CTRL_MAX_DIMS];
    u32 nr_of_dims;
    union {
        u64 step;
        u64 menu_skip_mask;
    };
    union {
        const char * const *qmenu;
        const s64 *qmenu_int;
    };
    unsigned long flags;
    void *priv;
    void *p_array;
    u32 p_array_alloc_elems;
    s32 val;
    struct {
        s32 val;
    } cur;
    union v4l2_ctrl_ptr p_def;
    union v4l2_ctrl_ptr p_min;
    union v4l2_ctrl_ptr p_max;
    union v4l2_ctrl_ptr p_new;
    union v4l2_ctrl_ptr p_cur;
};
```

**Members**

- `node`: The list node.
- `ev_subs`: The list of control event subscriptions.
- `handler`: The handler that owns the control.
- `cluster`: Point to start of cluster array.
- `ncontrols`: Number of controls in cluster array.
- `done`: Internal flag: set for each processed control.
- `is_new`: Set when the user specified a new value for this control. It
  is also set when called from [`v4l2_ctrl_handler_setup()`](#c-v4l2_ctrl_handler_setup). Drivers
  should never set this flag.
- `has_changed`: Set when the current value differs from the new value. Drivers
  should never use this flag.
- `is_private`: If set, then this control is private to its handler and it
  will not be added to any other handlers. Drivers can set
  this flag.
- `is_auto`: If set, then this control selects whether the other cluster
  members are in 'automatic' mode or 'manual' mode. This is
  used for autogain/gain type clusters. Drivers should never
  set this flag directly.
- `is_int`: If set, then this control has a simple integer value (i.e. it
  uses ctrl->val).
- `is_string`: If set, then this control has type `V4L2_CTRL_TYPE_STRING`.
- `is_ptr`: If set, then this control is an array and/or has type >=
  `V4L2_CTRL_COMPOUND_TYPES`
  and/or has type `V4L2_CTRL_TYPE_STRING`. In other words, [`struct v4l2_ext_control`](/kernel/userspace/userspace-api/media-v4l/vidioc-g-ext-ctrls.md#c-v4l2_ext_control) uses field p to point to the data.
- `is_array`: If set, then this control contains an N-dimensional array.
- `is_dyn_array`: If set, then this control contains a dynamically sized 1-dimensional array.
  If this is set, then **is_array** is also set.
- `has_volatiles`: If set, then one or more members of the cluster are volatile.
  Drivers should never touch this flag.
- `call_notify`: If set, then call the handler's notify function whenever the
  control's value changes.
- `manual_mode_value`: If the is_auto flag is set, then this is the value
  of the auto control that determines if that control is in
  manual mode. So if the value of the auto control equals this
  value, then the whole cluster is in manual mode. Drivers should
  never set this flag directly.
- `ops`: The control ops.
- `type_ops`: The control type ops.
- `id`: The control ID.
- `name`: The control name.
- `type`: The control type.
- `minimum`: The control's minimum value.
- `maximum`: The control's maximum value.
- `default_value`: The control's default value.
- `elems`: The number of elements in the N-dimensional array.
- `elem_size`: The size in bytes of the control.
- `new_elems`: The number of elements in p_new. This is the same as **elems**,
  except for dynamic arrays. In that case it is in the range of
  1 to **p_array_alloc_elems**.
- `dims`: The size of each dimension.
- `nr_of_dims`: The number of dimensions in **dims**.
- `{unnamed_union}`: anonymous
- `step`: The control's step value for non-menu controls.
- `menu_skip_mask`: The control's skip mask for menu controls. This makes it
  easy to skip menu items that are not valid. If bit X is set,
  then menu item X is skipped. Of course, this only works for
  menus with \<= 32 menu items. There are no menus that come
  close to that number, so this is OK. Should we ever need more,
  then this will have to be extended to a u64 or a bit array.
- `{unnamed_union}`: anonymous
- `qmenu`: A const char * array for all menu items. Array entries that are
  empty strings ("") correspond to non-existing menu items (this
  is in addition to the menu_skip_mask above). The last entry
  must be NULL.
  Used only if the **type** is `V4L2_CTRL_TYPE_MENU`.
- `qmenu_int`: A 64-bit integer array for with integer menu items.
  The size of array must be equal to the menu size, e. g.:
  ceil(\frac{maximum - minimum}{step}) + 1.
  Used only if the **type** is `V4L2_CTRL_TYPE_INTEGER_MENU`.
- `flags`: The control's flags.
- `priv`: The control's private pointer. For use by the driver. It is
  untouched by the control framework. Note that this pointer is
  not freed when the control is deleted. Should this be needed
  then a new internal bitfield can be added to tell the framework
  to free this pointer.
- `p_array`: Pointer to the allocated array. Only valid if **is_array** is true.
- `p_array_alloc_elems`: The number of elements in the allocated
  array for both the cur and new values. So **p_array** is actually
  sized for 2 * **p_array_alloc_elems** * **elem_size**. Only valid if
  **is_array** is true.
- `val`: The control's new s32 value.
- `cur`: Structure to store the current value.
- `cur.val`: The control's current value, if the **type** is represented via
  a u32 integer (see [`enum v4l2_ctrl_type`](/kernel/userspace/userspace-api/media-v4l/vidioc-queryctrl.md#c-v4l2_ctrl_type)).
- `p_def`: The control's default value represented via a union which
  provides a standard way of accessing control types
  through a pointer (for compound controls only).
- `p_min`: The control's minimum value represented via a union which
  provides a standard way of accessing control types
  through a pointer (for compound controls only).
- `p_max`: The control's maximum value represented via a union which
  provides a standard way of accessing control types
  through a pointer (for compound controls only).
- `p_new`: The control's new value represented via a union which provides
  a standard way of accessing control types
  through a pointer.
- `p_cur`: The control's current value represented via a union which
  provides a standard way of accessing control types
  through a pointer.

#### <a id="c-struct-v4l2_ctrl_ref"></a>`struct v4l2_ctrl_ref`

The control reference.

**Definition**

```c
struct v4l2_ctrl_ref {
    struct list_head node;
    struct v4l2_ctrl_ref *next;
    struct v4l2_ctrl *ctrl;
    struct v4l2_ctrl_helper *helper;
    bool from_other_dev;
    bool req_done;
    bool p_req_valid;
    bool p_req_array_enomem;
    u32 p_req_array_alloc_elems;
    u32 p_req_elems;
    union v4l2_ctrl_ptr p_req;
};
```

**Members**

- `node`: List node for the sorted list.
- `next`: Single-link list node for the hash.
- `ctrl`: The actual control information.
- `helper`: Pointer to helper struct. Used internally in
  `prepare_ext_ctrls` function at `v4l2-ctrl.c`.
- `from_other_dev`: If true, then **ctrl** was defined in another
  device than the [`struct v4l2_ctrl_handler`](#c-struct-v4l2_ctrl_handler).
- `req_done`: Internal flag: if the control handler containing this control
  reference is bound to a media request, then this is set when
  the control has been applied. This prevents applying controls
  from a cluster with multiple controls twice (when the first
  control of a cluster is applied, they all are).
- `p_req_valid`: If set, then p_req contains the control value for the request.
- `p_req_array_enomem`: If set, then p_req is invalid since allocating space for
  an array failed. Attempting to read this value shall
  result in ENOMEM. Only valid if ctrl->is_array is true.
- `p_req_array_alloc_elems`: The number of elements allocated for the
  array. Only valid if **p_req_valid** and ctrl->is_array are
  true.
- `p_req_elems`: The number of elements in **p_req**. This is the same as
  ctrl->elems, except for dynamic arrays. In that case it is in
  the range of 1 to **p_req_array_alloc_elems**. Only valid if
  **p_req_valid** is true.
- `p_req`: If the control handler containing this control reference
  is bound to a media request, then this points to the
  value of the control that must be applied when the request
  is executed, or to the value of the control at the time
  that the request was completed. If **p_req_valid** is false,
  then this control was never set for this request and the
  control will not be updated when this request is applied.

**Description**

Each control handler has a list of these refs. The list_head is used to
keep a sorted-by-control-ID list of all controls, while the next pointer
is used to link the control in the hash's bucket.

#### <a id="c-struct-v4l2_ctrl_handler"></a>`struct v4l2_ctrl_handler`

The control handler keeps track of all the controls: both the controls owned by the handler and those inherited from other handlers.

**Definition**

```c
struct v4l2_ctrl_handler {
    struct mutex _lock;
    struct mutex *lock;
    struct list_head ctrls;
    struct list_head ctrl_refs;
    struct v4l2_ctrl_ref *cached;
    struct v4l2_ctrl_ref **buckets;
    v4l2_ctrl_notify_fnc notify;
    void *notify_priv;
    u16 nr_of_buckets;
    int error;
    bool request_is_queued;
    struct list_head requests;
    struct list_head requests_queued;
    struct media_request_object req_obj;
};
```

**Members**

- `_lock`: Default for "lock".
- `lock`: Lock to control access to this handler and its controls.
  May be replaced by the user right after init.
- `ctrls`: The list of controls owned by this handler.
- `ctrl_refs`: The list of control references.
- `cached`: The last found control reference. It is common that the same
  control is needed multiple times, so this is a simple
  optimization.
- `buckets`: Buckets for the hashing. Allows for quick control lookup.
- `notify`: A notify callback that is called whenever the control changes
  value.
  Note that the handler's lock is held when the notify function
  is called!
- `notify_priv`: Passed as argument to the v4l2_ctrl notify callback.
- `nr_of_buckets`: Total number of buckets in the array.
- `error`: The error code of the first failed control addition.
- `request_is_queued`: True if the request was queued.
- `requests`: List to keep track of open control handler request objects.
  For the parent control handler (**req_obj.ops** == NULL) this
  is the list header. When the parent control handler is
  removed, it has to unbind and put all these requests since
  they refer to the parent.
- `requests_queued`: List of the queued requests. This determines the order
  in which these controls are applied. Once the request is
  completed it is removed from this list.
- `req_obj`: The [`struct media_request_object`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_request_object), used to link into a
  [`struct media_request`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_request). This request object has a refcount.

#### <a id="c-struct-v4l2_ctrl_config"></a>`struct v4l2_ctrl_config`

Control configuration structure.

**Definition**

```c
struct v4l2_ctrl_config {
    const struct v4l2_ctrl_ops *ops;
    const struct v4l2_ctrl_type_ops *type_ops;
    u32 id;
    const char *name;
    enum v4l2_ctrl_type type;
    s64 min;
    s64 max;
    u64 step;
    s64 def;
    union v4l2_ctrl_ptr p_def;
    union v4l2_ctrl_ptr p_min;
    union v4l2_ctrl_ptr p_max;
    u32 dims[V4L2_CTRL_MAX_DIMS];
    u32 elem_size;
    u32 flags;
    u64 menu_skip_mask;
    const char * const *qmenu;
    const s64 *qmenu_int;
    unsigned int is_private:1;
};
```

**Members**

- `ops`: The control ops.
- `type_ops`: The control type ops. Only needed for compound controls.
- `id`: The control ID.
- `name`: The control name.
- `type`: The control type.
- `min`: The control's minimum value.
- `max`: The control's maximum value.
- `step`: The control's step value for non-menu controls.
- `def`: The control's default value.
- `p_def`: The control's default value for compound controls.
- `p_min`: The control's minimum value for compound controls.
- `p_max`: The control's maximum value for compound controls.
- `dims`: The size of each dimension.
- `elem_size`: The size in bytes of the control.
- `flags`: The control's flags.
- `menu_skip_mask`: The control's skip mask for menu controls. This makes it
  easy to skip menu items that are not valid. If bit X is set,
  then menu item X is skipped. Of course, this only works for
  menus with \<= 64 menu items. There are no menus that come
  close to that number, so this is OK. Should we ever need more,
  then this will have to be extended to a bit array.
- `qmenu`: A const char * array for all menu items. Array entries that are
  empty strings ("") correspond to non-existing menu items (this
  is in addition to the menu_skip_mask above). The last entry
  must be NULL.
- `qmenu_int`: A const s64 integer array for all menu items of the type
  V4L2_CTRL_TYPE_INTEGER_MENU.
- `is_private`: If set, then this control is private to its handler and it
  will not be added to any other handlers.

#### <a id="c-v4l2_ctrl_fill"></a>`v4l2_ctrl_fill()`

```c
void v4l2_ctrl_fill(u32 id, const char **name, enum v4l2_ctrl_type *type, s64 *min, s64 *max, u64 *step, s64 *def, u32 *flags)
```

Fill in the control fields based on the control ID.

**Parameters**

- `u32 id`: ID of the control
- `const char **name`: pointer to be filled with a string with the name of the control
- `enum v4l2_ctrl_type *type`: pointer for storing the type of the control
- `s64 *min`: pointer for storing the minimum value for the control
- `s64 *max`: pointer for storing the maximum value for the control
- `u64 *step`: pointer for storing the control step
- `s64 *def`: pointer for storing the default value for the control
- `u32 *flags`: pointer for storing the flags to be used on the control

**Description**

This works for all standard V4L2 controls.
For non-standard controls it will only fill in the given arguments
and **name** content will be set to `NULL`.

This function will overwrite the contents of **name**, **type** and **flags**.
The contents of **min**, **max**, **step** and **def** may be modified depending on
the type.

> [!NOTE]
> Do not use in drivers! It is used internally for backwards compatibility
> control handling only. Once all drivers are converted to use the new
> control framework this function will no longer be exported.

#### <a id="c-v4l2_ctrl_handler_init_class"></a>`v4l2_ctrl_handler_init_class()`

```c
int v4l2_ctrl_handler_init_class(struct v4l2_ctrl_handler *hdl, unsigned int nr_of_controls_hint, struct lock_class_key *key, const char *name)
```

Initialize the control handler.

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: The control handler.
- `unsigned int nr_of_controls_hint`: A hint of how many controls this handler is
  expected to refer to. This is the total number, so including
  any inherited controls. It doesn't have to be precise, but if
  it is way off, then you either waste memory (too many buckets
  are allocated) or the control lookup becomes slower (not enough
  buckets are allocated, so there are more slow list lookups).
  It will always work, though.
- `struct lock_class_key *key`: Used by the lock validator if CONFIG_LOCKDEP is set.
- `const char *name`: Used by the lock validator if CONFIG_LOCKDEP is set.

**Description**

> [!IMPORTANT]
> Never use this call directly, always use the [`v4l2_ctrl_handler_init()`](#c-v4l2_ctrl_handler_init)
> macro that hides the **key** and **name** arguments.

**Return**

returns an error if the buckets could not be allocated. This
error will also be stored in **hdl->error**.

#### <a id="c-v4l2_ctrl_handler_init"></a>`v4l2_ctrl_handler_init()`

```c
v4l2_ctrl_handler_init(hdl, nr_of_controls_hint)
```

helper function to create a static struct `lock_class_key` and calls [`v4l2_ctrl_handler_init_class()`](#c-v4l2_ctrl_handler_init_class)

**Parameters**

- `hdl`: The control handler.
- `nr_of_controls_hint`: A hint of how many controls this handler is
  expected to refer to. This is the total number, so including
  any inherited controls. It doesn't have to be precise, but if
  it is way off, then you either waste memory (too many buckets
  are allocated) or the control lookup becomes slower (not enough
  buckets are allocated, so there are more slow list lookups).
  It will always work, though.

**Description**

This helper function creates a static struct `lock_class_key` and
calls [`v4l2_ctrl_handler_init_class()`](#c-v4l2_ctrl_handler_init_class), providing a proper name for the lock
validador.

Use this helper function to initialize a control handler.

#### <a id="c-v4l2_ctrl_handler_free"></a>`v4l2_ctrl_handler_free()`

```c
int v4l2_ctrl_handler_free(struct v4l2_ctrl_handler *hdl)
```

Free all controls owned by the handler and free the control list.

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: The control handler.

**Description**

Does nothing if **hdl** == NULL.

**Return**

**hdl**'s error field or 0 if **hdl** is NULL.

#### <a id="c-v4l2_ctrl_lock"></a>`v4l2_ctrl_lock()`

```c
void v4l2_ctrl_lock(struct v4l2_ctrl *ctrl)
```

Helper function to lock the handler associated with the control.

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control to lock.

#### <a id="c-v4l2_ctrl_unlock"></a>`v4l2_ctrl_unlock()`

```c
void v4l2_ctrl_unlock(struct v4l2_ctrl *ctrl)
```

Helper function to unlock the handler associated with the control.

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control to unlock.

#### <a id="c-__v4l2_ctrl_handler_setup"></a>`__v4l2_ctrl_handler_setup()`

```c
int __v4l2_ctrl_handler_setup(struct v4l2_ctrl_handler *hdl)
```

Call the s_ctrl op for all controls belonging to the handler to initialize the hardware to the current control values. The caller is responsible for acquiring the control handler mutex on behalf of [`__v4l2_ctrl_handler_setup()`](#c-__v4l2_ctrl_handler_setup).

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: The control handler.

**Description**

Button controls will be skipped, as are read-only controls.

If **hdl** == NULL, then this just returns 0.

#### <a id="c-v4l2_ctrl_handler_setup"></a>`v4l2_ctrl_handler_setup()`

```c
int v4l2_ctrl_handler_setup(struct v4l2_ctrl_handler *hdl)
```

Call the s_ctrl op for all controls belonging to the handler to initialize the hardware to the current control values.

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: The control handler.

**Description**

Button controls will be skipped, as are read-only controls.

If **hdl** == NULL, then this just returns 0.

#### <a id="c-v4l2_ctrl_handler_log_status"></a>`v4l2_ctrl_handler_log_status()`

```c
void v4l2_ctrl_handler_log_status(struct v4l2_ctrl_handler *hdl, const char *prefix)
```

Log all controls owned by the handler.

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: The control handler.
- `const char *prefix`: The prefix to use when logging the control values. If the
  prefix does not end with a space, then ": " will be added
  after the prefix. If **prefix** == NULL, then no prefix will be
  used.

**Description**

For use with VIDIOC_LOG_STATUS.

Does nothing if **hdl** == NULL.

#### <a id="c-v4l2_ctrl_new_custom"></a>`v4l2_ctrl_new_custom()`

```c
struct v4l2_ctrl * v4l2_ctrl_new_custom(struct v4l2_ctrl_handler *hdl, const struct v4l2_ctrl_config *cfg, void *priv)
```

Allocate and initialize a new custom V4L2 control.

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: The control handler.
- `const struct v4l2_ctrl_config *cfg`: The control's configuration data.
- `void *priv`: The control's driver-specific private data.

**Description**

If the [`v4l2_ctrl`](#c-struct-v4l2_ctrl) struct could not be allocated then NULL is returned
and **hdl->error** is set to the error code (if it wasn't set already).

#### <a id="c-v4l2_ctrl_new_std"></a>`v4l2_ctrl_new_std()`

```c
struct v4l2_ctrl * v4l2_ctrl_new_std(struct v4l2_ctrl_handler *hdl, const struct v4l2_ctrl_ops *ops, u32 id, s64 min, s64 max, u64 step, s64 def)
```

Allocate and initialize a new standard V4L2 non-menu control.

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: The control handler.
- `const struct v4l2_ctrl_ops *ops`: The control ops.
- `u32 id`: The control ID.
- `s64 min`: The control's minimum value.
- `s64 max`: The control's maximum value.
- `u64 step`: The control's step value
- `s64 def`: The control's default value.

**Description**

If the [`v4l2_ctrl`](#c-struct-v4l2_ctrl) struct could not be allocated, or the control
ID is not known, then NULL is returned and **hdl->error** is set to the
appropriate error code (if it wasn't set already).

If **id** refers to a menu control, then this function will return NULL.

Use [`v4l2_ctrl_new_std_menu()`](#c-v4l2_ctrl_new_std_menu) when adding menu controls.

#### <a id="c-v4l2_ctrl_new_std_menu"></a>`v4l2_ctrl_new_std_menu()`

```c
struct v4l2_ctrl * v4l2_ctrl_new_std_menu(struct v4l2_ctrl_handler *hdl, const struct v4l2_ctrl_ops *ops, u32 id, u8 max, u64 mask, u8 def)
```

Allocate and initialize a new standard V4L2 menu control.

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: The control handler.
- `const struct v4l2_ctrl_ops *ops`: The control ops.
- `u32 id`: The control ID.
- `u8 max`: The control's maximum value.
- `u64 mask`: The control's skip mask for menu controls. This makes it
  easy to skip menu items that are not valid. If bit X is set,
  then menu item X is skipped. Of course, this only works for
  menus with \<= 64 menu items. There are no menus that come
  close to that number, so this is OK. Should we ever need more,
  then this will have to be extended to a bit array.
- `u8 def`: The control's default value.

**Description**

Same as [`v4l2_ctrl_new_std()`](#c-v4l2_ctrl_new_std), but **min** is set to 0 and the **mask** value
determines which menu items are to be skipped.

If **id** refers to a non-menu control, then this function will return NULL.

#### <a id="c-v4l2_ctrl_new_std_menu_items"></a>`v4l2_ctrl_new_std_menu_items()`

```c
struct v4l2_ctrl * v4l2_ctrl_new_std_menu_items(struct v4l2_ctrl_handler *hdl, const struct v4l2_ctrl_ops *ops, u32 id, u8 max, u64 mask, u8 def, const char * const *qmenu)
```

Create a new standard V4L2 menu control with driver specific menu.

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: The control handler.
- `const struct v4l2_ctrl_ops *ops`: The control ops.
- `u32 id`: The control ID.
- `u8 max`: The control's maximum value.
- `u64 mask`: The control's skip mask for menu controls. This makes it
  easy to skip menu items that are not valid. If bit X is set,
  then menu item X is skipped. Of course, this only works for
  menus with \<= 64 menu items. There are no menus that come
  close to that number, so this is OK. Should we ever need more,
  then this will have to be extended to a bit array.
- `u8 def`: The control's default value.
- `const char * const *qmenu`: The new menu.

**Description**

Same as [`v4l2_ctrl_new_std_menu()`](#c-v4l2_ctrl_new_std_menu), but **qmenu** will be the driver specific
menu of this control.

#### <a id="c-v4l2_ctrl_new_std_compound"></a>`v4l2_ctrl_new_std_compound()`

```c
struct v4l2_ctrl * v4l2_ctrl_new_std_compound(struct v4l2_ctrl_handler *hdl, const struct v4l2_ctrl_ops *ops, u32 id, const union v4l2_ctrl_ptr p_def, const union v4l2_ctrl_ptr p_min, const union v4l2_ctrl_ptr p_max)
```

Allocate and initialize a new standard V4L2 compound control.

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: The control handler.
- `const struct v4l2_ctrl_ops *ops`: The control ops.
- `u32 id`: The control ID.
- `const union v4l2_ctrl_ptr p_def`: The control's default value.
- `const union v4l2_ctrl_ptr p_min`: The control's minimum value.
- `const union v4l2_ctrl_ptr p_max`: The control's maximum value.

**Description**

Same as [`v4l2_ctrl_new_std()`](#c-v4l2_ctrl_new_std), but with support for compound controls.
To fill in the **p_def**, **p_min** and **p_max** fields, use [`v4l2_ctrl_ptr_create()`](#c-v4l2_ctrl_ptr_create)
to convert a pointer to a const union v4l2_ctrl_ptr.
Use v4l2_ctrl_ptr_create(NULL) if you want the default, minimum or maximum
value of the compound control to be all zeroes.
If the compound control does not set the `V4L2_CTRL_FLAG_HAS_WHICH_MIN_MAX`
flag, then it does not has minimum and maximum values. In that case just use
v4l2_ctrl_ptr_create(NULL) for the **p_min** and **p_max** arguments.

#### <a id="c-v4l2_ctrl_new_int_menu"></a>`v4l2_ctrl_new_int_menu()`

```c
struct v4l2_ctrl * v4l2_ctrl_new_int_menu(struct v4l2_ctrl_handler *hdl, const struct v4l2_ctrl_ops *ops, u32 id, u8 max, u8 def, const s64 *qmenu_int)
```

Create a new standard V4L2 integer menu control.

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: The control handler.
- `const struct v4l2_ctrl_ops *ops`: The control ops.
- `u32 id`: The control ID.
- `u8 max`: The control's maximum value.
- `u8 def`: The control's default value.
- `const s64 *qmenu_int`: The control's menu entries.

**Description**

Same as [`v4l2_ctrl_new_std_menu()`](#c-v4l2_ctrl_new_std_menu), but **mask** is set to 0 and it additionally
takes as an argument an array of integers determining the menu items.

If **id** refers to a non-integer-menu control, then this function will
return `NULL`.

#### <a id="c-v4l2_ctrl_filter"></a>`v4l2_ctrl_filter()`

```c
typedef bool v4l2_ctrl_filter(const struct v4l2_ctrl *ctrl)
```

Typedef to define the filter function to be used when adding a control handler.

**Parameters**

- `const struct v4l2_ctrl *ctrl`: pointer to struct [`v4l2_ctrl`](#c-struct-v4l2_ctrl).

#### <a id="c-v4l2_ctrl_add_handler"></a>`v4l2_ctrl_add_handler()`

```c
int v4l2_ctrl_add_handler(struct v4l2_ctrl_handler *hdl, struct v4l2_ctrl_handler *add, v4l2_ctrl_filter filter, bool from_other_dev)
```

Add all controls from handler **add** to handler **hdl**.

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: The control handler.
- `struct v4l2_ctrl_handler *add`: The control handler whose controls you want to add to
  the **hdl** control handler.
- `v4l2_ctrl_filter filter`: This function will filter which controls should be added.
- `bool from_other_dev`: If true, then the controls in **add** were defined in another
  device than **hdl**.

**Description**

Does nothing if either of the two handlers is a NULL pointer.
If **filter** is NULL, then all controls are added. Otherwise only those
controls for which **filter** returns true will be added.
In case of an error **hdl->error** will be set to the error code (if it
wasn't set already).

#### <a id="c-v4l2_ctrl_radio_filter"></a>`v4l2_ctrl_radio_filter()`

```c
bool v4l2_ctrl_radio_filter(const struct v4l2_ctrl *ctrl)
```

Standard filter for radio controls.

**Parameters**

- `const struct v4l2_ctrl *ctrl`: The control that is filtered.

**Description**

This will return true for any controls that are valid for radio device
nodes. Those are all of the V4L2_CID_AUDIO_* user controls and all FM
transmitter class controls.

This function is to be used with [`v4l2_ctrl_add_handler()`](#c-v4l2_ctrl_add_handler).

#### <a id="c-v4l2_ctrl_cluster"></a>`v4l2_ctrl_cluster()`

```c
void v4l2_ctrl_cluster(unsigned int ncontrols, struct v4l2_ctrl **controls)
```

Mark all controls in the cluster as belonging to that cluster.

**Parameters**

- `unsigned int ncontrols`: The number of controls in this cluster.
- `struct v4l2_ctrl **controls`: The cluster control array of size **ncontrols**.

#### <a id="c-v4l2_ctrl_auto_cluster"></a>`v4l2_ctrl_auto_cluster()`

```c
void v4l2_ctrl_auto_cluster(unsigned int ncontrols, struct v4l2_ctrl **controls, u8 manual_val, bool set_volatile)
```

Mark all controls in the cluster as belonging to that cluster and set it up for autofoo/foo-type handling.

**Parameters**

- `unsigned int ncontrols`: The number of controls in this cluster.
- `struct v4l2_ctrl **controls`: The cluster control array of size **ncontrols**. The first control
  must be the 'auto' control (e.g. autogain, autoexposure, etc.)
- `u8 manual_val`: The value for the first control in the cluster that equals the
  manual setting.
- `bool set_volatile`: If true, then all controls except the first auto control will
  be volatile.

**Description**

Use for control groups where one control selects some automatic feature and
the other controls are only active whenever the automatic feature is turned
off (manual mode). Typical examples: autogain vs gain, auto-whitebalance vs
red and blue balance, etc.

The behavior of such controls is as follows:

When the autofoo control is set to automatic, then any manual controls
are set to inactive and any reads will call g_volatile_ctrl (if the control
was marked volatile).

When the autofoo control is set to manual, then any manual controls will
be marked active, and any reads will just return the current value without
going through g_volatile_ctrl.

In addition, this function will set the `V4L2_CTRL_FLAG_UPDATE` flag
on the autofoo control and `V4L2_CTRL_FLAG_INACTIVE` on the foo control(s)
if autofoo is in auto mode.

#### <a id="c-v4l2_ctrl_find"></a>`v4l2_ctrl_find()`

```c
struct v4l2_ctrl * v4l2_ctrl_find(struct v4l2_ctrl_handler *hdl, u32 id)
```

Find a control with the given ID.

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: The control handler.
- `u32 id`: The control ID to find.

**Description**

If **hdl** == NULL this will return NULL as well. Will lock the handler so
do not use from inside [`v4l2_ctrl_ops`](#c-struct-v4l2_ctrl_ops).

#### <a id="c-v4l2_ctrl_activate"></a>`v4l2_ctrl_activate()`

```c
void v4l2_ctrl_activate(struct v4l2_ctrl *ctrl, bool active)
```

Make the control active or inactive.

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control to (de)activate.
- `bool active`: True if the control should become active.

**Description**

This sets or clears the V4L2_CTRL_FLAG_INACTIVE flag atomically.
Does nothing if **ctrl** == NULL.
This will usually be called from within the s_ctrl op.
The V4L2_EVENT_CTRL event will be generated afterwards.

This function assumes that the control handler is locked.

#### <a id="c-__v4l2_ctrl_grab"></a>`__v4l2_ctrl_grab()`

```c
void __v4l2_ctrl_grab(struct v4l2_ctrl *ctrl, bool grabbed)
```

Unlocked variant of v4l2_ctrl_grab.

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control to (de)activate.
- `bool grabbed`: True if the control should become grabbed.

**Description**

This sets or clears the V4L2_CTRL_FLAG_GRABBED flag atomically.
Does nothing if **ctrl** == NULL.
The V4L2_EVENT_CTRL event will be generated afterwards.
This will usually be called when starting or stopping streaming in the
driver.

This function assumes that the control handler is locked by the caller.

#### <a id="c-v4l2_ctrl_grab"></a>`v4l2_ctrl_grab()`

```c
void v4l2_ctrl_grab(struct v4l2_ctrl *ctrl, bool grabbed)
```

Mark the control as grabbed or not grabbed.

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control to (de)activate.
- `bool grabbed`: True if the control should become grabbed.

**Description**

This sets or clears the V4L2_CTRL_FLAG_GRABBED flag atomically.
Does nothing if **ctrl** == NULL.
The V4L2_EVENT_CTRL event will be generated afterwards.
This will usually be called when starting or stopping streaming in the
driver.

This function assumes that the control handler is not locked and will
take the lock itself.

#### <a id="c-__v4l2_ctrl_modify_range"></a>`__v4l2_ctrl_modify_range()`

```c
int __v4l2_ctrl_modify_range(struct v4l2_ctrl *ctrl, s64 min, s64 max, u64 step, s64 def)
```

Unlocked variant of [`v4l2_ctrl_modify_range()`](#c-v4l2_ctrl_modify_range)

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control to update.
- `s64 min`: The control's minimum value.
- `s64 max`: The control's maximum value.
- `u64 step`: The control's step value
- `s64 def`: The control's default value.

**Description**

Update the range of a control on the fly. This works for control types
INTEGER, BOOLEAN, MENU, INTEGER MENU and BITMASK. For menu controls the
**step** value is interpreted as a menu_skip_mask.

An error is returned if one of the range arguments is invalid for this
control type.

The caller is responsible for acquiring the control handler mutex on behalf
of [`__v4l2_ctrl_modify_range()`](#c-__v4l2_ctrl_modify_range).

#### <a id="c-v4l2_ctrl_modify_range"></a>`v4l2_ctrl_modify_range()`

```c
int v4l2_ctrl_modify_range(struct v4l2_ctrl *ctrl, s64 min, s64 max, u64 step, s64 def)
```

Update the range of a control.

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control to update.
- `s64 min`: The control's minimum value.
- `s64 max`: The control's maximum value.
- `u64 step`: The control's step value
- `s64 def`: The control's default value.

**Description**

Update the range of a control on the fly. This works for control types
INTEGER, BOOLEAN, MENU, INTEGER MENU and BITMASK. For menu controls the
**step** value is interpreted as a menu_skip_mask.

An error is returned if one of the range arguments is invalid for this
control type.

This function assumes that the control handler is not locked and will
take the lock itself.

#### <a id="c-__v4l2_ctrl_modify_dimensions"></a>`__v4l2_ctrl_modify_dimensions()`

```c
int __v4l2_ctrl_modify_dimensions(struct v4l2_ctrl *ctrl, u32 dims[V4L2_CTRL_MAX_DIMS])
```

Unlocked variant of [`v4l2_ctrl_modify_dimensions()`](#c-v4l2_ctrl_modify_dimensions)

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control to update.
- `u32 dims[V4L2_CTRL_MAX_DIMS]`: The control's new dimensions.

**Description**

Update the dimensions of an array control on the fly. The elements of the
array are reset to their default value, even if the dimensions are
unchanged.

An error is returned if **dims** is invalid for this control.

The caller is responsible for acquiring the control handler mutex on behalf
of [`__v4l2_ctrl_modify_dimensions()`](#c-__v4l2_ctrl_modify_dimensions).

**Note**

calling this function when the same control is used in pending requests
is untested. It should work (a request with the wrong size of the control
will drop that control silently), but it will be very confusing.

#### <a id="c-v4l2_ctrl_modify_dimensions"></a>`v4l2_ctrl_modify_dimensions()`

```c
int v4l2_ctrl_modify_dimensions(struct v4l2_ctrl *ctrl, u32 dims[V4L2_CTRL_MAX_DIMS])
```

Update the dimensions of an array control.

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control to update.
- `u32 dims[V4L2_CTRL_MAX_DIMS]`: The control's new dimensions.

**Description**

Update the dimensions of an array control on the fly. The elements of the
array are reset to their default value, even if the dimensions are
unchanged.

An error is returned if **dims** is invalid for this control type.

This function assumes that the control handler is not locked and will
take the lock itself.

**Note**

calling this function when the same control is used in pending requests
is untested. It should work (a request with the wrong size of the control
will drop that control silently), but it will be very confusing.

#### <a id="c-v4l2_ctrl_notify"></a>`v4l2_ctrl_notify()`

```c
void v4l2_ctrl_notify(struct v4l2_ctrl *ctrl, v4l2_ctrl_notify_fnc notify, void *priv)
```

Function to set a notify callback for a control.

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control.
- `v4l2_ctrl_notify_fnc notify`: The callback function.
- `void *priv`: The callback private handle, passed as argument to the callback.

**Description**

This function sets a callback function for the control. If **ctrl** is NULL,
then it will do nothing. If **notify** is NULL, then the notify callback will
be removed.

There can be only one notify. If another already exists, then a WARN_ON
will be issued and the function will do nothing.

#### <a id="c-v4l2_ctrl_get_name"></a>`v4l2_ctrl_get_name()`

```c
const char * v4l2_ctrl_get_name(u32 id)
```

Get the name of the control

**Parameters**

- `u32 id`: The control ID.

**Description**

This function returns the name of the given control ID or NULL if it isn't
a known control.

#### <a id="c-v4l2_ctrl_get_menu"></a>`v4l2_ctrl_get_menu()`

```c
const char * const * v4l2_ctrl_get_menu(u32 id)
```

Get the menu string array of the control

**Parameters**

- `u32 id`: The control ID.

**Description**

This function returns the NULL-terminated menu string array name of the
given control ID or NULL if it isn't a known menu control.

#### <a id="c-v4l2_ctrl_get_int_menu"></a>`v4l2_ctrl_get_int_menu()`

```c
const s64 * v4l2_ctrl_get_int_menu(u32 id, u32 *len)
```

Get the integer menu array of the control

**Parameters**

- `u32 id`: The control ID.
- `u32 *len`: The size of the integer array.

**Description**

This function returns the integer array of the given control ID or NULL if it
if it isn't a known integer menu control.

#### <a id="c-v4l2_ctrl_g_ctrl"></a>`v4l2_ctrl_g_ctrl()`

```c
s32 v4l2_ctrl_g_ctrl(struct v4l2_ctrl *ctrl)
```

Helper function to get the control's value from within a driver.

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control.

**Description**

This returns the control's value safely by going through the control
framework. This function will lock the control's handler, so it cannot be
used from within the [`v4l2_ctrl_ops`](#c-struct-v4l2_ctrl_ops) functions.

This function is for integer type controls only.

#### <a id="c-__v4l2_ctrl_s_ctrl"></a>`__v4l2_ctrl_s_ctrl()`

```c
int __v4l2_ctrl_s_ctrl(struct v4l2_ctrl *ctrl, s32 val)
```

Unlocked variant of [`v4l2_ctrl_s_ctrl()`](#c-v4l2_ctrl_s_ctrl).

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control.
- `s32 val`: The new value.

**Description**

This sets the control's new value safely by going through the control
framework. This function assumes the control's handler is already locked,
allowing it to be used from within the [`v4l2_ctrl_ops`](#c-struct-v4l2_ctrl_ops) functions.

This function is for integer type controls only.

#### <a id="c-v4l2_ctrl_s_ctrl"></a>`v4l2_ctrl_s_ctrl()`

```c
int v4l2_ctrl_s_ctrl(struct v4l2_ctrl *ctrl, s32 val)
```

Helper function to set the control's value from within a driver.

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control.
- `s32 val`: The new value.

**Description**

This sets the control's new value safely by going through the control
framework. This function will lock the control's handler, so it cannot be
used from within the [`v4l2_ctrl_ops`](#c-struct-v4l2_ctrl_ops) functions.

This function is for integer type controls only.

#### <a id="c-v4l2_ctrl_g_ctrl_int64"></a>`v4l2_ctrl_g_ctrl_int64()`

```c
s64 v4l2_ctrl_g_ctrl_int64(struct v4l2_ctrl *ctrl)
```

Helper function to get a 64-bit control's value from within a driver.

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control.

**Description**

This returns the control's value safely by going through the control
framework. This function will lock the control's handler, so it cannot be
used from within the [`v4l2_ctrl_ops`](#c-struct-v4l2_ctrl_ops) functions.

This function is for 64-bit integer type controls only.

#### <a id="c-__v4l2_ctrl_s_ctrl_int64"></a>`__v4l2_ctrl_s_ctrl_int64()`

```c
int __v4l2_ctrl_s_ctrl_int64(struct v4l2_ctrl *ctrl, s64 val)
```

Unlocked variant of [`v4l2_ctrl_s_ctrl_int64()`](#c-v4l2_ctrl_s_ctrl_int64).

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control.
- `s64 val`: The new value.

**Description**

This sets the control's new value safely by going through the control
framework. This function assumes the control's handler is already locked,
allowing it to be used from within the [`v4l2_ctrl_ops`](#c-struct-v4l2_ctrl_ops) functions.

This function is for 64-bit integer type controls only.

#### <a id="c-v4l2_ctrl_s_ctrl_int64"></a>`v4l2_ctrl_s_ctrl_int64()`

```c
int v4l2_ctrl_s_ctrl_int64(struct v4l2_ctrl *ctrl, s64 val)
```

Helper function to set a 64-bit control's value from within a driver.

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control.
- `s64 val`: The new value.

**Description**

This sets the control's new value safely by going through the control
framework. This function will lock the control's handler, so it cannot be
used from within the [`v4l2_ctrl_ops`](#c-struct-v4l2_ctrl_ops) functions.

This function is for 64-bit integer type controls only.

#### <a id="c-__v4l2_ctrl_s_ctrl_string"></a>`__v4l2_ctrl_s_ctrl_string()`

```c
int __v4l2_ctrl_s_ctrl_string(struct v4l2_ctrl *ctrl, const char *s)
```

Unlocked variant of [`v4l2_ctrl_s_ctrl_string()`](#c-v4l2_ctrl_s_ctrl_string).

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control.
- `const char *s`: The new string.

**Description**

This sets the control's new string safely by going through the control
framework. This function assumes the control's handler is already locked,
allowing it to be used from within the [`v4l2_ctrl_ops`](#c-struct-v4l2_ctrl_ops) functions.

This function is for string type controls only.

#### <a id="c-v4l2_ctrl_s_ctrl_string"></a>`v4l2_ctrl_s_ctrl_string()`

```c
int v4l2_ctrl_s_ctrl_string(struct v4l2_ctrl *ctrl, const char *s)
```

Helper function to set a control's string value from within a driver.

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control.
- `const char *s`: The new string.

**Description**

This sets the control's new string safely by going through the control
framework. This function will lock the control's handler, so it cannot be
used from within the [`v4l2_ctrl_ops`](#c-struct-v4l2_ctrl_ops) functions.

This function is for string type controls only.

#### <a id="c-__v4l2_ctrl_s_ctrl_compound"></a>`__v4l2_ctrl_s_ctrl_compound()`

```c
int __v4l2_ctrl_s_ctrl_compound(struct v4l2_ctrl *ctrl, enum v4l2_ctrl_type type, const void *p)
```

Unlocked variant to set a compound control

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control.
- `enum v4l2_ctrl_type type`: The type of the data.
- `const void *p`: The new compound payload.

**Description**

This sets the control's new compound payload safely by going through the
control framework. This function assumes the control's handler is already
locked, allowing it to be used from within the [`v4l2_ctrl_ops`](#c-struct-v4l2_ctrl_ops) functions.

This function is for compound type controls only.

#### <a id="c-v4l2_ctrl_s_ctrl_compound"></a>`v4l2_ctrl_s_ctrl_compound()`

```c
int v4l2_ctrl_s_ctrl_compound(struct v4l2_ctrl *ctrl, enum v4l2_ctrl_type type, const void *p)
```

Helper function to set a compound control from within a driver.

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control.
- `enum v4l2_ctrl_type type`: The type of the data.
- `const void *p`: The new compound payload.

**Description**

This sets the control's new compound payload safely by going through the
control framework. This function will lock the control's handler, so it
cannot be used from within the [`v4l2_ctrl_ops`](#c-struct-v4l2_ctrl_ops) functions.

This function is for compound type controls only.

#### <a id="c-v4l2_ctrl_replace"></a>`v4l2_ctrl_replace()`

```c
void v4l2_ctrl_replace(struct v4l2_event *old, const struct v4l2_event *new)
```

Function to be used as a callback to [`struct v4l2_subscribed_event_ops`](/kernel/hardware/driver-api/media/v4l2-event.md#c-struct-v4l2_subscribed_event_ops) replace\(\)

**Parameters**

- `struct v4l2_event *old`: pointer to struct `v4l2_event` with the reported
  event;
- `const struct v4l2_event *new`: pointer to struct `v4l2_event` with the modified
  event;

#### <a id="c-v4l2_ctrl_merge"></a>`v4l2_ctrl_merge()`

```c
void v4l2_ctrl_merge(const struct v4l2_event *old, struct v4l2_event *new)
```

Function to be used as a callback to [`struct v4l2_subscribed_event_ops`](/kernel/hardware/driver-api/media/v4l2-event.md#c-struct-v4l2_subscribed_event_ops) merge(\)

**Parameters**

- `const struct v4l2_event *old`: pointer to struct `v4l2_event` with the reported
  event;
- `struct v4l2_event *new`: pointer to struct `v4l2_event` with the merged
  event;

#### <a id="c-v4l2_ctrl_log_status"></a>`v4l2_ctrl_log_status()`

```c
int v4l2_ctrl_log_status(struct file *file, void *priv)
```

helper function to implement `VIDIOC_LOG_STATUS` ioctl

**Parameters**

- `struct file *file`: pointer to struct file
- `void *priv`: unused. Kept just to be compatible to the arguments expected by
  [`struct v4l2_ioctl_ops`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops).vidioc_log_status.

**Description**

Can be used as a vidioc_log_status function that just dumps all controls
associated with the filehandle.

#### <a id="c-v4l2_ctrl_subscribe_event"></a>`v4l2_ctrl_subscribe_event()`

```c
int v4l2_ctrl_subscribe_event(struct v4l2_fh *fh, const struct v4l2_event_subscription *sub)
```

Subscribes to an event

**Parameters**

- `struct v4l2_fh *fh`: pointer to struct v4l2_fh
- `const struct v4l2_event_subscription *sub`: pointer to [`struct v4l2_event_subscription`](/kernel/userspace/userspace-api/media-v4l/vidioc-subscribe-event.md#c-v4l2_event_subscription)

**Description**

Can be used as a vidioc_subscribe_event function that just subscribes
control events.

#### <a id="c-v4l2_ctrl_poll"></a>`v4l2_ctrl_poll()`

```c
__poll_t v4l2_ctrl_poll(struct file *file, struct poll_table_struct *wait)
```

function to be used as a callback to the `poll()` That just polls for control events.

**Parameters**

- `struct file *file`: pointer to struct file
- `struct poll_table_struct *wait`: pointer to struct poll_table_struct

#### <a id="c-v4l2_ctrl_request_setup"></a>`v4l2_ctrl_request_setup()`

```c
int v4l2_ctrl_request_setup(struct media_request *req, struct v4l2_ctrl_handler *parent)
```

helper function to apply control values in a request

**Parameters**

- `struct media_request *req`: The request
- `struct v4l2_ctrl_handler *parent`: The parent control handler ('priv' in [`media_request_object_find()`](/kernel/hardware/driver-api/media/mc-core.md#c-media_request_object_find))

**Description**

This is a helper function to call the control handler's s_ctrl callback with
the control values contained in the request. Do note that this approach of
applying control values in a request is only applicable to memory-to-memory
devices.

#### <a id="c-v4l2_ctrl_request_complete"></a>`v4l2_ctrl_request_complete()`

```c
void v4l2_ctrl_request_complete(struct media_request *req, struct v4l2_ctrl_handler *parent)
```

Complete a control handler request object

**Parameters**

- `struct media_request *req`: The request
- `struct v4l2_ctrl_handler *parent`: The parent control handler ('priv' in [`media_request_object_find()`](/kernel/hardware/driver-api/media/mc-core.md#c-media_request_object_find))

**Description**

This function is to be called on each control handler that may have had a
request object associated with it, i.e. control handlers of a driver that
supports requests.

The function first obtains the values of any volatile controls in the control
handler and attach them to the request. Then, the function completes the
request object.

#### <a id="c-v4l2_ctrl_request_hdl_find"></a>`v4l2_ctrl_request_hdl_find()`

```c
struct v4l2_ctrl_handler * v4l2_ctrl_request_hdl_find(struct media_request *req, struct v4l2_ctrl_handler *parent)
```

Find the control handler in the request

**Parameters**

- `struct media_request *req`: The request
- `struct v4l2_ctrl_handler *parent`: The parent control handler ('priv' in [`media_request_object_find()`](/kernel/hardware/driver-api/media/mc-core.md#c-media_request_object_find))

**Description**

This function finds the control handler in the request. It may return
NULL if not found. When done, you must call [`v4l2_ctrl_request_hdl_put()`](#c-v4l2_ctrl_request_hdl_put)
with the returned handler pointer.

If the request is not in state VALIDATING or QUEUED, then this function
will always return NULL.

Note that in state VALIDATING the req_queue_mutex is held, so
no objects can be added or deleted from the request.

In state QUEUED it is the driver that will have to ensure this.

#### <a id="c-v4l2_ctrl_request_hdl_put"></a>`v4l2_ctrl_request_hdl_put()`

```c
void v4l2_ctrl_request_hdl_put(struct v4l2_ctrl_handler *hdl)
```

Put the control handler

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: Put this control handler

**Description**

This function released the control handler previously obtained from'
[`v4l2_ctrl_request_hdl_find()`](#c-v4l2_ctrl_request_hdl_find).

#### <a id="c-v4l2_ctrl_request_hdl_ctrl_find"></a>`v4l2_ctrl_request_hdl_ctrl_find()`

```c
struct v4l2_ctrl * v4l2_ctrl_request_hdl_ctrl_find(struct v4l2_ctrl_handler *hdl, u32 id)
```

Find a control with the given ID.

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: The control handler from the request.
- `u32 id`: The ID of the control to find.

**Description**

This function returns a pointer to the control if this control is
part of the request or NULL otherwise.

#### <a id="c-v4l2_queryctrl"></a>`v4l2_queryctrl()`

```c
int v4l2_queryctrl(struct v4l2_ctrl_handler *hdl, struct v4l2_queryctrl *qc)
```

Helper function to implement VIDIOC_QUERYCTRL ioctl

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: pointer to [`struct v4l2_ctrl_handler`](#c-struct-v4l2_ctrl_handler)
- `struct v4l2_queryctrl *qc`: pointer to [`struct v4l2_queryctrl`](/kernel/userspace/userspace-api/media-v4l/vidioc-queryctrl.md#c-struct-v4l2_queryctrl)

**Description**

If hdl == NULL then they will all return -EINVAL.

#### <a id="c-v4l2_query_ext_ctrl_to_v4l2_queryctrl"></a>`v4l2_query_ext_ctrl_to_v4l2_queryctrl()`

```c
void v4l2_query_ext_ctrl_to_v4l2_queryctrl(struct v4l2_queryctrl *to, const struct v4l2_query_ext_ctrl *from)
```

Convert a qec to qe.

**Parameters**

- `struct v4l2_queryctrl *to`: The v4l2_queryctrl to write to.
- `const struct v4l2_query_ext_ctrl *from`: The v4l2_query_ext_ctrl to read from.

**Description**

This function is a helper to convert a v4l2_query_ext_ctrl into a
v4l2_queryctrl.

#### <a id="c-v4l2_query_ext_ctrl"></a>`v4l2_query_ext_ctrl()`

```c
int v4l2_query_ext_ctrl(struct v4l2_ctrl_handler *hdl, struct v4l2_query_ext_ctrl *qc)
```

Helper function to implement VIDIOC_QUERY_EXT_CTRL ioctl

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: pointer to [`struct v4l2_ctrl_handler`](#c-struct-v4l2_ctrl_handler)
- `struct v4l2_query_ext_ctrl *qc`: pointer to [`struct v4l2_query_ext_ctrl`](/kernel/userspace/userspace-api/media-v4l/vidioc-queryctrl.md#c-struct-v4l2_query_ext_ctrl)

**Description**

If hdl == NULL then they will all return -EINVAL.

#### <a id="c-v4l2_querymenu"></a>`v4l2_querymenu()`

```c
int v4l2_querymenu(struct v4l2_ctrl_handler *hdl, struct v4l2_querymenu *qm)
```

Helper function to implement VIDIOC_QUERYMENU ioctl

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: pointer to [`struct v4l2_ctrl_handler`](#c-struct-v4l2_ctrl_handler)
- `struct v4l2_querymenu *qm`: pointer to [`struct v4l2_querymenu`](/kernel/userspace/userspace-api/media-v4l/vidioc-queryctrl.md#c-struct-v4l2_querymenu)

**Description**

If hdl == NULL then they will all return -EINVAL.

#### <a id="c-v4l2_g_ctrl"></a>`v4l2_g_ctrl()`

```c
int v4l2_g_ctrl(struct v4l2_ctrl_handler *hdl, struct v4l2_control *ctrl)
```

Helper function to implement VIDIOC_G_CTRL ioctl

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: pointer to [`struct v4l2_ctrl_handler`](#c-struct-v4l2_ctrl_handler)
- `struct v4l2_control *ctrl`: pointer to [`struct v4l2_control`](/kernel/userspace/userspace-api/media-v4l/vidioc-g-ctrl.md#c-v4l2_control)

**Description**

If hdl == NULL then they will all return -EINVAL.

#### <a id="c-v4l2_s_ctrl"></a>`v4l2_s_ctrl()`

```c
int v4l2_s_ctrl(struct v4l2_fh *fh, struct v4l2_ctrl_handler *hdl, struct v4l2_control *ctrl)
```

Helper function to implement VIDIOC_S_CTRL ioctl

**Parameters**

- `struct v4l2_fh *fh`: pointer to [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh)
- `struct v4l2_ctrl_handler *hdl`: pointer to [`struct v4l2_ctrl_handler`](#c-struct-v4l2_ctrl_handler)
- `struct v4l2_control *ctrl`: pointer to [`struct v4l2_control`](/kernel/userspace/userspace-api/media-v4l/vidioc-g-ctrl.md#c-v4l2_control)

**Description**

If hdl == NULL then they will all return -EINVAL.

#### <a id="c-v4l2_g_ext_ctrls"></a>`v4l2_g_ext_ctrls()`

```c
int v4l2_g_ext_ctrls(struct v4l2_ctrl_handler *hdl, struct video_device *vdev, struct media_device *mdev, struct v4l2_ext_controls *c)
```

Helper function to implement VIDIOC_G_EXT_CTRLS ioctl

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: pointer to [`struct v4l2_ctrl_handler`](#c-struct-v4l2_ctrl_handler)
- `struct video_device *vdev`: pointer to [`struct video_device`](/kernel/hardware/driver-api/media/v4l2-dev.md#c-struct-video_device)
- `struct media_device *mdev`: pointer to [`struct media_device`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_device)
- `struct v4l2_ext_controls *c`: pointer to [`struct v4l2_ext_controls`](/kernel/userspace/userspace-api/media-v4l/vidioc-g-ext-ctrls.md#c-v4l2_ext_controls)

**Description**

If hdl == NULL then they will all return -EINVAL.

#### <a id="c-v4l2_try_ext_ctrls"></a>`v4l2_try_ext_ctrls()`

```c
int v4l2_try_ext_ctrls(struct v4l2_ctrl_handler *hdl, struct video_device *vdev, struct media_device *mdev, struct v4l2_ext_controls *c)
```

Helper function to implement VIDIOC_TRY_EXT_CTRLS ioctl

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: pointer to [`struct v4l2_ctrl_handler`](#c-struct-v4l2_ctrl_handler)
- `struct video_device *vdev`: pointer to [`struct video_device`](/kernel/hardware/driver-api/media/v4l2-dev.md#c-struct-video_device)
- `struct media_device *mdev`: pointer to [`struct media_device`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_device)
- `struct v4l2_ext_controls *c`: pointer to [`struct v4l2_ext_controls`](/kernel/userspace/userspace-api/media-v4l/vidioc-g-ext-ctrls.md#c-v4l2_ext_controls)

**Description**

If hdl == NULL then they will all return -EINVAL.

#### <a id="c-v4l2_s_ext_ctrls"></a>`v4l2_s_ext_ctrls()`

```c
int v4l2_s_ext_ctrls(struct v4l2_fh *fh, struct v4l2_ctrl_handler *hdl, struct video_device *vdev, struct media_device *mdev, struct v4l2_ext_controls *c)
```

Helper function to implement VIDIOC_S_EXT_CTRLS ioctl

**Parameters**

- `struct v4l2_fh *fh`: pointer to [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh)
- `struct v4l2_ctrl_handler *hdl`: pointer to [`struct v4l2_ctrl_handler`](#c-struct-v4l2_ctrl_handler)
- `struct video_device *vdev`: pointer to [`struct video_device`](/kernel/hardware/driver-api/media/v4l2-dev.md#c-struct-video_device)
- `struct media_device *mdev`: pointer to [`struct media_device`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_device)
- `struct v4l2_ext_controls *c`: pointer to [`struct v4l2_ext_controls`](/kernel/userspace/userspace-api/media-v4l/vidioc-g-ext-ctrls.md#c-v4l2_ext_controls)

**Description**

If hdl == NULL then they will all return -EINVAL.

#### <a id="c-v4l2_ctrl_subdev_subscribe_event"></a>`v4l2_ctrl_subdev_subscribe_event()`

```c
int v4l2_ctrl_subdev_subscribe_event(struct v4l2_subdev *sd, struct v4l2_fh *fh, struct v4l2_event_subscription *sub)
```

Helper function to implement as a [`struct v4l2_subdev_core_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_core_ops) subscribe_event function that just subscribes control events.

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)
- `struct v4l2_fh *fh`: pointer to [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh)
- `struct v4l2_event_subscription *sub`: pointer to [`struct v4l2_event_subscription`](/kernel/userspace/userspace-api/media-v4l/vidioc-subscribe-event.md#c-v4l2_event_subscription)

#### <a id="c-v4l2_ctrl_subdev_log_status"></a>`v4l2_ctrl_subdev_log_status()`

```c
int v4l2_ctrl_subdev_log_status(struct v4l2_subdev *sd)
```

Log all controls owned by subdev's control handler.

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)

#### <a id="c-v4l2_ctrl_new_fwnode_properties"></a>`v4l2_ctrl_new_fwnode_properties()`

```c
int v4l2_ctrl_new_fwnode_properties(struct v4l2_ctrl_handler *hdl, const struct v4l2_ctrl_ops *ctrl_ops, const struct v4l2_fwnode_device_properties *p)
```

Register controls for the device properties

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: pointer to [`struct v4l2_ctrl_handler`](#c-struct-v4l2_ctrl_handler) to register controls on
- `const struct v4l2_ctrl_ops *ctrl_ops`: pointer to [`struct v4l2_ctrl_ops`](#c-struct-v4l2_ctrl_ops) to register controls with
- `const struct v4l2_fwnode_device_properties *p`: pointer to [`struct v4l2_fwnode_device_properties`](/kernel/hardware/driver-api/media/v4l2-fwnode.md#c-struct-v4l2_fwnode_device_properties)

**Description**

This function registers controls associated to device properties, using the
property values contained in **p** parameter, if the property has been set to
a value.

Currently the following v4l2 controls are parsed and registered:
- V4L2_CID_CAMERA_ORIENTATION
- V4L2_CID_CAMERA_SENSOR_ROTATION;

Controls already registered by the caller with the **hdl** control handler are
not overwritten. Callers should register the controls they want to handle
themselves before calling this function.

This function will set the control handler's error field on failure, just as
other functions adding controls to the handler.

**Return**

0 on success, a negative error code on failure.

#### <a id="c-v4l2_ctrl_type_op_equal"></a>`v4l2_ctrl_type_op_equal()`

```c
bool v4l2_ctrl_type_op_equal(const struct v4l2_ctrl *ctrl, union v4l2_ctrl_ptr ptr1, union v4l2_ctrl_ptr ptr2)
```

Default v4l2_ctrl_type_ops equal callback.

**Parameters**

- `const struct v4l2_ctrl *ctrl`: The v4l2_ctrl pointer.
- `union v4l2_ctrl_ptr ptr1`: A v4l2 control value.
- `union v4l2_ctrl_ptr ptr2`: A v4l2 control value.

**Return**

true if values are equal, otherwise false.

#### <a id="c-v4l2_ctrl_type_op_init"></a>`v4l2_ctrl_type_op_init()`

```c
void v4l2_ctrl_type_op_init(const struct v4l2_ctrl *ctrl, u32 from_idx, union v4l2_ctrl_ptr ptr)
```

Default v4l2_ctrl_type_ops init callback.

**Parameters**

- `const struct v4l2_ctrl *ctrl`: The v4l2_ctrl pointer.
- `u32 from_idx`: Starting element index.
- `union v4l2_ctrl_ptr ptr`: The v4l2 control value.

**Return**

void

#### <a id="c-v4l2_ctrl_type_op_log"></a>`v4l2_ctrl_type_op_log()`

```c
void v4l2_ctrl_type_op_log(const struct v4l2_ctrl *ctrl)
```

Default v4l2_ctrl_type_ops log callback.

**Parameters**

- `const struct v4l2_ctrl *ctrl`: The v4l2_ctrl pointer.

**Return**

void

#### <a id="c-v4l2_ctrl_type_op_validate"></a>`v4l2_ctrl_type_op_validate()`

```c
int v4l2_ctrl_type_op_validate(const struct v4l2_ctrl *ctrl, union v4l2_ctrl_ptr ptr)
```

Default v4l2_ctrl_type_ops validate callback.

**Parameters**

- `const struct v4l2_ctrl *ctrl`: The v4l2_ctrl pointer.
- `union v4l2_ctrl_ptr ptr`: The v4l2 control value.

**Return**

0 on success, a negative error code on failure.

---

# Video4Linux devices

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for Video4Linux devices.

<a id="rst-video4linux-devices"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [Introduction](</kernel/hardware/driver-api/media/v4l2-intro.md>)
- [Video device' s internal representation](</kernel/hardware/driver-api/media/v4l2-dev.md>)
- [V4L2 device instance](</kernel/hardware/driver-api/media/v4l2-device.md>)
- [V4L2 File handles](</kernel/hardware/driver-api/media/v4l2-fh.md>)
- [V4L2 sub-devices](</kernel/hardware/driver-api/media/v4l2-subdev.md>)
- [V4L2 events](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/driver-api/media/v4l2-event.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [V4L2 Controls](</kernel/hardware/driver-api/media/v4l2-controls.md>)
- [V4L2 videobuf2 functions and data structures](</kernel/hardware/driver-api/media/v4l2-videobuf2.md>)
- [V4L2 DV Timings functions](</kernel/hardware/driver-api/media/v4l2-dv-timings.md>)
- [V4L2 flash functions and data structures](</kernel/hardware/driver-api/media/v4l2-flash-led-class.md>)
- [V4L2 Media Controller functions and data structures](</kernel/hardware/driver-api/media/v4l2-mc.md>)
- [V4L2 Media Bus functions and data structures](</kernel/hardware/driver-api/media/v4l2-mediabus.md>)
- [V4L2 Memory to Memory functions and data structures](</kernel/hardware/driver-api/media/v4l2-mem2mem.md>)
- [V4L2 async kAPI](</kernel/hardware/driver-api/media/v4l2-async.md>)
- [V4L2 fwnode kAPI](</kernel/hardware/driver-api/media/v4l2-fwnode.md>)
- [V4L2 CCI kAPI](</kernel/hardware/driver-api/media/v4l2-cci.md>)
- [V4L2 rect helper functions](</kernel/hardware/driver-api/media/v4l2-rect.md>)
- [Tuner functions and data structures](</kernel/hardware/driver-api/media/v4l2-tuner.md>)
- [V4L2 common functions and data structures](</kernel/hardware/driver-api/media/v4l2-common.md>)
- [Hauppauge TV EEPROM functions and data structures](</kernel/hardware/driver-api/media/v4l2-tveeprom.md>)
- [V4L2 JPEG header related functions and data structures](</kernel/hardware/driver-api/media/v4l2-jpeg.md>)
- [V4L2 generic ISP parameters and statistics support](</kernel/hardware/driver-api/media/v4l2-isp.md>)

---

# Video device' s internal representation

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> The actual device nodes in the /dev directory are created using the video_device struct (v4l2-dev.h). This struct can either be allocated dynamically or embedded in a larger struct.

<a id="rst-video-device-s-internal-representation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The actual device nodes in the `/dev` directory are created using the `video_device` struct (`v4l2-dev.h`). This struct can either be allocated dynamically or embedded in a larger struct.

To allocate it dynamically use `video_device_alloc()`:



```c
struct video_device *vdev = video_device_alloc();

if (vdev == NULL)
        return -ENOMEM;

vdev->release = video_device_release;
```

If you embed it in a larger struct, then you must set the `release()` callback to your own function:



```c
struct video_device *vdev = &my_vdev->vdev;

vdev->release = my_vdev_release;
```

The `release()` callback must be set and it is called when the last user of the video device exits.

The default `video_device_release()` callback currently just calls `kfree` to free the allocated memory.

There is also a `video_device_release_empty()` function that does nothing (is empty) and should be used if the struct is embedded and there is nothing to do when it is released.

You should also set these fields of `video_device`:

- `video_device`-&gt;v4l2_dev: must be set to the `v4l2_device` parent device.

- `video_device`-&gt;name: set to something descriptive and unique.

- `video_device`-&gt;vfl_dir: set this to `VFL_DIR_RX` for capture devices (`VFL_DIR_RX` has value 0, so this is normally already the default), set to `VFL_DIR_TX` for output devices and `VFL_DIR_M2M` for mem2mem (codec) devices.

- `video_device`-&gt;fops: set to the `v4l2_file_operations` struct.

- `video_device`-&gt;ioctl_ops: if you use the `v4l2_ioctl_ops` to simplify ioctl maintenance (highly recommended to use this and it might become compulsory in the future\!), then set this to your `v4l2_ioctl_ops` struct. The `video_device`-&gt;vfl_type and `video_device`-&gt;vfl_dir fields are used to disable ops that do not match the type/dir combination. E.g. VBI ops are disabled for non-VBI nodes, and output ops  are disabled for a capture device. This makes it possible to provide just one `v4l2_ioctl_ops` struct for both vbi and video nodes.

- `video_device`-&gt;lock: leave to `NULL` if you want to do all the locking  in the driver. Otherwise you give it a pointer to a struct `mutex_lock` and before the `video_device`-&gt;unlocked_ioctl file operation is called this lock will be taken by the core and released afterwards. See the next section for more details.

- `video_device`-&gt;queue: a pointer to the struct vb2_queue associated with this device node. If queue is not `NULL`, and queue-&gt;lock is not `NULL`, then queue-&gt;lock is used for the queuing ioctls (`VIDIOC_REQBUFS`, `CREATE_BUFS`, `QBUF`, `DQBUF`,  `QUERYBUF`, `PREPARE_BUF`, `STREAMON` and `STREAMOFF`) instead of the lock above. That way the [vb2](</kernel/hardware/driver-api/media/v4l2-videobuf2.md#rst-vb2-framework>) queuing framework does not have to wait for other ioctls.   This queue pointer is also used by the [vb2](</kernel/hardware/driver-api/media/v4l2-videobuf2.md#rst-vb2-framework>) helper functions to check for queuing ownership (i.e. is the filehandle calling it allowed to do the operation).

- `video_device`-&gt;prio: keeps track of the priorities. Used to implement `VIDIOC_G_PRIORITY` and `VIDIOC_S_PRIORITY`. If left to `NULL`, then it will use the struct v4l2_prio_state in `v4l2_device`. If you want to have a separate priority state per (group of) device node(s),   then you can point it to your own struct `v4l2_prio_state`.

- `video_device`-&gt;dev_parent: you only set this if v4l2_device was registered with `NULL` as the parent `device` struct. This only happens in cases where one hardware device has multiple PCI devices that all share the same `v4l2_device` core.

  The cx88 driver is an example of this: one core `v4l2_device` struct, but   it is used by both a raw video PCI device (cx8800) and a MPEG PCI device (cx8802). Since the `v4l2_device` cannot be associated with two PCI devices at the same time it is setup without a parent device. But when the struct video_device is initialized you **do** know which parent PCI device to use and so you set `dev_device` to the correct PCI device.

If you use `v4l2_ioctl_ops`, then you should set `video_device`-&gt;unlocked_ioctl to `video_ioctl2()` in your `v4l2_file_operations` struct.

In some cases you want to tell the core that a function you had specified in your `v4l2_ioctl_ops` should be ignored. You can mark such ioctls by calling this function before `video_register_device()` is called:

> `v4l2_disable_ioctl <v4l2_disable_ioctl>()` (`vdev <video_device>`, cmd).

This tends to be needed if based on external factors (e.g. which card is being used) you want to turns off certain features in `v4l2_ioctl_ops` without having to make a new struct.

The `v4l2_file_operations` struct is a subset of file_operations. The main difference is that the inode argument is omitted since it is never used.

If integration with the media framework is needed, you must initialize the `media_entity` struct embedded in the `video_device` struct (entity field) by calling `media_entity_pads_init()`:



```c
struct media_pad *pad = &my_vdev->pad;
int err;

err = media_entity_pads_init(&vdev->entity, 1, pad);
```

The pads array must have been previously initialized. There is no need to manually set the struct media_entity type and name fields.

A reference to the entity will be automatically acquired/released when the video device is opened/closed.

<a id="rst-ioctls-and-locking"></a>

## ioctls and locking

The V4L core provides optional locking services. The main service is the lock field in struct video_device, which is a pointer to a mutex. If you set this pointer, then that will be used by unlocked_ioctl to serialize all ioctls.

If you are using the [videobuf2 framework](</kernel/hardware/driver-api/media/v4l2-videobuf2.md#rst-vb2-framework>), then there is a second lock that you can set: `video_device`-&gt;queue-&gt;lock. If set, then this lock will be used instead of `video_device`-&gt;lock to serialize all queuing ioctls (see the previous section for the full list of those ioctls).

The advantage of using a different lock for the queuing ioctls is that for some drivers (particularly USB drivers) certain commands such as setting controls can take a long time, so you want to use a separate lock for the buffer queuing ioctls. That way your `VIDIOC_DQBUF` doesn't stall because the driver is busy changing the e.g. exposure of the webcam.

Of course, you can always do all the locking yourself by leaving both lock pointers at `NULL`.

In the case of [videobuf2](</kernel/hardware/driver-api/media/v4l2-videobuf2.md#rst-vb2-framework>) you must set the `queue->lock` pointer to the lock you use to serialize the queuing ioctls. This ensures that that lock is released while waiting in `VIDIOC_DQBUF` for a buffer to arrive, and it is retaken afterwards.

The implementation of a hotplug disconnect should also take the lock from `video_device` before calling v4l2_device_disconnect. If you are also using `video_device`-&gt;queue-&gt;lock, then you have to first lock `video_device`-&gt;queue-&gt;lock followed by `video_device`-&gt;lock. That way you can be sure no ioctl is running when you call `v4l2_device_disconnect()`.

<a id="rst-video-device-registration"></a>

## Video device registration

Next you register the video device with `video_register_device()`. This will create the character device for you.



```c
err = video_register_device(vdev, VFL_TYPE_VIDEO, -1);
if (err) {
        video_device_release(vdev); /* or kfree(my_vdev); */
        return err;
}
```

If the `v4l2_device` parent device has a not `NULL` mdev field, the video device entity will be automatically registered with the media device.

Which device is registered depends on the type argument. The following types exist:


<table>
<thead>
<tr>
<th>


`vfl_devnode_type`

</th>
<th>


Device name

</th>
<th>


Usage

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


`VFL_TYPE_VIDEO`

</td>
<td>


`/dev/videoX`

</td>
<td>


for video input/output devices

</td>
</tr>
<tr>
<td>


`VFL_TYPE_VBI`

</td>
<td>


`/dev/vbiX`

</td>
<td>


for vertical blank data (i.e. closed captions, teletext)

</td>
</tr>
<tr>
<td>


`VFL_TYPE_RADIO`

</td>
<td>


`/dev/radioX`

</td>
<td>


for radio tuners

</td>
</tr>
<tr>
<td>


`VFL_TYPE_SUBDEV`

</td>
<td>


`/dev/v4l-subdevX`

</td>
<td>


for V4L2 subdevices

</td>
</tr>
<tr>
<td>


`VFL_TYPE_SDR`

</td>
<td>


`/dev/swradioX`

</td>
<td>


for Software Defined Radio (SDR) tuners

</td>
</tr>
<tr>
<td>


`VFL_TYPE_TOUCH`

</td>
<td>


`/dev/v4l-touchX`

</td>
<td>


for touch sensors

</td>
</tr>
</tbody>
</table>

The last argument gives you a certain amount of control over the device node number used (i.e. the X in `videoX`). Normally you will pass -1 to let the v4l2 framework pick the first free number. But sometimes users want to select a specific node number. It is common that drivers allow the user to select a specific device node number through a driver module option. That number is then passed to this function and video_register_device will attempt to select that device node number. If that number was already in use, then the next free device node number will be selected and it will send a warning to the kernel log.

Another use-case is if a driver creates many devices. In that case it can be useful to place different video devices in separate ranges. For example, video capture devices start at 0, video output devices start at 16. So you can use the last argument to specify a minimum device node number and the v4l2 framework will try to pick the first free number that is equal or higher to what you passed. If that fails, then it will just pick the first free number.

Since in this case you do not care about a warning about not being able to select the specified device node number, you can call the function `video_register_device_no_warn()` instead.

Whenever a device node is created some attributes are also created for you. If you look in `/sys/class/video4linux` you see the devices. Go into e.g. `video0` and you will see 'name', 'dev_debug' and 'index' attributes. The 'name' attribute is the 'name' field of the video_device struct. The 'dev_debug' attribute can be used to enable core debugging. See the next section for more detailed information on this.

The 'index' attribute is the index of the device node: for each call to `video_register_device()` the index is just increased by 1. The first video device node you register always starts with index 0.

Users can setup udev rules that utilize the index attribute to make fancy device names (e.g. '`mpegX`' for MPEG video capture device nodes).

After the device was successfully registered, then you can use these fields:

- `video_device`-&gt;vfl_type: the device type passed to `video_register_device()`.

- `video_device`-&gt;minor: the assigned device minor number.

- `video_device`-&gt;num: the device node number (i.e. the X in `videoX`).

- `video_device`-&gt;index: the device index number.

If the registration failed, then you need to call `video_device_release()` to free the allocated `video_device` struct, or free your own struct if the `video_device` was embedded in it. The `vdev->release()` callback will never be called if the registration failed, nor should you ever attempt to unregister the device if the registration failed.

<a id="rst-video-device-debugging"></a>

## video device debugging

The 'dev_debug' attribute that is created for each video, vbi, radio or swradio device in `/sys/class/video4linux/<devX>/` allows you to enable logging of file operations.

It is a bitmask and the following bits can be set:

<!-- tabularcolumns: |p{5ex}|L| -->


<table>
<thead>
<tr>
<th>


Mask

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x01

</td>
<td>


Log the ioctl name and error code. VIDIOC\_(D)QBUF ioctls are only logged if bit 0x08 is also set.

</td>
</tr>
<tr>
<td>


0x02

</td>
<td>


Log the ioctl name arguments and error code. VIDIOC\_(D)QBUF ioctls are only logged if bit 0x08 is also set.

</td>
</tr>
<tr>
<td>


0x04

</td>
<td>


Log the file operations open, release, read, write, mmap and get_unmapped_area. The read and write operations are only logged if bit 0x08 is also set.

</td>
</tr>
<tr>
<td>


0x08

</td>
<td>


Log the read and write file operations and the VIDIOC_QBUF and VIDIOC_DQBUF ioctls.

</td>
</tr>
<tr>
<td>


0x10

</td>
<td>


Log the poll file operation.

</td>
</tr>
<tr>
<td>


0x20

</td>
<td>


Log error and messages in the control operations.

</td>
</tr>
</tbody>
</table>

<a id="rst-video-device-cleanup"></a>

## Video device cleanup

When the video device nodes have to be removed, either during the unload of the driver or because the USB device was disconnected, then you should unregister them with:

> `video_unregister_device()` (`vdev <video_device>`);

This will remove the device nodes from sysfs (causing udev to remove them from `/dev`).

After `video_unregister_device()` returns no new opens can be done. However, in the case of USB devices some application might still have one of these device nodes open. So after the unregister all file operations (except release, of course) will return an error as well.

When the last user of the video device node exits, then the `vdev->release()` callback is called and you can do the final cleanup there.

Don't forget to cleanup the media entity associated with the video device if it has been initialized:

> `media_entity_cleanup <media_entity_cleanup>()` (&amp;vdev-&gt;entity);

This can be done from the release callback.

<a id="rst-helper-functions"></a>

## helper functions

There are a few useful helper functions:

- file and `video_device` private data

You can set/get driver private data in the video_device struct using:

> `video_get_drvdata <video_get_drvdata>()` (`vdev <video_device>`);
>
> `video_set_drvdata <video_set_drvdata>()` (`vdev <video_device>`);

Note that you can safely call `video_set_drvdata()` before calling `video_register_device()`.

And this function:

> `video_devdata <video_devdata>()` (struct file \*file);

returns the video_device belonging to the file struct.

The `video_devdata()` function combines `video_get_drvdata()` with `video_devdata()`:

> `video_drvdata <video_drvdata>()` (struct file \*file);

You can go from a `video_device` struct to the v4l2_device struct using:



```c
struct v4l2_device *v4l2_dev = vdev->v4l2_dev;
```

- Device node name

The `video_device` node kernel name can be retrieved using:

> `video_device_node_name <video_device_node_name>()` (`vdev <video_device>`);

The name is used as a hint by userspace tools such as udev. The function should be used where possible instead of accessing the video_device::num and video_device::minor fields.

<a id="rst-video-device-functions-and-data-structures"></a>

## video_device functions and data structures


#### <a id="c-enum-vfl_devnode_type"></a>`enum vfl_devnode_type`

type of V4L2 device node

**Constants**

- `VFL_TYPE_VIDEO`: for video input/output devices
- `VFL_TYPE_VBI`: for vertical blank data (i.e. closed captions, teletext)
- `VFL_TYPE_RADIO`: for radio tuners
- `VFL_TYPE_SUBDEV`: for V4L2 subdevices
- `VFL_TYPE_SDR`: for Software Defined Radio tuners
- `VFL_TYPE_TOUCH`: for touch sensors
- `VFL_TYPE_MAX`: number of VFL types, must always be last in the enum

#### <a id="c-enum-vfl_devnode_direction"></a>`enum vfl_devnode_direction`

Identifies if a [`struct video_device`](#c-struct-video_device) corresponds to a receiver, a transmitter or a mem-to-mem device.

**Constants**

- `VFL_DIR_RX`: device is a receiver.
- `VFL_DIR_TX`: device is a transmitter.
- `VFL_DIR_M2M`: device is a memory to memory device.

**Note**

Ignored if [`enum vfl_devnode_type`](#c-enum-vfl_devnode_type) is `VFL_TYPE_SUBDEV`.

#### <a id="c-enum-v4l2_video_device_flags"></a>`enum v4l2_video_device_flags`

Flags used by [`struct video_device`](#c-struct-video_device)

**Constants**

- `V4L2_FL_REGISTERED`: indicates that a [`struct video_device`](#c-struct-video_device) is registered.
  Drivers can clear this flag if they want to block all future
  device access. It is cleared by video_unregister_device.
- `V4L2_FL_USES_V4L2_FH`: indicates that file->private_data points to [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh).
  This flag is set by the core when [`v4l2_fh_init()`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-v4l2_fh_init) is called.
  All drivers must use it.
- `V4L2_FL_QUIRK_INVERTED_CROP`: some old M2M drivers use g/s_crop/cropcap incorrectly: crop and
  compose are swapped. If this flag is set, then the selection
  targets are swapped in the g/s_crop/cropcap functions in v4l2-ioctl.c.
  This allows those drivers to correctly implement the selection API,
  but the old crop API will still work as expected in order to preserve
  backwards compatibility.
  Never set this flag for new drivers.
- `V4L2_FL_SUBDEV_RO_DEVNODE`: indicates that the video device node is registered in read-only mode.
  The flag only applies to device nodes registered for sub-devices, it is
  set by the core when the sub-devices device nodes are registered with
  [`v4l2_device_register_ro_subdev_nodes()`](/kernel/hardware/driver-api/media/v4l2-device.md#c-v4l2_device_register_ro_subdev_nodes) and used by the sub-device ioctl
  handler to restrict access to some ioctl calls.

#### <a id="c-struct-v4l2_prio_state"></a>`struct v4l2_prio_state`

stores the priority states

**Definition**

```c
struct v4l2_prio_state {
    atomic_t prios[4];
};
```

**Members**

- `prios`: array with elements to store the array priorities

**Description**

> [!NOTE]
> The size of **prios** array matches the number of priority types defined
> by enum `v4l2_priority`.

#### <a id="c-v4l2_prio_init"></a>`v4l2_prio_init()`

```c
void v4l2_prio_init(struct v4l2_prio_state *global)
```

initializes a struct v4l2_prio_state

**Parameters**

- `struct v4l2_prio_state *global`: pointer to [`struct v4l2_prio_state`](#c-struct-v4l2_prio_state)

#### <a id="c-v4l2_prio_change"></a>`v4l2_prio_change()`

```c
int v4l2_prio_change(struct v4l2_prio_state *global, enum v4l2_priority *local, enum v4l2_priority new)
```

changes the v4l2 file handler priority

**Parameters**

- `struct v4l2_prio_state *global`: pointer to the [`struct v4l2_prio_state`](#c-struct-v4l2_prio_state) of the device node.
- `enum v4l2_priority *local`: pointer to the desired priority, as defined by enum `v4l2_priority`
- `enum v4l2_priority new`: Priority type requested, as defined by enum `v4l2_priority`.

**Description**

> [!NOTE]
> This function should be used only by the V4L2 core.

#### <a id="c-v4l2_prio_open"></a>`v4l2_prio_open()`

```c
void v4l2_prio_open(struct v4l2_prio_state *global, enum v4l2_priority *local)
```

Implements the priority logic for a file handler open

**Parameters**

- `struct v4l2_prio_state *global`: pointer to the [`struct v4l2_prio_state`](#c-struct-v4l2_prio_state) of the device node.
- `enum v4l2_priority *local`: pointer to the desired priority, as defined by enum `v4l2_priority`

**Description**

> [!NOTE]
> This function should be used only by the V4L2 core.

#### <a id="c-v4l2_prio_close"></a>`v4l2_prio_close()`

```c
void v4l2_prio_close(struct v4l2_prio_state *global, enum v4l2_priority local)
```

Implements the priority logic for a file handler close

**Parameters**

- `struct v4l2_prio_state *global`: pointer to the [`struct v4l2_prio_state`](#c-struct-v4l2_prio_state) of the device node.
- `enum v4l2_priority local`: priority to be released, as defined by enum `v4l2_priority`

**Description**

> [!NOTE]
> This function should be used only by the V4L2 core.

#### <a id="c-v4l2_prio_max"></a>`v4l2_prio_max()`

```c
enum v4l2_priority v4l2_prio_max(struct v4l2_prio_state *global)
```

Return the maximum priority, as stored at the **global** array.

**Parameters**

- `struct v4l2_prio_state *global`: pointer to the [`struct v4l2_prio_state`](#c-struct-v4l2_prio_state) of the device node.

**Description**

> [!NOTE]
> This function should be used only by the V4L2 core.

#### <a id="c-v4l2_prio_check"></a>`v4l2_prio_check()`

```c
int v4l2_prio_check(struct v4l2_prio_state *global, enum v4l2_priority local)
```

Implements the priority logic for a file handler close

**Parameters**

- `struct v4l2_prio_state *global`: pointer to the [`struct v4l2_prio_state`](#c-struct-v4l2_prio_state) of the device node.
- `enum v4l2_priority local`: desired priority, as defined by enum `v4l2_priority` local

**Description**

> [!NOTE]
> This function should be used only by the V4L2 core.

#### <a id="c-struct-v4l2_file_operations"></a>`struct v4l2_file_operations`

fs operations used by a V4L2 device

**Definition**

```c
struct v4l2_file_operations {
        struct module *owner;
        ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);
        ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);
        __poll_t (*poll) (struct file *, struct poll_table_struct *);
        long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long);
    #ifdef CONFIG_COMPAT;
        long (*compat_ioctl32) (struct file *, unsigned int, unsigned long);
    #endif;
        unsigned long (*get_unmapped_area) (struct file *, unsigned long, unsigned long, unsigned long, unsigned long);
        int (*mmap) (struct file *, struct vm_area_struct *);
        int (*open) (struct file *);
        int (*release) (struct file *);
};
```

**Members**

- `owner`: pointer to struct module
- `read`: operations needed to implement the `read()` syscall
- `write`: operations needed to implement the `write()` syscall
- `poll`: operations needed to implement the `poll()` syscall
- `unlocked_ioctl`: operations needed to implement the `ioctl()` syscall
- `compat_ioctl32`: operations needed to implement the `ioctl()` syscall for
  the special case where the Kernel uses 64 bits instructions, but
  the userspace uses 32 bits.
- `get_unmapped_area`: called by the `mmap()` syscall, used when %!CONFIG_MMU
- `mmap`: operations needed to implement the `mmap()` syscall
- `open`: operations needed to implement the `open()` syscall
- `release`: operations needed to implement the `release()` syscall

**Description**

> [!NOTE]
> Those operations are used to implemente the fs struct file_operations
> at the V4L2 drivers. The V4L2 core overrides the fs ops with some
> extra logic needed by the subsystem.

#### <a id="c-struct-video_device"></a>`struct video_device`

Structure used to create and manage the V4L2 device nodes.

**Definition**

```c
struct video_device {
    #if defined(CONFIG_MEDIA_CONTROLLER);
        struct media_entity entity;
        struct media_intf_devnode *intf_devnode;
        struct media_pipeline pipe;
    #endif;
        const struct v4l2_file_operations *fops;
        u32 device_caps;
        struct device dev;
        struct cdev *cdev;
        struct v4l2_device *v4l2_dev;
        struct device *dev_parent;
        struct v4l2_ctrl_handler *ctrl_handler;
        struct vb2_queue *queue;
        struct v4l2_prio_state *prio;
        char name[64];
        enum vfl_devnode_type vfl_type;
        enum vfl_devnode_direction vfl_dir;
        int minor;
        u16 num;
        unsigned long flags;
        int index;
        spinlock_t fh_lock;
        struct list_head        fh_list;
        int dev_debug;
        v4l2_std_id tvnorms;
        void (*release)(struct video_device *vdev);
        const struct v4l2_ioctl_ops *ioctl_ops;
        unsigned long valid_ioctls[BITS_TO_LONGS(BASE_VIDIOC_PRIVATE)];
        struct mutex *lock;
};
```

**Members**

- `entity`: [`struct media_entity`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_entity)
- `intf_devnode`: pointer to [`struct media_intf_devnode`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_intf_devnode)
- `pipe`: [`struct media_pipeline`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_pipeline)
- `fops`: pointer to [`struct v4l2_file_operations`](#c-struct-v4l2_file_operations) for the video device
- `device_caps`: device capabilities as used in v4l2_capabilities
- `dev`: [`struct device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) for the video device
- `cdev`: character device
- `v4l2_dev`: pointer to [`struct v4l2_device`](/kernel/hardware/driver-api/media/v4l2-device.md#c-struct-v4l2_device) parent
- `dev_parent`: pointer to [`struct device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) parent
- `ctrl_handler`: Control handler associated with this device node.
  May be NULL.
- `queue`: [`struct vb2_queue`](/kernel/hardware/driver-api/media/v4l2-videobuf2.md#c-struct-vb2_queue) associated with this device node. May be NULL.
- `prio`: pointer to [`struct v4l2_prio_state`](#c-struct-v4l2_prio_state) with device's Priority state.
  If NULL, then v4l2_dev->prio will be used.
- `name`: video device name
- `vfl_type`: V4L device type, as defined by [`enum vfl_devnode_type`](#c-enum-vfl_devnode_type)
- `vfl_dir`: V4L receiver, transmitter or m2m
- `minor`: device node 'minor'. It is set to -1 if the registration failed
- `num`: number of the video device node
- `flags`: video device flags. Use bitops to set/clear/test flags.
  Contains a set of [`enum v4l2_video_device_flags`](#c-enum-v4l2_video_device_flags).
- `index`: attribute to differentiate multiple indices on one physical device
- `fh_lock`: Lock for all v4l2_fhs
- `fh_list`: List of [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh)
- `dev_debug`: Internal device debug flags, not for use by drivers
- `tvnorms`: Supported tv norms
- `release`: video device `release()` callback
- `ioctl_ops`: pointer to [`struct v4l2_ioctl_ops`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) with ioctl callbacks
- `valid_ioctls`: bitmap with the valid ioctls for this device
- `lock`: pointer to `struct mutex` serialization lock

**Description**

> [!NOTE]
> Only set **dev_parent** if that can't be deduced from **v4l2_dev**.

#### <a id="c-media_entity_to_video_device"></a>`media_entity_to_video_device()`

```c
media_entity_to_video_device(__entity)
```

Returns a [`struct video_device`](#c-struct-video_device) from the [`struct media_entity`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_entity) embedded on it.

**Parameters**

- `__entity`: pointer to [`struct media_entity`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_entity), may be NULL

#### <a id="c-to_video_device"></a>`to_video_device()`

```c
to_video_device(cd)
```

Returns a [`struct video_device`](#c-struct-video_device) from the [`struct device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) embedded on it.

**Parameters**

- `cd`: pointer to [`struct device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device)

#### <a id="c-__video_register_device"></a>`__video_register_device()`

```c
int __video_register_device(struct video_device *vdev, enum vfl_devnode_type type, int nr, int warn_if_nr_in_use, struct module *owner)
```

register video4linux devices

**Parameters**

- `struct video_device *vdev`: struct video_device to register
- `enum vfl_devnode_type type`: type of device to register, as defined by [`enum vfl_devnode_type`](#c-enum-vfl_devnode_type)
- `int nr`: which device node number is desired:
  (0 == /dev/video0, 1 == /dev/video1, ..., -1 == first free)
- `int warn_if_nr_in_use`: warn if the desired device node number
  was already in use and another number was chosen instead.
- `struct module *owner`: module that owns the video device node

**Description**

The registration code assigns minor numbers and device node numbers
based on the requested type and registers the new device node with
the kernel.

This function assumes that struct video_device was zeroed when it
was allocated and does not contain any stale date.

An error is returned if no free minor or device node number could be
found, or if the registration of the device node failed.

Returns 0 on success.

> [!NOTE]
> This function is meant to be used only inside the V4L2 core.
> Drivers should use [`video_register_device()`](#c-video_register_device) or
> [`video_register_device_no_warn()`](#c-video_register_device_no_warn).

#### <a id="c-video_register_device"></a>`video_register_device()`

```c
int video_register_device(struct video_device *vdev, enum vfl_devnode_type type, int nr)
```

register video4linux devices

**Parameters**

- `struct video_device *vdev`: struct video_device to register
- `enum vfl_devnode_type type`: type of device to register, as defined by [`enum vfl_devnode_type`](#c-enum-vfl_devnode_type)
- `int nr`: which device node number is desired:
  (0 == /dev/video0, 1 == /dev/video1, ..., -1 == first free)

**Description**

Internally, it calls [`__video_register_device()`](#c-__video_register_device). Please see its
documentation for more details.

> [!NOTE]
> if video_register_device fails, the `release()` callback of
> [`struct video_device`](#c-struct-video_device) structure is *not* called, so the caller
> is responsible for freeing any data. Usually that means that
> you [`video_device_release()`](#c-video_device_release) should be called on failure.

#### <a id="c-video_register_device_no_warn"></a>`video_register_device_no_warn()`

```c
int video_register_device_no_warn(struct video_device *vdev, enum vfl_devnode_type type, int nr)
```

register video4linux devices

**Parameters**

- `struct video_device *vdev`: struct video_device to register
- `enum vfl_devnode_type type`: type of device to register, as defined by [`enum vfl_devnode_type`](#c-enum-vfl_devnode_type)
- `int nr`: which device node number is desired:
  (0 == /dev/video0, 1 == /dev/video1, ..., -1 == first free)

**Description**

This function is identical to [`video_register_device()`](#c-video_register_device) except that no
warning is issued if the desired device node number was already in use.

Internally, it calls [`__video_register_device()`](#c-__video_register_device). Please see its
documentation for more details.

> [!NOTE]
> if video_register_device fails, the `release()` callback of
> [`struct video_device`](#c-struct-video_device) structure is *not* called, so the caller
> is responsible for freeing any data. Usually that means that
> you [`video_device_release()`](#c-video_device_release) should be called on failure.

#### <a id="c-video_unregister_device"></a>`video_unregister_device()`

```c
void video_unregister_device(struct video_device *vdev)
```

Unregister video devices.

**Parameters**

- `struct video_device *vdev`: [`struct video_device`](#c-struct-video_device) to register

**Description**

Does nothing if vdev == NULL or if [`video_is_registered()`](#c-video_is_registered) returns false.

#### <a id="c-video_device_alloc"></a>`video_device_alloc()`

```c
struct video_device * video_device_alloc(void)
```

helper function to alloc [`struct video_device`](#c-struct-video_device)

**Parameters**

- `void`: no arguments

**Description**

Returns NULL if `-ENOMEM` or a [`struct video_device`](#c-struct-video_device) on success.

#### <a id="c-video_device_release"></a>`video_device_release()`

```c
void video_device_release(struct video_device *vdev)
```

helper function to release [`struct video_device`](#c-struct-video_device)

**Parameters**

- `struct video_device *vdev`: pointer to [`struct video_device`](#c-struct-video_device)

**Description**

Can also be used for video_device->release\(\).

#### <a id="c-video_device_release_empty"></a>`video_device_release_empty()`

```c
void video_device_release_empty(struct video_device *vdev)
```

helper function to implement the video_device->release\(\) callback.

**Parameters**

- `struct video_device *vdev`: pointer to [`struct video_device`](#c-struct-video_device)

**Description**

This release function does nothing.

It should be used when the video_device is a static global struct.

> [!NOTE]
> Having a static video_device is a dubious construction at best.

#### <a id="c-v4l2_disable_ioctl"></a>`v4l2_disable_ioctl()`

```c
void v4l2_disable_ioctl(struct video_device *vdev, unsigned int cmd)
```

mark that a given command isn't implemented. shouldn't use core locking

**Parameters**

- `struct video_device *vdev`: pointer to [`struct video_device`](#c-struct-video_device)
- `unsigned int cmd`: ioctl command

**Description**

This function allows drivers to provide just one v4l2_ioctl_ops struct, but
disable ioctls based on the specific card that is actually found.

> [!NOTE]
> This must be called before video_register_device.
> See also the comments for `determine_valid_ioctls()`.

#### <a id="c-video_get_drvdata"></a>`video_get_drvdata()`

```c
void * video_get_drvdata(struct video_device *vdev)
```

gets private data from [`struct video_device`](#c-struct-video_device).

**Parameters**

- `struct video_device *vdev`: pointer to [`struct video_device`](#c-struct-video_device)

**Description**

returns a pointer to the private data

#### <a id="c-video_set_drvdata"></a>`video_set_drvdata()`

```c
void video_set_drvdata(struct video_device *vdev, void *data)
```

sets private data from [`struct video_device`](#c-struct-video_device).

**Parameters**

- `struct video_device *vdev`: pointer to [`struct video_device`](#c-struct-video_device)
- `void *data`: private data pointer

#### <a id="c-video_devdata"></a>`video_devdata()`

```c
struct video_device * video_devdata(struct file *file)
```

gets [`struct video_device`](#c-struct-video_device) from struct file.

**Parameters**

- `struct file *file`: pointer to struct file

#### <a id="c-video_drvdata"></a>`video_drvdata()`

```c
void * video_drvdata(struct file *file)
```

gets private data from [`struct video_device`](#c-struct-video_device) using the struct file.

**Parameters**

- `struct file *file`: pointer to struct file

**Description**

This is function combines both [`video_get_drvdata()`](#c-video_get_drvdata) and [`video_devdata()`](#c-video_devdata)
as this is used very often.

#### <a id="c-video_device_node_name"></a>`video_device_node_name()`

```c
const char * video_device_node_name(struct video_device *vdev)
```

returns the video device name

**Parameters**

- `struct video_device *vdev`: pointer to [`struct video_device`](#c-struct-video_device)

**Description**

Returns the device name string

#### <a id="c-video_is_registered"></a>`video_is_registered()`

```c
int video_is_registered(struct video_device *vdev)
```

returns true if the [`struct video_device`](#c-struct-video_device) is registered.

**Parameters**

- `struct video_device *vdev`: pointer to [`struct video_device`](#c-struct-video_device)

#### <a id="c-v4l2_debugfs_root"></a>`v4l2_debugfs_root()`

```c
struct dentry * v4l2_debugfs_root(void)
```

returns the dentry of the top-level "v4l2" debugfs dir

**Parameters**

- `void`: no arguments

**Description**

If this directory does not yet exist, then it will be created.

#### <a id="c-video_device_pipeline_start"></a>`video_device_pipeline_start()`

```c
int video_device_pipeline_start(struct video_device *vdev, struct media_pipeline *pipe)
```

Mark a pipeline as streaming

**Parameters**

- `struct video_device *vdev`: Starting video device
- `struct media_pipeline *pipe`: Media pipeline to be assigned to all entities in the pipeline.

**Description**

Mark all entities connected to a given video device through enabled links,
either directly or indirectly, as streaming. The given pipeline object is
assigned to every pad in the pipeline and stored in the media_pad pipe
field.

Calls to this function can be nested, in which case the same number of
[`video_device_pipeline_stop()`](#c-video_device_pipeline_stop) calls will be required to stop streaming. The
pipeline pointer must be identical for all nested calls to
[`video_device_pipeline_start()`](#c-video_device_pipeline_start).

The video device must contain a single pad.

This is a convenience wrapper around [`media_pipeline_start()`](/kernel/hardware/driver-api/media/mc-core.md#c-media_pipeline_start).

#### <a id="c-__video_device_pipeline_start"></a>`__video_device_pipeline_start()`

```c
int __video_device_pipeline_start(struct video_device *vdev, struct media_pipeline *pipe)
```

Mark a pipeline as streaming

**Parameters**

- `struct video_device *vdev`: Starting video device
- `struct media_pipeline *pipe`: Media pipeline to be assigned to all entities in the pipeline.

**Description**

..note:: This is the non-locking version of [`video_device_pipeline_start()`](#c-video_device_pipeline_start)

The video device must contain a single pad.

This is a convenience wrapper around [`__media_pipeline_start()`](/kernel/hardware/driver-api/media/mc-core.md#c-__media_pipeline_start).

#### <a id="c-video_device_pipeline_stop"></a>`video_device_pipeline_stop()`

```c
void video_device_pipeline_stop(struct video_device *vdev)
```

Mark a pipeline as not streaming

**Parameters**

- `struct video_device *vdev`: Starting video device

**Description**

Mark all entities connected to a given video device through enabled links,
either directly or indirectly, as not streaming. The media_pad pipe field
is reset to `NULL`.

If multiple calls to [`media_pipeline_start()`](/kernel/hardware/driver-api/media/mc-core.md#c-media_pipeline_start) have been made, the same
number of calls to this function are required to mark the pipeline as not
streaming.

The video device must contain a single pad.

This is a convenience wrapper around [`media_pipeline_stop()`](/kernel/hardware/driver-api/media/mc-core.md#c-media_pipeline_stop).

#### <a id="c-__video_device_pipeline_stop"></a>`__video_device_pipeline_stop()`

```c
void __video_device_pipeline_stop(struct video_device *vdev)
```

Mark a pipeline as not streaming

**Parameters**

- `struct video_device *vdev`: Starting video device

**Description**

> [!NOTE]
> This is the non-locking version of [`media_pipeline_stop()`](/kernel/hardware/driver-api/media/mc-core.md#c-media_pipeline_stop)

The video device must contain a single pad.

This is a convenience wrapper around [`__media_pipeline_stop()`](/kernel/hardware/driver-api/media/mc-core.md#c-__media_pipeline_stop).

#### <a id="c-video_device_pipeline_alloc_start"></a>`video_device_pipeline_alloc_start()`

```c
int video_device_pipeline_alloc_start(struct video_device *vdev)
```

Mark a pipeline as streaming

**Parameters**

- `struct video_device *vdev`: Starting video device

**Description**

[`video_device_pipeline_alloc_start()`](#c-video_device_pipeline_alloc_start) is similar to [`video_device_pipeline_start()`](#c-video_device_pipeline_start)
but instead of working on a given pipeline the function will use an
existing pipeline if the video device is already part of a pipeline, or
allocate a new pipeline.

Calls to [`video_device_pipeline_alloc_start()`](#c-video_device_pipeline_alloc_start) must be matched with
[`video_device_pipeline_stop()`](#c-video_device_pipeline_stop).

#### <a id="c-video_device_pipeline"></a>`video_device_pipeline()`

```c
struct media_pipeline * video_device_pipeline(struct video_device *vdev)
```

Get the media pipeline a video device is part of

**Parameters**

- `struct video_device *vdev`: The video device

**Description**

This function returns the media pipeline that a video device has been
associated with when constructing the pipeline with
[`video_device_pipeline_start()`](#c-video_device_pipeline_start). The pointer remains valid until
[`video_device_pipeline_stop()`](#c-video_device_pipeline_stop) is called.

The video device must contain a single pad.

This is a convenience wrapper around [`media_entity_pipeline()`](/kernel/hardware/driver-api/media/mc-core.md#c-media_entity_pipeline).

**Return**

The media_pipeline the video device is part of, or NULL if the video
device is not part of any pipeline.

---

# V4L2 device instance

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Each device instance is represented by a struct v4l2_device. Very simple devices can just allocate this struct, but most of the time you would embed this struct inside a larger struct.

<a id="rst-v4l2-device-instance"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Each device instance is represented by a struct v4l2_device. Very simple devices can just allocate this struct, but most of the time you would embed this struct inside a larger struct.

You must register the device instance by calling:

> `v4l2_device_register <v4l2_device_register>()` (dev, `v4l2_dev <v4l2_device>`).

Registration will initialize the `v4l2_device` struct. If the dev-&gt;driver_data field is `NULL`, it will be linked to `v4l2_dev <v4l2_device>` argument.

Drivers that want integration with the media device framework need to set dev-&gt;driver_data manually to point to the driver-specific device structure that embed the struct v4l2_device instance. This is achieved by a `dev_set_drvdata()` call before registering the V4L2 device instance. They must also set the struct v4l2_device mdev field to point to a properly initialized and registered `media_device` instance.

If `v4l2_dev <v4l2_device>`-&gt;name is empty then it will be set to a value derived from dev (driver name followed by the bus_id, to be precise). If you set it up before  calling `v4l2_device_register()` then it will be untouched. If dev is `NULL`, then you **must** setup `v4l2_dev <v4l2_device>`-&gt;name before calling `v4l2_device_register()`.

You can use `v4l2_device_set_name()` to set the name based on a driver name and a driver-global atomic_t instance. This will generate names like `ivtv0`, `ivtv1`, etc. If the name ends with a digit, then it will insert a dash: `cx18-0`, `cx18-1`, etc. This function returns the instance number.

The first `dev` argument is normally the `struct device` pointer of a `pci_dev`, `usb_interface` or `platform_device`. It is rare for dev to be `NULL`, but it happens with ISA devices or when one device creates multiple PCI devices, thus making it impossible to associate `v4l2_dev <v4l2_device>` with a particular parent.

You can also supply a `notify()` callback that can be called by sub-devices to notify you of events. Whether you need to set this depends on the sub-device. Any notifications a sub-device supports must be defined in a header in `include/media/subdevice.h`.

V4L2 devices are unregistered by calling:

> `v4l2_device_unregister()` (`v4l2_dev <v4l2_device>`).

If the dev-&gt;driver_data field points to `v4l2_dev <v4l2_device>`, it will be reset to `NULL`. Unregistering will also automatically unregister all subdevs from the device.

If you have a hotpluggable device (e.g. a USB device), then when a disconnect happens the parent device becomes invalid. Since `v4l2_device` has a pointer to that parent device it has to be cleared as well to mark that the parent is gone. To do this call:

> `v4l2_device_disconnect()` (`v4l2_dev <v4l2_device>`).

This does *not* unregister the subdevs, so you still need to call the `v4l2_device_unregister()` function for that. If your driver is not hotpluggable, then there is no need to call `v4l2_device_disconnect()`.

Sometimes you need to iterate over all devices registered by a specific driver. This is usually the case if multiple device drivers use the same hardware. E.g. the ivtvfb driver is a framebuffer driver that uses the ivtv hardware. The same is true for alsa drivers for example.

You can iterate over all registered devices as follows:



```c
static int callback(struct device *dev, void *p)
{
        struct v4l2_device *v4l2_dev = dev_get_drvdata(dev);

        /* test if this device was inited */
        if (v4l2_dev == NULL)
                return 0;
        ...
        return 0;
}

int iterate(void *p)
{
        struct device_driver *drv;
        int err;

        /* Find driver 'ivtv' on the PCI bus.
        pci_bus_type is a global. For USB buses use usb_bus_type. */
        drv = driver_find("ivtv", &pci_bus_type);
        /* iterate over all ivtv device instances */
        err = driver_for_each_device(drv, NULL, p, callback);
        put_driver(drv);
        return err;
}
```

Sometimes you need to keep a running counter of the device instance. This is commonly used to map a device instance to an index of a module option array.

The recommended approach is as follows:



```c
static atomic_t drv_instance = ATOMIC_INIT(0);

static int drv_probe(struct pci_dev *pdev, const struct pci_device_id *pci_id)
{
        ...
        state->instance = atomic_inc_return(&drv_instance) - 1;
}
```

If you have multiple device nodes then it can be difficult to know when it is safe to unregister `v4l2_device` for hotpluggable devices. For this purpose `v4l2_device` has refcounting support. The refcount is increased whenever `video_register_device()` is called and it is decreased whenever that device node is released. When the refcount reaches zero, then the `v4l2_device` release() callback is called. You can do your final cleanup there.

If other device nodes (e.g. ALSA) are created, then you can increase and decrease the refcount manually as well by calling:

> `v4l2_device_get()` (`v4l2_dev <v4l2_device>`).

or:

> `v4l2_device_put()` (`v4l2_dev <v4l2_device>`).

Since the initial refcount is 1 you also need to call `v4l2_device_put()` in the `disconnect()` callback (for USB devices) or in the `remove()` callback (for e.g. PCI devices), otherwise the refcount will never reach 0.

<a id="rst-v4l2-device-functions-and-data-structures"></a>

## v4l2_device functions and data structures


#### <a id="c-struct-v4l2_device"></a>`struct v4l2_device`

main struct to for V4L2 device drivers

**Definition**

```c
struct v4l2_device {
    struct device *dev;
    struct media_device *mdev;
    struct list_head subdevs;
    spinlock_t lock;
    char name[36];
    void (*notify)(struct v4l2_subdev *sd, unsigned int notification, void *arg);
    struct v4l2_ctrl_handler *ctrl_handler;
    struct v4l2_prio_state prio;
    struct kref ref;
    void (*release)(struct v4l2_device *v4l2_dev);
};
```

**Members**

- `dev`: pointer to struct device.
- `mdev`: pointer to struct media_device, may be NULL.
- `subdevs`: used to keep track of the registered subdevs
- `lock`: lock this struct; can be used by the driver as well
  if this struct is embedded into a larger struct.
- `name`: unique device name, by default the driver name + bus ID
- `notify`: notify operation called by some sub-devices.
- `ctrl_handler`: The control handler. May be `NULL`.
- `prio`: Device's priority state
- `ref`: Keep track of the references to this struct.
- `release`: Release function that is called when the ref count
  goes to 0.

**Description**

Each instance of a V4L2 device should create the v4l2_device struct,
either stand-alone or embedded in a larger struct.

It allows easy access to sub-devices (see v4l2-subdev.h) and provides
basic V4L2 device-level support.

> [!NOTE]
> \#) **dev->driver_data** points to this struct.
> \#) **dev** might be `NULL` if there is no parent device

#### <a id="c-v4l2_device_get"></a>`v4l2_device_get()`

```c
void v4l2_device_get(struct v4l2_device *v4l2_dev)
```

gets a V4L2 device reference

**Parameters**

- `struct v4l2_device *v4l2_dev`: pointer to struct [`v4l2_device`](#c-struct-v4l2_device)

**Description**

This is an ancillary routine meant to increment the usage for the
struct [`v4l2_device`](#c-struct-v4l2_device) pointed by **v4l2_dev**.

#### <a id="c-v4l2_device_put"></a>`v4l2_device_put()`

```c
int v4l2_device_put(struct v4l2_device *v4l2_dev)
```

puts a V4L2 device reference

**Parameters**

- `struct v4l2_device *v4l2_dev`: pointer to struct [`v4l2_device`](#c-struct-v4l2_device)

**Description**

This is an ancillary routine meant to decrement the usage for the
struct [`v4l2_device`](#c-struct-v4l2_device) pointed by **v4l2_dev**.

#### <a id="c-v4l2_device_register"></a>`v4l2_device_register()`

```c
int v4l2_device_register(struct device *dev, struct v4l2_device *v4l2_dev)
```

Initialize v4l2_dev and make **dev->driver_data** point to **v4l2_dev**.

**Parameters**

- `struct device *dev`: pointer to struct [`device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device)
- `struct v4l2_device *v4l2_dev`: pointer to struct [`v4l2_device`](#c-struct-v4l2_device)

**Description**

> [!NOTE]
> **dev** may be `NULL` in rare cases (ISA devices).
> In such case the caller must fill in the **v4l2_dev->name** field
> before calling this function.

#### <a id="c-v4l2_device_set_name"></a>`v4l2_device_set_name()`

```c
int v4l2_device_set_name(struct v4l2_device *v4l2_dev, const char *basename, atomic_t *instance)
```

Optional function to initialize the name field of struct [`v4l2_device`](#c-struct-v4l2_device)

**Parameters**

- `struct v4l2_device *v4l2_dev`: pointer to struct [`v4l2_device`](#c-struct-v4l2_device)
- `const char *basename`: base name for the device name
- `atomic_t *instance`: pointer to a static atomic_t var with the instance usage for
  the device driver.

**Description**

[`v4l2_device_set_name()`](#c-v4l2_device_set_name) initializes the name field of struct [`v4l2_device`](#c-struct-v4l2_device)
using the driver name and a driver-global atomic_t instance.

This function will increment the instance counter and returns the
instance value used in the name.

**Example**

static atomic_t drv_instance = ATOMIC_INIT(0);

\...

instance = v4l2_device_set_name(&\ v4l2_dev, "foo", &\ drv_instance);

The first time this is called the name field will be set to foo0 and
this function returns 0. If the name ends with a digit (e.g. cx18),
then the name will be set to cx18-0 since cx180 would look really odd.

#### <a id="c-v4l2_device_disconnect"></a>`v4l2_device_disconnect()`

```c
void v4l2_device_disconnect(struct v4l2_device *v4l2_dev)
```

Change V4L2 device state to disconnected.

**Parameters**

- `struct v4l2_device *v4l2_dev`: pointer to struct v4l2_device

**Description**

Should be called when the USB parent disconnects.
Since the parent disappears, this ensures that **v4l2_dev** doesn't have
an invalid parent pointer.

> [!NOTE]
> This function sets **v4l2_dev->dev** to NULL.

#### <a id="c-v4l2_device_unregister"></a>`v4l2_device_unregister()`

```c
void v4l2_device_unregister(struct v4l2_device *v4l2_dev)
```

Unregister all sub-devices and any other resources related to **v4l2_dev**.

**Parameters**

- `struct v4l2_device *v4l2_dev`: pointer to struct v4l2_device

#### <a id="c-v4l2_device_register_subdev"></a>`v4l2_device_register_subdev()`

```c
v4l2_device_register_subdev(v4l2_dev, sd)
```

Registers a subdev with a v4l2 device.

**Parameters**

- `v4l2_dev`: pointer to struct [`v4l2_device`](#c-struct-v4l2_device)
- `sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)

**Description**

While registered, the subdev module is marked as in-use.

An error is returned if the module is no longer loaded on any attempts
to register it.

#### <a id="c-v4l2_device_unregister_subdev"></a>`v4l2_device_unregister_subdev()`

```c
void v4l2_device_unregister_subdev(struct v4l2_subdev *sd)
```

Unregisters a subdev with a v4l2 device.

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)

**Description**

#### <a id="c-__v4l2_device_register_subdev_nodes"></a>`__v4l2_device_register_subdev_nodes()`

```c
int __v4l2_device_register_subdev_nodes(struct v4l2_device *v4l2_dev, bool read_only)
```

Registers device nodes for all subdevs of the v4l2 device that are marked with the `V4L2_SUBDEV_FL_HAS_DEVNODE` flag.

**Parameters**

- `struct v4l2_device *v4l2_dev`: pointer to struct v4l2_device
- `bool read_only`: subdevices read-only flag. True to register the subdevices
  device nodes in read-only mode, false to allow full access to the
  subdevice userspace API.

#### <a id="c-v4l2_device_register_subdev_nodes"></a>`v4l2_device_register_subdev_nodes()`

```c
int v4l2_device_register_subdev_nodes(struct v4l2_device *v4l2_dev)
```

Registers subdevices device nodes with unrestricted access to the subdevice userspace operations

**Parameters**

- `struct v4l2_device *v4l2_dev`: pointer to struct v4l2_device

**Description**

Internally calls [`__v4l2_device_register_subdev_nodes()`](#c-__v4l2_device_register_subdev_nodes). See its documentation
for more details.

#### <a id="c-v4l2_device_register_ro_subdev_nodes"></a>`v4l2_device_register_ro_subdev_nodes()`

```c
int v4l2_device_register_ro_subdev_nodes(struct v4l2_device *v4l2_dev)
```

Registers subdevices device nodes in read-only mode

**Parameters**

- `struct v4l2_device *v4l2_dev`: pointer to struct v4l2_device

**Description**

Internally calls [`__v4l2_device_register_subdev_nodes()`](#c-__v4l2_device_register_subdev_nodes). See its documentation
for more details.

#### <a id="c-v4l2_subdev_notify"></a>`v4l2_subdev_notify()`

```c
void v4l2_subdev_notify(struct v4l2_subdev *sd, unsigned int notification, void *arg)
```

Sends a notification to v4l2_device.

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)
- `unsigned int notification`: type of notification. Please notice that the notification
  type is driver-specific.
- `void *arg`: arguments for the notification. Those are specific to each
  notification type.

#### <a id="c-v4l2_device_supports_requests"></a>`v4l2_device_supports_requests()`

```c
bool v4l2_device_supports_requests(struct v4l2_device *v4l2_dev)
```

Test if requests are supported.

**Parameters**

- `struct v4l2_device *v4l2_dev`: pointer to struct v4l2_device

#### <a id="c-v4l2_device_for_each_subdev"></a>`v4l2_device_for_each_subdev()`

```c
v4l2_device_for_each_subdev(sd, v4l2_dev)
```

Helper macro that interates over all sub-devices of a given [`v4l2_device`](#c-struct-v4l2_device).

**Parameters**

- `sd`: pointer that will be filled by the macro with all
  [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev) pointer used as an iterator by the loop.
- `v4l2_dev`: [`struct v4l2_device`](#c-struct-v4l2_device) owning the sub-devices to iterate over.

**Description**

This macro iterates over all sub-devices owned by the **v4l2_dev** device.
It acts as a for loop iterator and executes the next statement with
the **sd** variable pointing to each sub-device in turn.

#### <a id="c-__v4l2_device_call_subdevs_p"></a>`__v4l2_device_call_subdevs_p()`

```c
__v4l2_device_call_subdevs_p(v4l2_dev, sd, cond, o, f, args...)
```

Calls the specified operation for all subdevs matching the condition.

**Parameters**

- `v4l2_dev`: [`struct v4l2_device`](#c-struct-v4l2_device) owning the sub-devices to iterate over.
- `sd`: pointer that will be filled by the macro with all
  [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev) pointer used as an iterator by the loop.
- `cond`: condition to be match
- `o`: name of the element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops) that contains **f**.
  Each element there groups a set of operations functions.
- `f`: operation function that will be called if **cond** matches.
  The operation functions are defined in groups, according to
  each element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops).
- `args...`: arguments for **f**.

**Description**

Ignore any errors.

**Note**

subdevs cannot be added or deleted while walking
the subdevs list.

#### <a id="c-__v4l2_device_call_subdevs"></a>`__v4l2_device_call_subdevs()`

```c
__v4l2_device_call_subdevs(v4l2_dev, cond, o, f, args...)
```

Calls the specified operation for all subdevs matching the condition.

**Parameters**

- `v4l2_dev`: [`struct v4l2_device`](#c-struct-v4l2_device) owning the sub-devices to iterate over.
- `cond`: condition to be match
- `o`: name of the element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops) that contains **f**.
  Each element there groups a set of operations functions.
- `f`: operation function that will be called if **cond** matches.
  The operation functions are defined in groups, according to
  each element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops).
- `args...`: arguments for **f**.

**Description**

Ignore any errors.

**Note**

subdevs cannot be added or deleted while walking
the subdevs list.

#### <a id="c-__v4l2_device_call_subdevs_until_err_p"></a>`__v4l2_device_call_subdevs_until_err_p()`

```c
__v4l2_device_call_subdevs_until_err_p(v4l2_dev, sd, cond, o, f, args...)
```

Calls the specified operation for all subdevs matching the condition.

**Parameters**

- `v4l2_dev`: [`struct v4l2_device`](#c-struct-v4l2_device) owning the sub-devices to iterate over.
- `sd`: pointer that will be filled by the macro with all
  [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev) sub-devices associated with **v4l2_dev**.
- `cond`: condition to be match
- `o`: name of the element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops) that contains **f**.
  Each element there groups a set of operations functions.
- `f`: operation function that will be called if **cond** matches.
  The operation functions are defined in groups, according to
  each element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops).
- `args...`: arguments for **f**.

**Description**

If the operation returns an error other than 0 or `-ENOIOCTLCMD`
for any subdevice, then abort and return with that error code, zero
otherwise.

**Note**

subdevs cannot be added or deleted while walking
the subdevs list.

#### <a id="c-__v4l2_device_call_subdevs_until_err"></a>`__v4l2_device_call_subdevs_until_err()`

```c
__v4l2_device_call_subdevs_until_err(v4l2_dev, cond, o, f, args...)
```

Calls the specified operation for all subdevs matching the condition.

**Parameters**

- `v4l2_dev`: [`struct v4l2_device`](#c-struct-v4l2_device) owning the sub-devices to iterate over.
- `cond`: condition to be match
- `o`: name of the element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops) that contains **f**.
  Each element there groups a set of operations functions.
- `f`: operation function that will be called if **cond** matches.
  The operation functions are defined in groups, according to
  each element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops).
- `args...`: arguments for **f**.

**Description**

If the operation returns an error other than 0 or `-ENOIOCTLCMD`
for any subdevice, then abort and return with that error code,
zero otherwise.

**Note**

subdevs cannot be added or deleted while walking
the subdevs list.

#### <a id="c-v4l2_device_call_all"></a>`v4l2_device_call_all()`

```c
v4l2_device_call_all(v4l2_dev, grpid, o, f, args...)
```

Calls the specified operation for all subdevs matching the [`v4l2_subdev.grp_id`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev), as assigned by the bridge driver.

**Parameters**

- `v4l2_dev`: [`struct v4l2_device`](#c-struct-v4l2_device) owning the sub-devices to iterate over.
- `grpid`: [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)->grp_id group ID to match.
  Use 0 to match them all.
- `o`: name of the element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops) that contains **f**.
  Each element there groups a set of operations functions.
- `f`: operation function that will be called if **cond** matches.
  The operation functions are defined in groups, according to
  each element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops).
- `args...`: arguments for **f**.

**Description**

Ignore any errors.

**Note**

subdevs cannot be added or deleted while walking
the subdevs list.

#### <a id="c-v4l2_device_call_until_err"></a>`v4l2_device_call_until_err()`

```c
v4l2_device_call_until_err(v4l2_dev, grpid, o, f, args...)
```

Calls the specified operation for all subdevs matching the [`v4l2_subdev.grp_id`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev), as assigned by the bridge driver, until an error occurs.

**Parameters**

- `v4l2_dev`: [`struct v4l2_device`](#c-struct-v4l2_device) owning the sub-devices to iterate over.
- `grpid`: [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)->grp_id group ID to match.
  Use 0 to match them all.
- `o`: name of the element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops) that contains **f**.
  Each element there groups a set of operations functions.
- `f`: operation function that will be called if **cond** matches.
  The operation functions are defined in groups, according to
  each element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops).
- `args...`: arguments for **f**.

**Description**

If the operation returns an error other than 0 or `-ENOIOCTLCMD`
for any subdevice, then abort and return with that error code,
zero otherwise.

**Note**

subdevs cannot be added or deleted while walking
the subdevs list.

#### <a id="c-v4l2_device_mask_call_all"></a>`v4l2_device_mask_call_all()`

```c
v4l2_device_mask_call_all(v4l2_dev, grpmsk, o, f, args...)
```

Calls the specified operation for all subdevices where a group ID matches a specified bitmask.

**Parameters**

- `v4l2_dev`: [`struct v4l2_device`](#c-struct-v4l2_device) owning the sub-devices to iterate over.
- `grpmsk`: bitmask to be checked against [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)->grp_id
  group ID to be matched. Use 0 to match them all.
- `o`: name of the element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops) that contains **f**.
  Each element there groups a set of operations functions.
- `f`: operation function that will be called if **cond** matches.
  The operation functions are defined in groups, according to
  each element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops).
- `args...`: arguments for **f**.

**Description**

Ignore any errors.

**Note**

subdevs cannot be added or deleted while walking
the subdevs list.

#### <a id="c-v4l2_device_mask_call_until_err"></a>`v4l2_device_mask_call_until_err()`

```c
v4l2_device_mask_call_until_err(v4l2_dev, grpmsk, o, f, args...)
```

Calls the specified operation for all subdevices where a group ID matches a specified bitmask.

**Parameters**

- `v4l2_dev`: [`struct v4l2_device`](#c-struct-v4l2_device) owning the sub-devices to iterate over.
- `grpmsk`: bitmask to be checked against [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)->grp_id
  group ID to be matched. Use 0 to match them all.
- `o`: name of the element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops) that contains **f**.
  Each element there groups a set of operations functions.
- `f`: operation function that will be called if **cond** matches.
  The operation functions are defined in groups, according to
  each element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops).
- `args...`: arguments for **f**.

**Description**

If the operation returns an error other than 0 or `-ENOIOCTLCMD`
for any subdevice, then abort and return with that error code,
zero otherwise.

**Note**

subdevs cannot be added or deleted while walking
the subdevs list.

#### <a id="c-v4l2_device_has_op"></a>`v4l2_device_has_op()`

```c
v4l2_device_has_op(v4l2_dev, grpid, o, f)
```

checks if any subdev with matching grpid has a given ops.

**Parameters**

- `v4l2_dev`: [`struct v4l2_device`](#c-struct-v4l2_device) owning the sub-devices to iterate over.
- `grpid`: [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)->grp_id group ID to match.
  Use 0 to match them all.
- `o`: name of the element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops) that contains **f**.
  Each element there groups a set of operations functions.
- `f`: operation function that will be called if **cond** matches.
  The operation functions are defined in groups, according to
  each element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops).

#### <a id="c-v4l2_device_mask_has_op"></a>`v4l2_device_mask_has_op()`

```c
v4l2_device_mask_has_op(v4l2_dev, grpmsk, o, f)
```

checks if any subdev with matching group mask has a given ops.

**Parameters**

- `v4l2_dev`: [`struct v4l2_device`](#c-struct-v4l2_device) owning the sub-devices to iterate over.
- `grpmsk`: bitmask to be checked against [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)->grp_id
  group ID to be matched. Use 0 to match them all.
- `o`: name of the element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops) that contains **f**.
  Each element there groups a set of operations functions.
- `f`: operation function that will be called if **cond** matches.
  The operation functions are defined in groups, according to
  each element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops).

---

# V4L2 DV Timings functions

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for V4L2 DV Timings functions.

<a id="rst-v4l2-dv-timings-functions"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-v4l2_calc_timeperframe"></a>`v4l2_calc_timeperframe()`

```c
struct v4l2_fract v4l2_calc_timeperframe(const struct v4l2_dv_timings *t)
```

helper function to calculate timeperframe based v4l2_dv_timings fields.

**Parameters**

- `const struct v4l2_dv_timings *t`: Timings for the video mode.

**Description**

Calculates the expected timeperframe using the pixel clock value and
horizontal/vertical measures. This means that v4l2_dv_timings structure
must be correctly and fully filled.

#### <a id="c-v4l2_check_dv_timings_fnc"></a>`v4l2_check_dv_timings_fnc()`

```c
typedef bool v4l2_check_dv_timings_fnc(const struct v4l2_dv_timings *t, void *handle)
```

timings check callback

**Parameters**

- `const struct v4l2_dv_timings *t`: the v4l2_dv_timings struct.
- `void *handle`: a handle from the driver.

**Description**

Returns true if the given timings are valid.

#### <a id="c-v4l2_valid_dv_timings"></a>`v4l2_valid_dv_timings()`

```c
bool v4l2_valid_dv_timings(const struct v4l2_dv_timings *t, const struct v4l2_dv_timings_cap *cap, v4l2_check_dv_timings_fnc fnc, void *fnc_handle)
```

are these timings valid?

**Parameters**

- `const struct v4l2_dv_timings *t`: the v4l2_dv_timings struct.
- `const struct v4l2_dv_timings_cap *cap`: the v4l2_dv_timings_cap capabilities.
- `v4l2_check_dv_timings_fnc fnc`: callback to check if this timing is OK. May be NULL.
- `void *fnc_handle`: a handle that is passed on to **fnc**.

**Description**

Returns true if the given dv_timings struct is supported by the
hardware capabilities and the callback function (if non-NULL), returns
false otherwise.

#### <a id="c-v4l2_enum_dv_timings_cap"></a>`v4l2_enum_dv_timings_cap()`

```c
int v4l2_enum_dv_timings_cap(struct v4l2_enum_dv_timings *t, const struct v4l2_dv_timings_cap *cap, v4l2_check_dv_timings_fnc fnc, void *fnc_handle)
```

Helper function to enumerate possible DV timings based on capabilities

**Parameters**

- `struct v4l2_enum_dv_timings *t`: the v4l2_enum_dv_timings struct.
- `const struct v4l2_dv_timings_cap *cap`: the v4l2_dv_timings_cap capabilities.
- `v4l2_check_dv_timings_fnc fnc`: callback to check if this timing is OK. May be NULL.
- `void *fnc_handle`: a handle that is passed on to **fnc**.

**Description**

This enumerates dv_timings using the full list of possible CEA-861 and DMT
timings, filtering out any timings that are not supported based on the
hardware capabilities and the callback function (if non-NULL).

If a valid timing for the given index is found, it will fill in **t** and
return 0, otherwise it returns -EINVAL.

#### <a id="c-v4l2_find_dv_timings_cap"></a>`v4l2_find_dv_timings_cap()`

```c
bool v4l2_find_dv_timings_cap(struct v4l2_dv_timings *t, const struct v4l2_dv_timings_cap *cap, unsigned pclock_delta, v4l2_check_dv_timings_fnc fnc, void *fnc_handle)
```

Find the closest timings struct

**Parameters**

- `struct v4l2_dv_timings *t`: the v4l2_enum_dv_timings struct.
- `const struct v4l2_dv_timings_cap *cap`: the v4l2_dv_timings_cap capabilities.
- `unsigned pclock_delta`: maximum delta between t->pixelclock and the timing struct
  under consideration.
- `v4l2_check_dv_timings_fnc fnc`: callback to check if a given timings struct is OK. May be NULL.
- `void *fnc_handle`: a handle that is passed on to **fnc**.

**Description**

This function tries to map the given timings to an entry in the
full list of possible CEA-861 and DMT timings, filtering out any timings
that are not supported based on the hardware capabilities and the callback
function (if non-NULL).

On success it will fill in **t** with the found timings and it returns true.
On failure it will return false.

#### <a id="c-v4l2_find_dv_timings_cea861_vic"></a>`v4l2_find_dv_timings_cea861_vic()`

```c
bool v4l2_find_dv_timings_cea861_vic(struct v4l2_dv_timings *t, u8 vic)
```

find timings based on CEA-861 VIC

**Parameters**

- `struct v4l2_dv_timings *t`: the timings data.
- `u8 vic`: CEA-861 VIC code

**Description**

On success it will fill in **t** with the found timings and it returns true.
On failure it will return false.

#### <a id="c-v4l2_match_dv_timings"></a>`v4l2_match_dv_timings()`

```c
bool v4l2_match_dv_timings(const struct v4l2_dv_timings *measured, const struct v4l2_dv_timings *standard, unsigned pclock_delta, bool match_reduced_fps)
```

do two timings match?

**Parameters**

- `const struct v4l2_dv_timings *measured`: the measured timings data.
- `const struct v4l2_dv_timings *standard`: the timings according to the standard.
- `unsigned pclock_delta`: maximum delta in Hz between standard->pixelclock and
  the measured timings.
- `bool match_reduced_fps`: if true, then fail if V4L2_DV_FL_REDUCED_FPS does not
  match.

**Description**

Returns true if the two timings match, returns false otherwise.

#### <a id="c-v4l2_print_dv_timings"></a>`v4l2_print_dv_timings()`

```c
void v4l2_print_dv_timings(const char *dev_prefix, const char *prefix, const struct v4l2_dv_timings *t, bool detailed)
```

log the contents of a dv_timings struct

**Parameters**

- `const char *dev_prefix`: device prefix for each log line.
- `const char *prefix`: additional prefix for each log line, may be NULL.
- `const struct v4l2_dv_timings *t`: the timings data.
- `bool detailed`: if true, give a detailed log.

#### <a id="c-v4l2_detect_cvt"></a>`v4l2_detect_cvt()`

```c
bool v4l2_detect_cvt(unsigned int frame_height, unsigned int hfreq, unsigned int vsync, unsigned int active_width, u32 polarities, bool interlaced, const struct v4l2_dv_timings_cap *cap, struct v4l2_dv_timings *fmt)
```

detect if the given timings follow the CVT standard

**Parameters**

- `unsigned int frame_height`: the total height of the frame (including blanking) in lines.
- `unsigned int hfreq`: the horizontal frequency in Hz.
- `unsigned int vsync`: the height of the vertical sync in lines.
- `unsigned int active_width`: active width of image (does not include blanking). This
  information is needed only in case of version 2 of reduced blanking.
  In other cases, this parameter does not have any effect on timings.
- `u32 polarities`: the horizontal and vertical polarities (same as struct
  v4l2_bt_timings polarities).
- `bool interlaced`: if this flag is true, it indicates interlaced format
- `const struct v4l2_dv_timings_cap *cap`: the v4l2_dv_timings_cap capabilities.
- `struct v4l2_dv_timings *fmt`: the resulting timings.

**Description**

This function will attempt to detect if the given values correspond to a
valid CVT format. If so, then it will return true, and fmt will be filled
in with the found CVT timings.

#### <a id="c-v4l2_detect_gtf"></a>`v4l2_detect_gtf()`

```c
bool v4l2_detect_gtf(unsigned int frame_height, unsigned int hfreq, unsigned int vsync, u32 polarities, bool interlaced, struct v4l2_fract aspect, const struct v4l2_dv_timings_cap *cap, struct v4l2_dv_timings *fmt)
```

detect if the given timings follow the GTF standard

**Parameters**

- `unsigned int frame_height`: the total height of the frame (including blanking) in lines.
- `unsigned int hfreq`: the horizontal frequency in Hz.
- `unsigned int vsync`: the height of the vertical sync in lines.
- `u32 polarities`: the horizontal and vertical polarities (same as struct
  v4l2_bt_timings polarities).
- `bool interlaced`: if this flag is true, it indicates interlaced format
- `struct v4l2_fract aspect`: preferred aspect ratio. GTF has no method of determining the
  aspect ratio in order to derive the image width from the
  image height, so it has to be passed explicitly. Usually
  the native screen aspect ratio is used for this. If it
  is not filled in correctly, then 16:9 will be assumed.
- `const struct v4l2_dv_timings_cap *cap`: the v4l2_dv_timings_cap capabilities.
- `struct v4l2_dv_timings *fmt`: the resulting timings.

**Description**

This function will attempt to detect if the given values correspond to a
valid GTF format. If so, then it will return true, and fmt will be filled
in with the found GTF timings.

#### <a id="c-v4l2_calc_aspect_ratio"></a>`v4l2_calc_aspect_ratio()`

```c
struct v4l2_fract v4l2_calc_aspect_ratio(u8 hor_landscape, u8 vert_portrait)
```

calculate the aspect ratio based on bytes 0x15 and 0x16 from the EDID.

**Parameters**

- `u8 hor_landscape`: byte 0x15 from the EDID.
- `u8 vert_portrait`: byte 0x16 from the EDID.

**Description**

Determines the aspect ratio from the EDID.
See VESA Enhanced EDID standard, release A, rev 2, section 3.6.2:
"Horizontal and Vertical Screen Size or Aspect Ratio"

#### <a id="c-v4l2_dv_timings_aspect_ratio"></a>`v4l2_dv_timings_aspect_ratio()`

```c
struct v4l2_fract v4l2_dv_timings_aspect_ratio(const struct v4l2_dv_timings *t)
```

calculate the aspect ratio based on the v4l2_dv_timings information.

**Parameters**

- `const struct v4l2_dv_timings *t`: the timings data.

#### <a id="c-can_reduce_fps"></a>`can_reduce_fps()`

```c
bool can_reduce_fps(struct v4l2_bt_timings *bt)
```

check if conditions for reduced fps are true.

**Parameters**

- `struct v4l2_bt_timings *bt`: v4l2 timing structure

**Description**

For different timings reduced fps is allowed if the following conditions
are met:

- For CVT timings: if reduced blanking v2 (vsync == 8) is true.
- For CEA861 timings: if `V4L2_DV_FL_CAN_REDUCE_FPS` flag is true.

#### <a id="c-struct-v4l2_hdmi_colorimetry"></a>`struct v4l2_hdmi_colorimetry`

describes the HDMI colorimetry information

**Definition**

```c
struct v4l2_hdmi_colorimetry {
    enum v4l2_colorspace colorspace;
    enum v4l2_ycbcr_encoding ycbcr_enc;
    enum v4l2_quantization quantization;
    enum v4l2_xfer_func xfer_func;
};
```

**Members**

- `colorspace`: enum v4l2_colorspace, the colorspace
- `ycbcr_enc`: enum v4l2_ycbcr_encoding, Y'CbCr encoding
- `quantization`: enum v4l2_quantization, colorspace quantization
- `xfer_func`: enum v4l2_xfer_func, colorspace transfer function

---

# V4L2 events

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> The V4L2 events provide a generic way to pass events to user space. The driver must use v4l2_fh to be able to support V4L2 events.

<a id="rst-v4l2-events"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The V4L2 events provide a generic way to pass events to user space. The driver must use `v4l2_fh` to be able to support V4L2 events.

Events are subscribed per-filehandle. An event specification consists of a `type` and is optionally associated with an object identified through the `id` field. If unused, then the `id` is 0. So an event is uniquely identified by the `(type, id)` tuple.

The `v4l2_fh` struct has a list of subscribed events on its `subscribed` field.

When the user subscribes to an event, a `v4l2_subscribed_event` struct is added to `v4l2_fh`<!-- -->`.subscribed`, one for every subscribed event.

Each `v4l2_subscribed_event` struct ends with a `v4l2_kevent` ringbuffer, with the size given by the caller of `v4l2_event_subscribe()`. This ringbuffer is used to store any events raised by the driver.

So every `(type, ID)` event tuple will have its own `v4l2_kevent` ringbuffer. This guarantees that if a driver is generating lots of events of one type in a short time, then that will not overwrite events of another type.

But if you get more events of one type than the size of the `v4l2_kevent` ringbuffer, then the oldest event will be dropped and the new one added.

The `v4l2_kevent` struct links into the `available` list of the `v4l2_fh` struct so [vidioc\_dqevent](</kernel/userspace/userspace-api/media-v4l/vidioc-dqevent.md#rst-vidioc-dqevent>) will know which event to dequeue first.

Finally, if the event subscription is associated with a particular object such as a V4L2 control, then that object needs to know about that as well so that an event can be raised by that object. So the `node` field can be used to link the `v4l2_subscribed_event` struct into a list of such objects.

So to summarize:

- struct v4l2\_fh has two lists: one of the `subscribed` events, and one of the `available` events.

- struct v4l2\_subscribed\_event has a ringbuffer of raised (pending) events of that particular type.

- If struct v4l2\_subscribed\_event is associated with a specific object, then that object will have an internal list of struct v4l2\_subscribed\_event so it knows who subscribed an event to that object.

Furthermore, the internal struct v4l2\_subscribed\_event has `merge()` and `replace()` callbacks which drivers can set. These callbacks are called when a new event is raised and there is no more room.

The `replace()` callback allows you to replace the payload of the old event with that of the new event, merging any relevant data from the old payload into the new payload that replaces it. It is called when this event type has a ringbuffer with size is one, i.e. only one event can be stored in the ringbuffer.

The `merge()` callback allows you to merge the oldest event payload into that of the second-oldest event payload. It is called when the ringbuffer has size is greater than one.

This way no status information is lost, just the intermediate steps leading up to that state.

A good example of these `replace`/`merge` callbacks is in v4l2-event.c: `ctrls_replace()` and `ctrls_merge()` callbacks for the control event.

> [!NOTE]
>
> these callbacks can be called from interrupt context, so they must be fast.

In order to queue events to video device, drivers should call:

> `v4l2_event_queue <v4l2_event_queue>()` (`vdev <video_device>`, `ev <v4l2_event>`)

The driver's only responsibility is to fill in the type and the data fields. The other fields will be filled in by V4L2.

<a id="rst-event-subscription"></a>

## Event subscription

Subscribing to an event is via:

> `v4l2_event_subscribe <v4l2_event_subscribe>()` (`fh <v4l2_fh>`, `sub <v4l2_event_subscription>` , elems, `ops <v4l2_subscribed_event_ops>`)

This function is used to implement `video_device`-&gt; `ioctl_ops <v4l2_ioctl_ops>`-&gt; `vidioc_subscribe_event`, but the driver must check first if the driver is able to produce events with specified event id, and then should call `v4l2_event_subscribe()` to subscribe the event.

The elems argument is the size of the event queue for this event. If it is 0, then the framework will fill in a default value (this depends on the event type).

The ops argument allows the driver to specify a number of callbacks:

<!-- tabularcolumns: |p{1.5cm}|p{16.0cm}| -->


<table>
<thead>
<tr>
<th>


Callback

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


add

</td>
<td>


called when a new listener gets added (subscribing to the same event twice will only cause this callback to get called once)

</td>
</tr>
<tr>
<td>


del

</td>
<td>


called when a listener stops listening

</td>
</tr>
<tr>
<td>


replace

</td>
<td>


replace event 'old' with event 'new'.

</td>
</tr>
<tr>
<td>


merge

</td>
<td>


merge event 'old' into event 'new'.

</td>
</tr>
</tbody>
</table>

All 4 callbacks are optional, if you don't want to specify any callbacks the ops argument itself maybe `NULL`.

<a id="rst-unsubscribing-an-event"></a>

## Unsubscribing an event

Unsubscribing to an event is via:

> `v4l2_event_unsubscribe <v4l2_event_unsubscribe>()` (`fh <v4l2_fh>`, `sub <v4l2_event_subscription>`)

This function is used to implement `video_device`-&gt; `ioctl_ops <v4l2_ioctl_ops>`-&gt; `vidioc_unsubscribe_event`. A driver may call `v4l2_event_unsubscribe()` directly unless it wants to be involved in unsubscription process.

The special type `V4L2_EVENT_ALL` may be used to unsubscribe all events. The drivers may want to handle this in a special way.

<a id="rst-check-if-there-s-a-pending-event"></a>

## Check if there's a pending event

Checking if there's a pending event is via:

> `v4l2_event_pending <v4l2_event_pending>()` (`fh <v4l2_fh>`)

This function returns the number of pending events. Useful when implementing poll.

<a id="rst-how-events-work"></a>

## How events work

Events are delivered to user space through the poll system call. The driver can use `v4l2_fh`-&gt;wait (a wait\_queue\_head\_t) as the argument for `poll_wait()`.

There are standard and private events. New standard events must use the smallest available event type. The drivers must allocate their events from their own class starting from class base. Class base is `V4L2_EVENT_PRIVATE_START` + n \* 1000 where n is the lowest available number. The first event type in the class is reserved for future use, so the first available event type is 'class base + 1'.

An example on how the V4L2 events may be used can be found in the OMAP 3 ISP driver (`drivers/media/platform/ti/omap3isp`).

A subdev can directly send an event to the `v4l2_device` notify function with `V4L2_DEVICE_NOTIFY_EVENT`. This allows the bridge to map the subdev that sends the event to the video node(s) associated with the subdev that need to be informed about such an event.

<a id="rst-v4l2-event-functions-and-data-structures"></a>

### V4L2 event functions and data structures


#### <a id="c-struct-v4l2_kevent"></a>`struct v4l2_kevent`

Internal kernel event struct.

**Definition**

```c
struct v4l2_kevent {
    struct list_head        list;
    struct v4l2_subscribed_event *sev;
    struct v4l2_event       event;
    u64 ts;
};
```

**Members**

- `list`: List node for the v4l2_fh->available list.
- `sev`: Pointer to parent v4l2_subscribed_event.
- `event`: The event itself.
- `ts`: The timestamp of the event.

#### <a id="c-struct-v4l2_subscribed_event_ops"></a>`struct v4l2_subscribed_event_ops`

Subscribed event operations.

**Definition**

```c
struct v4l2_subscribed_event_ops {
    int (*add)(struct v4l2_subscribed_event *sev, unsigned int elems);
    void (*del)(struct v4l2_subscribed_event *sev);
    void (*replace)(struct v4l2_event *old, const struct v4l2_event *new);
    void (*merge)(const struct v4l2_event *old, struct v4l2_event *new);
};
```

**Members**

- `add`: Optional callback, called when a new listener is added
- `del`: Optional callback, called when a listener stops listening
- `replace`: Optional callback that can replace event 'old' with event 'new'.
- `merge`: Optional callback that can merge event 'old' into event 'new'.

#### <a id="c-struct-v4l2_subscribed_event"></a>`struct v4l2_subscribed_event`

Internal struct representing a subscribed event.

**Definition**

```c
struct v4l2_subscribed_event {
    struct list_head        list;
    u32 type;
    u32 id;
    u32 flags;
    struct v4l2_fh          *fh;
    struct list_head        node;
    const struct v4l2_subscribed_event_ops *ops;
    unsigned int            elems;
    unsigned int            first;
    unsigned int            in_use;
    struct v4l2_kevent      events[] ;
};
```

**Members**

- `list`: List node for the v4l2_fh->subscribed list.
- `type`: Event type.
- `id`: Associated object ID (e.g. control ID). 0 if there isn't any.
- `flags`: Copy of v4l2_event_subscription->flags.
- `fh`: Filehandle that subscribed to this event.
- `node`: List node that hooks into the object's event list
  (if there is one).
- `ops`: v4l2_subscribed_event_ops
- `elems`: The number of elements in the events array.
- `first`: The index of the events containing the oldest available event.
- `in_use`: The number of queued events.
- `events`: An array of **elems** events.

#### <a id="c-v4l2_event_dequeue"></a>`v4l2_event_dequeue()`

```c
int v4l2_event_dequeue(struct v4l2_fh *fh, struct v4l2_event *event, int nonblocking)
```

Dequeue events from video device.

**Parameters**

- `struct v4l2_fh *fh`: pointer to struct v4l2_fh
- `struct v4l2_event *event`: pointer to struct v4l2_event
- `int nonblocking`: if not zero, waits for an event to arrive

#### <a id="c-v4l2_event_queue"></a>`v4l2_event_queue()`

```c
void v4l2_event_queue(struct video_device *vdev, const struct v4l2_event *ev)
```

Queue events to video device.

**Parameters**

- `struct video_device *vdev`: pointer to [`struct video_device`](/kernel/hardware/driver-api/media/v4l2-dev.md#c-struct-video_device)
- `const struct v4l2_event *ev`: pointer to [`struct v4l2_event`](/kernel/userspace/userspace-api/media-v4l/vidioc-dqevent.md#c-v4l2_event)

**Description**

The event will be queued for all [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh) file handlers.

> [!NOTE]
> The driver's only responsibility is to fill in the type and the data
> fields. The other fields will be filled in by V4L2.

#### <a id="c-v4l2_event_queue_fh"></a>`v4l2_event_queue_fh()`

```c
void v4l2_event_queue_fh(struct v4l2_fh *fh, const struct v4l2_event *ev)
```

Queue events to video device.

**Parameters**

- `struct v4l2_fh *fh`: pointer to [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh)
- `const struct v4l2_event *ev`: pointer to [`struct v4l2_event`](/kernel/userspace/userspace-api/media-v4l/vidioc-dqevent.md#c-v4l2_event)

**Description**

The event will be queued only for the specified [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh) file handler.

> [!NOTE]
> The driver's only responsibility is to fill in the type and the data
> fields. The other fields will be filled in by V4L2.

#### <a id="c-v4l2_event_wake_all"></a>`v4l2_event_wake_all()`

```c
void v4l2_event_wake_all(struct video_device *vdev)
```

Wake all filehandles.

**Parameters**

- `struct video_device *vdev`: pointer to [`struct video_device`](/kernel/hardware/driver-api/media/v4l2-dev.md#c-struct-video_device)

**Description**

Used when unregistering a video device.

#### <a id="c-v4l2_event_pending"></a>`v4l2_event_pending()`

```c
int v4l2_event_pending(struct v4l2_fh *fh)
```

Check if an event is available

**Parameters**

- `struct v4l2_fh *fh`: pointer to [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh)

**Description**

Returns the number of pending events.

#### <a id="c-v4l2_event_subscribe"></a>`v4l2_event_subscribe()`

```c
int v4l2_event_subscribe(struct v4l2_fh *fh, const struct v4l2_event_subscription *sub, unsigned int elems, const struct v4l2_subscribed_event_ops *ops)
```

Subscribes to an event

**Parameters**

- `struct v4l2_fh *fh`: pointer to [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh)
- `const struct v4l2_event_subscription *sub`: pointer to [`struct v4l2_event_subscription`](/kernel/userspace/userspace-api/media-v4l/vidioc-subscribe-event.md#c-v4l2_event_subscription)
- `unsigned int elems`: size of the events queue
- `const struct v4l2_subscribed_event_ops *ops`: pointer to [`v4l2_subscribed_event_ops`](#c-struct-v4l2_subscribed_event_ops)

**Description**

> [!NOTE]
> if **elems** is zero, the framework will fill in a default value,
> with is currently 1 element.

#### <a id="c-v4l2_event_unsubscribe"></a>`v4l2_event_unsubscribe()`

```c
int v4l2_event_unsubscribe(struct v4l2_fh *fh, const struct v4l2_event_subscription *sub)
```

Unsubscribes to an event

**Parameters**

- `struct v4l2_fh *fh`: pointer to [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh)
- `const struct v4l2_event_subscription *sub`: pointer to [`struct v4l2_event_subscription`](/kernel/userspace/userspace-api/media-v4l/vidioc-subscribe-event.md#c-v4l2_event_subscription)

#### <a id="c-v4l2_event_unsubscribe_all"></a>`v4l2_event_unsubscribe_all()`

```c
void v4l2_event_unsubscribe_all(struct v4l2_fh *fh)
```

Unsubscribes to all events

**Parameters**

- `struct v4l2_fh *fh`: pointer to [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh)

#### <a id="c-v4l2_event_subdev_unsubscribe"></a>`v4l2_event_subdev_unsubscribe()`

```c
int v4l2_event_subdev_unsubscribe(struct v4l2_subdev *sd, struct v4l2_fh *fh, struct v4l2_event_subscription *sub)
```

Subdev variant of [`v4l2_event_unsubscribe()`](#c-v4l2_event_unsubscribe)

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)
- `struct v4l2_fh *fh`: pointer to [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh)
- `struct v4l2_event_subscription *sub`: pointer to [`struct v4l2_event_subscription`](/kernel/userspace/userspace-api/media-v4l/vidioc-subscribe-event.md#c-v4l2_event_subscription)

**Description**

> [!NOTE]
> This function should be used for the [`struct v4l2_subdev_core_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_core_ops)
> `unsubscribe_event` field.

#### <a id="c-v4l2_src_change_event_subscribe"></a>`v4l2_src_change_event_subscribe()`

```c
int v4l2_src_change_event_subscribe(struct v4l2_fh *fh, const struct v4l2_event_subscription *sub)
```

helper function that calls [`v4l2_event_subscribe()`](#c-v4l2_event_subscribe) if the event is `V4L2_EVENT_SOURCE_CHANGE`.

**Parameters**

- `struct v4l2_fh *fh`: pointer to struct v4l2_fh
- `const struct v4l2_event_subscription *sub`: pointer to [`struct v4l2_event_subscription`](/kernel/userspace/userspace-api/media-v4l/vidioc-subscribe-event.md#c-v4l2_event_subscription)

#### <a id="c-v4l2_src_change_event_subdev_subscribe"></a>`v4l2_src_change_event_subdev_subscribe()`

```c
int v4l2_src_change_event_subdev_subscribe(struct v4l2_subdev *sd, struct v4l2_fh *fh, struct v4l2_event_subscription *sub)
```

Variant of [`v4l2_event_subscribe()`](#c-v4l2_event_subscribe), meant to subscribe only events of the type `V4L2_EVENT_SOURCE_CHANGE`.

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)
- `struct v4l2_fh *fh`: pointer to [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh)
- `struct v4l2_event_subscription *sub`: pointer to [`struct v4l2_event_subscription`](/kernel/userspace/userspace-api/media-v4l/vidioc-subscribe-event.md#c-v4l2_event_subscription)

---

# V4L2 File handles

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> struct v4l2_fh provides a way to easily keep file handle specific data that is used by the V4L2 framework. Its usage is mandatory in all drivers.

<a id="rst-v4l2-file-handles"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

struct v4l2_fh provides a way to easily keep file handle specific data that is used by the V4L2 framework. Its usage is mandatory in all drivers.

struct v4l2_fh is allocated in the driver's `open()` file operation handler. It is typically embedded in a larger driver-specific structure. The `v4l2_fh` must be initialized with a call to `v4l2_fh_init()`, and added to the video device with `v4l2_fh_add()`. This associates the `v4l2_fh` with the `file` by setting `file->private_data` to point to the `v4l2_fh`.

Similarly, the struct v4l2_fh is freed in the driver's `release()` file operation handler. It must be removed from the video device with `v4l2_fh_del()` and cleaned up with `v4l2_fh_exit()` before being freed.

Drivers must not access `file->private_data` directly. They can retrieve the `v4l2_fh` associated with a `file` by calling `file_to_v4l2_fh()`. Drivers can extract their own file handle structure by using the container_of macro.

Example:



```c
struct my_fh {
        int blah;
        struct v4l2_fh fh;
};

...

int my_open(struct file *file)
{
        struct my_fh *my_fh;
        struct video_device *vfd;
        int ret;

        ...

        my_fh = kzalloc(sizeof(*my_fh), GFP_KERNEL);

        ...

        v4l2_fh_init(&my_fh->fh, vfd);

        ...

        v4l2_fh_add(&my_fh->fh, file);
        return 0;
}

int my_release(struct file *file)
{
        struct v4l2_fh *fh = file_to_v4l2_fh(file);
        struct my_fh *my_fh = container_of(fh, struct my_fh, fh);

        ...
        v4l2_fh_del(&my_fh->fh, file);
        v4l2_fh_exit(&my_fh->fh);
        kfree(my_fh);
        return 0;
}
```

Below is a short description of the `v4l2_fh` functions used:

`v4l2_fh_init <v4l2_fh_init>()` (`fh <v4l2_fh>`, `vdev <video_device>`)

- Initialise the file handle. This **MUST** be performed in the driver's `v4l2_file_operations`-&gt;open() handler.

`v4l2_fh_add <v4l2_fh_add>()` (`fh <v4l2_fh>`, struct file \*filp)

- Add a `v4l2_fh` to `video_device` file handle list. Must be called once the file handle is completely initialized.

`v4l2_fh_del <v4l2_fh_del>()` (`fh <v4l2_fh>`, struct file \*filp)

- Unassociate the file handle from `video_device`. The file handle exit function may now be called.

`v4l2_fh_exit <v4l2_fh_exit>()` (`fh <v4l2_fh>`)

- Uninitialise the file handle. After uninitialisation the `v4l2_fh` memory can be freed.

`file_to_v4l2_fh <file_to_v4l2_fh>()` (struct file \*filp)

- Retrieve the `v4l2_fh` instance associated with a `file`.

If struct v4l2_fh is not embedded, then you can use these helper functions:

`v4l2_fh_open <v4l2_fh_open>()` (struct file \*filp)

- This allocates a struct v4l2_fh, initializes it and adds it to the struct video_device associated with the file struct.

`v4l2_fh_release <v4l2_fh_release>()` (struct file \*filp)

- This deletes it from the struct video_device associated with the file struct, uninitialised the `v4l2_fh` and frees it.

These two functions can be plugged into the v4l2_file_operation's `open()` and `release()` ops.

Several drivers need to do something when the first file handle is opened and when the last file handle closes. Two helper functions were added to check whether the `v4l2_fh` struct is the only open filehandle of the associated device node:

`v4l2_fh_is_singular <v4l2_fh_is_singular>()` (`fh <v4l2_fh>`)

- Returns 1 if the file handle is the only open file handle, else 0.

`v4l2_fh_is_singular_file <v4l2_fh_is_singular_file>()` (struct file \*filp)

- Same, but it calls v4l2_fh_is_singular with filp-&gt;private_data.

<a id="rst-v4l2-fh-functions-and-data-structures"></a>

## V4L2 fh functions and data structures


#### <a id="c-struct-v4l2_fh"></a>`struct v4l2_fh`

Describes a V4L2 file handler

**Definition**

```c
struct v4l2_fh {
    struct list_head        list;
    struct video_device     *vdev;
    struct v4l2_ctrl_handler *ctrl_handler;
    enum v4l2_priority      prio;
    wait_queue_head_t wait;
    struct mutex            subscribe_lock;
    struct list_head        subscribed;
    struct list_head        available;
    unsigned int            navailable;
    u32 sequence;
    struct v4l2_m2m_ctx     *m2m_ctx;
};
```

**Members**

- `list`: list of file handlers
- `vdev`: pointer to [`struct video_device`](/kernel/hardware/driver-api/media/v4l2-dev.md#c-struct-video_device)
- `ctrl_handler`: pointer to [`struct v4l2_ctrl_handler`](/kernel/hardware/driver-api/media/v4l2-controls.md#c-struct-v4l2_ctrl_handler)
- `prio`: priority of the file handler, as defined by [`enum v4l2_priority`](/kernel/userspace/userspace-api/media-v4l/vidioc-g-priority.md#c-v4l2_priority)
- `wait`: event' s wait queue
- `subscribe_lock`: serialise changes to the subscribed list; guarantee that
  the add and del event callbacks are orderly called
- `subscribed`: list of subscribed events
- `available`: list of events waiting to be dequeued
- `navailable`: number of available events at **available** list
- `sequence`: event sequence number
- `m2m_ctx`: pointer to [`struct v4l2_m2m_ctx`](/kernel/hardware/driver-api/media/v4l2-mem2mem.md#c-struct-v4l2_m2m_ctx)

#### <a id="c-file_to_v4l2_fh"></a>`file_to_v4l2_fh()`

```c
struct v4l2_fh * file_to_v4l2_fh(struct file *filp)
```

Return the v4l2_fh associated with a struct file

**Parameters**

- `struct file *filp`: pointer to [`struct file`](/kernel/internals/filesystems/api-summary.md#c-struct-file)

**Description**

This function should be used by drivers to retrieve the [`struct v4l2_fh`](#c-struct-v4l2_fh)
instance pointer stored in the file private_data instead of accessing the
private_data field directly.

#### <a id="c-v4l2_fh_init"></a>`v4l2_fh_init()`

```c
void v4l2_fh_init(struct v4l2_fh *fh, struct video_device *vdev)
```

Initialise the file handle.

**Parameters**

- `struct v4l2_fh *fh`: pointer to [`struct v4l2_fh`](#c-struct-v4l2_fh)
- `struct video_device *vdev`: pointer to [`struct video_device`](/kernel/hardware/driver-api/media/v4l2-dev.md#c-struct-video_device)

**Description**

Parts of the V4L2 framework using the
file handles should be initialised in this function. Must be called
from driver's v4l2_file_operations->open\(\) handler if the driver
uses [`struct v4l2_fh`](#c-struct-v4l2_fh).

#### <a id="c-v4l2_fh_add"></a>`v4l2_fh_add()`

```c
void v4l2_fh_add(struct v4l2_fh *fh, struct file *filp)
```

Add the fh to the list of file handles on a video_device.

**Parameters**

- `struct v4l2_fh *fh`: pointer to [`struct v4l2_fh`](#c-struct-v4l2_fh)
- `struct file *filp`: pointer to [`struct file`](/kernel/internals/filesystems/api-summary.md#c-struct-file) associated with **fh**

**Description**

The function sets filp->private_data to point to **fh**.

> [!NOTE]
> The **fh** file handle must be initialised first.

#### <a id="c-v4l2_fh_open"></a>`v4l2_fh_open()`

```c
int v4l2_fh_open(struct file *filp)
```

Ancillary routine that can be used as the open\(\) op of v4l2_file_operations.

**Parameters**

- `struct file *filp`: pointer to struct file

**Description**

It allocates a v4l2_fh and inits and adds it to the [`struct video_device`](/kernel/hardware/driver-api/media/v4l2-dev.md#c-struct-video_device)
associated with the file pointer.

On error filp->private_data will be `NULL`, otherwise it will point to
the [`struct v4l2_fh`](#c-struct-v4l2_fh).

#### <a id="c-v4l2_fh_del"></a>`v4l2_fh_del()`

```c
void v4l2_fh_del(struct v4l2_fh *fh, struct file *filp)
```

Remove file handle from the list of file handles.

**Parameters**

- `struct v4l2_fh *fh`: pointer to [`struct v4l2_fh`](#c-struct-v4l2_fh)
- `struct file *filp`: pointer to [`struct file`](/kernel/internals/filesystems/api-summary.md#c-struct-file) associated with **fh**

**Description**

The function resets filp->private_data to NULL.

> [!NOTE]
> Must be called in v4l2_file_operations->release\(\) handler if the driver
> uses [`struct v4l2_fh`](#c-struct-v4l2_fh).

#### <a id="c-v4l2_fh_exit"></a>`v4l2_fh_exit()`

```c
void v4l2_fh_exit(struct v4l2_fh *fh)
```

Release resources related to a file handle.

**Parameters**

- `struct v4l2_fh *fh`: pointer to [`struct v4l2_fh`](#c-struct-v4l2_fh)

**Description**

Parts of the V4L2 framework using the v4l2_fh must release their
resources here, too.

> [!NOTE]
> Must be called in v4l2_file_operations->release\(\) handler if the
> driver uses [`struct v4l2_fh`](#c-struct-v4l2_fh).

#### <a id="c-v4l2_fh_release"></a>`v4l2_fh_release()`

```c
int v4l2_fh_release(struct file *filp)
```

Ancillary routine that can be used as the release\(\) op of v4l2_file_operations.

**Parameters**

- `struct file *filp`: pointer to struct file

**Description**

It deletes and exits the v4l2_fh associated with the file pointer and
frees it. It will do nothing if filp->private_data (the pointer to the
v4l2_fh struct) is `NULL`.

This function always returns 0.

#### <a id="c-v4l2_fh_is_singular"></a>`v4l2_fh_is_singular()`

```c
int v4l2_fh_is_singular(struct v4l2_fh *fh)
```

Returns 1 if this filehandle is the only filehandle opened for the associated video_device.

**Parameters**

- `struct v4l2_fh *fh`: pointer to [`struct v4l2_fh`](#c-struct-v4l2_fh)

**Description**

If **fh** is NULL, then it returns 0.

#### <a id="c-v4l2_fh_is_singular_file"></a>`v4l2_fh_is_singular_file()`

```c
int v4l2_fh_is_singular_file(struct file *filp)
```

Returns 1 if this filehandle is the only filehandle opened for the associated video_device.

**Parameters**

- `struct file *filp`: pointer to struct file

**Description**

This is a helper function variant of [`v4l2_fh_is_singular()`](#c-v4l2_fh_is_singular) with uses
struct file as argument.

If filp->private_data is `NULL`, then it will return 0.

---

# V4L2 flash functions and data structures

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for V4L2 flash functions and data structures.

<a id="rst-v4l2-flash-functions-and-data-structures"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-struct-v4l2_flash_ctrl_data"></a>`struct v4l2_flash_ctrl_data`

flash control initialization data, filled basing on the features declared by the LED flash class driver in the v4l2_flash_config

**Definition**

```c
struct v4l2_flash_ctrl_data {
    struct v4l2_ctrl_config config;
    u32 cid;
};
```

**Members**

- `config`: initialization data for a control
- `cid`: contains v4l2 flash control id if the config
  field was initialized, 0 otherwise

#### <a id="c-struct-v4l2_flash_ops"></a>`struct v4l2_flash_ops`

V4L2 flash operations

**Definition**

```c
struct v4l2_flash_ops {
    int (*external_strobe_set)(struct v4l2_flash *v4l2_flash, bool enable);
    enum led_brightness (*intensity_to_led_brightness) (struct v4l2_flash *v4l2_flash, s32 intensity);
    s32 (*led_brightness_to_intensity) (struct v4l2_flash *v4l2_flash, enum led_brightness);
};
```

**Members**

- `external_strobe_set`: Setup strobing the flash by hardware pin state
  assertion.
- `intensity_to_led_brightness`: Convert intensity to brightness in a device
  specific manner
- `led_brightness_to_intensity`: convert brightness to intensity in a device
  specific manner.

#### <a id="c-struct-v4l2_flash_config"></a>`struct v4l2_flash_config`

V4L2 Flash sub-device initialization data

**Definition**

```c
struct v4l2_flash_config {
    char dev_name[32];
    struct led_flash_setting intensity;
    u32 flash_faults;
    unsigned int has_external_strobe:1;
};
```

**Members**

- `dev_name`: the name of the media entity,
  unique in the system
- `intensity`: non-flash strobe constraints for the LED
- `flash_faults`: bitmask of flash faults that the LED flash class
  device can report; corresponding LED_FAULT* bit
  definitions are available in the header file
  \<linux/led-class-flash.h>
- `has_external_strobe`: external strobe capability

#### <a id="c-struct-v4l2_flash"></a>`struct v4l2_flash`

Flash sub-device context

**Definition**

```c
struct v4l2_flash {
    struct led_classdev_flash *fled_cdev;
    struct led_classdev *iled_cdev;
    const struct v4l2_flash_ops *ops;
    struct v4l2_subdev sd;
    struct v4l2_ctrl_handler hdl;
    struct v4l2_ctrl **ctrls;
};
```

**Members**

- `fled_cdev`: LED flash class device controlled by this sub-device
- `iled_cdev`: LED class device representing indicator LED associated
  with the LED flash class device
- `ops`: V4L2 specific flash ops
- `sd`: V4L2 sub-device
- `hdl`: flash controls handler
- `ctrls`: array of pointers to controls, whose values define
  the sub-device state

#### <a id="c-v4l2_subdev_to_v4l2_flash"></a>`v4l2_subdev_to_v4l2_flash()`

```c
struct v4l2_flash * v4l2_subdev_to_v4l2_flash(struct v4l2_subdev *sd)
```

Returns a [`struct v4l2_flash`](#c-struct-v4l2_flash) from the [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev) embedded on it.

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)

#### <a id="c-v4l2_ctrl_to_v4l2_flash"></a>`v4l2_ctrl_to_v4l2_flash()`

```c
struct v4l2_flash * v4l2_ctrl_to_v4l2_flash(struct v4l2_ctrl *c)
```

Returns a [`struct v4l2_flash`](#c-struct-v4l2_flash) from the [`struct v4l2_ctrl`](/kernel/hardware/driver-api/media/v4l2-controls.md#c-struct-v4l2_ctrl) embedded on it.

**Parameters**

- `struct v4l2_ctrl *c`: pointer to [`struct v4l2_ctrl`](/kernel/hardware/driver-api/media/v4l2-controls.md#c-struct-v4l2_ctrl)

#### <a id="c-v4l2_flash_init"></a>`v4l2_flash_init()`

```c
struct v4l2_flash * v4l2_flash_init(struct device *dev, struct fwnode_handle *fwn, struct led_classdev_flash *fled_cdev, const struct v4l2_flash_ops *ops, struct v4l2_flash_config *config)
```

initialize V4L2 flash led sub-device

**Parameters**

- `struct device *dev`: flash device, e.g. an I2C device
- `struct fwnode_handle *fwn`: fwnode_handle of the LED, may be NULL if the same as device's
- `struct led_classdev_flash *fled_cdev`: LED flash class device to wrap
- `const struct v4l2_flash_ops *ops`: V4L2 Flash device ops
- `struct v4l2_flash_config *config`: initialization data for V4L2 Flash sub-device

**Description**

Create V4L2 Flash sub-device wrapping given LED subsystem device.
The ops pointer is stored by the V4L2 flash framework. No
references are held to config nor its contents once this function
has returned.

**Return**

A valid pointer, or, when an error occurs, the return
value is encoded using [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR). Use [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) to check and
[`PTR_ERR()`](/kernel/internals/core-api/kernel-api.md#c-PTR_ERR) to obtain the numeric return value.

#### <a id="c-v4l2_flash_indicator_init"></a>`v4l2_flash_indicator_init()`

```c
struct v4l2_flash * v4l2_flash_indicator_init(struct device *dev, struct fwnode_handle *fwn, struct led_classdev *iled_cdev, struct v4l2_flash_config *config)
```

initialize V4L2 indicator sub-device

**Parameters**

- `struct device *dev`: flash device, e.g. an I2C device
- `struct fwnode_handle *fwn`: fwnode_handle of the LED, may be NULL if the same as device's
- `struct led_classdev *iled_cdev`: LED flash class device representing the indicator LED
- `struct v4l2_flash_config *config`: initialization data for V4L2 Flash sub-device

**Description**

Create V4L2 Flash sub-device wrapping given LED subsystem device.
The ops pointer is stored by the V4L2 flash framework. No
references are held to config nor its contents once this function
has returned.

**Return**

A valid pointer, or, when an error occurs, the return
value is encoded using [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR). Use [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) to check and
[`PTR_ERR()`](/kernel/internals/core-api/kernel-api.md#c-PTR_ERR) to obtain the numeric return value.

#### <a id="c-v4l2_flash_release"></a>`v4l2_flash_release()`

```c
void v4l2_flash_release(struct v4l2_flash *v4l2_flash)
```

release V4L2 Flash sub-device

**Parameters**

- `struct v4l2_flash *v4l2_flash`: the V4L2 Flash sub-device to release

**Description**

Release V4L2 Flash sub-device.

---

# V4L2 fwnode kAPI

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for V4L2 fwnode kAPI.

<a id="rst-v4l2-fwnode-kapi"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-struct-v4l2_fwnode_endpoint"></a>`struct v4l2_fwnode_endpoint`

the endpoint data structure

**Definition**

```c
struct v4l2_fwnode_endpoint {
    struct fwnode_endpoint base;
    enum v4l2_mbus_type bus_type;
    struct {
        struct v4l2_mbus_config_parallel parallel;
        struct v4l2_mbus_config_mipi_csi1 mipi_csi1;
        struct v4l2_mbus_config_mipi_csi2 mipi_csi2;
    } bus;
    u64 *link_frequencies;
    unsigned int nr_of_link_frequencies;
};
```

**Members**

- `base`: fwnode endpoint of the v4l2_fwnode
- `bus_type`: bus type
- `bus`: bus configuration data structure
- `bus.parallel`: embedded [`struct v4l2_mbus_config_parallel`](/kernel/hardware/driver-api/media/v4l2-mediabus.md#c-struct-v4l2_mbus_config_parallel).
  Used if the bus is parallel.
- `bus.mipi_csi1`: embedded [`struct v4l2_mbus_config_mipi_csi1`](/kernel/hardware/driver-api/media/v4l2-mediabus.md#c-struct-v4l2_mbus_config_mipi_csi1).
  Used if the bus is MIPI Alliance's Camera Serial
  Interface version 1 (MIPI CSI1) or Standard
  Mobile Imaging Architecture's Compact Camera Port 2
  (SMIA CCP2).
- `bus.mipi_csi2`: embedded [`struct v4l2_mbus_config_mipi_csi2`](/kernel/hardware/driver-api/media/v4l2-mediabus.md#c-struct-v4l2_mbus_config_mipi_csi2).
  Used if the bus is MIPI Alliance's Camera Serial
  Interface version 2 (MIPI CSI2).
- `link_frequencies`: array of supported link frequencies
- `nr_of_link_frequencies`: number of elements in link_frequenccies array

#### <a id="c-V4L2_FWNODE_PROPERTY_UNSET"></a>`V4L2_FWNODE_PROPERTY_UNSET`

```c
V4L2_FWNODE_PROPERTY_UNSET
```

identify a non initialized property

**Description**

All properties in [`struct v4l2_fwnode_device_properties`](#c-struct-v4l2_fwnode_device_properties) are initialized
to this value.

#### <a id="c-enum-v4l2_fwnode_orientation"></a>`enum v4l2_fwnode_orientation`

possible device orientation

**Constants**

- `V4L2_FWNODE_ORIENTATION_FRONT`: device installed on the front side
- `V4L2_FWNODE_ORIENTATION_BACK`: device installed on the back side
- `V4L2_FWNODE_ORIENTATION_EXTERNAL`: device externally located

#### <a id="c-struct-v4l2_fwnode_device_properties"></a>`struct v4l2_fwnode_device_properties`

fwnode device properties

**Definition**

```c
struct v4l2_fwnode_device_properties {
    enum v4l2_fwnode_orientation orientation;
    unsigned int rotation;
};
```

**Members**

- `orientation`: device orientation. See [`enum v4l2_fwnode_orientation`](#c-enum-v4l2_fwnode_orientation)
- `rotation`: device rotation

#### <a id="c-struct-v4l2_fwnode_link"></a>`struct v4l2_fwnode_link`

a link between two endpoints

**Definition**

```c
struct v4l2_fwnode_link {
    struct fwnode_handle *local_node;
    unsigned int local_port;
    unsigned int local_id;
    struct fwnode_handle *remote_node;
    unsigned int remote_port;
    unsigned int remote_id;
};
```

**Members**

- `local_node`: pointer to device_node of this endpoint
- `local_port`: identifier of the port this endpoint belongs to
- `local_id`: identifier of the id this endpoint belongs to
- `remote_node`: pointer to device_node of the remote endpoint
- `remote_port`: identifier of the port the remote endpoint belongs to
- `remote_id`: identifier of the id the remote endpoint belongs to

#### <a id="c-enum-v4l2_connector_type"></a>`enum v4l2_connector_type`

connector type

**Constants**

- `V4L2_CONN_UNKNOWN`: unknown connector type, no V4L2 connector configuration
- `V4L2_CONN_COMPOSITE`: analog composite connector
- `V4L2_CONN_SVIDEO`: analog svideo connector

#### <a id="c-struct-v4l2_connector_link"></a>`struct v4l2_connector_link`

connector link data structure

**Definition**

```c
struct v4l2_connector_link {
    struct list_head head;
    struct v4l2_fwnode_link fwnode_link;
};
```

**Members**

- `head`: structure to be used to add the link to the
  [`struct v4l2_fwnode_connector`](#c-struct-v4l2_fwnode_connector)
- `fwnode_link`: [`struct v4l2_fwnode_link`](#c-struct-v4l2_fwnode_link) link between the connector and the
  device the connector belongs to.

#### <a id="c-struct-v4l2_fwnode_connector_analog"></a>`struct v4l2_fwnode_connector_analog`

analog connector data structure

**Definition**

```c
struct v4l2_fwnode_connector_analog {
    v4l2_std_id sdtv_stds;
};
```

**Members**

- `sdtv_stds`: sdtv standards this connector supports, set to V4L2_STD_ALL
  if no restrictions are specified.

#### <a id="c-struct-v4l2_fwnode_connector"></a>`struct v4l2_fwnode_connector`

the connector data structure

**Definition**

```c
struct v4l2_fwnode_connector {
    const char *name;
    const char *label;
    enum v4l2_connector_type type;
    struct list_head links;
    unsigned int nr_of_links;
    union {
        struct v4l2_fwnode_connector_analog analog;
    } connector;
};
```

**Members**

- `name`: the connector device name
- `label`: optional connector label
- `type`: connector type
- `links`: list of all connector [`struct v4l2_connector_link`](#c-struct-v4l2_connector_link) links
- `nr_of_links`: total number of links
- `connector`: connector configuration
- `connector.analog`: analog connector configuration
  [`struct v4l2_fwnode_connector_analog`](#c-struct-v4l2_fwnode_connector_analog)

#### <a id="c-enum-v4l2_fwnode_bus_type"></a>`enum v4l2_fwnode_bus_type`

Video bus types defined by firmware properties

**Constants**

- `V4L2_FWNODE_BUS_TYPE_GUESS`: Default value if no bus-type fwnode property
- `V4L2_FWNODE_BUS_TYPE_CSI2_CPHY`: MIPI CSI-2 bus, C-PHY physical layer
- `V4L2_FWNODE_BUS_TYPE_CSI1`: MIPI CSI-1 bus
- `V4L2_FWNODE_BUS_TYPE_CCP2`: SMIA Compact Camera Port 2 bus
- `V4L2_FWNODE_BUS_TYPE_CSI2_DPHY`: MIPI CSI-2 bus, D-PHY physical layer
- `V4L2_FWNODE_BUS_TYPE_PARALLEL`: Camera Parallel Interface bus
- `V4L2_FWNODE_BUS_TYPE_BT656`: BT.656 video format bus-type
- `V4L2_FWNODE_BUS_TYPE_DPI`: Video Parallel Interface bus
- `NR_OF_V4L2_FWNODE_BUS_TYPE`: Number of bus-types

#### <a id="c-v4l2_fwnode_endpoint_parse"></a>`v4l2_fwnode_endpoint_parse()`

```c
int v4l2_fwnode_endpoint_parse(struct fwnode_handle *fwnode, struct v4l2_fwnode_endpoint *vep)
```

parse all fwnode node properties

**Parameters**

- `struct fwnode_handle *fwnode`: pointer to the endpoint's fwnode handle (may be NULL)
- `struct v4l2_fwnode_endpoint *vep`: pointer to the V4L2 fwnode data structure

**Description**

This function parses the V4L2 fwnode endpoint specific parameters from the
firmware. There are two ways to use this function, either by letting it
obtain the type of the bus (by setting the **vep.bus_type** field to
V4L2_MBUS_UNKNOWN) or specifying the bus type explicitly to one of the [`enum v4l2_mbus_type`](/kernel/hardware/driver-api/media/v4l2-mediabus.md#c-enum-v4l2_mbus_type) types.

When **vep.bus_type** is V4L2_MBUS_UNKNOWN, the function will use the "bus-type"
property to determine the type when it is available. The caller is
responsible for validating the contents of **vep.bus_type** field after the call
returns.

As a deprecated functionality to support older DT bindings without "bus-type"
property for devices that support multiple types, if the "bus-type" property
does not exist, the function will attempt to guess the type based on the
endpoint properties available. NEVER RELY ON GUESSING THE BUS TYPE IN NEW
DRIVERS OR BINDINGS.

It is also possible to set **vep.bus_type** corresponding to an actual bus. In
this case the function will only attempt to parse properties related to this
bus, and it will return an error if the value of the "bus-type" property
corresponds to a different bus.

The caller is required to initialise all fields of **vep**, either with
explicitly values, or by zeroing them.

The function does not change the V4L2 fwnode endpoint state if it fails.

**NOTE**

This function does not parse "link-frequencies" property as its size is
not known in advance. Please use [`v4l2_fwnode_endpoint_alloc_parse()`](#c-v4l2_fwnode_endpoint_alloc_parse) if you
need properties of variable size.

**Return**

`0` on success or a negative error code on failure:
`-ENOMEM` on memory allocation failure
`-EINVAL` on parsing failure, including **fwnode** == NULL
`-ENXIO` on mismatching bus types

#### <a id="c-v4l2_fwnode_endpoint_free"></a>`v4l2_fwnode_endpoint_free()`

```c
void v4l2_fwnode_endpoint_free(struct v4l2_fwnode_endpoint *vep)
```

free the V4L2 fwnode acquired by [`v4l2_fwnode_endpoint_alloc_parse()`](#c-v4l2_fwnode_endpoint_alloc_parse)

**Parameters**

- `struct v4l2_fwnode_endpoint *vep`: the V4L2 fwnode the resources of which are to be released

**Description**

It is safe to call this function with NULL argument or on a V4L2 fwnode the
parsing of which failed.

#### <a id="c-v4l2_fwnode_endpoint_alloc_parse"></a>`v4l2_fwnode_endpoint_alloc_parse()`

```c
int v4l2_fwnode_endpoint_alloc_parse(struct fwnode_handle *fwnode, struct v4l2_fwnode_endpoint *vep)
```

parse all fwnode node properties

**Parameters**

- `struct fwnode_handle *fwnode`: pointer to the endpoint's fwnode handle (may be NULL)
- `struct v4l2_fwnode_endpoint *vep`: pointer to the V4L2 fwnode data structure

**Description**

This function parses the V4L2 fwnode endpoint specific parameters from the
firmware. There are two ways to use this function, either by letting it
obtain the type of the bus (by setting the **vep.bus_type** field to
V4L2_MBUS_UNKNOWN) or specifying the bus type explicitly to one of the [`enum v4l2_mbus_type`](/kernel/hardware/driver-api/media/v4l2-mediabus.md#c-enum-v4l2_mbus_type) types.

When **vep.bus_type** is V4L2_MBUS_UNKNOWN, the function will use the "bus-type"
property to determine the type when it is available. The caller is
responsible for validating the contents of **vep.bus_type** field after the call
returns.

As a deprecated functionality to support older DT bindings without "bus-type"
property for devices that support multiple types, if the "bus-type" property
does not exist, the function will attempt to guess the type based on the
endpoint properties available. NEVER RELY ON GUESSING THE BUS TYPE IN NEW
DRIVERS OR BINDINGS.

It is also possible to set **vep.bus_type** corresponding to an actual bus. In
this case the function will only attempt to parse properties related to this
bus, and it will return an error if the value of the "bus-type" property
corresponds to a different bus.

The caller is required to initialise all fields of **vep**, either with
explicitly values, or by zeroing them.

The function does not change the V4L2 fwnode endpoint state if it fails.

[`v4l2_fwnode_endpoint_alloc_parse()`](#c-v4l2_fwnode_endpoint_alloc_parse) has two important differences to
[`v4l2_fwnode_endpoint_parse()`](#c-v4l2_fwnode_endpoint_parse):

1. It also parses variable size data.

2. The memory it has allocated to store the variable size data must be freed
   using [`v4l2_fwnode_endpoint_free()`](#c-v4l2_fwnode_endpoint_free) when no longer needed.

**Return**

`0` on success or a negative error code on failure:
`-ENOMEM` on memory allocation failure
`-EINVAL` on parsing failure, including **fwnode** == NULL
`-ENXIO` on mismatching bus types

#### <a id="c-v4l2_fwnode_parse_link"></a>`v4l2_fwnode_parse_link()`

```c
int v4l2_fwnode_parse_link(struct fwnode_handle *fwnode, struct v4l2_fwnode_link *link)
```

parse a link between two endpoints

**Parameters**

- `struct fwnode_handle *fwnode`: pointer to the endpoint's fwnode at the local end of the link
- `struct v4l2_fwnode_link *link`: pointer to the V4L2 fwnode link data structure

**Description**

Fill the link structure with the local and remote nodes and port numbers.
The local_node and remote_node fields are set to point to the local and
remote port's parent nodes respectively (the port parent node being the
parent node of the port node if that node isn't a 'ports' node, or the
grand-parent node of the port node otherwise).

A reference is taken to both the local and remote nodes, the caller must use
[`v4l2_fwnode_put_link()`](#c-v4l2_fwnode_put_link) to drop the references when done with the
link.

**Return**

0 on success, or -ENOLINK if the remote endpoint fwnode can't be
found.

#### <a id="c-v4l2_fwnode_put_link"></a>`v4l2_fwnode_put_link()`

```c
void v4l2_fwnode_put_link(struct v4l2_fwnode_link *link)
```

drop references to nodes in a link

**Parameters**

- `struct v4l2_fwnode_link *link`: pointer to the V4L2 fwnode link data structure

**Description**

Drop references to the local and remote nodes in the link. This function
must be called on every link parsed with [`v4l2_fwnode_parse_link()`](#c-v4l2_fwnode_parse_link).

#### <a id="c-v4l2_fwnode_connector_free"></a>`v4l2_fwnode_connector_free()`

```c
void v4l2_fwnode_connector_free(struct v4l2_fwnode_connector *connector)
```

free the V4L2 connector acquired memory

**Parameters**

- `struct v4l2_fwnode_connector *connector`: the V4L2 connector resources of which are to be released

**Description**

Free all allocated memory and put all links acquired by
[`v4l2_fwnode_connector_parse()`](#c-v4l2_fwnode_connector_parse) and [`v4l2_fwnode_connector_add_link()`](#c-v4l2_fwnode_connector_add_link).

It is safe to call this function with NULL argument or on a V4L2 connector
the parsing of which failed.

#### <a id="c-v4l2_fwnode_connector_parse"></a>`v4l2_fwnode_connector_parse()`

```c
int v4l2_fwnode_connector_parse(struct fwnode_handle *fwnode, struct v4l2_fwnode_connector *connector)
```

initialize the 'struct v4l2_fwnode_connector'

**Parameters**

- `struct fwnode_handle *fwnode`: pointer to the subdev endpoint's fwnode handle where the connector
  is connected to or to the connector endpoint fwnode handle.
- `struct v4l2_fwnode_connector *connector`: pointer to the V4L2 fwnode connector data structure

**Description**

Fill the [`struct v4l2_fwnode_connector`](#c-struct-v4l2_fwnode_connector) with the connector type, label and
all [`enum v4l2_connector_type`](#c-enum-v4l2_connector_type) specific connector data. The label is optional
so it is set to `NULL` if no one was found. The function initialize the links
to zero. Adding links to the connector is done by calling
[`v4l2_fwnode_connector_add_link()`](#c-v4l2_fwnode_connector_add_link).

The memory allocated for the label must be freed when no longer needed.
Freeing the memory is done by [`v4l2_fwnode_connector_free()`](#c-v4l2_fwnode_connector_free).

**Return**

* `0` on success or a negative error code on failure:
* `-EINVAL` if **fwnode** is invalid
* `-ENOTCONN` if connector type is unknown or connector device can't be found

#### <a id="c-v4l2_fwnode_connector_add_link"></a>`v4l2_fwnode_connector_add_link()`

```c
int v4l2_fwnode_connector_add_link(struct fwnode_handle *fwnode, struct v4l2_fwnode_connector *connector)
```

add a link between a connector node and a v4l2-subdev node.

**Parameters**

- `struct fwnode_handle *fwnode`: pointer to the subdev endpoint's fwnode handle where the connector
  is connected to
- `struct v4l2_fwnode_connector *connector`: pointer to the V4L2 fwnode connector data structure

**Description**

Add a new [`struct v4l2_connector_link`](#c-struct-v4l2_connector_link) link to the
[`struct v4l2_fwnode_connector`](#c-struct-v4l2_fwnode_connector) connector links list. The link local_node
points to the connector node, the remote_node to the host v4l2 (sub)dev.

The taken references to remote_node and local_node must be dropped and the
allocated memory must be freed when no longer needed. Both is done by calling
[`v4l2_fwnode_connector_free()`](#c-v4l2_fwnode_connector_free).

**Return**

* `0` on success or a negative error code on failure:
* `-EINVAL` if **fwnode** or **connector** is invalid or **connector** type is unknown
* `-ENOMEM` on link memory allocation failure
* `-ENOTCONN` if remote connector device can't be found
* `-ENOLINK` if link parsing between v4l2 (sub)dev and connector fails

#### <a id="c-v4l2_fwnode_device_parse"></a>`v4l2_fwnode_device_parse()`

```c
int v4l2_fwnode_device_parse(struct device *dev, struct v4l2_fwnode_device_properties *props)
```

parse fwnode device properties

**Parameters**

- `struct device *dev`: pointer to [`struct device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device)
- `struct v4l2_fwnode_device_properties *props`: pointer to [`struct v4l2_fwnode_device_properties`](#c-struct-v4l2_fwnode_device_properties) where to store the
  parsed properties values

**Description**

This function parses and validates the V4L2 fwnode device properties from the
firmware interface, and fills the **struct** v4l2_fwnode_device_properties
provided by the caller.

**Return**

% 0 on success
`-EINVAL` if a parsed property value is not valid

---

# Introduction

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> The V4L2 drivers tend to be very complex due to the complexity of the hardware: most devices have multiple ICs, export multiple device nodes in /dev, and create also non-V4L2 devices such as DVB, ALSA, FB, I2C and input (IR) devices.

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

The V4L2 drivers tend to be very complex due to the complexity of the hardware: most devices have multiple ICs, export multiple device nodes in /dev, and create also non-V4L2 devices such as DVB, ALSA, FB, I2C and input (IR) devices.

Especially the fact that V4L2 drivers have to setup supporting ICs to do audio/video muxing/encoding/decoding makes it more complex than most. Usually these ICs are connected to the main bridge driver through one or more I2C buses, but other buses can also be used. Such devices are called 'sub-devices'.

For a long time the framework was limited to the video_device struct for creating V4L device nodes and video_buf for handling the video buffers (note that this document does not discuss the video_buf framework).

This meant that all drivers had to do the setup of device instances and connecting to sub-devices themselves. Some of this is quite complicated to do right and many drivers never did do it correctly.

There is also a lot of common code that could never be refactored due to the lack of a framework.

So this framework sets up the basic building blocks that all drivers need and this same framework should make it much easier to refactor common code into utility functions shared by all drivers.

A good example to look at as a reference is the v4l2-pci-skeleton.c source that is available in samples/v4l/. It is a skeleton driver for a PCI capture card, and demonstrates how to use the V4L2 driver framework. It can be used as a template for real PCI video capture driver.

<a id="rst-structure-of-a-v4l-driver"></a>

## Structure of a V4L driver

All drivers have the following structure:

1. A struct for each device instance containing the device state.

2. A way of initializing and commanding sub-devices (if any).

3. Creating V4L2 device nodes (/dev/videoX, /dev/vbiX and /dev/radioX) and keeping track of device-node specific data.

4. Filehandle-specific structs containing per-filehandle data;

5. video buffer handling.

This is a rough schematic of how it all relates:



```none
device instances
  |
  +-sub-device instances
  |
  \-V4L2 device nodes
      |
      \-filehandle instances
```

<a id="rst-structure-of-the-v4l2-framework"></a>

## Structure of the V4L2 framework

The framework closely resembles the driver structure: it has a v4l2_device struct for the device instance data, a v4l2_subdev struct to refer to sub-device instances, the video_device struct stores V4L2 device node data and the v4l2_fh struct keeps track of filehandle instances.

The V4L2 framework also optionally integrates with the media framework. If a driver sets the struct v4l2_device mdev field, sub-devices and video nodes will automatically appear in the media framework as entities.

---

# V4L2 generic ISP parameters and statistics support

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> ISP configuration parameters and statistics are processed and collected by drivers and exchanged with userspace through data types that usually reflect the ISP peripheral registers layout.

<a id="rst-v4l2-generic-isp-parameters-and-statistics-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-design-rationale"></a>

## Design rationale

ISP configuration parameters and statistics are processed and collected by drivers and exchanged with userspace through data types that usually reflect the ISP peripheral registers layout.

Each ISP driver defines its own metadata output format for parameters and a metadata capture format for statistics. The buffer layout is realized by a set of C structures that reflects the registers layout. The number and types of C structures is fixed by the format definition and becomes part of the Linux kernel uAPI/uABI interface.

Because of the hard requirement of backward compatibility when extending the user API/ABI interface, modifying an ISP driver capture or output metadata format after it has been accepted by mainline is very hard if not impossible.

It generally happens, in fact, that after the first accepted revision of an ISP driver the buffers layout need to be modified, either to support new hardware blocks, to fix bugs or to support different revisions of the hardware.

Each of these situations would require defining a new metadata format, making it really hard to maintain and extend drivers and requiring userspace to use the correct format depending on the kernel revision in use.

<a id="rst-v4l2-isp-configuration-parameters"></a>

## V4L2 ISP configuration parameters

For these reasons, Video4Linux2 defines generic types for ISP configuration parameters and statistics. Drivers are still expected to define their own formats for their metadata output and capture nodes, but the buffers layout can be defined using the extensible and versioned types defined by include/uapi/linux/media/v4l2-isp.h.

Drivers are expected to provide the definitions of their supported ISP blocks and the expected maximum size of a buffer.

For driver developers a set of helper functions to assist them with validation of the buffer received from userspace is available in drivers/media/v4l2-core/v4l2-isp.c

<a id="rst-v4l2-isp-support-driver-documentation"></a>

## V4L2 ISP support driver documentation


#### <a id="c-v4l2_isp_params_buffer_size"></a>`v4l2_isp_params_buffer_size()`

```c
v4l2_isp_params_buffer_size(max_params_size)
```

Calculate size of v4l2_isp_params_buffer

**Parameters**

- `max_params_size`: The total size of the ISP configuration blocks

**Description**

Users of the v4l2 extensible parameters will have differing sized data arrays
depending on their specific parameter buffers. Drivers and userspace will
need to be able to calculate the appropriate size of the struct to
accommodate all ISP configuration blocks provided by the platform.
This macro provides a convenient tool for the calculation.

#### <a id="c-v4l2_isp_params_validate_buffer_size"></a>`v4l2_isp_params_validate_buffer_size()`

```c
int v4l2_isp_params_validate_buffer_size(struct device *dev, struct vb2_buffer *vb, size_t max_size)
```

Validate a V4L2 ISP buffer sizes

**Parameters**

- `struct device *dev`: the driver's device pointer
- `struct vb2_buffer *vb`: the videobuf2 buffer
- `size_t max_size`: the maximum allowed buffer size

**Description**

This function performs validation of the size of a V4L2 ISP parameters buffer
before the driver can access the actual data buffer content.

After the sizes validation, drivers should copy the buffer content to a
kernel-only memory area to prevent userspace from modifying it,
before completing validation using [`v4l2_isp_params_validate_buffer()`](#c-v4l2_isp_params_validate_buffer).

The **vb** buffer as received from the vb2 .`buf_prepare()` operation is checked
against **max_size** and it's validated to be large enough to accommodate at
least one ISP configuration block.

#### <a id="c-struct-v4l2_isp_params_block_type_info"></a>`struct v4l2_isp_params_block_type_info`

V4L2 ISP per-block-type info

**Definition**

```c
struct v4l2_isp_params_block_type_info {
    size_t size;
};
```

**Members**

- `size`: the block type expected size

**Description**

The v4l2_isp_params_block_type_info collects information of the ISP
configuration block types for validation purposes. It currently only contains
the expected block type size.

Drivers shall prepare a list of block type info, indexed by block type, one
for each supported ISP block type and correctly populate them with the
expected block type size.

#### <a id="c-v4l2_isp_params_validate_buffer"></a>`v4l2_isp_params_validate_buffer()`

```c
int v4l2_isp_params_validate_buffer(struct device *dev, struct vb2_buffer *vb, const struct v4l2_isp_params_buffer *buffer, const struct v4l2_isp_params_block_type_info *type_info, size_t num_block_types)
```

Validate a V4L2 ISP parameters buffer

**Parameters**

- `struct device *dev`: the driver's device pointer
- `struct vb2_buffer *vb`: the videobuf2 buffer
- `const struct v4l2_isp_params_buffer *buffer`: the V4L2 ISP parameters buffer
- `const struct v4l2_isp_params_block_type_info *type_info`: the array of per-block-type validation info
- `size_t num_block_types`: the number of block types in the type_info array

**Description**

This function completes the validation of a V4L2 ISP parameters buffer,
verifying each configuration block correctness before the driver can use
them to program the hardware.

Drivers should use this function after having validated the correctness of
the vb2 buffer sizes by using the [`v4l2_isp_params_validate_buffer_size()`](#c-v4l2_isp_params_validate_buffer_size)
helper first. Once the buffer size has been validated, drivers should
perform a copy of the user provided buffer into a kernel-only memory buffer
to prevent userspace from modifying its content after it has been submitted
to the driver, and then call this function to complete validation.

---

# V4L2 JPEG header related functions and data structures

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for V4L2 JPEG header related functions and data structures.

<a id="rst-v4l2-jpeg-header-related-functions-and-data-structures"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-struct-v4l2_jpeg_reference"></a>`struct v4l2_jpeg_reference`

reference into the JPEG buffer

**Definition**

```c
struct v4l2_jpeg_reference {
    u8 *start;
    size_t length;
};
```

**Members**

- `start`: pointer to the start of the referenced segment or table
- `length`: size of the referenced segment or table

**Description**

Wnen referencing marker segments, start points right after the marker code,
and length is the size of the segment parameters, excluding the marker code.

#### <a id="c-struct-v4l2_jpeg_frame_component_spec"></a>`struct v4l2_jpeg_frame_component_spec`

frame component-specification

**Definition**

```c
struct v4l2_jpeg_frame_component_spec {
    u8 component_identifier;
    u8 horizontal_sampling_factor;
    u8 vertical_sampling_factor;
    u8 quantization_table_selector;
};
```

**Members**

- `component_identifier`: C\[i\]
- `horizontal_sampling_factor`: H\[i\]
- `vertical_sampling_factor`: V\[i\]
- `quantization_table_selector`: quantization table destination selector Tq\[i\]

#### <a id="c-struct-v4l2_jpeg_frame_header"></a>`struct v4l2_jpeg_frame_header`

JPEG frame header

**Definition**

```c
struct v4l2_jpeg_frame_header {
    u16 height;
    u16 width;
    u8 precision;
    u8 num_components;
    struct v4l2_jpeg_frame_component_spec component[V4L2_JPEG_MAX_COMPONENTS];
    enum v4l2_jpeg_chroma_subsampling subsampling;
};
```

**Members**

- `height`: Y
- `width`: X
- `precision`: P
- `num_components`: Nf
- `component`: component-specification, see v4l2_jpeg_frame_component_spec
- `subsampling`: decoded subsampling from component-specification

#### <a id="c-struct-v4l2_jpeg_scan_component_spec"></a>`struct v4l2_jpeg_scan_component_spec`

scan component-specification

**Definition**

```c
struct v4l2_jpeg_scan_component_spec {
    u8 component_selector;
    u8 dc_entropy_coding_table_selector;
    u8 ac_entropy_coding_table_selector;
};
```

**Members**

- `component_selector`: Cs\[j\]
- `dc_entropy_coding_table_selector`: Td\[j\]
- `ac_entropy_coding_table_selector`: Ta\[j\]

#### <a id="c-struct-v4l2_jpeg_scan_header"></a>`struct v4l2_jpeg_scan_header`

JPEG scan header

**Definition**

```c
struct v4l2_jpeg_scan_header {
    u8 num_components;
    struct v4l2_jpeg_scan_component_spec component[V4L2_JPEG_MAX_COMPONENTS];
};
```

**Members**

- `num_components`: Ns
- `component`: component-specification, see v4l2_jpeg_scan_component_spec

#### <a id="c-enum-v4l2_jpeg_app14_tf"></a>`enum v4l2_jpeg_app14_tf`

APP14 transform flag According to Rec. ITU-T T.872 (06/2012) 6.5.3 APP14 segment is for color encoding, it contains a transform flag, which may have values of 0, 1 and 2 and are interpreted as follows:

**Constants**

- `V4L2_JPEG_APP14_TF_CMYK_RGB`: CMYK for images encoded with four components
  RGB for images encoded with three components
- `V4L2_JPEG_APP14_TF_YCBCR`: an image encoded with three components using YCbCr
- `V4L2_JPEG_APP14_TF_YCCK`: an image encoded with four components using YCCK
- `V4L2_JPEG_APP14_TF_UNKNOWN`: indicate app14 is not present

#### <a id="c-struct-v4l2_jpeg_header"></a>`struct v4l2_jpeg_header`

parsed JPEG header

**Definition**

```c
struct v4l2_jpeg_header {
    struct v4l2_jpeg_reference sof;
    struct v4l2_jpeg_reference sos;
    unsigned int num_dht;
    struct v4l2_jpeg_reference dht[V4L2_JPEG_MAX_TABLES];
    unsigned int num_dqt;
    struct v4l2_jpeg_reference dqt[V4L2_JPEG_MAX_TABLES];
    struct v4l2_jpeg_frame_header frame;
    struct v4l2_jpeg_scan_header *scan;
    struct v4l2_jpeg_reference *quantization_tables;
    struct v4l2_jpeg_reference *huffman_tables;
    u16 restart_interval;
    size_t ecs_offset;
    enum v4l2_jpeg_app14_tf app14_tf;
};
```

**Members**

- `sof`: pointer to frame header and size
- `sos`: pointer to scan header and size
- `num_dht`: number of entries in **dht**
- `dht`: pointers to huffman tables and sizes
- `num_dqt`: number of entries in **dqt**
- `dqt`: pointers to quantization tables and sizes
- `frame`: parsed frame header
- `scan`: pointer to parsed scan header, optional
- `quantization_tables`: references to four quantization tables, optional
- `huffman_tables`: references to four Huffman tables in DC0, DC1, AC0, AC1
  order, optional
- `restart_interval`: number of MCU per restart interval, Ri
- `ecs_offset`: buffer offset in bytes to the entropy coded segment
- `app14_tf`: transform flag from app14 data

**Description**

When this structure is passed to v4l2_jpeg_parse_header, the optional scan,
quantization_tables, and huffman_tables pointers must be initialized to NULL
or point at valid memory.



#### <a id="c-v4l2_jpeg_parse_header"></a>`v4l2_jpeg_parse_header()`

```c
int v4l2_jpeg_parse_header(void *buf, size_t len, struct v4l2_jpeg_header *out)
```

locate marker segments and optionally parse headers

**Parameters**

- `void *buf`: address of the JPEG buffer, should start with a SOI marker
- `size_t len`: length of the JPEG buffer
- `struct v4l2_jpeg_header *out`: returns marker segment positions and optionally parsed headers

**Description**

The out->scan_header pointer must be initialized to NULL or point to a valid
v4l2_jpeg_scan_header structure. The out->huffman_tables and
out->quantization_tables pointers must be initialized to NULL or point to a
valid array of 4 v4l2_jpeg_reference structures each.

Returns 0 or negative error if parsing failed.

---

# V4L2 Media Controller functions and data structures

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for V4L2 Media Controller functions and data structures.

<a id="rst-v4l2-media-controller-functions-and-data-structures"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-v4l2_mc_create_media_graph"></a>`v4l2_mc_create_media_graph()`

```c
int v4l2_mc_create_media_graph(struct media_device *mdev)
```

create Media Controller links at the graph.

**Parameters**

- `struct media_device *mdev`: pointer to the [`media_device`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_device) struct.

**Description**

Add links between the entities commonly found on PC customer's hardware at
the V4L2 side: camera sensors, audio and video PLL-IF decoders, tuners,
analog TV decoder and I/O entities (video, VBI and Software Defined Radio).

> [!NOTE]
> Webcams are modelled on a very simple way: the sensor is
> connected directly to the I/O entity. All dirty details, like
> scaler and crop HW are hidden. While such mapping is enough for v4l2
> interface centric PC-consumer's hardware, V4L2 subdev centric camera
> hardware should not use this routine, as it will not build the right graph.

#### <a id="c-v4l_enable_media_source"></a>`v4l_enable_media_source()`

```c
int v4l_enable_media_source(struct video_device *vdev)
```

Hold media source for exclusive use if free

**Parameters**

- `struct video_device *vdev`: pointer to struct video_device

**Description**

This interface calls enable_source handler to determine if
media source is free for use. The enable_source handler is
responsible for checking is the media source is free and
start a pipeline between the media source and the media
entity associated with the video device. This interface
should be called from v4l2-core and dvb-core interfaces
that change the source configuration.

**Return**

returns zero on success or a negative error code.

#### <a id="c-v4l_disable_media_source"></a>`v4l_disable_media_source()`

```c
void v4l_disable_media_source(struct video_device *vdev)
```

Release media source

**Parameters**

- `struct video_device *vdev`: pointer to struct video_device

**Description**

This interface calls disable_source handler to release
the media source. The disable_source handler stops the
active media pipeline between the media source and the
media entity associated with the video device.

**Return**

returns zero on success or a negative error code.

#### <a id="c-v4l2_create_fwnode_links_to_pad"></a>`v4l2_create_fwnode_links_to_pad()`

```c
int v4l2_create_fwnode_links_to_pad(struct v4l2_subdev *src_sd, struct media_pad *sink, u32 flags)
```

Create fwnode-based links from a source subdev to a sink pad.

**Parameters**

- `struct v4l2_subdev *src_sd`: pointer to a source subdev
- `struct media_pad *sink`: pointer to a sink pad
- `u32 flags`: the link flags

**Description**

This function searches for fwnode endpoint connections from a source
subdevice to a single sink pad, and if suitable connections are found,
translates them into media links to that pad. The function can be
called by the sink, in its v4l2-async notifier bound callback, to create
links from a bound source subdevice.

The **flags** argument specifies the link flags. The caller shall ensure that
the flags are valid regardless of the number of links that may be created.
For instance, setting the MEDIA_LNK_FL_ENABLED flag will cause all created
links to be enabled, which isn't valid if more than one link is created.

> [!NOTE]
> Any sink subdevice that calls this function must implement the
> .get_fwnode_pad media operation in order to verify endpoints passed
> to the sink are owned by the sink.

Return 0 on success or a negative error code on failure.

#### <a id="c-v4l2_create_fwnode_links"></a>`v4l2_create_fwnode_links()`

```c
int v4l2_create_fwnode_links(struct v4l2_subdev *src_sd, struct v4l2_subdev *sink_sd)
```

Create fwnode-based links from a source subdev to a sink subdev.

**Parameters**

- `struct v4l2_subdev *src_sd`: pointer to a source subdevice
- `struct v4l2_subdev *sink_sd`: pointer to a sink subdevice

**Description**

This function searches for any and all fwnode endpoint connections
between source and sink subdevices, and translates them into media
links. The function can be called by the sink subdevice, in its
v4l2-async notifier subdev bound callback, to create all links from
a bound source subdevice.

> [!NOTE]
> Any sink subdevice that calls this function must implement the
> .get_fwnode_pad media operation in order to verify endpoints passed
> to the sink are owned by the sink.

Return 0 on success or a negative error code on failure.

#### <a id="c-v4l2_pipeline_pm_get"></a>`v4l2_pipeline_pm_get()`

```c
int v4l2_pipeline_pm_get(struct media_entity *entity)
```

Increase the use count of a pipeline

**Parameters**

- `struct media_entity *entity`: The root entity of a pipeline

**Description**

THIS FUNCTION IS DEPRECATED. DO NOT USE IN NEW DRIVERS. USE RUNTIME PM
ON SUB-DEVICE DRIVERS INSTEAD.

Update the use count of all entities in the pipeline and power entities on.

This function is intended to be called in video node open. It uses
struct media_entity.use_count to track the power status. The use
of this function should be paired with [`v4l2_pipeline_link_notify()`](#c-v4l2_pipeline_link_notify).

Return 0 on success or a negative error code on failure.

#### <a id="c-v4l2_pipeline_pm_put"></a>`v4l2_pipeline_pm_put()`

```c
void v4l2_pipeline_pm_put(struct media_entity *entity)
```

Decrease the use count of a pipeline

**Parameters**

- `struct media_entity *entity`: The root entity of a pipeline

**Description**

THIS FUNCTION IS DEPRECATED. DO NOT USE IN NEW DRIVERS. USE RUNTIME PM
ON SUB-DEVICE DRIVERS INSTEAD.

Update the use count of all entities in the pipeline and power entities off.

This function is intended to be called in video node release. It uses
struct media_entity.use_count to track the power status. The use
of this function should be paired with [`v4l2_pipeline_link_notify()`](#c-v4l2_pipeline_link_notify).

#### <a id="c-v4l2_pipeline_link_notify"></a>`v4l2_pipeline_link_notify()`

```c
int v4l2_pipeline_link_notify(struct media_link *link, u32 flags, unsigned int notification)
```

Link management notification callback

**Parameters**

- `struct media_link *link`: The link
- `u32 flags`: New link flags that will be applied
- `unsigned int notification`: The link's state change notification type (MEDIA_DEV_NOTIFY_*)

**Description**

THIS FUNCTION IS DEPRECATED. DO NOT USE IN NEW DRIVERS. USE RUNTIME PM
ON SUB-DEVICE DRIVERS INSTEAD.

React to link management on powered pipelines by updating the use count of
all entities in the source and sink sides of the link. Entities are powered
on or off accordingly. The use of this function should be paired
with v4l2_pipeline_pm_{get,put}().

Return 0 on success or a negative error code on failure. Powering entities
off is assumed to never fail. This function will not fail for disconnection
events.

---

# V4L2 Media Bus functions and data structures

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for V4L2 Media Bus functions and data structures.

<a id="rst-v4l2-media-bus-functions-and-data-structures"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-enum-v4l2_mbus_csi2_cphy_line_orders_type"></a>`enum v4l2_mbus_csi2_cphy_line_orders_type`

CSI-2 C-PHY line order

**Constants**

- `V4L2_MBUS_CSI2_CPHY_LINE_ORDER_ABC`: C-PHY line order ABC (default)
- `V4L2_MBUS_CSI2_CPHY_LINE_ORDER_ACB`: C-PHY line order ACB
- `V4L2_MBUS_CSI2_CPHY_LINE_ORDER_BAC`: C-PHY line order BAC
- `V4L2_MBUS_CSI2_CPHY_LINE_ORDER_BCA`: C-PHY line order BCA
- `V4L2_MBUS_CSI2_CPHY_LINE_ORDER_CAB`: C-PHY line order CAB
- `V4L2_MBUS_CSI2_CPHY_LINE_ORDER_CBA`: C-PHY line order CBA

#### <a id="c-struct-v4l2_mbus_config_mipi_csi2"></a>`struct v4l2_mbus_config_mipi_csi2`

MIPI CSI-2 data bus configuration

**Definition**

```c
struct v4l2_mbus_config_mipi_csi2 {
    unsigned int flags;
    unsigned char data_lanes[V4L2_MBUS_CSI2_MAX_DATA_LANES];
    unsigned char clock_lane;
    unsigned char num_data_lanes;
    bool lane_polarities[1 + V4L2_MBUS_CSI2_MAX_DATA_LANES];
    enum v4l2_mbus_csi2_cphy_line_orders_type line_orders[V4L2_MBUS_CSI2_MAX_DATA_LANES];
};
```

**Members**

- `flags`: media bus (V4L2_MBUS_*) flags
- `data_lanes`: an array of physical data lane indexes
- `clock_lane`: physical lane index of the clock lane
- `num_data_lanes`: number of data lanes
- `lane_polarities`: polarity of the lanes. The order is the same of
  the physical lanes.
- `line_orders`: line order of the data lanes. The order is the same of the
  physical lanes.

#### <a id="c-struct-v4l2_mbus_config_parallel"></a>`struct v4l2_mbus_config_parallel`

parallel data bus configuration

**Definition**

```c
struct v4l2_mbus_config_parallel {
    unsigned int flags;
    unsigned char bus_width;
    unsigned char data_shift;
};
```

**Members**

- `flags`: media bus (V4L2_MBUS_*) flags
- `bus_width`: bus width in bits
- `data_shift`: data shift in bits

#### <a id="c-struct-v4l2_mbus_config_mipi_csi1"></a>`struct v4l2_mbus_config_mipi_csi1`

CSI-1/CCP2 data bus configuration

**Definition**

```c
struct v4l2_mbus_config_mipi_csi1 {
    unsigned char clock_inv:1;
    unsigned char strobe:1;
    bool lane_polarity[2];
    unsigned char data_lane;
    unsigned char clock_lane;
};
```

**Members**

- `clock_inv`: polarity of clock/strobe signal
  false - not inverted, true - inverted
- `strobe`: false - data/clock, true - data/strobe
- `lane_polarity`: the polarities of the clock (index 0) and data lanes
  index (1)
- `data_lane`: the number of the data lane
- `clock_lane`: the number of the clock lane

#### <a id="c-enum-v4l2_mbus_type"></a>`enum v4l2_mbus_type`

media bus type

**Constants**

- `V4L2_MBUS_UNKNOWN`: unknown bus type, no V4L2 mediabus configuration
- `V4L2_MBUS_PARALLEL`: parallel interface with hsync and vsync
- `V4L2_MBUS_BT656`: parallel interface with embedded synchronisation, can
  also be used for BT.1120
- `V4L2_MBUS_CSI1`: MIPI CSI-1 serial interface
- `V4L2_MBUS_CCP2`: CCP2 (Compact Camera Port 2)
- `V4L2_MBUS_CSI2_DPHY`: MIPI CSI-2 serial interface, with D-PHY
- `V4L2_MBUS_CSI2_CPHY`: MIPI CSI-2 serial interface, with C-PHY
- `V4L2_MBUS_DPI`: MIPI VIDEO DPI interface
- `V4L2_MBUS_INVALID`: invalid bus type (keep as last)

#### <a id="c-struct-v4l2_mbus_config"></a>`struct v4l2_mbus_config`

media bus configuration

**Definition**

```c
struct v4l2_mbus_config {
    enum v4l2_mbus_type type;
    u64 link_freq;
    union {
        struct v4l2_mbus_config_parallel parallel;
        struct v4l2_mbus_config_mipi_csi1 mipi_csi1;
        struct v4l2_mbus_config_mipi_csi2 mipi_csi2;
    } bus;
};
```

**Members**

- `type`: interface type
- `link_freq`: The link frequency. See also V4L2_CID_LINK_FREQ control.
- `bus`: bus configuration data structure
- `bus.parallel`: embedded [`struct v4l2_mbus_config_parallel`](#c-struct-v4l2_mbus_config_parallel).
  Used if the bus is parallel or BT.656.
- `bus.mipi_csi1`: embedded [`struct v4l2_mbus_config_mipi_csi1`](#c-struct-v4l2_mbus_config_mipi_csi1).
  Used if the bus is MIPI Alliance's Camera Serial
  Interface version 1 (MIPI CSI1) or Standard
  Mobile Imaging Architecture's Compact Camera Port 2
  (SMIA CCP2).
- `bus.mipi_csi2`: embedded [`struct v4l2_mbus_config_mipi_csi2`](#c-struct-v4l2_mbus_config_mipi_csi2).
  Used if the bus is MIPI Alliance's Camera Serial
  Interface version 2 (MIPI CSI2).

#### <a id="c-v4l2_fill_pix_format"></a>`v4l2_fill_pix_format()`

```c
void v4l2_fill_pix_format(struct v4l2_pix_format *pix_fmt, const struct v4l2_mbus_framefmt *mbus_fmt)
```

Ancillary routine that fills a [`struct v4l2_pix_format`](/kernel/userspace/userspace-api/media-v4l/pixfmt-v4l2.md#c-v4l2_pix_format) fields from a [`struct v4l2_mbus_framefmt`](/kernel/userspace/userspace-api/media-v4l/subdev-formats.md#c-v4l2_mbus_framefmt).

**Parameters**

- `struct v4l2_pix_format *pix_fmt`: pointer to [`struct v4l2_pix_format`](/kernel/userspace/userspace-api/media-v4l/pixfmt-v4l2.md#c-v4l2_pix_format) to be filled
- `const struct v4l2_mbus_framefmt *mbus_fmt`: pointer to [`struct v4l2_mbus_framefmt`](/kernel/userspace/userspace-api/media-v4l/subdev-formats.md#c-v4l2_mbus_framefmt) to be used as model

#### <a id="c-v4l2_fill_mbus_format"></a>`v4l2_fill_mbus_format()`

```c
void v4l2_fill_mbus_format(struct v4l2_mbus_framefmt *mbus_fmt, const struct v4l2_pix_format *pix_fmt, u32 code)
```

Ancillary routine that fills a [`struct v4l2_mbus_framefmt`](/kernel/userspace/userspace-api/media-v4l/subdev-formats.md#c-v4l2_mbus_framefmt) from a [`struct v4l2_pix_format`](/kernel/userspace/userspace-api/media-v4l/pixfmt-v4l2.md#c-v4l2_pix_format) and a data format code.

**Parameters**

- `struct v4l2_mbus_framefmt *mbus_fmt`: pointer to [`struct v4l2_mbus_framefmt`](/kernel/userspace/userspace-api/media-v4l/subdev-formats.md#c-v4l2_mbus_framefmt) to be filled
- `const struct v4l2_pix_format *pix_fmt`: pointer to [`struct v4l2_pix_format`](/kernel/userspace/userspace-api/media-v4l/pixfmt-v4l2.md#c-v4l2_pix_format) to be used as model
- `u32 code`: data format code (from `enum v4l2_mbus_pixelcode`)

#### <a id="c-v4l2_fill_pix_format_mplane"></a>`v4l2_fill_pix_format_mplane()`

```c
void v4l2_fill_pix_format_mplane(struct v4l2_pix_format_mplane *pix_mp_fmt, const struct v4l2_mbus_framefmt *mbus_fmt)
```

Ancillary routine that fills a [`struct v4l2_pix_format_mplane`](/kernel/userspace/userspace-api/media-v4l/pixfmt-v4l2-mplane.md#c-v4l2_pix_format_mplane) fields from a media bus structure.

**Parameters**

- `struct v4l2_pix_format_mplane *pix_mp_fmt`: pointer to [`struct v4l2_pix_format_mplane`](/kernel/userspace/userspace-api/media-v4l/pixfmt-v4l2-mplane.md#c-v4l2_pix_format_mplane) to be filled
- `const struct v4l2_mbus_framefmt *mbus_fmt`: pointer to [`struct v4l2_mbus_framefmt`](/kernel/userspace/userspace-api/media-v4l/subdev-formats.md#c-v4l2_mbus_framefmt) to be used as model

#### <a id="c-v4l2_fill_mbus_format_mplane"></a>`v4l2_fill_mbus_format_mplane()`

```c
void v4l2_fill_mbus_format_mplane(struct v4l2_mbus_framefmt *mbus_fmt, const struct v4l2_pix_format_mplane *pix_mp_fmt)
```

Ancillary routine that fills a [`struct v4l2_mbus_framefmt`](/kernel/userspace/userspace-api/media-v4l/subdev-formats.md#c-v4l2_mbus_framefmt) from a [`struct v4l2_pix_format_mplane`](/kernel/userspace/userspace-api/media-v4l/pixfmt-v4l2-mplane.md#c-v4l2_pix_format_mplane).

**Parameters**

- `struct v4l2_mbus_framefmt *mbus_fmt`: pointer to [`struct v4l2_mbus_framefmt`](/kernel/userspace/userspace-api/media-v4l/subdev-formats.md#c-v4l2_mbus_framefmt) to be filled
- `const struct v4l2_pix_format_mplane *pix_mp_fmt`: pointer to [`struct v4l2_pix_format_mplane`](/kernel/userspace/userspace-api/media-v4l/pixfmt-v4l2-mplane.md#c-v4l2_pix_format_mplane) to be used as model

---

# V4L2 Memory to Memory functions and data structures

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for V4L2 Memory to Memory functions and data structures.

<a id="rst-v4l2-memory-to-memory-functions-and-data-structures"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-struct-v4l2_m2m_ops"></a>`struct v4l2_m2m_ops`

mem-to-mem device driver callbacks

**Definition**

```c
struct v4l2_m2m_ops {
    void (*device_run)(void *priv);
    int (*job_ready)(void *priv);
    void (*job_abort)(void *priv);
};
```

**Members**

- `device_run`: required. Begin the actual job (transaction) inside this
  callback.
  The job does NOT have to end before this callback returns
  (and it will be the usual case). When the job finishes,
  [`v4l2_m2m_job_finish()`](#c-v4l2_m2m_job_finish) or [`v4l2_m2m_buf_done_and_job_finish()`](#c-v4l2_m2m_buf_done_and_job_finish)
  has to be called.
- `job_ready`: optional. Should return 0 if the driver does not have a job
  fully prepared to run yet (i.e. it will not be able to finish a
  transaction without sleeping). If not provided, it will be
  assumed that one source and one destination buffer are all
  that is required for the driver to perform one full transaction.
  This method may not sleep.
- `job_abort`: optional. Informs the driver that it has to abort the currently
  running transaction as soon as possible (i.e. as soon as it can
  stop the device safely; e.g. in the next interrupt handler),
  even if the transaction would not have been finished by then.
  After the driver performs the necessary steps, it has to call
  [`v4l2_m2m_job_finish()`](#c-v4l2_m2m_job_finish) or [`v4l2_m2m_buf_done_and_job_finish()`](#c-v4l2_m2m_buf_done_and_job_finish) as
  if the transaction ended normally.
  This function does not have to (and will usually not) wait
  until the device enters a state when it can be stopped.

#### <a id="c-struct-v4l2_m2m_queue_ctx"></a>`struct v4l2_m2m_queue_ctx`

represents a queue for buffers ready to be processed

**Definition**

```c
struct v4l2_m2m_queue_ctx {
    struct vb2_queue        q;
    struct list_head        rdy_queue;
    spinlock_t rdy_spinlock;
    u8 num_rdy;
    bool buffered;
};
```

**Members**

- `q`: pointer to struct [`vb2_queue`](/kernel/hardware/driver-api/media/v4l2-videobuf2.md#c-struct-vb2_queue)
- `rdy_queue`: List of V4L2 mem-to-mem queues
- `rdy_spinlock`: spin lock to protect the struct usage
- `num_rdy`: number of buffers ready to be processed
- `buffered`: is the queue buffered?

**Description**

Queue for buffers ready to be processed as soon as this
instance receives access to the device.

#### <a id="c-struct-v4l2_m2m_ctx"></a>`struct v4l2_m2m_ctx`

Memory to memory context structure

**Definition**

```c
struct v4l2_m2m_ctx {
    struct mutex                    *q_lock;
    bool new_frame;
    bool is_draining;
    struct vb2_v4l2_buffer          *last_src_buf;
    bool next_buf_last;
    bool has_stopped;
    bool ignore_cap_streaming;
    struct v4l2_m2m_dev             *m2m_dev;
    struct v4l2_m2m_queue_ctx       cap_q_ctx;
    struct v4l2_m2m_queue_ctx       out_q_ctx;
    struct list_head                queue;
    unsigned long                   job_flags;
    wait_queue_head_t finished;
    void *priv;
};
```

**Members**

- `q_lock`: struct `mutex` lock
- `new_frame`: valid in the device_run callback: if true, then this
  starts a new frame; if false, then this is a new slice
  for an existing frame. This is always true unless
  V4L2_BUF_CAP_SUPPORTS_M2M_HOLD_CAPTURE_BUF is set, which
  indicates slicing support.
- `is_draining`: indicates device is in draining phase
- `last_src_buf`: indicate the last source buffer for draining
- `next_buf_last`: next capture queud buffer will be tagged as last
- `has_stopped`: indicate the device has been stopped
- `ignore_cap_streaming`: If true, job_ready can be called even if the CAPTURE
  queue is not streaming. This allows firmware to
  analyze the bitstream header which arrives on the
  OUTPUT queue. The driver must implement the job_ready
  callback correctly to make sure that the requirements
  for actual decoding are met.
- `m2m_dev`: opaque pointer to the internal data to handle M2M context
- `cap_q_ctx`: Capture (output to memory) queue context
- `out_q_ctx`: Output (input from memory) queue context
- `queue`: List of memory to memory contexts
- `job_flags`: Job queue flags, used internally by v4l2-mem2mem.c:
  `TRANS_QUEUED`, `TRANS_RUNNING` and `TRANS_ABORT`.
- `finished`: Wait queue used to signalize when a job queue finished.
- `priv`: Instance private data

**Description**

The memory to memory context is specific to a file handle, NOT to e.g.
a device.

#### <a id="c-struct-v4l2_m2m_buffer"></a>`struct v4l2_m2m_buffer`

Memory to memory buffer

**Definition**

```c
struct v4l2_m2m_buffer {
    struct vb2_v4l2_buffer  vb;
    struct list_head        list;
};
```

**Members**

- `vb`: pointer to struct [`vb2_v4l2_buffer`](/kernel/hardware/driver-api/media/v4l2-videobuf2.md#c-struct-vb2_v4l2_buffer)
- `list`: list of m2m buffers

#### <a id="c-v4l2_m2m_get_curr_priv"></a>`v4l2_m2m_get_curr_priv()`

```c
void * v4l2_m2m_get_curr_priv(struct v4l2_m2m_dev *m2m_dev)
```

return driver private data for the currently running instance or NULL if no instance is running

**Parameters**

- `struct v4l2_m2m_dev *m2m_dev`: opaque pointer to the internal data to handle M2M context

#### <a id="c-v4l2_m2m_get_vq"></a>`v4l2_m2m_get_vq()`

```c
struct vb2_queue * v4l2_m2m_get_vq(struct v4l2_m2m_ctx *m2m_ctx, enum v4l2_buf_type type)
```

return vb2_queue for the given type

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `enum v4l2_buf_type type`: type of the V4L2 buffer, as defined by enum `v4l2_buf_type`

**Description**

This function returns the capture queue when **type** is a capture type, and the
output queue otherwise. It never returns a NULL pointer.

#### <a id="c-v4l2_m2m_try_schedule"></a>`v4l2_m2m_try_schedule()`

```c
void v4l2_m2m_try_schedule(struct v4l2_m2m_ctx *m2m_ctx)
```

check whether an instance is ready to be added to the pending job queue and add it if so.

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

**Description**

There are three basic requirements an instance has to meet to be able to run:
1) at least one source buffer has to be queued,
2) at least one destination buffer has to be queued,
3) streaming has to be on.

If a queue is buffered (for example a decoder hardware ringbuffer that has
to be drained before doing streamoff), allow scheduling without v4l2 buffers
on that queue.

There may also be additional, custom requirements. In such case the driver
should supply a custom callback (job_ready in v4l2_m2m_ops) that should
return 1 if the instance is ready.
An example of the above could be an instance that requires more than one
src/dst buffer per transaction.

#### <a id="c-v4l2_m2m_job_finish"></a>`v4l2_m2m_job_finish()`

```c
void v4l2_m2m_job_finish(struct v4l2_m2m_dev *m2m_dev, struct v4l2_m2m_ctx *m2m_ctx)
```

inform the framework that a job has been finished and have it clean up

**Parameters**

- `struct v4l2_m2m_dev *m2m_dev`: opaque pointer to the internal data to handle M2M context
- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

**Description**

Called by a driver to yield back the device after it has finished with it.
Should be called as soon as possible after reaching a state which allows
other instances to take control of the device.

This function has to be called only after [`v4l2_m2m_ops->device_run`](#c-struct-v4l2_m2m_ops)
callback has been called on the driver.

#### <a id="c-v4l2_m2m_buf_done_and_job_finish"></a>`v4l2_m2m_buf_done_and_job_finish()`

```c
void v4l2_m2m_buf_done_and_job_finish(struct v4l2_m2m_dev *m2m_dev, struct v4l2_m2m_ctx *m2m_ctx, enum vb2_buffer_state state)
```

return source/destination buffers with state and inform the framework that a job has been finished and have it clean up

**Parameters**

- `struct v4l2_m2m_dev *m2m_dev`: opaque pointer to the internal data to handle M2M context
- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `enum vb2_buffer_state state`: vb2 buffer state passed to `v4l2_m2m_buf_done()`.

**Description**

Drivers that set V4L2_BUF_CAP_SUPPORTS_M2M_HOLD_CAPTURE_BUF must use this
function instead of `job_finish()` to take held buffers into account. It is
optional for other drivers.

This function removes the source buffer from the ready list and returns
it with the given state. The same is done for the destination buffer, unless
it is marked 'held'. In that case the buffer is kept on the ready list.

After that the job is finished (see `job_finish()`).

This allows for multiple output buffers to be used to fill in a single
capture buffer. This is typically used by stateless decoders where
multiple e.g. H.264 slices contribute to a single decoded frame.

#### <a id="c-v4l2_m2m_clear_state"></a>`v4l2_m2m_clear_state()`

```c
void v4l2_m2m_clear_state(struct v4l2_m2m_ctx *m2m_ctx)
```

clear encoding/decoding state

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

#### <a id="c-v4l2_m2m_mark_stopped"></a>`v4l2_m2m_mark_stopped()`

```c
void v4l2_m2m_mark_stopped(struct v4l2_m2m_ctx *m2m_ctx)
```

set current encoding/decoding state as stopped

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

#### <a id="c-v4l2_m2m_dst_buf_is_last"></a>`v4l2_m2m_dst_buf_is_last()`

```c
bool v4l2_m2m_dst_buf_is_last(struct v4l2_m2m_ctx *m2m_ctx)
```

return the current encoding/decoding session draining management state of next queued capture buffer

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

**Description**

This last capture buffer should be tagged with V4L2_BUF_FLAG_LAST to notify
the end of the capture session.

#### <a id="c-v4l2_m2m_has_stopped"></a>`v4l2_m2m_has_stopped()`

```c
bool v4l2_m2m_has_stopped(struct v4l2_m2m_ctx *m2m_ctx)
```

return the current encoding/decoding session stopped state

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

#### <a id="c-v4l2_m2m_is_last_draining_src_buf"></a>`v4l2_m2m_is_last_draining_src_buf()`

```c
bool v4l2_m2m_is_last_draining_src_buf(struct v4l2_m2m_ctx *m2m_ctx, struct vb2_v4l2_buffer *vbuf)
```

return the output buffer draining state in the current encoding/decoding session

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct vb2_v4l2_buffer *vbuf`: pointer to struct `v4l2_buffer`

**Description**

This will identify the last output buffer queued before a session stop
was required, leading to an actual encoding/decoding session stop state
in the encoding/decoding process after being processed.

#### <a id="c-v4l2_m2m_last_buffer_done"></a>`v4l2_m2m_last_buffer_done()`

```c
void v4l2_m2m_last_buffer_done(struct v4l2_m2m_ctx *m2m_ctx, struct vb2_v4l2_buffer *vbuf)
```

marks the buffer with LAST flag and DONE

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct vb2_v4l2_buffer *vbuf`: pointer to struct `v4l2_buffer`

#### <a id="c-v4l2_m2m_suspend"></a>`v4l2_m2m_suspend()`

```c
void v4l2_m2m_suspend(struct v4l2_m2m_dev *m2m_dev)
```

stop new jobs from being run and wait for current job to finish

**Parameters**

- `struct v4l2_m2m_dev *m2m_dev`: opaque pointer to the internal data to handle M2M context

**Description**

Called by a driver in the suspend hook. Stop new jobs from being run, and
wait for current running job to finish.

#### <a id="c-v4l2_m2m_resume"></a>`v4l2_m2m_resume()`

```c
void v4l2_m2m_resume(struct v4l2_m2m_dev *m2m_dev)
```

resume job running and try to run a queued job

**Parameters**

- `struct v4l2_m2m_dev *m2m_dev`: opaque pointer to the internal data to handle M2M context

**Description**

Called by a driver in the resume hook. This reverts the operation of
[`v4l2_m2m_suspend()`](#c-v4l2_m2m_suspend) and allows job to be run. Also try to run a queued job if
there is any.

#### <a id="c-v4l2_m2m_reqbufs"></a>`v4l2_m2m_reqbufs()`

```c
int v4l2_m2m_reqbufs(struct file *file, struct v4l2_m2m_ctx *m2m_ctx, struct v4l2_requestbuffers *reqbufs)
```

multi-queue-aware REQBUFS multiplexer

**Parameters**

- `struct file *file`: pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file)
- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct v4l2_requestbuffers *reqbufs`: pointer to struct `v4l2_requestbuffers`

#### <a id="c-v4l2_m2m_querybuf"></a>`v4l2_m2m_querybuf()`

```c
int v4l2_m2m_querybuf(struct file *file, struct v4l2_m2m_ctx *m2m_ctx, struct v4l2_buffer *buf)
```

multi-queue-aware QUERYBUF multiplexer

**Parameters**

- `struct file *file`: pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file)
- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct v4l2_buffer *buf`: pointer to struct `v4l2_buffer`

**Description**

See [`v4l2_m2m_mmap()`](#c-v4l2_m2m_mmap) documentation for details.

#### <a id="c-v4l2_m2m_qbuf"></a>`v4l2_m2m_qbuf()`

```c
int v4l2_m2m_qbuf(struct file *file, struct v4l2_m2m_ctx *m2m_ctx, struct v4l2_buffer *buf)
```

enqueue a source or destination buffer, depending on the type

**Parameters**

- `struct file *file`: pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file)
- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct v4l2_buffer *buf`: pointer to struct `v4l2_buffer`

#### <a id="c-v4l2_m2m_dqbuf"></a>`v4l2_m2m_dqbuf()`

```c
int v4l2_m2m_dqbuf(struct file *file, struct v4l2_m2m_ctx *m2m_ctx, struct v4l2_buffer *buf)
```

dequeue a source or destination buffer, depending on the type

**Parameters**

- `struct file *file`: pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file)
- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct v4l2_buffer *buf`: pointer to struct `v4l2_buffer`

#### <a id="c-v4l2_m2m_prepare_buf"></a>`v4l2_m2m_prepare_buf()`

```c
int v4l2_m2m_prepare_buf(struct file *file, struct v4l2_m2m_ctx *m2m_ctx, struct v4l2_buffer *buf)
```

prepare a source or destination buffer, depending on the type

**Parameters**

- `struct file *file`: pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file)
- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct v4l2_buffer *buf`: pointer to struct `v4l2_buffer`

#### <a id="c-v4l2_m2m_create_bufs"></a>`v4l2_m2m_create_bufs()`

```c
int v4l2_m2m_create_bufs(struct file *file, struct v4l2_m2m_ctx *m2m_ctx, struct v4l2_create_buffers *create)
```

create a source or destination buffer, depending on the type

**Parameters**

- `struct file *file`: pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file)
- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct v4l2_create_buffers *create`: pointer to struct `v4l2_create_buffers`

#### <a id="c-v4l2_m2m_expbuf"></a>`v4l2_m2m_expbuf()`

```c
int v4l2_m2m_expbuf(struct file *file, struct v4l2_m2m_ctx *m2m_ctx, struct v4l2_exportbuffer *eb)
```

export a source or destination buffer, depending on the type

**Parameters**

- `struct file *file`: pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file)
- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct v4l2_exportbuffer *eb`: pointer to struct `v4l2_exportbuffer`

#### <a id="c-v4l2_m2m_streamon"></a>`v4l2_m2m_streamon()`

```c
int v4l2_m2m_streamon(struct file *file, struct v4l2_m2m_ctx *m2m_ctx, enum v4l2_buf_type type)
```

turn on streaming for a video queue

**Parameters**

- `struct file *file`: pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file)
- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `enum v4l2_buf_type type`: type of the V4L2 buffer, as defined by enum `v4l2_buf_type`

#### <a id="c-v4l2_m2m_streamoff"></a>`v4l2_m2m_streamoff()`

```c
int v4l2_m2m_streamoff(struct file *file, struct v4l2_m2m_ctx *m2m_ctx, enum v4l2_buf_type type)
```

turn off streaming for a video queue

**Parameters**

- `struct file *file`: pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file)
- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `enum v4l2_buf_type type`: type of the V4L2 buffer, as defined by enum `v4l2_buf_type`

#### <a id="c-v4l2_m2m_update_start_streaming_state"></a>`v4l2_m2m_update_start_streaming_state()`

```c
void v4l2_m2m_update_start_streaming_state(struct v4l2_m2m_ctx *m2m_ctx, struct vb2_queue *q)
```

update the encoding/decoding session state when a start of streaming of a video queue is requested

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct vb2_queue *q`: queue

#### <a id="c-v4l2_m2m_update_stop_streaming_state"></a>`v4l2_m2m_update_stop_streaming_state()`

```c
void v4l2_m2m_update_stop_streaming_state(struct v4l2_m2m_ctx *m2m_ctx, struct vb2_queue *q)
```

update the encoding/decoding session state when a stop of streaming of a video queue is requested

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct vb2_queue *q`: queue

#### <a id="c-v4l2_m2m_encoder_cmd"></a>`v4l2_m2m_encoder_cmd()`

```c
int v4l2_m2m_encoder_cmd(struct file *file, struct v4l2_m2m_ctx *m2m_ctx, struct v4l2_encoder_cmd *ec)
```

execute an encoder command

**Parameters**

- `struct file *file`: pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file)
- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct v4l2_encoder_cmd *ec`: pointer to the encoder command

#### <a id="c-v4l2_m2m_decoder_cmd"></a>`v4l2_m2m_decoder_cmd()`

```c
int v4l2_m2m_decoder_cmd(struct file *file, struct v4l2_m2m_ctx *m2m_ctx, struct v4l2_decoder_cmd *dc)
```

execute a decoder command

**Parameters**

- `struct file *file`: pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file)
- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct v4l2_decoder_cmd *dc`: pointer to the decoder command

#### <a id="c-v4l2_m2m_poll"></a>`v4l2_m2m_poll()`

```c
__poll_t v4l2_m2m_poll(struct file *file, struct v4l2_m2m_ctx *m2m_ctx, struct poll_table_struct *wait)
```

poll replacement, for destination buffers only

**Parameters**

- `struct file *file`: pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file)
- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct poll_table_struct *wait`: pointer to struct `poll_table_struct`

**Description**

Call from the driver's `poll()` function. Will poll both queues. If a buffer
is available to dequeue (with dqbuf) from the source queue, this will
indicate that a non-blocking write can be performed, while read will be
returned in case of the destination queue.

#### <a id="c-v4l2_m2m_mmap"></a>`v4l2_m2m_mmap()`

```c
int v4l2_m2m_mmap(struct file *file, struct v4l2_m2m_ctx *m2m_ctx, struct vm_area_struct *vma)
```

source and destination queues-aware mmap multiplexer

**Parameters**

- `struct file *file`: pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file)
- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct vm_area_struct *vma`: pointer to struct `vm_area_struct`

**Description**

Call from driver's `mmap()` function. Will handle `mmap()` for both queues
seamlessly for the video buffer, which will receive normal per-queue offsets
and proper vb2 queue pointers. The differentiation is made outside
vb2 by adding a predefined offset to buffers from one of the queues
and subtracting it before passing it back to vb2. Only drivers (and
thus applications) receive modified offsets.

#### <a id="c-v4l2_m2m_init"></a>`v4l2_m2m_init()`

```c
struct v4l2_m2m_dev * v4l2_m2m_init(const struct v4l2_m2m_ops *m2m_ops)
```

initialize per-driver m2m data

**Parameters**

- `const struct v4l2_m2m_ops *m2m_ops`: pointer to struct v4l2_m2m_ops

**Description**

Usually called from driver's `probe()` function.

**Return**

returns an opaque pointer to the internal data to handle M2M context

#### <a id="c-v4l2_m2m_release"></a>`v4l2_m2m_release()`

```c
void v4l2_m2m_release(struct v4l2_m2m_dev *m2m_dev)
```

cleans up and frees a m2m_dev structure

**Parameters**

- `struct v4l2_m2m_dev *m2m_dev`: opaque pointer to the internal data to handle M2M context

**Description**

Usually called from driver's `remove()` function.

#### <a id="c-v4l2_m2m_get"></a>`v4l2_m2m_get()`

```c
void v4l2_m2m_get(struct v4l2_m2m_dev *m2m_dev)
```

take a reference to the m2m_dev structure

**Parameters**

- `struct v4l2_m2m_dev *m2m_dev`: opaque pointer to the internal data to handle M2M context

**Description**

This is used to share the M2M device across multiple devices. This
can be used to avoid scheduling two hardware nodes concurrently.

#### <a id="c-v4l2_m2m_put"></a>`v4l2_m2m_put()`

```c
void v4l2_m2m_put(struct v4l2_m2m_dev *m2m_dev)
```

remove a reference to the m2m_dev structure

**Parameters**

- `struct v4l2_m2m_dev *m2m_dev`: opaque pointer to the internal data to handle M2M context

**Description**

Once the M2M device has no more references, [`v4l2_m2m_release()`](#c-v4l2_m2m_release) will be
called automatically. Users of this method should never call
[`v4l2_m2m_release()`](#c-v4l2_m2m_release) directly. See [`v4l2_m2m_get()`](#c-v4l2_m2m_get) for more details.

#### <a id="c-v4l2_m2m_ctx_init"></a>`v4l2_m2m_ctx_init()`

```c
struct v4l2_m2m_ctx * v4l2_m2m_ctx_init(struct v4l2_m2m_dev *m2m_dev, void *drv_priv, int (*queue_init)(void *priv, struct vb2_queue *src_vq, struct vb2_queue *dst_vq))
```

allocate and initialize a m2m context

**Parameters**

- `struct v4l2_m2m_dev *m2m_dev`: opaque pointer to the internal data to handle M2M context
- `void *drv_priv`: driver's instance private data
- `int (*queue_init)(void *priv, struct vb2_queue *src_vq, struct vb2_queue *dst_vq)`: a callback for queue type-specific initialization function
  to be used for initializing vb2_queues

**Description**

Usually called from driver's `open()` function.

#### <a id="c-v4l2_m2m_ctx_release"></a>`v4l2_m2m_ctx_release()`

```c
void v4l2_m2m_ctx_release(struct v4l2_m2m_ctx *m2m_ctx)
```

release m2m context

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

**Description**

Usually called from driver's `release()` function.

#### <a id="c-v4l2_m2m_buf_queue"></a>`v4l2_m2m_buf_queue()`

```c
void v4l2_m2m_buf_queue(struct v4l2_m2m_ctx *m2m_ctx, struct vb2_v4l2_buffer *vbuf)
```

add a buffer to the proper ready buffers list.

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct vb2_v4l2_buffer *vbuf`: pointer to struct [`vb2_v4l2_buffer`](/kernel/hardware/driver-api/media/v4l2-videobuf2.md#c-struct-vb2_v4l2_buffer)

**Description**

Call from vb2_queue_ops->ops->buf_queue, vb2_queue_ops callback.

#### <a id="c-v4l2_m2m_num_src_bufs_ready"></a>`v4l2_m2m_num_src_bufs_ready()`

```c
unsigned int v4l2_m2m_num_src_bufs_ready(struct v4l2_m2m_ctx *m2m_ctx)
```

return the number of source buffers ready for use

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

#### <a id="c-v4l2_m2m_num_dst_bufs_ready"></a>`v4l2_m2m_num_dst_bufs_ready()`

```c
unsigned int v4l2_m2m_num_dst_bufs_ready(struct v4l2_m2m_ctx *m2m_ctx)
```

return the number of destination buffers ready for use

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

#### <a id="c-v4l2_m2m_next_buf"></a>`v4l2_m2m_next_buf()`

```c
struct vb2_v4l2_buffer * v4l2_m2m_next_buf(struct v4l2_m2m_queue_ctx *q_ctx)
```

return next buffer from the list of ready buffers

**Parameters**

- `struct v4l2_m2m_queue_ctx *q_ctx`: pointer to struct **v4l2_m2m_queue_ctx**

#### <a id="c-v4l2_m2m_next_src_buf"></a>`v4l2_m2m_next_src_buf()`

```c
struct vb2_v4l2_buffer * v4l2_m2m_next_src_buf(struct v4l2_m2m_ctx *m2m_ctx)
```

return next source buffer from the list of ready buffers

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

#### <a id="c-v4l2_m2m_next_dst_buf"></a>`v4l2_m2m_next_dst_buf()`

```c
struct vb2_v4l2_buffer * v4l2_m2m_next_dst_buf(struct v4l2_m2m_ctx *m2m_ctx)
```

return next destination buffer from the list of ready buffers

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

#### <a id="c-v4l2_m2m_last_buf"></a>`v4l2_m2m_last_buf()`

```c
struct vb2_v4l2_buffer * v4l2_m2m_last_buf(struct v4l2_m2m_queue_ctx *q_ctx)
```

return last buffer from the list of ready buffers

**Parameters**

- `struct v4l2_m2m_queue_ctx *q_ctx`: pointer to struct **v4l2_m2m_queue_ctx**

#### <a id="c-v4l2_m2m_last_src_buf"></a>`v4l2_m2m_last_src_buf()`

```c
struct vb2_v4l2_buffer * v4l2_m2m_last_src_buf(struct v4l2_m2m_ctx *m2m_ctx)
```

return last source buffer from the list of ready buffers

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

#### <a id="c-v4l2_m2m_last_dst_buf"></a>`v4l2_m2m_last_dst_buf()`

```c
struct vb2_v4l2_buffer * v4l2_m2m_last_dst_buf(struct v4l2_m2m_ctx *m2m_ctx)
```

return last destination buffer from the list of ready buffers

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

#### <a id="c-v4l2_m2m_for_each_dst_buf"></a>`v4l2_m2m_for_each_dst_buf()`

```c
v4l2_m2m_for_each_dst_buf(m2m_ctx, b)
```

iterate over a list of destination ready buffers

**Parameters**

- `m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `b`: current buffer of type struct v4l2_m2m_buffer

#### <a id="c-v4l2_m2m_for_each_src_buf"></a>`v4l2_m2m_for_each_src_buf()`

```c
v4l2_m2m_for_each_src_buf(m2m_ctx, b)
```

iterate over a list of source ready buffers

**Parameters**

- `m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `b`: current buffer of type struct v4l2_m2m_buffer

#### <a id="c-v4l2_m2m_for_each_dst_buf_safe"></a>`v4l2_m2m_for_each_dst_buf_safe()`

```c
v4l2_m2m_for_each_dst_buf_safe(m2m_ctx, b, n)
```

iterate over a list of destination ready buffers safely

**Parameters**

- `m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `b`: current buffer of type struct v4l2_m2m_buffer
- `n`: used as temporary storage

#### <a id="c-v4l2_m2m_for_each_src_buf_safe"></a>`v4l2_m2m_for_each_src_buf_safe()`

```c
v4l2_m2m_for_each_src_buf_safe(m2m_ctx, b, n)
```

iterate over a list of source ready buffers safely

**Parameters**

- `m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `b`: current buffer of type struct v4l2_m2m_buffer
- `n`: used as temporary storage

#### <a id="c-v4l2_m2m_get_src_vq"></a>`v4l2_m2m_get_src_vq()`

```c
struct vb2_queue * v4l2_m2m_get_src_vq(struct v4l2_m2m_ctx *m2m_ctx)
```

return vb2_queue for source buffers

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

#### <a id="c-v4l2_m2m_get_dst_vq"></a>`v4l2_m2m_get_dst_vq()`

```c
struct vb2_queue * v4l2_m2m_get_dst_vq(struct v4l2_m2m_ctx *m2m_ctx)
```

return vb2_queue for destination buffers

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

#### <a id="c-v4l2_m2m_buf_remove"></a>`v4l2_m2m_buf_remove()`

```c
struct vb2_v4l2_buffer * v4l2_m2m_buf_remove(struct v4l2_m2m_queue_ctx *q_ctx)
```

take off a buffer from the list of ready buffers and return it

**Parameters**

- `struct v4l2_m2m_queue_ctx *q_ctx`: pointer to struct **v4l2_m2m_queue_ctx**

#### <a id="c-v4l2_m2m_src_buf_remove"></a>`v4l2_m2m_src_buf_remove()`

```c
struct vb2_v4l2_buffer * v4l2_m2m_src_buf_remove(struct v4l2_m2m_ctx *m2m_ctx)
```

take off a source buffer from the list of ready buffers and return it

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

#### <a id="c-v4l2_m2m_dst_buf_remove"></a>`v4l2_m2m_dst_buf_remove()`

```c
struct vb2_v4l2_buffer * v4l2_m2m_dst_buf_remove(struct v4l2_m2m_ctx *m2m_ctx)
```

take off a destination buffer from the list of ready buffers and return it

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

#### <a id="c-v4l2_m2m_buf_remove_by_buf"></a>`v4l2_m2m_buf_remove_by_buf()`

```c
void v4l2_m2m_buf_remove_by_buf(struct v4l2_m2m_queue_ctx *q_ctx, struct vb2_v4l2_buffer *vbuf)
```

take off exact buffer from the list of ready buffers

**Parameters**

- `struct v4l2_m2m_queue_ctx *q_ctx`: pointer to struct **v4l2_m2m_queue_ctx**
- `struct vb2_v4l2_buffer *vbuf`: the buffer to be removed

#### <a id="c-v4l2_m2m_src_buf_remove_by_buf"></a>`v4l2_m2m_src_buf_remove_by_buf()`

```c
void v4l2_m2m_src_buf_remove_by_buf(struct v4l2_m2m_ctx *m2m_ctx, struct vb2_v4l2_buffer *vbuf)
```

take off exact source buffer from the list of ready buffers

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct vb2_v4l2_buffer *vbuf`: the buffer to be removed

#### <a id="c-v4l2_m2m_dst_buf_remove_by_buf"></a>`v4l2_m2m_dst_buf_remove_by_buf()`

```c
void v4l2_m2m_dst_buf_remove_by_buf(struct v4l2_m2m_ctx *m2m_ctx, struct vb2_v4l2_buffer *vbuf)
```

take off exact destination buffer from the list of ready buffers

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct vb2_v4l2_buffer *vbuf`: the buffer to be removed

#### <a id="c-v4l2_m2m_buf_copy_metadata"></a>`v4l2_m2m_buf_copy_metadata()`

```c
void v4l2_m2m_buf_copy_metadata(const struct vb2_v4l2_buffer *out_vb, struct vb2_v4l2_buffer *cap_vb)
```

copy buffer metadata from the output buffer to the capture buffer

**Parameters**

- `const struct vb2_v4l2_buffer *out_vb`: the output buffer that is the source of the metadata.
- `struct vb2_v4l2_buffer *cap_vb`: the capture buffer that will receive the metadata.

**Description**

This helper function copies the timestamp, timecode (if the TIMECODE
buffer flag was set), field, and the TIMECODE and TSTAMP_SRC_MASK flags from
**out_vb** to **cap_vb**.

---

# V4L2 rect helper functions

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for V4L2 rect helper functions.

<a id="rst-v4l2-rect-helper-functions"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-v4l2_rect_set_size_to"></a>`v4l2_rect_set_size_to()`

```c
void v4l2_rect_set_size_to(struct v4l2_rect *r, const struct v4l2_rect *size)
```

copy the width/height values.

**Parameters**

- `struct v4l2_rect *r`: rect whose width and height fields will be set
- `const struct v4l2_rect *size`: rect containing the width and height fields you need.

#### <a id="c-v4l2_rect_set_min_size"></a>`v4l2_rect_set_min_size()`

```c
void v4l2_rect_set_min_size(struct v4l2_rect *r, const struct v4l2_rect *min_size)
```

width and height of r should be >= min_size.

**Parameters**

- `struct v4l2_rect *r`: rect whose width and height will be modified
- `const struct v4l2_rect *min_size`: rect containing the minimal width and height

#### <a id="c-v4l2_rect_set_max_size"></a>`v4l2_rect_set_max_size()`

```c
void v4l2_rect_set_max_size(struct v4l2_rect *r, const struct v4l2_rect *max_size)
```

width and height of r should be \<= max_size

**Parameters**

- `struct v4l2_rect *r`: rect whose width and height will be modified
- `const struct v4l2_rect *max_size`: rect containing the maximum width and height

#### <a id="c-v4l2_rect_map_inside"></a>`v4l2_rect_map_inside()`

```c
void v4l2_rect_map_inside(struct v4l2_rect *r, const struct v4l2_rect *boundary)
```

r should be inside boundary.

**Parameters**

- `struct v4l2_rect *r`: rect that will be modified
- `const struct v4l2_rect *boundary`: rect containing the boundary for **r**

#### <a id="c-v4l2_rect_same_size"></a>`v4l2_rect_same_size()`

```c
bool v4l2_rect_same_size(const struct v4l2_rect *r1, const struct v4l2_rect *r2)
```

return true if r1 has the same size as r2

**Parameters**

- `const struct v4l2_rect *r1`: rectangle.
- `const struct v4l2_rect *r2`: rectangle.

**Description**

Return true if both rectangles have the same size.

#### <a id="c-v4l2_rect_same_position"></a>`v4l2_rect_same_position()`

```c
bool v4l2_rect_same_position(const struct v4l2_rect *r1, const struct v4l2_rect *r2)
```

return true if r1 has the same position as r2

**Parameters**

- `const struct v4l2_rect *r1`: rectangle.
- `const struct v4l2_rect *r2`: rectangle.

**Description**

Return true if both rectangles have the same position

#### <a id="c-v4l2_rect_equal"></a>`v4l2_rect_equal()`

```c
bool v4l2_rect_equal(const struct v4l2_rect *r1, const struct v4l2_rect *r2)
```

return true if r1 equals r2

**Parameters**

- `const struct v4l2_rect *r1`: rectangle.
- `const struct v4l2_rect *r2`: rectangle.

**Description**

Return true if both rectangles have the same size and position.

#### <a id="c-v4l2_rect_intersect"></a>`v4l2_rect_intersect()`

```c
void v4l2_rect_intersect(struct v4l2_rect *r, const struct v4l2_rect *r1, const struct v4l2_rect *r2)
```

calculate the intersection of two rects.

**Parameters**

- `struct v4l2_rect *r`: intersection of **r1** and **r2**.
- `const struct v4l2_rect *r1`: rectangle.
- `const struct v4l2_rect *r2`: rectangle.

#### <a id="c-v4l2_rect_scale"></a>`v4l2_rect_scale()`

```c
void v4l2_rect_scale(struct v4l2_rect *r, const struct v4l2_rect *from, const struct v4l2_rect *to)
```

scale rect r by to/from

**Parameters**

- `struct v4l2_rect *r`: rect to be scaled.
- `const struct v4l2_rect *from`: from rectangle.
- `const struct v4l2_rect *to`: to rectangle.

**Description**

This scales rectangle **r** horizontally by **to->width** / **from->width** and
vertically by **to->height** / **from->height**.

Typically **r** is a rectangle inside **from** and you want the rectangle as
it would appear after scaling **from** to **to**. So the resulting **r** will
be the scaled rectangle inside **to**.

#### <a id="c-v4l2_rect_overlap"></a>`v4l2_rect_overlap()`

```c
bool v4l2_rect_overlap(const struct v4l2_rect *r1, const struct v4l2_rect *r2)
```

do r1 and r2 overlap?

**Parameters**

- `const struct v4l2_rect *r1`: rectangle.
- `const struct v4l2_rect *r2`: rectangle.

**Description**

Returns true if **r1** and **r2** overlap.

#### <a id="c-v4l2_rect_enclosed"></a>`v4l2_rect_enclosed()`

```c
bool v4l2_rect_enclosed(struct v4l2_rect *r1, struct v4l2_rect *r2)
```

is r1 enclosed in r2?

**Parameters**

- `struct v4l2_rect *r1`: rectangle.
- `struct v4l2_rect *r2`: rectangle.

**Description**

Returns true if **r1** is enclosed in **r2**.

---

# V4L2 sub-devices

_Peios Kernel / Hardware and drivers / Driver development / Media 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.

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-v4l2-sub-devices"></a>

## 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 `v4l2_subdev` struct (v4l2-subdev.h) was created.

Each sub-device driver must have a `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 `v4l2_subdev` using `v4l2_set_subdevdata()`. That makes it easy to go from a `v4l2_subdev` to the actual low-level bus-specific device data.

You also need a way to go from the low-level struct to `v4l2_subdev`. For the common i2c_client struct the i2c_set_clientdata() call is used to store a `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 `v4l2_subdev` structure provides host private data for that purpose that can be accessed with `v4l2_get_subdev_hostdata()` and `v4l2_set_subdev_hostdata()`.

From the bridge driver perspective, you load the sub-device module and somehow obtain the `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 `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:



```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 `v4l2_subdev` struct using:

> `v4l2_subdev_init <v4l2_subdev_init>()` (`sd <v4l2_subdev>`, &amp;`ops <v4l2_subdev_ops>`).

Afterwards you need to initialize `sd <v4l2_subdev>`-&gt;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 `media_entity` struct embedded in the `v4l2_subdev` struct (entity field) by calling `media_entity_pads_init()`, if the entity has pads:



```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:



```c
media_entity_cleanup(&sd->entity);
```

If a sub-device driver implements sink pads, the subdev driver may set the link_validate field in `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 `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.

<a id="rst-subdev-registration"></a>

### 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.

<a id="rst-registering-synchronous-sub-devices"></a>

#### Registering synchronous sub-devices

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

> `v4l2_device_register_subdev <v4l2_device_register_subdev>()` (`v4l2_dev <v4l2_device>`, `sd <v4l2_subdev>`).

This can fail if the subdev module disappeared before it could be registered. After this function was called successfully the subdev-&gt;dev field points to the `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:

> `v4l2_device_unregister_subdev <v4l2_device_unregister_subdev>()` (`sd <v4l2_subdev>`).

Afterwards the subdev module can be unloaded and `sd <v4l2_subdev>`-&gt;dev == `NULL`.

<a id="rst-registering-asynchronous-sub-devices"></a>
<a id="rst-media-registering-async-subdevs"></a>

#### 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 `v4l2_async_register_subdev()` function. Unregistration is performed using the `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 `v4l2_async_register_subdev()`, including enabling runtime PM. This is because the sub-device becomes accessible as soon as it gets registered.

<a id="rst-asynchronous-sub-device-notifiers"></a>

#### Asynchronous sub-device notifiers

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

Before registering the notifier, bridge drivers must do two things: first, the notifier must be initialized using the `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. `v4l2_async_nf_add_fwnode()`, `v4l2_async_nf_add_fwnode_remote()` and `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.

<a id="rst-asynchronous-sub-device-notifier-for-sub-devices"></a>

#### 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 `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.

<a id="rst-asynchronous-sub-device-registration-helper-for-camera-sensor-drivers"></a>

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

`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 `v4l2_async_unregister_subdev()`.

<a id="rst-asynchronous-sub-device-notifier-example"></a>

#### Asynchronous sub-device notifier example

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



```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);
```

<a id="rst-asynchronous-sub-device-notifier-callbacks"></a>

#### 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 `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 `v4l2_async_connection`.

<a id="rst-calling-subdev-operations"></a>

### Calling subdev operations

The advantage of using `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:



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

but it is better and easier to use this macro:



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

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

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



```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:



```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 `sd <v4l2_subdev>`-&gt;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.

<a id="rst-v4l2-sub-device-userspace-api"></a>

## V4L2 sub-device userspace API

Bridge drivers traditionally expose one or multiple video nodes to userspace, and control subdevices through the `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 [the media controller API](</kernel/userspace/userspace-api/media-mediactl/media-controller.md#rst-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 `v4l2_device` driver can create device nodes for all registered sub-devices marked with `V4L2_SUBDEV_FL_HAS_DEVNODE` by calling `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` `v4l2_subdev`.flags before registering the sub-device. After registration events can be queued as usual on the `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.

<a id="rst-read-only-sub-device-userspace-api"></a>

## Read-only sub-device userspace API

Bridge drivers that control their connected subdevices through direct calls to the kernel API realized by `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 `v4l2_device` driver should call `v4l2_device_register_ro_subdev_nodes()`.

Access to the following ioctls for userspace applications is restricted on sub-device device nodes registered with `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 [V4L2_SUBDEV_FORMAT_TRY](</kernel/userspace/userspace-api/media-v4l/vidioc-subdev-g-fmt.md#rst-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`.

<a id="rst-i2c-sub-device-drivers"></a>

## 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 `v4l2_subdev` support to an I2C driver is to embed the `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 `v4l2_subdev` directly.

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



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

Initialize the `v4l2_subdev` struct as follows:



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

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

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



```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 `v4l2_subdev` struct to the `i2c_client` struct:



```c
struct i2c_client *client = v4l2_get_subdevdata(sd);
```

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



```c
struct v4l2_subdev *sd = i2c_get_clientdata(client);
```

Make sure to call `v4l2_device_unregister_subdev()`(`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 `v4l2_device_unregister_subdev()`(`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:



```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 `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 `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 `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:

`v4l2_i2c_new_subdev_board()` uses an `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 `v4l2_i2c_new_subdev()` function will call `v4l2_i2c_new_subdev_board()`, internally filling a `i2c_board_info` structure using the `client_type` and the `addr` to fill it.

<a id="rst-centrally-managed-subdev-active-state"></a>

## 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 `v4l2_subdev_state`. One instance of state, which contains the active device configuration, is stored in the sub-device itself as part of the `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 [ACTIVE and TRY formats](</kernel/userspace/userspace-api/media-v4l/vidioc-subdev-g-fmt.md#rst-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 `v4l2_subdev_lock_state()` and `v4l2_subdev_unlock_state()`. The caller can do so by calling the subdev operation through the `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 `v4l2_subdev_lock_and_get_active_state()`. The sub-device active state must equally be released by calling `v4l2_subdev_unlock_state()`.

Drivers must never manually access the state stored in the `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 `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 `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():



```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.

<a id="rst-streams-multiplexed-media-pads-and-internal-routing"></a>

## 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.

<a id="rst-v4l2-sub-device-functions-and-data-structures"></a>

## V4L2 sub-device functions and data structures


#### <a id="c-struct-v4l2_decode_vbi_line"></a>`struct v4l2_decode_vbi_line`

used to decode_vbi_line

**Definition**

```c
struct v4l2_decode_vbi_line {
    u32 is_second_field;
    u8 *p;
    u32 line;
    u32 type;
};
```

**Members**

- `is_second_field`: Set to 0 for the first (odd) field;
  set to 1 for the second (even) field.
- `p`: Pointer to the sliced VBI data from the decoder. On exit, points to
  the start of the payload.
- `line`: Line number of the sliced VBI data (1-23)
- `type`: VBI service type (V4L2_SLICED_*). 0 if no service found

#### <a id="c-enum-v4l2_subdev_io_pin_bits"></a>`enum v4l2_subdev_io_pin_bits`

Subdevice external IO pin configuration bits

**Constants**

- `V4L2_SUBDEV_IO_PIN_DISABLE`: disables a pin config. ENABLE assumed.
- `V4L2_SUBDEV_IO_PIN_OUTPUT`: set it if pin is an output.
- `V4L2_SUBDEV_IO_PIN_INPUT`: set it if pin is an input.
- `V4L2_SUBDEV_IO_PIN_SET_VALUE`: to set the output value via
  [`struct v4l2_subdev_io_pin_config`](#c-struct-v4l2_subdev_io_pin_config)->value.
- `V4L2_SUBDEV_IO_PIN_ACTIVE_LOW`: pin active is bit 0.
  Otherwise, ACTIVE HIGH is assumed.

#### <a id="c-struct-v4l2_subdev_io_pin_config"></a>`struct v4l2_subdev_io_pin_config`

Subdevice external IO pin configuration

**Definition**

```c
struct v4l2_subdev_io_pin_config {
    u32 flags;
    u8 pin;
    u8 function;
    u8 value;
    u8 strength;
};
```

**Members**

- `flags`: bitmask with flags for this pin's config, whose bits are defined by
  [`enum v4l2_subdev_io_pin_bits`](#c-enum-v4l2_subdev_io_pin_bits).
- `pin`: Chip external IO pin to configure
- `function`: Internal signal pad/function to route to IO pin
- `value`: Initial value for pin - e.g. GPIO output value
- `strength`: Pin drive strength

#### <a id="c-struct-v4l2_subdev_core_ops"></a>`struct v4l2_subdev_core_ops`

Define core ops callbacks for subdevs

**Definition**

```c
struct v4l2_subdev_core_ops {
        int (*log_status)(struct v4l2_subdev *sd);
        int (*s_io_pin_config)(struct v4l2_subdev *sd, size_t n, struct v4l2_subdev_io_pin_config *pincfg);
        int (*init)(struct v4l2_subdev *sd, u32 val);
        int (*load_fw)(struct v4l2_subdev *sd);
        int (*reset)(struct v4l2_subdev *sd, u32 val);
        int (*s_gpio)(struct v4l2_subdev *sd, u32 val);
        long (*command)(struct v4l2_subdev *sd, unsigned int cmd, void *arg);
        long (*ioctl)(struct v4l2_subdev *sd, unsigned int cmd, void *arg);
    #ifdef CONFIG_COMPAT;
        long (*compat_ioctl32)(struct v4l2_subdev *sd, unsigned int cmd, unsigned long arg);
    #endif;
    #ifdef CONFIG_VIDEO_ADV_DEBUG;
        int (*g_register)(struct v4l2_subdev *sd, struct v4l2_dbg_register *reg);
        int (*s_register)(struct v4l2_subdev *sd, const struct v4l2_dbg_register *reg);
    #endif;
        int (*s_power)(struct v4l2_subdev *sd, int on);
        int (*interrupt_service_routine)(struct v4l2_subdev *sd, u32 status, bool *handled);
        int (*subscribe_event)(struct v4l2_subdev *sd, struct v4l2_fh *fh, struct v4l2_event_subscription *sub);
        int (*unsubscribe_event)(struct v4l2_subdev *sd, struct v4l2_fh *fh, struct v4l2_event_subscription *sub);
};
```

**Members**

- `log_status`: callback for `VIDIOC_LOG_STATUS()` ioctl handler code.
- `s_io_pin_config`: configure one or more chip I/O pins for chips that
  multiplex different internal signal pads out to IO pins.  This function
  takes a pointer to an array of 'n' pin configuration entries, one for
  each pin being configured.  This function could be called at times
  other than just subdevice initialization.
- `init`: initialize the sensor registers to some sort of reasonable default
  values. Do not use for new drivers and should be removed in existing
  drivers.
- `load_fw`: load firmware.
- `reset`: generic reset command. The argument selects which subsystems to
  reset. Passing 0 will always reset the whole chip. Do not use for new
  drivers without discussing this first on the linux-media mailinglist.
  There should be no reason normally to reset a device.
- `s_gpio`: set GPIO pins. Very simple right now, might need to be extended with
  a direction argument if needed.
- `command`: called by in-kernel drivers in order to call functions internal
  to subdev drivers driver that have a separate callback.
- `ioctl`: called at the end of `ioctl()` syscall handler at the V4L2 core.
  used to provide support for private ioctls used on the driver.
- `compat_ioctl32`: called when a 32 bits application uses a 64 bits Kernel,
  in order to fix data passed from/to userspace.
- `g_register`: callback for `VIDIOC_DBG_G_REGISTER()` ioctl handler code.
- `s_register`: callback for `VIDIOC_DBG_S_REGISTER()` ioctl handler code.
- `s_power`: puts subdevice in power saving mode (on == 0) or normal operation
  mode (on == 1). DEPRECATED. See
  Documentation/driver-api/media/camera-sensor.rst . pre_streamon and
  post_streamoff callbacks can be used for e.g. setting the bus to LP-11
  mode before s_stream is called.
- `interrupt_service_routine`: Called by the bridge chip's interrupt service
  handler, when an interrupt status has be raised due to this subdev,
  so that this subdev can handle the details.  It may schedule work to be
  performed later.  It must not sleep. **Called from an IRQ context**.
- `subscribe_event`: used by the drivers to request the control framework that
  for it to be warned when the value of a control changes.
- `unsubscribe_event`: remove event subscription from the control framework.

#### <a id="c-struct-v4l2_subdev_tuner_ops"></a>`struct v4l2_subdev_tuner_ops`

Callbacks used when v4l device was opened in radio mode.

**Definition**

```c
struct v4l2_subdev_tuner_ops {
    int (*standby)(struct v4l2_subdev *sd);
    int (*s_radio)(struct v4l2_subdev *sd);
    int (*s_frequency)(struct v4l2_subdev *sd, const struct v4l2_frequency *freq);
    int (*g_frequency)(struct v4l2_subdev *sd, struct v4l2_frequency *freq);
    int (*enum_freq_bands)(struct v4l2_subdev *sd, struct v4l2_frequency_band *band);
    int (*g_tuner)(struct v4l2_subdev *sd, struct v4l2_tuner *vt);
    int (*s_tuner)(struct v4l2_subdev *sd, const struct v4l2_tuner *vt);
    int (*g_modulator)(struct v4l2_subdev *sd, struct v4l2_modulator *vm);
    int (*s_modulator)(struct v4l2_subdev *sd, const struct v4l2_modulator *vm);
    int (*s_type_addr)(struct v4l2_subdev *sd, struct tuner_setup *type);
    int (*s_config)(struct v4l2_subdev *sd, const struct v4l2_priv_tun_config *config);
};
```

**Members**

- `standby`: puts the tuner in standby mode. It will be woken up
  automatically the next time it is used.
- `s_radio`: callback that switches the tuner to radio mode.
  drivers should explicitly call it when a tuner ops should
  operate on radio mode, before being able to handle it.
  Used on devices that have both AM/FM radio receiver and TV.
- `s_frequency`: callback for `VIDIOC_S_FREQUENCY()` ioctl handler code.
- `g_frequency`: callback for `VIDIOC_G_FREQUENCY()` ioctl handler code.
  freq->type must be filled in. Normally done by [`video_ioctl2()`](/kernel/hardware/driver-api/media/v4l2-common.md#c-video_ioctl2)
  or the bridge driver.
- `enum_freq_bands`: callback for `VIDIOC_ENUM_FREQ_BANDS()` ioctl handler code.
- `g_tuner`: callback for `VIDIOC_G_TUNER()` ioctl handler code.
- `s_tuner`: callback for `VIDIOC_S_TUNER()` ioctl handler code. **vt->type** must be
  filled in. Normally done by video_ioctl2 or the
  bridge driver.
- `g_modulator`: callback for `VIDIOC_G_MODULATOR()` ioctl handler code.
- `s_modulator`: callback for `VIDIOC_S_MODULATOR()` ioctl handler code.
- `s_type_addr`: sets tuner type and its I2C addr.
- `s_config`: sets tda9887 specific stuff, like port1, port2 and qss

**Description**

> [!NOTE]
> On devices that have both AM/FM and TV, it is up to the driver
> to explicitly call s_radio when the tuner should be switched to
> radio mode, before handling other [`struct v4l2_subdev_tuner_ops`](#c-struct-v4l2_subdev_tuner_ops)
> that would require it. An example of such usage is:
>
> ```text
> static void s_frequency(void *priv, const struct v4l2_frequency *f)
> {
>       ...
>       if (f.type == V4L2_TUNER_RADIO)
>               v4l2_device_call_all(v4l2_dev, 0, tuner, s_radio);
>       ...
>       v4l2_device_call_all(v4l2_dev, 0, tuner, s_frequency);
> }
> ```

#### <a id="c-struct-v4l2_subdev_audio_ops"></a>`struct v4l2_subdev_audio_ops`

Callbacks used for audio-related settings

**Definition**

```c
struct v4l2_subdev_audio_ops {
    int (*s_clock_freq)(struct v4l2_subdev *sd, u32 freq);
    int (*s_i2s_clock_freq)(struct v4l2_subdev *sd, u32 freq);
    int (*s_routing)(struct v4l2_subdev *sd, u32 input, u32 output, u32 config);
    int (*s_stream)(struct v4l2_subdev *sd, int enable);
};
```

**Members**

- `s_clock_freq`: set the frequency (in Hz) of the audio clock output.
  Used to slave an audio processor to the video decoder, ensuring that
  audio and video remain synchronized. Usual values for the frequency
  are 48000, 44100 or 32000 Hz. If the frequency is not supported, then
  -EINVAL is returned.
- `s_i2s_clock_freq`: sets I2S speed in bps. This is used to provide a standard
  way to select I2S clock used by driving digital audio streams at some
  board designs. Usual values for the frequency are 1024000 and 2048000.
  If the frequency is not supported, then `-EINVAL` is returned.
- `s_routing`: used to define the input and/or output pins of an audio chip,
  and any additional configuration data.
  Never attempt to use user-level input IDs (e.g. Composite, S-Video,
  Tuner) at this level. An i2c device shouldn't know about whether an
  input pin is connected to a Composite connector, become on another
  board or platform it might be connected to something else entirely.
  The calling driver is responsible for mapping a user-level input to
  the right pins on the i2c device.
- `s_stream`: used to notify the audio code that stream will start or has
  stopped.

#### <a id="c-struct-v4l2_mbus_frame_desc_entry_csi2"></a>`struct v4l2_mbus_frame_desc_entry_csi2`

**Definition**

```c
struct v4l2_mbus_frame_desc_entry_csi2 {
    u8 vc;
    u8 dt;
};
```

**Members**

- `vc`: CSI-2 virtual channel
- `dt`: CSI-2 data type ID

#### <a id="c-enum-v4l2_mbus_frame_desc_flags"></a>`enum v4l2_mbus_frame_desc_flags`

media bus frame description flags

**Constants**

- `V4L2_MBUS_FRAME_DESC_FL_LEN_MAX`: Indicates that [`struct v4l2_mbus_frame_desc_entry`](#c-struct-v4l2_mbus_frame_desc_entry)->length field
  specifies maximum data length.
- `V4L2_MBUS_FRAME_DESC_FL_BLOB`: Indicates that the format does not have line offsets, i.e.
  the receiver should use 1D DMA.

#### <a id="c-struct-v4l2_mbus_frame_desc_entry"></a>`struct v4l2_mbus_frame_desc_entry`

media bus frame description structure

**Definition**

```c
struct v4l2_mbus_frame_desc_entry {
    enum v4l2_mbus_frame_desc_flags flags;
    u32 stream;
    u32 pixelcode;
    u32 length;
    union {
        struct v4l2_mbus_frame_desc_entry_csi2 csi2;
    } bus;
};
```

**Members**

- `flags`: bitmask flags, as defined by [`enum v4l2_mbus_frame_desc_flags`](#c-enum-v4l2_mbus_frame_desc_flags).
- `stream`: stream in routing configuration
- `pixelcode`: media bus pixel code, valid if **flags**
  `FRAME_DESC_FL_BLOB` is not set.
- `length`: number of octets per frame, valid if **flags**
  `V4L2_MBUS_FRAME_DESC_FL_LEN_MAX` is set.
- `bus`: Bus-specific frame descriptor parameters
- `bus.csi2`: CSI-2-specific bus configuration

#### <a id="c-enum-v4l2_mbus_frame_desc_type"></a>`enum v4l2_mbus_frame_desc_type`

media bus frame description type

**Constants**

- `V4L2_MBUS_FRAME_DESC_TYPE_UNDEFINED`: Undefined frame desc type. Drivers should not use this, it is
  for backwards compatibility.
- `V4L2_MBUS_FRAME_DESC_TYPE_PARALLEL`: Parallel media bus.
- `V4L2_MBUS_FRAME_DESC_TYPE_CSI2`: CSI-2 media bus. Frame desc parameters must be set in
  [`struct v4l2_mbus_frame_desc_entry`](#c-struct-v4l2_mbus_frame_desc_entry)->csi2.

#### <a id="c-struct-v4l2_mbus_frame_desc"></a>`struct v4l2_mbus_frame_desc`

media bus data frame description

**Definition**

```c
struct v4l2_mbus_frame_desc {
    enum v4l2_mbus_frame_desc_type type;
    struct v4l2_mbus_frame_desc_entry entry[V4L2_FRAME_DESC_ENTRY_MAX];
    unsigned short num_entries;
};
```

**Members**

- `type`: type of the bus (enum v4l2_mbus_frame_desc_type)
- `entry`: frame descriptors array
- `num_entries`: number of entries in **entry** array

#### <a id="c-enum-v4l2_subdev_pre_streamon_flags"></a>`enum v4l2_subdev_pre_streamon_flags`

Flags for pre_streamon subdev core op

**Constants**

- `V4L2_SUBDEV_PRE_STREAMON_FL_MANUAL_LP`: Set the transmitter to either LP-11
  or LP-111 mode before call to `s_stream()`.

#### <a id="c-struct-v4l2_subdev_video_ops"></a>`struct v4l2_subdev_video_ops`

Callbacks used when v4l device was opened in video mode.

**Definition**

```c
struct v4l2_subdev_video_ops {
    int (*s_routing)(struct v4l2_subdev *sd, u32 input, u32 output, u32 config);
    int (*s_crystal_freq)(struct v4l2_subdev *sd, u32 freq, u32 flags);
    int (*g_std)(struct v4l2_subdev *sd, v4l2_std_id *norm);
    int (*s_std)(struct v4l2_subdev *sd, v4l2_std_id norm);
    int (*s_std_output)(struct v4l2_subdev *sd, v4l2_std_id std);
    int (*g_std_output)(struct v4l2_subdev *sd, v4l2_std_id *std);
    int (*querystd)(struct v4l2_subdev *sd, v4l2_std_id *std);
    int (*g_tvnorms)(struct v4l2_subdev *sd, v4l2_std_id *std);
    int (*g_tvnorms_output)(struct v4l2_subdev *sd, v4l2_std_id *std);
    int (*g_input_status)(struct v4l2_subdev *sd, u32 *status);
    int (*s_stream)(struct v4l2_subdev *sd, int enable);
    int (*s_rx_buffer)(struct v4l2_subdev *sd, void *buf, unsigned int *size);
    int (*pre_streamon)(struct v4l2_subdev *sd, u32 flags);
    int (*post_streamoff)(struct v4l2_subdev *sd);
};
```

**Members**

- `s_routing`: see s_routing in audio_ops, except this version is for video
  devices.
- `s_crystal_freq`: sets the frequency of the crystal used to generate the
  clocks in Hz. An extra flags field allows device specific configuration
  regarding clock frequency dividers, etc. If not used, then set flags
  to 0. If the frequency is not supported, then -EINVAL is returned.
- `g_std`: callback for `VIDIOC_G_STD()` ioctl handler code.
- `s_std`: callback for `VIDIOC_S_STD()` ioctl handler code.
- `s_std_output`: set v4l2_std_id for video OUTPUT devices. This is ignored by
  video input devices.
- `g_std_output`: get current standard for video OUTPUT devices. This is ignored
  by video input devices.
- `querystd`: callback for `VIDIOC_QUERYSTD()` ioctl handler code.
- `g_tvnorms`: get `v4l2_std_id` with all standards supported by the video
  CAPTURE device. This is ignored by video output devices.
- `g_tvnorms_output`: get v4l2_std_id with all standards supported by the video
  OUTPUT device. This is ignored by video capture devices.
- `g_input_status`: get input status. Same as the status field in the
  [`struct v4l2_input`](/kernel/userspace/userspace-api/media-v4l/vidioc-enuminput.md#c-v4l2_input)
- `s_stream`: start (enabled == 1) or stop (enabled == 0) streaming on the
  sub-device. Failure on stop will remove any resources acquired in
  streaming start, while the error code is still returned by the driver.
  The caller shall track the subdev state, and shall not start or stop an
  already started or stopped subdev. Also see call_s_stream wrapper in
  v4l2-subdev.c.
- `s_rx_buffer`: set a host allocated memory buffer for the subdev. The subdev
  can adjust **size** to a lower value and must not write more data to the
  buffer starting at **data** than the original value of **size**.
- `pre_streamon`: May be called before streaming is actually started, to help
  initialising the bus. Current usage is to set a CSI-2 transmitter to
  LP-11 or LP-111 mode before streaming. See [`enum v4l2_subdev_pre_streamon_flags`](#c-enum-v4l2_subdev_pre_streamon_flags).
- `post_streamoff`: Called after streaming is stopped, but if and only if
  pre_streamon was called earlier.

**Description**

This callback is DEPRECATED. New drivers should instead implement
[`v4l2_subdev_pad_ops.enable_streams`](#c-struct-v4l2_subdev_pad_ops) and
[`v4l2_subdev_pad_ops.disable_streams`](#c-struct-v4l2_subdev_pad_ops) operations, and use
v4l2_subdev_s_stream_helper for the [`v4l2_subdev_video_ops.s_stream`](#c-struct-v4l2_subdev_video_ops)
operation to support legacy users.

Drivers should also not call the .`s_stream()` subdev operation directly,
but use the [`v4l2_subdev_enable_streams()`](#c-v4l2_subdev_enable_streams) and
[`v4l2_subdev_disable_streams()`](#c-v4l2_subdev_disable_streams) helpers.

pre_streamon shall return error if it cannot perform the operation as
indicated by the flags argument. In particular, -EACCES indicates lack
of support for the operation. The caller shall call post_streamoff for
each successful call of pre_streamon.

#### <a id="c-struct-v4l2_subdev_vbi_ops"></a>`struct v4l2_subdev_vbi_ops`

Callbacks used when v4l device was opened in video mode via the vbi device node.

**Definition**

```c
struct v4l2_subdev_vbi_ops {
    int (*decode_vbi_line)(struct v4l2_subdev *sd, struct v4l2_decode_vbi_line *vbi_line);
    int (*s_vbi_data)(struct v4l2_subdev *sd, const struct v4l2_sliced_vbi_data *vbi_data);
    int (*g_vbi_data)(struct v4l2_subdev *sd, struct v4l2_sliced_vbi_data *vbi_data);
    int (*g_sliced_vbi_cap)(struct v4l2_subdev *sd, struct v4l2_sliced_vbi_cap *cap);
    int (*s_raw_fmt)(struct v4l2_subdev *sd, struct v4l2_vbi_format *fmt);
    int (*g_sliced_fmt)(struct v4l2_subdev *sd, struct v4l2_sliced_vbi_format *fmt);
    int (*s_sliced_fmt)(struct v4l2_subdev *sd, struct v4l2_sliced_vbi_format *fmt);
};
```

**Members**

- `decode_vbi_line`: video decoders that support sliced VBI need to implement
  this ioctl. Field p of the [`struct v4l2_decode_vbi_line`](#c-struct-v4l2_decode_vbi_line) is set to the
  start of the VBI data that was generated by the decoder. The driver
  then parses the sliced VBI data and sets the other fields in the
  struct accordingly. The pointer p is updated to point to the start of
  the payload which can be copied verbatim into the data field of the
  [`struct v4l2_sliced_vbi_data`](/kernel/userspace/userspace-api/media-v4l/dev-sliced-vbi.md#c-v4l2_sliced_vbi_data). If no valid VBI data was found, then the
  type field is set to 0 on return.
- `s_vbi_data`: used to generate VBI signals on a video signal.
  [`struct v4l2_sliced_vbi_data`](/kernel/userspace/userspace-api/media-v4l/dev-sliced-vbi.md#c-v4l2_sliced_vbi_data) is filled with the data packets that
  should be output. Note that if you set the line field to 0, then that
  VBI signal is disabled. If no valid VBI data was found, then the type
  field is set to 0 on return.
- `g_vbi_data`: used to obtain the sliced VBI packet from a readback register.
  Not all video decoders support this. If no data is available because
  the readback register contains invalid or erroneous data `-EIO` is
  returned. Note that you must fill in the 'id' member and the 'field'
  member (to determine whether CC data from the first or second field
  should be obtained).
- `g_sliced_vbi_cap`: callback for `VIDIOC_G_SLICED_VBI_CAP()` ioctl handler
  code.
- `s_raw_fmt`: setup the video encoder/decoder for raw VBI.
- `g_sliced_fmt`: retrieve the current sliced VBI settings.
- `s_sliced_fmt`: setup the sliced VBI settings.

#### <a id="c-struct-v4l2_subdev_sensor_ops"></a>`struct v4l2_subdev_sensor_ops`

v4l2-subdev sensor operations

**Definition**

```c
struct v4l2_subdev_sensor_ops {
    int (*g_skip_top_lines)(struct v4l2_subdev *sd, u32 *lines);
    int (*g_skip_frames)(struct v4l2_subdev *sd, u32 *frames);
};
```

**Members**

- `g_skip_top_lines`: number of lines at the top of the image to be skipped.
  This is needed for some sensors, which always corrupt
  several top lines of the output image, or which send their
  metadata in them.
- `g_skip_frames`: number of frames to skip at stream start. This is needed for
  buggy sensors that generate faulty frames when they are
  turned on.

#### <a id="c-enum-v4l2_subdev_ir_mode"></a>`enum v4l2_subdev_ir_mode`

describes the type of IR supported

**Constants**

- `V4L2_SUBDEV_IR_MODE_PULSE_WIDTH`: IR uses struct ir_raw_event records

#### <a id="c-struct-v4l2_subdev_ir_parameters"></a>`struct v4l2_subdev_ir_parameters`

Parameters for IR TX or TX

**Definition**

```c
struct v4l2_subdev_ir_parameters {
    unsigned int bytes_per_data_element;
    enum v4l2_subdev_ir_mode mode;
    bool enable;
    bool interrupt_enable;
    bool shutdown;
    bool modulation;
    u32 max_pulse_width;
    unsigned int carrier_freq;
    unsigned int duty_cycle;
    bool invert_level;
    bool invert_carrier_sense;
    u32 noise_filter_min_width;
    unsigned int carrier_range_lower;
    unsigned int carrier_range_upper;
    u32 resolution;
};
```

**Members**

- `bytes_per_data_element`: bytes per data element of data in read or
  write call.
- `mode`: IR mode as defined by [`enum v4l2_subdev_ir_mode`](#c-enum-v4l2_subdev_ir_mode).
- `enable`: device is active if true
- `interrupt_enable`: IR interrupts are enabled if true
- `shutdown`: if true: set hardware to low/no power, false: normal mode
- `modulation`: if true, it uses carrier, if false: baseband
- `max_pulse_width`: maximum pulse width in ns, valid only for baseband signal
- `carrier_freq`: carrier frequency in Hz, valid only for modulated signal
- `duty_cycle`: duty cycle percentage, valid only for modulated signal
- `invert_level`: invert signal level
- `invert_carrier_sense`: Send 0/space as a carrier burst. used only in TX.
- `noise_filter_min_width`: min time of a valid pulse, in ns. Used only for RX.
- `carrier_range_lower`: Lower carrier range, in Hz, valid only for modulated
  signal. Used only for RX.
- `carrier_range_upper`: Upper carrier range, in Hz, valid only for modulated
  signal. Used only for RX.
- `resolution`: The receive resolution, in ns . Used only for RX.

#### <a id="c-struct-v4l2_subdev_ir_ops"></a>`struct v4l2_subdev_ir_ops`

operations for IR subdevices

**Definition**

```c
struct v4l2_subdev_ir_ops {
    int (*rx_read)(struct v4l2_subdev *sd, u8 *buf, size_t count, ssize_t *num);
    int (*rx_g_parameters)(struct v4l2_subdev *sd, struct v4l2_subdev_ir_parameters *params);
    int (*rx_s_parameters)(struct v4l2_subdev *sd, struct v4l2_subdev_ir_parameters *params);
    int (*tx_write)(struct v4l2_subdev *sd, u8 *buf, size_t count, ssize_t *num);
    int (*tx_g_parameters)(struct v4l2_subdev *sd, struct v4l2_subdev_ir_parameters *params);
    int (*tx_s_parameters)(struct v4l2_subdev *sd, struct v4l2_subdev_ir_parameters *params);
};
```

**Members**

- `rx_read`: Reads received codes or pulse width data.
  The semantics are similar to a non-blocking `read()` call.
- `rx_g_parameters`: Get the current operating parameters and state of
  the IR receiver.
- `rx_s_parameters`: Set the current operating parameters and state of
  the IR receiver.  It is recommended to call
  \[rt\]x_g_parameters first to fill out the current state, and only change
  the fields that need to be changed.  Upon return, the actual device
  operating parameters and state will be returned.  Note that hardware
  limitations may prevent the actual settings from matching the requested
  settings - e.g. an actual carrier setting of 35,904 Hz when 36,000 Hz
  was requested.  An exception is when the shutdown parameter is true.
  The last used operational parameters will be returned, but the actual
  state of the hardware be different to minimize power consumption and
  processing when shutdown is true.
- `tx_write`: Writes codes or pulse width data for transmission.
  The semantics are similar to a non-blocking `write()` call.
- `tx_g_parameters`: Get the current operating parameters and state of
  the IR transmitter.
- `tx_s_parameters`: Set the current operating parameters and state of
  the IR transmitter.  It is recommended to call
  \[rt\]x_g_parameters first to fill out the current state, and only change
  the fields that need to be changed.  Upon return, the actual device
  operating parameters and state will be returned.  Note that hardware
  limitations may prevent the actual settings from matching the requested
  settings - e.g. an actual carrier setting of 35,904 Hz when 36,000 Hz
  was requested.  An exception is when the shutdown parameter is true.
  The last used operational parameters will be returned, but the actual
  state of the hardware be different to minimize power consumption and
  processing when shutdown is true.

#### <a id="c-struct-v4l2_subdev_pad_config"></a>`struct v4l2_subdev_pad_config`

Used for storing subdev pad information.

**Definition**

```c
struct v4l2_subdev_pad_config {
    struct v4l2_mbus_framefmt format;
    struct v4l2_rect crop;
    struct v4l2_rect compose;
    struct v4l2_fract interval;
};
```

**Members**

- `format`: [`struct v4l2_mbus_framefmt`](/kernel/userspace/userspace-api/media-v4l/subdev-formats.md#c-v4l2_mbus_framefmt)
- `crop`: [`struct v4l2_rect`](/kernel/userspace/userspace-api/media-v4l/dev-overlay.md#c-v4l2_rect) to be used for crop
- `compose`: [`struct v4l2_rect`](/kernel/userspace/userspace-api/media-v4l/dev-overlay.md#c-v4l2_rect) to be used for compose
- `interval`: frame interval

#### <a id="c-struct-v4l2_subdev_stream_configs"></a>`struct v4l2_subdev_stream_configs`

A collection of stream configs.

**Definition**

```c
struct v4l2_subdev_stream_configs {
    u32 num_configs;
    struct v4l2_subdev_stream_config *configs;
};
```

**Members**

- `num_configs`: number of entries in **config**.
- `configs`: an array of [`struct v4l2_subdev_stream_configs`](#c-struct-v4l2_subdev_stream_configs).

#### <a id="c-struct-v4l2_subdev_krouting"></a>`struct v4l2_subdev_krouting`

subdev routing table

**Definition**

```c
struct v4l2_subdev_krouting {
    unsigned int len_routes;
    unsigned int num_routes;
    struct v4l2_subdev_route *routes;
};
```

**Members**

- `len_routes`: length of routes array, in routes
- `num_routes`: number of routes
- `routes`: [`struct v4l2_subdev_route`](/kernel/userspace/userspace-api/media-v4l/vidioc-subdev-g-routing.md#c-v4l2_subdev_route)

**Description**

This structure contains the routing table for a subdev.

#### <a id="c-struct-v4l2_subdev_state"></a>`struct v4l2_subdev_state`

Used for storing subdev state information.

**Definition**

```c
struct v4l2_subdev_state {
    struct mutex _lock;
    struct mutex *lock;
    struct v4l2_subdev *sd;
    struct v4l2_subdev_pad_config *pads;
    struct v4l2_subdev_krouting routing;
    struct v4l2_subdev_stream_configs stream_configs;
};
```

**Members**

- `_lock`: default for 'lock'
- `lock`: mutex for the state. May be replaced by the user.
- `sd`: the sub-device which the state is related to
- `pads`: [`struct v4l2_subdev_pad_config`](#c-struct-v4l2_subdev_pad_config) array
- `routing`: routing table for the subdev
- `stream_configs`: stream configurations (only for V4L2_SUBDEV_FL_STREAMS)

**Description**

This structure only needs to be passed to the pad op if the 'which' field
of the main argument is set to `V4L2_SUBDEV_FORMAT_TRY`. For
`V4L2_SUBDEV_FORMAT_ACTIVE` it is safe to pass `NULL`.

#### <a id="c-struct-v4l2_subdev_pad_ops"></a>`struct v4l2_subdev_pad_ops`

v4l2-subdev pad level operations

**Definition**

```c
struct v4l2_subdev_pad_ops {
        int (*enum_mbus_code)(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, struct v4l2_subdev_mbus_code_enum *code);
        int (*enum_frame_size)(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, struct v4l2_subdev_frame_size_enum *fse);
        int (*enum_frame_interval)(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, struct v4l2_subdev_frame_interval_enum *fie);
        int (*get_fmt)(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, struct v4l2_subdev_format *format);
        int (*set_fmt)(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, struct v4l2_subdev_format *format);
        int (*get_selection)(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, struct v4l2_subdev_selection *sel);
        int (*set_selection)(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, struct v4l2_subdev_selection *sel);
        int (*get_frame_interval)(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, struct v4l2_subdev_frame_interval *interval);
        int (*set_frame_interval)(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, struct v4l2_subdev_frame_interval *interval);
        int (*get_edid)(struct v4l2_subdev *sd, struct v4l2_edid *edid);
        int (*set_edid)(struct v4l2_subdev *sd, struct v4l2_edid *edid);
        int (*s_dv_timings)(struct v4l2_subdev *sd, unsigned int pad, struct v4l2_dv_timings *timings);
        int (*g_dv_timings)(struct v4l2_subdev *sd, unsigned int pad, struct v4l2_dv_timings *timings);
        int (*query_dv_timings)(struct v4l2_subdev *sd, unsigned int pad, struct v4l2_dv_timings *timings);
        int (*dv_timings_cap)(struct v4l2_subdev *sd, struct v4l2_dv_timings_cap *cap);
        int (*enum_dv_timings)(struct v4l2_subdev *sd, struct v4l2_enum_dv_timings *timings);
    #ifdef CONFIG_MEDIA_CONTROLLER;
        int (*link_validate)(struct v4l2_subdev *sd, struct media_link *link, struct v4l2_subdev_format *source_fmt, struct v4l2_subdev_format *sink_fmt);
    #endif;
        int (*get_frame_desc)(struct v4l2_subdev *sd, unsigned int pad, struct v4l2_mbus_frame_desc *fd);
        int (*set_frame_desc)(struct v4l2_subdev *sd, unsigned int pad, struct v4l2_mbus_frame_desc *fd);
        int (*get_mbus_config)(struct v4l2_subdev *sd, unsigned int pad, struct v4l2_mbus_config *config);
        int (*set_routing)(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, enum v4l2_subdev_format_whence which, struct v4l2_subdev_krouting *route);
        int (*enable_streams)(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, u32 pad, u64 streams_mask);
        int (*disable_streams)(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, u32 pad, u64 streams_mask);
};
```

**Members**

- `enum_mbus_code`: callback for `VIDIOC_SUBDEV_ENUM_MBUS_CODE()` ioctl handler
  code.
- `enum_frame_size`: callback for `VIDIOC_SUBDEV_ENUM_FRAME_SIZE()` ioctl handler
  code.
- `enum_frame_interval`: callback for `VIDIOC_SUBDEV_ENUM_FRAME_INTERVAL()` ioctl
  handler code.
- `get_fmt`: callback for `VIDIOC_SUBDEV_G_FMT()` ioctl handler code.
- `set_fmt`: callback for `VIDIOC_SUBDEV_S_FMT()` ioctl handler code.
- `get_selection`: callback for `VIDIOC_SUBDEV_G_SELECTION()` ioctl handler code.
- `set_selection`: callback for `VIDIOC_SUBDEV_S_SELECTION()` ioctl handler code.
- `get_frame_interval`: callback for `VIDIOC_SUBDEV_G_FRAME_INTERVAL()`
  ioctl handler code.
- `set_frame_interval`: callback for `VIDIOC_SUBDEV_S_FRAME_INTERVAL()`
  ioctl handler code.
- `get_edid`: callback for `VIDIOC_SUBDEV_G_EDID()` ioctl handler code.
- `set_edid`: callback for `VIDIOC_SUBDEV_S_EDID()` ioctl handler code.
- `s_dv_timings`: Set custom dv timings in the sub device. This is used
  when sub device is capable of setting detailed timing information
  in the hardware to generate/detect the video signal.
- `g_dv_timings`: Get custom dv timings in the sub device.
- `query_dv_timings`: callback for `VIDIOC_QUERY_DV_TIMINGS()` ioctl handler code.
- `dv_timings_cap`: callback for `VIDIOC_SUBDEV_DV_TIMINGS_CAP()` ioctl handler
  code.
- `enum_dv_timings`: callback for `VIDIOC_SUBDEV_ENUM_DV_TIMINGS()` ioctl handler
  code.
- `link_validate`: used by the media controller code to check if the links
  that belongs to a pipeline can be used for stream.
- `get_frame_desc`: get the current low level media bus frame parameters.
- `set_frame_desc`: set the low level media bus frame parameters, **fd** array
  may be adjusted by the subdev driver to device capabilities.
- `get_mbus_config`: get the media bus configuration of a remote sub-device.
  The media bus configuration is usually retrieved from the
  firmware interface at sub-device probe time, immediately
  applied to the hardware and eventually adjusted by the
  driver. Remote sub-devices (usually video receivers) shall
  use this operation to query the transmitting end bus
  configuration in order to adjust their own one accordingly.
  Callers should make sure they get the most up-to-date as
  possible configuration from the remote end, likely calling
  this operation as close as possible to stream on time. The
  operation shall fail if the pad index it has been called on
  is not valid or in case of unrecoverable failures. The
  config argument has been memset to 0 just before calling
  the op.
- `set_routing`: Enable or disable data connection routes described in the
  subdevice routing table. Subdevs that implement this operation
  must set the V4L2_SUBDEV_FL_STREAMS flag.
- `enable_streams`: Enable the streams defined in streams_mask on the given
  source pad. Subdevs that implement this operation must use the active
  state management provided by the subdev core (enabled through a call to
  [`v4l2_subdev_init_finalize()`](#c-v4l2_subdev_init_finalize) at initialization time). Do not call
  directly, use [`v4l2_subdev_enable_streams()`](#c-v4l2_subdev_enable_streams) instead.
- `disable_streams`: Disable the streams defined in streams_mask on the given
  source pad. Subdevs that implement this operation must use the active
  state management provided by the subdev core (enabled through a call to
  [`v4l2_subdev_init_finalize()`](#c-v4l2_subdev_init_finalize) at initialization time). Do not call
  directly, use [`v4l2_subdev_disable_streams()`](#c-v4l2_subdev_disable_streams) instead.

**Description**

Drivers that support only a single stream without setting the
V4L2_SUBDEV_CAP_STREAMS sub-device capability flag can ignore the mask
argument.

Drivers that support only a single stream without setting the
V4L2_SUBDEV_CAP_STREAMS sub-device capability flag can ignore the mask
argument.

#### <a id="c-struct-v4l2_subdev_ops"></a>`struct v4l2_subdev_ops`

Subdev operations

**Definition**

```c
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_vbi_ops        *vbi;
    const struct v4l2_subdev_ir_ops         *ir;
    const struct v4l2_subdev_sensor_ops     *sensor;
    const struct v4l2_subdev_pad_ops        *pad;
};
```

**Members**

- `core`: pointer to [`struct v4l2_subdev_core_ops`](#c-struct-v4l2_subdev_core_ops). Can be `NULL`
- `tuner`: pointer to [`struct v4l2_subdev_tuner_ops`](#c-struct-v4l2_subdev_tuner_ops). Can be `NULL`
- `audio`: pointer to [`struct v4l2_subdev_audio_ops`](#c-struct-v4l2_subdev_audio_ops). Can be `NULL`
- `video`: pointer to [`struct v4l2_subdev_video_ops`](#c-struct-v4l2_subdev_video_ops). Can be `NULL`
- `vbi`: pointer to [`struct v4l2_subdev_vbi_ops`](#c-struct-v4l2_subdev_vbi_ops). Can be `NULL`
- `ir`: pointer to [`struct v4l2_subdev_ir_ops`](#c-struct-v4l2_subdev_ir_ops). Can be `NULL`
- `sensor`: pointer to [`struct v4l2_subdev_sensor_ops`](#c-struct-v4l2_subdev_sensor_ops). Can be `NULL`
- `pad`: pointer to [`struct v4l2_subdev_pad_ops`](#c-struct-v4l2_subdev_pad_ops). Can be `NULL`

#### <a id="c-struct-v4l2_subdev_internal_ops"></a>`struct v4l2_subdev_internal_ops`

V4L2 subdev internal ops

**Definition**

```c
struct v4l2_subdev_internal_ops {
    int (*init_state)(struct v4l2_subdev *sd, struct v4l2_subdev_state *state);
    int (*registered)(struct v4l2_subdev *sd);
    void (*unregistered)(struct v4l2_subdev *sd);
    int (*open)(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh);
    int (*close)(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh);
    void (*release)(struct v4l2_subdev *sd);
};
```

**Members**

- `init_state`: initialize the subdev state to default values
- `registered`: called when this subdev is registered. When called the v4l2_dev
  field is set to the correct v4l2_device.
- `unregistered`: called when this subdev is unregistered. When called the
  v4l2_dev field is still set to the correct v4l2_device.
- `open`: called when the subdev device node is opened by an application.
- `close`: called when the subdev device node is closed. Please note that
  it is possible for **close** to be called after **unregistered**!
- `release`: called when the last user of the subdev device is gone. This
  happens after the **unregistered** callback and when the last open
  filehandle to the v4l-subdevX device node was closed. If no device
  node was created for this sub-device, then the **release** callback
  is called right after the **unregistered** callback.
  The **release** callback is typically used to free the memory containing
  the v4l2_subdev structure. It is almost certainly required for any
  sub-device that sets the V4L2_SUBDEV_FL_HAS_DEVNODE flag.

**Description**

> [!NOTE]
> Never call this from drivers, only the v4l2 framework can call
> these ops.

#### <a id="c-struct-v4l2_subdev_platform_data"></a>`struct v4l2_subdev_platform_data`

regulators config struct

**Definition**

```c
struct v4l2_subdev_platform_data {
    struct regulator_bulk_data *regulators;
    int num_regulators;
    void *host_priv;
};
```

**Members**

- `regulators`: Optional regulators used to power on/off the subdevice
- `num_regulators`: Number of regululators
- `host_priv`: Per-subdevice data, specific for a certain video host device

#### <a id="c-struct-v4l2_subdev"></a>`struct v4l2_subdev`

describes a V4L2 sub-device

**Definition**

```c
struct v4l2_subdev {
    #if defined(CONFIG_MEDIA_CONTROLLER);
        struct media_entity entity;
    #endif;
        struct list_head list;
        struct module *owner;
        bool owner_v4l2_dev;
        u32 flags;
        struct v4l2_device *v4l2_dev;
        const struct v4l2_subdev_ops *ops;
        const struct v4l2_subdev_internal_ops *internal_ops;
        struct v4l2_ctrl_handler *ctrl_handler;
        char name[52];
        u32 grp_id;
        void *dev_priv;
        void *host_priv;
        struct video_device *devnode;
        struct device *dev;
        struct fwnode_handle *fwnode;
        struct list_head async_list;
        struct list_head async_subdev_endpoint_list;
        struct v4l2_async_notifier *subdev_notifier;
        struct list_head asc_list;
        struct v4l2_subdev_platform_data *pdata;
        struct mutex *state_lock;
        struct led_classdev *privacy_led;
        struct v4l2_subdev_state *active_state;
        u64 enabled_pads;
        bool s_stream_enabled;
};
```

**Members**

- `entity`: pointer to [`struct media_entity`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_entity)
- `list`: List of sub-devices
- `owner`: The owner is the same as the driver's [`struct device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) owner.
- `owner_v4l2_dev`: true if the `sd->owner` matches the owner of **v4l2_dev->dev**
  owner. Initialized by [`v4l2_device_register_subdev()`](/kernel/hardware/driver-api/media/v4l2-device.md#c-v4l2_device_register_subdev).
- `flags`: subdev flags. Can be:
  `V4L2_SUBDEV_FL_IS_I2C` - Set this flag if this subdev is a i2c device;
  `V4L2_SUBDEV_FL_IS_SPI` - Set this flag if this subdev is a spi device;
  `V4L2_SUBDEV_FL_HAS_DEVNODE` - Set this flag if this subdev needs a
  device node;
  `V4L2_SUBDEV_FL_HAS_EVENTS` -  Set this flag if this subdev generates
  events.
- `v4l2_dev`: pointer to struct [`v4l2_device`](/kernel/hardware/driver-api/media/v4l2-device.md#c-struct-v4l2_device)
- `ops`: pointer to struct [`v4l2_subdev_ops`](#c-struct-v4l2_subdev_ops)
- `internal_ops`: pointer to struct [`v4l2_subdev_internal_ops`](#c-struct-v4l2_subdev_internal_ops).
  Never call these internal ops from within a driver!
- `ctrl_handler`: The control handler of this subdev. May be NULL.
- `name`: Name of the sub-device. Please notice that the name must be unique.
- `grp_id`: can be used to group similar subdevs. Value is driver-specific
- `dev_priv`: pointer to private data
- `host_priv`: pointer to private data used by the device where the subdev
  is attached.
- `devnode`: subdev device node
- `dev`: pointer to the physical device, if any
- `fwnode`: The fwnode_handle of the subdev, usually the same as
  either dev->of_node->fwnode or dev->fwnode (whichever is non-NULL).
- `async_list`: Links this subdev to a global subdev_list or
  **notifier->done_list** list.
- `async_subdev_endpoint_list`: List entry in async_subdev_endpoint_entry of
  [`struct v4l2_async_subdev_endpoint`](/kernel/hardware/driver-api/media/v4l2-async.md#c-struct-v4l2_async_subdev_endpoint).
- `subdev_notifier`: A sub-device notifier implicitly registered for the sub-
  device using [`v4l2_async_register_subdev_sensor()`](/kernel/hardware/driver-api/media/v4l2-async.md#c-v4l2_async_register_subdev_sensor).
- `asc_list`: Async connection list, of [`struct v4l2_async_connection`](/kernel/hardware/driver-api/media/v4l2-async.md#c-struct-v4l2_async_connection).subdev_entry.
- `pdata`: common part of subdevice platform data
- `state_lock`: A pointer to a lock used for all the subdev's states, set by the
  driver. This is optional. If NULL, each state instance will get
  a lock of its own.
- `privacy_led`: Optional pointer to a LED classdev for the privacy LED for sensors.
- `active_state`: Active state for the subdev (NULL for subdevs tracking the
  state internally). Initialized by calling
  [`v4l2_subdev_init_finalize()`](#c-v4l2_subdev_init_finalize).
- `enabled_pads`: Bitmask of enabled pads used by [`v4l2_subdev_enable_streams()`](#c-v4l2_subdev_enable_streams)
  and [`v4l2_subdev_disable_streams()`](#c-v4l2_subdev_disable_streams) helper functions for
  fallback cases.
- `s_stream_enabled`: Tracks whether streaming has been enabled with s_stream.
  This is only for `call_s_stream()` internal use.

**Description**

Each instance of a subdev driver should create this struct, either
stand-alone or embedded in a larger struct.

This structure should be initialized by [`v4l2_subdev_init()`](#c-v4l2_subdev_init) or one of
its variants: [`v4l2_spi_subdev_init()`](/kernel/hardware/driver-api/media/v4l2-common.md#c-v4l2_spi_subdev_init), [`v4l2_i2c_subdev_init()`](/kernel/hardware/driver-api/media/v4l2-common.md#c-v4l2_i2c_subdev_init).

#### <a id="c-media_entity_to_v4l2_subdev"></a>`media_entity_to_v4l2_subdev()`

```c
media_entity_to_v4l2_subdev(ent)
```

Returns a [`struct v4l2_subdev`](#c-struct-v4l2_subdev) from the [`struct media_entity`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_entity) embedded in it.

**Parameters**

- `ent`: pointer to [`struct media_entity`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_entity).

#### <a id="c-vdev_to_v4l2_subdev"></a>`vdev_to_v4l2_subdev()`

```c
vdev_to_v4l2_subdev(vdev)
```

Returns a [`struct v4l2_subdev`](#c-struct-v4l2_subdev) from the [`struct video_device`](/kernel/hardware/driver-api/media/v4l2-dev.md#c-struct-video_device) embedded on it.

**Parameters**

- `vdev`: pointer to [`struct video_device`](/kernel/hardware/driver-api/media/v4l2-dev.md#c-struct-video_device)

#### <a id="c-struct-v4l2_subdev_fh"></a>`struct v4l2_subdev_fh`

Used for storing subdev information per file handle

**Definition**

```c
struct v4l2_subdev_fh {
        struct v4l2_fh vfh;
        struct module *owner;
    #if defined(CONFIG_VIDEO_V4L2_SUBDEV_API);
        struct v4l2_subdev_state *state;
        u64 client_caps;
    #endif;
};
```

**Members**

- `vfh`: pointer to [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh)
- `owner`: module pointer to the owner of this file handle
- `state`: pointer to [`struct v4l2_subdev_state`](#c-struct-v4l2_subdev_state)
- `client_caps`: bitmask of `V4L2_SUBDEV_CLIENT_CAP_*`

#### <a id="c-to_v4l2_subdev_fh"></a>`to_v4l2_subdev_fh()`

```c
to_v4l2_subdev_fh(fh)
```

Returns a [`struct v4l2_subdev_fh`](#c-struct-v4l2_subdev_fh) from the [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh) embedded on it.

**Parameters**

- `fh`: pointer to [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh)

#### <a id="c-v4l2_set_subdevdata"></a>`v4l2_set_subdevdata()`

```c
void v4l2_set_subdevdata(struct v4l2_subdev *sd, void *p)
```

Sets V4L2 dev private device data

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](#c-struct-v4l2_subdev)
- `void *p`: pointer to the private device data to be stored.

#### <a id="c-v4l2_get_subdevdata"></a>`v4l2_get_subdevdata()`

```c
void * v4l2_get_subdevdata(const struct v4l2_subdev *sd)
```

Gets V4L2 dev private device data

**Parameters**

- `const struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](#c-struct-v4l2_subdev)

**Description**

Returns the pointer to the private device data to be stored.

#### <a id="c-v4l2_set_subdev_hostdata"></a>`v4l2_set_subdev_hostdata()`

```c
void v4l2_set_subdev_hostdata(struct v4l2_subdev *sd, void *p)
```

Sets V4L2 dev private host data

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](#c-struct-v4l2_subdev)
- `void *p`: pointer to the private data to be stored.

#### <a id="c-v4l2_get_subdev_hostdata"></a>`v4l2_get_subdev_hostdata()`

```c
void * v4l2_get_subdev_hostdata(const struct v4l2_subdev *sd)
```

Gets V4L2 dev private data

**Parameters**

- `const struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](#c-struct-v4l2_subdev)

**Description**

Returns the pointer to the private host data to be stored.

#### <a id="c-v4l2_subdev_get_fwnode_pad_1_to_1"></a>`v4l2_subdev_get_fwnode_pad_1_to_1()`

```c
int v4l2_subdev_get_fwnode_pad_1_to_1(struct media_entity *entity, struct fwnode_endpoint *endpoint)
```

Get pad number from a subdev fwnode endpoint, assuming 1:1 port:pad

**Parameters**

- `struct media_entity *entity`: Pointer to the subdev entity
- `struct fwnode_endpoint *endpoint`: Pointer to a parsed fwnode endpoint

**Description**

This function can be used as the .get_fwnode_pad operation for
subdevices that map port numbers and pad indexes 1:1. If the endpoint
is owned by the subdevice, the function returns the endpoint port
number.

Returns the endpoint port number on success or a negative error code.

#### <a id="c-v4l2_subdev_link_validate_default"></a>`v4l2_subdev_link_validate_default()`

```c
int v4l2_subdev_link_validate_default(struct v4l2_subdev *sd, struct media_link *link, struct v4l2_subdev_format *source_fmt, struct v4l2_subdev_format *sink_fmt)
```

validates a media link

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](#c-struct-v4l2_subdev)
- `struct media_link *link`: pointer to [`struct media_link`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_link)
- `struct v4l2_subdev_format *source_fmt`: pointer to [`struct v4l2_subdev_format`](/kernel/userspace/userspace-api/media-v4l/vidioc-subdev-g-fmt.md#c-v4l2_subdev_format)
- `struct v4l2_subdev_format *sink_fmt`: pointer to [`struct v4l2_subdev_format`](/kernel/userspace/userspace-api/media-v4l/vidioc-subdev-g-fmt.md#c-v4l2_subdev_format)

**Description**

This function ensures that width, height and the media bus pixel
code are equal on both source and sink of the link.

#### <a id="c-v4l2_subdev_link_validate"></a>`v4l2_subdev_link_validate()`

```c
int v4l2_subdev_link_validate(struct media_link *link)
```

validates a media link

**Parameters**

- `struct media_link *link`: pointer to [`struct media_link`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_link)

**Description**

This function calls the subdev's link_validate ops to validate
if a media link is valid for streaming. It also internally
calls [`v4l2_subdev_link_validate_default()`](#c-v4l2_subdev_link_validate_default) to ensure that
width, height and the media bus pixel code are equal on both
source and sink of the link.

The function can be used as a drop-in `media_entity_ops.link_validate`
implementation for v4l2_subdev instances. It supports all links between
subdevs, as well as links between subdevs and video devices, provided that
the video devices also implement their `media_entity_ops.link_validate`
operation.

#### <a id="c-v4l2_subdev_has_pad_interdep"></a>`v4l2_subdev_has_pad_interdep()`

```c
bool v4l2_subdev_has_pad_interdep(struct media_entity *entity, unsigned int pad0, unsigned int pad1)
```

MC has_pad_interdep implementation for subdevs

**Parameters**

- `struct media_entity *entity`: pointer to [`struct media_entity`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_entity)
- `unsigned int pad0`: pad number for the first pad
- `unsigned int pad1`: pad number for the second pad

**Description**

This function is an implementation of the
media_entity_operations.has_pad_interdep operation for subdevs that
implement the multiplexed streams API (as indicated by the
V4L2_SUBDEV_FL_STREAMS subdev flag).

It considers two pads interdependent if there is an active route between pad0
and pad1.

#### <a id="c-__v4l2_subdev_state_alloc"></a>`__v4l2_subdev_state_alloc()`

```c
struct v4l2_subdev_state * __v4l2_subdev_state_alloc(struct v4l2_subdev *sd, const char *lock_name, struct lock_class_key *key)
```

allocate v4l2_subdev_state

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](#c-struct-v4l2_subdev) for which the state is being allocated.
- `const char *lock_name`: name of the state lock
- `struct lock_class_key *key`: lock_class_key for the lock

**Description**

Must call [`__v4l2_subdev_state_free()`](#c-__v4l2_subdev_state_free) when state is no longer needed.

Not to be called directly by the drivers.

#### <a id="c-__v4l2_subdev_state_free"></a>`__v4l2_subdev_state_free()`

```c
void __v4l2_subdev_state_free(struct v4l2_subdev_state *state)
```

free a v4l2_subdev_state

**Parameters**

- `struct v4l2_subdev_state *state`: v4l2_subdev_state to be freed.

**Description**

Not to be called directly by the drivers.

#### <a id="c-v4l2_subdev_init_finalize"></a>`v4l2_subdev_init_finalize()`

```c
v4l2_subdev_init_finalize(sd)
```

Finalizes the initialization of the subdevice

**Parameters**

- `sd`: The subdev

**Description**

This function finalizes the initialization of the subdev, including
allocation of the active state for the subdev.

This function must be called by the subdev drivers that use the centralized
active state, after the subdev struct has been initialized and
[`media_entity_pads_init()`](/kernel/hardware/driver-api/media/mc-core.md#c-media_entity_pads_init) has been called, but before registering the
subdev.

The user must call [`v4l2_subdev_cleanup()`](#c-v4l2_subdev_cleanup) when the subdev is being removed.

#### <a id="c-v4l2_subdev_cleanup"></a>`v4l2_subdev_cleanup()`

```c
void v4l2_subdev_cleanup(struct v4l2_subdev *sd)
```

Releases the resources allocated by the subdevice

**Parameters**

- `struct v4l2_subdev *sd`: The subdevice

**Description**

Clean up a V4L2 async sub-device. Must be called for a sub-device as part of
its release if resources have been associated with it using
[`v4l2_async_subdev_endpoint_add()`](/kernel/hardware/driver-api/media/v4l2-async.md#c-v4l2_async_subdev_endpoint_add) or [`v4l2_subdev_init_finalize()`](#c-v4l2_subdev_init_finalize).

#### <a id="c-v4l2_subdev_state_get_format"></a>`v4l2_subdev_state_get_format()`

```c
v4l2_subdev_state_get_format(state, pad, ...)
```

Get pointer to a stream format

**Parameters**

- `state`: subdevice state
- `pad`: pad id
- `...`: stream id (optional argument)

**Description**

This returns a pointer to [`struct v4l2_mbus_framefmt`](/kernel/userspace/userspace-api/media-v4l/subdev-formats.md#c-v4l2_mbus_framefmt) for the given pad +
stream in the subdev state.

For stream-unaware drivers the format for the corresponding pad is returned.
If the pad does not exist, NULL is returned.

#### <a id="c-v4l2_subdev_state_get_crop"></a>`v4l2_subdev_state_get_crop()`

```c
v4l2_subdev_state_get_crop(state, pad, ...)
```

Get pointer to a stream crop rectangle

**Parameters**

- `state`: subdevice state
- `pad`: pad id
- `...`: stream id (optional argument)

**Description**

This returns a pointer to crop rectangle for the given pad + stream in the
subdev state.

For stream-unaware drivers the crop rectangle for the corresponding pad is
returned. If the pad does not exist, NULL is returned.

#### <a id="c-v4l2_subdev_state_get_compose"></a>`v4l2_subdev_state_get_compose()`

```c
v4l2_subdev_state_get_compose(state, pad, ...)
```

Get pointer to a stream compose rectangle

**Parameters**

- `state`: subdevice state
- `pad`: pad id
- `...`: stream id (optional argument)

**Description**

This returns a pointer to compose rectangle for the given pad + stream in the
subdev state.

For stream-unaware drivers the compose rectangle for the corresponding pad is
returned. If the pad does not exist, NULL is returned.

#### <a id="c-v4l2_subdev_state_get_interval"></a>`v4l2_subdev_state_get_interval()`

```c
v4l2_subdev_state_get_interval(state, pad, ...)
```

Get pointer to a stream frame interval

**Parameters**

- `state`: subdevice state
- `pad`: pad id
- `...`: stream id (optional argument)

**Description**

This returns a pointer to the frame interval for the given pad + stream in
the subdev state.

For stream-unaware drivers the frame interval for the corresponding pad is
returned. If the pad does not exist, NULL is returned.

#### <a id="c-v4l2_subdev_get_fmt"></a>`v4l2_subdev_get_fmt()`

```c
int v4l2_subdev_get_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, struct v4l2_subdev_format *format)
```

Fill format based on state

**Parameters**

- `struct v4l2_subdev *sd`: subdevice
- `struct v4l2_subdev_state *state`: subdevice state
- `struct v4l2_subdev_format *format`: pointer to [`struct v4l2_subdev_format`](/kernel/userspace/userspace-api/media-v4l/vidioc-subdev-g-fmt.md#c-v4l2_subdev_format)

**Description**

Fill **format->format** field based on the information in the **format** struct.

This function can be used by the subdev drivers which support active state to
implement v4l2_subdev_pad_ops.get_fmt if the subdev driver does not need to
do anything special in their get_fmt op.

Returns 0 on success, error value otherwise.

#### <a id="c-v4l2_subdev_get_frame_interval"></a>`v4l2_subdev_get_frame_interval()`

```c
int v4l2_subdev_get_frame_interval(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, struct v4l2_subdev_frame_interval *fi)
```

Fill frame interval based on state

**Parameters**

- `struct v4l2_subdev *sd`: subdevice
- `struct v4l2_subdev_state *state`: subdevice state
- `struct v4l2_subdev_frame_interval *fi`: pointer to [`struct v4l2_subdev_frame_interval`](/kernel/userspace/userspace-api/media-v4l/vidioc-subdev-g-frame-interval.md#c-v4l2_subdev_frame_interval)

**Description**

Fill **fi->interval** field based on the information in the **fi** struct.

This function can be used by the subdev drivers which support active state to
implement v4l2_subdev_pad_ops.get_frame_interval if the subdev driver does
not need to do anything special in their get_frame_interval op.

Returns 0 on success, error value otherwise.

#### <a id="c-v4l2_subdev_set_routing"></a>`v4l2_subdev_set_routing()`

```c
int v4l2_subdev_set_routing(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, const struct v4l2_subdev_krouting *routing)
```

Set given routing to subdev state

**Parameters**

- `struct v4l2_subdev *sd`: The subdevice
- `struct v4l2_subdev_state *state`: The subdevice state
- `const struct v4l2_subdev_krouting *routing`: Routing that will be copied to subdev state

**Description**

This will release old routing table (if any) from the state, allocate
enough space for the given routing, and copy the routing.

This can be used from the subdev driver's set_routing op, after validating
the routing.

#### <a id="c-for_each_active_route"></a>`for_each_active_route()`

```c
for_each_active_route(routing, route)
```

iterate on all active routes of a routing table

**Parameters**

- `routing`: The routing table
- `route`: The route iterator

#### <a id="c-v4l2_subdev_set_routing_with_fmt"></a>`v4l2_subdev_set_routing_with_fmt()`

```c
int v4l2_subdev_set_routing_with_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, const struct v4l2_subdev_krouting *routing, const struct v4l2_mbus_framefmt *fmt)
```

Set given routing and format to subdev state

**Parameters**

- `struct v4l2_subdev *sd`: The subdevice
- `struct v4l2_subdev_state *state`: The subdevice state
- `const struct v4l2_subdev_krouting *routing`: Routing that will be copied to subdev state
- `const struct v4l2_mbus_framefmt *fmt`: Format used to initialize all the streams

**Description**

This is the same as v4l2_subdev_set_routing, but additionally initializes
all the streams using the given format.

#### <a id="c-v4l2_subdev_routing_find_opposite_end"></a>`v4l2_subdev_routing_find_opposite_end()`

```c
int v4l2_subdev_routing_find_opposite_end(const struct v4l2_subdev_krouting *routing, u32 pad, u32 stream, u32 *other_pad, u32 *other_stream)
```

Find the opposite stream

**Parameters**

- `const struct v4l2_subdev_krouting *routing`: routing used to find the opposite side
- `u32 pad`: pad id
- `u32 stream`: stream id
- `u32 *other_pad`: pointer used to return the opposite pad
- `u32 *other_stream`: pointer used to return the opposite stream

**Description**

This function uses the routing table to find the pad + stream which is
opposite the given pad + stream.

**other_pad** and/or **other_stream** can be NULL if the caller does not need the
value.

Returns 0 on success, or -EINVAL if no matching route is found.

#### <a id="c-v4l2_subdev_state_get_opposite_stream_format"></a>`v4l2_subdev_state_get_opposite_stream_format()`

```c
struct v4l2_mbus_framefmt * v4l2_subdev_state_get_opposite_stream_format(struct v4l2_subdev_state *state, u32 pad, u32 stream)
```

Get pointer to opposite stream format

**Parameters**

- `struct v4l2_subdev_state *state`: subdevice state
- `u32 pad`: pad id
- `u32 stream`: stream id

**Description**

This returns a pointer to [`struct v4l2_mbus_framefmt`](/kernel/userspace/userspace-api/media-v4l/subdev-formats.md#c-v4l2_mbus_framefmt) for the pad + stream
that is opposite the given pad + stream in the subdev state.

If the state does not contain the given pad + stream, NULL is returned.

#### <a id="c-v4l2_subdev_state_xlate_streams"></a>`v4l2_subdev_state_xlate_streams()`

```c
u64 v4l2_subdev_state_xlate_streams(const struct v4l2_subdev_state *state, u32 pad0, u32 pad1, u64 *streams)
```

Translate streams from one pad to another

**Parameters**

- `const struct v4l2_subdev_state *state`: Subdevice state
- `u32 pad0`: The first pad
- `u32 pad1`: The second pad
- `u64 *streams`: Streams bitmask on the first pad

**Description**

Streams on sink pads of a subdev are routed to source pads as expressed in
the subdev state routing table. Stream numbers don't necessarily match on
the sink and source side of a route. This function translates stream numbers
on **pad0**, expressed as a bitmask in **streams**, to the corresponding streams
on **pad1** using the routing table from the **state**. It returns the stream mask
on **pad1**, and updates **streams** with the streams that have been found in the
routing table.

**pad0** and **pad1** must be a sink and a source, in any order.

**Return**

The bitmask of streams of **pad1** that are routed to **streams** on **pad0**.

#### <a id="c-enum-v4l2_subdev_routing_restriction"></a>`enum v4l2_subdev_routing_restriction`

Subdevice internal routing restrictions

**Constants**

- `V4L2_SUBDEV_ROUTING_NO_1_TO_N`: an input stream shall not be routed to multiple output streams (stream
  duplication)
- `V4L2_SUBDEV_ROUTING_NO_N_TO_1`: multiple input streams shall not be routed to the same output stream
  (stream merging)
- `V4L2_SUBDEV_ROUTING_NO_SINK_STREAM_MIX`: all streams from a sink pad must be routed to a single source pad
- `V4L2_SUBDEV_ROUTING_NO_SOURCE_STREAM_MIX`: all streams on a source pad must originate from a single sink pad
- `V4L2_SUBDEV_ROUTING_NO_SINK_MULTIPLEXING`: sink pads shall not contain multiplexed streams
- `V4L2_SUBDEV_ROUTING_NO_SOURCE_MULTIPLEXING`: source pads shall not contain multiplexed streams
- `V4L2_SUBDEV_ROUTING_ONLY_1_TO_1`: only non-overlapping 1-to-1 stream routing is allowed (a combination of
  **V4L2_SUBDEV_ROUTING_NO_1_TO_N** and **V4L2_SUBDEV_ROUTING_NO_N_TO_1**)
- `V4L2_SUBDEV_ROUTING_NO_STREAM_MIX`: all streams from a sink pad must be routed to a single source pad, and
  that source pad shall not get routes from any other sink pad
  (a combination of **V4L2_SUBDEV_ROUTING_NO_SINK_STREAM_MIX** and
  **V4L2_SUBDEV_ROUTING_NO_SOURCE_STREAM_MIX**)
- `V4L2_SUBDEV_ROUTING_NO_MULTIPLEXING`: no multiplexed streams allowed on either source or sink sides.

#### <a id="c-v4l2_subdev_routing_validate"></a>`v4l2_subdev_routing_validate()`

```c
int v4l2_subdev_routing_validate(struct v4l2_subdev *sd, const struct v4l2_subdev_krouting *routing, enum v4l2_subdev_routing_restriction disallow)
```

Verify that routes comply with driver constraints

**Parameters**

- `struct v4l2_subdev *sd`: The subdevice
- `const struct v4l2_subdev_krouting *routing`: Routing to verify
- `enum v4l2_subdev_routing_restriction disallow`: Restrictions on routes

**Description**

This verifies that the given routing complies with the **disallow** constraints.

Returns 0 on success, error value otherwise.

#### <a id="c-v4l2_subdev_enable_streams"></a>`v4l2_subdev_enable_streams()`

```c
int v4l2_subdev_enable_streams(struct v4l2_subdev *sd, u32 pad, u64 streams_mask)
```

Enable streams on a pad

**Parameters**

- `struct v4l2_subdev *sd`: The subdevice
- `u32 pad`: The pad
- `u64 streams_mask`: Bitmask of streams to enable

**Description**

This function enables streams on a source **pad** of a subdevice. The pad is
identified by its index, while the streams are identified by the
**streams_mask** bitmask. This allows enabling multiple streams on a pad at
once.

Enabling a stream that is already enabled isn't allowed. If **streams_mask**
contains an already enabled stream, this function returns -EALREADY without
performing any operation.

Per-stream enable is only available for subdevs that implement the
.`enable_streams()` and .`disable_streams()` operations. For other subdevs, this
function implements a best-effort compatibility by calling the .`s_stream()`
operation, limited to subdevs that have a single source pad.

Drivers that are not stream-aware shall set **streams_mask** to BIT_ULL(0).

**Return**

* 0: Success
* -EALREADY: One of the streams in streams_mask is already enabled
* -EINVAL: The pad index is invalid, or doesn't correspond to a source pad
* -EOPNOTSUPP: Falling back to the legacy .`s_stream()` operation is
  impossible because the subdev has multiple source pads

#### <a id="c-v4l2_subdev_disable_streams"></a>`v4l2_subdev_disable_streams()`

```c
int v4l2_subdev_disable_streams(struct v4l2_subdev *sd, u32 pad, u64 streams_mask)
```

Disable streams on a pad

**Parameters**

- `struct v4l2_subdev *sd`: The subdevice
- `u32 pad`: The pad
- `u64 streams_mask`: Bitmask of streams to disable

**Description**

This function disables streams on a source **pad** of a subdevice. The pad is
identified by its index, while the streams are identified by the
**streams_mask** bitmask. This allows disabling multiple streams on a pad at
once.

Disabling a streams that is not enabled isn't allowed. If **streams_mask**
contains a disabled stream, this function returns -EALREADY without
performing any operation.

Per-stream disable is only available for subdevs that implement the
.`enable_streams()` and .`disable_streams()` operations. For other subdevs, this
function implements a best-effort compatibility by calling the .`s_stream()`
operation, limited to subdevs that have a single source pad.

Drivers that are not stream-aware shall set **streams_mask** to BIT_ULL(0).

**Return**

* 0: Success
* -EALREADY: One of the streams in streams_mask is not enabled
* -EINVAL: The pad index is invalid, or doesn't correspond to a source pad
* -EOPNOTSUPP: Falling back to the legacy .`s_stream()` operation is
  impossible because the subdev has multiple source pads

#### <a id="c-v4l2_subdev_s_stream_helper"></a>`v4l2_subdev_s_stream_helper()`

```c
int v4l2_subdev_s_stream_helper(struct v4l2_subdev *sd, int enable)
```

Helper to implement the subdev s_stream operation using enable_streams and disable_streams

**Parameters**

- `struct v4l2_subdev *sd`: The subdevice
- `int enable`: Enable or disable streaming

**Description**

Subdevice drivers that implement the streams-aware
[`v4l2_subdev_pad_ops.enable_streams`](#c-struct-v4l2_subdev_pad_ops) and [`v4l2_subdev_pad_ops.disable_streams`](#c-struct-v4l2_subdev_pad_ops)
operations can use this helper to implement the legacy
[`v4l2_subdev_video_ops.s_stream`](#c-struct-v4l2_subdev_video_ops) operation.

This helper can only be used by subdevs that have a single source pad.

**Return**

0 on success, or a negative error code otherwise.

#### <a id="c-v4l2_subdev_lock_state"></a>`v4l2_subdev_lock_state()`

```c
void v4l2_subdev_lock_state(struct v4l2_subdev_state *state)
```

Locks the subdev state

**Parameters**

- `struct v4l2_subdev_state *state`: The subdevice state

**Description**

Locks the given subdev state.

The state must be unlocked with [`v4l2_subdev_unlock_state()`](#c-v4l2_subdev_unlock_state) after use.

#### <a id="c-v4l2_subdev_unlock_state"></a>`v4l2_subdev_unlock_state()`

```c
void v4l2_subdev_unlock_state(struct v4l2_subdev_state *state)
```

Unlocks the subdev state

**Parameters**

- `struct v4l2_subdev_state *state`: The subdevice state

**Description**

Unlocks the given subdev state.

#### <a id="c-v4l2_subdev_lock_states"></a>`v4l2_subdev_lock_states()`

```c
void v4l2_subdev_lock_states(struct v4l2_subdev_state *state1, struct v4l2_subdev_state *state2)
```

Lock two sub-device states

**Parameters**

- `struct v4l2_subdev_state *state1`: One subdevice state
- `struct v4l2_subdev_state *state2`: The other subdevice state

**Description**

Locks the state of two sub-devices.

The states must be unlocked with [`v4l2_subdev_unlock_states()`](#c-v4l2_subdev_unlock_states) after use.

This differs from calling [`v4l2_subdev_lock_state()`](#c-v4l2_subdev_lock_state) on both states so that if
the states share the same lock, the lock is acquired only once (so no
deadlock occurs). The caller is responsible for ensuring the locks will
always be acquired in the same order.

#### <a id="c-v4l2_subdev_unlock_states"></a>`v4l2_subdev_unlock_states()`

```c
void v4l2_subdev_unlock_states(struct v4l2_subdev_state *state1, struct v4l2_subdev_state *state2)
```

Unlock two sub-device states

**Parameters**

- `struct v4l2_subdev_state *state1`: One subdevice state
- `struct v4l2_subdev_state *state2`: The other subdevice state

**Description**

Unlocks the state of two sub-devices.

This differs from calling [`v4l2_subdev_unlock_state()`](#c-v4l2_subdev_unlock_state) on both states so that
if the states share the same lock, the lock is released only once.

#### <a id="c-v4l2_subdev_get_unlocked_active_state"></a>`v4l2_subdev_get_unlocked_active_state()`

```c
struct v4l2_subdev_state * v4l2_subdev_get_unlocked_active_state(struct v4l2_subdev *sd)
```

Checks that the active subdev state is unlocked and returns it

**Parameters**

- `struct v4l2_subdev *sd`: The subdevice

**Description**

Returns the active state for the subdevice, or NULL if the subdev does not
support active state. If the state is not NULL, calls
`lockdep_assert_not_held()` to issue a warning if the state is locked.

This function is to be used e.g. when getting the active state for the sole
purpose of passing it forward, without accessing the state fields.

#### <a id="c-v4l2_subdev_get_locked_active_state"></a>`v4l2_subdev_get_locked_active_state()`

```c
struct v4l2_subdev_state * v4l2_subdev_get_locked_active_state(struct v4l2_subdev *sd)
```

Checks that the active subdev state is locked and returns it

**Parameters**

- `struct v4l2_subdev *sd`: The subdevice

**Description**

Returns the active state for the subdevice, or NULL if the subdev does not
support active state. If the state is not NULL, calls `lockdep_assert_held()`
to issue a warning if the state is not locked.

This function is to be used when the caller knows that the active state is
already locked.

#### <a id="c-v4l2_subdev_lock_and_get_active_state"></a>`v4l2_subdev_lock_and_get_active_state()`

```c
struct v4l2_subdev_state * v4l2_subdev_lock_and_get_active_state(struct v4l2_subdev *sd)
```

Locks and returns the active subdev state for the subdevice

**Parameters**

- `struct v4l2_subdev *sd`: The subdevice

**Description**

Returns the locked active state for the subdevice, or NULL if the subdev
does not support active state.

The state must be unlocked with [`v4l2_subdev_unlock_state()`](#c-v4l2_subdev_unlock_state) after use.

#### <a id="c-v4l2_subdev_init"></a>`v4l2_subdev_init()`

```c
void v4l2_subdev_init(struct v4l2_subdev *sd, const struct v4l2_subdev_ops *ops)
```

initializes the sub-device struct

**Parameters**

- `struct v4l2_subdev *sd`: pointer to the [`struct v4l2_subdev`](#c-struct-v4l2_subdev) to be initialized
- `const struct v4l2_subdev_ops *ops`: pointer to [`struct v4l2_subdev_ops`](#c-struct-v4l2_subdev_ops).

#### <a id="c-v4l2_subdev_call"></a>`v4l2_subdev_call()`

```c
v4l2_subdev_call(sd, o, f, args...)
```

call an operation of a v4l2_subdev.

**Parameters**

- `sd`: pointer to the [`struct v4l2_subdev`](#c-struct-v4l2_subdev)
- `o`: name of the element at [`struct v4l2_subdev_ops`](#c-struct-v4l2_subdev_ops) that contains **f**.
  Each element there groups a set of callbacks functions.
- `f`: callback function to be called.
  The callback functions are defined in groups, according to
  each element at [`struct v4l2_subdev_ops`](#c-struct-v4l2_subdev_ops).
- `args...`: arguments for **f**.

**Example**

err = v4l2_subdev_call(sd, video, s_std, norm);

#### <a id="c-v4l2_subdev_call_state_active"></a>`v4l2_subdev_call_state_active()`

```c
v4l2_subdev_call_state_active(sd, o, f, args...)
```

call an operation of a v4l2_subdev which takes state as a parameter, passing the subdev its active state.

**Parameters**

- `sd`: pointer to the [`struct v4l2_subdev`](#c-struct-v4l2_subdev)
- `o`: name of the element at [`struct v4l2_subdev_ops`](#c-struct-v4l2_subdev_ops) that contains **f**.
  Each element there groups a set of callbacks functions.
- `f`: callback function to be called.
  The callback functions are defined in groups, according to
  each element at [`struct v4l2_subdev_ops`](#c-struct-v4l2_subdev_ops).
- `args...`: arguments for **f**.

**Description**

This is similar to [`v4l2_subdev_call()`](#c-v4l2_subdev_call), except that this version can only be
used for ops that take a subdev state as a parameter. The macro will get the
active state, lock it before calling the op and unlock it after the call.

#### <a id="c-v4l2_subdev_call_state_try"></a>`v4l2_subdev_call_state_try()`

```c
v4l2_subdev_call_state_try(sd, o, f, args...)
```

call an operation of a v4l2_subdev which takes state as a parameter, passing the subdev a newly allocated try state.

**Parameters**

- `sd`: pointer to the [`struct v4l2_subdev`](#c-struct-v4l2_subdev)
- `o`: name of the element at [`struct v4l2_subdev_ops`](#c-struct-v4l2_subdev_ops) that contains **f**.
  Each element there groups a set of callbacks functions.
- `f`: callback function to be called.
  The callback functions are defined in groups, according to
  each element at [`struct v4l2_subdev_ops`](#c-struct-v4l2_subdev_ops).
- `args...`: arguments for **f**.

**Description**

This is similar to [`v4l2_subdev_call_state_active()`](#c-v4l2_subdev_call_state_active), except that as this
version allocates a new state, this is only usable for
V4L2_SUBDEV_FORMAT_TRY use cases.

**Note**

only legacy non-MC drivers may need this macro.

#### <a id="c-v4l2_subdev_has_op"></a>`v4l2_subdev_has_op()`

```c
v4l2_subdev_has_op(sd, o, f)
```

Checks if a subdev defines a certain operation.

**Parameters**

- `sd`: pointer to the [`struct v4l2_subdev`](#c-struct-v4l2_subdev)
- `o`: The group of callback functions in [`struct v4l2_subdev_ops`](#c-struct-v4l2_subdev_ops)
  which **f** is a part of.
- `f`: callback function to be checked for its existence.

#### <a id="c-v4l2_subdev_notify_event"></a>`v4l2_subdev_notify_event()`

```c
void v4l2_subdev_notify_event(struct v4l2_subdev *sd, const struct v4l2_event *ev)
```

Delivers event notification for subdevice

**Parameters**

- `struct v4l2_subdev *sd`: The subdev for which to deliver the event
- `const struct v4l2_event *ev`: The event to deliver

**Description**

Will deliver the specified event to all userspace event listeners which are
subscribed to the v42l subdev event queue as well as to the bridge driver
using the notify callback. The notification type for the notify callback
will be `V4L2_DEVICE_NOTIFY_EVENT`.

#### <a id="c-v4l2_subdev_is_streaming"></a>`v4l2_subdev_is_streaming()`

```c
bool v4l2_subdev_is_streaming(struct v4l2_subdev *sd)
```

Returns if the subdevice is streaming

**Parameters**

- `struct v4l2_subdev *sd`: The subdevice

**Description**

[`v4l2_subdev_is_streaming()`](#c-v4l2_subdev_is_streaming) tells if the subdevice is currently streaming.
"Streaming" here means whether .`s_stream()` or .`enable_streams()` has been
successfully called, and the streaming has not yet been disabled.

If the subdevice implements .`enable_streams()` this function must be called
while holding the active state lock.

---

# Tuner functions and data structures

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for Tuner functions and data structures.

<a id="rst-tuner-functions-and-data-structures"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-enum-tuner_mode"></a>`enum tuner_mode`

Mode of the tuner

**Constants**

- `T_RADIO`: Tuner core will work in radio mode
- `T_ANALOG_TV`: Tuner core will work in analog TV mode

**Description**

Older boards only had a single tuner device, but some devices have a
separate tuner for radio. In any case, the tuner-core needs to know if
the tuner chip(s) will be used in radio mode or analog TV mode, as, on
radio mode, frequencies are specified on a different range than on TV
mode. This enum is used by the tuner core in order to work with the
proper tuner range and eventually use a different tuner chip while in
radio mode.

#### <a id="c-struct-tuner_setup"></a>`struct tuner_setup`

setup the tuner chipsets

**Definition**

```c
struct tuner_setup {
    unsigned short  addr;
    unsigned int    type;
    unsigned int    mode_mask;
    void *config;
    int (*tuner_callback)(void *dev, int component, int cmd, int arg);
};
```

**Members**

- `addr`: I2C address used to control the tuner device/chipset
- `type`: Type of the tuner, as defined at the TUNER_* macros.
  Each different tuner model should have an unique
  identifier.
- `mode_mask`: Mask with the allowed tuner modes: V4L2_TUNER_RADIO,
  V4L2_TUNER_ANALOG_TV and/or V4L2_TUNER_DIGITAL_TV,
  describing if the tuner should be used to support
  Radio, analog TV and/or digital TV.
- `config`: Used to send tuner-specific configuration for complex
  tuners that require extra parameters to be set.
  Only a very few tuners require it and its usage on
  newer tuners should be avoided.
- `tuner_callback`: Some tuners require to call back the bridge driver,
  in order to do some tasks like rising a GPIO at the
  bridge chipset, in order to do things like resetting
  the device.

**Description**

Older boards only had a single tuner device. Nowadays multiple tuner
devices may be present on a single board. Using TUNER_SET_TYPE_ADDR
to pass the tuner_setup structure it is possible to setup each tuner
device in turn.

Since multiple devices may be present it is no longer sufficient to
send a command to a single i2c device. Instead you should broadcast
the command to all i2c devices.

By setting the mode_mask correctly you can select which commands are
accepted by a specific tuner device. For example, set mode_mask to
T_RADIO if the device is a radio-only tuner. That specific tuner will
only accept commands when the tuner is in radio mode and ignore them
when the tuner is set to TV mode.



#### <a id="c-enum-param_type"></a>`enum param_type`

type of the tuner pameters

**Constants**

- `TUNER_PARAM_TYPE_RADIO`: Tuner params are for FM and/or AM radio
- `TUNER_PARAM_TYPE_PAL`: Tuner params are for PAL color TV standard
- `TUNER_PARAM_TYPE_SECAM`: Tuner params are for SECAM color TV standard
- `TUNER_PARAM_TYPE_NTSC`: Tuner params are for NTSC color TV standard
- `TUNER_PARAM_TYPE_DIGITAL`: Tuner params are for digital TV

#### <a id="c-struct-tuner_range"></a>`struct tuner_range`

define the frequencies supported by the tuner

**Definition**

```c
struct tuner_range {
    unsigned short limit;
    unsigned char config;
    unsigned char cb;
};
```

**Members**

- `limit`: Max frequency supported by that range, in 62.5 kHz
  (TV) or 62.5 Hz (Radio), as defined by
  V4L2_TUNER_CAP_LOW.
- `config`: Value of the band switch byte (BB) to setup this mode.
- `cb`: Value of the CB byte to setup this mode.

**Description**

Please notice that digital tuners like xc3028/xc4000/xc5000 don't use
those ranges, as they're defined inside the driver. This is used by
analog tuners that are compatible with the "Philips way" to setup the
tuners. On those devices, the tuner set is done via 4 bytes:

\#) divider byte1 (DB1)
\#) divider byte 2 (DB2)
\#) Control byte (CB)
\#) band switch byte (BB)

Some tuners also have an additional optional Auxiliary byte (AB).

#### <a id="c-struct-tuner_params"></a>`struct tuner_params`

Parameters to be used to setup the tuner. Those are used by drivers/media/tuners/tuner-types.c in order to specify the tuner properties. Most of the parameters are for tuners based on tda9887 IF-PLL multi-standard analog TV/Radio demodulator, with is very common on legacy analog tuners.

**Definition**

```c
struct tuner_params {
    enum param_type type;
    unsigned int cb_first_if_lower_freq:1;
    unsigned int has_tda9887:1;
    unsigned int port1_fm_high_sensitivity:1;
    unsigned int port2_fm_high_sensitivity:1;
    unsigned int fm_gain_normal:1;
    unsigned int intercarrier_mode:1;
    unsigned int port1_active:1;
    unsigned int port2_active:1;
    unsigned int port1_invert_for_secam_lc:1;
    unsigned int port2_invert_for_secam_lc:1;
    unsigned int port1_set_for_fm_mono:1;
    unsigned int default_pll_gating_18:1;
    unsigned int radio_if:2;
    signed int default_top_low:5;
    signed int default_top_mid:5;
    signed int default_top_high:5;
    signed int default_top_secam_low:5;
    signed int default_top_secam_mid:5;
    signed int default_top_secam_high:5;
    u16 iffreq;
    unsigned int count;
    const struct tuner_range *ranges;
};
```

**Members**

- `type`: Type of the tuner parameters, as defined at
  enum param_type. If the tuner supports multiple
  standards, an array should be used, with one
  row per different standard.
- `cb_first_if_lower_freq`: Many Philips-based tuners have a comment in
  their datasheet like
  "For channel selection involving band
  switching, and to ensure smooth tuning to the
  desired channel without causing unnecessary
  charge pump action, it is recommended to
  consider the difference between wanted channel
  frequency and the current channel frequency.
  Unnecessary charge pump action will result
  in very low tuning voltage which may drive the
  oscillator to extreme conditions".
  Set cb_first_if_lower_freq to 1, if this check
  is required for this tuner. I tested this for
  PAL by first setting the TV frequency to
  203 MHz and then switching to 96.6 MHz FM
  radio. The result was static unless the
  control byte was sent first.
- `has_tda9887`: Set to 1 if this tuner uses a tda9887
- `port1_fm_high_sensitivity`: Many Philips tuners use tda9887 PORT1 to select
  the FM radio sensitivity. If this setting is 1,
  then set PORT1 to 1 to get proper FM reception.
- `port2_fm_high_sensitivity`: Some Philips tuners use tda9887 PORT2 to select
  the FM radio sensitivity. If this setting is 1,
  then set PORT2 to 1 to get proper FM reception.
- `fm_gain_normal`: Some Philips tuners use tda9887 cGainNormal to
  select the FM radio sensitivity. If this
  setting is 1, e register will use cGainNormal
  instead of cGainLow.
- `intercarrier_mode`: Most tuners with a tda9887 use QSS mode.
  Some (cheaper) tuners use Intercarrier mode.
  If this setting is 1, then the tuner needs to
  be set to intercarrier mode.
- `port1_active`: This setting sets the default value for PORT1.
  0 means inactive, 1 means active. Note: the
  actual bit value written to the tda9887 is
  inverted. So a 0 here means a 1 in the B6 bit.
- `port2_active`: This setting sets the default value for PORT2.
  0 means inactive, 1 means active. Note: the
  actual bit value written to the tda9887 is
  inverted. So a 0 here means a 1 in the B7 bit.
- `port1_invert_for_secam_lc`: Sometimes PORT1 is inverted when the SECAM-L'
  standard is selected. Set this bit to 1 if this
  is needed.
- `port2_invert_for_secam_lc`: Sometimes PORT2 is inverted when the SECAM-L'
  standard is selected. Set this bit to 1 if this
  is needed.
- `port1_set_for_fm_mono`: Some cards require PORT1 to be 1 for mono Radio
  FM and 0 for stereo.
- `default_pll_gating_18`: Select 18% (or according to datasheet 0%)
  L standard PLL gating, vs the driver default
  of 36%.
- `radio_if`: IF to use in radio mode.  Tuners with a
  separate radio IF filter seem to use 10.7,
  while those without use 33.3 for PAL/SECAM
  tuners and 41.3 for NTSC tuners.
  0 = 10.7, 1 = 33.3, 2 = 41.3
- `default_top_low`: Default tda9887 TOP value in dB for the low
  band. Default is 0. Range: -16:+15
- `default_top_mid`: Default tda9887 TOP value in dB for the mid
  band. Default is 0. Range: -16:+15
- `default_top_high`: Default tda9887 TOP value in dB for the high
  band. Default is 0. Range: -16:+15
- `default_top_secam_low`: Default tda9887 TOP value in dB for SECAM-L/L'
  for the low band. Default is 0. Several tuners
  require a different TOP value for the
  SECAM-L/L' standards. Range: -16:+15
- `default_top_secam_mid`: Default tda9887 TOP value in dB for SECAM-L/L'
  for the mid band. Default is 0. Several tuners
  require a different TOP value for the
  SECAM-L/L' standards. Range: -16:+15
- `default_top_secam_high`: Default tda9887 TOP value in dB for SECAM-L/L'
  for the high band. Default is 0. Several tuners
  require a different TOP value for the
  SECAM-L/L' standards. Range: -16:+15
- `iffreq`: Intermediate frequency (IF) used by the tuner
  on digital mode.
- `count`: Size of the ranges array.
- `ranges`: Array with the frequency ranges supported by
  the tuner.

#### <a id="c-struct-tunertype"></a>`struct tunertype`

describes the known tuners.

**Definition**

```c
struct tunertype {
    char *name;
    unsigned int count;
    const struct tuner_params *params;
    u16 min;
    u16 max;
    u32 stepsize;
    u8 *initdata;
    u8 *sleepdata;
};
```

**Members**

- `name`: string with the tuner's name.
- `count`: size of [`struct tuner_params`](#c-struct-tuner_params) array.
- `params`: pointer to [`struct tuner_params`](#c-struct-tuner_params) array.
- `min`: minimal tuner frequency, in 62.5 kHz step.
  should be multiplied to 16 to convert to MHz.
- `max`: minimal tuner frequency, in 62.5 kHz step.
  Should be multiplied to 16 to convert to MHz.
- `stepsize`: frequency step, in Hz.
- `initdata`: optional byte sequence to initialize the tuner.
- `sleepdata`: optional byte sequence to power down the tuner.

---

# Hauppauge TV EEPROM functions and data structures

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for Hauppauge TV EEPROM functions and data structures.

<a id="rst-hauppauge-tv-eeprom-functions-and-data-structures"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-enum-tveeprom_audio_processor"></a>`enum tveeprom_audio_processor`

Specifies the type of audio processor used on a Hauppauge device.

**Constants**

- `TVEEPROM_AUDPROC_NONE`: No audio processor present
- `TVEEPROM_AUDPROC_INTERNAL`: The audio processor is internal to the
  video processor
- `TVEEPROM_AUDPROC_MSP`: The audio processor is a MSPXXXX device
- `TVEEPROM_AUDPROC_OTHER`: The audio processor is another device

#### <a id="c-struct-tveeprom"></a>`struct tveeprom`

Contains the fields parsed from Hauppauge eeproms

**Definition**

```c
struct tveeprom {
    u32 has_radio;
    u32 has_ir;
    u32 has_MAC_address;
    u32 tuner_type;
    u32 tuner_formats;
    u32 tuner_hauppauge_model;
    u32 tuner2_type;
    u32 tuner2_formats;
    u32 tuner2_hauppauge_model;
    u32 audio_processor;
    u32 decoder_processor;
    u32 model;
    u32 revision;
    u32 serial_number;
    char rev_str[5];
    u8 MAC_address[ETH_ALEN];
};
```

**Members**

- `has_radio`: 1 if the device has radio; 0 otherwise.
- `has_ir`: If has_ir == 0, then it is unknown what the IR
  capabilities are. Otherwise:
  bit 0) 1 (= IR capabilities are known);
  bit 1) IR receiver present;
  bit 2) IR transmitter (blaster) present.
- `has_MAC_address`: 0: no MAC, 1: MAC present, 2: unknown.
- `tuner_type`: type of the tuner (TUNER_*, as defined at
  include/media/tuner.h).
- `tuner_formats`: Supported analog TV standards (V4L2_STD_*).
- `tuner_hauppauge_model`: Hauppauge's code for the device model number.
- `tuner2_type`: type of the second tuner (TUNER_*, as defined
  at include/media/tuner.h).
- `tuner2_formats`: Tuner 2 supported analog TV standards
  (V4L2_STD_*).
- `tuner2_hauppauge_model`: tuner 2 Hauppauge's code for the device model
  number.
- `audio_processor`: analog audio decoder, as defined by enum
  tveeprom_audio_processor.
- `decoder_processor`: Hauppauge's code for the decoder chipset.
  Unused by the drivers, as they probe the
  decoder based on the PCI or USB ID.
- `model`: Hauppauge's model number
- `revision`: Card revision number
- `serial_number`: Card's serial number
- `rev_str`: Card revision converted to number
- `MAC_address`: MAC address for the network interface

#### <a id="c-tveeprom_hauppauge_analog"></a>`tveeprom_hauppauge_analog()`

```c
void tveeprom_hauppauge_analog(struct tveeprom *tvee, unsigned char *eeprom_data)
```

Fill struct tveeprom using the contents of the eeprom previously filled at **eeprom_data** field.

**Parameters**

- `struct tveeprom *tvee`: Struct to where the eeprom parsed data will be filled;
- `unsigned char *eeprom_data`: Array with the contents of the eeprom_data. It should
  contain 256 bytes filled with the contents of the
  eeprom read from the Hauppauge device.

#### <a id="c-tveeprom_read"></a>`tveeprom_read()`

```c
int tveeprom_read(struct i2c_client *c, unsigned char *eedata, int len)
```

Reads the contents of the eeprom found at the Hauppauge devices.

**Parameters**

- `struct i2c_client *c`: I2C client struct
- `unsigned char *eedata`: Array where the eeprom content will be stored.
- `int len`: Size of **eedata** array. If the eeprom content will be latter
  be parsed by [`tveeprom_hauppauge_analog()`](#c-tveeprom_hauppauge_analog), len should be, at
  least, 256.

---

# V4L2 videobuf2 functions and data structures

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for V4L2 videobuf2 functions and data structures.

<a id="rst-v4l2-videobuf2-functions-and-data-structures"></a>
<a id="rst-vb2-framework"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-enum-vb2_memory"></a>`enum vb2_memory`

type of memory model used to make the buffers visible on userspace.

**Constants**

- `VB2_MEMORY_UNKNOWN`: Buffer status is unknown or it is not used yet on
  userspace.
- `VB2_MEMORY_MMAP`: The buffers are allocated by the Kernel and it is
  memory mapped via `mmap()` ioctl. This model is
  also used when the user is using the buffers via
  `read()` or `write()` system calls.
- `VB2_MEMORY_USERPTR`: The buffers was allocated in userspace and it is
  memory mapped via `mmap()` ioctl.
- `VB2_MEMORY_DMABUF`: The buffers are passed to userspace via DMA buffer.

#### <a id="c-struct-vb2_mem_ops"></a>`struct vb2_mem_ops`

memory handling/memory allocator operations.

**Definition**

```c
struct vb2_mem_ops {
    void *(*alloc)(struct vb2_buffer *vb, struct device *dev, unsigned long size);
    void (*put)(void *buf_priv);
    struct dma_buf *(*get_dmabuf)(struct vb2_buffer *vb, void *buf_priv, unsigned long flags);
    void *(*get_userptr)(struct vb2_buffer *vb, struct device *dev, unsigned long vaddr, unsigned long size);
    void (*put_userptr)(void *buf_priv);
    void (*prepare)(void *buf_priv);
    void (*finish)(void *buf_priv);
    void *(*attach_dmabuf)(struct vb2_buffer *vb, struct device *dev, struct dma_buf *dbuf, unsigned long size);
    void (*detach_dmabuf)(void *buf_priv);
    int (*map_dmabuf)(void *buf_priv);
    void (*unmap_dmabuf)(void *buf_priv);
    void *(*vaddr)(struct vb2_buffer *vb, void *buf_priv);
    void *(*cookie)(struct vb2_buffer *vb, void *buf_priv);
    unsigned int    (*num_users)(void *buf_priv);
    int (*mmap)(void *buf_priv, struct vm_area_struct *vma);
};
```

**Members**

- `alloc`: allocate video memory and, optionally, allocator private data,
  return [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on failure or a pointer to allocator private,
  per-buffer data on success; the returned private structure
  will then be passed as **buf_priv** argument to other ops in this
  structure. The size argument to this function shall be
  *page aligned*.
- `put`: inform the allocator that the buffer will no longer be used;
  usually will result in the allocator freeing the buffer (if
  no other users of this buffer are present); the **buf_priv**
  argument is the allocator private per-buffer structure
  previously returned from the alloc callback.
- `get_dmabuf`: acquire userspace memory for a hardware operation; used for
  DMABUF memory types.
- `get_userptr`: acquire userspace memory for a hardware operation; used for
  USERPTR memory types; vaddr is the address passed to the
  videobuf2 layer when queuing a video buffer of USERPTR type;
  should return an allocator private per-buffer structure
  associated with the buffer on success, [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on failure;
  the returned private structure will then be passed as **buf_priv**
  argument to other ops in this structure.
- `put_userptr`: inform the allocator that a USERPTR buffer will no longer
  be used.
- `prepare`: called every time the buffer is passed from userspace to the
  driver, useful for cache synchronisation, optional.
- `finish`: called every time the buffer is passed back from the driver
  to the userspace, also optional.
- `attach_dmabuf`: attach a shared [`struct dma_buf`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_buf) for a hardware operation;
  used for DMABUF memory types; dev is the alloc device
  dbuf is the shared dma_buf; returns [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on failure;
  allocator private per-buffer structure on success;
  this needs to be used for further accesses to the buffer.
- `detach_dmabuf`: inform the exporter of the buffer that the current DMABUF
  buffer is no longer used; the **buf_priv** argument is the
  allocator private per-buffer structure previously returned
  from the attach_dmabuf callback.
- `map_dmabuf`: request for access to the dmabuf from allocator; the allocator
  of dmabuf is informed that this driver is going to use the
  dmabuf.
- `unmap_dmabuf`: releases access control to the dmabuf - allocator is notified
  that this driver is done using the dmabuf for now.
- `vaddr`: return a kernel virtual address to a given memory buffer
  associated with the passed private structure or NULL if no
  such mapping exists.
- `cookie`: return allocator specific cookie for a given memory buffer
  associated with the passed private structure or NULL if not
  available.
- `num_users`: return the current number of users of a memory buffer;
  return 1 if the videobuf2 layer (or actually the driver using
  it) is the only user.
- `mmap`: setup a userspace mapping for a given memory buffer under
  the provided virtual memory region.

**Description**

Those operations are used by the videobuf2 core to implement the memory
handling/memory allocators for each type of supported streaming I/O method.

> [!NOTE]
> \#) Required ops for USERPTR types: get_userptr, put_userptr.
>
> \#) Required ops for MMAP types: alloc, put, num_users, mmap.
>
> \#) Required ops for read/write access types: alloc, put, num_users, vaddr.
>
> - #) Required ops for DMABUF types: attach_dmabuf, detach_dmabuf,
>
>   map_dmabuf, unmap_dmabuf.

#### <a id="c-struct-vb2_plane"></a>`struct vb2_plane`

plane information.

**Definition**

```c
struct vb2_plane {
    void *mem_priv;
    struct dma_buf          *dbuf;
    unsigned int            dbuf_mapped;
    bool dbuf_duplicated;
    unsigned int            bytesused;
    unsigned int            length;
    unsigned int            min_length;
    union {
        unsigned int    offset;
        unsigned long   userptr;
        int fd;
    } m;
    unsigned int            data_offset;
};
```

**Members**

- `mem_priv`: private data with this plane.
- `dbuf`: dma_buf - shared buffer object.
- `dbuf_mapped`: flag to show whether dbuf is mapped or not
- `dbuf_duplicated`: boolean to show whether dbuf is duplicated with a
  previous plane of the buffer.
- `bytesused`: number of bytes occupied by data in the plane (payload).
- `length`: size of this plane (NOT the payload) in bytes. The maximum
  valid size is MAX_UINT - PAGE_SIZE.
- `min_length`: minimum required size of this plane (NOT the payload) in bytes.
  **length** is always greater or equal to **min_length**, and like
  **length**, it is limited to MAX_UINT - PAGE_SIZE.
- `m`: Union with memtype-specific data.
- `m.offset`: when memory in the associated struct vb2_buffer is
  `VB2_MEMORY_MMAP`, equals the offset from the start of
  the device memory for this plane (or is a "cookie" that
  should be passed to `mmap()` called on the video node).
- `m.userptr`: when memory is `VB2_MEMORY_USERPTR`, a userspace pointer
  pointing to this plane.
- `m.fd`: when memory is `VB2_MEMORY_DMABUF`, a userspace file
  descriptor associated with this plane.
- `data_offset`: offset in the plane to the start of data; usually 0,
  unless there is a header in front of the data.

**Description**

Should contain enough information to be able to cover all the fields
of [`struct v4l2_plane`](/kernel/userspace/userspace-api/media-v4l/buffer.md#c-v4l2_plane) at videodev2.h.

#### <a id="c-enum-vb2_io_modes"></a>`enum vb2_io_modes`

queue access methods.

**Constants**

- `VB2_MMAP`: driver supports MMAP with streaming API.
- `VB2_USERPTR`: driver supports USERPTR with streaming API.
- `VB2_READ`: driver supports `read()` style access.
- `VB2_WRITE`: driver supports `write()` style access.
- `VB2_DMABUF`: driver supports DMABUF with streaming API.

#### <a id="c-enum-vb2_buffer_state"></a>`enum vb2_buffer_state`

current video buffer state.

**Constants**

- `VB2_BUF_STATE_DEQUEUED`: buffer under userspace control.
- `VB2_BUF_STATE_IN_REQUEST`: buffer is queued in media request.
- `VB2_BUF_STATE_PREPARING`: buffer is being prepared in videobuf2.
- `VB2_BUF_STATE_QUEUED`: buffer queued in videobuf2, but not in driver.
- `VB2_BUF_STATE_ACTIVE`: buffer queued in driver and possibly used
  in a hardware operation.
- `VB2_BUF_STATE_DONE`: buffer returned from driver to videobuf2, but
  not yet dequeued to userspace.
- `VB2_BUF_STATE_ERROR`: same as above, but the operation on the buffer
  has ended with an error, which will be reported
  to the userspace when it is dequeued.

#### <a id="c-struct-vb2_buffer"></a>`struct vb2_buffer`

represents a video buffer.

**Definition**

```c
struct vb2_buffer {
    struct vb2_queue        *vb2_queue;
    unsigned int            index;
    unsigned int            type;
    unsigned int            memory;
    unsigned int            num_planes;
    u64 timestamp;
    struct media_request    *request;
    struct media_request_object     req_obj;
};
```

**Members**

- `vb2_queue`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with the queue to
  which this driver belongs.
- `index`: id number of the buffer.
- `type`: buffer type.
- `memory`: the method, in which the actual data is passed.
- `num_planes`: number of planes in the buffer
  on an internal driver queue.
- `timestamp`: frame timestamp in ns.
- `request`: the request this buffer is associated with.
- `req_obj`: used to bind this buffer to a request. This
  request object has a refcount.

#### <a id="c-struct-vb2_ops"></a>`struct vb2_ops`

driver-specific callbacks.

**Definition**

```c
struct vb2_ops {
    int (*queue_setup)(struct vb2_queue *q, unsigned int *num_buffers, unsigned int *num_planes, unsigned int sizes[], struct device *alloc_devs[]);
    int (*buf_out_validate)(struct vb2_buffer *vb);
    int (*buf_init)(struct vb2_buffer *vb);
    int (*buf_prepare)(struct vb2_buffer *vb);
    void (*buf_finish)(struct vb2_buffer *vb);
    void (*buf_cleanup)(struct vb2_buffer *vb);
    int (*prepare_streaming)(struct vb2_queue *q);
    int (*start_streaming)(struct vb2_queue *q, unsigned int count);
    void (*stop_streaming)(struct vb2_queue *q);
    void (*unprepare_streaming)(struct vb2_queue *q);
    void (*buf_queue)(struct vb2_buffer *vb);
    void (*buf_request_complete)(struct vb2_buffer *vb);
};
```

**Members**

- `queue_setup`: called from `VIDIOC_REQBUFS()` and `VIDIOC_CREATE_BUFS()`
  handlers before memory allocation. It can be called
  twice: if the original number of requested buffers
  could not be allocated, then it will be called a
  second time with the actually allocated number of
  buffers to verify if that is OK.
  The driver should return the required number of buffers
  in \*num_buffers, the required number of planes per
  buffer in \*num_planes, the size of each plane should be
  set in the sizes\\[\\] array and optional per-plane
  allocator specific device in the alloc_devs\\[\\] array.
  When called from `VIDIOC_REQBUFS()`, \*num_planes == 0,
  the driver has to use the currently configured format to
  determine the plane sizes and \*num_buffers is the total
  number of buffers that are being allocated. When called
  from `VIDIOC_CREATE_BUFS()`, \*num_planes != 0 and it
  describes the requested number of planes and sizes\\[\\]
  contains the requested plane sizes. In this case
  \*num_buffers are being allocated additionally to
  the buffers already allocated. If either \*num_planes
  or the requested sizes are invalid callback must return `-EINVAL`.
- `buf_out_validate`: called when the output buffer is prepared or queued
  to a request; drivers can use this to validate
  userspace-provided information; this is required only
  for OUTPUT queues.
- `buf_init`: called once after allocating a buffer (in MMAP case)
  or after acquiring a new USERPTR buffer; drivers may
  perform additional buffer-related initialization;
  initialization failure (return != 0) will prevent
  queue setup from completing successfully; optional.
- `buf_prepare`: called every time the buffer is queued from userspace
  and from the `VIDIOC_PREPARE_BUF()` ioctl; drivers may
  perform any initialization required before each
  hardware operation in this callback; drivers can
  access/modify the buffer here as it is still synced for
  the CPU; drivers that support `VIDIOC_CREATE_BUFS()` must
  also validate the buffer size; if an error is returned,
  the buffer will not be queued in driver; optional.
- `buf_finish`: called before every dequeue of the buffer back to
  userspace; the buffer is synced for the CPU, so drivers
  can access/modify the buffer contents; drivers may
  perform any operations required before userspace
  accesses the buffer; optional. The buffer state can be
  one of the following: `DONE` and `ERROR` occur while
  streaming is in progress, and the `PREPARED` state occurs
  when the queue has been canceled and all pending
  buffers are being returned to their default `DEQUEUED`
  state. Typically you only have to do something if the
  state is `VB2_BUF_STATE_DONE`, since in all other cases
  the buffer contents will be ignored anyway.
- `buf_cleanup`: called once before the buffer is freed; drivers may
  perform any additional cleanup; optional.
- `prepare_streaming`: called once to prepare for 'streaming' state; this is
  where validation can be done to verify everything is
  okay and streaming resources can be claimed. It is
  called when the VIDIOC_STREAMON ioctl is called. The
  actual streaming starts when **start_streaming** is called.
  Optional.
- `start_streaming`: called once to enter 'streaming' state; the driver may
  receive buffers with **buf_queue** callback
  before **start_streaming** is called; the driver gets the
  number of already queued buffers in count parameter;
  driver can return an error if hardware fails, in that
  case all buffers that have been already given by
  the **buf_queue** callback are to be returned by the driver
  by calling [`vb2_buffer_done()`](#c-vb2_buffer_done) with `VB2_BUF_STATE_QUEUED`.
  If you need a minimum number of buffers before you can
  start streaming, then set
  [`vb2_queue->min_queued_buffers`](#c-struct-vb2_queue). If that is non-zero
  then **start_streaming** won't be called until at least
  that many buffers have been queued up by userspace.
- `stop_streaming`: called when 'streaming' state must be disabled; driver
  should stop any DMA transactions or wait until they
  finish and give back all buffers it got from `buf_queue`
  callback by calling [`vb2_buffer_done()`](#c-vb2_buffer_done) with either
  `VB2_BUF_STATE_DONE` or `VB2_BUF_STATE_ERROR`; may use
  [`vb2_wait_for_all_buffers()`](#c-vb2_wait_for_all_buffers) function
- `unprepare_streaming`: called as counterpart to **prepare_streaming**; any claimed
  streaming resources can be released here. It is
  called when the VIDIOC_STREAMOFF ioctls is called or
  when the streaming filehandle is closed. Optional.
- `buf_queue`: passes buffer vb to the driver; driver may start
  hardware operation on this buffer; driver should give
  the buffer back by calling [`vb2_buffer_done()`](#c-vb2_buffer_done) function;
  it is always called after calling `VIDIOC_STREAMON()`
  ioctl; might be called before **start_streaming** callback
  if user pre-queued buffers before calling
  `VIDIOC_STREAMON()`.
- `buf_request_complete`: a buffer that was never queued to the driver but is
  associated with a queued request was canceled.
  The driver will have to mark associated objects in the
  request as completed; required if requests are
  supported.

**Description**

These operations are not called from interrupt context except where
mentioned specifically.

#### <a id="c-struct-vb2_buf_ops"></a>`struct vb2_buf_ops`

driver-specific callbacks.

**Definition**

```c
struct vb2_buf_ops {
    int (*verify_planes_array)(struct vb2_buffer *vb, const void *pb);
    void (*init_buffer)(struct vb2_buffer *vb);
    void (*fill_user_buffer)(struct vb2_buffer *vb, void *pb);
    int (*fill_vb2_buffer)(struct vb2_buffer *vb, struct vb2_plane *planes);
    void (*copy_timestamp)(struct vb2_buffer *vb, const void *pb);
};
```

**Members**

- `verify_planes_array`: Verify that a given user space structure contains
  enough planes for the buffer. This is called
  for each dequeued buffer.
- `init_buffer`: given a [`vb2_buffer`](#c-struct-vb2_buffer) initialize the extra data after
  struct vb2_buffer.
  For V4L2 this is a [`struct vb2_v4l2_buffer`](#c-struct-vb2_v4l2_buffer).
- `fill_user_buffer`: given a [`vb2_buffer`](#c-struct-vb2_buffer) fill in the userspace structure.
  For V4L2 this is a [`struct v4l2_buffer`](/kernel/userspace/userspace-api/media-v4l/buffer.md#c-v4l2_buffer).
- `fill_vb2_buffer`: given a userspace structure, fill in the [`vb2_buffer`](#c-struct-vb2_buffer).
  If the userspace structure is invalid, then this op
  will return an error.
- `copy_timestamp`: copy the timestamp from a userspace structure to
  the [`struct vb2_buffer`](#c-struct-vb2_buffer).

#### <a id="c-struct-vb2_queue"></a>`struct vb2_queue`

a videobuf2 queue.

**Definition**

```c
struct vb2_queue {
    unsigned int                    type;
    unsigned int                    io_modes;
    struct device                   *dev;
    unsigned long                   dma_attrs;
    unsigned int                    bidirectional:1;
    unsigned int                    fileio_read_once:1;
    unsigned int                    fileio_write_immediately:1;
    unsigned int                    allow_zero_bytesused:1;
    unsigned int               quirk_poll_must_check_waiting_for_buffers:1;
    unsigned int                    supports_requests:1;
    unsigned int                    requires_requests:1;
    unsigned int                    uses_qbuf:1;
    unsigned int                    uses_requests:1;
    unsigned int                    allow_cache_hints:1;
    unsigned int                    non_coherent_mem:1;
    struct mutex                    *lock;
    void *owner;
    const struct vb2_ops            *ops;
    const struct vb2_mem_ops        *mem_ops;
    const struct vb2_buf_ops        *buf_ops;
    void *drv_priv;
    u32 subsystem_flags;
    unsigned int                    buf_struct_size;
    u32 timestamp_flags;
    gfp_t gfp_flags;
    u32 min_queued_buffers;
    u32 min_reqbufs_allocation;
    struct device                   *alloc_devs[VB2_MAX_PLANES];
};
```

**Members**

- `type`: private buffer type whose content is defined by the vb2-core
  caller. For example, for V4L2, it should match
  the types defined on [`enum v4l2_buf_type`](/kernel/userspace/userspace-api/media-v4l/buffer.md#c-v4l2_buf_type).
- `io_modes`: supported io methods (see [`enum vb2_io_modes`](#c-enum-vb2_io_modes)).
- `dev`: device to use for the default allocation context if the driver
  doesn't fill in the **alloc_devs** array.
- `dma_attrs`: DMA attributes to use for the DMA.
- `bidirectional`: when this flag is set the DMA direction for the buffers of
  this queue will be overridden with `DMA_BIDIRECTIONAL` direction.
  This is useful in cases where the hardware (firmware) writes to
  a buffer which is mapped as read (`DMA_TO_DEVICE`), or reads from
  buffer which is mapped for write (`DMA_FROM_DEVICE`) in order
  to satisfy some internal hardware restrictions or adds a padding
  needed by the processing algorithm. In case the DMA mapping is
  not bidirectional but the hardware (firmware) trying to access
  the buffer (in the opposite direction) this could lead to an
  IOMMU protection faults.
- `fileio_read_once`: report EOF after reading the first buffer
- `fileio_write_immediately`: queue buffer after each `write()` call
- `allow_zero_bytesused`: allow bytesused == 0 to be passed to the driver
- `quirk_poll_must_check_waiting_for_buffers`: Return `EPOLLERR` at poll when QBUF
  has not been called. This is a vb1 idiom that has been adopted
  also by vb2.
- `supports_requests`: this queue supports the Request API.
- `requires_requests`: this queue requires the Request API. If this is set to 1,
  then supports_requests must be set to 1 as well.
- `uses_qbuf`: qbuf was used directly for this queue. Set to 1 the first
  time this is called. Set to 0 when the queue is canceled.
  If this is 1, then you cannot queue buffers from a request.
- `uses_requests`: requests are used for this queue. Set to 1 the first time
  a request is queued. Set to 0 when the queue is canceled.
  If this is 1, then you cannot queue buffers directly.
- `allow_cache_hints`: when set user-space can pass cache management hints in
  order to skip cache flush/invalidation on ->`prepare()` or/and
  ->`finish()`.
- `non_coherent_mem`: when set queue will attempt to allocate buffers using
  non-coherent memory.
- `lock`: pointer to a mutex that protects the [`struct vb2_queue`](#c-struct-vb2_queue). The
  driver must set this to a mutex to let the v4l2 core serialize
  the queuing ioctls. This lock is used when waiting for a new
  buffer to arrive: the lock is released, we wait for the new
  buffer, and then retaken.
- `owner`: The filehandle that 'owns' the buffers, i.e. the filehandle
  that called reqbufs, create_buffers or started fileio.
  This field is not used by the videobuf2 core API, but it allows
  drivers to easily associate an owner filehandle with the queue.
- `ops`: driver-specific callbacks
- `mem_ops`: memory allocator specific callbacks
- `buf_ops`: callbacks to deliver buffer information.
  between user-space and kernel-space.
- `drv_priv`: driver private data.
- `subsystem_flags`: Flags specific to the subsystem (V4L2/DVB/etc.). Not used
  by the vb2 core.
- `buf_struct_size`: size of the driver-specific buffer structure;
  "0" indicates the driver doesn't want to use a custom buffer
  structure type. In that case a subsystem-specific struct
  will be used (in the case of V4L2 that is
  `sizeof(struct vb2_v4l2_buffer)`). The first field of the
  driver-specific buffer structure must be the subsystem-specific
  struct (vb2_v4l2_buffer in the case of V4L2).
- `timestamp_flags`: Timestamp flags; `V4L2_BUF_FLAG_TIMESTAMP_*` and
  `V4L2_BUF_FLAG_TSTAMP_SRC_*`
- `gfp_flags`: additional gfp flags used when allocating the buffers.
  Typically this is 0, but it may be e.g. `GFP_DMA` or `__GFP_DMA32`
  to force the buffer allocation to a specific memory zone.
- `min_queued_buffers`: the minimum number of queued buffers needed before
  **start_streaming** can be called. Used when a DMA engine
  cannot be started unless at least this number of buffers
  have been queued into the driver.
  VIDIOC_REQBUFS will ensure at least **min_queued_buffers** + 1
  buffers will be allocated. Note that VIDIOC_CREATE_BUFS will not
  modify the requested buffer count.
- `min_reqbufs_allocation`: the minimum number of buffers to be allocated when
  calling VIDIOC_REQBUFS. Note that VIDIOC_CREATE_BUFS will *not*
  modify the requested buffer count and does not use this field.
  Drivers can set this if there has to be a certain number of
  buffers available for the hardware to work effectively.
  This allows calling VIDIOC_REQBUFS with a buffer count of 1 and
  it will be automatically adjusted to a workable buffer count.
  If set, then **min_reqbufs_allocation** must be larger than
  **min_queued_buffers** + 1.
  If this field is > 3, then it is highly recommended that the
  driver implements the V4L2_CID_MIN_BUFFERS_FOR_CAPTURE/OUTPUT
  control.
- `alloc_devs`: [`struct device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) memory type/allocator-specific per-plane device

#### <a id="c-vb2_queue_allows_cache_hints"></a>`vb2_queue_allows_cache_hints()`

```c
bool vb2_queue_allows_cache_hints(struct vb2_queue *q)
```

Return true if the queue allows cache and memory consistency hints.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue

#### <a id="c-vb2_plane_vaddr"></a>`vb2_plane_vaddr()`

```c
void * vb2_plane_vaddr(struct vb2_buffer *vb, unsigned int plane_no)
```

Return a kernel virtual address of a given plane.

**Parameters**

- `struct vb2_buffer *vb`: pointer to [`struct vb2_buffer`](#c-struct-vb2_buffer) to which the plane in
  question belongs to.
- `unsigned int plane_no`: plane number for which the address is to be returned.

**Description**

This function returns a kernel virtual address of a given plane if
such a mapping exist, NULL otherwise.

#### <a id="c-vb2_plane_cookie"></a>`vb2_plane_cookie()`

```c
void * vb2_plane_cookie(struct vb2_buffer *vb, unsigned int plane_no)
```

Return allocator specific cookie for the given plane.

**Parameters**

- `struct vb2_buffer *vb`: pointer to [`struct vb2_buffer`](#c-struct-vb2_buffer) to which the plane in
  question belongs to.
- `unsigned int plane_no`: plane number for which the cookie is to be returned.

**Description**

This function returns an allocator specific cookie for a given plane if
available, NULL otherwise. The allocator should provide some simple static
inline function, which would convert this cookie to the allocator specific
type that can be used directly by the driver to access the buffer. This can
be for example physical address, pointer to scatter list or IOMMU mapping.

#### <a id="c-vb2_buffer_done"></a>`vb2_buffer_done()`

```c
void vb2_buffer_done(struct vb2_buffer *vb, enum vb2_buffer_state state)
```

inform videobuf2 that an operation on a buffer is finished.

**Parameters**

- `struct vb2_buffer *vb`: pointer to [`struct vb2_buffer`](#c-struct-vb2_buffer) to be used.
- `enum vb2_buffer_state state`: state of the buffer, as defined by [`enum vb2_buffer_state`](#c-enum-vb2_buffer_state).
  Either `VB2_BUF_STATE_DONE` if the operation finished
  successfully, `VB2_BUF_STATE_ERROR` if the operation finished
  with an error or `VB2_BUF_STATE_QUEUED`.

**Description**

This function should be called by the driver after a hardware operation on
a buffer is finished and the buffer may be returned to userspace. The driver
cannot use this buffer anymore until it is queued back to it by videobuf
by the means of [`vb2_ops->buf_queue`](#c-struct-vb2_ops) callback. Only buffers previously queued
to the driver by [`vb2_ops->buf_queue`](#c-struct-vb2_ops) can be passed to this function.

While streaming a buffer can only be returned in state DONE or ERROR.
The [`vb2_ops->start_streaming`](#c-struct-vb2_ops) op can also return them in case the DMA engine
cannot be started for some reason. In that case the buffers should be
returned with state QUEUED to put them back into the queue.

#### <a id="c-vb2_discard_done"></a>`vb2_discard_done()`

```c
void vb2_discard_done(struct vb2_queue *q)
```

discard all buffers marked as DONE.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.

**Description**

This function is intended to be used with suspend/resume operations. It
discards all 'done' buffers as they would be too old to be requested after
resume.

Drivers must stop the hardware and synchronize with interrupt handlers and/or
delayed works before calling this function to make sure no buffer will be
touched by the driver and/or hardware.

#### <a id="c-vb2_wait_for_all_buffers"></a>`vb2_wait_for_all_buffers()`

```c
int vb2_wait_for_all_buffers(struct vb2_queue *q)
```

wait until all buffers are given back to vb2.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.

**Description**

This function will wait until all buffers that have been given to the driver
by [`vb2_ops->buf_queue`](#c-struct-vb2_ops) are given back to vb2 with [`vb2_buffer_done()`](#c-vb2_buffer_done).
It is intended to be called with all locks taken, for example from
[`vb2_ops->stop_streaming`](#c-struct-vb2_ops) callback.

#### <a id="c-vb2_core_querybuf"></a>`vb2_core_querybuf()`

```c
void vb2_core_querybuf(struct vb2_queue *q, struct vb2_buffer *vb, void *pb)
```

query video buffer information.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `struct vb2_buffer *vb`: pointer to struct [`vb2_buffer`](#c-struct-vb2_buffer).
- `void *pb`: buffer struct passed from userspace.

**Description**

Videobuf2 core helper to implement `VIDIOC_QUERYBUF()` operation. It is called
internally by VB2 by an API-specific handler, like `videobuf2-v4l2.h`.

The passed buffer should have been verified.

This function fills the relevant information for the userspace.

**Return**

returns zero on success; an error code otherwise.

#### <a id="c-vb2_core_reqbufs"></a>`vb2_core_reqbufs()`

```c
int vb2_core_reqbufs(struct vb2_queue *q, enum vb2_memory memory, unsigned int flags, unsigned int *count)
```

Initiate streaming.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `enum vb2_memory memory`: memory type, as defined by [`enum vb2_memory`](#c-enum-vb2_memory).
- `unsigned int flags`: auxiliary queue/buffer management flags. Currently, the only
  used flag is `V4L2_MEMORY_FLAG_NON_COHERENT`.
- `unsigned int *count`: requested buffer count.

**Description**

Videobuf2 core helper to implement `VIDIOC_REQBUF()` operation. It is called
internally by VB2 by an API-specific handler, like `videobuf2-v4l2.h`.

This function:

\#) verifies streaming parameters passed from the userspace;
\#) sets up the queue;
\#) negotiates number of buffers and planes per buffer with the driver
to be used during streaming;
\#) allocates internal buffer structures ([`struct vb2_buffer`](#c-struct-vb2_buffer)), according to
the agreed parameters;
\#) for MMAP memory type, allocates actual video memory, using the
memory handling/allocation routines provided during queue initialization.

If req->count is 0, all the memory will be freed instead.

If the queue has been allocated previously by a previous [`vb2_core_reqbufs()`](#c-vb2_core_reqbufs)
call and the queue is not busy, memory will be reallocated.

**Return**

returns zero on success; an error code otherwise.

#### <a id="c-vb2_core_create_bufs"></a>`vb2_core_create_bufs()`

```c
int vb2_core_create_bufs(struct vb2_queue *q, enum vb2_memory memory, unsigned int flags, unsigned int *count, unsigned int requested_planes, const unsigned int requested_sizes[], unsigned int *first_index)
```

Allocate buffers and any required auxiliary structs

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `enum vb2_memory memory`: memory type, as defined by [`enum vb2_memory`](#c-enum-vb2_memory).
- `unsigned int flags`: auxiliary queue/buffer management flags.
- `unsigned int *count`: requested buffer count.
- `unsigned int requested_planes`: number of planes requested.
- `const unsigned int requested_sizes[]`: array with the size of the planes.
- `unsigned int *first_index`: index of the first created buffer, all allocated buffers have
  indices in the range \[first_index..first_index+count-1\]

**Description**

Videobuf2 core helper to implement `VIDIOC_CREATE_BUFS()` operation. It is
called internally by VB2 by an API-specific handler, like
`videobuf2-v4l2.h`.

This function:

\#) verifies parameter sanity;
\#) calls the [`vb2_ops->queue_setup`](#c-struct-vb2_ops) queue operation;
\#) performs any necessary memory allocations.

**Return**

returns zero on success; an error code otherwise.

#### <a id="c-vb2_core_prepare_buf"></a>`vb2_core_prepare_buf()`

```c
int vb2_core_prepare_buf(struct vb2_queue *q, struct vb2_buffer *vb, void *pb)
```

Pass ownership of a buffer from userspace to the kernel.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `struct vb2_buffer *vb`: pointer to struct [`vb2_buffer`](#c-struct-vb2_buffer).
- `void *pb`: buffer structure passed from userspace to
  [`v4l2_ioctl_ops->vidioc_prepare_buf`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) handler in driver.

**Description**

Videobuf2 core helper to implement `VIDIOC_PREPARE_BUF()` operation. It is
called internally by VB2 by an API-specific handler, like
`videobuf2-v4l2.h`.

The passed buffer should have been verified.

This function calls vb2_ops->buf_prepare callback in the driver
(if provided), in which driver-specific buffer initialization can
be performed.

**Return**

returns zero on success; an error code otherwise.

#### <a id="c-vb2_core_remove_bufs"></a>`vb2_core_remove_bufs()`

```c
int vb2_core_remove_bufs(struct vb2_queue *q, unsigned int start, unsigned int count)
```

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `unsigned int start`: first index of the range of buffers to remove.
- `unsigned int count`: number of buffers to remove.

**Return**

returns zero on success; an error code otherwise.

#### <a id="c-vb2_core_qbuf"></a>`vb2_core_qbuf()`

```c
int vb2_core_qbuf(struct vb2_queue *q, struct vb2_buffer *vb, void *pb, struct media_request *req)
```

Queue a buffer from userspace

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `struct vb2_buffer *vb`: pointer to struct [`vb2_buffer`](#c-struct-vb2_buffer).
- `void *pb`: buffer structure passed from userspace to
  v4l2_ioctl_ops->vidioc_qbuf handler in driver
- `struct media_request *req`: pointer to [`struct media_request`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_request), may be NULL.

**Description**

Videobuf2 core helper to implement `VIDIOC_QBUF()` operation. It is called
internally by VB2 by an API-specific handler, like `videobuf2-v4l2.h`.

This function:

- #) If **req** is non-NULL, then the buffer will be bound to this

  media request and it returns. The buffer will be prepared and
  queued to the driver (i.e. the next two steps) when the request
  itself is queued.
- #) if necessary, calls [`vb2_ops->buf_prepare`](#c-struct-vb2_ops) callback in the driver

  (if provided), in which driver-specific buffer initialization can
  be performed;
- #) if streaming is on, queues the buffer in driver by the means of

  [`vb2_ops->buf_queue`](#c-struct-vb2_ops) callback for processing.

**Return**

returns zero on success; an error code otherwise.

#### <a id="c-vb2_core_dqbuf"></a>`vb2_core_dqbuf()`

```c
int vb2_core_dqbuf(struct vb2_queue *q, unsigned int *pindex, void *pb, bool nonblocking)
```

Dequeue a buffer to the userspace

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue
- `unsigned int *pindex`: pointer to the buffer index. May be NULL
- `void *pb`: buffer structure passed from userspace to
  v4l2_ioctl_ops->vidioc_dqbuf handler in driver.
- `bool nonblocking`: if true, this call will not sleep waiting for a buffer if no
  buffers ready for dequeuing are present. Normally the driver
  would be passing (file->f_flags & O_NONBLOCK) here.

**Description**

Videobuf2 core helper to implement `VIDIOC_DQBUF()` operation. It is called
internally by VB2 by an API-specific handler, like `videobuf2-v4l2.h`.

This function:

- #) calls buf_finish callback in the driver (if provided), in which

  driver can perform any additional operations that may be required before
  returning the buffer to userspace, such as cache sync,
- #) the buffer struct members are filled with relevant information for

  the userspace.

**Return**

returns zero on success; an error code otherwise.

#### <a id="c-vb2_core_streamon"></a>`vb2_core_streamon()`

```c
int vb2_core_streamon(struct vb2_queue *q, unsigned int type)
```

Implements VB2 stream ON logic

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue
- `unsigned int type`: type of the queue to be started.
  For V4L2, this is defined by [`enum v4l2_buf_type`](/kernel/userspace/userspace-api/media-v4l/buffer.md#c-v4l2_buf_type) type.

**Description**

Videobuf2 core helper to implement `VIDIOC_STREAMON()` operation. It is called
internally by VB2 by an API-specific handler, like `videobuf2-v4l2.h`.

**Return**

returns zero on success; an error code otherwise.

#### <a id="c-vb2_core_streamoff"></a>`vb2_core_streamoff()`

```c
int vb2_core_streamoff(struct vb2_queue *q, unsigned int type)
```

Implements VB2 stream OFF logic

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue
- `unsigned int type`: type of the queue to be started.
  For V4L2, this is defined by [`enum v4l2_buf_type`](/kernel/userspace/userspace-api/media-v4l/buffer.md#c-v4l2_buf_type) type.

**Description**

Videobuf2 core helper to implement `VIDIOC_STREAMOFF()` operation. It is
called internally by VB2 by an API-specific handler, like
`videobuf2-v4l2.h`.

**Return**

returns zero on success; an error code otherwise.

#### <a id="c-vb2_core_expbuf"></a>`vb2_core_expbuf()`

```c
int vb2_core_expbuf(struct vb2_queue *q, int *fd, unsigned int type, struct vb2_buffer *vb, unsigned int plane, unsigned int flags)
```

Export a buffer as a file descriptor.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `int *fd`: pointer to the file descriptor associated with DMABUF
  (set by driver).
- `unsigned int type`: buffer type.
- `struct vb2_buffer *vb`: pointer to struct [`vb2_buffer`](#c-struct-vb2_buffer).
- `unsigned int plane`: index of the plane to be exported, 0 for single plane queues
- `unsigned int flags`: file flags for newly created file, as defined at
  include/uapi/asm-generic/fcntl.h.
  Currently, the only used flag is `O_CLOEXEC`.
  is supported, refer to manual of open syscall for more details.

**Description**

Videobuf2 core helper to implement `VIDIOC_EXPBUF()` operation. It is called
internally by VB2 by an API-specific handler, like `videobuf2-v4l2.h`.

**Return**

returns zero on success; an error code otherwise.

#### <a id="c-vb2_core_queue_init"></a>`vb2_core_queue_init()`

```c
int vb2_core_queue_init(struct vb2_queue *q)
```

initialize a videobuf2 queue

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
  This structure should be allocated in driver

**Description**

The [`vb2_queue`](#c-struct-vb2_queue) structure should be allocated by the driver. The driver is
responsible of clearing it's content and setting initial values for some
required entries before calling this function.

> [!NOTE]
> The following fields at **q** should be set before calling this function:
> [`vb2_queue->ops`](#c-struct-vb2_queue), [`vb2_queue->mem_ops`](#c-struct-vb2_queue), [`vb2_queue->type`](#c-struct-vb2_queue).

#### <a id="c-vb2_core_queue_release"></a>`vb2_core_queue_release()`

```c
void vb2_core_queue_release(struct vb2_queue *q)
```

stop streaming, release the queue and free memory

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.

**Description**

This function stops streaming and performs necessary clean ups, including
freeing video buffer memory. The driver is responsible for freeing
the [`struct vb2_queue`](#c-struct-vb2_queue) itself.

#### <a id="c-vb2_queue_error"></a>`vb2_queue_error()`

```c
void vb2_queue_error(struct vb2_queue *q)
```

signal a fatal error on the queue

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.

**Description**

Flag that a fatal unrecoverable error has occurred and wake up all processes
waiting on the queue. Polling will now set `EPOLLERR` and queuing and dequeuing
buffers will return `-EIO`.

The error flag will be cleared when canceling the queue, either from
[`vb2_streamoff()`](#c-vb2_streamoff) or [`vb2_queue_release()`](#c-vb2_queue_release). Drivers should thus not call this
function before starting the stream, otherwise the error flag will remain set
until the queue is released when closing the device node.

#### <a id="c-vb2_mmap"></a>`vb2_mmap()`

```c
int vb2_mmap(struct vb2_queue *q, struct vm_area_struct *vma)
```

map video buffers into application address space.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `struct vm_area_struct *vma`: pointer to `struct vm_area_struct` with the vma passed
  to the mmap file operation handler in the driver.

**Description**

Should be called from mmap file operation handler of a driver.
This function maps one plane of one of the available video buffers to
userspace. To map whole video memory allocated on reqbufs, this function
has to be called once per each plane per each buffer previously allocated.

When the userspace application calls mmap, it passes to it an offset returned
to it earlier by the means of [`v4l2_ioctl_ops->vidioc_querybuf`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) handler.
That offset acts as a "cookie", which is then used to identify the plane
to be mapped.

This function finds a plane with a matching offset and a mapping is performed
by the means of a provided memory operation.

The return values from this function are intended to be directly returned
from the mmap handler in driver.

#### <a id="c-vb2_get_unmapped_area"></a>`vb2_get_unmapped_area()`

```c
unsigned long vb2_get_unmapped_area(struct vb2_queue *q, unsigned long addr, unsigned long len, unsigned long pgoff, unsigned long flags)
```

map video buffers into application address space.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `unsigned long addr`: memory address.
- `unsigned long len`: buffer size.
- `unsigned long pgoff`: page offset.
- `unsigned long flags`: memory flags.

**Description**

This function is used in noMMU platforms to propose address mapping
for a given buffer. It's intended to be used as a handler for the
`file_operations->get_unmapped_area` operation.

This is called by the `mmap()` syscall routines will call this
to get a proposed address for the mapping, when `!CONFIG_MMU`.

#### <a id="c-vb2_core_poll"></a>`vb2_core_poll()`

```c
__poll_t vb2_core_poll(struct vb2_queue *q, struct file *file, poll_table *wait)
```

implements poll `syscall()` logic.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `struct file *file`: [`struct file`](/kernel/internals/filesystems/api-summary.md#c-struct-file) argument passed to the poll
  file operation handler.
- `poll_table *wait`: `poll_table` wait argument passed to the poll
  file operation handler.

**Description**

This function implements poll file operation handler for a driver.
For CAPTURE queues, if a buffer is ready to be dequeued, the userspace will
be informed that the file descriptor of a video device is available for
reading.
For OUTPUT queues, if a buffer is ready to be dequeued, the file descriptor
will be reported as available for writing.

The return values from this function are intended to be directly returned
from poll handler in driver.

#### <a id="c-vb2_read"></a>`vb2_read()`

```c
size_t vb2_read(struct vb2_queue *q, char __user *data, size_t count, loff_t *ppos, int nonblock)
```

implements `read()` syscall logic.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `char __user *data`: pointed to target userspace buffer
- `size_t count`: number of bytes to read
- `loff_t *ppos`: file handle position tracking pointer
- `int nonblock`: mode selector (1 means blocking calls, 0 means nonblocking)

#### <a id="c-vb2_write"></a>`vb2_write()`

```c
size_t vb2_write(struct vb2_queue *q, const char __user *data, size_t count, loff_t *ppos, int nonblock)
```

implements `write()` syscall logic.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `const char __user *data`: pointed to target userspace buffer
- `size_t count`: number of bytes to write
- `loff_t *ppos`: file handle position tracking pointer
- `int nonblock`: mode selector (1 means blocking calls, 0 means nonblocking)

#### <a id="c-vb2_thread_fnc"></a>`vb2_thread_fnc()`

```c
typedef int vb2_thread_fnc(struct vb2_buffer *vb, void *priv)
```

callback function for use with vb2_thread.

**Parameters**

- `struct vb2_buffer *vb`: pointer to struct [`vb2_buffer`](#c-struct-vb2_buffer).
- `void *priv`: pointer to a private data.

**Description**

This is called whenever a buffer is dequeued in the thread.

#### <a id="c-vb2_thread_start"></a>`vb2_thread_start()`

```c
int vb2_thread_start(struct vb2_queue *q, vb2_thread_fnc fnc, void *priv, const char *thread_name)
```

start a thread for the given queue.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `vb2_thread_fnc fnc`: [`vb2_thread_fnc`](#c-vb2_thread_fnc) callback function.
- `void *priv`: priv pointer passed to the callback function.
- `const char *thread_name`: the name of the thread. This will be prefixed with "vb2-".

**Description**

This starts a thread that will queue and dequeue until an error occurs
or [`vb2_thread_stop()`](#c-vb2_thread_stop) is called.

> [!IMPORTANT]
> This function should not be used for anything else but the videobuf2-dvb
> support. If you think you have another good use-case for this, then please
> contact the linux-media mailing list first.

#### <a id="c-vb2_thread_stop"></a>`vb2_thread_stop()`

```c
int vb2_thread_stop(struct vb2_queue *q)
```

stop the thread for the given queue.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.

#### <a id="c-vb2_is_streaming"></a>`vb2_is_streaming()`

```c
bool vb2_is_streaming(struct vb2_queue *q)
```

return streaming status of the queue.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.

#### <a id="c-vb2_fileio_is_active"></a>`vb2_fileio_is_active()`

```c
bool vb2_fileio_is_active(struct vb2_queue *q)
```

return true if fileio is active.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.

**Description**

This returns true if `read()` or `write()` is used to stream the data
as opposed to stream I/O. This is almost never an important distinction,
except in rare cases. One such case is that using `read()` or `write()` to
stream a format using `V4L2_FIELD_ALTERNATE` is not allowed since there
is no way you can pass the field information of each buffer to/from
userspace. A driver that supports this field format should check for
this in the [`vb2_ops->queue_setup`](#c-struct-vb2_ops) op and reject it if this function returns
true.

#### <a id="c-vb2_get_num_buffers"></a>`vb2_get_num_buffers()`

```c
unsigned int vb2_get_num_buffers(struct vb2_queue *q)
```

get the number of buffer in a queue

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.

#### <a id="c-vb2_is_busy"></a>`vb2_is_busy()`

```c
bool vb2_is_busy(struct vb2_queue *q)
```

return busy status of the queue.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.

**Description**

This function checks if queue has any buffers allocated.

#### <a id="c-vb2_get_drv_priv"></a>`vb2_get_drv_priv()`

```c
void * vb2_get_drv_priv(struct vb2_queue *q)
```

return driver private data associated with the queue.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.

#### <a id="c-vb2_set_plane_payload"></a>`vb2_set_plane_payload()`

```c
void vb2_set_plane_payload(struct vb2_buffer *vb, unsigned int plane_no, unsigned long size)
```

set bytesused for the plane **plane_no**.

**Parameters**

- `struct vb2_buffer *vb`: pointer to [`struct vb2_buffer`](#c-struct-vb2_buffer) to which the plane in
  question belongs to.
- `unsigned int plane_no`: plane number for which payload should be set.
- `unsigned long size`: payload in bytes.

#### <a id="c-vb2_get_plane_payload"></a>`vb2_get_plane_payload()`

```c
unsigned long vb2_get_plane_payload(struct vb2_buffer *vb, unsigned int plane_no)
```

get bytesused for the plane plane_no

**Parameters**

- `struct vb2_buffer *vb`: pointer to [`struct vb2_buffer`](#c-struct-vb2_buffer) to which the plane in
  question belongs to.
- `unsigned int plane_no`: plane number for which payload should be set.

#### <a id="c-vb2_plane_size"></a>`vb2_plane_size()`

```c
unsigned long vb2_plane_size(struct vb2_buffer *vb, unsigned int plane_no)
```

return plane size in bytes.

**Parameters**

- `struct vb2_buffer *vb`: pointer to [`struct vb2_buffer`](#c-struct-vb2_buffer) to which the plane in
  question belongs to.
- `unsigned int plane_no`: plane number for which size should be returned.

#### <a id="c-vb2_start_streaming_called"></a>`vb2_start_streaming_called()`

```c
bool vb2_start_streaming_called(struct vb2_queue *q)
```

return streaming status of driver.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.

#### <a id="c-vb2_clear_last_buffer_dequeued"></a>`vb2_clear_last_buffer_dequeued()`

```c
void vb2_clear_last_buffer_dequeued(struct vb2_queue *q)
```

clear last buffer dequeued flag of queue.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.

#### <a id="c-vb2_get_buffer"></a>`vb2_get_buffer()`

```c
struct vb2_buffer * vb2_get_buffer(struct vb2_queue *q, unsigned int index)
```

get a buffer from a queue

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `unsigned int index`: buffer index

**Description**

This function obtains a buffer from a queue, by its index.
Keep in mind that there is no refcounting involved in this
operation, so the buffer lifetime should be taken into
consideration.

#### <a id="c-vb2_buffer_in_use"></a>`vb2_buffer_in_use()`

```c
bool vb2_buffer_in_use(struct vb2_queue *q, struct vb2_buffer *vb)
```

return true if the buffer is in use and the queue cannot be freed (by the means of VIDIOC_REQBUFS(0)) call.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `struct vb2_buffer *vb`: buffer for which plane size should be returned.

#### <a id="c-vb2_verify_memory_type"></a>`vb2_verify_memory_type()`

```c
int vb2_verify_memory_type(struct vb2_queue *q, enum vb2_memory memory, unsigned int type)
```

Check whether the memory type and buffer type passed to a buffer operation are compatible with the queue.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `enum vb2_memory memory`: memory model, as defined by enum [`vb2_memory`](#c-enum-vb2_memory).
- `unsigned int type`: private buffer type whose content is defined by the vb2-core
  caller. For example, for V4L2, it should match
  the types defined on enum `v4l2_buf_type`.

#### <a id="c-vb2_request_object_is_buffer"></a>`vb2_request_object_is_buffer()`

```c
bool vb2_request_object_is_buffer(struct media_request_object *obj)
```

return true if the object is a buffer

**Parameters**

- `struct media_request_object *obj`: the request object.

#### <a id="c-vb2_request_buffer_cnt"></a>`vb2_request_buffer_cnt()`

```c
unsigned int vb2_request_buffer_cnt(struct media_request *req)
```

return the number of buffers in the request

**Parameters**

- `struct media_request *req`: the request.



#### <a id="c-struct-vb2_v4l2_buffer"></a>`struct vb2_v4l2_buffer`

video buffer information for v4l2.

**Definition**

```c
struct vb2_v4l2_buffer {
    struct vb2_buffer       vb2_buf;
    __u32 flags;
    __u32 field;
    struct v4l2_timecode    timecode;
    __u32 sequence;
    __s32 request_fd;
    bool is_held;
    struct vb2_plane        planes[VB2_MAX_PLANES];
};
```

**Members**

- `vb2_buf`: embedded struct [`vb2_buffer`](#c-struct-vb2_buffer).
- `flags`: buffer informational flags.
- `field`: field order of the image in the buffer, as defined by
  [`enum v4l2_field`](/kernel/userspace/userspace-api/media-v4l/field-order.md#c-v4l2_field).
- `timecode`: frame timecode.
- `sequence`: sequence count of this frame.
- `request_fd`: the request_fd associated with this buffer
- `is_held`: if true, then this capture buffer was held
- `planes`: plane information (userptr/fd, length, bytesused, data_offset).

**Description**

Should contain enough information to be able to cover all the fields
of [`struct v4l2_buffer`](/kernel/userspace/userspace-api/media-v4l/buffer.md#c-v4l2_buffer) at `videodev2.h`.

#### <a id="c-vb2_find_buffer"></a>`vb2_find_buffer()`

```c
struct vb2_buffer * vb2_find_buffer(struct vb2_queue *q, u64 timestamp)
```

Find a buffer with given timestamp

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `u64 timestamp`: the timestamp to find.

**Description**

Returns the buffer with the given **timestamp**, or NULL if not found.

#### <a id="c-vb2_reqbufs"></a>`vb2_reqbufs()`

```c
int vb2_reqbufs(struct vb2_queue *q, struct v4l2_requestbuffers *req)
```

Wrapper for [`vb2_core_reqbufs()`](#c-vb2_core_reqbufs) that also verifies the memory and type values.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `struct v4l2_requestbuffers *req`: [`struct v4l2_requestbuffers`](/kernel/userspace/userspace-api/media-v4l/vidioc-reqbufs.md#c-v4l2_requestbuffers) passed from userspace to
  [`v4l2_ioctl_ops->vidioc_reqbufs`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) handler in driver.

#### <a id="c-vb2_create_bufs"></a>`vb2_create_bufs()`

```c
int vb2_create_bufs(struct vb2_queue *q, struct v4l2_create_buffers *create)
```

Wrapper for [`vb2_core_create_bufs()`](#c-vb2_core_create_bufs) that also verifies the memory and type values.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `struct v4l2_create_buffers *create`: creation parameters, passed from userspace to
  [`v4l2_ioctl_ops->vidioc_create_bufs`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) handler in driver

#### <a id="c-vb2_prepare_buf"></a>`vb2_prepare_buf()`

```c
int vb2_prepare_buf(struct vb2_queue *q, struct media_device *mdev, struct v4l2_buffer *b)
```

Pass ownership of a buffer from userspace to the kernel

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `struct media_device *mdev`: pointer to [`struct media_device`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_device), may be NULL.
- `struct v4l2_buffer *b`: buffer structure passed from userspace to
  [`v4l2_ioctl_ops->vidioc_prepare_buf`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) handler in driver

**Description**

Should be called from [`v4l2_ioctl_ops->vidioc_prepare_buf`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) ioctl handler
of a driver.

This function:

\#) verifies the passed buffer,
\#) calls [`vb2_ops->buf_prepare`](#c-struct-vb2_ops) callback in the driver (if provided),
in which driver-specific buffer initialization can be performed.
\#) if **b->request_fd** is non-zero and **mdev->ops->req_queue** is set,
then bind the prepared buffer to the request.

The return values from this function are intended to be directly returned
from [`v4l2_ioctl_ops->vidioc_prepare_buf`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) handler in driver.

#### <a id="c-vb2_qbuf"></a>`vb2_qbuf()`

```c
int vb2_qbuf(struct vb2_queue *q, struct media_device *mdev, struct v4l2_buffer *b)
```

Queue a buffer from userspace

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `struct media_device *mdev`: pointer to [`struct media_device`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_device), may be NULL.
- `struct v4l2_buffer *b`: buffer structure passed from userspace to
  [`v4l2_ioctl_ops->vidioc_qbuf`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) handler in driver

**Description**

Should be called from [`v4l2_ioctl_ops->vidioc_qbuf`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) handler of a driver.

This function:

\#) verifies the passed buffer;
\#) if **b->request_fd** is non-zero and **mdev->ops->req_queue** is set,
then bind the buffer to the request.
\#) if necessary, calls [`vb2_ops->buf_prepare`](#c-struct-vb2_ops) callback in the driver
(if provided), in which driver-specific buffer initialization can
be performed;
\#) if streaming is on, queues the buffer in driver by the means of
[`vb2_ops->buf_queue`](#c-struct-vb2_ops) callback for processing.

The return values from this function are intended to be directly returned
from [`v4l2_ioctl_ops->vidioc_qbuf`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) handler in driver.

#### <a id="c-vb2_expbuf"></a>`vb2_expbuf()`

```c
int vb2_expbuf(struct vb2_queue *q, struct v4l2_exportbuffer *eb)
```

Export a buffer as a file descriptor

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `struct v4l2_exportbuffer *eb`: export buffer structure passed from userspace to
  [`v4l2_ioctl_ops->vidioc_expbuf`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) handler in driver

**Description**

The return values from this function are intended to be directly returned
from [`v4l2_ioctl_ops->vidioc_expbuf`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) handler in driver.

#### <a id="c-vb2_dqbuf"></a>`vb2_dqbuf()`

```c
int vb2_dqbuf(struct vb2_queue *q, struct v4l2_buffer *b, bool nonblocking)
```

Dequeue a buffer to the userspace

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `struct v4l2_buffer *b`: buffer structure passed from userspace to
  [`v4l2_ioctl_ops->vidioc_dqbuf`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) handler in driver
- `bool nonblocking`: if true, this call will not sleep waiting for a buffer if no
  buffers ready for dequeuing are present. Normally the driver
  would be passing ([`file->f_flags`](/kernel/internals/filesystems/api-summary.md#c-struct-file) & `O_NONBLOCK`) here

**Description**

Should be called from [`v4l2_ioctl_ops->vidioc_dqbuf`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) ioctl handler
of a driver.

This function:

\#) verifies the passed buffer;
\#) calls [`vb2_ops->buf_finish`](#c-struct-vb2_ops) callback in the driver (if provided), in which
driver can perform any additional operations that may be required before
returning the buffer to userspace, such as cache sync;
\#) the buffer struct members are filled with relevant information for
the userspace.

The return values from this function are intended to be directly returned
from [`v4l2_ioctl_ops->vidioc_dqbuf`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) handler in driver.

#### <a id="c-vb2_streamon"></a>`vb2_streamon()`

```c
int vb2_streamon(struct vb2_queue *q, enum v4l2_buf_type type)
```

start streaming

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `enum v4l2_buf_type type`: type argument passed from userspace to vidioc_streamon handler,
  as defined by [`enum v4l2_buf_type`](/kernel/userspace/userspace-api/media-v4l/buffer.md#c-v4l2_buf_type).

**Description**

Should be called from [`v4l2_ioctl_ops->vidioc_streamon`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) handler of a driver.

This function:

1) verifies current state
2) passes any previously queued buffers to the driver and starts streaming

The return values from this function are intended to be directly returned
from [`v4l2_ioctl_ops->vidioc_streamon`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) handler in the driver.

#### <a id="c-vb2_streamoff"></a>`vb2_streamoff()`

```c
int vb2_streamoff(struct vb2_queue *q, enum v4l2_buf_type type)
```

stop streaming

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `enum v4l2_buf_type type`: type argument passed from userspace to vidioc_streamoff handler

**Description**

Should be called from vidioc_streamoff handler of a driver.

This function:

\#) verifies current state,
\#) stop streaming and dequeues any queued buffers, including those previously
passed to the driver (after waiting for the driver to finish).

This call can be used for pausing playback.
The return values from this function are intended to be directly returned
from vidioc_streamoff handler in the driver

#### <a id="c-vb2_queue_init"></a>`vb2_queue_init()`

```c
int vb2_queue_init(struct vb2_queue *q)
```

initialize a videobuf2 queue

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.

**Description**

The vb2_queue structure should be allocated by the driver. The driver is
responsible of clearing it's content and setting initial values for some
required entries before calling this function.
q->ops, q->mem_ops, q->type and q->io_modes are mandatory. Please refer
to the struct vb2_queue description in include/media/videobuf2-core.h
for more information.

#### <a id="c-vb2_queue_init_name"></a>`vb2_queue_init_name()`

```c
int vb2_queue_init_name(struct vb2_queue *q, const char *name)
```

initialize a videobuf2 queue with a name

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `const char *name`: the queue name

**Description**

This function initializes the vb2_queue exactly like [`vb2_queue_init()`](#c-vb2_queue_init),
and additionally sets the queue name. The queue name is used for logging
purpose, and should uniquely identify the queue within the context of the
device it belongs to. This is useful to attribute kernel log messages to the
right queue for m2m devices or other devices that handle multiple queues.

#### <a id="c-vb2_queue_release"></a>`vb2_queue_release()`

```c
void vb2_queue_release(struct vb2_queue *q)
```

stop streaming, release the queue and free memory

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.

**Description**

This function stops streaming and performs necessary clean ups, including
freeing video buffer memory. The driver is responsible for freeing
the vb2_queue structure itself.

#### <a id="c-vb2_queue_change_type"></a>`vb2_queue_change_type()`

```c
int vb2_queue_change_type(struct vb2_queue *q, unsigned int type)
```

change the type of an inactive vb2_queue

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `unsigned int type`: the type to change to (V4L2_BUF_TYPE_VIDEO_*)

**Description**

This function changes the type of the vb2_queue. This is only possible
if the queue is not busy (i.e. no buffers have been allocated).

[`vb2_queue_change_type()`](#c-vb2_queue_change_type) can be used to support multiple buffer types using
the same queue. The driver can implement v4l2_ioctl_ops.vidioc_reqbufs and
v4l2_ioctl_ops.vidioc_create_bufs functions and call [`vb2_queue_change_type()`](#c-vb2_queue_change_type)
before calling `vb2_ioctl_reqbufs()` or `vb2_ioctl_create_bufs()`, and thus
"lock" the buffer type until the buffers have been released.

#### <a id="c-vb2_poll"></a>`vb2_poll()`

```c
__poll_t vb2_poll(struct vb2_queue *q, struct file *file, poll_table *wait)
```

implements poll userspace operation

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `struct file *file`: file argument passed to the poll file operation handler
- `poll_table *wait`: wait argument passed to the poll file operation handler

**Description**

This function implements poll file operation handler for a driver.
For CAPTURE queues, if a buffer is ready to be dequeued, the userspace will
be informed that the file descriptor of a video device is available for
reading.
For OUTPUT queues, if a buffer is ready to be dequeued, the file descriptor
will be reported as available for writing.

If the driver uses struct v4l2_fh, then [`vb2_poll()`](#c-vb2_poll) will also check for any
pending events.

The return values from this function are intended to be directly returned
from poll handler in driver.

#### <a id="c-vb2_queue_is_busy"></a>`vb2_queue_is_busy()`

```c
bool vb2_queue_is_busy(struct vb2_queue *q, struct file *file)
```

check if the queue is busy

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `struct file *file`: file through which the vb2 queue access is performed

**Description**

The queue is considered busy if it has an owner and the owner is not the
**file**.

Queue ownership is acquired and checked by some of the v4l2_ioctl_ops helpers
below. Drivers can also use this function directly when they need to
open-code ioctl handlers, for instance to add additional checks between the
queue ownership test and the call to the corresponding vb2 operation.

#### <a id="c-vb2_video_unregister_device"></a>`vb2_video_unregister_device()`

```c
void vb2_video_unregister_device(struct video_device *vdev)
```

unregister the video device and release queue

**Parameters**

- `struct video_device *vdev`: pointer to [`struct video_device`](/kernel/hardware/driver-api/media/v4l2-dev.md#c-struct-video_device)

**Description**

If the driver uses `vb2_fop_release()`/`_vb2_fop_release()`, then it should use
[`vb2_video_unregister_device()`](#c-vb2_video_unregister_device) instead of [`video_unregister_device()`](/kernel/hardware/driver-api/media/v4l2-dev.md#c-video_unregister_device).

This function will call [`video_unregister_device()`](/kernel/hardware/driver-api/media/v4l2-dev.md#c-video_unregister_device) and then release the
vb2_queue if streaming is in progress. This will stop streaming and
this will simplify the unbind sequence since after this call all subdevs
will have stopped streaming as well.



#### <a id="c-struct-vb2_vmarea_handler"></a>`struct vb2_vmarea_handler`

common vma refcount tracking handler.

**Definition**

```c
struct vb2_vmarea_handler {
    refcount_t *refcount;
    void (*put)(void *arg);
    void *arg;
};
```

**Members**

- `refcount`: pointer to `refcount_t` entry in the buffer.
- `put`: callback to function that decreases buffer refcount.
- `arg`: argument for **put** callback.
