code:
.. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later
.. c:namespace:: V4L

.. _VIDIOC_SUBDEV_ENUM_MBUS_CODE:

**********************************
ioctl VIDIOC_SUBDEV_ENUM_MBUS_CODE
**********************************

Name
====

VIDIOC_SUBDEV_ENUM_MBUS_CODE - Enumerate media bus formats

Synopsis
========

.. c:macro:: VIDIOC_SUBDEV_ENUM_MBUS_CODE

``int ioctl(int fd, VIDIOC_SUBDEV_ENUM_MBUS_CODE, struct v4l2_subdev_mbus_code_enum * argp)``

Arguments
=========

``fd``
    File descriptor returned by :c:func:`open()`.

``argp``
    Pointer to struct :c:type:`v4l2_subdev_mbus_code_enum`.

Description
===========

To enumerate media bus formats available at a given sub-device pad
applications initialize the ``pad``, ``which`` and ``index`` fields of
struct
:c:type:`v4l2_subdev_mbus_code_enum` and
call the :ref:`VIDIOC_SUBDEV_ENUM_MBUS_CODE` ioctl with a pointer to this
structure. Drivers fill the rest of the structure or return an ``EINVAL``
error code if either the ``pad`` or ``index`` are invalid. All media bus
formats are enumerable by beginning at index zero and incrementing by
one until ``EINVAL`` is returned.

Available media bus formats may depend on the current 'try' formats at
other pads of the sub-device, as well as on the current active links.
See :ref:`VIDIOC_SUBDEV_G_FMT` for more
information about the try formats.

.. c:type:: v4l2_subdev_mbus_code_enum

.. tabularcolumns:: |p{4.4cm}|p{4.4cm}|p{8.5cm}|

.. flat-table:: struct v4l2_subdev_mbus_code_enum
    :header-rows:  0
    :stub-columns: 0
    :widths:       1 1 2

    * - __u32
      - ``pad``
      - Pad number as reported by the media controller API.
    * - __u32
      - ``index``
      - Number of the format in the enumeration, set by the application.
    * - __u32
      - ``code``
      - The media bus format code, as defined in
	:ref:`v4l2-mbus-format`.
    * - __u32
      - ``which``
      - Media bus format codes to be enumerated, from enum
	:ref:`v4l2_subdev_format_whence <v4l2-subdev-format-whence>`.
    * - __u32
      - ``flags``
      - See :ref:`v4l2-subdev-mbus-code-flags`
    * - __u32
      - ``reserved``\ [7]
      - Reserved for future extensions. Applications and drivers must set
	the array to zero.

.. raw:: latex

   \footnotesize

.. tabularcolumns:: |p{8.8cm}|p{2.2cm}|p{6.3cm}|

.. _v4l2-subdev-mbus-code-flags:

.. flat-table:: Subdev Media Bus Code Enumerate Flags
    :header-rows:  0
    :stub-columns: 0
    :widths:       1 1 2

    * - V4L2_SUBDEV_MBUS_CODE_CSC_COLORSPACE
      - 0x00000001
      - The driver allows the application to try to change the default colorspace
	encoding. The application can ask to configure the colorspace of the
	subdevice when calling the :ref:`VIDIOC_SUBDEV_S_FMT <VIDIOC_SUBDEV_G_FMT>`
	ioctl with :ref:`V4L2_MBUS_FRAMEFMT_SET_CSC <mbus-framefmt-set-csc>` set.
	See :ref:`v4l2-mbus-format` on how to do this.
    * - V4L2_SUBDEV_MBUS_CODE_CSC_XFER_FUNC
      - 0x00000002
      - The driver allows the application to try to change the default transform function.
	The application can ask to configure the transform function of
	the subdevice when calling the :ref:`VIDIOC_SUBDEV_S_FMT <VIDIOC_SUBDEV_G_FMT>`
	ioctl with :ref:`V4L2_MBUS_FRAMEFMT_SET_CSC <mbus-framefmt-set-csc>` set.
	See :ref:`v4l2-mbus-format` on how to do this.
    * - V4L2_SUBDEV_MBUS_CODE_CSC_YCBCR_ENC
      - 0x00000004
      - The driver allows the application to try to change the default Y'CbCr
	encoding. The application can ask to configure the Y'CbCr encoding of the
	subdevice when calling the :ref:`VIDIOC_SUBDEV_S_FMT <VIDIOC_SUBDEV_G_FMT>`
	ioctl with :ref:`V4L2_MBUS_FRAMEFMT_SET_CSC <mbus-framefmt-set-csc>` set.
	See :ref:`v4l2-mbus-format` on how to do this.
    * - V4L2_SUBDEV_MBUS_CODE_CSC_HSV_ENC
      - 0x00000004
      - The driver allows the application to try to change the default HSV
	encoding. The application can ask to configure the HSV encoding of the
	subdevice when calling the :ref:`VIDIOC_SUBDEV_S_FMT <VIDIOC_SUBDEV_G_FMT>`
	ioctl with :ref:`V4L2_MBUS_FRAMEFMT_SET_CSC <mbus-framefmt-set-csc>` set.
	See :ref:`v4l2-mbus-format` on how to do this.
    * - V4L2_SUBDEV_MBUS_CODE_CSC_QUANTIZATION
      - 0x00000008
      - The driver allows the application to try to change the default
	quantization. The application can ask to configure the quantization of
	the subdevice when calling the :ref:`VIDIOC_SUBDEV_S_FMT <VIDIOC_SUBDEV_G_FMT>`
	ioctl with :ref:`V4L2_MBUS_FRAMEFMT_SET_CSC <mbus-framefmt-set-csc>` set.
	See :ref:`v4l2-mbus-format` on how to do this.

.. raw:: latex

   \normalsize

Return Value
============

On success 0 is returned, on error -1 and the ``errno`` variable is set
appropriately. The generic error codes are described at the
:ref:`Generic Error Codes <gen-errors>` chapter.

EINVAL
    The struct
    :c:type:`v4l2_subdev_mbus_code_enum`
    ``pad`` references a non-existing pad, or the ``index`` field is out
    of bounds.


code:
.. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later
.. c:namespace:: V4L

.. _VIDIOC_SUBDEV_G_CROP:

************************************************
ioctl VIDIOC_SUBDEV_G_CROP, VIDIOC_SUBDEV_S_CROP
************************************************

Name
====

VIDIOC_SUBDEV_G_CROP - VIDIOC_SUBDEV_S_CROP - Get or set the crop rectangle on a subdev pad

Synopsis
========

.. c:macro:: VIDIOC_SUBDEV_G_CROP

``int ioctl(int fd, VIDIOC_SUBDEV_G_CROP, struct v4l2_subdev_crop *argp)``

.. c:macro:: VIDIOC_SUBDEV_S_CROP

``int ioctl(int fd, VIDIOC_SUBDEV_S_CROP, const struct v4l2_subdev_crop *argp)``

Arguments
=========

``fd``
    File descriptor returned by :c:func:`open()`.

``argp``
    Pointer to struct :c:type:`v4l2_subdev_crop`.

Description
===========

.. note::

    This is an :ref:`obsolete` interface and may be removed
    in the future. It is superseded by
    :ref:`the selection API <VIDIOC_SUBDEV_G_SELECTION>`.

To retrieve the current crop rectangle applications set the ``pad``
field of a struct :c:type:`v4l2_subdev_crop` to the
desired pad number as reported by the media API and the ``which`` field
to ``V4L2_SUBDEV_FORMAT_ACTIVE``. They then call the
``VIDIOC_SUBDEV_G_CROP`` ioctl with a pointer to this structure. The
driver fills the members of the ``rect`` field or returns ``EINVAL`` error
code if the input arguments are invalid, or if cropping is not supported
on the given pad.

To change the current crop rectangle applications set both the ``pad``
and ``which`` fields and all members of the ``rect`` field. They then
call the ``VIDIOC_SUBDEV_S_CROP`` ioctl with a pointer to this
structure. The driver verifies the requested crop rectangle, adjusts it
based on the hardware capabilities and configures the device. Upon
return the struct :c:type:`v4l2_subdev_crop`
contains the current format as would be returned by a
``VIDIOC_SUBDEV_G_CROP`` call.

Applications can query the device capabilities by setting the ``which``
to ``V4L2_SUBDEV_FORMAT_TRY``. When set, 'try' crop rectangles are not
applied to the device by the driver, but are mangled exactly as active
crop rectangles and stored in the sub-device file handle. Two
applications querying the same sub-device would thus not interact with
each other.

If the subdev device node has been registered in read-only mode, calls to
``VIDIOC_SUBDEV_S_CROP`` are only valid if the ``which`` field is set to
``V4L2_SUBDEV_FORMAT_TRY``, otherwise an error is returned and the errno
variable is set to ``-EPERM``.

Drivers must not return an error solely because the requested crop
rectangle doesn't match the device capabilities. They must instead
modify the rectangle to match what the hardware can provide. The
modified format should be as close as possible to the original request.

.. c:type:: v4l2_subdev_crop

.. tabularcolumns:: |p{4.4cm}|p{4.4cm}|p{8.5cm}|

.. flat-table:: struct v4l2_subdev_crop
    :header-rows:  0
    :stub-columns: 0
    :widths:       1 1 2

    * - __u32
      - ``pad``
      - Pad number as reported by the media framework.
    * - __u32
      - ``which``
      - Crop rectangle to get or set, from enum
	:ref:`v4l2_subdev_format_whence <v4l2-subdev-format-whence>`.
    * - struct :c:type:`v4l2_rect`
      - ``rect``
      - Crop rectangle boundaries, in pixels.
    * - __u32
      - ``reserved``\ [8]
      - Reserved for future extensions. Applications and drivers must set
	the array to zero.

Return Value
============

On success 0 is returned, on error -1 and the ``errno`` variable is set
appropriately. The generic error codes are described at the
:ref:`Generic Error Codes <gen-errors>` chapter.

EBUSY
    The crop rectangle can't be changed because the pad is currently
    busy. This can be caused, for instance, by an active video stream on
    the pad. The ioctl must not be retried without performing another
    action to fix the problem first. Only returned by
    ``VIDIOC_SUBDEV_S_CROP``

EINVAL
    The struct :c:type:`v4l2_subdev_crop` ``pad``
    references a non-existing pad, the ``which`` field references a
    non-existing format, or cropping is not supported on the given
    subdev pad.

EPERM
    The ``VIDIOC_SUBDEV_S_CROP`` ioctl has been called on a read-only subdevice
    and the ``which`` field is set to ``V4L2_SUBDEV_FORMAT_ACTIVE``.

repo_name: angery/linux


code:
.. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later
.. c:namespace:: V4L

.. _VIDIOC_SUBDEV_G_FMT:

**********************************************
ioctl VIDIOC_SUBDEV_G_FMT, VIDIOC_SUBDEV_S_FMT
**********************************************

Name
====

VIDIOC_SUBDEV_G_FMT - VIDIOC_SUBDEV_S_FMT - Get or set the data format on a subdev pad

Synopsis
========

.. c:macro:: VIDIOC_SUBDEV_G_FMT

``int ioctl(int fd, VIDIOC_SUBDEV_G_FMT, struct v4l2_subdev_format *argp)``

.. c:macro:: VIDIOC_SUBDEV_S_FMT

``int ioctl(int fd, VIDIOC_SUBDEV_S_FMT, struct v4l2_subdev_format *argp)``

Arguments
=========

``fd``
    File descriptor returned by :c:func:`open()`.

``argp``
    Pointer to struct :c:type:`v4l2_subdev_format`.

Description
===========

These ioctls are used to negotiate the frame format at specific subdev
pads in the image pipeline.

To retrieve the current format applications set the ``pad`` field of a
struct :c:type:`v4l2_subdev_format` to the desired
pad number as reported by the media API and the ``which`` field to
``V4L2_SUBDEV_FORMAT_ACTIVE``. When they call the
``VIDIOC_SUBDEV_G_FMT`` ioctl with a pointer to this structure the
driver fills the members of the ``format`` field.

To change the current format applications set both the ``pad`` and
``which`` fields and all members of the ``format`` field. When they call
the ``VIDIOC_SUBDEV_S_FMT`` ioctl with a pointer to this structure the
driver verifies the requested format, adjusts it based on the hardware
capabilities and configures the device. Upon return the struct
:c:type:`v4l2_subdev_format` contains the current
format as would be returned by a ``VIDIOC_SUBDEV_G_FMT`` call.

Applications can query the device capabilities by setting the ``which``
to ``V4L2_SUBDEV_FORMAT_TRY``. When set, 'try' formats are not applied
to the device by the driver, but are changed exactly as active formats
and stored in the sub-device file handle. Two applications querying the
same sub-device would thus not interact with each other.

For instance, to try a format at the output pad of a sub-device,
applications would first set the try format at the sub-device input with
the ``VIDIOC_SUBDEV_S_FMT`` ioctl. They would then either retrieve the
default format at the output pad with the ``VIDIOC_SUBDEV_G_FMT`` ioctl,
or set the desired output pad format with the ``VIDIOC_SUBDEV_S_FMT``
ioctl and check the returned value.

Try formats do not depend on active formats, but can depend on the
current links configuration or sub-device controls value. For instance,
a low-pass noise filter might crop pixels at the frame boundaries,
modifying its output frame size.

If the subdev device node has been registered in read-only mode, calls to
``VIDIOC_SUBDEV_S_FMT`` are only valid if the ``which`` field is set to
``V4L2_SUBDEV_FORMAT_TRY``, otherwise an error is returned and the errno
variable is set to ``-EPERM``.

Drivers must not return an error solely because the requested format
doesn't match the device capabilities. They must instead modify the
format to match what the hardware can provide. The modified format
should be as close as possible to the original request.

.. tabularcolumns:: |p{4.4cm}|p{4.4cm}|p{8.5cm}|

.. c:type:: v4l2_subdev_format

.. flat-table:: struct v4l2_subdev_format
    :header-rows:  0
    :stub-columns: 0
    :widths:       1 1 2

    * - __u32
      - ``pad``
      - Pad number as reported by the media controller API.
    * - __u32
      - ``which``
      - Format to modified, from enum
	:ref:`v4l2_subdev_format_whence <v4l2-subdev-format-whence>`.
    * - struct :c:type:`v4l2_mbus_framefmt`
      - ``format``
      - Definition of an image format, see :c:type:`v4l2_mbus_framefmt` for
	details.
    * - __u32
      - ``reserved``\ [8]
      - Reserved for future extensions. Applications and drivers must set
	the array to zero.

.. tabularcolumns:: |p{6.6cm}|p{2.2cm}|p{8.5cm}|

.. _v4l2-subdev-format-whence:

.. flat-table:: enum v4l2_subdev_format_whence
    :header-rows:  0
    :stub-columns: 0
    :widths:       3 1 4

    * - V4L2_SUBDEV_FORMAT_TRY
      - 0
      - Try formats, used for querying device capabilities.
    * - V4L2_SUBDEV_FORMAT_ACTIVE
      - 1
      - Active formats, applied to the hardware.

Return Value
============

On success 0 is returned, on error -1 and the ``errno`` variable is set
appropriately. The generic error codes are described at the
:ref:`Generic Error Codes <gen-errors>` chapter.

EBUSY
    The format can't be changed because the pad is currently busy. This
    can be caused, for instance, by an active video stream on the pad.
    The ioctl must not be retried without performing another action to
    fix the problem first. Only returned by ``VIDIOC_SUBDEV_S_FMT``

EINVAL
    The struct :c:type:`v4l2_subdev_format`
    ``pad`` references a non-existing pad, or the ``which`` field
    references a non-existing format.

EPERM
    The ``VIDIOC_SUBDEV_S_FMT`` ioctl has been called on a read-only subdevice
    and the ``which`` field is set to ``V4L2_SUBDEV_FORMAT_ACTIVE``.

============

On success 0 is returned, on error -1 and the ``errno`` variable is set
appropriately. The generic error codes are described at the
:ref:`Generic Error Codes <gen-errors>` chapter.


code:
.. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later
.. c:namespace:: V4L

.. _VIDIOC_SUBDEV_G_FRAME_INTERVAL:

********************************************************************
ioctl VIDIOC_SUBDEV_G_FRAME_INTERVAL, VIDIOC_SUBDEV_S_FRAME_INTERVAL
********************************************************************

Name
====

VIDIOC_SUBDEV_G_FRAME_INTERVAL - VIDIOC_SUBDEV_S_FRAME_INTERVAL - Get or set the frame interval on a subdev pad

Synopsis
========

.. c:macro:: VIDIOC_SUBDEV_G_FRAME_INTERVAL

``int ioctl(int fd, VIDIOC_SUBDEV_G_FRAME_INTERVAL, struct v4l2_subdev_frame_interval *argp)``

.. c:macro:: VIDIOC_SUBDEV_S_FRAME_INTERVAL

``int ioctl(int fd, VIDIOC_SUBDEV_S_FRAME_INTERVAL, struct v4l2_subdev_frame_interval *argp)``

Arguments
=========

``fd``
    File descriptor returned by :c:func:`open()`.

``argp``
    Pointer to struct :c:type:`v4l2_subdev_frame_interval`.

Description
===========

These ioctls are used to get and set the frame interval at specific
subdev pads in the image pipeline. The frame interval only makes sense
for sub-devices that can control the frame period on their own. This
includes, for instance, image sensors and TV tuners. Sub-devices that
don't support frame intervals must not implement these ioctls.

To retrieve the current frame interval applications set the ``pad``
field of a struct
:c:type:`v4l2_subdev_frame_interval` to
the desired pad number as reported by the media controller API. When
they call the ``VIDIOC_SUBDEV_G_FRAME_INTERVAL`` ioctl with a pointer to
this structure the driver fills the members of the ``interval`` field.

To change the current frame interval applications set both the ``pad``
field and all members of the ``interval`` field. When they call the
``VIDIOC_SUBDEV_S_FRAME_INTERVAL`` ioctl with a pointer to this
structure the driver verifies the requested interval, adjusts it based
on the hardware capabilities and configures the device. Upon return the
struct
:c:type:`v4l2_subdev_frame_interval`
contains the current frame interval as would be returned by a
``VIDIOC_SUBDEV_G_FRAME_INTERVAL`` call.

Calling ``VIDIOC_SUBDEV_S_FRAME_INTERVAL`` on a subdev device node that has been
registered in read-only mode is not allowed. An error is returned and the errno
variable is set to ``-EPERM``.

Drivers must not return an error solely because the requested interval
doesn't match the device capabilities. They must instead modify the
interval to match what the hardware can provide. The modified interval
should be as close as possible to the original request.

Changing the frame interval shall never change the format. Changing the
format, on the other hand, may change the frame interval.

Sub-devices that support the frame interval ioctls should implement them
on a single pad only. Their behaviour when supported on multiple pads of
the same sub-device is not defined.

.. c:type:: v4l2_subdev_frame_interval

.. tabularcolumns:: |p{4.4cm}|p{4.4cm}|p{8.5cm}|

.. flat-table:: struct v4l2_subdev_frame_interval
    :header-rows:  0
    :stub-columns: 0
    :widths:       1 1 2

    * - __u32
      - ``pad``
      - Pad number as reported by the media controller API.
    * - struct :c:type:`v4l2_fract`
      - ``interval``
      - Period, in seconds, between consecutive video frames.
    * - __u32
      - ``reserved``\ [9]
      - Reserved for future extensions. Applications and drivers must set
	the array to zero.

Return Value
============

On success 0 is returned, on error -1 and the ``errno`` variable is set
appropriately. The generic error codes are described at the
:ref:`Generic Error Codes <gen-errors>` chapter.

EBUSY
    The frame interval can't be changed because the pad is currently
    busy. This can be caused, for instance, by an active video stream on
    the pad. The ioctl must not be retried without performing another
    action to fix the problem first. Only returned by
    ``VIDIOC_SUBDEV_S_FRAME_INTERVAL``

EINVAL
    The struct
    :c:type:`v4l2_subdev_frame_interval`
    ``pad`` references a non-existing pad, or the pad doesn't support
    frame intervals.

EPERM
    The ``VIDIOC_SUBDEV_S_FRAME_INTERVAL`` ioctl has been called on a read-only
    subdevice.


code:
.. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later
.. c:namespace:: V4L

.. _VIDIOC_SUBDEV_G_SELECTION:

**********************************************************
ioctl VIDIOC_SUBDEV_G_SELECTION, VIDIOC_SUBDEV_S_SELECTION
**********************************************************

Name
====

VIDIOC_SUBDEV_G_SELECTION - VIDIOC_SUBDEV_S_SELECTION - Get or set selection rectangles on a subdev pad

Synopsis
========

.. c:macro:: VIDIOC_SUBDEV_G_SELECTION

``int ioctl(int fd, VIDIOC_SUBDEV_G_SELECTION, struct v4l2_subdev_selection *argp)``

.. c:macro:: VIDIOC_SUBDEV_S_SELECTION

``int ioctl(int fd, VIDIOC_SUBDEV_S_SELECTION, struct v4l2_subdev_selection *argp)``

Arguments
=========

``fd``
    File descriptor returned by :c:func:`open()`.

``argp``
    Pointer to struct :c:type:`v4l2_subdev_selection`.

Description
===========

The selections are used to configure various image processing
functionality performed by the subdevs which affect the image size. This
currently includes cropping, scaling and composition.

The selection API replaces
:ref:`the old subdev crop API <VIDIOC_SUBDEV_G_CROP>`. All the
function of the crop API, and more, are supported by the selections API.

See :ref:`subdev` for more information on how each selection target
affects the image processing pipeline inside the subdevice.

If the subdev device node has been registered in read-only mode, calls to
``VIDIOC_SUBDEV_S_SELECTION`` are only valid if the ``which`` field is set to
``V4L2_SUBDEV_FORMAT_TRY``, otherwise an error is returned and the errno
variable is set to ``-EPERM``.

Types of selection targets
--------------------------

There are two types of selection targets: actual and bounds. The actual
targets are the targets which configure the hardware. The BOUNDS target
will return a rectangle that contain all possible actual rectangles.

Discovering supported features
------------------------------

To discover which targets are supported, the user can perform
``VIDIOC_SUBDEV_G_SELECTION`` on them. Any unsupported target will
return ``EINVAL``.

Selection targets and flags are documented in
:ref:`v4l2-selections-common`.

.. c:type:: v4l2_subdev_selection

.. tabularcolumns:: |p{4.4cm}|p{4.4cm}|p{8.5cm}|

.. flat-table:: struct v4l2_subdev_selection
    :header-rows:  0
    :stub-columns: 0
    :widths:       1 1 2

    * - __u32
      - ``which``
      - Active or try selection, from enum
	:ref:`v4l2_subdev_format_whence <v4l2-subdev-format-whence>`.
    * - __u32
      - ``pad``
      - Pad number as reported by the media framework.
    * - __u32
      - ``target``
      - Target selection rectangle. See :ref:`v4l2-selections-common`.
    * - __u32
      - ``flags``
      - Flags. See :ref:`v4l2-selection-flags`.
    * - struct :c:type:`v4l2_rect`
      - ``r``
      - Selection rectangle, in pixels.
    * - __u32
      - ``reserved``\ [8]
      - Reserved for future extensions. Applications and drivers must set
	the array to zero.

Return Value
============

On success 0 is returned, on error -1 and the ``errno`` variable is set
appropriately. The generic error codes are described at the
:ref:`Generic Error Codes <gen-errors>` chapter.

EBUSY
    The selection rectangle can't be changed because the pad is
    currently busy. This can be caused, for instance, by an active video
    stream on the pad. The ioctl must not be retried without performing
    another action to fix the problem first. Only returned by
    ``VIDIOC_SUBDEV_S_SELECTION``

EINVAL
    The struct :c:type:`v4l2_subdev_selection`
    ``pad`` references a non-existing pad, the ``which`` field
    references a non-existing format, or the selection target is not
    supported on the given subdev pad.

EPERM
    The ``VIDIOC_SUBDEV_S_SELECTION`` ioctl has been called on a read-only
    subdevice and the ``which`` field is set to ``V4L2_SUBDEV_FORMAT_ACTIVE``.


code:
.. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later
.. c:namespace:: V4L

.. _VIDIOC_SUBDEV_QUERYCAP:

****************************
ioctl VIDIOC_SUBDEV_QUERYCAP
****************************

Name
====

VIDIOC_SUBDEV_QUERYCAP - Query sub-device capabilities

Synopsis
========

.. c:macro:: VIDIOC_SUBDEV_QUERYCAP

``int ioctl(int fd, VIDIOC_SUBDEV_QUERYCAP, struct v4l2_subdev_capability *argp)``

Arguments
=========

``fd``
    File descriptor returned by :c:func:`open()`.

``argp``
    Pointer to struct :c:type:`v4l2_subdev_capability`.

Description
===========

All V4L2 sub-devices support the ``VIDIOC_SUBDEV_QUERYCAP`` ioctl. It is used to
identify kernel devices compatible with this specification and to obtain
information about driver and hardware capabilities. The ioctl takes a pointer to
a struct :c:type:`v4l2_subdev_capability` which is filled by the driver. When
the driver is not compatible with this specification the ioctl returns
``ENOTTY`` error code.

.. tabularcolumns:: |p{1.5cm}|p{2.9cm}|p{12.9cm}|

.. c:type:: v4l2_subdev_capability

.. flat-table:: struct v4l2_subdev_capability
    :header-rows:  0
    :stub-columns: 0
    :widths:       3 4 20

    * - __u32
      - ``version``
      - Version number of the driver.

	The version reported is provided by the V4L2 subsystem following the
	kernel numbering scheme. However, it may not always return the same
	version as the kernel if, for example, a stable or
	distribution-modified kernel uses the V4L2 stack from a newer kernel.

	The version number is formatted using the ``KERNEL_VERSION()``
	macro:
    * - :cspan:`2`

	``#define KERNEL_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c))``

	``__u32 version = KERNEL_VERSION(0, 8, 1);``

	``printf ("Version: %u.%u.%u\\n",``

	``(version >> 16) & 0xFF, (version >> 8) & 0xFF, version & 0xFF);``
    * - __u32
      - ``capabilities``
      - Sub-device capabilities of the opened device, see
	:ref:`subdevice-capabilities`.
    * - __u32
      - ``reserved``\ [14]
      - Reserved for future extensions. Set to 0 by the V4L2 core.

.. tabularcolumns:: |p{6.8cm}|p{2.4cm}|p{8.1cm}|

.. _subdevice-capabilities:

.. cssclass:: longtable

.. flat-table:: Sub-Device Capabilities Flags
    :header-rows:  0
    :stub-columns: 0
    :widths:       3 1 4

    * - V4L2_SUBDEV_CAP_RO_SUBDEV
      - 0x00000001
      - The sub-device device node is registered in read-only mode.
	Access to the sub-device ioctls that modify the device state is
	restricted. Refer to each individual subdevice ioctl documentation
	for a description of which restrictions apply to a read-only sub-device.

Return Value
============

On success 0 is returned, on error -1 and the ``errno`` variable is set
appropriately. The generic error codes are described at the
:ref:`Generic Error Codes <gen-errors>` chapter.

ENOTTY
    The device node is not a V4L2 sub-device.


code:
.. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later
.. c:namespace:: V4L

.. _VIDIOC_SUBSCRIBE_EVENT:
.. _VIDIOC_UNSUBSCRIBE_EVENT:

******************************************************
ioctl VIDIOC_SUBSCRIBE_EVENT, VIDIOC_UNSUBSCRIBE_EVENT
******************************************************

Name
====

VIDIOC_SUBSCRIBE_EVENT - VIDIOC_UNSUBSCRIBE_EVENT - Subscribe or unsubscribe event

Synopsis
========

.. c:macro:: VIDIOC_SUBSCRIBE_EVENT

``int ioctl(int fd, VIDIOC_SUBSCRIBE_EVENT, struct v4l2_event_subscription *argp)``

.. c:macro:: VIDIOC_UNSUBSCRIBE_EVENT

``int ioctl(int fd, VIDIOC_UNSUBSCRIBE_EVENT, struct v4l2_event_subscription *argp)``

Arguments
=========

``fd``
    File descriptor returned by :c:func:`open()`.

``argp``
    Pointer to struct :c:type:`v4l2_event_subscription`.

Description
===========

Subscribe or unsubscribe V4L2 event. Subscribed events are dequeued by
using the :ref:`VIDIOC_DQEVENT` ioctl.

.. tabularcolumns:: |p{2.6cm}|p{4.4cm}|p{10.3cm}|

.. c:type:: v4l2_event_subscription

.. flat-table:: struct v4l2_event_subscription
    :header-rows:  0
    :stub-columns: 0
    :widths:       1 1 2

    * - __u32
      - ``type``
      - Type of the event, see :ref:`event-type`.

	.. note::

	   ``V4L2_EVENT_ALL`` can be used with
	   :ref:`VIDIOC_UNSUBSCRIBE_EVENT <VIDIOC_SUBSCRIBE_EVENT>` for
	   unsubscribing all events at once.
    * - __u32
      - ``id``
      - ID of the event source. If there is no ID associated with the
	event source, then set this to 0. Whether or not an event needs an
	ID depends on the event type.
    * - __u32
      - ``flags``
      - Event flags, see :ref:`event-flags`.
    * - __u32
      - ``reserved``\ [5]
      - Reserved for future extensions. Drivers and applications must set
	the array to zero.

.. tabularcolumns:: |p{7.5cm}|p{2.0cm}|p{7.8cm}|

.. _event-flags:

.. flat-table:: Event Flags
    :header-rows:  0
    :stub-columns: 0
    :widths:       3 1 4

    * - ``V4L2_EVENT_SUB_FL_SEND_INITIAL``
      - 0x0001
      - When this event is subscribed an initial event will be sent
	containing the current status. This only makes sense for events
	that are triggered by a status change such as ``V4L2_EVENT_CTRL``.
	Other events will ignore this flag.
    * - ``V4L2_EVENT_SUB_FL_ALLOW_FEEDBACK``
      - 0x0002
      - If set, then events directly caused by an ioctl will also be sent
	to the filehandle that called that ioctl. For example, changing a
	control using :ref:`VIDIOC_S_CTRL <VIDIOC_G_CTRL>` will cause
	a V4L2_EVENT_CTRL to be sent back to that same filehandle.
	Normally such events are suppressed to prevent feedback loops
	where an application changes a control to a one value and then
	another, and then receives an event telling it that that control
	has changed to the first value.

	Since it can't tell whether that event was caused by another
	application or by the :ref:`VIDIOC_S_CTRL <VIDIOC_G_CTRL>`
	call it is hard to decide whether to set the control to the value
	in the event, or ignore it.

	Think carefully when you set this flag so you won't get into
	situations like that.

Return Value
============

On success 0 is returned, on error -1 and the ``errno`` variable is set
appropriately. The generic error codes are described at the
:ref:`Generic Error Codes <gen-errors>` chapter.


code:
.. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later

.. _yuv-formats:

***********
YUV Formats
***********

YUV is the format native to TV broadcast and composite video signals. It
separates the brightness information (Y) from the color information (U
and V or Cb and Cr). The color information consists of red and blue
*color difference* signals, this way the green component can be
reconstructed by subtracting from the brightness component. See
:ref:`colorspaces` for conversion examples. YUV was chosen because
early television would only transmit brightness information. To add
color in a way compatible with existing receivers a new signal carrier
was added to transmit the color difference signals.

Subsampling
===========

YUV formats commonly encode images with a lower resolution for the chroma
components than for the luma component. This compression technique, taking
advantage of the human eye being more sensitive to luminance than color
differences, is called chroma subsampling.

While many combinations of subsampling factors in the horizontal and vertical
direction are possible, common factors are 1 (no subsampling), 2 and 4, with
horizontal subsampling always larger than or equal to vertical subsampling.
Common combinations are named as follows.

- `4:4:4`: No subsampling
- `4:2:2`: Horizontal subsampling by 2, no vertical subsampling
- `4:2:0`: Horizontal subsampling by 2, vertical subsampling by 2
- `4:1:1`: Horizontal subsampling by 4, no vertical subsampling
- `4:1:0`: Horizontal subsampling by 4, vertical subsampling by 4

Subsampling the chroma component effectively creates chroma values that can be
located in different spatial locations:

- .. _yuv-chroma-centered:

  The subsampled chroma value may be calculated by simply averaging the chroma
  value of two consecutive pixels. It effectively models the chroma of a pixel
  sited between the two original pixels. This is referred to as centered or
  interstitially sited chroma.

- .. _yuv-chroma-cosited:

  The other option is to subsample chroma values in a way that place them in
  the same spatial sites as the pixels. This may be performed by skipping every
  other chroma sample (creating aliasing artifacts), or with filters using an
  odd number of taps. This is referred to as co-sited chroma.

The following examples show different combination of chroma siting in a 4x4
image.

.. flat-table:: 4:2:2 subsampling, interstitially sited
    :header-rows: 1
    :stub-columns: 1

    * -
      - 0
      -
      - 1
      -
      - 2
      -
      - 3
    * - 0
      - Y
      - C
      - Y
      -
      - Y
      - C
      - Y
    * - 1
      - Y
      - C
      - Y
      -
      - Y
      - C
      - Y
    * - 2
      - Y
      - C
      - Y
      -
      - Y
      - C
      - Y
    * - 3
      - Y
      - C
      - Y
      -
      - Y
      - C
      - Y

.. flat-table:: 4:2:2 subsampling, co-sited
    :header-rows: 1
    :stub-columns: 1

    * -
      - 0
      -
      - 1
      -
      - 2
      -
      - 3
    * - 0
      - Y/C
      -
      - Y
      -
      - Y/C
      -
      - Y
    * - 1
      - Y/C
      -
      - Y
      -
      - Y/C
      -
      - Y
    * - 2
      - Y/C
      -
      - Y
      -
      - Y/C
      -
      - Y
    * - 3
      - Y/C
      -
      - Y
      -
      - Y/C
      -
      - Y

.. flat-table:: 4:2:0 subsampling, horizontally interstitially sited, vertically co-sited
    :header-rows: 1
    :stub-columns: 1

    * -
      - 0
      -
      - 1
      -
      - 2
      -
      - 3
    * - 0
      - Y
      - C
      - Y
      -
      - Y
      - C
      - Y
    * - 1
      - Y
      -
      - Y
      -
      - Y
      -
      - Y
    * - 2
      - Y
      - C
      - Y
      -
      - Y
      - C
      - Y
    * - 3
      - Y
      -
      - Y
      -
      - Y
      -
      - Y

.. flat-table:: 4:1:0 subsampling, horizontally and vertically interstitially sited
    :header-rows: 1
    :stub-columns: 1

    * -
      - 0
      -
      - 1
      -
      - 2
      -
      - 3
    * - 0
      - Y
      -
      - Y
      -
      - Y
      -
      - Y
    * -
      -
      -
      -
      -
      -
      -
      -
    * - 1
      - Y
      -
      - Y
      -
      - Y
      -
      - Y
    * -
      -
      -
      -
      - C
      -
      -
      -
    * - 2
      - Y
      -
      - Y
      -
      - Y
      -
      - Y
    * -
      -
      -
      -
      -
      -
      -
      -
    * - 3
      - Y
      -
      - Y
      -
      - Y
      -
      - Y

.. toctree::
    :maxdepth: 1

    pixfmt-packed-yuv
    pixfmt-yuv-planar
    pixfmt-yuv-luma
    pixfmt-y8i
    pixfmt-y12i
    pixfmt-uv8
    pixfmt-m420


code:
# SPDX-License-Identifier: GPL-2.0

# Ignore header name
ignore define _UAPI__LINUX_VIDEODEV2_H

#
# The cross reference valitator for videodev2.h DocBook never cared
# about enum symbols or defines. Yet, they're all (or almost all?)
# handled inside V4L API sections. So, for now, it is safe to just
# ignore. This should be revisited, as validating it helps to avoid
# having something not documented at the uAPI.
#

# Those symbols should not be used by uAPI - don't document them
ignore symbol V4L2_BUF_TYPE_PRIVATE
ignore symbol V4L2_TUNER_DIGITAL_TV
ignore symbol V4L2_COLORSPACE_BT878

# Documented enum v4l2_field
replace symbol V4L2_FIELD_ALTERNATE :c:type:`v4l2_field`
replace symbol V4L2_FIELD_ANY :c:type:`v4l2_field`
replace symbol V4L2_FIELD_BOTTOM :c:type:`v4l2_field`
replace symbol V4L2_FIELD_INTERLACED :c:type:`v4l2_field`
replace symbol V4L2_FIELD_INTERLACED_BT :c:type:`v4l2_field`
replace symbol V4L2_FIELD_INTERLACED_TB :c:type:`v4l2_field`
replace symbol V4L2_FIELD_NONE :c:type:`v4l2_field`
replace symbol V4L2_FIELD_SEQ_BT :c:type:`v4l2_field`
replace symbol V4L2_FIELD_SEQ_TB :c:type:`v4l2_field`
replace symbol V4L2_FIELD_TOP :c:type:`v4l2_field`

# Documented enum v4l2_buf_type
replace symbol V4L2_BUF_TYPE_META_CAPTURE :c:type:`v4l2_buf_type`
replace symbol V4L2_BUF_TYPE_META_OUTPUT :c:type:`v4l2_buf_type`
replace symbol V4L2_BUF_TYPE_SDR_CAPTURE :c:type:`v4l2_buf_type`
replace symbol V4L2_BUF_TYPE_SDR_OUTPUT :c:type:`v4l2_buf_type`
replace symbol V4L2_BUF_TYPE_SLICED_VBI_CAPTURE :c:type:`v4l2_buf_type`
replace symbol V4L2_BUF_TYPE_SLICED_VBI_OUTPUT :c:type:`v4l2_buf_type`
replace symbol V4L2_BUF_TYPE_VBI_CAPTURE :c:type:`v4l2_buf_type`
replace symbol V4L2_BUF_TYPE_VBI_OUTPUT :c:type:`v4l2_buf_type`
replace symbol V4L2_BUF_TYPE_VIDEO_CAPTURE :c:type:`v4l2_buf_type`
replace symbol V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE :c:type:`v4l2_buf_type`
replace symbol V4L2_BUF_TYPE_VIDEO_OUTPUT :c:type:`v4l2_buf_type`
replace symbol V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE :c:type:`v4l2_buf_type`
replace symbol V4L2_BUF_TYPE_VIDEO_OUTPUT_OVERLAY :c:type:`v4l2_buf_type`
replace symbol V4L2_BUF_TYPE_VIDEO_OVERLAY :c:type:`v4l2_buf_type`

# Documented enum v4l2_tuner_type
replace symbol V4L2_TUNER_ANALOG_TV :c:type:`v4l2_tuner_type`
replace symbol V4L2_TUNER_RADIO :c:type:`v4l2_tuner_type`
replace symbol V4L2_TUNER_RF :c:type:`v4l2_tuner_type`
replace symbol V4L2_TUNER_SDR :c:type:`v4l2_tuner_type`

# Documented enum v4l2_memory
replace symbol V4L2_MEMORY_DMABUF :c:type:`v4l2_memory`
replace symbol V4L2_MEMORY_MMAP :c:type:`v4l2_memory`
replace symbol V4L2_MEMORY_OVERLAY :c:type:`v4l2_memory`
replace symbol V4L2_MEMORY_USERPTR :c:type:`v4l2_memory`

# Documented enum v4l2_colorspace
replace symbol V4L2_COLORSPACE_470_SYSTEM_BG :c:type:`v4l2_colorspace`
replace symbol V4L2_COLORSPACE_470_SYSTEM_M :c:type:`v4l2_colorspace`
replace symbol V4L2_COLORSPACE_OPRGB :c:type:`v4l2_colorspace`
replace define V4L2_COLORSPACE_ADOBERGB :c:type:`v4l2_colorspace`
replace symbol V4L2_COLORSPACE_BT2020 :c:type:`v4l2_colorspace`
replace symbol V4L2_COLORSPACE_DCI_P3 :c:type:`v4l2_colorspace`
replace symbol V4L2_COLORSPACE_DEFAULT :c:type:`v4l2_colorspace`
replace symbol V4L2_COLORSPACE_JPEG :c:type:`v4l2_colorspace`
replace symbol V4L2_COLORSPACE_RAW :c:type:`v4l2_colorspace`
replace symbol V4L2_COLORSPACE_REC709 :c:type:`v4l2_colorspace`
replace symbol V4L2_COLORSPACE_SMPTE170M :c:type:`v4l2_colorspace`
replace symbol V4L2_COLORSPACE_SMPTE240M :c:type:`v4l2_colorspace`
replace symbol V4L2_COLORSPACE_SRGB :c:type:`v4l2_colorspace`
replace symbol V4L2_COLORSPACE_LAST :c:type:`v4l2_colorspace`

# Documented enum v4l2_xfer_func
replace symbol V4L2_XFER_FUNC_709 :c:type:`v4l2_xfer_func`
replace symbol V4L2_XFER_FUNC_OPRGB :c:type:`v4l2_xfer_func`
replace define V4L2_XFER_FUNC_ADOBERGB :c:type:`v4l2_xfer_func`
replace symbol V4L2_XFER_FUNC_DCI_P3 :c:type:`v4l2_xfer_func`
replace symbol V4L2_XFER_FUNC_DEFAULT :c:type:`v4l2_xfer_func`
replace symbol V4L2_XFER_FUNC_NONE :c:type:`v4l2_xfer_func`
replace symbol V4L2_XFER_FUNC_SMPTE2084 :c:type:`v4l2_xfer_func`
replace symbol V4L2_XFER_FUNC_SMPTE240M :c:type:`v4l2_xfer_func`
replace symbol V4L2_XFER_FUNC_SRGB :c:type:`v4l2_xfer_func`
replace symbol V4L2_XFER_FUNC_LAST :c:type:`v4l2_xfer_func`

# Documented enum v4l2_ycbcr_encoding
replace symbol V4L2_YCBCR_ENC_601 :c:type:`v4l2_ycbcr_encoding`
replace symbol V4L2_YCBCR_ENC_709 :c:type:`v4l2_ycbcr_encoding`
replace symbol V4L2_YCBCR_ENC_BT2020 :c:type:`v4l2_ycbcr_encoding`
replace symbol V4L2_YCBCR_ENC_BT2020_CONST_LUM :c:type:`v4l2_ycbcr_encoding`
replace symbol V4L2_YCBCR_ENC_DEFAULT :c:type:`v4l2_ycbcr_encoding`
replace symbol V4L2_YCBCR_ENC_SYCC :c:type:`v4l2_ycbcr_encoding`
replace symbol V4L2_YCBCR_ENC_XV601 :c:type:`v4l2_ycbcr_encoding`
replace symbol V4L2_YCBCR_ENC_XV709 :c:type:`v4l2_ycbcr_encoding`
replace symbol V4L2_YCBCR_ENC_SMPTE240M :c:type:`v4l2_ycbcr_encoding`
replace symbol V4L2_YCBCR_ENC_LAST :c:type:`v4l2_ycbcr_encoding`

# Documented enum v4l2_hsv_encoding
replace symbol V4L2_HSV_ENC_180 :c:type:`v4l2_hsv_encoding`
replace symbol V4L2_HSV_ENC_256 :c:type:`v4l2_hsv_encoding`

# Documented enum v4l2_quantization
replace symbol V4L2_QUANTIZATION_DEFAULT :c:type:`v4l2_quantization`
replace symbol V4L2_QUANTIZATION_FULL_RANGE :c:type:`v4l2_quantization`
replace symbol V4L2_QUANTIZATION_LIM_RANGE :c:type:`v4l2_quantization`

# Documented enum v4l2_priority
replace symbol V4L2_PRIORITY_BACKGROUND :c:type:`v4l2_priority`
replace symbol V4L2_PRIORITY_DEFAULT :c:type:`v4l2_priority`
replace symbol V4L2_PRIORITY_INTERACTIVE :c:type:`v4l2_priority`
replace symbol V4L2_PRIORITY_RECORD :c:type:`v4l2_priority`
replace symbol V4L2_PRIORITY_UNSET :c:type:`v4l2_priority`

# Documented enum v4l2_frmsizetypes
replace symbol V4L2_FRMSIZE_TYPE_CONTINUOUS :c:type:`v4l2_frmsizetypes`
replace symbol V4L2_FRMSIZE_TYPE_DISCRETE :c:type:`v4l2_frmsizetypes`
replace symbol V4L2_FRMSIZE_TYPE_STEPWISE :c:type:`v4l2_frmsizetypes`

# Documented enum frmivaltypes
replace symbol V4L2_FRMIVAL_TYPE_CONTINUOUS :c:type:`v4l2_frmivaltypes`
replace symbol V4L2_FRMIVAL_TYPE_DISCRETE :c:type:`v4l2_frmivaltypes`
replace symbol V4L2_FRMIVAL_TYPE_STEPWISE :c:type:`v4l2_frmivaltypes`

# Documented enum :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_COMPOUND_TYPES vidioc_queryctrl

replace symbol V4L2_CTRL_TYPE_BITMASK :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_BOOLEAN :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_BUTTON :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_CTRL_CLASS :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_INTEGER :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_INTEGER64 :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_INTEGER_MENU :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_MENU :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_STRING :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_U16 :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_U32 :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_U8 :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_MPEG2_SEQUENCE :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_MPEG2_PICTURE :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_MPEG2_QUANTISATION :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_H264_SPS :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_H264_PPS :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_H264_SCALING_MATRIX :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_H264_PRED_WEIGHTS :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_H264_SLICE_PARAMS :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_H264_DECODE_PARAMS :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_HEVC_SPS :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_HEVC_PPS :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_HEVC_SLICE_PARAMS :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_AREA :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_FWHT_PARAMS :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_VP8_FRAME :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_VP9_COMPRESSED_HDR :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_VP9_FRAME :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_HDR10_CLL_INFO :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_HDR10_MASTERING_DISPLAY :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_HEVC_SPS :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_HEVC_PPS :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_HEVC_SLICE_PARAMS :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_HEVC_SCALING_MATRIX :c:type:`v4l2_ctrl_type`
replace symbol V4L2_CTRL_TYPE_HEVC_DECODE_PARAMS :c:type:`v4l2_ctrl_type`

# V4L2 capability defines
replace define V4L2_CAP_VIDEO_CAPTURE device-capabilities
replace define V4L2_CAP_VIDEO_CAPTURE_MPLANE device-capabilities
replace define V4L2_CAP_VIDEO_OUTPUT device-capabilities
replace define V4L2_CAP_VIDEO_OUTPUT_MPLANE device-capabilities
replace define V4L2_CAP_VIDEO_M2M device-capabilities
replace define V4L2_CAP_VIDEO_M2M_MPLANE device-capabilities
replace define V4L2_CAP_VIDEO_OVERLAY device-capabilities
replace define V4L2_CAP_VBI_CAPTURE device-capabilities
replace define V4L2_CAP_VBI_OUTPUT device-capabilities
replace define V4L2_CAP_SLICED_VBI_CAPTURE device-capabilities
replace define V4L2_CAP_SLICED_VBI_OUTPUT device-capabilities
replace define V4L2_CAP_RDS_CAPTURE device-capabilities
replace define V4L2_CAP_VIDEO_OUTPUT_OVERLAY device-capabilities
replace define V4L2_CAP_HW_FREQ_SEEK device-capabilities
replace define V4L2_CAP_RDS_OUTPUT device-capabilities
replace define V4L2_CAP_TUNER device-capabilities
replace define V4L2_CAP_AUDIO device-capabilities
replace define V4L2_CAP_RADIO device-capabilities
replace define V4L2_CAP_MODULATOR device-capabilities
replace define V4L2_CAP_SDR_CAPTURE device-capabilities
replace define V4L2_CAP_EXT_PIX_FORMAT device-capabilities
replace define V4L2_CAP_SDR_OUTPUT device-capabilities
replace define V4L2_CAP_META_CAPTURE device-capabilities
replace define V4L2_CAP_READWRITE device-capabilities
replace define V4L2_CAP_ASYNCIO device-capabilities
replace define V4L2_CAP_STREAMING device-capabilities
replace define V4L2_CAP_META_OUTPUT device-capabilities
replace define V4L2_CAP_DEVICE_CAPS device-capabilities
replace define V4L2_CAP_TOUCH device-capabilities
replace define V4L2_CAP_IO_MC device-capabilities

# V4L2 pix flags
replace define V4L2_PIX_FMT_PRIV_MAGIC :c:type:`v4l2_pix_format`
replace define V4L2_PIX_FMT_FLAG_PREMUL_ALPHA format-flags
replace define V4L2_PIX_FMT_HM12 :c:type:`v4l2_pix_format`
replace define V4L2_PIX_FMT_SUNXI_TILED_NV12 :c:type:`v4l2_pix_format`

# V4L2 format flags
replace define V4L2_FMT_FLAG_COMPRESSED fmtdesc-flags
replace define V4L2_FMT_FLAG_EMULATED fmtdesc-flags
replace define V4L2_FMT_FLAG_CONTINUOUS_BYTESTREAM fmtdesc-flags
replace define V4L2_FMT_FLAG_DYN_RESOLUTION fmtdesc-flags
replace define V4L2_FMT_FLAG_ENC_CAP_FRAME_INTERVAL fmtdesc-flags
replace define V4L2_FMT_FLAG_CSC_COLORSPACE fmtdesc-flags
replace define V4L2_FMT_FLAG_CSC_XFER_FUNC fmtdesc-flags
replace define V4L2_FMT_FLAG_CSC_YCBCR_ENC fmtdesc-flags
replace define V4L2_FMT_FLAG_CSC_HSV_ENC fmtdesc-flags
replace define V4L2_FMT_FLAG_CSC_QUANTIZATION fmtdesc-flags

# V4L2 timecode types
replace define V4L2_TC_TYPE_24FPS timecode-type
replace define V4L2_TC_TYPE_25FPS timecode-type
replace define V4L2_TC_TYPE_30FPS timecode-type
replace define V4L2_TC_TYPE_50FPS timecode-type
replace define V4L2_TC_TYPE_60FPS timecode-type

# V4L2 timecode flags
replace define V4L2_TC_FLAG_DROPFRAME timecode-flags
replace define V4L2_TC_FLAG_COLORFRAME timecode-flags
replace define V4L2_TC_USERBITS_field timecode-flags
replace define V4L2_TC_USERBITS_USERDEFINED timecode-flags
replace define V4L2_TC_USERBITS_8BITCHARS timecode-flags

# V4L2 JPEG markers
replace define V4L2_JPEG_MARKER_DHT jpeg-markers
replace define V4L2_JPEG_MARKER_DQT jpeg-markers
replace define V4L2_JPEG_MARKER_DRI jpeg-markers
replace define V4L2_JPEG_MARKER_COM jpeg-markers
replace define V4L2_JPEG_MARKER_APP jpeg-markers

# V4L2 framebuffer caps and flags

replace define V4L2_FBUF_CAP_EXTERNOVERLAY framebuffer-cap
replace define V4L2_FBUF_CAP_CHROMAKEY framebuffer-cap
replace define V4L2_FBUF_CAP_LIST_CLIPPING framebuffer-cap
replace define V4L2_FBUF_CAP_BITMAP_CLIPPING framebuffer-cap
replace define V4L2_FBUF_CAP_LOCAL_ALPHA framebuffer-cap
replace define V4L2_FBUF_CAP_GLOBAL_ALPHA framebuffer-cap
replace define V4L2_FBUF_CAP_LOCAL_INV_ALPHA framebuffer-cap
replace define V4L2_FBUF_CAP_SRC_CHROMAKEY framebuffer-cap

replace define V4L2_FBUF_FLAG_PRIMARY framebuffer-flags
replace define V4L2_FBUF_FLAG_OVERLAY framebuffer-flags
replace define V4L2_FBUF_FLAG_CHROMAKEY framebuffer-flags
replace define V4L2_FBUF_FLAG_LOCAL_ALPHA framebuffer-flags
replace define V4L2_FBUF_FLAG_GLOBAL_ALPHA framebuffer-flags
replace define V4L2_FBUF_FLAG_LOCAL_INV_ALPHA framebuffer-flags
replace define V4L2_FBUF_FLAG_SRC_CHROMAKEY framebuffer-flags

# Used on VIDIOC_G_PARM

replace define V4L2_MODE_HIGHQUALITY parm-flags
replace define V4L2_CAP_TIMEPERFRAME :c:type:`v4l2_captureparm`

# The V4L2_STD_foo are all defined at v4l2_std_id table

replace define V4L2_STD_PAL_B v4l2-std-id
replace define V4L2_STD_PAL_B1 v4l2-std-id
replace define V4L2_STD_PAL_G v4l2-std-id
replace define V4L2_STD_PAL_H v4l2-std-id
replace define V4L2_STD_PAL_I v4l2-std-id
replace define V4L2_STD_PAL_D v4l2-std-id
replace define V4L2_STD_PAL_D1 v4l2-std-id
replace define V4L2_STD_PAL_K v4l2-std-id
replace define V4L2_STD_PAL_M v4l2-std-id
replace define V4L2_STD_PAL_N v4l2-std-id
replace define V4L2_STD_PAL_Nc v4l2-std-id
replace define V4L2_STD_PAL_60 v4l2-std-id
replace define V4L2_STD_NTSC_M v4l2-std-id
replace define V4L2_STD_NTSC_M_JP v4l2-std-id
replace define V4L2_STD_NTSC_443 v4l2-std-id
replace define V4L2_STD_NTSC_M_KR v4l2-std-id
replace define V4L2_STD_SECAM_B v4l2-std-id
replace define V4L2_STD_SECAM_D v4l2-std-id
replace define V4L2_STD_SECAM_G v4l2-std-id
replace define V4L2_STD_SECAM_H v4l2-std-id
replace define V4L2_STD_SECAM_K v4l2-std-id
replace define V4L2_STD_SECAM_K1 v4l2-std-id
replace define V4L2_STD_SECAM_L v4l2-std-id
replace define V4L2_STD_SECAM_LC v4l2-std-id
replace define V4L2_STD_ATSC_8_VSB v4l2-std-id
replace define V4L2_STD_ATSC_16_VSB v4l2-std-id
replace define V4L2_STD_NTSC v4l2-std-id
replace define V4L2_STD_SECAM_DK v4l2-std-id
replace define V4L2_STD_SECAM v4l2-std-id
replace define V4L2_STD_PAL_BG v4l2-std-id
replace define V4L2_STD_PAL_DK v4l2-std-id
replace define V4L2_STD_PAL v4l2-std-id
replace define V4L2_STD_B v4l2-std-id
replace define V4L2_STD_G v4l2-std-id
replace define V4L2_STD_H v4l2-std-id
replace define V4L2_STD_L v4l2-std-id
replace define V4L2_STD_GH v4l2-std-id
replace define V4L2_STD_DK v4l2-std-id
replace define V4L2_STD_BG v4l2-std-id
replace define V4L2_STD_MN v4l2-std-id
replace define V4L2_STD_MTS v4l2-std-id
replace define V4L2_STD_525_60 v4l2-std-id
replace define V4L2_STD_625_50 v4l2-std-id
replace define V4L2_STD_ATSC v4l2-std-id
replace define V4L2_STD_UNKNOWN v4l2-std-id
replace define V4L2_STD_ALL v4l2-std-id

# V4L2 DT BT timings definitions

replace define V4L2_DV_PROGRESSIVE :c:type:`v4l2_bt_timings`
replace define V4L2_DV_INTERLACED :c:type:`v4l2_bt_timings`

replace define V4L2_DV_VSYNC_POS_POL :c:type:`v4l2_bt_timings`
replace define V4L2_DV_HSYNC_POS_POL :c:type:`v4l2_bt_timings`

replace define V4L2_DV_BT_STD_CEA861 dv-bt-standards
replace define V4L2_DV_BT_STD_DMT dv-bt-standards
replace define V4L2_DV_BT_STD_CVT dv-bt-standards
replace define V4L2_DV_BT_STD_GTF dv-bt-standards
replace define V4L2_DV_BT_STD_SDI dv-bt-standards

replace define V4L2_DV_FL_REDUCED_BLANKING dv-bt-standards
replace define V4L2_DV_FL_CAN_REDUCE_FPS dv-bt-standards
replace define V4L2_DV_FL_CAN_DETECT_REDUCED_FPS dv-bt-standards
replace define V4L2_DV_FL_REDUCED_FPS dv-bt-standards
replace define V4L2_DV_FL_HALF_LINE dv-bt-standards
replace define V4L2_DV_FL_IS_CE_VIDEO dv-bt-standards
replace define V4L2_DV_FL_FIRST_FIELD_EXTRA_LINE dv-bt-standards
replace define V4L2_DV_FL_HAS_PICTURE_ASPECT dv-bt-standards
replace define V4L2_DV_FL_HAS_CEA861_VIC dv-bt-standards
replace define V4L2_DV_FL_HAS_HDMI_VIC dv-bt-standards

replace define V4L2_DV_BT_656_1120 dv-timing-types

replace define V4L2_DV_BT_CAP_INTERLACED framebuffer-cap
replace define V4L2_DV_BT_CAP_PROGRESSIVE framebuffer-cap
replace define V4L2_DV_BT_CAP_REDUCED_BLANKING framebuffer-cap
replace define V4L2_DV_BT_CAP_CUSTOM framebuffer-cap

# V4L2 input

replace define V4L2_INPUT_TYPE_TUNER input-type
replace define V4L2_INPUT_TYPE_CAMERA input-type
replace define V4L2_INPUT_TYPE_TOUCH input-type

replace define V4L2_IN_ST_NO_POWER input-status
replace define V4L2_IN_ST_NO_SIGNAL input-status
replace define V4L2_IN_ST_NO_COLOR input-status
replace define V4L2_IN_ST_HFLIP input-status
replace define V4L2_IN_ST_VFLIP input-status
replace define V4L2_IN_ST_NO_H_LOCK input-status
replace define V4L2_IN_ST_COLOR_KILL input-status
replace define V4L2_IN_ST_NO_SYNC input-status
replace define V4L2_IN_ST_NO_EQU input-status
replace define V4L2_IN_ST_NO_CARRIER input-status
replace define V4L2_IN_ST_MACROVISION input-status
replace define V4L2_IN_ST_NO_ACCESS input-status
replace define V4L2_IN_ST_VTR input-status
replace define V4L2_IN_ST_NO_V_LOCK input-status
replace define V4L2_IN_ST_NO_STD_LOCK input-status

replace define V4L2_IN_CAP_DV_TIMINGS input-capabilities
replace define V4L2_IN_CAP_STD input-capabilities
replace define V4L2_IN_CAP_NATIVE_SIZE input-capabilities

# V4L2 output

replace define V4L2_OUTPUT_TYPE_MODULATOR output-type
replace define V4L2_OUTPUT_TYPE_ANALOG output-type
replace define V4L2_OUTPUT_TYPE_ANALOGVGAOVERLAY output-type

replace define V4L2_OUT_CAP_DV_TIMINGS output-capabilities
replace define V4L2_OUT_CAP_STD output-capabilities
replace define V4L2_OUT_CAP_NATIVE_SIZE output-capabilities

# V4L2 control flags

replace define V4L2_CTRL_FLAG_DISABLED control-flags
replace define V4L2_CTRL_FLAG_GRABBED control-flags
replace define V4L2_CTRL_FLAG_READ_ONLY control-flags
replace define V4L2_CTRL_FLAG_UPDATE control-flags
replace define V4L2_CTRL_FLAG_INACTIVE control-flags
replace define V4L2_CTRL_FLAG_SLIDER control-flags
replace define V4L2_CTRL_FLAG_WRITE_ONLY control-flags
replace define V4L2_CTRL_FLAG_VOLATILE control-flags
replace define V4L2_CTRL_FLAG_HAS_PAYLOAD control-flags
replace define V4L2_CTRL_FLAG_EXECUTE_ON_WRITE control-flags
replace define V4L2_CTRL_FLAG_MODIFY_LAYOUT control-flags
replace define V4L2_CTRL_FLAG_DYNAMIC_ARRAY control-flags

replace define V4L2_CTRL_FLAG_NEXT_CTRL control
replace define V4L2_CTRL_FLAG_NEXT_COMPOUND control
replace define V4L2_CID_PRIVATE_BASE control

# V4L2 tuner

replace define V4L2_TUNER_CAP_LOW tuner-capability
replace define V4L2_TUNER_CAP_NORM tuner-capability
replace define V4L2_TUNER_CAP_HWSEEK_BOUNDED tuner-capability
replace define V4L2_TUNER_CAP_HWSEEK_WRAP tuner-capability
replace define V4L2_TUNER_CAP_STEREO tuner-capability
replace define V4L2_TUNER_CAP_LANG2 tuner-capability
replace define V4L2_TUNER_CAP_SAP tuner-capability
replace define V4L2_TUNER_CAP_LANG1 tuner-capability
replace define V4L2_TUNER_CAP_RDS tuner-capability
replace define V4L2_TUNER_CAP_RDS_BLOCK_IO tuner-capability
replace define V4L2_TUNER_CAP_RDS_CONTROLS tuner-capability
replace define V4L2_TUNER_CAP_FREQ_BANDS tuner-capability
replace define V4L2_TUNER_CAP_HWSEEK_PROG_LIM tuner-capability
replace define V4L2_TUNER_CAP_1HZ tuner-capability

replace define V4L2_TUNER_SUB_MONO tuner-rxsubchans
replace define V4L2_TUNER_SUB_STEREO tuner-rxsubchans
replace define V4L2_TUNER_SUB_LANG2 tuner-rxsubchans
replace define V4L2_TUNER_SUB_SAP tuner-rxsubchans
replace define V4L2_TUNER_SUB_LANG1 tuner-rxsubchans
replace define V4L2_TUNER_SUB_RDS tuner-rxsubchans

replace define V4L2_TUNER_MODE_MONO tuner-audmode
replace define V4L2_TUNER_MODE_STEREO tuner-audmode
replace define V4L2_TUNER_MODE_LANG2 tuner-audmode
replace define V4L2_TUNER_MODE_SAP tuner-audmode
replace define V4L2_TUNER_MODE_LANG1 tuner-audmode
replace define V4L2_TUNER_MODE_LANG1_LANG2 tuner-audmode

replace define V4L2_BAND_MODULATION_VSB band-modulation
replace define V4L2_BAND_MODULATION_FM band-modulation
replace define V4L2_BAND_MODULATION_AM band-modulation

replace define V4L2_RDS_BLOCK_MSK v4l2-rds-block
replace define V4L2_RDS_BLOCK_A v4l2-rds-block
replace define V4L2_RDS_BLOCK_B v4l2-rds-block
replace define V4L2_RDS_BLOCK_C v4l2-rds-block
replace define V4L2_RDS_BLOCK_D v4l2-rds-block
replace define V4L2_RDS_BLOCK_C_ALT v4l2-rds-block
replace define V4L2_RDS_BLOCK_INVALID v4l2-rds-block
replace define V4L2_RDS_BLOCK_CORRECTED v4l2-rds-block
replace define V4L2_RDS_BLOCK_ERROR v4l2-rds-block

# V4L2 audio

replace define V4L2_AUDCAP_STEREO audio-capability
replace define V4L2_AUDCAP_AVL audio-capability

replace define V4L2_AUDMODE_AVL audio-mode

# MPEG

replace define V4L2_ENC_IDX_FRAME_I :c:type:`v4l2_enc_idx`
replace define V4L2_ENC_IDX_FRAME_P :c:type:`v4l2_enc_idx`
replace define V4L2_ENC_IDX_FRAME_B :c:type:`v4l2_enc_idx`
replace define V4L2_ENC_IDX_FRAME_MASK :c:type:`v4l2_enc_idx`
replace define V4L2_ENC_IDX_ENTRIES :c:type:`v4l2_enc_idx`

replace define V4L2_ENC_CMD_START encoder-cmds
replace define V4L2_ENC_CMD_STOP encoder-cmds
replace define V4L2_ENC_CMD_PAUSE encoder-cmds
replace define V4L2_ENC_CMD_RESUME encoder-cmds

replace define V4L2_ENC_CMD_STOP_AT_GOP_END encoder-flags

replace define V4L2_DEC_CMD_START decoder-cmds
replace define V4L2_DEC_CMD_STOP decoder-cmds
replace define V4L2_DEC_CMD_PAUSE decoder-cmds
replace define V4L2_DEC_CMD_RESUME decoder-cmds
replace define V4L2_DEC_CMD_FLUSH decoder-cmds

replace define V4L2_DEC_CMD_START_MUTE_AUDIO decoder-cmds
replace define V4L2_DEC_CMD_PAUSE_TO_BLACK decoder-cmds
replace define V4L2_DEC_CMD_STOP_TO_BLACK decoder-cmds
replace define V4L2_DEC_CMD_STOP_IMMEDIATELY decoder-cmds

replace define V4L2_DEC_START_FMT_NONE decoder-cmds
replace define V4L2_DEC_START_FMT_GOP decoder-cmds

# V4L2 VBI

replace define V4L2_VBI_UNSYNC vbifmt-flags
replace define V4L2_VBI_INTERLACED vbifmt-flags

replace define V4L2_VBI_ITU_525_F1_START :c:type:`v4l2_vbi_format`
replace define V4L2_VBI_ITU_525_F2_START :c:type:`v4l2_vbi_format`
replace define V4L2_VBI_ITU_625_F1_START :c:type:`v4l2_vbi_format`
replace define V4L2_VBI_ITU_625_F2_START :c:type:`v4l2_vbi_format`

replace define V4L2_SLICED_TELETEXT_B vbi-services
replace define V4L2_SLICED_VPS vbi-services
replace define V4L2_SLICED_CAPTION_525 vbi-services
replace define V4L2_SLICED_WSS_625 vbi-services
replace define V4L2_SLICED_VBI_525 vbi-services
replace define V4L2_SLICED_VBI_625 vbi-services

replace define V4L2_MPEG_VBI_IVTV_TELETEXT_B ITV0-Line-Identifier-Constants
replace define V4L2_MPEG_VBI_IVTV_CAPTION_525 ITV0-Line-Identifier-Constants
replace define V4L2_MPEG_VBI_IVTV_WSS_625 ITV0-Line-Identifier-Constants
replace define V4L2_MPEG_VBI_IVTV_VPS ITV0-Line-Identifier-Constants

replace define V4L2_MPEG_VBI_IVTV_MAGIC0 v4l2-mpeg-vbi-fmt-ivtv-magic
replace define V4L2_MPEG_VBI_IVTV_MAGIC1 v4l2-mpeg-vbi-fmt-ivtv-magic

# V4L2 events

replace define V4L2_EVENT_ALL event-type
replace define V4L2_EVENT_VSYNC event-type
replace define V4L2_EVENT_EOS event-type
replace define V4L2_EVENT_CTRL event-type
replace define V4L2_EVENT_FRAME_SYNC event-type
replace define V4L2_EVENT_SOURCE_CHANGE event-type
replace define V4L2_EVENT_MOTION_DET event-type
replace define V4L2_EVENT_PRIVATE_START event-type

replace define V4L2_EVENT_CTRL_CH_VALUE ctrl-changes-flags
replace define V4L2_EVENT_CTRL_CH_FLAGS ctrl-changes-flags
replace define V4L2_EVENT_CTRL_CH_RANGE ctrl-changes-flags
replace define V4L2_EVENT_CTRL_CH_DIMENSIONS ctrl-changes-flags

replace define V4L2_EVENT_SRC_CH_RESOLUTION src-changes-flags

replace define V4L2_EVENT_MD_FL_HAVE_FRAME_SEQ :c:type:`v4l2_event_motion_det`

replace define V4L2_EVENT_SUB_FL_SEND_INITIAL event-flags
replace define V4L2_EVENT_SUB_FL_ALLOW_FEEDBACK event-flags

# V4L2 debugging
replace define V4L2_CHIP_MATCH_BRIDGE vidioc_dbg_g_register
replace define V4L2_CHIP_MATCH_SUBDEV vidioc_dbg_g_register
replace define V4L2_CHIP_MATCH_HOST vidioc_dbg_g_register
replace define V4L2_CHIP_MATCH_I2C_DRIVER vidioc_dbg_g_register
replace define V4L2_CHIP_MATCH_I2C_ADDR vidioc_dbg_g_register
replace define V4L2_CHIP_MATCH_AC97 vidioc_dbg_g_register

replace define V4L2_CHIP_FL_READABLE vidioc_dbg_g_register
replace define V4L2_CHIP_FL_WRITABLE vidioc_dbg_g_register

# Ignore reserved ioctl and ancillary macros

ignore define VIDEO_MAX_FRAME
ignore define VIDEO_MAX_PLANES
ignore define v4l2_fourcc
ignore define v4l2_fourcc_be
ignore define V4L2_FIELD_HAS_TOP
ignore define V4L2_FIELD_HAS_BOTTOM
ignore define V4L2_FIELD_HAS_BOTH
ignore define V4L2_FIELD_HAS_T_OR_B
ignore define V4L2_TYPE_IS_MULTIPLANAR
ignore define V4L2_TYPE_IS_OUTPUT
ignore define V4L2_TUNER_ADC
ignore define V4L2_MAP_COLORSPACE_DEFAULT
ignore define V4L2_MAP_XFER_FUNC_DEFAULT
ignore define V4L2_MAP_YCBCR_ENC_DEFAULT
ignore define V4L2_DV_BT_BLANKING_WIDTH
ignore define V4L2_DV_BT_FRAME_WIDTH
ignore define V4L2_DV_BT_BLANKING_HEIGHT
ignore define V4L2_DV_BT_FRAME_HEIGHT
ignore define V4L2_IN_CAP_CUSTOM_TIMINGS
ignore define V4L2_CTRL_ID_MASK
ignore define V4L2_CTRL_ID2CLASS
ignore define V4L2_CTRL_ID2WHICH
ignore define V4L2_CTRL_DRIVER_PRIV
ignore define V4L2_CTRL_MAX_DIMS
ignore define V4L2_CTRL_WHICH_CUR_VAL
ignore define V4L2_CTRL_WHICH_DEF_VAL
ignore define V4L2_CTRL_WHICH_REQUEST_VAL
ignore define V4L2_OUT_CAP_CUSTOM_TIMINGS
ignore define V4L2_CID_MAX_CTRLS

ignore define BASE_VIDIOC_PRIVATE

# Associate ioctls with their counterparts
replace ioctl VIDIOC_DBG_S_REGISTER vidioc_dbg_g_register
replace ioctl VIDIOC_DQBUF vidioc_qbuf
replace ioctl VIDIOC_S_AUDOUT vidioc_g_audout
replace ioctl VIDIOC_S_CROP vidioc_g_crop
replace ioctl VIDIOC_S_CTRL vidioc_g_ctrl
replace ioctl VIDIOC_S_DV_TIMINGS vidioc_g_dv_timings
replace ioctl VIDIOC_S_EDID vidioc_g_edid
replace ioctl VIDIOC_S_EXT_CTRLS vidioc_g_ext_ctrls
replace ioctl VIDIOC_S_FBUF vidioc_g_fbuf
replace ioctl VIDIOC_S_FMT vidioc_g_fmt
replace ioctl VIDIOC_S_FREQUENCY vidioc_g_frequency
replace ioctl VIDIOC_S_INPUT vidioc_g_input
replace ioctl VIDIOC_S_JPEGCOMP vidioc_g_jpegcomp
replace ioctl VIDIOC_S_MODULATOR vidioc_g_modulator
replace ioctl VIDIOC_S_OUTPUT vidioc_g_output
replace ioctl VIDIOC_S_PARM vidioc_g_parm
replace ioctl VIDIOC_S_PRIORITY vidioc_g_priority
replace ioctl VIDIOC_S_SELECTION vidioc_g_selection
replace ioctl VIDIOC_S_STD vidioc_g_std
replace ioctl VIDIOC_S_AUDIO vidioc_g_audio
replace ioctl VIDIOC_S_TUNER vidioc_g_tuner
replace ioctl VIDIOC_TRY_DECODER_CMD vidioc_decoder_cmd
replace ioctl VIDIOC_TRY_ENCODER_CMD vidioc_encoder_cmd
replace ioctl VIDIOC_TRY_EXT_CTRLS vidioc_g_ext_ctrls
replace ioctl VIDIOC_TRY_FMT vidioc_g_fmt
replace ioctl VIDIOC_STREAMOFF vidioc_streamon
replace ioctl VIDIOC_QUERY_EXT_CTRL vidioc_queryctrl
replace ioctl VIDIOC_QUERYMENU vidioc_queryctrl


code:
.. SPDX-License-Identifier: BSD-3-Clause

================
Netlink Handbook
================

Netlink documentation for users.

.. toctree::
   :maxdepth: 2

   intro


code:
.. SPDX-License-Identifier: BSD-3-Clause

=======================
Introduction to Netlink
=======================

Netlink is often described as an ioctl() replacement.
It aims to replace fixed-format C structures as supplied
to ioctl() with a format which allows an easy way to add
or extended the arguments.

To achieve this Netlink uses a minimal fixed-format metadata header
followed by multiple attributes in the TLV (type, length, value) format.

Unfortunately the protocol has evolved over the years, in an organic
and undocumented fashion, making it hard to coherently explain.
To make the most practical sense this document starts by describing
netlink as it is used today and dives into more "historical" uses
in later sections.

Opening a socket
================

Netlink communication happens over sockets, a socket needs to be
opened first:

.. code-block:: c

  fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC);

The use of sockets allows for a natural way of exchanging information
in both directions (to and from the kernel). The operations are still
performed synchronously when applications send() the request but
a separate recv() system call is needed to read the reply.

A very simplified flow of a Netlink "call" will therefore look
something like:

.. code-block:: c

  fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC);

  /* format the request */
  send(fd, &request, sizeof(request));
  n = recv(fd, &response, RSP_BUFFER_SIZE);
  /* interpret the response */

Netlink also provides natural support for "dumping", i.e. communicating
to user space all objects of a certain type (e.g. dumping all network
interfaces).

.. code-block:: c

  fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC);

  /* format the dump request */
  send(fd, &request, sizeof(request));
  while (1) {
    n = recv(fd, &buffer, RSP_BUFFER_SIZE);
    /* one recv() call can read multiple messages, hence the loop below */
    for (nl_msg in buffer) {
      if (nl_msg.nlmsg_type == NLMSG_DONE)
        goto dump_finished;
      /* process the object */
    }
  }
  dump_finished:

The first two arguments of the socket() call require little explanation -
it is opening a Netlink socket, with all headers provided by the user
(hence NETLINK, RAW). The last argument is the protocol within Netlink.
This field used to identify the subsystem with which the socket will
communicate.

Classic vs Generic Netlink
--------------------------

Initial implementation of Netlink depended on a static allocation
of IDs to subsystems and provided little supporting infrastructure.
Let us refer to those protocols collectively as **Classic Netlink**.
The list of them is defined on top of the ``include/uapi/linux/netlink.h``
file, they include among others - general networking (NETLINK_ROUTE),
iSCSI (NETLINK_ISCSI), and audit (NETLINK_AUDIT).

**Generic Netlink** (introduced in 2005) allows for dynamic registration of
subsystems (and subsystem ID allocation), introspection and simplifies
implementing the kernel side of the interface.

The following section describes how to use Generic Netlink, as the
number of subsystems using Generic Netlink outnumbers the older
protocols by an order of magnitude. There are also no plans for adding
more Classic Netlink protocols to the kernel.
Basic information on how communicating with core networking parts of
the Linux kernel (or another of the 20 subsystems using Classic
Netlink) differs from Generic Netlink is provided later in this document.

Generic Netlink
===============

In addition to the Netlink fixed metadata header each Netlink protocol
defines its own fixed metadata header. (Similarly to how network
headers stack - Ethernet > IP > TCP we have Netlink > Generic N. > Family.)

A Netlink message always starts with struct nlmsghdr, which is followed
by a protocol-specific header. In case of Generic Netlink the protocol
header is struct genlmsghdr.

The practical meaning of the fields in case of Generic Netlink is as follows:

.. code-block:: c

  struct nlmsghdr {
	__u32	nlmsg_len;	/* Length of message including headers */
	__u16	nlmsg_type;	/* Generic Netlink Family (subsystem) ID */
	__u16	nlmsg_flags;	/* Flags - request or dump */
	__u32	nlmsg_seq;	/* Sequence number */
	__u32	nlmsg_pid;	/* Port ID, set to 0 */
  };
  struct genlmsghdr {
	__u8	cmd;		/* Command, as defined by the Family */
	__u8	version;	/* Irrelevant, set to 1 */
	__u16	reserved;	/* Reserved, set to 0 */
  };
  /* TLV attributes follow... */

In Classic Netlink :c:member:`nlmsghdr.nlmsg_type` used to identify
which operation within the subsystem the message was referring to
(e.g. get information about a netdev). Generic Netlink needs to mux
multiple subsystems in a single protocol so it uses this field to
identify the subsystem, and :c:member:`genlmsghdr.cmd` identifies
the operation instead. (See :ref:`res_fam` for
information on how to find the Family ID of the subsystem of interest.)
Note that the first 16 values (0 - 15) of this field are reserved for
control messages both in Classic Netlink and Generic Netlink.
See :ref:`nl_msg_type` for more details.

There are 3 usual types of message exchanges on a Netlink socket:

 - performing a single action (``do``);
 - dumping information (``dump``);
 - getting asynchronous notifications (``multicast``).

Classic Netlink is very flexible and presumably allows other types
of exchanges to happen, but in practice those are the three that get
used.

Asynchronous notifications are sent by the kernel and received by
the user sockets which subscribed to them. ``do`` and ``dump`` requests
are initiated by the user. :c:member:`nlmsghdr.nlmsg_flags` should
be set as follows:

 - for ``do``: ``NLM_F_REQUEST | NLM_F_ACK``
 - for ``dump``: ``NLM_F_REQUEST | NLM_F_ACK | NLM_F_DUMP``

:c:member:`nlmsghdr.nlmsg_seq` should be a set to a monotonically
increasing value. The value gets echoed back in responses and doesn't
matter in practice, but setting it to an increasing value for each
message sent is considered good hygiene. The purpose of the field is
matching responses to requests. Asynchronous notifications will have
:c:member:`nlmsghdr.nlmsg_seq` of ``0``.

:c:member:`nlmsghdr.nlmsg_pid` is the Netlink equivalent of an address.
This field can be set to ``0`` when talking to the kernel.
See :ref:`nlmsg_pid` for the (uncommon) uses of the field.

The expected use for :c:member:`genlmsghdr.version` was to allow
versioning of the APIs provided by the subsystems. No subsystem to
date made significant use of this field, so setting it to ``1`` seems
like a safe bet.

.. _nl_msg_type:

Netlink message types
---------------------

As previously mentioned :c:member:`nlmsghdr.nlmsg_type` carries
protocol specific values but the first 16 identifiers are reserved
(first subsystem specific message type should be equal to
``NLMSG_MIN_TYPE`` which is ``0x10``).

There are only 4 Netlink control messages defined:

 - ``NLMSG_NOOP`` - ignore the message, not used in practice;
 - ``NLMSG_ERROR`` - carries the return code of an operation;
 - ``NLMSG_DONE`` - marks the end of a dump;
 - ``NLMSG_OVERRUN`` - socket buffer has overflown, not used to date.

``NLMSG_ERROR`` and ``NLMSG_DONE`` are of practical importance.
They carry return codes for operations. Note that unless
the ``NLM_F_ACK`` flag is set on the request Netlink will not respond
with ``NLMSG_ERROR`` if there is no error. To avoid having to special-case
this quirk it is recommended to always set ``NLM_F_ACK``.

The format of ``NLMSG_ERROR`` is described by struct nlmsgerr::

  ----------------------------------------------
  | struct nlmsghdr - response header          |
  ----------------------------------------------
  |    int error                               |
  ----------------------------------------------
  | struct nlmsghdr - original request header |
  ----------------------------------------------
  | ** optionally (1) payload of the request   |
  ----------------------------------------------
  | ** optionally (2) extended ACK             |
  ----------------------------------------------

There are two instances of struct nlmsghdr here, first of the response
and second of the request. ``NLMSG_ERROR`` carries the information about
the request which led to the error. This could be useful when trying
to match requests to responses or re-parse the request to dump it into
logs.

The payload of the request is not echoed in messages reporting success
(``error == 0``) or if ``NETLINK_CAP_ACK`` setsockopt() was set.
The latter is common
and perhaps recommended as having to read a copy of every request back
from the kernel is rather wasteful. The absence of request payload
is indicated by ``NLM_F_CAPPED`` in :c:member:`nlmsghdr.nlmsg_flags`.

The second optional element of ``NLMSG_ERROR`` are the extended ACK
attributes. See :ref:`ext_ack` for more details. The presence
of extended ACK is indicated by ``NLM_F_ACK_TLVS`` in
:c:member:`nlmsghdr.nlmsg_flags`.

``NLMSG_DONE`` is simpler, the request is never echoed but the extended
ACK attributes may be present::

  ----------------------------------------------
  | struct nlmsghdr - response header          |
  ----------------------------------------------
  |    int error                               |
  ----------------------------------------------
  | ** optionally extended ACK                 |
  ----------------------------------------------

.. _res_fam:

Resolving the Family ID
-----------------------

This section explains how to find the Family ID of a subsystem.
It also serves as an example of Generic Netlink communication.

Generic Netlink is itself a subsystem exposed via the Generic Netlink API.
To avoid a circular dependency Generic Netlink has a statically allocated
Family ID (``GENL_ID_CTRL`` which is equal to ``NLMSG_MIN_TYPE``).
The Generic Netlink family implements a command used to find out information
about other families (``CTRL_CMD_GETFAMILY``).

To get information about the Generic Netlink family named for example
``"test1"`` we need to send a message on the previously opened Generic Netlink
socket. The message should target the Generic Netlink Family (1), be a
``do`` (2) call to ``CTRL_CMD_GETFAMILY`` (3). A ``dump`` version of this
call would make the kernel respond with information about *all* the families
it knows about. Last but not least the name of the family in question has
to be specified (4) as an attribute with the appropriate type::

  struct nlmsghdr:
    __u32 nlmsg_len:	32
    __u16 nlmsg_type:	GENL_ID_CTRL               // (1)
    __u16 nlmsg_flags:	NLM_F_REQUEST | NLM_F_ACK  // (2)
    __u32 nlmsg_seq:	1
    __u32 nlmsg_pid:	0

  struct genlmsghdr:
    __u8 cmd:		CTRL_CMD_GETFAMILY         // (3)
    __u8 version:	2 /* or 1, doesn't matter */
    __u16 reserved:	0

  struct nlattr:                                   // (4)
    __u16 nla_len:	10
    __u16 nla_type:	CTRL_ATTR_FAMILY_NAME
    char data: 		test1\0

  (padding:)
    char data:		\0\0

The length fields in Netlink (:c:member:`nlmsghdr.nlmsg_len`
and :c:member:`nlattr.nla_len`) always *include* the header.
Attribute headers in netlink must be aligned to 4 bytes from the start
of the message, hence the extra ``\0\0`` after ``CTRL_ATTR_FAMILY_NAME``.
The attribute lengths *exclude* the padding.

If the family is found kernel will reply with two messages, the response
with all the information about the family::

  /* Message #1 - reply */
  struct nlmsghdr:
    __u32 nlmsg_len:	136
    __u16 nlmsg_type:	GENL_ID_CTRL
    __u16 nlmsg_flags:	0
    __u32 nlmsg_seq:	1    /* echoed from our request */
    __u32 nlmsg_pid:	5831 /* The PID of our user space process */

  struct genlmsghdr:
    __u8 cmd:		CTRL_CMD_GETFAMILY
    __u8 version:	2
    __u16 reserved:	0

  struct nlattr:
    __u16 nla_len:	10
    __u16 nla_type:	CTRL_ATTR_FAMILY_NAME
    char data: 		test1\0

  (padding:)
    data:		\0\0

  struct nlattr:
    __u16 nla_len:	6
    __u16 nla_type:	CTRL_ATTR_FAMILY_ID
    __u16: 		123  /* The Family ID we are after */

  (padding:)
    char data:		\0\0

  struct nlattr:
    __u16 nla_len:	9
    __u16 nla_type:	CTRL_ATTR_FAMILY_VERSION
    __u16: 		1

  /* ... etc, more attributes will follow. */

And the error code (success) since ``NLM_F_ACK`` had been set on the request::

  /* Message #2 - the ACK */
  struct nlmsghdr:
    __u32 nlmsg_len:	36
    __u16 nlmsg_type:	NLMSG_ERROR
    __u16 nlmsg_flags:	NLM_F_CAPPED /* There won't be a payload */
    __u32 nlmsg_seq:	1    /* echoed from our request */
    __u32 nlmsg_pid:	5831 /* The PID of our user space process */

  int error:		0

  struct nlmsghdr: /* Copy of the request header as we sent it */
    __u32 nlmsg_len:	32
    __u16 nlmsg_type:	GENL_ID_CTRL
    __u16 nlmsg_flags:	NLM_F_REQUEST | NLM_F_ACK
    __u32 nlmsg_seq:	1
    __u32 nlmsg_pid:	0

The order of attributes (struct nlattr) is not guaranteed so the user
has to walk the attributes and parse them.

Note that Generic Netlink sockets are not associated or bound to a single
family. A socket can be used to exchange messages with many different
families, selecting the recipient family on message-by-message basis using
the :c:member:`nlmsghdr.nlmsg_type` field.

.. _ext_ack:

Extended ACK
------------

Extended ACK controls reporting of additional error/warning TLVs
in ``NLMSG_ERROR`` and ``NLMSG_DONE`` messages. To maintain backward
compatibility this feature has to be explicitly enabled by setting
the ``NETLINK_EXT_ACK`` setsockopt() to ``1``.

Types of extended ack attributes are defined in enum nlmsgerr_attrs.
The most commonly used attributes are ``NLMSGERR_ATTR_MSG``,
``NLMSGERR_ATTR_OFFS`` and ``NLMSGERR_ATTR_MISS_*``.

``NLMSGERR_ATTR_MSG`` carries a message in English describing
the encountered problem. These messages are far more detailed
than what can be expressed thru standard UNIX error codes.

``NLMSGERR_ATTR_OFFS`` points to the attribute which caused the problem.

``NLMSGERR_ATTR_MISS_TYPE`` and ``NLMSGERR_ATTR_MISS_NEST``
inform about a missing attribute.

Extended ACKs can be reported on errors as well as in case of success.
The latter should be treated as a warning.

Extended ACKs greatly improve the usability of Netlink and should
always be enabled, appropriately parsed and reported to the user.

Advanced topics
===============

Dump consistency
----------------

Some of the data structures kernel uses for storing objects make
it hard to provide an atomic snapshot of all the objects in a dump
(without impacting the fast-paths updating them).

Kernel may set the ``NLM_F_DUMP_INTR`` flag on any message in a dump
(including the ``NLMSG_DONE`` message) if the dump was interrupted and
may be inconsistent (e.g. missing objects). User space should retry
the dump if it sees the flag set.

Introspection
-------------

The basic introspection abilities are enabled by access to the Family
object as reported in :ref:`res_fam`. User can query information about
the Generic Netlink family, including which operations are supported
by the kernel and what attributes the kernel understands.
Family information includes the highest ID of an attribute kernel can parse,
a separate command (``CTRL_CMD_GETPOLICY``) provides detailed information
about supported attributes, including ranges of values the kernel accepts.

Querying family information is useful in cases when user space needs
to make sure that the kernel has support for a feature before issuing
a request.

.. _nlmsg_pid:

nlmsg_pid
---------

:c:member:`nlmsghdr.nlmsg_pid` is the Netlink equivalent of an address.
It is referred to as Port ID, sometimes Process ID because for historical
reasons if the application does not select (bind() to) an explicit Port ID
kernel will automatically assign it the ID equal to its Process ID
(as reported by the getpid() system call).

Similarly to the bind() semantics of the TCP/IP network protocols the value
of zero means "assign automatically", hence it is common for applications
to leave the :c:member:`nlmsghdr.nlmsg_pid` field initialized to ``0``.

The field is still used today in rare cases when kernel needs to send
a unicast notification. User space application can use bind() to associate
its socket with a specific PID, it then communicates its PID to the kernel.
This way the kernel can reach the specific user space process.

This sort of communication is utilized in UMH (User Mode Helper)-like
scenarios when kernel needs to trigger user space processing or ask user
space for a policy decision.

Multicast notifications
-----------------------

One of the strengths of Netlink is the ability to send event notifications
to user space. This is a unidirectional form of communication (kernel ->
user) and does not involve any control messages like ``NLMSG_ERROR`` or
``NLMSG_DONE``.

For example the Generic Netlink family itself defines a set of multicast
notifications about registered families. When a new family is added the
sockets subscribed to the notifications will get the following message::

  struct nlmsghdr:
    __u32 nlmsg_len:	136
    __u16 nlmsg_type:	GENL_ID_CTRL
    __u16 nlmsg_flags:	0
    __u32 nlmsg_seq:	0
    __u32 nlmsg_pid:	0

  struct genlmsghdr:
    __u8 cmd:		CTRL_CMD_NEWFAMILY
    __u8 version:	2
    __u16 reserved:	0

  struct nlattr:
    __u16 nla_len:	10
    __u16 nla_type:	CTRL_ATTR_FAMILY_NAME
    char data: 		test1\0

  (padding:)
    data:		\0\0

  struct nlattr:
    __u16 nla_len:	6
    __u16 nla_type:	CTRL_ATTR_FAMILY_ID
    __u16: 		123  /* The Family ID we are after */

  (padding:)
    char data:		\0\0

  struct nlattr:
    __u16 nla_len:	9
    __u16 nla_type:	CTRL_ATTR_FAMILY_VERSION
    __u16: 		1

  /* ... etc, more attributes will follow. */

The notification contains the same information as the response
to the ``CTRL_CMD_GETFAMILY`` request.

The Netlink headers of the notification are mostly 0 and irrelevant.
The :c:member:`nlmsghdr.nlmsg_seq` may be either zero or a monotonically
increasing notification sequence number maintained by the family.

To receive notifications the user socket must subscribe to the relevant
notification group. Much like the Family ID, the Group ID for a given
multicast group is dynamic and can be found inside the Family information.
The ``CTRL_ATTR_MCAST_GROUPS`` attribute contains nests with names
(``CTRL_ATTR_MCAST_GRP_NAME``) and IDs (``CTRL_ATTR_MCAST_GRP_ID``) of
the groups family.

Once the Group ID is known a setsockopt() call adds the socket to the group:

.. code-block:: c

  unsigned int group_id;

  /* .. find the group ID... */

  setsockopt(fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
             &group_id, sizeof(group_id));

The socket will now receive notifications.

It is recommended to use separate sockets for receiving notifications
and sending requests to the kernel. The asynchronous nature of notifications
means that they may get mixed in with the responses making the message
handling much harder.

Buffer sizing
-------------

Netlink sockets are datagram sockets rather than stream sockets,
meaning that each message must be received in its entirety by a single
recv()/recvmsg() system call. If the buffer provided by the user is too
short, the message will be truncated and the ``MSG_TRUNC`` flag set
in struct msghdr (struct msghdr is the second argument
of the recvmsg() system call, *not* a Netlink header).

Upon truncation the remaining part of the message is discarded.

Netlink expects that the user buffer will be at least 8kB or a page
size of the CPU architecture, whichever is bigger. Particular Netlink
families may, however, require a larger buffer. 32kB buffer is recommended
for most efficient handling of dumps (larger buffer fits more dumped
objects and therefore fewer recvmsg() calls are needed).

Classic Netlink
===============

The main differences between Classic and Generic Netlink are the dynamic
allocation of subsystem identifiers and availability of introspection.
In theory the protocol does not differ significantly, however, in practice
Classic Netlink experimented with concepts which were abandoned in Generic
Netlink (really, they usually only found use in a small corner of a single
subsystem). This section is meant as an explainer of a few of such concepts,
with the explicit goal of giving the Generic Netlink
users the confidence to ignore them when reading the uAPI headers.

Most of the concepts and examples here refer to the ``NETLINK_ROUTE`` family,
which covers much of the configuration of the Linux networking stack.
Real documentation of that family, deserves a chapter (or a book) of its own.

Families
--------

Netlink refers to subsystems as families. This is a remnant of using
sockets and the concept of protocol families, which are part of message
demultiplexing in ``NETLINK_ROUTE``.

Sadly every layer of encapsulation likes to refer to whatever it's carrying
as "families" making the term very confusing:

 1. AF_NETLINK is a bona fide socket protocol family
 2. AF_NETLINK's documentation refers to what comes after its own
    header (struct nlmsghdr) in a message as a "Family Header"
 3. Generic Netlink is a family for AF_NETLINK (struct genlmsghdr follows
    struct nlmsghdr), yet it also calls its users "Families".

Note that the Generic Netlink Family IDs are in a different "ID space"
and overlap with Classic Netlink protocol numbers (e.g. ``NETLINK_CRYPTO``
has the Classic Netlink protocol ID of 21 which Generic Netlink will
happily allocate to one of its families as well).

Strict checking
---------------

The ``NETLINK_GET_STRICT_CHK`` socket option enables strict input checking
in ``NETLINK_ROUTE``. It was needed because historically kernel did not
validate the fields of structures it didn't process. This made it impossible
to start using those fields later without risking regressions in applications
which initialized them incorrectly or not at all.

``NETLINK_GET_STRICT_CHK`` declares that the application is initializing
all fields correctly. It also opts into validating that message does not
contain trailing data and requests that kernel rejects attributes with
type higher than largest attribute type known to the kernel.

``NETLINK_GET_STRICT_CHK`` is not used outside of ``NETLINK_ROUTE``.

Unknown attributes
------------------

Historically Netlink ignored all unknown attributes. The thinking was that
it would free the application from having to probe what kernel supports.
The application could make a request to change the state and check which
parts of the request "stuck".

This is no longer the case for new Generic Netlink families and those opting
in to strict checking. See enum netlink_validation for validation types
performed.

Fixed metadata and structures
-----------------------------

Classic Netlink made liberal use of fixed-format structures within
the messages. Messages would commonly have a structure with
a considerable number of fields after struct nlmsghdr. It was also
common to put structures with multiple members inside attributes,
without breaking each member into an attribute of its own.

This has caused problems with validation and extensibility and
therefore using binary structures is actively discouraged for new
attributes.

Request types
-------------

``NETLINK_ROUTE`` categorized requests into 4 types ``NEW``, ``DEL``, ``GET``,
and ``SET``. Each object can handle all or some of those requests
(objects being netdevs, routes, addresses, qdiscs etc.) Request type
is defined by the 2 lowest bits of the message type, so commands for
new objects would always be allocated with a stride of 4.

Each object would also have it's own fixed metadata shared by all request
types (e.g. struct ifinfomsg for netdev requests, struct ifaddrmsg for address
requests, struct tcmsg for qdisc requests).

Even though other protocols and Generic Netlink commands often use
the same verbs in their message names (``GET``, ``SET``) the concept
of request types did not find wider adoption.

Notification echo
-----------------

``NLM_F_ECHO`` requests for notifications resulting from the request
to be queued onto the requesting socket. This is useful to discover
the impact of the request.

Note that this feature is not universally implemented.

Other request-type-specific flags
---------------------------------

Classic Netlink defined various flags for its ``GET``, ``NEW``
and ``DEL`` requests in the upper byte of nlmsg_flags in struct nlmsghdr.
Since request types have not been generalized the request type specific
flags are rarely used (and considered deprecated for new families).

For ``GET`` - ``NLM_F_ROOT`` and ``NLM_F_MATCH`` are combined into
``NLM_F_DUMP``, and not used separately. ``NLM_F_ATOMIC`` is never used.

For ``DEL`` - ``NLM_F_NONREC`` is only used by nftables and ``NLM_F_BULK``
only by FDB some operations.

The flags for ``NEW`` are used most commonly in classic Netlink. Unfortunately,
the meaning is not crystal clear. The following description is based on the
best guess of the intention of the authors, and in practice all families
stray from it in one way or another. ``NLM_F_REPLACE`` asks to replace
an existing object, if no matching object exists the operation should fail.
``NLM_F_EXCL`` has the opposite semantics and only succeeds if object already
existed.
``NLM_F_CREATE`` asks for the object to be created if it does not
exist, it can be combined with ``NLM_F_REPLACE`` and ``NLM_F_EXCL``.

A comment in the main Netlink uAPI header states::

   4.4BSD ADD		NLM_F_CREATE|NLM_F_EXCL
   4.4BSD CHANGE	NLM_F_REPLACE

   True CHANGE		NLM_F_CREATE|NLM_F_REPLACE
   Append		NLM_F_CREATE
   Check		NLM_F_EXCL

which seems to indicate that those flags predate request types.
``NLM_F_REPLACE`` without ``NLM_F_CREATE`` was initially used instead
of ``SET`` commands.
``NLM_F_EXCL`` without ``NLM_F_CREATE`` was used to check if object exists
without creating it, presumably predating ``GET`` commands.

``NLM_F_APPEND`` indicates that if one key can have multiple objects associated
with it (e.g. multiple next-hop objects for a route) the new object should be
added to the list rather than replacing the entire list.

uAPI reference
==============

.. kernel-doc:: include/uapi/linux/netlink.h


code:
======================
No New Privileges Flag
======================

The execve system call can grant a newly-started program privileges that
its parent did not have.  The most obvious examples are setuid/setgid
programs and file capabilities.  To prevent the parent program from
gaining these privileges as well, the kernel and user code must be
careful to prevent the parent from doing anything that could subvert the
child.  For example:

 - The dynamic loader handles ``LD_*`` environment variables differently if
   a program is setuid.

 - chroot is disallowed to unprivileged processes, since it would allow
   ``/etc/passwd`` to be replaced from the point of view of a process that
   inherited chroot.

 - The exec code has special handling for ptrace.

These are all ad-hoc fixes.  The ``no_new_privs`` bit (since Linux 3.5) is a
new, generic mechanism to make it safe for a process to modify its
execution environment in a manner that persists across execve.  Any task
can set ``no_new_privs``.  Once the bit is set, it is inherited across fork,
clone, and execve and cannot be unset.  With ``no_new_privs`` set, ``execve()``
promises not to grant the privilege to do anything that could not have
been done without the execve call.  For example, the setuid and setgid
bits will no longer change the uid or gid; file capabilities will not
add to the permitted set, and LSMs will not relax constraints after
execve.

To set ``no_new_privs``, use::

    prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);

Be careful, though: LSMs might also not tighten constraints on exec
in ``no_new_privs`` mode.  (This means that setting up a general-purpose
service launcher to set ``no_new_privs`` before execing daemons may
interfere with LSM-based sandboxing.)

Note that ``no_new_privs`` does not prevent privilege changes that do not
involve ``execve()``.  An appropriately privileged task can still call
``setuid(2)`` and receive SCM_RIGHTS datagrams.

There are two main use cases for ``no_new_privs`` so far:

 - Filters installed for the seccomp mode 2 sandbox persist across
   execve and can change the behavior of newly-executed programs.
   Unprivileged users are therefore only allowed to install such filters
   if ``no_new_privs`` is set.

 - By itself, ``no_new_privs`` can be used to reduce the attack surface
   available to an unprivileged user.  If everything running with a
   given uid has ``no_new_privs`` set, then that uid will be unable to
   escalate its privileges by directly attacking setuid, setgid, and
   fcap-using binaries; it will need to compromise something without the
   ``no_new_privs`` bit set first.

In the future, other potentially dangerous kernel features could become
available to unprivileged tasks if ``no_new_privs`` is set.  In principle,
several options to ``unshare(2)`` and ``clone(2)`` would be safe when
``no_new_privs`` is set, and ``no_new_privs`` + ``chroot`` is considerable less
dangerous than chroot by itself.